@meith/drivers 0.16.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/LICENSE.md +165 -0
- package/package.json +47 -0
- package/src/cache/memory-cache.ts +61 -0
- package/src/cache/next-cache.ts +29 -0
- package/src/cache/redis-cache.ts +128 -0
- package/src/files/local-file-store.ts +59 -0
- package/src/files/s3-file-store.ts +190 -0
- package/src/highlighting/index.ts +1 -0
- package/src/highlighting/shiki-highlighter.ts +92 -0
- package/src/images/codec.ts +76 -0
- package/src/images/index.ts +9 -0
- package/src/images/locate-wasm.ts +108 -0
- package/src/images/processor.ts +40 -0
- package/src/index.ts +17 -0
- package/src/mail/index.ts +113 -0
- package/src/mail/sender.ts +12 -0
- package/src/mail/smtp.ts +77 -0
- package/src/queue/memory-queue.ts +137 -0
- package/src/queue/postgres-queue.ts +218 -0
- package/src/resolve.ts +89 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@meith/drivers",
|
|
3
|
+
"version": "0.16.0",
|
|
4
|
+
"license": "LGPL-3.0-or-later",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/meith-dev/meith.git",
|
|
8
|
+
"directory": "packages/drivers"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "./src/index.ts",
|
|
12
|
+
"types": "./src/index.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": "./src/index.ts",
|
|
15
|
+
"./highlighting": "./src/highlighting/index.ts",
|
|
16
|
+
"./images": "./src/images/index.ts",
|
|
17
|
+
"./files/s3-file-store": "./src/files/s3-file-store.ts"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"src",
|
|
21
|
+
"!src/**/*.test.*",
|
|
22
|
+
"!src/**/*.type-test.*"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@aws-sdk/client-s3": "3.1111.0",
|
|
29
|
+
"@aws-sdk/s3-request-presigner": "3.1111.0",
|
|
30
|
+
"@jsquash/jpeg": "^1.6.0",
|
|
31
|
+
"@jsquash/png": "^3.1.1",
|
|
32
|
+
"@jsquash/resize": "^2.1.1",
|
|
33
|
+
"@types/nodemailer": "^8.0.1",
|
|
34
|
+
"drizzle-orm": "^0.45.2",
|
|
35
|
+
"nodemailer": "^9.0.5",
|
|
36
|
+
"redis": "^6.2.1",
|
|
37
|
+
"shiki": "^4.4.3",
|
|
38
|
+
"@meith/attachments": "0.16.0",
|
|
39
|
+
"@meith/i18n": "0.16.0",
|
|
40
|
+
"@meith/db": "0.16.0",
|
|
41
|
+
"@meith/core": "0.16.0",
|
|
42
|
+
"@meith/settings": "0.16.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"next": "16.3.1"
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { CacheDriver, CacheSetOptions } from '@meith/core'
|
|
2
|
+
|
|
3
|
+
interface Entry {
|
|
4
|
+
value: unknown
|
|
5
|
+
expiresAt?: number
|
|
6
|
+
tags: readonly string[]
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class MemoryCache implements CacheDriver {
|
|
10
|
+
private readonly entries = new Map<string, Entry>()
|
|
11
|
+
|
|
12
|
+
constructor(private readonly maxEntries = 5000) {}
|
|
13
|
+
|
|
14
|
+
get<T>(key: string): Promise<T | undefined> {
|
|
15
|
+
const entry = this.entries.get(key)
|
|
16
|
+
if (!entry) return Promise.resolve(undefined)
|
|
17
|
+
|
|
18
|
+
if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) {
|
|
19
|
+
this.entries.delete(key)
|
|
20
|
+
return Promise.resolve(undefined)
|
|
21
|
+
}
|
|
22
|
+
return Promise.resolve(entry.value as T)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
set<T>(key: string, value: T, options: CacheSetOptions = {}): Promise<void> {
|
|
26
|
+
if (this.entries.size >= this.maxEntries && !this.entries.has(key)) {
|
|
27
|
+
const oldest = this.entries.keys().next()
|
|
28
|
+
if (!oldest.done) this.entries.delete(oldest.value)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const entry: Entry = { value, tags: options.tags ?? [] }
|
|
32
|
+
if (options.ttlSeconds !== undefined) {
|
|
33
|
+
entry.expiresAt = Date.now() + options.ttlSeconds * 1000
|
|
34
|
+
}
|
|
35
|
+
this.entries.set(key, entry)
|
|
36
|
+
return Promise.resolve()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
delete(key: string): Promise<void> {
|
|
40
|
+
this.entries.delete(key)
|
|
41
|
+
return Promise.resolve()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
invalidateTags(tags: readonly string[]): Promise<void> {
|
|
45
|
+
if (tags.length === 0) return Promise.resolve()
|
|
46
|
+
const wanted = new Set(tags)
|
|
47
|
+
|
|
48
|
+
for (const [key, entry] of this.entries) {
|
|
49
|
+
if (entry.tags.some((t) => wanted.has(t))) this.entries.delete(key)
|
|
50
|
+
}
|
|
51
|
+
return Promise.resolve()
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
size(): number {
|
|
55
|
+
return this.entries.size
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
reset(): void {
|
|
59
|
+
this.entries.clear()
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { revalidateTag } from 'next/cache'
|
|
2
|
+
|
|
3
|
+
import type { CacheDriver, CacheSetOptions } from '@meith/core'
|
|
4
|
+
|
|
5
|
+
import { MemoryCache } from './memory-cache'
|
|
6
|
+
|
|
7
|
+
export class NextCacheDriver implements CacheDriver {
|
|
8
|
+
private readonly local = new MemoryCache()
|
|
9
|
+
|
|
10
|
+
get<T>(key: string): Promise<T | undefined> {
|
|
11
|
+
return this.local.get<T>(key)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
set<T>(key: string, value: T, options?: CacheSetOptions): Promise<void> {
|
|
15
|
+
return this.local.set(key, value, options)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
delete(key: string): Promise<void> {
|
|
19
|
+
return this.local.delete(key)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async invalidateTags(tags: readonly string[]): Promise<void> {
|
|
23
|
+
await this.local.invalidateTags(tags)
|
|
24
|
+
|
|
25
|
+
for (const tag of tags) {
|
|
26
|
+
revalidateTag(tag, 'max')
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createClient } from 'redis'
|
|
2
|
+
|
|
3
|
+
import { type CacheDriver, type CacheSetOptions, logger } from '@meith/core'
|
|
4
|
+
|
|
5
|
+
const DATE_MARK = '\u001fmeith:date'
|
|
6
|
+
|
|
7
|
+
function encode(value: unknown): string | undefined {
|
|
8
|
+
return JSON.stringify(value, function (this: Record<string, unknown>, key, raw) {
|
|
9
|
+
const original = this[key]
|
|
10
|
+
return original instanceof Date ? { [DATE_MARK]: original.toISOString() } : raw
|
|
11
|
+
})
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function decode<T>(text: string): T {
|
|
15
|
+
return JSON.parse(text, (_key, raw) => {
|
|
16
|
+
if (
|
|
17
|
+
raw !== null &&
|
|
18
|
+
typeof raw === 'object' &&
|
|
19
|
+
!Array.isArray(raw) &&
|
|
20
|
+
typeof (raw as Record<string, unknown>)[DATE_MARK] === 'string' &&
|
|
21
|
+
Object.keys(raw as object).length === 1
|
|
22
|
+
) {
|
|
23
|
+
return new Date((raw as Record<string, string>)[DATE_MARK] as string)
|
|
24
|
+
}
|
|
25
|
+
return raw
|
|
26
|
+
}) as T
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const INVALIDATE_TAG = `
|
|
30
|
+
local keys = redis.call('SMEMBERS', KEYS[1])
|
|
31
|
+
for i = 1, #keys, 1000 do
|
|
32
|
+
redis.call('DEL', unpack(keys, i, math.min(i + 999, #keys)))
|
|
33
|
+
end
|
|
34
|
+
redis.call('DEL', KEYS[1])
|
|
35
|
+
return #keys
|
|
36
|
+
`
|
|
37
|
+
|
|
38
|
+
export interface RedisCacheOptions {
|
|
39
|
+
readonly url?: string
|
|
40
|
+
readonly socketPath?: string
|
|
41
|
+
readonly keyPrefix?: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type Client = ReturnType<typeof createClient>
|
|
45
|
+
|
|
46
|
+
export class RedisCacheDriver implements CacheDriver {
|
|
47
|
+
private readonly client: Client
|
|
48
|
+
private readonly prefix: string
|
|
49
|
+
private ready: Promise<unknown> | undefined
|
|
50
|
+
|
|
51
|
+
constructor(options: RedisCacheOptions = {}) {
|
|
52
|
+
const log = logger({ driver: 'redis-cache' })
|
|
53
|
+
this.client = createClient(
|
|
54
|
+
options.socketPath !== undefined
|
|
55
|
+
? { socket: { path: options.socketPath, tls: false } }
|
|
56
|
+
: options.url !== undefined
|
|
57
|
+
? { url: options.url }
|
|
58
|
+
: {},
|
|
59
|
+
)
|
|
60
|
+
this.client.on('error', (error: unknown) => {
|
|
61
|
+
log.error({ err: error }, 'redis cache connection error')
|
|
62
|
+
})
|
|
63
|
+
this.prefix = options.keyPrefix ?? 'meith:'
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private valueKey(key: string): string {
|
|
67
|
+
return `${this.prefix}v:${key}`
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private tagKey(tag: string): string {
|
|
71
|
+
return `${this.prefix}t:${tag}`
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private async connection(): Promise<Client> {
|
|
75
|
+
this.ready ??= this.client.connect().catch((error: unknown) => {
|
|
76
|
+
this.ready = undefined
|
|
77
|
+
throw error
|
|
78
|
+
})
|
|
79
|
+
await this.ready
|
|
80
|
+
return this.client
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async get<T>(key: string): Promise<T | undefined> {
|
|
84
|
+
const client = await this.connection()
|
|
85
|
+
const stored = await client.get(this.valueKey(key))
|
|
86
|
+
return stored === null ? undefined : decode<T>(stored)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async set<T>(key: string, value: T, options: CacheSetOptions = {}): Promise<void> {
|
|
90
|
+
const text = encode(value)
|
|
91
|
+
if (text === undefined || (options.ttlSeconds !== undefined && options.ttlSeconds <= 0)) {
|
|
92
|
+
await this.delete(key)
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const client = await this.connection()
|
|
97
|
+
const valueKey = this.valueKey(key)
|
|
98
|
+
const multi = client.multi()
|
|
99
|
+
multi.set(
|
|
100
|
+
valueKey,
|
|
101
|
+
text,
|
|
102
|
+
options.ttlSeconds === undefined
|
|
103
|
+
? {}
|
|
104
|
+
: { expiration: { type: 'EX', value: Math.ceil(options.ttlSeconds) } },
|
|
105
|
+
)
|
|
106
|
+
for (const tag of options.tags ?? []) {
|
|
107
|
+
multi.sAdd(this.tagKey(tag), valueKey)
|
|
108
|
+
}
|
|
109
|
+
await multi.exec()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async delete(key: string): Promise<void> {
|
|
113
|
+
const client = await this.connection()
|
|
114
|
+
await client.del(this.valueKey(key))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async invalidateTags(tags: readonly string[]): Promise<void> {
|
|
118
|
+
if (tags.length === 0) return
|
|
119
|
+
const client = await this.connection()
|
|
120
|
+
await Promise.all(tags.map((tag) => client.eval(INVALIDATE_TAG, { keys: [this.tagKey(tag)] })))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async close(): Promise<void> {
|
|
124
|
+
if (this.ready === undefined) return
|
|
125
|
+
await this.ready.catch(() => undefined)
|
|
126
|
+
if (this.client.isOpen) await this.client.close()
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { dirname, join, normalize, resolve, sep } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import { type FileStore, type PutFileOptions, type StoredFile, ValidationError } from '@meith/core'
|
|
6
|
+
import { msg } from '@meith/i18n'
|
|
7
|
+
|
|
8
|
+
export class LocalFileStore implements FileStore {
|
|
9
|
+
constructor(
|
|
10
|
+
private readonly root: string,
|
|
11
|
+
private readonly publicPrefix = '/uploads',
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
private pathFor(key: string): string {
|
|
15
|
+
if (key.includes('\0')) throw new ValidationError(msg('error.drivers.invalid-file-key'))
|
|
16
|
+
|
|
17
|
+
const base = resolve(this.root)
|
|
18
|
+
const target = resolve(base, normalize(key))
|
|
19
|
+
|
|
20
|
+
if (target !== base && !target.startsWith(base + sep)) {
|
|
21
|
+
throw new ValidationError(msg('error.drivers.invalid-file-key'))
|
|
22
|
+
}
|
|
23
|
+
return target
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async put(key: string, body: Uint8Array, options: PutFileOptions): Promise<StoredFile> {
|
|
27
|
+
const path = this.pathFor(key)
|
|
28
|
+
await mkdir(dirname(path), { recursive: true })
|
|
29
|
+
await writeFile(path, body)
|
|
30
|
+
|
|
31
|
+
return { key, size: body.byteLength, contentType: options.contentType }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async get(key: string): Promise<Uint8Array | undefined> {
|
|
35
|
+
try {
|
|
36
|
+
return await readFile(this.pathFor(key))
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
|
|
39
|
+
throw error
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async delete(key: string): Promise<void> {
|
|
44
|
+
await rm(this.pathFor(key), { force: true })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
signedUrl(): Promise<string | undefined> {
|
|
48
|
+
return Promise.resolve(undefined)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
url(key: string): string {
|
|
52
|
+
return `${this.publicPrefix}/${key}`
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
static keyFor(prefix: string, body: Uint8Array, extension: string): string {
|
|
56
|
+
const digest = createHash('sha256').update(body).digest('hex')
|
|
57
|
+
return join(prefix, digest.slice(0, 2), `${digest}${extension}`)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DeleteObjectCommand,
|
|
3
|
+
GetObjectCommand,
|
|
4
|
+
ListObjectsV2Command,
|
|
5
|
+
PutObjectCommand,
|
|
6
|
+
S3Client,
|
|
7
|
+
} from '@aws-sdk/client-s3'
|
|
8
|
+
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
ConfigurationError,
|
|
12
|
+
type FileStore,
|
|
13
|
+
type PutFileOptions,
|
|
14
|
+
type StoredFile,
|
|
15
|
+
} from '@meith/core'
|
|
16
|
+
|
|
17
|
+
export interface S3FileStoreConfig {
|
|
18
|
+
readonly bucket: string
|
|
19
|
+
readonly region: string
|
|
20
|
+
readonly accessKeyId: string
|
|
21
|
+
readonly secretAccessKey: string
|
|
22
|
+
readonly endpoint?: string | undefined
|
|
23
|
+
readonly publicBaseUrl?: string | undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface S3Like {
|
|
27
|
+
send(command: unknown): Promise<unknown>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function assertUsableKey(key: string): void {
|
|
31
|
+
if (key === '' || key.trim() !== key) {
|
|
32
|
+
throw new ConfigurationError(`Invalid object key: ${JSON.stringify(key)}`)
|
|
33
|
+
}
|
|
34
|
+
if (key.startsWith('/') || key.includes('//')) {
|
|
35
|
+
throw new ConfigurationError(`Object key must not contain empty segments: ${key}`)
|
|
36
|
+
}
|
|
37
|
+
if (key.split('/').some((segment) => segment === '..' || segment === '.')) {
|
|
38
|
+
throw new ConfigurationError(`Object key must not contain relative segments: ${key}`)
|
|
39
|
+
}
|
|
40
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point
|
|
41
|
+
if (/[\u0000-\u001f\u007f]/.test(key)) {
|
|
42
|
+
throw new ConfigurationError('Object key must not contain control characters.')
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isNotFound(error: unknown): boolean {
|
|
47
|
+
const name = (error as { name?: string } | null)?.name
|
|
48
|
+
const status = (error as { $metadata?: { httpStatusCode?: number } } | null)?.$metadata
|
|
49
|
+
?.httpStatusCode
|
|
50
|
+
|
|
51
|
+
return name === 'NoSuchKey' || name === 'NotFound' || status === 404
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class S3FileStore implements FileStore {
|
|
55
|
+
private readonly sender: S3Like
|
|
56
|
+
|
|
57
|
+
private readonly signingClient: S3Client
|
|
58
|
+
|
|
59
|
+
constructor(
|
|
60
|
+
private readonly config: S3FileStoreConfig,
|
|
61
|
+
sender?: S3Like,
|
|
62
|
+
) {
|
|
63
|
+
this.signingClient = new S3Client({
|
|
64
|
+
region: config.region,
|
|
65
|
+
credentials: {
|
|
66
|
+
accessKeyId: config.accessKeyId,
|
|
67
|
+
secretAccessKey: config.secretAccessKey,
|
|
68
|
+
},
|
|
69
|
+
...(config.endpoint === undefined ? {} : { endpoint: config.endpoint, forcePathStyle: true }),
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
this.sender = sender ?? this.signingClient
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
static fromEnv(env: {
|
|
76
|
+
S3_BUCKET?: string | undefined
|
|
77
|
+
S3_REGION?: string | undefined
|
|
78
|
+
S3_ACCESS_KEY_ID?: string | undefined
|
|
79
|
+
S3_SECRET_ACCESS_KEY?: string | undefined
|
|
80
|
+
S3_ENDPOINT?: string | undefined
|
|
81
|
+
}): S3FileStore {
|
|
82
|
+
const missing = (
|
|
83
|
+
['S3_BUCKET', 'S3_REGION', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'] as const
|
|
84
|
+
).filter((key) => !env[key])
|
|
85
|
+
|
|
86
|
+
if (missing.length > 0) {
|
|
87
|
+
throw new ConfigurationError(
|
|
88
|
+
`FILESTORE_DRIVER=s3 requires ${missing.join(', ')}. See .env.example.`,
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return new S3FileStore({
|
|
93
|
+
bucket: env.S3_BUCKET as string,
|
|
94
|
+
region: env.S3_REGION as string,
|
|
95
|
+
accessKeyId: env.S3_ACCESS_KEY_ID as string,
|
|
96
|
+
secretAccessKey: env.S3_SECRET_ACCESS_KEY as string,
|
|
97
|
+
endpoint: env.S3_ENDPOINT,
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async put(key: string, body: Uint8Array, options: PutFileOptions): Promise<StoredFile> {
|
|
102
|
+
assertUsableKey(key)
|
|
103
|
+
|
|
104
|
+
await this.sender.send(
|
|
105
|
+
new PutObjectCommand({
|
|
106
|
+
Bucket: this.config.bucket,
|
|
107
|
+
Key: key,
|
|
108
|
+
Body: body,
|
|
109
|
+
ContentType: options.contentType,
|
|
110
|
+
}),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
return { key, size: body.byteLength, contentType: options.contentType }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async get(key: string): Promise<Uint8Array | undefined> {
|
|
117
|
+
assertUsableKey(key)
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
const response = (await this.sender.send(
|
|
121
|
+
new GetObjectCommand({ Bucket: this.config.bucket, Key: key }),
|
|
122
|
+
)) as { Body?: { transformToByteArray(): Promise<Uint8Array> } }
|
|
123
|
+
|
|
124
|
+
if (!response.Body) return undefined
|
|
125
|
+
return await response.Body.transformToByteArray()
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (isNotFound(error)) return undefined
|
|
128
|
+
throw error
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async *listKeys(): AsyncGenerator<string> {
|
|
133
|
+
let continuationToken: string | undefined
|
|
134
|
+
|
|
135
|
+
do {
|
|
136
|
+
const response = (await this.sender.send(
|
|
137
|
+
new ListObjectsV2Command({
|
|
138
|
+
Bucket: this.config.bucket,
|
|
139
|
+
...(continuationToken === undefined ? {} : { ContinuationToken: continuationToken }),
|
|
140
|
+
}),
|
|
141
|
+
)) as {
|
|
142
|
+
Contents?: readonly { Key?: string }[]
|
|
143
|
+
IsTruncated?: boolean
|
|
144
|
+
NextContinuationToken?: string
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
for (const object of response.Contents ?? []) {
|
|
148
|
+
if (object.Key !== undefined) yield object.Key
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
continuationToken = response.IsTruncated ? response.NextContinuationToken : undefined
|
|
152
|
+
} while (continuationToken !== undefined)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async delete(key: string): Promise<void> {
|
|
156
|
+
assertUsableKey(key)
|
|
157
|
+
|
|
158
|
+
try {
|
|
159
|
+
await this.sender.send(new DeleteObjectCommand({ Bucket: this.config.bucket, Key: key }))
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (isNotFound(error)) return
|
|
162
|
+
throw error
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async signedUrl(key: string, expiresInSeconds: number): Promise<string | undefined> {
|
|
167
|
+
assertUsableKey(key)
|
|
168
|
+
|
|
169
|
+
if (expiresInSeconds <= 0) {
|
|
170
|
+
throw new ConfigurationError('signedUrl requires a positive expiry.')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return getSignedUrl(
|
|
174
|
+
this.signingClient,
|
|
175
|
+
new GetObjectCommand({ Bucket: this.config.bucket, Key: key }),
|
|
176
|
+
{ expiresIn: expiresInSeconds },
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
url(key: string): string {
|
|
181
|
+
assertUsableKey(key)
|
|
182
|
+
|
|
183
|
+
const base =
|
|
184
|
+
this.config.publicBaseUrl ??
|
|
185
|
+
this.config.endpoint ??
|
|
186
|
+
`https://${this.config.bucket}.s3.${this.config.region}.amazonaws.com`
|
|
187
|
+
|
|
188
|
+
return `${base.replace(/\/+$/, '')}/${key}`
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { type CodeHighlighter, codeHighlighter } from './shiki-highlighter'
|