nuxt-filer 0.0.12 → 0.0.13

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/README.md CHANGED
@@ -193,9 +193,42 @@ filer: {
193
193
 
194
194
  `@nuxt/image` and `ipx` are declared as optional peer dependencies — they only need to be installed if you want to use this integration.
195
195
 
196
+ ## S3 storage
197
+
198
+ For durable object storage (AWS S3, Cloudflare R2, MinIO, …) use the built-in
199
+ `createS3Provider`. It stores each file as a data object plus a JSON metadata
200
+ sidecar, and — unlike unstorage's generic `s3` driver — `list()`/`findByMeta()`
201
+ use real S3 prefix listing with continuation pagination, so a group stays
202
+ correctly scoped even inside a large or shared bucket.
203
+
204
+ ```ts
205
+ // nuxt.config.ts
206
+ export default defineNuxtConfig({
207
+ modules: ['nuxt-filer'],
208
+ filer: { provider: 'custom' },
209
+ })
210
+ ```
211
+
212
+ ```ts
213
+ // server/plugins/file-provider.ts
214
+ export default defineNitroPlugin(() => {
215
+ const { s3 } = useRuntimeConfig()
216
+ setFileStorageProvider(createS3Provider({
217
+ accessKeyId: s3.accessKeyId,
218
+ secretAccessKey: s3.secretAccessKey,
219
+ endpoint: s3.endpoint, // e.g. https://<acct>.r2.cloudflarestorage.com
220
+ region: s3.region, // R2: 'auto'
221
+ bucket: s3.bucket,
222
+ // prefix: 'media/', // optional: namespace within a shared bucket
223
+ }))
224
+ })
225
+ ```
226
+
227
+ > `createS3Provider` requires the optional [`aws4fetch`](https://github.com/mhart/aws4fetch) peer dependency (`npm i aws4fetch`). Pass a custom `client` to use a different transport or to unit-test without network.
228
+
196
229
  ## Custom Provider
197
230
 
198
- For advanced use cases (database-backed metadata, S3 storage, external file sync), implement the `FileStorageProvider` interface and register it in a Nitro plugin:
231
+ For advanced use cases (database-backed metadata, external file sync), implement the `FileStorageProvider` interface and register it in a Nitro plugin:
199
232
 
200
233
  ```ts
201
234
  // nuxt.config.ts
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-filer",
3
3
  "configKey": "filer",
4
- "version": "0.0.12",
4
+ "version": "0.0.13",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -37,6 +37,10 @@ const module = defineNuxtModule({
37
37
  {
38
38
  name: "createUnstorageProvider",
39
39
  from: resolver.resolve("./runtime/server/providers/unstorage")
40
+ },
41
+ {
42
+ name: "createS3Provider",
43
+ from: resolver.resolve("./runtime/server/providers/s3")
40
44
  }
41
45
  ]);
42
46
  const typesSpecifier = "nuxt-filer/runtime/types";
@@ -0,0 +1,40 @@
1
+ import type { FileStorageProvider } from '../../../runtime/types.js';
2
+ /**
3
+ * Minimal S3 object-store surface the provider needs. Abstracted so the
4
+ * provider can be unit-tested with an in-memory fake (pass `client`), and so
5
+ * the real implementation (aws4fetch) stays isolated.
6
+ *
7
+ * `listKeys` MUST list with a server-side prefix and paginate through every
8
+ * page — that's the whole point of this provider over unstorage's generic s3
9
+ * driver, which lists the bucket root and caps at 1000 keys.
10
+ */
11
+ export interface S3Client {
12
+ put(key: string, body: Buffer | Uint8Array, contentType?: string): Promise<void>;
13
+ get(key: string): Promise<Buffer | null>;
14
+ head(key: string): Promise<boolean>;
15
+ delete(key: string): Promise<void>;
16
+ listKeys(prefix: string): AsyncGenerator<string, void, unknown>;
17
+ }
18
+ export interface S3ProviderOptions {
19
+ accessKeyId?: string;
20
+ secretAccessKey?: string;
21
+ /** S3 API endpoint, e.g. https://<acct>.r2.cloudflarestorage.com */
22
+ endpoint?: string;
23
+ /** SigV4 region. R2 uses 'auto' (the default). */
24
+ region?: string;
25
+ bucket?: string;
26
+ /** Optional key prefix to namespace files within a shared bucket. */
27
+ prefix?: string;
28
+ /** Inject a custom S3 client (testing or alternative transport). */
29
+ client?: S3Client;
30
+ }
31
+ /**
32
+ * S3-backed {@link FileStorageProvider}. Binary data and a JSON metadata
33
+ * sidecar are stored as separate objects per file, mirroring the built-in
34
+ * unstorage provider's semantics — but `list`/`findByMeta` use real S3 prefix
35
+ * listing with continuation pagination, so a group is correctly scoped even
36
+ * inside a large shared bucket.
37
+ *
38
+ * Key layout: `${prefix}${groupId}/data/${id}` and `${prefix}${groupId}/meta/${id}`.
39
+ */
40
+ export declare function createS3Provider(options: S3ProviderOptions): FileStorageProvider;
@@ -0,0 +1,215 @@
1
+ import { randomUUID } from "node:crypto";
2
+ export function createS3Provider(options) {
3
+ const prefix = options.prefix ? options.prefix.replace(/\/+$/, "") + "/" : "";
4
+ let clientPromise;
5
+ const getClient = () => clientPromise ??= options.client ? Promise.resolve(options.client) : createAwsS3Client(options);
6
+ const dataKey = (groupId, id) => `${prefix}${groupId}/data/${id}`;
7
+ const metaKey = (groupId, id) => `${prefix}${groupId}/meta/${id}`;
8
+ const metaPrefix = (groupId) => `${prefix}${groupId}/meta/`;
9
+ const groupIdFromMetaKey = (key) => {
10
+ const rel = key.slice(prefix.length);
11
+ return rel.slice(0, rel.lastIndexOf("/meta/"));
12
+ };
13
+ const idFromKey = (key) => key.slice(key.lastIndexOf("/") + 1);
14
+ const readMeta = async (client, key) => {
15
+ const raw = await client.get(key);
16
+ if (!raw) return null;
17
+ try {
18
+ return JSON.parse(raw.toString("utf8"));
19
+ } catch {
20
+ return null;
21
+ }
22
+ };
23
+ const toStoredFile = (id, groupId, meta, data) => ({
24
+ id,
25
+ groupId,
26
+ data: data ?? void 0,
27
+ meta: stripInternal(meta),
28
+ createdAt: meta?._createdAt ? new Date(meta._createdAt) : void 0,
29
+ updatedAt: meta?._updatedAt ? new Date(meta._updatedAt) : void 0
30
+ });
31
+ return {
32
+ async create(groupId, data, meta) {
33
+ const client = await getClient();
34
+ const id = randomUUID();
35
+ await client.put(dataKey(groupId, id), data, meta?.mime);
36
+ if (meta) {
37
+ const now = (/* @__PURE__ */ new Date()).toISOString();
38
+ await client.put(
39
+ metaKey(groupId, id),
40
+ Buffer.from(JSON.stringify({ ...meta, _createdAt: now, _updatedAt: now })),
41
+ "application/json"
42
+ );
43
+ }
44
+ return { id };
45
+ },
46
+ async get(groupId, id) {
47
+ const client = await getClient();
48
+ const [data, meta] = await Promise.all([
49
+ client.get(dataKey(groupId, id)),
50
+ readMeta(client, metaKey(groupId, id))
51
+ ]);
52
+ if (!data && !meta) return null;
53
+ return toStoredFile(id, groupId, meta, data ?? void 0);
54
+ },
55
+ async getData(groupId, id) {
56
+ return (await getClient()).get(dataKey(groupId, id));
57
+ },
58
+ async getMeta(id) {
59
+ const client = await getClient();
60
+ for await (const key of client.listKeys(prefix)) {
61
+ if (key.endsWith(`/meta/${id}`)) {
62
+ return stripInternal(await readMeta(client, key));
63
+ }
64
+ }
65
+ return null;
66
+ },
67
+ async list(groupId) {
68
+ const client = await getClient();
69
+ const files = [];
70
+ for await (const key of client.listKeys(metaPrefix(groupId))) {
71
+ const meta = await readMeta(client, key);
72
+ if (!meta) continue;
73
+ files.push(toStoredFile(idFromKey(key), groupId, meta));
74
+ }
75
+ return files;
76
+ },
77
+ async update(id, meta) {
78
+ const client = await getClient();
79
+ for await (const key of client.listKeys(prefix)) {
80
+ if (!key.endsWith(`/meta/${id}`)) continue;
81
+ const existing = await readMeta(client, key) ?? {};
82
+ await client.put(
83
+ key,
84
+ Buffer.from(
85
+ JSON.stringify({ ...existing, ...meta, _updatedAt: (/* @__PURE__ */ new Date()).toISOString() })
86
+ ),
87
+ "application/json"
88
+ );
89
+ return;
90
+ }
91
+ throw new Error(`File metadata not found: ${id}`);
92
+ },
93
+ async remove(groupId, id) {
94
+ const client = await getClient();
95
+ await Promise.all([
96
+ client.delete(dataKey(groupId, id)),
97
+ client.delete(metaKey(groupId, id))
98
+ ]);
99
+ },
100
+ async clear(groupId) {
101
+ const client = await getClient();
102
+ for await (const key of client.listKeys(`${prefix}${groupId}/`)) {
103
+ await client.delete(key);
104
+ }
105
+ },
106
+ async has(groupId, id) {
107
+ return (await getClient()).head(dataKey(groupId, id));
108
+ },
109
+ async findByMeta(filter) {
110
+ const client = await getClient();
111
+ const scanPrefix = filter.groupId ? metaPrefix(filter.groupId) : prefix;
112
+ for await (const key of client.listKeys(scanPrefix)) {
113
+ if (!key.includes("/meta/")) continue;
114
+ const meta = await readMeta(client, key);
115
+ if (!meta) continue;
116
+ if (meta[filter.key] === filter.value) {
117
+ return toStoredFile(idFromKey(key), groupIdFromMetaKey(key), meta);
118
+ }
119
+ }
120
+ return null;
121
+ }
122
+ };
123
+ }
124
+ function stripInternal(meta) {
125
+ if (!meta) return { name: "", mime: "", type: "", version: 0 };
126
+ const { _createdAt, _updatedAt, ...rest } = meta;
127
+ return rest;
128
+ }
129
+ async function createAwsS3Client(options) {
130
+ for (const key of ["accessKeyId", "secretAccessKey", "endpoint", "bucket"]) {
131
+ if (!options[key]) {
132
+ throw new Error(`[nuxt-filer] createS3Provider: missing required option "${key}"`);
133
+ }
134
+ }
135
+ let AwsClient;
136
+ try {
137
+ ({ AwsClient } = await import("aws4fetch"));
138
+ } catch {
139
+ throw new Error(
140
+ '[nuxt-filer] createS3Provider needs the optional "aws4fetch" dependency. Install it: npm i aws4fetch'
141
+ );
142
+ }
143
+ const aws = new AwsClient({
144
+ service: "s3",
145
+ accessKeyId: options.accessKeyId,
146
+ secretAccessKey: options.secretAccessKey,
147
+ region: options.region || "auto"
148
+ });
149
+ const base = `${options.endpoint.replace(/\/+$/, "")}/${options.bucket}`;
150
+ const objectUrl = (key) => `${base}/${key.split("/").map(encodeURIComponent).join("/")}`;
151
+ const signedFetch = (url, init) => aws.sign(url, init).then((req) => fetch(req));
152
+ return {
153
+ async put(key, body, contentType) {
154
+ const res = await signedFetch(objectUrl(key), {
155
+ method: "PUT",
156
+ body,
157
+ headers: contentType ? { "content-type": contentType } : void 0
158
+ });
159
+ if (!res.ok) {
160
+ throw new Error(`[nuxt-filer] S3 PUT ${key}: ${res.status} ${res.statusText}`);
161
+ }
162
+ },
163
+ async get(key) {
164
+ const res = await signedFetch(objectUrl(key));
165
+ if (res.status === 404) return null;
166
+ if (!res.ok) {
167
+ throw new Error(`[nuxt-filer] S3 GET ${key}: ${res.status} ${res.statusText}`);
168
+ }
169
+ return Buffer.from(await res.arrayBuffer());
170
+ },
171
+ async head(key) {
172
+ const res = await signedFetch(objectUrl(key), { method: "HEAD" });
173
+ if (res.status === 404) return false;
174
+ if (!res.ok) {
175
+ throw new Error(`[nuxt-filer] S3 HEAD ${key}: ${res.status} ${res.statusText}`);
176
+ }
177
+ return true;
178
+ },
179
+ async delete(key) {
180
+ const res = await signedFetch(objectUrl(key), { method: "DELETE" });
181
+ if (!res.ok && res.status !== 404) {
182
+ throw new Error(`[nuxt-filer] S3 DELETE ${key}: ${res.status} ${res.statusText}`);
183
+ }
184
+ },
185
+ async *listKeys(keyPrefix) {
186
+ let token;
187
+ do {
188
+ const url = new URL(base);
189
+ url.searchParams.set("list-type", "2");
190
+ if (keyPrefix) url.searchParams.set("prefix", keyPrefix);
191
+ if (token) url.searchParams.set("continuation-token", token);
192
+ const res = await signedFetch(url.toString());
193
+ if (!res.ok) {
194
+ throw new Error(`[nuxt-filer] S3 LIST ${keyPrefix}: ${res.status} ${res.statusText}`);
195
+ }
196
+ const xml = await res.text();
197
+ for (const key of parseListKeys(xml)) yield key;
198
+ token = matchTag(xml, "IsTruncated") === "true" ? matchTag(xml, "NextContinuationToken") : void 0;
199
+ } while (token);
200
+ }
201
+ };
202
+ }
203
+ function parseListKeys(xml) {
204
+ const keys = [];
205
+ const re = /<Key>([\s\S]*?)<\/Key>/g;
206
+ let match;
207
+ while (match = re.exec(xml)) keys.push(decodeXml(match[1]));
208
+ return keys;
209
+ }
210
+ function matchTag(xml, tag) {
211
+ return xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`))?.[1];
212
+ }
213
+ function decodeXml(value) {
214
+ return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
215
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-filer",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "File storage module for Nuxt",
5
5
  "repository": {
6
6
  "type": "git",
@@ -45,6 +45,7 @@
45
45
  "@nuxt/devtools": "^3.2.4",
46
46
  "@nuxt/eslint-config": "^1.15.2",
47
47
  "@nuxt/image": "^2.0.0",
48
+ "aws4fetch": "^1.0.20",
48
49
  "@nuxt/module-builder": "^1.0.2",
49
50
  "@nuxt/schema": "^4.4.2",
50
51
  "@nuxt/test-utils": "^4.0.0",
@@ -60,6 +61,7 @@
60
61
  },
61
62
  "peerDependencies": {
62
63
  "@nuxt/image": "^2.0.0",
64
+ "aws4fetch": "^1.0.20",
63
65
  "ipx": "^3.0.0",
64
66
  "sharp": "^0.33.0 || ^0.34.0"
65
67
  },
@@ -67,6 +69,9 @@
67
69
  "@nuxt/image": {
68
70
  "optional": true
69
71
  },
72
+ "aws4fetch": {
73
+ "optional": true
74
+ },
70
75
  "ipx": {
71
76
  "optional": true
72
77
  },
@@ -0,0 +1,314 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type {
3
+ FileStorageProvider,
4
+ FileMeta,
5
+ StoredFile,
6
+ } from '../../../runtime/types';
7
+
8
+ /**
9
+ * Minimal S3 object-store surface the provider needs. Abstracted so the
10
+ * provider can be unit-tested with an in-memory fake (pass `client`), and so
11
+ * the real implementation (aws4fetch) stays isolated.
12
+ *
13
+ * `listKeys` MUST list with a server-side prefix and paginate through every
14
+ * page — that's the whole point of this provider over unstorage's generic s3
15
+ * driver, which lists the bucket root and caps at 1000 keys.
16
+ */
17
+ export interface S3Client {
18
+ put(key: string, body: Buffer | Uint8Array, contentType?: string): Promise<void>;
19
+ get(key: string): Promise<Buffer | null>;
20
+ head(key: string): Promise<boolean>;
21
+ delete(key: string): Promise<void>;
22
+ listKeys(prefix: string): AsyncGenerator<string, void, unknown>;
23
+ }
24
+
25
+ export interface S3ProviderOptions {
26
+ accessKeyId?: string;
27
+ secretAccessKey?: string;
28
+ /** S3 API endpoint, e.g. https://<acct>.r2.cloudflarestorage.com */
29
+ endpoint?: string;
30
+ /** SigV4 region. R2 uses 'auto' (the default). */
31
+ region?: string;
32
+ bucket?: string;
33
+ /** Optional key prefix to namespace files within a shared bucket. */
34
+ prefix?: string;
35
+ /** Inject a custom S3 client (testing or alternative transport). */
36
+ client?: S3Client;
37
+ }
38
+
39
+ type InternalMeta = FileMeta & { _createdAt?: string; _updatedAt?: string };
40
+
41
+ /**
42
+ * S3-backed {@link FileStorageProvider}. Binary data and a JSON metadata
43
+ * sidecar are stored as separate objects per file, mirroring the built-in
44
+ * unstorage provider's semantics — but `list`/`findByMeta` use real S3 prefix
45
+ * listing with continuation pagination, so a group is correctly scoped even
46
+ * inside a large shared bucket.
47
+ *
48
+ * Key layout: `${prefix}${groupId}/data/${id}` and `${prefix}${groupId}/meta/${id}`.
49
+ */
50
+ export function createS3Provider(options: S3ProviderOptions): FileStorageProvider {
51
+ const prefix = options.prefix ? options.prefix.replace(/\/+$/, '') + '/' : '';
52
+
53
+ let clientPromise: Promise<S3Client> | undefined;
54
+ const getClient = () =>
55
+ (clientPromise ??= options.client
56
+ ? Promise.resolve(options.client)
57
+ : createAwsS3Client(options));
58
+
59
+ const dataKey = (groupId: string, id: string) => `${prefix}${groupId}/data/${id}`;
60
+ const metaKey = (groupId: string, id: string) => `${prefix}${groupId}/meta/${id}`;
61
+ const metaPrefix = (groupId: string) => `${prefix}${groupId}/meta/`;
62
+
63
+ /** `${prefix}${groupId}/meta/${id}` → groupId (groups may contain '/'). */
64
+ const groupIdFromMetaKey = (key: string) => {
65
+ const rel = key.slice(prefix.length);
66
+ return rel.slice(0, rel.lastIndexOf('/meta/'));
67
+ };
68
+ const idFromKey = (key: string) => key.slice(key.lastIndexOf('/') + 1);
69
+
70
+ const readMeta = async (client: S3Client, key: string): Promise<InternalMeta | null> => {
71
+ const raw = await client.get(key);
72
+ if (!raw) return null;
73
+ try {
74
+ return JSON.parse(raw.toString('utf8')) as InternalMeta;
75
+ } catch {
76
+ return null;
77
+ }
78
+ };
79
+
80
+ const toStoredFile = (
81
+ id: string,
82
+ groupId: string,
83
+ meta: InternalMeta | null,
84
+ data?: Buffer,
85
+ ): StoredFile => ({
86
+ id,
87
+ groupId,
88
+ data: data ?? undefined,
89
+ meta: stripInternal(meta),
90
+ createdAt: meta?._createdAt ? new Date(meta._createdAt) : undefined,
91
+ updatedAt: meta?._updatedAt ? new Date(meta._updatedAt) : undefined,
92
+ });
93
+
94
+ return {
95
+ async create(groupId, data, meta) {
96
+ const client = await getClient();
97
+ const id = randomUUID();
98
+
99
+ await client.put(dataKey(groupId, id), data, meta?.mime);
100
+
101
+ if (meta) {
102
+ const now = new Date().toISOString();
103
+ await client.put(
104
+ metaKey(groupId, id),
105
+ Buffer.from(JSON.stringify({ ...meta, _createdAt: now, _updatedAt: now })),
106
+ 'application/json',
107
+ );
108
+ }
109
+
110
+ return { id };
111
+ },
112
+
113
+ async get(groupId, id) {
114
+ const client = await getClient();
115
+ const [data, meta] = await Promise.all([
116
+ client.get(dataKey(groupId, id)),
117
+ readMeta(client, metaKey(groupId, id)),
118
+ ]);
119
+ if (!data && !meta) return null;
120
+ return toStoredFile(id, groupId, meta, data ?? undefined);
121
+ },
122
+
123
+ async getData(groupId, id) {
124
+ return (await getClient()).get(dataKey(groupId, id));
125
+ },
126
+
127
+ async getMeta(id) {
128
+ // No groupId: scan meta objects (bounded by `prefix` when set). The
129
+ // serving path uses get/getData (which carry a groupId), so this is the
130
+ // only non-group-scoped lookup.
131
+ const client = await getClient();
132
+ for await (const key of client.listKeys(prefix)) {
133
+ if (key.endsWith(`/meta/${id}`)) {
134
+ return stripInternal(await readMeta(client, key));
135
+ }
136
+ }
137
+ return null;
138
+ },
139
+
140
+ async list(groupId) {
141
+ const client = await getClient();
142
+ const files: StoredFile[] = [];
143
+ for await (const key of client.listKeys(metaPrefix(groupId))) {
144
+ const meta = await readMeta(client, key);
145
+ if (!meta) continue;
146
+ files.push(toStoredFile(idFromKey(key), groupId, meta));
147
+ }
148
+ return files;
149
+ },
150
+
151
+ async update(id, meta) {
152
+ const client = await getClient();
153
+ for await (const key of client.listKeys(prefix)) {
154
+ if (!key.endsWith(`/meta/${id}`)) continue;
155
+ const existing = (await readMeta(client, key)) ?? ({} as InternalMeta);
156
+ await client.put(
157
+ key,
158
+ Buffer.from(
159
+ JSON.stringify({ ...existing, ...meta, _updatedAt: new Date().toISOString() }),
160
+ ),
161
+ 'application/json',
162
+ );
163
+ return;
164
+ }
165
+ throw new Error(`File metadata not found: ${id}`);
166
+ },
167
+
168
+ async remove(groupId, id) {
169
+ const client = await getClient();
170
+ await Promise.all([
171
+ client.delete(dataKey(groupId, id)),
172
+ client.delete(metaKey(groupId, id)),
173
+ ]);
174
+ },
175
+
176
+ async clear(groupId) {
177
+ const client = await getClient();
178
+ for await (const key of client.listKeys(`${prefix}${groupId}/`)) {
179
+ await client.delete(key);
180
+ }
181
+ },
182
+
183
+ async has(groupId, id) {
184
+ return (await getClient()).head(dataKey(groupId, id));
185
+ },
186
+
187
+ async findByMeta(filter) {
188
+ const client = await getClient();
189
+ const scanPrefix = filter.groupId ? metaPrefix(filter.groupId) : prefix;
190
+ for await (const key of client.listKeys(scanPrefix)) {
191
+ if (!key.includes('/meta/')) continue;
192
+ const meta = await readMeta(client, key);
193
+ if (!meta) continue;
194
+ if (meta[filter.key] === filter.value) {
195
+ return toStoredFile(idFromKey(key), groupIdFromMetaKey(key), meta);
196
+ }
197
+ }
198
+ return null;
199
+ },
200
+ };
201
+ }
202
+
203
+ function stripInternal(meta: InternalMeta | null): FileMeta {
204
+ if (!meta) return { name: '', mime: '', type: '', version: 0 };
205
+ const { _createdAt, _updatedAt, ...rest } = meta;
206
+ return rest as FileMeta;
207
+ }
208
+
209
+ /** Default {@link S3Client} backed by aws4fetch (SigV4 over fetch). */
210
+ async function createAwsS3Client(options: S3ProviderOptions): Promise<S3Client> {
211
+ for (const key of ['accessKeyId', 'secretAccessKey', 'endpoint', 'bucket'] as const) {
212
+ if (!options[key]) {
213
+ throw new Error(`[nuxt-filer] createS3Provider: missing required option "${key}"`);
214
+ }
215
+ }
216
+
217
+ let AwsClient: typeof import('aws4fetch').AwsClient;
218
+ try {
219
+ ({ AwsClient } = await import('aws4fetch'));
220
+ } catch {
221
+ throw new Error(
222
+ '[nuxt-filer] createS3Provider needs the optional "aws4fetch" dependency. Install it: npm i aws4fetch',
223
+ );
224
+ }
225
+
226
+ const aws = new AwsClient({
227
+ service: 's3',
228
+ accessKeyId: options.accessKeyId!,
229
+ secretAccessKey: options.secretAccessKey!,
230
+ region: options.region || 'auto',
231
+ });
232
+
233
+ const base = `${options.endpoint!.replace(/\/+$/, '')}/${options.bucket}`;
234
+ const objectUrl = (key: string) =>
235
+ `${base}/${key.split('/').map(encodeURIComponent).join('/')}`;
236
+
237
+ const signedFetch = (url: string, init?: RequestInit) =>
238
+ aws.sign(url, init).then((req) => fetch(req));
239
+
240
+ return {
241
+ async put(key, body, contentType) {
242
+ const res = await signedFetch(objectUrl(key), {
243
+ method: 'PUT',
244
+ body: body as BodyInit,
245
+ headers: contentType ? { 'content-type': contentType } : undefined,
246
+ });
247
+ if (!res.ok) {
248
+ throw new Error(`[nuxt-filer] S3 PUT ${key}: ${res.status} ${res.statusText}`);
249
+ }
250
+ },
251
+ async get(key) {
252
+ const res = await signedFetch(objectUrl(key));
253
+ if (res.status === 404) return null;
254
+ if (!res.ok) {
255
+ throw new Error(`[nuxt-filer] S3 GET ${key}: ${res.status} ${res.statusText}`);
256
+ }
257
+ return Buffer.from(await res.arrayBuffer());
258
+ },
259
+ async head(key) {
260
+ const res = await signedFetch(objectUrl(key), { method: 'HEAD' });
261
+ if (res.status === 404) return false;
262
+ if (!res.ok) {
263
+ throw new Error(`[nuxt-filer] S3 HEAD ${key}: ${res.status} ${res.statusText}`);
264
+ }
265
+ return true;
266
+ },
267
+ async delete(key) {
268
+ const res = await signedFetch(objectUrl(key), { method: 'DELETE' });
269
+ if (!res.ok && res.status !== 404) {
270
+ throw new Error(`[nuxt-filer] S3 DELETE ${key}: ${res.status} ${res.statusText}`);
271
+ }
272
+ },
273
+ async *listKeys(keyPrefix) {
274
+ let token: string | undefined;
275
+ do {
276
+ const url = new URL(base);
277
+ url.searchParams.set('list-type', '2');
278
+ if (keyPrefix) url.searchParams.set('prefix', keyPrefix);
279
+ if (token) url.searchParams.set('continuation-token', token);
280
+
281
+ const res = await signedFetch(url.toString());
282
+ if (!res.ok) {
283
+ throw new Error(`[nuxt-filer] S3 LIST ${keyPrefix}: ${res.status} ${res.statusText}`);
284
+ }
285
+ const xml = await res.text();
286
+ for (const key of parseListKeys(xml)) yield key;
287
+
288
+ token =
289
+ matchTag(xml, 'IsTruncated') === 'true' ? matchTag(xml, 'NextContinuationToken') : undefined;
290
+ } while (token);
291
+ },
292
+ };
293
+ }
294
+
295
+ function parseListKeys(xml: string): string[] {
296
+ const keys: string[] = [];
297
+ const re = /<Key>([\s\S]*?)<\/Key>/g;
298
+ let match: RegExpExecArray | null;
299
+ while ((match = re.exec(xml))) keys.push(decodeXml(match[1]!));
300
+ return keys;
301
+ }
302
+
303
+ function matchTag(xml: string, tag: string): string | undefined {
304
+ return xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`))?.[1];
305
+ }
306
+
307
+ function decodeXml(value: string): string {
308
+ return value
309
+ .replace(/&lt;/g, '<')
310
+ .replace(/&gt;/g, '>')
311
+ .replace(/&quot;/g, '"')
312
+ .replace(/&#39;/g, "'")
313
+ .replace(/&amp;/g, '&');
314
+ }