@develit-io/backend-sdk 5.5.0 → 5.7.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/dist/index.cjs +149 -33
- package/dist/index.d.cts +98 -60
- package/dist/index.d.mts +98 -60
- package/dist/index.d.ts +98 -60
- package/dist/index.mjs +144 -33
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -7,7 +7,9 @@ require('http-status-codes');
|
|
|
7
7
|
const z = require('zod/v4/core');
|
|
8
8
|
const h3 = require('h3');
|
|
9
9
|
const consola = require('consola');
|
|
10
|
-
const
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const crypto$1 = require('node:crypto');
|
|
12
|
+
const path = require('path');
|
|
11
13
|
const superjson = require('superjson');
|
|
12
14
|
|
|
13
15
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
|
@@ -25,6 +27,9 @@ function _interopNamespaceCompat(e) {
|
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
const z__namespace = /*#__PURE__*/_interopNamespaceCompat(z);
|
|
30
|
+
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
|
|
31
|
+
const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto$1);
|
|
32
|
+
const path__default = /*#__PURE__*/_interopDefaultCompat(path);
|
|
28
33
|
const superjson__default = /*#__PURE__*/_interopDefaultCompat(superjson);
|
|
29
34
|
|
|
30
35
|
const base = {
|
|
@@ -32,12 +37,17 @@ const base = {
|
|
|
32
37
|
createdAt: sqliteCore.integer("created_at", { mode: "timestamp_ms" }).default(
|
|
33
38
|
drizzleOrm.sql`(unixepoch('subsec') * 1000)`
|
|
34
39
|
),
|
|
35
|
-
modifiedAt: sqliteCore.integer("modified_at", { mode: "timestamp_ms" }).default(drizzleOrm.sql`null`).$onUpdate(() => /* @__PURE__ */ new Date())
|
|
40
|
+
modifiedAt: sqliteCore.integer("modified_at", { mode: "timestamp_ms" }).default(drizzleOrm.sql`null`).$onUpdate(() => /* @__PURE__ */ new Date()),
|
|
41
|
+
deletedAt: sqliteCore.integer("deleted_at", { mode: "timestamp_ms" }).default(drizzleOrm.sql`null`)
|
|
36
42
|
};
|
|
37
43
|
const basePostgres = {
|
|
38
44
|
id: pgCore.uuid("id").primaryKey(),
|
|
39
45
|
createdAt: pgCore.timestamp("created_at", { mode: "date", withTimezone: false }).defaultNow().notNull(),
|
|
40
|
-
modifiedAt: pgCore.timestamp("modified_at", { mode: "date", withTimezone: false }).default(drizzleOrm.sql`null`).$onUpdate(() => /* @__PURE__ */ new Date())
|
|
46
|
+
modifiedAt: pgCore.timestamp("modified_at", { mode: "date", withTimezone: false }).default(drizzleOrm.sql`null`).$onUpdate(() => /* @__PURE__ */ new Date()),
|
|
47
|
+
deletedAt: pgCore.timestamp("deleted_at", {
|
|
48
|
+
mode: "date",
|
|
49
|
+
withTimezone: false
|
|
50
|
+
}).default(drizzleOrm.sql`null`)
|
|
41
51
|
};
|
|
42
52
|
|
|
43
53
|
const ibanZodSchema = new z__namespace.$ZodString({
|
|
@@ -205,28 +215,116 @@ async function handleAction(worker, input, options = {}, actionExecution) {
|
|
|
205
215
|
}
|
|
206
216
|
}
|
|
207
217
|
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
218
|
+
const asNonEmpty = (arr) => {
|
|
219
|
+
return arr.length > 0 ? [arr[0], ...arr.slice(1)] : null;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
function createAuditLogWriter(table) {
|
|
223
|
+
return (logs, db) => {
|
|
224
|
+
if (logs.length === 0) return [];
|
|
225
|
+
const auditRecords = logs.map((log) => ({
|
|
226
|
+
...log,
|
|
227
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
228
|
+
id: crypto.randomUUID()
|
|
229
|
+
}));
|
|
230
|
+
return [db.insert(table).values(auditRecords)];
|
|
231
|
+
};
|
|
221
232
|
}
|
|
222
|
-
const uuidv4 = () => crypto.randomUUID();
|
|
223
233
|
|
|
224
|
-
|
|
225
|
-
|
|
234
|
+
function durableObjectNamespaceIdFromName(uniqueKey, name) {
|
|
235
|
+
const key = crypto__default.createHash("sha256").update(uniqueKey).digest();
|
|
236
|
+
const nameHmac = crypto__default.createHmac("sha256", key).update(name).digest().subarray(0, 16);
|
|
237
|
+
const hmac = crypto__default.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
|
|
238
|
+
return Buffer.concat([nameHmac, hmac]).toString("hex");
|
|
239
|
+
}
|
|
240
|
+
const getDatabaseIdFromWrangler = () => {
|
|
241
|
+
try {
|
|
242
|
+
const wranglerPath = path__default.resolve("./wrangler.jsonc");
|
|
243
|
+
const wranglerContent = fs__default.readFileSync(wranglerPath, "utf-8");
|
|
244
|
+
const cleanContent = wranglerContent.replace(
|
|
245
|
+
/\/\*[\s\S]*?\*\/|\/\/.*$/gm,
|
|
246
|
+
""
|
|
247
|
+
);
|
|
248
|
+
const config = JSON.parse(cleanContent);
|
|
249
|
+
const environment = process.env.ENVIRONMENT || "localhost";
|
|
250
|
+
let databaseId;
|
|
251
|
+
if (environment !== "localhost" && config.env?.[environment]) {
|
|
252
|
+
databaseId = config.env[environment].d1_databases?.[0]?.database_id;
|
|
253
|
+
console.log(
|
|
254
|
+
`Using database_id for environment '${environment}': ${databaseId}`
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
if (!databaseId) {
|
|
258
|
+
databaseId = config.d1_databases?.[0]?.database_id;
|
|
259
|
+
console.log(
|
|
260
|
+
`Using default database_id for environment '${environment}': ${databaseId}`
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
if (!databaseId) {
|
|
264
|
+
throw new Error("database_id not found in wrangler.jsonc");
|
|
265
|
+
}
|
|
266
|
+
return databaseId;
|
|
267
|
+
} catch (err) {
|
|
268
|
+
console.warn(
|
|
269
|
+
`Warning: Could not read database_id from wrangler.jsonc: ${err}`
|
|
270
|
+
);
|
|
271
|
+
}
|
|
226
272
|
};
|
|
227
|
-
|
|
228
|
-
const
|
|
229
|
-
return
|
|
273
|
+
const isRemoteEnvironment = () => {
|
|
274
|
+
const environment = process.env.ENVIRONMENT;
|
|
275
|
+
return environment && environment !== "localhost";
|
|
276
|
+
};
|
|
277
|
+
const getLocalD1 = (databaseId) => {
|
|
278
|
+
const name = durableObjectNamespaceIdFromName(
|
|
279
|
+
"miniflare-D1DatabaseObject",
|
|
280
|
+
databaseId
|
|
281
|
+
);
|
|
282
|
+
const searchPaths = [
|
|
283
|
+
path__default.resolve("../../.wrangler"),
|
|
284
|
+
// Root of monorepo
|
|
285
|
+
path__default.resolve("./.wrangler")
|
|
286
|
+
// Current directory
|
|
287
|
+
];
|
|
288
|
+
for (const basePath of searchPaths) {
|
|
289
|
+
try {
|
|
290
|
+
const dbFile = fs__default.readdirSync(basePath, { encoding: "utf-8", recursive: true }).find((f) => f.includes(name));
|
|
291
|
+
if (dbFile) {
|
|
292
|
+
const url = path__default.resolve(basePath, dbFile);
|
|
293
|
+
console.log(`Found D1 database at: ${url}`);
|
|
294
|
+
return url;
|
|
295
|
+
} else {
|
|
296
|
+
throw new Error(`No D1 database file found in ${basePath}`);
|
|
297
|
+
}
|
|
298
|
+
} catch {
|
|
299
|
+
console.warn(`Could not search in ${basePath}`);
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
const getCredentials = () => {
|
|
305
|
+
const databaseId = getDatabaseIdFromWrangler() ?? "";
|
|
306
|
+
if (isRemoteEnvironment()) {
|
|
307
|
+
return {
|
|
308
|
+
driver: "d1-http",
|
|
309
|
+
dbCredentials: {
|
|
310
|
+
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
311
|
+
databaseId,
|
|
312
|
+
token: process.env.CLOUDFLARE_API_TOKEN
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
} else {
|
|
316
|
+
return {
|
|
317
|
+
dbCredentials: {
|
|
318
|
+
url: getLocalD1(databaseId)
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
const drizzleD1Config = {
|
|
324
|
+
schema: "./src/database/schema/",
|
|
325
|
+
out: "./src/database/migrations/",
|
|
326
|
+
dialect: "sqlite",
|
|
327
|
+
...getCredentials()
|
|
230
328
|
};
|
|
231
329
|
|
|
232
330
|
class DatabaseTransaction {
|
|
@@ -291,17 +389,33 @@ const defineCommand = (handler) => {
|
|
|
291
389
|
});
|
|
292
390
|
};
|
|
293
391
|
|
|
294
|
-
function
|
|
295
|
-
return
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
return [db.insert(table).values(auditRecords)];
|
|
303
|
-
};
|
|
392
|
+
function first(rows) {
|
|
393
|
+
return rows.length > 0 ? rows[0] : void 0;
|
|
394
|
+
}
|
|
395
|
+
function firstOrError(rows) {
|
|
396
|
+
if (rows.length === 0) {
|
|
397
|
+
throw new Error("Query did not return any data.");
|
|
398
|
+
}
|
|
399
|
+
return rows[0];
|
|
304
400
|
}
|
|
401
|
+
const uuidv4 = () => crypto.randomUUID();
|
|
402
|
+
|
|
403
|
+
const drizzlePgConfig = {
|
|
404
|
+
schema: "./src/database/schema/",
|
|
405
|
+
out: "./src/database/migrations/",
|
|
406
|
+
dialect: "postgresql",
|
|
407
|
+
dbCredentials: {
|
|
408
|
+
url: process.env.DATABASE_URL
|
|
409
|
+
},
|
|
410
|
+
migrations: {
|
|
411
|
+
table: "__drizzle_migrations",
|
|
412
|
+
schema: "public"
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
const calculateExponentialBackoff = (attempts, baseDelaySeconds) => {
|
|
417
|
+
return baseDelaySeconds ** attempts;
|
|
418
|
+
};
|
|
305
419
|
|
|
306
420
|
const service = (serviceName) => {
|
|
307
421
|
return function(constructor) {
|
|
@@ -450,7 +564,9 @@ exports.createAuditLogWriter = createAuditLogWriter;
|
|
|
450
564
|
exports.createInternalError = createInternalError;
|
|
451
565
|
exports.defineCommand = defineCommand;
|
|
452
566
|
exports.develitWorker = develitWorker;
|
|
453
|
-
exports.
|
|
567
|
+
exports.drizzleD1Config = drizzleD1Config;
|
|
568
|
+
exports.drizzlePgConfig = drizzlePgConfig;
|
|
569
|
+
exports.durableObjectNamespaceIdFromName = durableObjectNamespaceIdFromName;
|
|
454
570
|
exports.first = first;
|
|
455
571
|
exports.firstOrError = firstOrError;
|
|
456
572
|
exports.handleAction = handleAction;
|
package/dist/index.d.cts
CHANGED
|
@@ -8,7 +8,6 @@ import { StatusCodes, ReasonPhrases } from 'http-status-codes';
|
|
|
8
8
|
export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
|
|
9
9
|
import * as z from 'zod/v4/core';
|
|
10
10
|
import { Queue } from '@cloudflare/workers-types';
|
|
11
|
-
import * as drizzle_kit from 'drizzle-kit';
|
|
12
11
|
import { BatchItem } from 'drizzle-orm/batch';
|
|
13
12
|
import { DrizzleD1Database } from 'drizzle-orm/d1';
|
|
14
13
|
|
|
@@ -16,11 +15,13 @@ declare const base: {
|
|
|
16
15
|
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
|
|
17
16
|
createdAt: drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>;
|
|
18
17
|
modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"modified_at">>>;
|
|
18
|
+
deletedAt: drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"deleted_at">>;
|
|
19
19
|
};
|
|
20
20
|
declare const basePostgres: {
|
|
21
21
|
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_pg_core.PgUUIDBuilderInitial<"id">>>;
|
|
22
22
|
createdAt: drizzle_orm.NotNull<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"created_at">>>;
|
|
23
23
|
modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"modified_at">>>;
|
|
24
|
+
deletedAt: drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"deleted_at">>;
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
type InternalErrorResponseStatus = Exclude<StatusCodes, 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207>;
|
|
@@ -160,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
160
161
|
*/
|
|
161
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
162
163
|
|
|
163
|
-
|
|
164
|
+
interface AuditLogPayload<T> {
|
|
165
|
+
action: T;
|
|
166
|
+
actorId: string;
|
|
167
|
+
actorUsername?: string;
|
|
168
|
+
service: string;
|
|
169
|
+
entityId?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
173
|
+
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
174
|
+
/**
|
|
175
|
+
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
176
|
+
*
|
|
177
|
+
* @param table - The Drizzle table definition for audit logs
|
|
178
|
+
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
183
|
+
* import { auditLogsTable } from './schema'
|
|
184
|
+
*
|
|
185
|
+
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
186
|
+
*
|
|
187
|
+
* // Use in initializeDB
|
|
188
|
+
* this.initializeDB(env.DB, schema, auditWriter)
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
192
|
+
|
|
193
|
+
declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): string;
|
|
194
|
+
declare const drizzleD1Config: {
|
|
195
|
+
driver: string;
|
|
196
|
+
dbCredentials: {
|
|
197
|
+
accountId: string | undefined;
|
|
198
|
+
databaseId: string;
|
|
199
|
+
token: string | undefined;
|
|
200
|
+
url?: undefined;
|
|
201
|
+
};
|
|
202
|
+
schema: string;
|
|
203
|
+
out: string;
|
|
204
|
+
dialect: "sqlite";
|
|
205
|
+
} | {
|
|
206
|
+
dbCredentials: {
|
|
207
|
+
url: string | undefined;
|
|
208
|
+
accountId?: undefined;
|
|
209
|
+
databaseId?: undefined;
|
|
210
|
+
token?: undefined;
|
|
211
|
+
};
|
|
212
|
+
driver?: undefined;
|
|
213
|
+
schema: string;
|
|
214
|
+
out: string;
|
|
215
|
+
dialect: "sqlite";
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
interface Command<TAuditAction = string> {
|
|
219
|
+
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
220
|
+
}
|
|
221
|
+
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
222
|
+
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
223
|
+
command: BatchItem<"sqlite">;
|
|
224
|
+
logPayload: CommandLogPayload<TAuditAction>;
|
|
225
|
+
id: string;
|
|
226
|
+
}) => CommandFactory<TParams, TAuditAction>;
|
|
227
|
+
|
|
228
|
+
declare class DatabaseTransaction<TAuditAction = string> {
|
|
229
|
+
private db;
|
|
230
|
+
private serviceName?;
|
|
231
|
+
private auditLogWriter?;
|
|
232
|
+
private commands;
|
|
233
|
+
private logs;
|
|
234
|
+
private ids;
|
|
235
|
+
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
236
|
+
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
237
|
+
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
238
|
+
executeAll(): Promise<void>;
|
|
239
|
+
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
240
|
+
getIds(): readonly string[];
|
|
241
|
+
getCommandsCount(): number;
|
|
242
|
+
}
|
|
243
|
+
|
|
164
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
165
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
166
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -172,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
172
252
|
}) => InternalError;
|
|
173
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
174
254
|
|
|
255
|
+
declare const drizzlePgConfig: {
|
|
256
|
+
schema: string;
|
|
257
|
+
out: string;
|
|
258
|
+
dialect: "postgresql";
|
|
259
|
+
dbCredentials: {
|
|
260
|
+
url: string;
|
|
261
|
+
};
|
|
262
|
+
migrations: {
|
|
263
|
+
table: string;
|
|
264
|
+
schema: string;
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
269
|
+
|
|
175
270
|
declare const RPCResponse: {
|
|
176
271
|
/**
|
|
177
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -250,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
250
345
|
*/
|
|
251
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
252
347
|
|
|
253
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
254
|
-
|
|
255
|
-
interface AuditLogPayload<T> {
|
|
256
|
-
action: T;
|
|
257
|
-
actorId: string;
|
|
258
|
-
actorUsername?: string;
|
|
259
|
-
service: string;
|
|
260
|
-
entityId?: string;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
interface Command<TAuditAction = string> {
|
|
264
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
265
|
-
}
|
|
266
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
267
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
268
|
-
command: BatchItem<"sqlite">;
|
|
269
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
270
|
-
id: string;
|
|
271
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
272
|
-
|
|
273
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
274
|
-
private db;
|
|
275
|
-
private serviceName?;
|
|
276
|
-
private auditLogWriter?;
|
|
277
|
-
private commands;
|
|
278
|
-
private logs;
|
|
279
|
-
private ids;
|
|
280
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
281
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
282
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
283
|
-
executeAll(): Promise<void>;
|
|
284
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
285
|
-
getIds(): readonly string[];
|
|
286
|
-
getCommandsCount(): number;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
290
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
291
|
-
/**
|
|
292
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
293
|
-
*
|
|
294
|
-
* @param table - The Drizzle table definition for audit logs
|
|
295
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
296
|
-
*
|
|
297
|
-
* @example
|
|
298
|
-
* ```typescript
|
|
299
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
300
|
-
* import { auditLogsTable } from './schema'
|
|
301
|
-
*
|
|
302
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
303
|
-
*
|
|
304
|
-
* // Use in initializeDB
|
|
305
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
306
|
-
* ```
|
|
307
|
-
*/
|
|
308
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
309
|
-
|
|
310
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
311
349
|
new (...args: any[]): {
|
|
312
350
|
name: string;
|
|
@@ -326,4 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
326
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
327
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
328
366
|
|
|
329
|
-
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
367
|
+
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|
package/dist/index.d.mts
CHANGED
|
@@ -8,7 +8,6 @@ import { StatusCodes, ReasonPhrases } from 'http-status-codes';
|
|
|
8
8
|
export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
|
|
9
9
|
import * as z from 'zod/v4/core';
|
|
10
10
|
import { Queue } from '@cloudflare/workers-types';
|
|
11
|
-
import * as drizzle_kit from 'drizzle-kit';
|
|
12
11
|
import { BatchItem } from 'drizzle-orm/batch';
|
|
13
12
|
import { DrizzleD1Database } from 'drizzle-orm/d1';
|
|
14
13
|
|
|
@@ -16,11 +15,13 @@ declare const base: {
|
|
|
16
15
|
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
|
|
17
16
|
createdAt: drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>;
|
|
18
17
|
modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"modified_at">>>;
|
|
18
|
+
deletedAt: drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"deleted_at">>;
|
|
19
19
|
};
|
|
20
20
|
declare const basePostgres: {
|
|
21
21
|
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_pg_core.PgUUIDBuilderInitial<"id">>>;
|
|
22
22
|
createdAt: drizzle_orm.NotNull<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"created_at">>>;
|
|
23
23
|
modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"modified_at">>>;
|
|
24
|
+
deletedAt: drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"deleted_at">>;
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
type InternalErrorResponseStatus = Exclude<StatusCodes, 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207>;
|
|
@@ -160,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
160
161
|
*/
|
|
161
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
162
163
|
|
|
163
|
-
|
|
164
|
+
interface AuditLogPayload<T> {
|
|
165
|
+
action: T;
|
|
166
|
+
actorId: string;
|
|
167
|
+
actorUsername?: string;
|
|
168
|
+
service: string;
|
|
169
|
+
entityId?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
173
|
+
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
174
|
+
/**
|
|
175
|
+
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
176
|
+
*
|
|
177
|
+
* @param table - The Drizzle table definition for audit logs
|
|
178
|
+
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
183
|
+
* import { auditLogsTable } from './schema'
|
|
184
|
+
*
|
|
185
|
+
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
186
|
+
*
|
|
187
|
+
* // Use in initializeDB
|
|
188
|
+
* this.initializeDB(env.DB, schema, auditWriter)
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
192
|
+
|
|
193
|
+
declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): string;
|
|
194
|
+
declare const drizzleD1Config: {
|
|
195
|
+
driver: string;
|
|
196
|
+
dbCredentials: {
|
|
197
|
+
accountId: string | undefined;
|
|
198
|
+
databaseId: string;
|
|
199
|
+
token: string | undefined;
|
|
200
|
+
url?: undefined;
|
|
201
|
+
};
|
|
202
|
+
schema: string;
|
|
203
|
+
out: string;
|
|
204
|
+
dialect: "sqlite";
|
|
205
|
+
} | {
|
|
206
|
+
dbCredentials: {
|
|
207
|
+
url: string | undefined;
|
|
208
|
+
accountId?: undefined;
|
|
209
|
+
databaseId?: undefined;
|
|
210
|
+
token?: undefined;
|
|
211
|
+
};
|
|
212
|
+
driver?: undefined;
|
|
213
|
+
schema: string;
|
|
214
|
+
out: string;
|
|
215
|
+
dialect: "sqlite";
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
interface Command<TAuditAction = string> {
|
|
219
|
+
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
220
|
+
}
|
|
221
|
+
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
222
|
+
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
223
|
+
command: BatchItem<"sqlite">;
|
|
224
|
+
logPayload: CommandLogPayload<TAuditAction>;
|
|
225
|
+
id: string;
|
|
226
|
+
}) => CommandFactory<TParams, TAuditAction>;
|
|
227
|
+
|
|
228
|
+
declare class DatabaseTransaction<TAuditAction = string> {
|
|
229
|
+
private db;
|
|
230
|
+
private serviceName?;
|
|
231
|
+
private auditLogWriter?;
|
|
232
|
+
private commands;
|
|
233
|
+
private logs;
|
|
234
|
+
private ids;
|
|
235
|
+
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
236
|
+
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
237
|
+
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
238
|
+
executeAll(): Promise<void>;
|
|
239
|
+
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
240
|
+
getIds(): readonly string[];
|
|
241
|
+
getCommandsCount(): number;
|
|
242
|
+
}
|
|
243
|
+
|
|
164
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
165
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
166
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -172,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
172
252
|
}) => InternalError;
|
|
173
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
174
254
|
|
|
255
|
+
declare const drizzlePgConfig: {
|
|
256
|
+
schema: string;
|
|
257
|
+
out: string;
|
|
258
|
+
dialect: "postgresql";
|
|
259
|
+
dbCredentials: {
|
|
260
|
+
url: string;
|
|
261
|
+
};
|
|
262
|
+
migrations: {
|
|
263
|
+
table: string;
|
|
264
|
+
schema: string;
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
269
|
+
|
|
175
270
|
declare const RPCResponse: {
|
|
176
271
|
/**
|
|
177
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -250,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
250
345
|
*/
|
|
251
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
252
347
|
|
|
253
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
254
|
-
|
|
255
|
-
interface AuditLogPayload<T> {
|
|
256
|
-
action: T;
|
|
257
|
-
actorId: string;
|
|
258
|
-
actorUsername?: string;
|
|
259
|
-
service: string;
|
|
260
|
-
entityId?: string;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
interface Command<TAuditAction = string> {
|
|
264
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
265
|
-
}
|
|
266
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
267
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
268
|
-
command: BatchItem<"sqlite">;
|
|
269
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
270
|
-
id: string;
|
|
271
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
272
|
-
|
|
273
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
274
|
-
private db;
|
|
275
|
-
private serviceName?;
|
|
276
|
-
private auditLogWriter?;
|
|
277
|
-
private commands;
|
|
278
|
-
private logs;
|
|
279
|
-
private ids;
|
|
280
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
281
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
282
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
283
|
-
executeAll(): Promise<void>;
|
|
284
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
285
|
-
getIds(): readonly string[];
|
|
286
|
-
getCommandsCount(): number;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
290
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
291
|
-
/**
|
|
292
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
293
|
-
*
|
|
294
|
-
* @param table - The Drizzle table definition for audit logs
|
|
295
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
296
|
-
*
|
|
297
|
-
* @example
|
|
298
|
-
* ```typescript
|
|
299
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
300
|
-
* import { auditLogsTable } from './schema'
|
|
301
|
-
*
|
|
302
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
303
|
-
*
|
|
304
|
-
* // Use in initializeDB
|
|
305
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
306
|
-
* ```
|
|
307
|
-
*/
|
|
308
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
309
|
-
|
|
310
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
311
349
|
new (...args: any[]): {
|
|
312
350
|
name: string;
|
|
@@ -326,4 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
326
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
327
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
328
366
|
|
|
329
|
-
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
367
|
+
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,6 @@ import { StatusCodes, ReasonPhrases } from 'http-status-codes';
|
|
|
8
8
|
export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
|
|
9
9
|
import * as z from 'zod/v4/core';
|
|
10
10
|
import { Queue } from '@cloudflare/workers-types';
|
|
11
|
-
import * as drizzle_kit from 'drizzle-kit';
|
|
12
11
|
import { BatchItem } from 'drizzle-orm/batch';
|
|
13
12
|
import { DrizzleD1Database } from 'drizzle-orm/d1';
|
|
14
13
|
|
|
@@ -16,11 +15,13 @@ declare const base: {
|
|
|
16
15
|
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>;
|
|
17
16
|
createdAt: drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>;
|
|
18
17
|
modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"modified_at">>>;
|
|
18
|
+
deletedAt: drizzle_orm.HasDefault<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"deleted_at">>;
|
|
19
19
|
};
|
|
20
20
|
declare const basePostgres: {
|
|
21
21
|
id: drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_pg_core.PgUUIDBuilderInitial<"id">>>;
|
|
22
22
|
createdAt: drizzle_orm.NotNull<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"created_at">>>;
|
|
23
23
|
modifiedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"modified_at">>>;
|
|
24
|
+
deletedAt: drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"deleted_at">>;
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
type InternalErrorResponseStatus = Exclude<StatusCodes, 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207>;
|
|
@@ -160,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
160
161
|
*/
|
|
161
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
162
163
|
|
|
163
|
-
|
|
164
|
+
interface AuditLogPayload<T> {
|
|
165
|
+
action: T;
|
|
166
|
+
actorId: string;
|
|
167
|
+
actorUsername?: string;
|
|
168
|
+
service: string;
|
|
169
|
+
entityId?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
173
|
+
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
174
|
+
/**
|
|
175
|
+
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
176
|
+
*
|
|
177
|
+
* @param table - The Drizzle table definition for audit logs
|
|
178
|
+
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
183
|
+
* import { auditLogsTable } from './schema'
|
|
184
|
+
*
|
|
185
|
+
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
186
|
+
*
|
|
187
|
+
* // Use in initializeDB
|
|
188
|
+
* this.initializeDB(env.DB, schema, auditWriter)
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
192
|
+
|
|
193
|
+
declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): string;
|
|
194
|
+
declare const drizzleD1Config: {
|
|
195
|
+
driver: string;
|
|
196
|
+
dbCredentials: {
|
|
197
|
+
accountId: string | undefined;
|
|
198
|
+
databaseId: string;
|
|
199
|
+
token: string | undefined;
|
|
200
|
+
url?: undefined;
|
|
201
|
+
};
|
|
202
|
+
schema: string;
|
|
203
|
+
out: string;
|
|
204
|
+
dialect: "sqlite";
|
|
205
|
+
} | {
|
|
206
|
+
dbCredentials: {
|
|
207
|
+
url: string | undefined;
|
|
208
|
+
accountId?: undefined;
|
|
209
|
+
databaseId?: undefined;
|
|
210
|
+
token?: undefined;
|
|
211
|
+
};
|
|
212
|
+
driver?: undefined;
|
|
213
|
+
schema: string;
|
|
214
|
+
out: string;
|
|
215
|
+
dialect: "sqlite";
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
interface Command<TAuditAction = string> {
|
|
219
|
+
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
220
|
+
}
|
|
221
|
+
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
222
|
+
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
223
|
+
command: BatchItem<"sqlite">;
|
|
224
|
+
logPayload: CommandLogPayload<TAuditAction>;
|
|
225
|
+
id: string;
|
|
226
|
+
}) => CommandFactory<TParams, TAuditAction>;
|
|
227
|
+
|
|
228
|
+
declare class DatabaseTransaction<TAuditAction = string> {
|
|
229
|
+
private db;
|
|
230
|
+
private serviceName?;
|
|
231
|
+
private auditLogWriter?;
|
|
232
|
+
private commands;
|
|
233
|
+
private logs;
|
|
234
|
+
private ids;
|
|
235
|
+
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
236
|
+
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
237
|
+
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
238
|
+
executeAll(): Promise<void>;
|
|
239
|
+
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
240
|
+
getIds(): readonly string[];
|
|
241
|
+
getCommandsCount(): number;
|
|
242
|
+
}
|
|
243
|
+
|
|
164
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
165
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
166
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -172,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
172
252
|
}) => InternalError;
|
|
173
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
174
254
|
|
|
255
|
+
declare const drizzlePgConfig: {
|
|
256
|
+
schema: string;
|
|
257
|
+
out: string;
|
|
258
|
+
dialect: "postgresql";
|
|
259
|
+
dbCredentials: {
|
|
260
|
+
url: string;
|
|
261
|
+
};
|
|
262
|
+
migrations: {
|
|
263
|
+
table: string;
|
|
264
|
+
schema: string;
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
269
|
+
|
|
175
270
|
declare const RPCResponse: {
|
|
176
271
|
/**
|
|
177
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -250,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
250
345
|
*/
|
|
251
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
252
347
|
|
|
253
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
254
|
-
|
|
255
|
-
interface AuditLogPayload<T> {
|
|
256
|
-
action: T;
|
|
257
|
-
actorId: string;
|
|
258
|
-
actorUsername?: string;
|
|
259
|
-
service: string;
|
|
260
|
-
entityId?: string;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
interface Command<TAuditAction = string> {
|
|
264
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
265
|
-
}
|
|
266
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
267
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
268
|
-
command: BatchItem<"sqlite">;
|
|
269
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
270
|
-
id: string;
|
|
271
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
272
|
-
|
|
273
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
274
|
-
private db;
|
|
275
|
-
private serviceName?;
|
|
276
|
-
private auditLogWriter?;
|
|
277
|
-
private commands;
|
|
278
|
-
private logs;
|
|
279
|
-
private ids;
|
|
280
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
281
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
282
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
283
|
-
executeAll(): Promise<void>;
|
|
284
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
285
|
-
getIds(): readonly string[];
|
|
286
|
-
getCommandsCount(): number;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
290
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
291
|
-
/**
|
|
292
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
293
|
-
*
|
|
294
|
-
* @param table - The Drizzle table definition for audit logs
|
|
295
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
296
|
-
*
|
|
297
|
-
* @example
|
|
298
|
-
* ```typescript
|
|
299
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
300
|
-
* import { auditLogsTable } from './schema'
|
|
301
|
-
*
|
|
302
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
303
|
-
*
|
|
304
|
-
* // Use in initializeDB
|
|
305
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
306
|
-
* ```
|
|
307
|
-
*/
|
|
308
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
309
|
-
|
|
310
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
311
349
|
new (...args: any[]): {
|
|
312
350
|
name: string;
|
|
@@ -326,4 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
326
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
327
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
328
366
|
|
|
329
|
-
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
367
|
+
export { type ActionExecution, type ActionHandlerOptions, type AuditLogWriter, type Command, type CommandLogPayload, DatabaseTransaction, type DevelitWorkerMethods, type GatewayResponse, type IRPCResponse, type IncludeRelation, type InferResultType, type InternalError, type InternalErrorResponseStatus, RPCResponse, type ValidatedInput, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|
package/dist/index.mjs
CHANGED
|
@@ -5,7 +5,9 @@ import 'http-status-codes';
|
|
|
5
5
|
import * as z from 'zod/v4/core';
|
|
6
6
|
import { createError } from 'h3';
|
|
7
7
|
import { consola } from 'consola';
|
|
8
|
-
import
|
|
8
|
+
import fs from 'fs';
|
|
9
|
+
import crypto$1 from 'node:crypto';
|
|
10
|
+
import path from 'path';
|
|
9
11
|
import superjson from 'superjson';
|
|
10
12
|
|
|
11
13
|
const base = {
|
|
@@ -13,12 +15,17 @@ const base = {
|
|
|
13
15
|
createdAt: integer("created_at", { mode: "timestamp_ms" }).default(
|
|
14
16
|
sql`(unixepoch('subsec') * 1000)`
|
|
15
17
|
),
|
|
16
|
-
modifiedAt: integer("modified_at", { mode: "timestamp_ms" }).default(sql`null`).$onUpdate(() => /* @__PURE__ */ new Date())
|
|
18
|
+
modifiedAt: integer("modified_at", { mode: "timestamp_ms" }).default(sql`null`).$onUpdate(() => /* @__PURE__ */ new Date()),
|
|
19
|
+
deletedAt: integer("deleted_at", { mode: "timestamp_ms" }).default(sql`null`)
|
|
17
20
|
};
|
|
18
21
|
const basePostgres = {
|
|
19
22
|
id: uuid("id").primaryKey(),
|
|
20
23
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: false }).defaultNow().notNull(),
|
|
21
|
-
modifiedAt: timestamp("modified_at", { mode: "date", withTimezone: false }).default(sql`null`).$onUpdate(() => /* @__PURE__ */ new Date())
|
|
24
|
+
modifiedAt: timestamp("modified_at", { mode: "date", withTimezone: false }).default(sql`null`).$onUpdate(() => /* @__PURE__ */ new Date()),
|
|
25
|
+
deletedAt: timestamp("deleted_at", {
|
|
26
|
+
mode: "date",
|
|
27
|
+
withTimezone: false
|
|
28
|
+
}).default(sql`null`)
|
|
22
29
|
};
|
|
23
30
|
|
|
24
31
|
const ibanZodSchema = new z.$ZodString({
|
|
@@ -186,28 +193,116 @@ async function handleAction(worker, input, options = {}, actionExecution) {
|
|
|
186
193
|
}
|
|
187
194
|
}
|
|
188
195
|
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
196
|
+
const asNonEmpty = (arr) => {
|
|
197
|
+
return arr.length > 0 ? [arr[0], ...arr.slice(1)] : null;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
function createAuditLogWriter(table) {
|
|
201
|
+
return (logs, db) => {
|
|
202
|
+
if (logs.length === 0) return [];
|
|
203
|
+
const auditRecords = logs.map((log) => ({
|
|
204
|
+
...log,
|
|
205
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
206
|
+
id: crypto.randomUUID()
|
|
207
|
+
}));
|
|
208
|
+
return [db.insert(table).values(auditRecords)];
|
|
209
|
+
};
|
|
202
210
|
}
|
|
203
|
-
const uuidv4 = () => crypto.randomUUID();
|
|
204
211
|
|
|
205
|
-
|
|
206
|
-
|
|
212
|
+
function durableObjectNamespaceIdFromName(uniqueKey, name) {
|
|
213
|
+
const key = crypto$1.createHash("sha256").update(uniqueKey).digest();
|
|
214
|
+
const nameHmac = crypto$1.createHmac("sha256", key).update(name).digest().subarray(0, 16);
|
|
215
|
+
const hmac = crypto$1.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
|
|
216
|
+
return Buffer.concat([nameHmac, hmac]).toString("hex");
|
|
217
|
+
}
|
|
218
|
+
const getDatabaseIdFromWrangler = () => {
|
|
219
|
+
try {
|
|
220
|
+
const wranglerPath = path.resolve("./wrangler.jsonc");
|
|
221
|
+
const wranglerContent = fs.readFileSync(wranglerPath, "utf-8");
|
|
222
|
+
const cleanContent = wranglerContent.replace(
|
|
223
|
+
/\/\*[\s\S]*?\*\/|\/\/.*$/gm,
|
|
224
|
+
""
|
|
225
|
+
);
|
|
226
|
+
const config = JSON.parse(cleanContent);
|
|
227
|
+
const environment = process.env.ENVIRONMENT || "localhost";
|
|
228
|
+
let databaseId;
|
|
229
|
+
if (environment !== "localhost" && config.env?.[environment]) {
|
|
230
|
+
databaseId = config.env[environment].d1_databases?.[0]?.database_id;
|
|
231
|
+
console.log(
|
|
232
|
+
`Using database_id for environment '${environment}': ${databaseId}`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
if (!databaseId) {
|
|
236
|
+
databaseId = config.d1_databases?.[0]?.database_id;
|
|
237
|
+
console.log(
|
|
238
|
+
`Using default database_id for environment '${environment}': ${databaseId}`
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
if (!databaseId) {
|
|
242
|
+
throw new Error("database_id not found in wrangler.jsonc");
|
|
243
|
+
}
|
|
244
|
+
return databaseId;
|
|
245
|
+
} catch (err) {
|
|
246
|
+
console.warn(
|
|
247
|
+
`Warning: Could not read database_id from wrangler.jsonc: ${err}`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
207
250
|
};
|
|
208
|
-
|
|
209
|
-
const
|
|
210
|
-
return
|
|
251
|
+
const isRemoteEnvironment = () => {
|
|
252
|
+
const environment = process.env.ENVIRONMENT;
|
|
253
|
+
return environment && environment !== "localhost";
|
|
254
|
+
};
|
|
255
|
+
const getLocalD1 = (databaseId) => {
|
|
256
|
+
const name = durableObjectNamespaceIdFromName(
|
|
257
|
+
"miniflare-D1DatabaseObject",
|
|
258
|
+
databaseId
|
|
259
|
+
);
|
|
260
|
+
const searchPaths = [
|
|
261
|
+
path.resolve("../../.wrangler"),
|
|
262
|
+
// Root of monorepo
|
|
263
|
+
path.resolve("./.wrangler")
|
|
264
|
+
// Current directory
|
|
265
|
+
];
|
|
266
|
+
for (const basePath of searchPaths) {
|
|
267
|
+
try {
|
|
268
|
+
const dbFile = fs.readdirSync(basePath, { encoding: "utf-8", recursive: true }).find((f) => f.includes(name));
|
|
269
|
+
if (dbFile) {
|
|
270
|
+
const url = path.resolve(basePath, dbFile);
|
|
271
|
+
console.log(`Found D1 database at: ${url}`);
|
|
272
|
+
return url;
|
|
273
|
+
} else {
|
|
274
|
+
throw new Error(`No D1 database file found in ${basePath}`);
|
|
275
|
+
}
|
|
276
|
+
} catch {
|
|
277
|
+
console.warn(`Could not search in ${basePath}`);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
const getCredentials = () => {
|
|
283
|
+
const databaseId = getDatabaseIdFromWrangler() ?? "";
|
|
284
|
+
if (isRemoteEnvironment()) {
|
|
285
|
+
return {
|
|
286
|
+
driver: "d1-http",
|
|
287
|
+
dbCredentials: {
|
|
288
|
+
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
289
|
+
databaseId,
|
|
290
|
+
token: process.env.CLOUDFLARE_API_TOKEN
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
} else {
|
|
294
|
+
return {
|
|
295
|
+
dbCredentials: {
|
|
296
|
+
url: getLocalD1(databaseId)
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
const drizzleD1Config = {
|
|
302
|
+
schema: "./src/database/schema/",
|
|
303
|
+
out: "./src/database/migrations/",
|
|
304
|
+
dialect: "sqlite",
|
|
305
|
+
...getCredentials()
|
|
211
306
|
};
|
|
212
307
|
|
|
213
308
|
class DatabaseTransaction {
|
|
@@ -272,17 +367,33 @@ const defineCommand = (handler) => {
|
|
|
272
367
|
});
|
|
273
368
|
};
|
|
274
369
|
|
|
275
|
-
function
|
|
276
|
-
return
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
return [db.insert(table).values(auditRecords)];
|
|
284
|
-
};
|
|
370
|
+
function first(rows) {
|
|
371
|
+
return rows.length > 0 ? rows[0] : void 0;
|
|
372
|
+
}
|
|
373
|
+
function firstOrError(rows) {
|
|
374
|
+
if (rows.length === 0) {
|
|
375
|
+
throw new Error("Query did not return any data.");
|
|
376
|
+
}
|
|
377
|
+
return rows[0];
|
|
285
378
|
}
|
|
379
|
+
const uuidv4 = () => crypto.randomUUID();
|
|
380
|
+
|
|
381
|
+
const drizzlePgConfig = {
|
|
382
|
+
schema: "./src/database/schema/",
|
|
383
|
+
out: "./src/database/migrations/",
|
|
384
|
+
dialect: "postgresql",
|
|
385
|
+
dbCredentials: {
|
|
386
|
+
url: process.env.DATABASE_URL
|
|
387
|
+
},
|
|
388
|
+
migrations: {
|
|
389
|
+
table: "__drizzle_migrations",
|
|
390
|
+
schema: "public"
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const calculateExponentialBackoff = (attempts, baseDelaySeconds) => {
|
|
395
|
+
return baseDelaySeconds ** attempts;
|
|
396
|
+
};
|
|
286
397
|
|
|
287
398
|
const service = (serviceName) => {
|
|
288
399
|
return function(constructor) {
|
|
@@ -420,4 +531,4 @@ function develitWorker(Worker) {
|
|
|
420
531
|
return DevelitWorker;
|
|
421
532
|
}
|
|
422
533
|
|
|
423
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
534
|
+
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker, drizzleD1Config, drizzlePgConfig, durableObjectNamespaceIdFromName, first, firstOrError, handleAction, handleActionResponse, ibanZodSchema, isInternalError, service, swiftZodSchema, useResult, useResultSync, uuidv4 };
|