@develit-io/backend-sdk 5.6.0 → 5.8.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 +143 -31
- package/dist/index.d.cts +96 -61
- package/dist/index.d.mts +96 -61
- package/dist/index.d.ts +96 -61
- package/dist/index.mjs +138 -31
- package/package.json +7 -1
package/dist/index.cjs
CHANGED
|
@@ -7,7 +7,10 @@ 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');
|
|
13
|
+
const jsoncParser = require('jsonc-parser');
|
|
11
14
|
const superjson = require('superjson');
|
|
12
15
|
|
|
13
16
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
|
@@ -25,6 +28,9 @@ function _interopNamespaceCompat(e) {
|
|
|
25
28
|
}
|
|
26
29
|
|
|
27
30
|
const z__namespace = /*#__PURE__*/_interopNamespaceCompat(z);
|
|
31
|
+
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
|
|
32
|
+
const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto$1);
|
|
33
|
+
const path__default = /*#__PURE__*/_interopDefaultCompat(path);
|
|
28
34
|
const superjson__default = /*#__PURE__*/_interopDefaultCompat(superjson);
|
|
29
35
|
|
|
30
36
|
const base = {
|
|
@@ -210,28 +216,116 @@ async function handleAction(worker, input, options = {}, actionExecution) {
|
|
|
210
216
|
}
|
|
211
217
|
}
|
|
212
218
|
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
219
|
+
const asNonEmpty = (arr) => {
|
|
220
|
+
return arr.length > 0 ? [arr[0], ...arr.slice(1)] : null;
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
function createAuditLogWriter(table) {
|
|
224
|
+
return (logs, db) => {
|
|
225
|
+
if (logs.length === 0) return [];
|
|
226
|
+
const auditRecords = logs.map((log) => ({
|
|
227
|
+
...log,
|
|
228
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
229
|
+
id: crypto.randomUUID()
|
|
230
|
+
}));
|
|
231
|
+
return [db.insert(table).values(auditRecords)];
|
|
232
|
+
};
|
|
226
233
|
}
|
|
227
|
-
const uuidv4 = () => crypto.randomUUID();
|
|
228
234
|
|
|
229
|
-
|
|
230
|
-
|
|
235
|
+
function durableObjectNamespaceIdFromName(uniqueKey, name) {
|
|
236
|
+
const key = crypto__default.createHash("sha256").update(uniqueKey).digest();
|
|
237
|
+
const nameHmac = crypto__default.createHmac("sha256", key).update(name).digest().subarray(0, 16);
|
|
238
|
+
const hmac = crypto__default.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
|
|
239
|
+
return Buffer.concat([nameHmac, hmac]).toString("hex");
|
|
240
|
+
}
|
|
241
|
+
const getDatabaseIdFromWrangler = () => {
|
|
242
|
+
try {
|
|
243
|
+
const wranglerPath = path__default.resolve("./wrangler.jsonc");
|
|
244
|
+
const wranglerContent = fs__default.readFileSync(wranglerPath, "utf-8");
|
|
245
|
+
const errors = [];
|
|
246
|
+
const config = jsoncParser.parse(wranglerContent, errors, { allowTrailingComma: true });
|
|
247
|
+
if (errors.length) {
|
|
248
|
+
throw new Error("Invalid JSONC in wrangler.jsonc");
|
|
249
|
+
}
|
|
250
|
+
const environment = process.env.ENVIRONMENT || "localhost";
|
|
251
|
+
let databaseId;
|
|
252
|
+
if (environment !== "localhost" && config.env?.[environment]) {
|
|
253
|
+
databaseId = config.env[environment].d1_databases?.[0]?.database_id;
|
|
254
|
+
console.log(
|
|
255
|
+
`Using database_id for environment '${environment}': ${databaseId}`
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
if (!databaseId) {
|
|
259
|
+
databaseId = config.d1_databases?.[0]?.database_id;
|
|
260
|
+
console.log(
|
|
261
|
+
`Using default database_id for environment '${environment}': ${databaseId}`
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
if (!databaseId) {
|
|
265
|
+
throw new Error("database_id not found in wrangler.jsonc");
|
|
266
|
+
}
|
|
267
|
+
return databaseId;
|
|
268
|
+
} catch (err) {
|
|
269
|
+
console.warn(
|
|
270
|
+
`Warning: Could not read database_id from wrangler.jsonc: ${err}`
|
|
271
|
+
);
|
|
272
|
+
}
|
|
231
273
|
};
|
|
232
|
-
|
|
233
|
-
const
|
|
234
|
-
return
|
|
274
|
+
const isRemoteEnvironment = () => {
|
|
275
|
+
const environment = process.env.ENVIRONMENT;
|
|
276
|
+
return environment && environment !== "localhost";
|
|
277
|
+
};
|
|
278
|
+
const getLocalD1 = (databaseId) => {
|
|
279
|
+
const name = durableObjectNamespaceIdFromName(
|
|
280
|
+
"miniflare-D1DatabaseObject",
|
|
281
|
+
databaseId
|
|
282
|
+
);
|
|
283
|
+
const searchPaths = [
|
|
284
|
+
path__default.resolve("../../.wrangler"),
|
|
285
|
+
// Root of monorepo
|
|
286
|
+
path__default.resolve("./.wrangler")
|
|
287
|
+
// Current directory
|
|
288
|
+
];
|
|
289
|
+
for (const basePath of searchPaths) {
|
|
290
|
+
try {
|
|
291
|
+
const dbFile = fs__default.readdirSync(basePath, { encoding: "utf-8", recursive: true }).find((f) => f.includes(name));
|
|
292
|
+
if (dbFile) {
|
|
293
|
+
const url = path__default.resolve(basePath, dbFile);
|
|
294
|
+
console.log(`Found D1 database at: ${url}`);
|
|
295
|
+
return url;
|
|
296
|
+
} else {
|
|
297
|
+
throw new Error(`No D1 database file found in ${basePath}`);
|
|
298
|
+
}
|
|
299
|
+
} catch {
|
|
300
|
+
console.warn(`Could not search in ${basePath}`);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
const getCredentials = () => {
|
|
306
|
+
const databaseId = getDatabaseIdFromWrangler() ?? "";
|
|
307
|
+
if (isRemoteEnvironment()) {
|
|
308
|
+
return {
|
|
309
|
+
driver: "d1-http",
|
|
310
|
+
dbCredentials: {
|
|
311
|
+
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
312
|
+
databaseId,
|
|
313
|
+
token: process.env.CLOUDFLARE_API_TOKEN
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
} else {
|
|
317
|
+
return {
|
|
318
|
+
dbCredentials: {
|
|
319
|
+
url: getLocalD1(databaseId)
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
const drizzleD1Config = {
|
|
325
|
+
schema: "./src/database/schema/",
|
|
326
|
+
out: "./src/database/migrations/",
|
|
327
|
+
dialect: "sqlite",
|
|
328
|
+
...getCredentials()
|
|
235
329
|
};
|
|
236
330
|
|
|
237
331
|
class DatabaseTransaction {
|
|
@@ -296,17 +390,33 @@ const defineCommand = (handler) => {
|
|
|
296
390
|
});
|
|
297
391
|
};
|
|
298
392
|
|
|
299
|
-
function
|
|
300
|
-
return
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
return [db.insert(table).values(auditRecords)];
|
|
308
|
-
};
|
|
393
|
+
function first(rows) {
|
|
394
|
+
return rows.length > 0 ? rows[0] : void 0;
|
|
395
|
+
}
|
|
396
|
+
function firstOrError(rows) {
|
|
397
|
+
if (rows.length === 0) {
|
|
398
|
+
throw new Error("Query did not return any data.");
|
|
399
|
+
}
|
|
400
|
+
return rows[0];
|
|
309
401
|
}
|
|
402
|
+
const uuidv4 = () => crypto.randomUUID();
|
|
403
|
+
|
|
404
|
+
const drizzlePgConfig = {
|
|
405
|
+
schema: "./src/database/schema/",
|
|
406
|
+
out: "./src/database/migrations/",
|
|
407
|
+
dialect: "postgresql",
|
|
408
|
+
dbCredentials: {
|
|
409
|
+
url: process.env.DATABASE_URL
|
|
410
|
+
},
|
|
411
|
+
migrations: {
|
|
412
|
+
table: "__drizzle_migrations",
|
|
413
|
+
schema: "public"
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
const calculateExponentialBackoff = (attempts, baseDelaySeconds) => {
|
|
418
|
+
return baseDelaySeconds ** attempts;
|
|
419
|
+
};
|
|
310
420
|
|
|
311
421
|
const service = (serviceName) => {
|
|
312
422
|
return function(constructor) {
|
|
@@ -455,7 +565,9 @@ exports.createAuditLogWriter = createAuditLogWriter;
|
|
|
455
565
|
exports.createInternalError = createInternalError;
|
|
456
566
|
exports.defineCommand = defineCommand;
|
|
457
567
|
exports.develitWorker = develitWorker;
|
|
458
|
-
exports.
|
|
568
|
+
exports.drizzleD1Config = drizzleD1Config;
|
|
569
|
+
exports.drizzlePgConfig = drizzlePgConfig;
|
|
570
|
+
exports.durableObjectNamespaceIdFromName = durableObjectNamespaceIdFromName;
|
|
459
571
|
exports.first = first;
|
|
460
572
|
exports.firstOrError = firstOrError;
|
|
461
573
|
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
|
|
|
@@ -162,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
162
161
|
*/
|
|
163
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
164
163
|
|
|
165
|
-
|
|
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
|
+
|
|
166
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
167
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
168
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -174,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
174
252
|
}) => InternalError;
|
|
175
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
176
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
|
+
|
|
177
270
|
declare const RPCResponse: {
|
|
178
271
|
/**
|
|
179
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -252,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
252
345
|
*/
|
|
253
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
254
347
|
|
|
255
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
256
|
-
|
|
257
|
-
interface AuditLogPayload<T> {
|
|
258
|
-
action: T;
|
|
259
|
-
actorId: string;
|
|
260
|
-
actorUsername?: string;
|
|
261
|
-
service: string;
|
|
262
|
-
entityId?: string;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
interface Command<TAuditAction = string> {
|
|
266
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
267
|
-
}
|
|
268
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
269
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
270
|
-
command: BatchItem<"sqlite">;
|
|
271
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
272
|
-
id: string;
|
|
273
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
274
|
-
|
|
275
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
276
|
-
private db;
|
|
277
|
-
private serviceName?;
|
|
278
|
-
private auditLogWriter?;
|
|
279
|
-
private commands;
|
|
280
|
-
private logs;
|
|
281
|
-
private ids;
|
|
282
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
283
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
284
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
285
|
-
executeAll(): Promise<void>;
|
|
286
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
287
|
-
getIds(): readonly string[];
|
|
288
|
-
getCommandsCount(): number;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
292
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
293
|
-
/**
|
|
294
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
295
|
-
*
|
|
296
|
-
* @param table - The Drizzle table definition for audit logs
|
|
297
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
298
|
-
*
|
|
299
|
-
* @example
|
|
300
|
-
* ```typescript
|
|
301
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
302
|
-
* import { auditLogsTable } from './schema'
|
|
303
|
-
*
|
|
304
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
305
|
-
*
|
|
306
|
-
* // Use in initializeDB
|
|
307
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
308
|
-
* ```
|
|
309
|
-
*/
|
|
310
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
311
|
-
|
|
312
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
313
349
|
new (...args: any[]): {
|
|
314
350
|
name: string;
|
|
@@ -328,5 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
328
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
329
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
330
366
|
|
|
331
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
332
|
-
export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, ValidatedInput };
|
|
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
|
|
|
@@ -162,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
162
161
|
*/
|
|
163
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
164
163
|
|
|
165
|
-
|
|
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
|
+
|
|
166
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
167
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
168
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -174,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
174
252
|
}) => InternalError;
|
|
175
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
176
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
|
+
|
|
177
270
|
declare const RPCResponse: {
|
|
178
271
|
/**
|
|
179
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -252,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
252
345
|
*/
|
|
253
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
254
347
|
|
|
255
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
256
|
-
|
|
257
|
-
interface AuditLogPayload<T> {
|
|
258
|
-
action: T;
|
|
259
|
-
actorId: string;
|
|
260
|
-
actorUsername?: string;
|
|
261
|
-
service: string;
|
|
262
|
-
entityId?: string;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
interface Command<TAuditAction = string> {
|
|
266
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
267
|
-
}
|
|
268
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
269
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
270
|
-
command: BatchItem<"sqlite">;
|
|
271
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
272
|
-
id: string;
|
|
273
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
274
|
-
|
|
275
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
276
|
-
private db;
|
|
277
|
-
private serviceName?;
|
|
278
|
-
private auditLogWriter?;
|
|
279
|
-
private commands;
|
|
280
|
-
private logs;
|
|
281
|
-
private ids;
|
|
282
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
283
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
284
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
285
|
-
executeAll(): Promise<void>;
|
|
286
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
287
|
-
getIds(): readonly string[];
|
|
288
|
-
getCommandsCount(): number;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
292
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
293
|
-
/**
|
|
294
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
295
|
-
*
|
|
296
|
-
* @param table - The Drizzle table definition for audit logs
|
|
297
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
298
|
-
*
|
|
299
|
-
* @example
|
|
300
|
-
* ```typescript
|
|
301
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
302
|
-
* import { auditLogsTable } from './schema'
|
|
303
|
-
*
|
|
304
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
305
|
-
*
|
|
306
|
-
* // Use in initializeDB
|
|
307
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
308
|
-
* ```
|
|
309
|
-
*/
|
|
310
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
311
|
-
|
|
312
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
313
349
|
new (...args: any[]): {
|
|
314
350
|
name: string;
|
|
@@ -328,5 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
328
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
329
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
330
366
|
|
|
331
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
332
|
-
export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, ValidatedInput };
|
|
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
|
|
|
@@ -162,7 +161,86 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
|
|
|
162
161
|
*/
|
|
163
162
|
type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
|
|
164
163
|
|
|
165
|
-
|
|
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
|
+
|
|
166
244
|
declare function first<T>(rows: T[]): T | undefined;
|
|
167
245
|
declare function firstOrError<T>(rows: T[]): T;
|
|
168
246
|
declare const uuidv4: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
@@ -174,6 +252,21 @@ declare const createInternalError: (error: unknown, details?: {
|
|
|
174
252
|
}) => InternalError;
|
|
175
253
|
declare const isInternalError: (error: unknown) => error is InternalError;
|
|
176
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
|
+
|
|
177
270
|
declare const RPCResponse: {
|
|
178
271
|
/**
|
|
179
272
|
* ✅ Constructs a successful RPC response.
|
|
@@ -252,63 +345,6 @@ declare const useResult: <T>(promise: Promise<T>) => Promise<Result<T>>;
|
|
|
252
345
|
*/
|
|
253
346
|
declare const useResultSync: <T>(fn: () => T) => Result<T>;
|
|
254
347
|
|
|
255
|
-
declare const calculateExponentialBackoff: (attempts: number, baseDelaySeconds: number) => number;
|
|
256
|
-
|
|
257
|
-
interface AuditLogPayload<T> {
|
|
258
|
-
action: T;
|
|
259
|
-
actorId: string;
|
|
260
|
-
actorUsername?: string;
|
|
261
|
-
service: string;
|
|
262
|
-
entityId?: string;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
interface Command<TAuditAction = string> {
|
|
266
|
-
handler: (db: DrizzleD1Database<Record<string, unknown>>) => CommandItem<TAuditAction>;
|
|
267
|
-
}
|
|
268
|
-
type CommandFactory<TParams = void, TAuditAction = string> = TParams extends void ? () => Command<TAuditAction> : (params: TParams) => Command<TAuditAction>;
|
|
269
|
-
declare const defineCommand: <TParams = void, TAuditAction = string>(handler: (db: DrizzleD1Database<Record<string, unknown>>, params: TParams) => {
|
|
270
|
-
command: BatchItem<"sqlite">;
|
|
271
|
-
logPayload: CommandLogPayload<TAuditAction>;
|
|
272
|
-
id: string;
|
|
273
|
-
}) => CommandFactory<TParams, TAuditAction>;
|
|
274
|
-
|
|
275
|
-
declare class DatabaseTransaction<TAuditAction = string> {
|
|
276
|
-
private db;
|
|
277
|
-
private serviceName?;
|
|
278
|
-
private auditLogWriter?;
|
|
279
|
-
private commands;
|
|
280
|
-
private logs;
|
|
281
|
-
private ids;
|
|
282
|
-
constructor(db: DrizzleD1Database<Record<string, unknown>>, serviceName?: string | undefined, auditLogWriter?: ((logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<"sqlite">[]) | undefined);
|
|
283
|
-
enqueue<U extends Command<TAuditAction>, T extends Readonly<U> | Readonly<[U, ...U[]]>>(commands: T): string | string[] | undefined;
|
|
284
|
-
execute(commandItem: Command<TAuditAction>): Promise<void>;
|
|
285
|
-
executeAll(): Promise<void>;
|
|
286
|
-
getLogs(): readonly AuditLogPayload<TAuditAction>[];
|
|
287
|
-
getIds(): readonly string[];
|
|
288
|
-
getCommandsCount(): number;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
type AuditLogTable = AnySQLiteTable | AnyPgTable;
|
|
292
|
-
type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
|
|
293
|
-
/**
|
|
294
|
-
* Creates an audit log writer function that inserts audit logs into a specified table
|
|
295
|
-
*
|
|
296
|
-
* @param table - The Drizzle table definition for audit logs
|
|
297
|
-
* @returns A function that can be passed to DatabaseTransaction constructor
|
|
298
|
-
*
|
|
299
|
-
* @example
|
|
300
|
-
* ```typescript
|
|
301
|
-
* import { createAuditLogWriter } from '@develit-io/workers-sdk'
|
|
302
|
-
* import { auditLogsTable } from './schema'
|
|
303
|
-
*
|
|
304
|
-
* const auditWriter = createAuditLogWriter(auditLogsTable)
|
|
305
|
-
*
|
|
306
|
-
* // Use in initializeDB
|
|
307
|
-
* this.initializeDB(env.DB, schema, auditWriter)
|
|
308
|
-
* ```
|
|
309
|
-
*/
|
|
310
|
-
declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
|
|
311
|
-
|
|
312
348
|
declare const service: (serviceName: string) => <T extends new (...args: any[]) => object>(constructor: T) => {
|
|
313
349
|
new (...args: any[]): {
|
|
314
350
|
name: string;
|
|
@@ -328,5 +364,4 @@ interface WithRetryCounterOptions {
|
|
|
328
364
|
type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
|
|
329
365
|
declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
|
|
330
366
|
|
|
331
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
332
|
-
export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, ValidatedInput };
|
|
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,10 @@ 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';
|
|
11
|
+
import { parse } from 'jsonc-parser';
|
|
9
12
|
import superjson from 'superjson';
|
|
10
13
|
|
|
11
14
|
const base = {
|
|
@@ -191,28 +194,116 @@ async function handleAction(worker, input, options = {}, actionExecution) {
|
|
|
191
194
|
}
|
|
192
195
|
}
|
|
193
196
|
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
197
|
+
const asNonEmpty = (arr) => {
|
|
198
|
+
return arr.length > 0 ? [arr[0], ...arr.slice(1)] : null;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
function createAuditLogWriter(table) {
|
|
202
|
+
return (logs, db) => {
|
|
203
|
+
if (logs.length === 0) return [];
|
|
204
|
+
const auditRecords = logs.map((log) => ({
|
|
205
|
+
...log,
|
|
206
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
207
|
+
id: crypto.randomUUID()
|
|
208
|
+
}));
|
|
209
|
+
return [db.insert(table).values(auditRecords)];
|
|
210
|
+
};
|
|
207
211
|
}
|
|
208
|
-
const uuidv4 = () => crypto.randomUUID();
|
|
209
212
|
|
|
210
|
-
|
|
211
|
-
|
|
213
|
+
function durableObjectNamespaceIdFromName(uniqueKey, name) {
|
|
214
|
+
const key = crypto$1.createHash("sha256").update(uniqueKey).digest();
|
|
215
|
+
const nameHmac = crypto$1.createHmac("sha256", key).update(name).digest().subarray(0, 16);
|
|
216
|
+
const hmac = crypto$1.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16);
|
|
217
|
+
return Buffer.concat([nameHmac, hmac]).toString("hex");
|
|
218
|
+
}
|
|
219
|
+
const getDatabaseIdFromWrangler = () => {
|
|
220
|
+
try {
|
|
221
|
+
const wranglerPath = path.resolve("./wrangler.jsonc");
|
|
222
|
+
const wranglerContent = fs.readFileSync(wranglerPath, "utf-8");
|
|
223
|
+
const errors = [];
|
|
224
|
+
const config = parse(wranglerContent, errors, { allowTrailingComma: true });
|
|
225
|
+
if (errors.length) {
|
|
226
|
+
throw new Error("Invalid JSONC in wrangler.jsonc");
|
|
227
|
+
}
|
|
228
|
+
const environment = process.env.ENVIRONMENT || "localhost";
|
|
229
|
+
let databaseId;
|
|
230
|
+
if (environment !== "localhost" && config.env?.[environment]) {
|
|
231
|
+
databaseId = config.env[environment].d1_databases?.[0]?.database_id;
|
|
232
|
+
console.log(
|
|
233
|
+
`Using database_id for environment '${environment}': ${databaseId}`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
if (!databaseId) {
|
|
237
|
+
databaseId = config.d1_databases?.[0]?.database_id;
|
|
238
|
+
console.log(
|
|
239
|
+
`Using default database_id for environment '${environment}': ${databaseId}`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (!databaseId) {
|
|
243
|
+
throw new Error("database_id not found in wrangler.jsonc");
|
|
244
|
+
}
|
|
245
|
+
return databaseId;
|
|
246
|
+
} catch (err) {
|
|
247
|
+
console.warn(
|
|
248
|
+
`Warning: Could not read database_id from wrangler.jsonc: ${err}`
|
|
249
|
+
);
|
|
250
|
+
}
|
|
212
251
|
};
|
|
213
|
-
|
|
214
|
-
const
|
|
215
|
-
return
|
|
252
|
+
const isRemoteEnvironment = () => {
|
|
253
|
+
const environment = process.env.ENVIRONMENT;
|
|
254
|
+
return environment && environment !== "localhost";
|
|
255
|
+
};
|
|
256
|
+
const getLocalD1 = (databaseId) => {
|
|
257
|
+
const name = durableObjectNamespaceIdFromName(
|
|
258
|
+
"miniflare-D1DatabaseObject",
|
|
259
|
+
databaseId
|
|
260
|
+
);
|
|
261
|
+
const searchPaths = [
|
|
262
|
+
path.resolve("../../.wrangler"),
|
|
263
|
+
// Root of monorepo
|
|
264
|
+
path.resolve("./.wrangler")
|
|
265
|
+
// Current directory
|
|
266
|
+
];
|
|
267
|
+
for (const basePath of searchPaths) {
|
|
268
|
+
try {
|
|
269
|
+
const dbFile = fs.readdirSync(basePath, { encoding: "utf-8", recursive: true }).find((f) => f.includes(name));
|
|
270
|
+
if (dbFile) {
|
|
271
|
+
const url = path.resolve(basePath, dbFile);
|
|
272
|
+
console.log(`Found D1 database at: ${url}`);
|
|
273
|
+
return url;
|
|
274
|
+
} else {
|
|
275
|
+
throw new Error(`No D1 database file found in ${basePath}`);
|
|
276
|
+
}
|
|
277
|
+
} catch {
|
|
278
|
+
console.warn(`Could not search in ${basePath}`);
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
const getCredentials = () => {
|
|
284
|
+
const databaseId = getDatabaseIdFromWrangler() ?? "";
|
|
285
|
+
if (isRemoteEnvironment()) {
|
|
286
|
+
return {
|
|
287
|
+
driver: "d1-http",
|
|
288
|
+
dbCredentials: {
|
|
289
|
+
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
290
|
+
databaseId,
|
|
291
|
+
token: process.env.CLOUDFLARE_API_TOKEN
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
} else {
|
|
295
|
+
return {
|
|
296
|
+
dbCredentials: {
|
|
297
|
+
url: getLocalD1(databaseId)
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
const drizzleD1Config = {
|
|
303
|
+
schema: "./src/database/schema/",
|
|
304
|
+
out: "./src/database/migrations/",
|
|
305
|
+
dialect: "sqlite",
|
|
306
|
+
...getCredentials()
|
|
216
307
|
};
|
|
217
308
|
|
|
218
309
|
class DatabaseTransaction {
|
|
@@ -277,17 +368,33 @@ const defineCommand = (handler) => {
|
|
|
277
368
|
});
|
|
278
369
|
};
|
|
279
370
|
|
|
280
|
-
function
|
|
281
|
-
return
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
return [db.insert(table).values(auditRecords)];
|
|
289
|
-
};
|
|
371
|
+
function first(rows) {
|
|
372
|
+
return rows.length > 0 ? rows[0] : void 0;
|
|
373
|
+
}
|
|
374
|
+
function firstOrError(rows) {
|
|
375
|
+
if (rows.length === 0) {
|
|
376
|
+
throw new Error("Query did not return any data.");
|
|
377
|
+
}
|
|
378
|
+
return rows[0];
|
|
290
379
|
}
|
|
380
|
+
const uuidv4 = () => crypto.randomUUID();
|
|
381
|
+
|
|
382
|
+
const drizzlePgConfig = {
|
|
383
|
+
schema: "./src/database/schema/",
|
|
384
|
+
out: "./src/database/migrations/",
|
|
385
|
+
dialect: "postgresql",
|
|
386
|
+
dbCredentials: {
|
|
387
|
+
url: process.env.DATABASE_URL
|
|
388
|
+
},
|
|
389
|
+
migrations: {
|
|
390
|
+
table: "__drizzle_migrations",
|
|
391
|
+
schema: "public"
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
const calculateExponentialBackoff = (attempts, baseDelaySeconds) => {
|
|
396
|
+
return baseDelaySeconds ** attempts;
|
|
397
|
+
};
|
|
291
398
|
|
|
292
399
|
const service = (serviceName) => {
|
|
293
400
|
return function(constructor) {
|
|
@@ -425,4 +532,4 @@ function develitWorker(Worker) {
|
|
|
425
532
|
return DevelitWorker;
|
|
426
533
|
}
|
|
427
534
|
|
|
428
|
-
export { DatabaseTransaction, RPCResponse, action, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, createAuditLogWriter, createInternalError, defineCommand, develitWorker,
|
|
535
|
+
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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@develit-io/backend-sdk",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.8.0",
|
|
4
4
|
"description": "Develit Backend SDK",
|
|
5
5
|
"author": "Develit.io",
|
|
6
6
|
"license": "ISC",
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
"lint": "biome check",
|
|
12
12
|
"lint:fix": "biome check --fix",
|
|
13
13
|
"build": "unbuild",
|
|
14
|
+
"test": "vitest",
|
|
15
|
+
"test:unit": "vitest test/unit",
|
|
14
16
|
"changelogen": "bunx changelogen@latest --bump",
|
|
15
17
|
"release": "bun run build && bunx changelogen@latest --release --push && npm publish --access public"
|
|
16
18
|
},
|
|
@@ -31,9 +33,13 @@
|
|
|
31
33
|
"drizzle-orm": "^0.44.3",
|
|
32
34
|
"h3": "^1.15.3",
|
|
33
35
|
"http-status-codes": "2.3.0",
|
|
36
|
+
"jsonc-parser": "^3.3.1",
|
|
34
37
|
"superjson": "^2.2.2"
|
|
35
38
|
},
|
|
36
39
|
"peerDependencies": {
|
|
37
40
|
"zod": "^4.0.11"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"vitest": "^1.6.0"
|
|
38
44
|
}
|
|
39
45
|
}
|