@develit-io/backend-sdk 5.20.0 → 5.21.1

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 CHANGED
@@ -5,8 +5,9 @@ const pgCore = require('drizzle-orm/pg-core');
5
5
  const sqliteCore = require('drizzle-orm/sqlite-core');
6
6
  const generalCodes = require('@develit-io/general-codes');
7
7
  const text = require('@std/text');
8
- require('http-status-codes');
8
+ const cloudflare = require('alchemy/cloudflare');
9
9
  const z = require('zod/v4/core');
10
+ require('http-status-codes');
10
11
  const h3 = require('h3');
11
12
  const fs = require('node:fs');
12
13
  const crypto$1 = require('node:crypto');
@@ -81,12 +82,9 @@ const composeD1Arguments = ({
81
82
  resourceName
82
83
  }) => {
83
84
  return {
84
- transform: {
85
- database: {
86
- name: resourceName,
87
- primaryLocationHint: "weur"
88
- }
89
- }
85
+ name: resourceName,
86
+ primaryLocationHint: "weur"
87
+ // TODO: It's possible that it will take care of migrations as well
90
88
  };
91
89
  };
92
90
 
@@ -94,11 +92,7 @@ const composeKvArguments = ({
94
92
  resourceName
95
93
  }) => {
96
94
  return {
97
- transform: {
98
- namespace: {
99
- title: resourceName
100
- }
101
- }
95
+ title: resourceName
102
96
  };
103
97
  };
104
98
 
