@conorroberts/utils 0.0.4

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/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/biome.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/1.8.3/schema.json",
3
+ "organizeImports": {
4
+ "enabled": false
5
+ },
6
+ "linter": {
7
+ "enabled": true,
8
+ "rules": {
9
+ "recommended": true,
10
+ "correctness": {
11
+ "noUnusedImports": "error",
12
+ "noUnusedVariables": "error",
13
+ "noUnusedLabels": "error",
14
+ "useHookAtTopLevel": "error",
15
+ "noUndeclaredVariables": "error",
16
+ "useJsxKeyInIterable": "error"
17
+ },
18
+ "suspicious": {
19
+ "noExplicitAny": "off"
20
+ },
21
+ "a11y": {
22
+ "useMediaCaption": "off",
23
+ "useAltText": "off",
24
+ "useKeyWithClickEvents": "off",
25
+ "useKeyWithMouseEvents": "off",
26
+ "noSvgWithoutTitle": "off"
27
+ },
28
+ "style": {
29
+ "noParameterAssign": "off",
30
+ "noUselessElse": "off"
31
+ },
32
+ "complexity": {
33
+ "noForEach": "off"
34
+ }
35
+ },
36
+ "include": [
37
+ "**/*.ts",
38
+ "**/*.tsx",
39
+ "**/*.json"
40
+ ]
41
+ },
42
+ "javascript": {
43
+ "formatter": {
44
+ "arrowParentheses": "always",
45
+ "lineWidth": 120,
46
+ "indentWidth": 2,
47
+ "quoteStyle": "double",
48
+ "trailingComma": "all",
49
+ "lineEnding": "crlf",
50
+ "indentStyle": "space"
51
+ }
52
+ }
53
+ }
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@conorroberts/utils",
3
+ "description": "",
4
+ "private": false,
5
+ "type": "module",
6
+ "exports": {
7
+ "./db": {
8
+ "types": "./dist/db.d.ts",
9
+ "default": "./dist/db.js"
10
+ },
11
+ "./schema": {
12
+ "types": "./dist/schema.d.ts",
13
+ "default": "./dist/schema.js"
14
+ },
15
+ "./logger": {
16
+ "types": "./dist/logger.d.ts",
17
+ "default": "./dist/logger.js"
18
+ },
19
+ "./cache": {
20
+ "types": "./dist/cache.d.ts",
21
+ "default": "./dist/cache.js"
22
+ },
23
+ "./env": {
24
+ "types": "./dist/env.d.ts",
25
+ "default": "./dist/env.js"
26
+ },
27
+ "./images": {
28
+ "types": "./dist/images.d.ts",
29
+ "default": "./dist/images.js"
30
+ }
31
+ },
32
+ "dependencies": {
33
+ "@libsql/client": "^0.6.0",
34
+ "@logtail/pino": "^0.4.17",
35
+ "@paralleldrive/cuid2": "^2.2.2",
36
+ "dayjs": "^1.11.11",
37
+ "drizzle-orm": "^0.31.0",
38
+ "ioredis": "^5.4.1",
39
+ "ofetch": "^1.3.4",
40
+ "pino": "^9.1.0",
41
+ "pino-pretty": "^10.3.1",
42
+ "remeda": "^2.0.10",
43
+ "unstorage": "^1.10.2",
44
+ "valibot": "0.30.0"
45
+ },
46
+ "keywords": [],
47
+ "author": "",
48
+ "license": "ISC",
49
+ "devDependencies": {
50
+ "@biomejs/biome": "^1.8.3",
51
+ "tsup": "^8.0.1",
52
+ "typescript": "^5.4.5"
53
+ },
54
+ "version": "0.0.4",
55
+ "scripts": {
56
+ "dev": "tsup --watch",
57
+ "build": "tsc --noEmit && tsup",
58
+ "build:clean": "tsc --noEmit && tsup --clean"
59
+ }
60
+ }
package/publish.sh ADDED
@@ -0,0 +1,2 @@
1
+ pnpm version patch
2
+ pnpm publish --access public
package/src/cache.ts ADDED
@@ -0,0 +1,24 @@
1
+ import {
2
+ createStorage as createUnstorage,
3
+ type Storage,
4
+ type StorageValue,
5
+ } from "unstorage";
6
+ import redisDriver, { type RedisOptions } from "unstorage/drivers/redis";
7
+
8
+ export class Cache {
9
+ private _cache: Storage<StorageValue>;
10
+
11
+ constructor(args: RedisOptions) {
12
+ this._cache = createUnstorage({
13
+ driver: redisDriver(args),
14
+ });
15
+ }
16
+
17
+ get cache() {
18
+ return this._cache;
19
+ }
20
+
21
+ public ttl(date: Date) {
22
+ return Math.floor((date.getTime() - Date.now()) / 1000);
23
+ }
24
+ }
package/src/db.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { createClient } from "@libsql/client";
2
+ import { LibSQLDatabase, drizzle } from "drizzle-orm/libsql";
3
+
4
+ export const createLibsqlClient = (args: {
5
+ url: string;
6
+ authToken?: string;
7
+ }) => {
8
+ return createClient(args);
9
+ };
10
+
11
+ export const createDbClient = <TSchema extends Record<string, unknown>>(
12
+ schema: TSchema,
13
+ args: { url: string; authToken?: string }
14
+ ) => {
15
+ const client = createLibsqlClient(args);
16
+ const db = drizzle(client, {
17
+ schema,
18
+ logger: false,
19
+ });
20
+
21
+ return db;
22
+ };
23
+
24
+ export type DatabaseClient<TSchema extends Record<string, unknown>> =
25
+ LibSQLDatabase<TSchema>;
26
+ export type DatabaseClientTransactionContext<
27
+ TSchema extends Record<string, unknown>
28
+ > = Parameters<Parameters<DatabaseClient<TSchema>["transaction"]>[0]>[0];
package/src/env.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { pipe } from "remeda";
2
+ import type { BaseSchema, Output } from "valibot";
3
+ import * as v from "valibot";
4
+
5
+ const PUBLIC_ENV_PREFIX = "PUBLIC_" as const;
6
+
7
+ /**
8
+ * Validates your environment variables against the given Valibot schema;
9
+ * @param args
10
+ * @returns An object containing client environment variables and another containing server environment variables
11
+ */
12
+ export const createEnv = <
13
+ Schema extends Record<string, BaseSchema>,
14
+ Env = {
15
+ [K in keyof Schema]: Output<Schema[K]>;
16
+ },
17
+ >(args: {
18
+ schema: Schema;
19
+ env: any;
20
+ }) => {
21
+ const pairs = Object.entries(args.schema);
22
+ const serverEnv = new Map();
23
+
24
+ for (const [key, value] of pairs) {
25
+ const result = v.safeParse(value, args.env[key] ?? null);
26
+
27
+ if (!result.success) {
28
+ console.error(`Environment variable "${key}" is invalid`);
29
+ process.exit(1);
30
+ }
31
+
32
+ serverEnv.set(key, result.output);
33
+ }
34
+
35
+ type ClientEnvKeys = Exclude<
36
+ { [K in keyof Env]: K extends `${typeof PUBLIC_ENV_PREFIX}${string}` ? K : never }[keyof Env],
37
+ undefined
38
+ >;
39
+
40
+ type ClientEnv = {
41
+ [B in ClientEnvKeys]: Env[B];
42
+ };
43
+
44
+ const clientEnv = pipe(
45
+ serverEnv,
46
+ (obj) => Array.from(obj.entries()),
47
+ (pairs) => pairs.filter(([k]) => k.startsWith(PUBLIC_ENV_PREFIX)),
48
+ (pairs) => Object.fromEntries(pairs),
49
+ ) as ClientEnv;
50
+
51
+ return { client: clientEnv, server: Object.fromEntries(serverEnv.entries()) as Env };
52
+ };
package/src/images.ts ADDED
@@ -0,0 +1,223 @@
1
+ import { createId } from "@paralleldrive/cuid2";
2
+ import dayjs from "dayjs";
3
+ import { ofetch } from "ofetch";
4
+
5
+ export interface OptimizedImageOptions {
6
+ anim?: boolean;
7
+ background?: string;
8
+ blur?: number;
9
+ brightness?: number;
10
+ compression?: "fast"; // faster compression = larger file size
11
+ contrast?: number;
12
+ dpr?: number;
13
+ fit?: "scale-down" | "contain" | "cover" | "crop" | "pad";
14
+ format?: "webp" | "avif" | "json";
15
+ gamma?: number;
16
+ width?: number;
17
+ height?: number;
18
+ metadata?: "keep" | "copyright" | "none";
19
+ quality?: number;
20
+ rotate?: number;
21
+ sharpen?: number;
22
+ }
23
+
24
+ export interface CreateImageUrlResponse {
25
+ result: {
26
+ id: string;
27
+ uploadURL: string;
28
+ };
29
+ success: boolean;
30
+ errors: unknown[];
31
+ messages: unknown[];
32
+ }
33
+
34
+ interface UploadImageResponse {
35
+ result: {
36
+ id: string;
37
+ filename: string;
38
+ uploaded: string;
39
+ requireSignedURLs: boolean;
40
+ variants: string[];
41
+ };
42
+ success: boolean;
43
+ errors: unknown[];
44
+ messages: unknown[];
45
+ }
46
+
47
+ export class ImageUtils<ImageIds extends Record<string, string>> {
48
+ private blacklist: string[] = ["img.clerk.com"];
49
+ private account: string;
50
+ private _imageIds: ImageIds | undefined;
51
+
52
+ constructor(args: {
53
+ accountId: string;
54
+ blacklist?: string[];
55
+ imageIds?: ImageIds;
56
+ }) {
57
+ this.account = args.accountId;
58
+
59
+ this._imageIds = args.imageIds;
60
+
61
+ if (args.blacklist) {
62
+ this.blacklist.push(...args.blacklist);
63
+ }
64
+ }
65
+
66
+ get imageIds() {
67
+ if (!this._imageIds) {
68
+ throw new Error(`imageIds was not supplied in constructor`);
69
+ }
70
+
71
+ return this._imageIds;
72
+ }
73
+
74
+ public url(id: string) {
75
+ return `https://imagedelivery.net/${this.account}/${id}/public`;
76
+ }
77
+
78
+ private isBlacklisted(url: string) {
79
+ return this.blacklist.some((u) => url.includes(u));
80
+ }
81
+
82
+ private isProtected(id: string) {
83
+ if (!this._imageIds) {
84
+ return false;
85
+ }
86
+
87
+ return Object.values(this._imageIds).some((e) => e === id);
88
+ }
89
+
90
+ /**
91
+ * Will only operate on images that have been uploaded via cloudflare images
92
+ */
93
+ public optimizeUrl(url: string, options: OptimizedImageOptions) {
94
+ if (this.isBlacklisted(url)) {
95
+ return url;
96
+ }
97
+
98
+ // Final format should look similar to: https://imagedelivery.net/<ACCOUNT_HASH>/<IMAGE_ID>/w=400,sharpen=3
99
+ return url.replace("public", this.createImageOptionsString(options));
100
+ }
101
+
102
+ public optimizeId(id: string, options: OptimizedImageOptions) {
103
+ return this.optimizeUrl(this.url(id), options);
104
+ }
105
+
106
+ public createOptionsSearchParams(options: OptimizedImageOptions) {
107
+ const params = new URLSearchParams();
108
+
109
+ const pairs = Object.entries(options);
110
+
111
+ for (const [key, val] of pairs) {
112
+ if (val === undefined) {
113
+ continue;
114
+ }
115
+
116
+ params.set(key, val.toString());
117
+ }
118
+
119
+ return params;
120
+ }
121
+
122
+ public createImageOptionsString(options: OptimizedImageOptions) {
123
+ const params = this.createOptionsSearchParams(options);
124
+
125
+ return Array.from(params.entries())
126
+ .map(([key, val]) => `${key}=${val}`)
127
+ .join(",");
128
+ }
129
+
130
+ public async createUploadUrls(count: number, args: { apiKey: string }) {
131
+ if (count === 0) {
132
+ return [];
133
+ }
134
+
135
+ const headers = new Headers();
136
+ headers.set("Authorization", `Bearer ${args.apiKey}`);
137
+
138
+ const urls = await Promise.all(
139
+ Array.from({ length: count }).map(async () => {
140
+ try {
141
+ const form = new FormData();
142
+ const id = createId();
143
+ form.append("id", id);
144
+ form.append("expiry", dayjs().add(5, "minute").toISOString());
145
+
146
+ const img = await ofetch<CreateImageUrlResponse>(
147
+ `https://api.cloudflare.com/client/v4/accounts/${this.account}/images/v2/direct_upload`,
148
+ { method: "POST", headers, body: form }
149
+ );
150
+
151
+ if (!img.success) {
152
+ throw new Error("Error uploading image");
153
+ }
154
+
155
+ return { url: img.result.uploadURL, id };
156
+ } catch (e) {
157
+ throw e;
158
+ }
159
+ })
160
+ );
161
+
162
+ return urls;
163
+ }
164
+
165
+ public async upload(url: string, body: FormData) {
166
+ const fetchResponse = await ofetch<UploadImageResponse>(url, {
167
+ method: "POST",
168
+ body,
169
+ });
170
+
171
+ if (!fetchResponse.success) {
172
+ throw new Error("Failed to upload image");
173
+ }
174
+
175
+ const downloadUrl = fetchResponse.result.variants[0];
176
+
177
+ if (!downloadUrl) {
178
+ throw new Error("Could not find download URL");
179
+ }
180
+
181
+ return downloadUrl;
182
+ }
183
+
184
+ public async delete(id: string, args: { apiKey: string }) {
185
+ if (this.isProtected(id)) {
186
+ return { success: true };
187
+ }
188
+
189
+ try {
190
+ const headers = new Headers();
191
+ headers.set("Authorization", `Bearer ${args.apiKey}`);
192
+
193
+ await ofetch(
194
+ `https://api.cloudflare.com/client/v4/accounts/${this.account}/images/v1/${id}`,
195
+ {
196
+ method: "POST",
197
+ headers,
198
+ }
199
+ );
200
+ return { success: true };
201
+ } catch (_e) {
202
+ return { success: false };
203
+ }
204
+ }
205
+
206
+ public async batchUpload(
207
+ files: { file: File; url: { id: string; value: string } }[]
208
+ ) {
209
+ return await Promise.all(
210
+ files.map(async (e) => {
211
+ const formData = new FormData();
212
+ formData.append("file", e.file);
213
+
214
+ const downloadUrl = await this.upload(e.url.value, formData);
215
+
216
+ return {
217
+ url: downloadUrl,
218
+ id: e.url.id,
219
+ };
220
+ })
221
+ );
222
+ }
223
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { pino } from "pino";
2
+
3
+ export const createLogger = (args: {
4
+ token?: string | undefined | null;
5
+ pretty?: boolean;
6
+ service: string;
7
+ }) => {
8
+ const l = pino(
9
+ {
10
+ level: "info",
11
+ redact: [],
12
+ transport: args.pretty
13
+ ? {
14
+ target: "pino-pretty",
15
+ }
16
+ : undefined,
17
+ },
18
+
19
+ args.token
20
+ ? pino.transport({
21
+ target: "@logtail/pino",
22
+ options: { sourceToken: args.token },
23
+ })
24
+ : undefined,
25
+ );
26
+
27
+ l.child({ service: args.service });
28
+
29
+ return l;
30
+ };
package/src/migrate.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { createClient } from "@libsql/client";
2
+ import { drizzle } from "drizzle-orm/libsql";
3
+ import { migrate as runDrizzleMigrate } from "drizzle-orm/libsql/migrator";
4
+
5
+ export const migrate = async <TSchema extends Record<string, any>>(
6
+ schema: TSchema,
7
+ args: {
8
+ url: string;
9
+ token?: string;
10
+ migrationsFolder: string;
11
+ }
12
+ ) => {
13
+ let url = args.url;
14
+
15
+ // Migrations are only supported via the libsql protocol
16
+ if (url.startsWith("http")) {
17
+ url = url.replace(/http(s)?/, "libsql");
18
+ }
19
+
20
+ const db = drizzle(
21
+ createClient(
22
+ // Auth token must be either 1) present and not undefined or 2) not present
23
+ args.token
24
+ ? {
25
+ url,
26
+ authToken: args.token,
27
+ }
28
+ : { url }
29
+ ),
30
+ { schema }
31
+ );
32
+
33
+ console.info("Running migrations");
34
+
35
+ await runDrizzleMigrate(db, {
36
+ migrationsFolder: args.migrationsFolder,
37
+ });
38
+
39
+ console.info("Migrations applied");
40
+ process.exit(0);
41
+ };
package/src/schema.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { createId } from "@paralleldrive/cuid2";
2
+ import { int, text } from "drizzle-orm/sqlite-core";
3
+
4
+ const timeColumns = {
5
+ createdAt: int("created_at", { mode: "timestamp_ms" })
6
+ .notNull()
7
+ .$defaultFn(() => new Date()),
8
+ updatedAt: int("updated_at", { mode: "timestamp_ms" })
9
+ .notNull()
10
+ .$defaultFn(() => new Date()),
11
+ };
12
+
13
+ const commonColumns = {
14
+ id: text("id")
15
+ .primaryKey()
16
+ .$defaultFn(() => createId()),
17
+ ...timeColumns,
18
+ };
19
+
20
+ export const columns = {
21
+ time: timeColumns,
22
+ common: commonColumns,
23
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { init } from "@paralleldrive/cuid2";
2
+
3
+ export const createRequestId = init({ length: 5 });
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "esModuleInterop": true,
4
+ "skipLibCheck": true,
5
+ "target": "es2022",
6
+ "verbatimModuleSyntax": true,
7
+ "allowJs": true,
8
+ "resolveJsonModule": true,
9
+ "moduleDetection": "force",
10
+ "strict": true,
11
+ "noUncheckedIndexedAccess": true,
12
+ "moduleResolution": "Bundler",
13
+ "module": "ESNext",
14
+ "noEmit": true,
15
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
16
+ "baseUrl": "."
17
+ },
18
+ "include": ["src/**/*", "package.json"]
19
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ format: ["esm"],
5
+ sourcemap: true,
6
+ dts: true,
7
+ entry: {
8
+ schema: "src/schema.ts",
9
+ db: "src/db.ts",
10
+ cache: "src/cache.ts",
11
+ logger: "src/logger.ts",
12
+ env: "src/env.ts",
13
+ images: "src/images.ts",
14
+ },
15
+ });