@@ -108,14 +102,10 @@ const composeQueueArguments = ({
108
102
  messageRetentionPeriod = 259200
109
103
  }) => {
110
104
  return {
111
- transform: {
112
- queue: {
113
- queueName: resourceName,
114
- settings: {
115
- deliveryDelay,
116
- messageRetentionPeriod
117
- }
118
- }
105
+ name: resourceName,
106
+ settings: {
107
+ deliveryDelay,
108
+ messageRetentionPeriod
119
109
  }
120
110
  };
121
111
  };
@@ -125,14 +115,10 @@ const composeR2Arguments = ({
125
115
  storageClass = "Standard"
126
116
  }) => {
127
117
  return {
128
- transform: {
129
- bucket: {
130
- name: resourceName,
131
- jurisdiction: "eu",
132
- location: "weur",
133
- storageClass
134
- }
135
- }
118
+ name: resourceName,
119
+ jurisdiction: "eu",
120
+ locationHint: "weur",
121
+ storageClass
136
122
  };
137
123
  };
138
124
 
@@ -155,23 +141,20 @@ const composeResourceName = ({
155
141
  class Infrastructure {
156
142
  project;
157
143
  environment;
158
- sst;
159
144
  constructor({
160
145
  project,
161
- environment,
162
- sst
146
+ environment
163
147
  }) {
164
148
  this.project = project;
165
149
  this.environment = environment;
166
- this.sst = sst;
167
150
  }
168
151
  /**
169
152
  * Creates an instance of Cloudflare KV.
170
153
  */
171
- kv(options) {
172
- const { resourceName, bindingName } = options;
173
- return new this.sst.cloudflare.Kv(
174
- `${composeBindingName({ resource: "kv", resourceName, bindingName })}`,
154
+ async kv(options) {
155
+ const { resourceName } = options;
156
+ return await cloudflare.KVNamespace(
157
+ resourceName,
175
158
  composeKvArguments({
176
159
  resourceName: composeResourceName({
177
160
  project: this.project,
@@ -184,10 +167,10 @@ class Infrastructure {
184
167
  /**
185
168
  * Creates an instance of Cloudflare D1.
186
169
  */
187
- d1(options) {
188
- const { resourceName, bindingName } = options;
189
- return new this.sst.cloudflare.D1(
190
- `${composeBindingName({ resource: "d1", resourceName, bindingName })}`,
170
+ async d1(options) {
171
+ const { resourceName } = options;
172
+ return await cloudflare.D1Database(
173
+ resourceName,
191
174
  composeD1Arguments({
192
175
  resourceName: composeResourceName({
193
176
  project: this.project,
@@ -200,10 +183,10 @@ class Infrastructure {
200
183
  /**
201
184
  * Creates an instance of Cloudflare Queue.
202
185
  */
203
- queue(options) {
204
- const { resourceName, bindingName, deliveryDelay, messageRetentionPeriod } = options;
205
- return new this.sst.cloudflare.Queue(
206
- `${composeBindingName({ resource: "queue", resourceName, bindingName })}`,
186
+ async queue(options) {
187
+ const { resourceName, deliveryDelay, messageRetentionPeriod } = options;
188
+ return await cloudflare.Queue(
189
+ resourceName,
207
190
  composeQueueArguments({
208
191
  resourceName: composeResourceName({
209
192
  project: this.project,
@@ -218,10 +201,10 @@ class Infrastructure {
218
201
  /**
219
202
  * Creates an instance of Cloudflare R2.
220
203
  */
221
- r2(options) {
222
- const { resourceName, bindingName, storageClass } = options;
223
- return new this.sst.cloudflare.Bucket(
224
- `${composeBindingName({ resource: "r2", resourceName, bindingName })}`,
204
+ async r2(options) {
205
+ const { resourceName, storageClass } = options;
206
+ return await cloudflare.R2Bucket(
207
+ resourceName,
225
208
  composeR2Arguments({
226
209
  resourceName: composeResourceName({
227
210
  project: this.project,
@@ -685,6 +668,39 @@ const defineCommand = (handler) => {
685
668
  }));
686
669
  };
687
670
 
671
+ async function useFetch(url, { parseAs = "json", ...options } = {}) {
672
+ const [response, fetchError] = await useResult(fetch(url, options));
673
+ if (fetchError || !response) {
674
+ return [null, createInternalError(fetchError, { code: "NETWORK_ERROR" })];
675
+ }
676
+ const parsers = {
677
+ json: () => response.json(),
678
+ text: () => response.text(),
679
+ blob: () => response.blob()
680
+ };
681
+ const [body, parseError] = await useResult(parsers[parseAs]());
682
+ if (!response.ok) {
683
+ return [
684
+ null,
685
+ createInternalError(parseError, {
686
+ message: body?.message ?? response.statusText,
687
+ code: "HTTP_ERROR",
688
+ status: response.status
689
+ })
690
+ ];
691
+ }
692
+ if (parseError) {
693
+ return [
694
+ null,
695
+ createInternalError(parseError, {
696
+ code: "PARSE_ERROR",
697
+ status: response.status
698
+ })
699
+ ];
700
+ }
701
+ return [body, null];
702
+ }
703
+
688
704
  const getPgLocalConnectionString = (id) => `postgres://db_user:db_password@127.0.0.1:${derivePortFromId(id)}/db`;
689
705
  const getPgDatabaseIdFromWrangler = () => {
690
706
  try {
@@ -912,6 +928,7 @@ exports.paginationQuerySchema = paginationQuerySchema;
912
928
  exports.paginationSchema = paginationSchema;
913
929
  exports.service = service;
914
930
  exports.swiftZodSchema = swiftZodSchema;
931
+ exports.useFetch = useFetch;
915
932
  exports.useResult = useResult;
916
933
  exports.useResultSync = useResultSync;
917
934
  exports.uuidv4 = uuidv4;
package/dist/index.d.cts CHANGED
@@ -4,10 +4,11 @@ import * as drizzle_orm from 'drizzle-orm';
4
4
  import { ExtractTablesWithRelations, DBQueryConfig, BuildQueryResult } from 'drizzle-orm';
5
5
  import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
6
6
  import { AnySQLiteTable } from 'drizzle-orm/sqlite-core';
7
+ import { KVNamespace, D1Database, Queue, R2Bucket } from 'alchemy/cloudflare';
8
+ import * as z from 'zod/v4/core';
7
9
  import { StatusCodes, ReasonPhrases } from 'http-status-codes';
8
10
  export { ReasonPhrases as InternalResponsePhrase, StatusCodes as InternalResponseStatus } from 'http-status-codes';
9
- import * as z from 'zod/v4/core';
10
- import { Queue } from '@cloudflare/workers-types';
11
+ import { Queue as Queue$1 } from '@cloudflare/workers-types';
11
12
  import { BatchItem } from 'drizzle-orm/batch';
12
13
  import { DrizzleD1Database } from 'drizzle-orm/d1';
13
14
 
@@ -50,19 +51,12 @@ type Project = 'creditio' | 'fp' | 'mdm' | 'moneio' | 'txs';
50
51
 
51
52
  type Environment = number | 'dev' | 'test' | 'staging' | 'production';
52
53
 
53
- interface SstInstance {
54
- cloudflare: {
55
- [key: string]: any;
56
- };
57
- }
58
54
  declare class Infrastructure {
59
55
  private project;
60
56
  private environment;
61
- private sst;
62
- constructor({ project, environment, sst, }: {
57
+ constructor({ project, environment, }: {
63
58
  project: Project;
64
59
  environment: Environment;
65
- sst: SstInstance;
66
60
  });
67
61
  /**
68
62
  * Creates an instance of Cloudflare KV.
@@ -72,11 +66,7 @@ declare class Infrastructure {
72
66
  * Name of the KV. Do not include the 'kv' prefix.
73
67
  */
74
68
  resourceName: string;
75
- /**
76
- * Name of the KV's binding. If not set, it is generated automatically based on the provided name.
77
- */
78
- bindingName?: string;
79
- }): any;
69
+ }): Promise<KVNamespace>;
80
70
  /**
81
71
  * Creates an instance of Cloudflare D1.
82
72
  */
@@ -85,11 +75,7 @@ declare class Infrastructure {
85
75
  * Name of the D1. Do not include the 'd1' prefix.
86
76
  */
87
77
  resourceName: string;
88
- /**
89
- * Name of the D1's binding. If not set, it is generated automatically based on the provided name.
90
- */
91
- bindingName?: string;
92
- }): any;
78
+ }): Promise<D1Database>;
93
79
  /**
94
80
  * Creates an instance of Cloudflare Queue.
95
81
  */
@@ -98,10 +84,6 @@ declare class Infrastructure {
98
84
  * Name of the Queue. Do not include the 'queue' prefix.
99
85
  */
100
86
  resourceName: string;
101
- /**
102
- * Name of the Queue's binding. If not set, it is generated automatically based on the provided name.
103
- */
104
- bindingName?: string;
105
87
  /**
106
88
  * The number of seconds to delay delivery of messages to the queue.
107
89
  */
@@ -110,7 +92,7 @@ declare class Infrastructure {
110
92
  * The number of seconds a message will remain in the queue before being deleted.
111
93
  */
112
94
  messageRetentionPeriod?: number;
113
- }): any;
95
+ }): Promise<Queue<unknown>>;
114
96
  /**
115
97
  * Creates an instance of Cloudflare R2.
116
98
  */
@@ -119,36 +101,35 @@ declare class Infrastructure {
119
101
  * Name of the R2. Do not include the 'r2' prefix.
120
102
  */
121
103
  resourceName: string;
122
- /**
123
- * Name of the R2's binding. If not set, it is generated automatically based on the provided name.
124
- */
125
- bindingName?: string;
126
104
  /**
127
105
  * The storage class for the R2 bucket.
128
106
  */
129
107
  storageClass?: 'Standard' | 'InfrequentAccess';
130
- }): any;
108
+ }): Promise<R2Bucket>;
131
109
  }
132
110
 
133
- type Resource = 'kv' | 'd1' | 'queue' | 'r2' | 'worker' | 'service' | 'orchestrator';
134
-
135
- type InternalErrorResponseStatus = Exclude<StatusCodes, 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207>;
136
- interface InternalError {
137
- status: InternalErrorResponseStatus;
138
- code: string;
139
- message: string;
111
+ interface AuditLogPayload<T> {
112
+ action: T;
113
+ actorId: string;
114
+ actorUsername?: string;
115
+ service: string;
116
+ entityId?: string;
140
117
  }
141
- interface IRPCResponse<T> {
142
- status: StatusCodes;
143
- message: string;
144
- data: T | null | undefined;
145
- error: boolean;
146
- phrase?: ReasonPhrases;
118
+
119
+ declare const ibanZodSchema: z.$ZodString<unknown>;
120
+ declare const swiftZodSchema: z.$ZodString<unknown>;
121
+
122
+ interface CommandLogPayload<T = string> {
123
+ action: T;
124
+ actorId: string;
125
+ actorUsername?: string;
126
+ entityId?: string;
147
127
  }
148
- interface GatewayResponse<T> {
149
- status?: number;
150
- message: string;
151
- data?: T;
128
+
129
+ interface CommandItem<TAuditAction = string> {
130
+ command: BatchItem<'sqlite'>;
131
+ logPayload: CommandLogPayload<TAuditAction>;
132
+ id: string;
152
133
  }
153
134
 
154
135
  /**
@@ -171,21 +152,7 @@ type InferResultType<Tables extends Record<string, unknown>, TableName extends k
171
152
  with: With;
172
153
  }>;
173
154
 
174
- declare const ibanZodSchema: z.$ZodString<unknown>;
175
- declare const swiftZodSchema: z.$ZodString<unknown>;
176
-
177
- interface CommandLogPayload<T = string> {
178
- action: T;
179
- actorId: string;
180
- actorUsername?: string;
181
- entityId?: string;
182
- }
183
-
184
- interface CommandItem<TAuditAction = string> {
185
- command: BatchItem<'sqlite'>;
186
- logPayload: CommandLogPayload<TAuditAction>;
187
- id: string;
188
- }
155
+ type Resource = 'kv' | 'd1' | 'queue' | 'r2' | 'worker' | 'service' | 'orchestrator';
189
156
 
190
157
  declare const paginationQuerySchema: z.$ZodObject<Readonly<Readonly<{
191
158
  [k: string]: z.$ZodType<unknown, unknown, z.$ZodTypeInternals<unknown, unknown>>;
@@ -194,6 +161,38 @@ declare const paginationSchema: z.$ZodObject<Readonly<Readonly<{
194
161
  [k: string]: z.$ZodType<unknown, unknown, z.$ZodTypeInternals<unknown, unknown>>;
195
162
  }>>, z.$ZodObjectConfig>;
196
163
 
164
+ type InternalErrorResponseStatus = Exclude<StatusCodes, 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207>;
165
+ interface InternalError {
166
+ status: InternalErrorResponseStatus;
167
+ code: string;
168
+ message: string;
169
+ }
170
+ interface IRPCResponse<T> {
171
+ status: StatusCodes;
172
+ message: string;
173
+ data: T | null | undefined;
174
+ error: boolean;
175
+ phrase?: ReasonPhrases;
176
+ }
177
+ interface GatewayResponse<T> {
178
+ status?: number;
179
+ message: string;
180
+ data?: T;
181
+ }
182
+
183
+ /**
184
+ * A utility function to handle operations and return a standardized result.
185
+ *
186
+ * This function wraps the call and ensures that both the resolved value
187
+ * and any potential errors are captured in a structured tuple format.
188
+ *
189
+ * @template T - The type of the expected result.
190
+ * @returns A call that resolves to a tuple containing:
191
+ * - The resolved data (`T | null`) if successful.
192
+ * - An `RPCError` object (`RPCError | null`) if an error occurs.
193
+ */
194
+ type Result<T> = [data: T | null, error: InternalError | null];
195
+
197
196
  declare const composeBindingName: ({ resource, resourceName, bindingName, }: {
198
197
  resource: Resource;
199
198
  resourceName: string;
@@ -223,8 +222,8 @@ interface DevelitWorkerMethods {
223
222
  logInput(data: object): void;
224
223
  logOutput(data: object): void;
225
224
  logError(error: object): void;
226
- pushToQueue<T>(queue: Queue, message: T | T[]): Promise<void>;
227
- recordAuditLogMessage<T>(queue: Queue, message: T | T[]): Promise<void>;
225
+ pushToQueue<T>(queue: Queue$1, message: T | T[]): Promise<void>;
226
+ recordAuditLogMessage<T>(queue: Queue$1, message: T | T[]): Promise<void>;
228
227
  handleInput<T extends z.$ZodType>(args: {
229
228
  input: z.infer<T>;
230
229
  schema: T;
@@ -287,14 +286,6 @@ type ValidatedInput<T extends z.$ZodType> = z.infer<T>;
287
286
  */
288
287
  type ActionExecution<TInput, TOutput> = TInput extends null ? () => Promise<TOutput> : (input: TInput) => Promise<TOutput>;
289
288
 
290
- interface AuditLogPayload<T> {
291
- action: T;
292
- actorId: string;
293
- actorUsername?: string;
294
- service: string;
295
- entityId?: string;
296
- }
297
-
298
289
  type AuditLogTable = AnySQLiteTable | AnyPgTable;
299
290
  type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction>[], db: DrizzleD1Database<Record<string, unknown>>) => BatchItem<'sqlite'>[];
300
291
  /**
@@ -316,7 +307,7 @@ type AuditLogWriter<TAuditAction = string> = (logs: AuditLogPayload<TAuditAction
316
307
  */
317
308
  declare function createAuditLogWriter<TAuditAction = string>(table: AuditLogTable): AuditLogWriter<TAuditAction>;
318
309
 
319
- declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): string;
310
+ declare function durableObjectNamespaceIdFromName(uniqueKey: string, name: string): any;
320
311
  declare const getD1DatabaseIdFromWrangler: () => string | undefined;
321
312
  declare const getD1Credentials: () => {
322
313
  driver?: undefined;
@@ -324,14 +315,14 @@ declare const getD1Credentials: () => {
324
315
  } | {
325
316
  driver: string;
326
317
  dbCredentials: {
327
- accountId: string | undefined;
318
+ accountId: any;
328
319
  databaseId: string;
329
- token: string | undefined;
320
+ token: any;
330
321
  url?: undefined;
331
322
  };
332
323
  } | {
333
324
  dbCredentials: {
334
- url: string | undefined;
325
+ url: any;
335
326
  accountId?: undefined;
336
327
  databaseId?: undefined;
337
328
  token?: undefined;
@@ -347,9 +338,9 @@ declare const getDrizzleD1Config: () => {
347
338
  } | {
348
339
  driver: string;
349
340
  dbCredentials: {
350
- accountId: string | undefined;
341
+ accountId: any;
351
342
  databaseId: string;
352
- token: string | undefined;
343
+ token: any;
353
344
  url?: undefined;
354
345
  };
355
346
  schema: string;
@@ -357,7 +348,7 @@ declare const getDrizzleD1Config: () => {
357
348
  dialect: "sqlite";
358
349
  } | {
359
350
  dbCredentials: {
360
- url: string | undefined;
351
+ url: any;
361
352
  accountId?: undefined;
362
353
  databaseId?: undefined;
363
354
  token?: undefined;
@@ -406,11 +397,16 @@ declare const createInternalError: (error: unknown, details?: {
406
397
  }) => InternalError;
407
398
  declare const isInternalError: (error: unknown) => error is InternalError;
408
399
 
400
+ interface UseFetchOptions extends RequestInit {
401
+ parseAs?: 'json' | 'text' | 'blob';
402
+ }
403
+ declare function useFetch<T = unknown>(url: string, { parseAs, ...options }?: UseFetchOptions): Promise<Result<T>>;
404
+
409
405
  declare const getPgLocalConnectionString: (id: string) => string;
410
406
  declare const getPgDatabaseIdFromWrangler: () => string | undefined;
411
407
  declare const getPgCredentials: (serviceName?: string) => {
412
408
  dbCredentials: {
413
- url: string;
409
+ url: any;
414
410
  };
415
411
  };
416
412
  declare const getDrizzlePgConfig: () => {
@@ -419,7 +415,7 @@ declare const getDrizzlePgConfig: () => {
419
415
  schema: string;
420
416
  };
421
417
  dbCredentials: {
422
- url: string;
418
+ url: any;
423
419
  };
424
420
  schema: string;
425
421
  out: string;
@@ -467,18 +463,6 @@ declare const RPCResponse: {
467
463
  validationError<T>(error: InternalError): IRPCResponse<T>;
468
464
  };
469
465
 
470
- /**
471
- * A utility function to handle operations and return a standardized result.
472
- *
473
- * This function wraps the call and ensures that both the resolved value
474
- * and any potential errors are captured in a structured tuple format.
475
- *
476
- * @template T - The type of the expected result.
477
- * @returns A call that resolves to a tuple containing:
478
- * - The resolved data (`T | null`) if successful.
479
- * - An `RPCError` object (`RPCError | null`) if an error occurs.
480
- */
481
- type Result<T> = [data: T | null, error: InternalError | null];
482
466
  /**
483
467
  * Executes a given promise and returns the result in a structured format.
484
468
  *
@@ -525,5 +509,5 @@ interface WithRetryCounterOptions {
525
509
  type AsyncMethod<TArgs extends unknown[] = unknown[], TResult = unknown> = (...args: TArgs) => Promise<TResult>;
526
510
  declare function cloudflareQueue<TArgs extends unknown[] = unknown[], TResult = unknown>(options: WithRetryCounterOptions): (target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<AsyncMethod<TArgs, TResult>>) => void;
527
511
 
528
- export { DatabaseTransaction, ENVIRONMENT, Infrastructure, RPCResponse, action, bankAccount, bankAccountBankCodeEnum, bankAccountCountryCodeEnum, bankAccountCurrencyEnum, bankAccountPostgres, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, composeBindingName, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getDrizzlePgConfig, getPgCredentials, getPgDatabaseIdFromWrangler, getPgLocalConnectionString, handleAction, handleActionResponse, ibanZodSchema, isInternalError, paginationQuerySchema, paginationSchema, service, swiftZodSchema, useResult, useResultSync, uuidv4, validateEnvironment };
512
+ export { DatabaseTransaction, ENVIRONMENT, Infrastructure, RPCResponse, action, bankAccount, bankAccountBankCodeEnum, bankAccountCountryCodeEnum, bankAccountCurrencyEnum, bankAccountPostgres, base, basePostgres, calculateExponentialBackoff, cloudflareQueue, composeBindingName, createAuditLogWriter, createInternalError, defineCommand, derivePortFromId, develitWorker, durableObjectNamespaceIdFromName, first, firstOrError, getD1Credentials, getD1DatabaseIdFromWrangler, getDrizzleD1Config, getDrizzlePgConfig, getPgCredentials, getPgDatabaseIdFromWrangler, getPgLocalConnectionString, handleAction, handleActionResponse, ibanZodSchema, isInternalError, paginationQuerySchema, paginationSchema, service, swiftZodSchema, useFetch, useResult, useResultSync, uuidv4, validateEnvironment };
529
513
  export type { ActionExecution, ActionHandlerOptions, AuditLogWriter, Command, CommandLogPayload, DevelitWorkerMethods, Environment, GatewayResponse, IRPCResponse, IncludeRelation, InferResultType, InternalError, InternalErrorResponseStatus, Project, ValidatedInput };