pecunia-core 0.0.0 → 0.0.2

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.
@@ -1,2 +1,2 @@
1
- import { a as useMiddleware, i as optionsMiddleware, n as createPaymentEndpoint, r as createPecuniaMiddleware, t as PaymentMiddleware } from "../index-CtOgkCz5.mjs";
1
+ import { a as useMiddleware, i as optionsMiddleware, n as createPaymentEndpoint, r as createPecuniaMiddleware, t as PaymentMiddleware } from "../index-BTBqeO2-.mjs";
2
2
  export { PaymentMiddleware, createPaymentEndpoint, createPecuniaMiddleware, optionsMiddleware, useMiddleware };
@@ -1,5 +1,5 @@
1
- import "../context-_erD9NsC.mjs";
1
+ import "../context-COLduJme.mjs";
2
2
  import "../async_hooks-D8vqDJIk.mjs";
3
- import { i as useMiddleware, n as createPecuniaMiddleware, r as optionsMiddleware, t as createPaymentEndpoint } from "../api-Dnub-EIf.mjs";
3
+ import { i as useMiddleware, n as createPecuniaMiddleware, r as optionsMiddleware, t as createPaymentEndpoint } from "../api-BlJV5ZQo.mjs";
4
4
 
5
5
  export { createPaymentEndpoint, createPecuniaMiddleware, optionsMiddleware, useMiddleware };
@@ -1,4 +1,4 @@
1
- import { f as runWithEndpointContext } from "./context-_erD9NsC.mjs";
1
+ import { f as runWithEndpointContext } from "./context-COLduJme.mjs";
2
2
  import { createEndpoint, createMiddleware } from "better-call";
3
3
 
4
4
  //#region src/api/middleware/index.ts
@@ -1,2 +1,2 @@
1
- import { At as RequestState, Dt as getCurrentDBAdapterAsyncLocalStorage, Et as getCurrentAdapter, Ft as hasRequestState, It as runWithRequestState, Lt as getCurrentAuthContext, Mt as defineRequestState, Nt as getCurrentRequestState, Ot as runWithAdapter, Pt as getRequestStateAsyncLocalStorage, Rt as getCurrentPaymentContextAsyncLocalStorage, jt as RequestStateWeakMap, kt as runWithTransaction, zt as runWithEndpointContext } from "../index-CtOgkCz5.mjs";
1
+ import { At as RequestState, Dt as getCurrentDBAdapterAsyncLocalStorage, Et as getCurrentAdapter, Ft as hasRequestState, It as runWithRequestState, Lt as getCurrentAuthContext, Mt as defineRequestState, Nt as getCurrentRequestState, Ot as runWithAdapter, Pt as getRequestStateAsyncLocalStorage, Rt as getCurrentPaymentContextAsyncLocalStorage, jt as RequestStateWeakMap, kt as runWithTransaction, zt as runWithEndpointContext } from "../index-BTBqeO2-.mjs";
2
2
  export { RequestState, RequestStateWeakMap, defineRequestState, getCurrentAdapter, getCurrentAuthContext, getCurrentDBAdapterAsyncLocalStorage, getCurrentPaymentContextAsyncLocalStorage, getCurrentRequestState, getRequestStateAsyncLocalStorage, hasRequestState, runWithAdapter, runWithEndpointContext, runWithRequestState, runWithTransaction };
@@ -1,4 +1,4 @@
1
- import { a as defineRequestState, c as hasRequestState, d as getCurrentPaymentContextAsyncLocalStorage, f as runWithEndpointContext, i as runWithTransaction, l as runWithRequestState, n as getCurrentDBAdapterAsyncLocalStorage, o as getCurrentRequestState, r as runWithAdapter, s as getRequestStateAsyncLocalStorage, t as getCurrentAdapter, u as getCurrentAuthContext } from "../context-_erD9NsC.mjs";
1
+ import { a as defineRequestState, c as hasRequestState, d as getCurrentPaymentContextAsyncLocalStorage, f as runWithEndpointContext, i as runWithTransaction, l as runWithRequestState, n as getCurrentDBAdapterAsyncLocalStorage, o as getCurrentRequestState, r as runWithAdapter, s as getRequestStateAsyncLocalStorage, t as getCurrentAdapter, u as getCurrentAuthContext } from "../context-COLduJme.mjs";
2
2
  import "../async_hooks-D8vqDJIk.mjs";
3
3
 
4
4
  export { defineRequestState, getCurrentAdapter, getCurrentAuthContext, getCurrentDBAdapterAsyncLocalStorage, getCurrentPaymentContextAsyncLocalStorage, getCurrentRequestState, getRequestStateAsyncLocalStorage, hasRequestState, runWithAdapter, runWithEndpointContext, runWithRequestState, runWithTransaction };
@@ -1,4 +1,4 @@
1
- import { t as getAsyncLocalStorage } from "./async_hooks-D8vqDJIk.mjs";
1
+ import { t as getAsyncLocalStorage$1 } from "./async_hooks-D8vqDJIk.mjs";
2
2
 
3
3
  //#region src/hooks/async_hooks/pure.ts
4
4
  /**
@@ -24,7 +24,7 @@ const AsyncLocalStoragePromise = Promise.resolve().then(() => {
24
24
  if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage;
25
25
  return AsyncLocalStoragePolyfill;
26
26
  });
27
- async function getAsyncLocalStorage$1() {
27
+ async function getAsyncLocalStorage() {
28
28
  const mod = await AsyncLocalStoragePromise;
29
29
  if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code");
30
30
  else return mod;
@@ -34,7 +34,7 @@ async function getAsyncLocalStorage$1() {
34
34
  //#region src/context/payment-context.ts
35
35
  let currentContextAsyncStorage = null;
36
36
  const ensureAsyncStorage$2 = async () => {
37
- if (!currentContextAsyncStorage) currentContextAsyncStorage = new (await (getAsyncLocalStorage$1()))();
37
+ if (!currentContextAsyncStorage) currentContextAsyncStorage = new (await (getAsyncLocalStorage()))();
38
38
  return currentContextAsyncStorage;
39
39
  };
40
40
  /**
@@ -58,7 +58,7 @@ async function runWithEndpointContext(context, fn) {
58
58
  //#region src/context/request-state.ts
59
59
  let requestStateAsyncStorage = null;
60
60
  const ensureAsyncStorage$1 = async () => {
61
- if (!requestStateAsyncStorage) requestStateAsyncStorage = new (await (getAsyncLocalStorage$1()))();
61
+ if (!requestStateAsyncStorage) requestStateAsyncStorage = new (await (getAsyncLocalStorage()))();
62
62
  return requestStateAsyncStorage;
63
63
  };
64
64
  async function getRequestStateAsyncLocalStorage() {
@@ -100,7 +100,7 @@ function defineRequestState(initFn) {
100
100
  //#region src/context/transaction.ts
101
101
  let currentAdapterAsyncStorage = null;
102
102
  const ensureAsyncStorage = async () => {
103
- if (!currentAdapterAsyncStorage) currentAdapterAsyncStorage = new (await (getAsyncLocalStorage()))();
103
+ if (!currentAdapterAsyncStorage) currentAdapterAsyncStorage = new (await (getAsyncLocalStorage$1()))();
104
104
  return currentAdapterAsyncStorage;
105
105
  };
106
106
  /**
@@ -1,2 +1,2 @@
1
- import { $t as KyselyDatabaseDialectType, Ct as initGetFieldAttributes, St as initGetFieldName, Tt as initGetDefaultFieldName, _t as discountSchema, at as getPaymentTables, bt as initGetModelName, ct as Subscription, dt as sharedDeletableSchema, ft as Product, gt as Discount, ht as priceSchema, lt as subscriptionSchema, mt as Price, ot as deepmerge, pt as productSchema, st as withApplyDefault, ut as sharedCoreSchema, vt as Customer, wt as initGetDefaultModelName, xt as initGetIdField, yt as customerSchema } from "../index-CtOgkCz5.mjs";
1
+ import { $t as KyselyDatabaseDialectType, Ct as initGetFieldAttributes, St as initGetFieldName, Tt as initGetDefaultFieldName, _t as discountSchema, at as getPaymentTables, bt as initGetModelName, ct as Subscription, dt as sharedDeletableSchema, ft as Product, gt as Discount, ht as priceSchema, lt as subscriptionSchema, mt as Price, ot as deepmerge, pt as productSchema, st as withApplyDefault, ut as sharedCoreSchema, vt as Customer, wt as initGetDefaultModelName, xt as initGetIdField, yt as customerSchema } from "../index-BTBqeO2-.mjs";
2
2
  export { Customer, Discount, KyselyDatabaseDialectType, Price, Product, Subscription, customerSchema, deepmerge, discountSchema, getPaymentTables, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, priceSchema, productSchema, sharedCoreSchema, sharedDeletableSchema, subscriptionSchema, withApplyDefault };
package/dist/db/index.mjs CHANGED
@@ -1,6 +1,147 @@
1
- import "../errors-vpD21Iku.mjs";
1
+ import { A as UsageAggregation, E as SubscriptionStatus, S as ProrationBehavior, b as PricingModel, c as BillingInterval, d as CollectionMethod, f as Currency, p as DiscountType, x as ProductType, y as PriceType } from "../errors-vpD21Iku.mjs";
2
2
  import { a as initGetFieldAttributes, c as initGetDefaultModelName, i as initGetModelName, n as deepmerge, o as initGetIdField, r as withApplyDefault, s as initGetDefaultFieldName, t as getPaymentTables } from "../get-payment-tables-0FkEj3dw.mjs";
3
3
  import "../generate-id-D3ZvbbXn.mjs";
4
- import { a as customerSchema, c as initGetFieldName, i as discountSchema, n as productSchema, o as sharedCoreSchema, r as priceSchema, s as sharedDeletableSchema, t as subscriptionSchema } from "../db-JBwMpkmd.mjs";
4
+ import z$1, { z } from "zod";
5
5
 
6
+ //#region src/db/attributes/get-field-name.ts
7
+ const initGetFieldName = ({ schema, usePlural }) => {
8
+ const getDefaultModelName = initGetDefaultModelName({
9
+ schema,
10
+ usePlural
11
+ });
12
+ const getDefaultFieldName = initGetDefaultFieldName({
13
+ schema,
14
+ usePlural
15
+ });
16
+ /**
17
+ * Get the field name which is expected to be saved in the database based on the user's schema.
18
+ *
19
+ * This function is useful if you need to save the field name to the database.
20
+ *
21
+ * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.
22
+ */
23
+ function getFieldName({ model: modelName, field: fieldName }) {
24
+ const model = getDefaultModelName(modelName);
25
+ const field = getDefaultFieldName({
26
+ model,
27
+ field: fieldName
28
+ });
29
+ return schema[model]?.fields[field]?.fieldName || field;
30
+ }
31
+ return getFieldName;
32
+ };
33
+
34
+ //#endregion
35
+ //#region src/db/schema/shared.ts
36
+ const sharedCoreSchema = z$1.object({
37
+ id: z$1.uuid("id"),
38
+ createdAt: z$1.date().default(() => /* @__PURE__ */ new Date()),
39
+ updatedAt: z$1.date().default(() => /* @__PURE__ */ new Date())
40
+ });
41
+ const sharedDeletableSchema = z$1.object({
42
+ deleted: z$1.boolean().default(false),
43
+ deletedAt: z$1.coerce.date().optional()
44
+ });
45
+
46
+ //#endregion
47
+ //#region src/db/schema/customer.ts
48
+ const customerSchema = sharedCoreSchema.extend({
49
+ phoneNumber: z$1.string().max(15),
50
+ firstName: z$1.string().max(50),
51
+ paymentMethodId: z$1.string().optional(),
52
+ lastName: z$1.string().max(50),
53
+ email: z$1.email().max(255)
54
+ });
55
+
56
+ //#endregion
57
+ //#region src/db/schema/discount.ts
58
+ const discountSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
59
+ code: z.string().max(50),
60
+ name: z.string().max(255).optional(),
61
+ description: z.string().optional(),
62
+ type: z.enum(DiscountType).default(DiscountType.PERCENTAGE),
63
+ value: z.number().positive().min(0),
64
+ currency: z.enum(Currency).optional(),
65
+ active: z.boolean().default(true),
66
+ startsAt: z.coerce.date().optional(),
67
+ endsAt: z.coerce.date().optional(),
68
+ maxUses: z.number().int().positive().optional(),
69
+ maxUsesPerCustomer: z.number().int().positive().optional(),
70
+ timesUsed: z.number().int().nonnegative().default(0),
71
+ minimumAmount: z.number().positive().optional(),
72
+ minimumAmountCurrency: z.enum(Currency).optional(),
73
+ maximumDiscountAmount: z.number().positive().optional(),
74
+ maximumDiscountAmountCurrency: z.enum(Currency).optional(),
75
+ durationInMonths: z.number().int().positive().optional(),
76
+ appliesToProductIds: z.array(z.uuid()).default([]),
77
+ appliesToPriceIds: z.array(z.uuid()).default([]),
78
+ appliesToCustomerIds: z.array(z.uuid()).default([]),
79
+ appliesToAllProducts: z.boolean().default(false),
80
+ appliesToAllPrices: z.boolean().default(false),
81
+ appliesToAllCustomers: z.boolean().default(true),
82
+ firstTimeCustomerOnly: z.boolean().default(false),
83
+ metadata: z.record(z.string(), z.union([z.string(), z.number()])).optional()
84
+ });
85
+
86
+ //#endregion
87
+ //#region src/db/schema/price.ts
88
+ const priceSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
89
+ productId: z.uuid().optional(),
90
+ unitAmount: z.number().default(0),
91
+ currency: z.enum(Currency).default(Currency.KES),
92
+ type: z.enum(PriceType).default(PriceType.ONE_TIME),
93
+ pricingModel: z.enum(PricingModel).default(PricingModel.FLAT),
94
+ billingInterval: z.enum(BillingInterval).default(BillingInterval.MONTH),
95
+ billingIntervalCount: z.number().min(1).default(1),
96
+ trialPeriodDays: z.number().min(0).default(0),
97
+ usageAggregation: z.enum(UsageAggregation).optional(),
98
+ active: z.boolean().default(true),
99
+ metadata: z.record(z.string(), z.union([z.string(), z.number()])).optional()
100
+ });
101
+
102
+ //#endregion
103
+ //#region src/db/schema/product.ts
104
+ const productSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
105
+ type: z$1.enum(ProductType),
106
+ name: z$1.string().max(255),
107
+ description: z$1.string().optional(),
108
+ images: z$1.array(z$1.string()).default([]),
109
+ defaultPriceId: z$1.uuid().optional(),
110
+ marketing_features: z$1.array(z$1.object({ name: z$1.string() })).optional(),
111
+ package_dimensions: z$1.object({
112
+ height: z$1.number(),
113
+ length: z$1.number(),
114
+ weight: z$1.number(),
115
+ width: z$1.number()
116
+ }).optional(),
117
+ shippable: z$1.boolean().optional(),
118
+ url: z$1.url().optional(),
119
+ active: z$1.boolean().default(true),
120
+ metadata: z$1.record(z$1.string(), z$1.union([z$1.string(), z$1.number()])).optional()
121
+ });
122
+
123
+ //#endregion
124
+ //#region src/db/schema/subscription.ts
125
+ const subscriptionSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
126
+ customerId: z.uuid(),
127
+ paymentMethodId: z.uuid().optional(),
128
+ discountId: z.uuid().optional(),
129
+ discountEndsAt: z.coerce.date().optional(),
130
+ status: z.enum(SubscriptionStatus).default(SubscriptionStatus.INCOMPLETE),
131
+ currentBillingPeriodStart: z.coerce.date(),
132
+ currentBillingPeriodEnd: z.coerce.date(),
133
+ currentTrialStart: z.coerce.date().optional(),
134
+ currentTrialEnd: z.coerce.date().optional(),
135
+ cancelAtPeriodEnd: z.boolean().default(false),
136
+ canceledAt: z.coerce.date().optional(),
137
+ cancelAt: z.coerce.date().optional(),
138
+ daysUntilDue: z.number().min(0).default(0),
139
+ proration: z.enum(ProrationBehavior).default(ProrationBehavior.CREATE_PRORATIONS),
140
+ collectionMethod: z.enum(CollectionMethod).default(CollectionMethod.SEND_INVOICE),
141
+ metadata: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
142
+ subscriptionStartedAt: z.coerce.date(),
143
+ subscriptionEndedAt: z.coerce.date().optional()
144
+ });
145
+
146
+ //#endregion
6
147
  export { customerSchema, deepmerge, discountSchema, getPaymentTables, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, priceSchema, productSchema, sharedCoreSchema, sharedDeletableSchema, subscriptionSchema, withApplyDefault };
@@ -1,2 +1,2 @@
1
- import { _ as isTest, a as TTY_COLORS, c as logger, d as EnvObject, f as env, g as isProduction, h as isDevelopment, i as Logger, l as shouldPublishLog, m as getEnvVar, n as LogHandlerParams, o as createLogger, p as getBooleanEnvVar, r as LogLevel, s as levels, t as InternalLogger, u as ENV, v as nodeENV, y as getColorDepth } from "../index-B_V7jOck.mjs";
1
+ import { _ as isTest, a as TTY_COLORS, c as logger, d as EnvObject, f as env, g as isProduction, h as isDevelopment, i as Logger, l as shouldPublishLog, m as getEnvVar, n as LogHandlerParams, o as createLogger, p as getBooleanEnvVar, r as LogLevel, s as levels, t as InternalLogger, u as ENV, v as nodeENV, y as getColorDepth } from "../index-CawQRXlV.mjs";
2
2
  export { ENV, EnvObject, InternalLogger, LogHandlerParams, LogLevel, Logger, TTY_COLORS, createLogger, env, getBooleanEnvVar, getColorDepth, getEnvVar, isDevelopment, isProduction, isTest, levels, logger, nodeENV, shouldPublishLog };
@@ -1,3 +1,3 @@
1
- import { a as shouldPublishLog, c as env, d as isDevelopment, f as isProduction, i as logger, l as getBooleanEnvVar, m as nodeENV, n as createLogger, o as getColorDepth, p as isTest, r as levels, s as ENV, t as TTY_COLORS, u as getEnvVar } from "../env-C7DHqPmD.mjs";
1
+ import { a as shouldPublishLog, c as env, d as isDevelopment, f as isProduction, i as logger, l as getBooleanEnvVar, m as nodeENV, n as createLogger, o as getColorDepth, p as isTest, r as levels, s as ENV, t as TTY_COLORS, u as getEnvVar } from "../env-ChlcfGdT.mjs";
2
2
 
3
3
  export { ENV, TTY_COLORS, createLogger, env, getBooleanEnvVar, getColorDepth, getEnvVar, isDevelopment, isProduction, isTest, levels, logger, nodeENV, shouldPublishLog };
@@ -1,2 +1,2 @@
1
- import { it as createProviderError, nt as PecuniaError, rt as ValidationError, tt as ApiError } from "../index-CtOgkCz5.mjs";
1
+ import { it as createProviderError, nt as PecuniaError, rt as ValidationError, tt as ApiError } from "../index-BTBqeO2-.mjs";
2
2
  export { ApiError, PecuniaError, ValidationError, createProviderError };
@@ -1,2 +1,2 @@
1
- import { t as getAsyncLocalStorage } from "../index-DOO_aiRf.mjs";
1
+ import { t as getAsyncLocalStorage } from "../index-CEwT7Oeu.mjs";
2
2
  export { getAsyncLocalStorage };
@@ -1,4 +1,3 @@
1
1
  import { t as getAsyncLocalStorage } from "../async_hooks-D8vqDJIk.mjs";
2
- import "../hooks-PXnNTy74.mjs";
3
2
 
4
3
  export { getAsyncLocalStorage };
@@ -1,4 +1,4 @@
1
- import { o as createLogger } from "./index-B_V7jOck.mjs";
1
+ import { o as createLogger } from "./index-CawQRXlV.mjs";
2
2
  import * as better_call0 from "better-call";
3
3
  import { Endpoint, EndpointContext, EndpointOptions, InputContext, Middleware, Status, StrictEndpoint } from "better-call";
4
4
  import z$1, { z } from "zod";
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { $ as WebHookEventStatus, $t as KyselyDatabaseDialectType, A as CheckoutSessionStatus, At as RequestState, B as PricingModel, Bt as ErrorDefinition, C as AdapterFactoryOptions, Ct as initGetFieldAttributes, D as AuditAction, Dt as getCurrentDBAdapterAsyncLocalStorage, E as Actor, Et as getCurrentAdapter, F as InvoiceStatus, Ft as hasRequestState, G as ScheduledTaskStatus, Gt as IndexableRegistry, H as ProrationBehavior, Ht as ErrorMap, I as LedgerEntryType, It as runWithRequestState, J as TransactionStatus, Jt as HookEndpointContext, K as ScheduledTaskType, Kt as ProviderErrorCode, L as PaymentIntentStatus, Lt as getCurrentAuthContext, M as Currency, Mt as defineRequestState, N as DiscountType, Nt as getCurrentRequestState, O as BillingInterval, Ot as runWithAdapter, P as ERROR_REGISTRY, Pt as getRequestStateAsyncLocalStorage, Q as WebHookDeliveryTrigger, Qt as createPecuniaEndpoint, R as PaymentProviders, Rt as getCurrentPaymentContextAsyncLocalStorage, S as AdapterFactoryCreator, St as initGetFieldName, T as AccountType, Tt as initGetDefaultFieldName, U as ProviderId, Ut as ErrorResponse, V as ProductType, Vt as ErrorDefinitionResponse, W as ScheduleStatus, Wt as ErrorType, X as UsageAction, Xt as PecuniaEndpoint, Y as TransactionType, Yt as PecuniaPlugin, Z as UsageAggregation, Zt as PecuniaMiddleware, _ as ProviderAdapter, _t as discountSchema, a as useMiddleware, an as DBPrimitive, at as getPaymentTables, b as AdapterFactory, bt as initGetModelName, c as SenlyContext, cn as ModelNames, ct as Subscription, d as DBAdapterDebugLogOption, dn as Primitive, dt as sharedDeletableSchema, en as Awaitable, et as statusCodes, f as DBAdapterFactoryConfig, fn as StandardSchemaV1, ft as Product, g as InternalAdapter, gt as Discount, h as DBTransactionAdapter, ht as priceSchema, i as optionsMiddleware, in as DBFieldType, it as createProviderError, j as CollectionMethod, jt as RequestStateWeakMap, k as CheckoutSessionMode, kt as runWithTransaction, l as CustomAdapter, ln as PecuniaDBSchema, lt as subscriptionSchema, m as DBAdapterSchemaCreation, mt as Price, n as createPaymentEndpoint, nn as DBFieldAttribute, nt as PecuniaError, o as GenericEndpointContext, on as LiteralString, ot as deepmerge, p as DBAdapterInstance, pt as productSchema, q as SubscriptionStatus, qt as PecuniaOptions, r as createPecuniaMiddleware, rn as DBFieldAttributeConfig, rt as ValidationError, s as PecuniaContext, sn as LiteralUnion, st as withApplyDefault, t as PaymentMiddleware, tn as BaseModelNames, tt as ApiError, u as DBAdapter, un as Prettify, ut as sharedCoreSchema, v as RequiredWhere, vt as Customer, w as createAdapterFactory, wt as initGetDefaultModelName, x as AdapterFactoryConfig, xt as initGetIdField, y as Where, yt as customerSchema, z as PriceType, zt as runWithEndpointContext } from "./index-CtOgkCz5.mjs";
2
- import { _ as isTest, a as TTY_COLORS, c as logger, d as EnvObject, f as env, g as isProduction, h as isDevelopment, i as Logger, l as shouldPublishLog, m as getEnvVar, n as LogHandlerParams, o as createLogger, p as getBooleanEnvVar, r as LogLevel, s as levels, t as InternalLogger, u as ENV, v as nodeENV, y as getColorDepth } from "./index-B_V7jOck.mjs";
3
- import { t as getAsyncLocalStorage } from "./index-DOO_aiRf.mjs";
4
- import { n as safeJSONParse, r as generateId, t as capitalizeFirstLetter } from "./index-BNj-TC2H.mjs";
1
+ import { $ as WebHookEventStatus, $t as KyselyDatabaseDialectType, A as CheckoutSessionStatus, At as RequestState, B as PricingModel, Bt as ErrorDefinition, C as AdapterFactoryOptions, Ct as initGetFieldAttributes, D as AuditAction, Dt as getCurrentDBAdapterAsyncLocalStorage, E as Actor, Et as getCurrentAdapter, F as InvoiceStatus, Ft as hasRequestState, G as ScheduledTaskStatus, Gt as IndexableRegistry, H as ProrationBehavior, Ht as ErrorMap, I as LedgerEntryType, It as runWithRequestState, J as TransactionStatus, Jt as HookEndpointContext, K as ScheduledTaskType, Kt as ProviderErrorCode, L as PaymentIntentStatus, Lt as getCurrentAuthContext, M as Currency, Mt as defineRequestState, N as DiscountType, Nt as getCurrentRequestState, O as BillingInterval, Ot as runWithAdapter, P as ERROR_REGISTRY, Pt as getRequestStateAsyncLocalStorage, Q as WebHookDeliveryTrigger, Qt as createPecuniaEndpoint, R as PaymentProviders, Rt as getCurrentPaymentContextAsyncLocalStorage, S as AdapterFactoryCreator, St as initGetFieldName, T as AccountType, Tt as initGetDefaultFieldName, U as ProviderId, Ut as ErrorResponse, V as ProductType, Vt as ErrorDefinitionResponse, W as ScheduleStatus, Wt as ErrorType, X as UsageAction, Xt as PecuniaEndpoint, Y as TransactionType, Yt as PecuniaPlugin, Z as UsageAggregation, Zt as PecuniaMiddleware, _ as ProviderAdapter, _t as discountSchema, a as useMiddleware, an as DBPrimitive, at as getPaymentTables, b as AdapterFactory, bt as initGetModelName, c as SenlyContext, cn as ModelNames, ct as Subscription, d as DBAdapterDebugLogOption, dn as Primitive, dt as sharedDeletableSchema, en as Awaitable, et as statusCodes, f as DBAdapterFactoryConfig, fn as StandardSchemaV1, ft as Product, g as InternalAdapter, gt as Discount, h as DBTransactionAdapter, ht as priceSchema, i as optionsMiddleware, in as DBFieldType, it as createProviderError, j as CollectionMethod, jt as RequestStateWeakMap, k as CheckoutSessionMode, kt as runWithTransaction, l as CustomAdapter, ln as PecuniaDBSchema, lt as subscriptionSchema, m as DBAdapterSchemaCreation, mt as Price, n as createPaymentEndpoint, nn as DBFieldAttribute, nt as PecuniaError, o as GenericEndpointContext, on as LiteralString, ot as deepmerge, p as DBAdapterInstance, pt as productSchema, q as SubscriptionStatus, qt as PecuniaOptions, r as createPecuniaMiddleware, rn as DBFieldAttributeConfig, rt as ValidationError, s as PecuniaContext, sn as LiteralUnion, st as withApplyDefault, t as PaymentMiddleware, tn as BaseModelNames, tt as ApiError, u as DBAdapter, un as Prettify, ut as sharedCoreSchema, v as RequiredWhere, vt as Customer, w as createAdapterFactory, wt as initGetDefaultModelName, x as AdapterFactoryConfig, xt as initGetIdField, y as Where, yt as customerSchema, z as PriceType, zt as runWithEndpointContext } from "./index-BTBqeO2-.mjs";
2
+ import { _ as isTest, a as TTY_COLORS, c as logger, d as EnvObject, f as env, g as isProduction, h as isDevelopment, i as Logger, l as shouldPublishLog, m as getEnvVar, n as LogHandlerParams, o as createLogger, p as getBooleanEnvVar, r as LogLevel, s as levels, t as InternalLogger, u as ENV, v as nodeENV, y as getColorDepth } from "./index-CawQRXlV.mjs";
3
+ import { t as getAsyncLocalStorage } from "./index-CEwT7Oeu.mjs";
4
+ import { n as safeJSONParse, r as generateId, t as capitalizeFirstLetter } from "./index-DYRZgwpi.mjs";
5
5
  export { AccountType, Actor, AdapterFactory, AdapterFactoryConfig, AdapterFactoryCreator, AdapterFactoryOptions, ApiError, AuditAction, Awaitable, BaseModelNames, BillingInterval, CheckoutSessionMode, CheckoutSessionStatus, CollectionMethod, Currency, CustomAdapter, Customer, DBAdapter, DBAdapterDebugLogOption, DBAdapterFactoryConfig, DBAdapterInstance, DBAdapterSchemaCreation, DBFieldAttribute, DBFieldAttributeConfig, DBFieldType, DBPrimitive, DBTransactionAdapter, Discount, DiscountType, ENV, ERROR_REGISTRY, EnvObject, ErrorDefinition, ErrorDefinitionResponse, ErrorMap, ErrorResponse, ErrorType, GenericEndpointContext, HookEndpointContext, IndexableRegistry, InternalAdapter, InternalLogger, InvoiceStatus, KyselyDatabaseDialectType, LedgerEntryType, LiteralString, LiteralUnion, LogHandlerParams, LogLevel, Logger, ModelNames, PaymentIntentStatus, PaymentMiddleware, PaymentProviders, PecuniaContext, PecuniaDBSchema, PecuniaEndpoint, PecuniaError, PecuniaMiddleware, PecuniaOptions, PecuniaPlugin, Prettify, Price, PriceType, PricingModel, Primitive, Product, ProductType, ProrationBehavior, ProviderAdapter, ProviderErrorCode, ProviderId, RequestState, RequestStateWeakMap, RequiredWhere, ScheduleStatus, ScheduledTaskStatus, ScheduledTaskType, SenlyContext, StandardSchemaV1, Subscription, SubscriptionStatus, TTY_COLORS, TransactionStatus, TransactionType, UsageAction, UsageAggregation, ValidationError, WebHookDeliveryTrigger, WebHookEventStatus, Where, capitalizeFirstLetter, createAdapterFactory, createLogger, createPaymentEndpoint, createPecuniaEndpoint, createPecuniaMiddleware, createProviderError, customerSchema, deepmerge, defineRequestState, discountSchema, env, generateId, getAsyncLocalStorage, getBooleanEnvVar, getColorDepth, getCurrentAdapter, getCurrentAuthContext, getCurrentDBAdapterAsyncLocalStorage, getCurrentPaymentContextAsyncLocalStorage, getCurrentRequestState, getEnvVar, getPaymentTables, getRequestStateAsyncLocalStorage, hasRequestState, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, isDevelopment, isProduction, isTest, levels, logger, nodeENV, optionsMiddleware, priceSchema, productSchema, runWithAdapter, runWithEndpointContext, runWithRequestState, runWithTransaction, safeJSONParse, sharedCoreSchema, sharedDeletableSchema, shouldPublishLog, statusCodes, subscriptionSchema, useMiddleware, withApplyDefault };
package/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
- import { a as defineRequestState, c as hasRequestState, d as getCurrentPaymentContextAsyncLocalStorage, f as runWithEndpointContext, i as runWithTransaction, l as runWithRequestState, n as getCurrentDBAdapterAsyncLocalStorage, o as getCurrentRequestState, r as runWithAdapter, s as getRequestStateAsyncLocalStorage, t as getCurrentAdapter, u as getCurrentAuthContext } from "./context-_erD9NsC.mjs";
1
+ import { a as defineRequestState, c as hasRequestState, d as getCurrentPaymentContextAsyncLocalStorage, f as runWithEndpointContext, i as runWithTransaction, l as runWithRequestState, n as getCurrentDBAdapterAsyncLocalStorage, o as getCurrentRequestState, r as runWithAdapter, s as getRequestStateAsyncLocalStorage, t as getCurrentAdapter, u as getCurrentAuthContext } from "./context-COLduJme.mjs";
2
2
  import { t as getAsyncLocalStorage } from "./async_hooks-D8vqDJIk.mjs";
3
- import { i as useMiddleware, n as createPecuniaMiddleware, r as optionsMiddleware, t as createPaymentEndpoint } from "./api-Dnub-EIf.mjs";
3
+ import { i as useMiddleware, n as createPecuniaMiddleware, r as optionsMiddleware, t as createPaymentEndpoint } from "./api-BlJV5ZQo.mjs";
4
4
  import { A as UsageAggregation, C as ScheduleStatus, D as TransactionStatus, E as SubscriptionStatus, M as WebHookEventStatus, N as statusCodes, O as TransactionType, P as ErrorType, S as ProrationBehavior, T as ScheduledTaskType, _ as PaymentIntentStatus, a as AccountType, b as PricingModel, c as BillingInterval, d as CollectionMethod, f as Currency, g as LedgerEntryType, h as InvoiceStatus, i as createProviderError, j as WebHookDeliveryTrigger, k as UsageAction, l as CheckoutSessionMode, m as ERROR_REGISTRY, n as PecuniaError, o as Actor, p as DiscountType, r as ValidationError, s as AuditAction, t as ApiError, u as CheckoutSessionStatus, v as PaymentProviders, w as ScheduledTaskStatus, x as ProductType, y as PriceType } from "./errors-vpD21Iku.mjs";
5
5
  import { a as initGetFieldAttributes, c as initGetDefaultModelName, i as initGetModelName, n as deepmerge, o as initGetIdField, r as withApplyDefault, s as initGetDefaultFieldName, t as getPaymentTables } from "./get-payment-tables-0FkEj3dw.mjs";
6
6
  import { t as generateId } from "./generate-id-D3ZvbbXn.mjs";
7
- import { a as customerSchema, c as initGetFieldName, i as discountSchema, n as productSchema, o as sharedCoreSchema, r as priceSchema, s as sharedDeletableSchema, t as subscriptionSchema } from "./db-JBwMpkmd.mjs";
8
- import { a as shouldPublishLog, c as env, d as isDevelopment, f as isProduction, i as logger, l as getBooleanEnvVar, m as nodeENV, n as createLogger, o as getColorDepth, p as isTest, r as levels, s as ENV, t as TTY_COLORS, u as getEnvVar } from "./env-C7DHqPmD.mjs";
9
- import "./hooks-PXnNTy74.mjs";
10
- import { n as safeJSONParse, t as capitalizeFirstLetter } from "./utils-BNmlJWNJ.mjs";
11
- import { n as createAdapterFactory, t as createPecuniaEndpoint } from "./types-B0U9sZ8x.mjs";
7
+ import { customerSchema, discountSchema, initGetFieldName, priceSchema, productSchema, sharedCoreSchema, sharedDeletableSchema, subscriptionSchema } from "./db/index.mjs";
8
+ import { a as shouldPublishLog, c as env, d as isDevelopment, f as isProduction, i as logger, l as getBooleanEnvVar, m as nodeENV, n as createLogger, o as getColorDepth, p as isTest, r as levels, s as ENV, t as TTY_COLORS, u as getEnvVar } from "./env-ChlcfGdT.mjs";
9
+ import "./hooks/index.mjs";
10
+ import { n as safeJSONParse, t as capitalizeFirstLetter } from "./utils-BtfYqMRX.mjs";
11
+ import { createAdapterFactory, createPecuniaEndpoint } from "./types/index.mjs";
12
12
 
13
13
  export { AccountType, Actor, ApiError, AuditAction, BillingInterval, CheckoutSessionMode, CheckoutSessionStatus, CollectionMethod, Currency, DiscountType, ENV, ERROR_REGISTRY, ErrorType, InvoiceStatus, LedgerEntryType, PaymentIntentStatus, PaymentProviders, PecuniaError, PriceType, PricingModel, ProductType, ProrationBehavior, ScheduleStatus, ScheduledTaskStatus, ScheduledTaskType, SubscriptionStatus, TTY_COLORS, TransactionStatus, TransactionType, UsageAction, UsageAggregation, ValidationError, WebHookDeliveryTrigger, WebHookEventStatus, capitalizeFirstLetter, createAdapterFactory, createLogger, createPaymentEndpoint, createPecuniaEndpoint, createPecuniaMiddleware, createProviderError, customerSchema, deepmerge, defineRequestState, discountSchema, env, generateId, getAsyncLocalStorage, getBooleanEnvVar, getColorDepth, getCurrentAdapter, getCurrentAuthContext, getCurrentDBAdapterAsyncLocalStorage, getCurrentPaymentContextAsyncLocalStorage, getCurrentRequestState, getEnvVar, getPaymentTables, getRequestStateAsyncLocalStorage, hasRequestState, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, isDevelopment, isProduction, isTest, levels, logger, nodeENV, optionsMiddleware, priceSchema, productSchema, runWithAdapter, runWithEndpointContext, runWithRequestState, runWithTransaction, safeJSONParse, sharedCoreSchema, sharedDeletableSchema, shouldPublishLog, statusCodes, subscriptionSchema, useMiddleware, withApplyDefault };
@@ -1,2 +1,2 @@
1
- import { Bt as ErrorDefinition, C as AdapterFactoryOptions, Gt as IndexableRegistry, Ht as ErrorMap, Jt as HookEndpointContext, Kt as ProviderErrorCode, Qt as createPecuniaEndpoint, S as AdapterFactoryCreator, Ut as ErrorResponse, Vt as ErrorDefinitionResponse, Wt as ErrorType, Xt as PecuniaEndpoint, Yt as PecuniaPlugin, Zt as PecuniaMiddleware, _ as ProviderAdapter, an as DBPrimitive, b as AdapterFactory, c as SenlyContext, cn as ModelNames, d as DBAdapterDebugLogOption, dn as Primitive, en as Awaitable, f as DBAdapterFactoryConfig, fn as StandardSchemaV1, g as InternalAdapter, h as DBTransactionAdapter, in as DBFieldType, l as CustomAdapter, ln as PecuniaDBSchema, m as DBAdapterSchemaCreation, nn as DBFieldAttribute, o as GenericEndpointContext, on as LiteralString, p as DBAdapterInstance, qt as PecuniaOptions, rn as DBFieldAttributeConfig, s as PecuniaContext, sn as LiteralUnion, tn as BaseModelNames, u as DBAdapter, un as Prettify, v as RequiredWhere, w as createAdapterFactory, x as AdapterFactoryConfig, y as Where } from "../index-CtOgkCz5.mjs";
1
+ import { Bt as ErrorDefinition, C as AdapterFactoryOptions, Gt as IndexableRegistry, Ht as ErrorMap, Jt as HookEndpointContext, Kt as ProviderErrorCode, Qt as createPecuniaEndpoint, S as AdapterFactoryCreator, Ut as ErrorResponse, Vt as ErrorDefinitionResponse, Wt as ErrorType, Xt as PecuniaEndpoint, Yt as PecuniaPlugin, Zt as PecuniaMiddleware, _ as ProviderAdapter, an as DBPrimitive, b as AdapterFactory, c as SenlyContext, cn as ModelNames, d as DBAdapterDebugLogOption, dn as Primitive, en as Awaitable, f as DBAdapterFactoryConfig, fn as StandardSchemaV1, g as InternalAdapter, h as DBTransactionAdapter, in as DBFieldType, l as CustomAdapter, ln as PecuniaDBSchema, m as DBAdapterSchemaCreation, nn as DBFieldAttribute, o as GenericEndpointContext, on as LiteralString, p as DBAdapterInstance, qt as PecuniaOptions, rn as DBFieldAttributeConfig, s as PecuniaContext, sn as LiteralUnion, tn as BaseModelNames, u as DBAdapter, un as Prettify, v as RequiredWhere, w as createAdapterFactory, x as AdapterFactoryConfig, y as Where } from "../index-BTBqeO2-.mjs";
2
2
  export { AdapterFactory, AdapterFactoryConfig, AdapterFactoryCreator, AdapterFactoryOptions, Awaitable, BaseModelNames, CustomAdapter, DBAdapter, DBAdapterDebugLogOption, DBAdapterFactoryConfig, DBAdapterInstance, DBAdapterSchemaCreation, DBFieldAttribute, DBFieldAttributeConfig, DBFieldType, DBPrimitive, DBTransactionAdapter, ErrorDefinition, ErrorDefinitionResponse, ErrorMap, ErrorResponse, ErrorType, GenericEndpointContext, HookEndpointContext, IndexableRegistry, InternalAdapter, LiteralString, LiteralUnion, ModelNames, PecuniaContext, PecuniaDBSchema, PecuniaEndpoint, PecuniaMiddleware, PecuniaOptions, PecuniaPlugin, Prettify, Primitive, ProviderAdapter, ProviderErrorCode, RequiredWhere, SenlyContext, StandardSchemaV1, Where, createAdapterFactory, createPecuniaEndpoint };
@@ -1,11 +1,323 @@
1
- import "../context-_erD9NsC.mjs";
1
+ import { f as runWithEndpointContext } from "../context-COLduJme.mjs";
2
2
  import "../async_hooks-D8vqDJIk.mjs";
3
- import "../api-Dnub-EIf.mjs";
4
- import { P as ErrorType } from "../errors-vpD21Iku.mjs";
5
- import "../get-payment-tables-0FkEj3dw.mjs";
3
+ import { i as useMiddleware } from "../api-BlJV5ZQo.mjs";
4
+ import { P as ErrorType, n as PecuniaError } from "../errors-vpD21Iku.mjs";
5
+ import { a as initGetFieldAttributes, c as initGetDefaultModelName, i as initGetModelName, o as initGetIdField, r as withApplyDefault, s as initGetDefaultFieldName, t as getPaymentTables } from "../get-payment-tables-0FkEj3dw.mjs";
6
6
  import "../generate-id-D3ZvbbXn.mjs";
7
- import "../env-C7DHqPmD.mjs";
8
- import "../utils-BNmlJWNJ.mjs";
9
- import { n as createAdapterFactory, t as createPecuniaEndpoint } from "../types-B0U9sZ8x.mjs";
7
+ import "../env-ChlcfGdT.mjs";
8
+ import { n as safeJSONParse } from "../utils-BtfYqMRX.mjs";
9
+ import { createEndpoint } from "better-call";
10
10
 
11
+ //#region src/types/db/adapter/factory/index.ts
12
+ const createAsIsTransaction = (adapter) => (fn) => fn(adapter);
13
+ const createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => {
14
+ const config = {
15
+ ...cfg,
16
+ supportsBooleans: cfg.supportsBooleans ?? true,
17
+ supportsDates: cfg.supportsDates ?? true,
18
+ supportsJSON: cfg.supportsJSON ?? false,
19
+ adapterName: cfg.adapterName ?? cfg.adapterId,
20
+ supportsNumericIds: cfg.supportsNumericIds ?? true,
21
+ supportsUUIDs: cfg.supportsUUIDs ?? false,
22
+ supportsArrays: cfg.supportsArrays ?? false,
23
+ transaction: cfg.transaction ?? false,
24
+ disableTransformInput: cfg.disableTransformInput ?? false,
25
+ disableTransformOutput: cfg.disableTransformOutput ?? false
26
+ };
27
+ const schema = getPaymentTables(options);
28
+ const debugLog = (..._args) => {};
29
+ const getDefaultModelName = initGetDefaultModelName({
30
+ usePlural: config.usePlural,
31
+ schema
32
+ });
33
+ const getDefaultFieldName = initGetDefaultFieldName({
34
+ usePlural: config.usePlural,
35
+ schema
36
+ });
37
+ const getModelName = initGetModelName({
38
+ usePlural: config.usePlural,
39
+ schema
40
+ });
41
+ const getFieldName = initGetDefaultFieldName({
42
+ schema,
43
+ usePlural: config.usePlural
44
+ });
45
+ const idField = initGetIdField();
46
+ const getFieldAttributes = initGetFieldAttributes({
47
+ schema,
48
+ options,
49
+ usePlural: config.usePlural,
50
+ disableIdGeneration: config.disableIdGeneration,
51
+ customIdGenerator: config.customIdGenerator
52
+ });
53
+ const transformInput = async (data, defaultModelName, action) => {
54
+ const transformedData = {};
55
+ const fields = schema[defaultModelName].fields;
56
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
57
+ fields.id = idField();
58
+ for (const field in fields) {
59
+ let value = data[field];
60
+ const fieldAttributes = fields[field];
61
+ const newFieldName = newMappedKeys[field] || fields[field].fieldName || field;
62
+ if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue;
63
+ let newValue = withApplyDefault(value, fieldAttributes, action);
64
+ if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue);
65
+ if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue);
66
+ else if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue);
67
+ else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString();
68
+ else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0;
69
+ if (config.customTransformInput) newValue = config.customTransformInput({
70
+ data: newValue,
71
+ action,
72
+ field: newFieldName,
73
+ fieldAttributes,
74
+ model: getModelName(defaultModelName),
75
+ schema,
76
+ options
77
+ });
78
+ if (newValue !== void 0) transformedData[newFieldName] = newValue;
79
+ }
80
+ return transformedData;
81
+ };
82
+ const transformOutput = async (data, unsafe_model, select = []) => {
83
+ const transformSingleOutput = async (data$1, unsafe_model$1, select$1 = []) => {
84
+ if (!data$1) return null;
85
+ const newMappedKeys = config.mapKeysTransformOutput ?? {};
86
+ const transformedData = {};
87
+ const tableSchema = schema[getDefaultModelName(unsafe_model$1)].fields;
88
+ for (const key in tableSchema) {
89
+ if (select$1.length && !select$1.includes(key)) continue;
90
+ const field = tableSchema[key];
91
+ if (!field) continue;
92
+ const originalKey = field.fieldName || key;
93
+ let newValue = data$1[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey];
94
+ if (field.transform?.output) newValue = await field.transform.output(newValue);
95
+ const newFieldName = newMappedKeys[key] || key;
96
+ if (originalKey === "id" || field.references?.field === "id") {
97
+ if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue);
98
+ } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue);
99
+ else if (config.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue);
100
+ else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue);
101
+ else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1;
102
+ if (config.customTransformOutput) newValue = config.customTransformOutput({
103
+ data: newValue,
104
+ field: newFieldName,
105
+ fieldAttributes: field,
106
+ select: select$1,
107
+ model: getModelName(unsafe_model$1),
108
+ schema,
109
+ options
110
+ });
111
+ transformedData[newFieldName] = newValue;
112
+ }
113
+ return transformedData;
114
+ };
115
+ return await transformSingleOutput(data, unsafe_model, select);
116
+ };
117
+ const transformWhereClause = ({ model, where, action }) => {
118
+ if (!where) return void 0;
119
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
120
+ return where.map((w) => {
121
+ const { field: unsafe_field, value, operator = "eq", connector = "AND" } = w;
122
+ if (operator === "in" && !Array.isArray(value)) throw new PecuniaError("Value must be an array");
123
+ const defaultModelName = getDefaultModelName(model);
124
+ const defaultFieldName = getDefaultFieldName({
125
+ field: unsafe_field,
126
+ model
127
+ });
128
+ const fieldName = newMappedKeys[defaultFieldName] || getFieldName({
129
+ field: defaultFieldName,
130
+ model: defaultModelName
131
+ });
132
+ const fieldAttr = getFieldAttributes({
133
+ field: defaultFieldName,
134
+ model: defaultModelName
135
+ });
136
+ let newValue = value;
137
+ if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString();
138
+ if (fieldAttr.type === "boolean" && typeof value === "boolean" && !config.supportsBooleans) newValue = value ? 1 : 0;
139
+ if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) newValue = JSON.stringify(value);
140
+ if (config.customTransformInput) newValue = config.customTransformInput({
141
+ data: newValue,
142
+ fieldAttributes: fieldAttr,
143
+ field: fieldName,
144
+ model: getModelName(model),
145
+ schema,
146
+ options,
147
+ action
148
+ });
149
+ return {
150
+ operator,
151
+ connector,
152
+ field: fieldName,
153
+ value: newValue
154
+ };
155
+ });
156
+ };
157
+ const adapterInstance = customAdapter({
158
+ options,
159
+ schema,
160
+ debugLog,
161
+ getFieldName,
162
+ getModelName,
163
+ getDefaultModelName,
164
+ getDefaultFieldName,
165
+ getFieldAttributes,
166
+ transformInput,
167
+ transformOutput,
168
+ transformWhereClause
169
+ });
170
+ let lazyLoadTransaction = null;
171
+ const adapter = {
172
+ transaction: async (cb) => {
173
+ if (!lazyLoadTransaction) lazyLoadTransaction = config.transaction ? config.transaction : createAsIsTransaction(adapter);
174
+ return lazyLoadTransaction(cb);
175
+ },
176
+ create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => {
177
+ const model = getModelName(unsafeModel);
178
+ unsafeModel = getDefaultModelName(unsafeModel);
179
+ if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) unsafeData.id = void 0;
180
+ let data = unsafeData;
181
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create");
182
+ const res = await adapterInstance.create({
183
+ data,
184
+ model
185
+ });
186
+ let transformed = res;
187
+ if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select);
188
+ return transformed;
189
+ },
190
+ update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
191
+ unsafeModel = getDefaultModelName(unsafeModel);
192
+ const model = getModelName(unsafeModel);
193
+ const where = transformWhereClause({
194
+ model: unsafeModel,
195
+ where: unsafeWhere,
196
+ action: "update"
197
+ });
198
+ let data = unsafeData;
199
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
200
+ const res = await adapterInstance.update({
201
+ model,
202
+ where,
203
+ update: data
204
+ });
205
+ if (config.disableTransformOutput) return res;
206
+ return await transformOutput(res, unsafeModel, void 0);
207
+ },
208
+ updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
209
+ const model = getModelName(unsafeModel);
210
+ const where = transformWhereClause({
211
+ model: unsafeModel,
212
+ where: unsafeWhere,
213
+ action: "updateMany"
214
+ });
215
+ unsafeModel = getDefaultModelName(unsafeModel);
216
+ let data = unsafeData;
217
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
218
+ return await adapterInstance.updateMany({
219
+ model,
220
+ where,
221
+ update: data
222
+ });
223
+ },
224
+ findOne: async ({ model: unsafeModel, where: unsafeWhere, select }) => {
225
+ const model = getModelName(unsafeModel);
226
+ const where = transformWhereClause({
227
+ model: unsafeModel,
228
+ where: unsafeWhere,
229
+ action: "findOne"
230
+ });
231
+ unsafeModel = getDefaultModelName(unsafeModel);
232
+ const res = await adapterInstance.findOne({
233
+ model,
234
+ where,
235
+ select
236
+ });
237
+ if (config.disableTransformOutput) return res;
238
+ return await transformOutput(res, unsafeModel, select);
239
+ },
240
+ findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, sortBy, offset }) => {
241
+ const limit = unsafeLimit ?? 100;
242
+ const model = getModelName(unsafeModel);
243
+ const where = transformWhereClause({
244
+ model: unsafeModel,
245
+ where: unsafeWhere,
246
+ action: "findMany"
247
+ });
248
+ unsafeModel = getDefaultModelName(unsafeModel);
249
+ const res = await adapterInstance.findMany({
250
+ model,
251
+ where,
252
+ limit,
253
+ sortBy,
254
+ offset
255
+ });
256
+ if (config.disableTransformOutput) return res;
257
+ return await Promise.all(res.map(async (r) => {
258
+ return await transformOutput(r, unsafeModel, void 0);
259
+ }));
260
+ },
261
+ delete: async ({ model: unsafeModel, where: unsafeWhere }) => {
262
+ const model = getModelName(unsafeModel);
263
+ const where = transformWhereClause({
264
+ model: unsafeModel,
265
+ where: unsafeWhere,
266
+ action: "delete"
267
+ });
268
+ await adapterInstance.delete({
269
+ model,
270
+ where
271
+ });
272
+ },
273
+ deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => {
274
+ const model = getModelName(unsafeModel);
275
+ const where = transformWhereClause({
276
+ model: unsafeModel,
277
+ where: unsafeWhere,
278
+ action: "deleteMany"
279
+ });
280
+ return await adapterInstance.deleteMany({
281
+ model,
282
+ where
283
+ });
284
+ },
285
+ count: async ({ model: unsafeModel, where: unsafeWhere }) => {
286
+ const model = getModelName(unsafeModel);
287
+ const where = transformWhereClause({
288
+ model: unsafeModel,
289
+ where: unsafeWhere,
290
+ action: "count"
291
+ });
292
+ return await adapterInstance.count({
293
+ model,
294
+ where
295
+ });
296
+ },
297
+ options: {
298
+ adapterConfig: config,
299
+ ...adapterInstance.options ?? {}
300
+ },
301
+ id: config.adapterId
302
+ };
303
+ return adapter;
304
+ };
305
+
306
+ //#endregion
307
+ //#region src/types/middleware/index.ts
308
+ function createPecuniaEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {
309
+ const path = typeof pathOrOptions === "string" ? pathOrOptions : void 0;
310
+ const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions;
311
+ const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever;
312
+ if (path) return createEndpoint(path, {
313
+ ...options,
314
+ use: [...options?.use || [], ...useMiddleware]
315
+ }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));
316
+ return createEndpoint({
317
+ ...options,
318
+ use: [...options?.use || [], ...useMiddleware]
319
+ }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));
320
+ }
321
+
322
+ //#endregion
11
323
  export { ErrorType, createAdapterFactory, createPecuniaEndpoint };
@@ -1,2 +1,2 @@
1
- import { n as safeJSONParse, r as generateId, t as capitalizeFirstLetter } from "../index-BNj-TC2H.mjs";
1
+ import { n as safeJSONParse, r as generateId, t as capitalizeFirstLetter } from "../index-DYRZgwpi.mjs";
2
2
  export { capitalizeFirstLetter, generateId, safeJSONParse };
@@ -1,5 +1,5 @@
1
1
  import { t as generateId } from "../generate-id-D3ZvbbXn.mjs";
2
- import "../env-C7DHqPmD.mjs";
3
- import { n as safeJSONParse, t as capitalizeFirstLetter } from "../utils-BNmlJWNJ.mjs";
2
+ import "../env-ChlcfGdT.mjs";
3
+ import { n as safeJSONParse, t as capitalizeFirstLetter } from "../utils-BtfYqMRX.mjs";
4
4
 
5
5
  export { capitalizeFirstLetter, generateId, safeJSONParse };
@@ -1,4 +1,4 @@
1
- import { i as logger } from "./env-C7DHqPmD.mjs";
1
+ import { i as logger } from "./env-ChlcfGdT.mjs";
2
2
 
3
3
  //#region src/utils/json-parse.ts
4
4
  function safeJSONParse(data) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pecunia-core",
3
- "version": "0.0.0",
3
+ "version": "0.0.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.mjs",
6
6
  "module": "./dist/index.mjs",
@@ -102,23 +102,19 @@
102
102
  "coverage": "vitest run --coverage"
103
103
  },
104
104
  "devDependencies": {
105
- "@better-auth/utils": "catalog:",
106
- "@better-fetch/fetch": "catalog:",
107
- "better-call": "catalog:",
108
105
  "jose": "^6.1.0",
109
106
  "kysely": "^0.28.5",
110
107
  "nanostores": "^1.0.1",
111
- "tsdown": "catalog:"
108
+ "tsdown": "^0.19.0",
109
+ "typescript": "^5.9.3"
112
110
  },
113
111
  "dependencies": {
114
112
  "@standard-schema/spec": "^1.0.0",
113
+ "better-call": "^1.1.8",
115
114
  "uuidv7": "^1.1.0",
116
115
  "zod": "^4.1.12"
117
116
  },
118
117
  "peerDependencies": {
119
- "@better-auth/utils": "catalog:",
120
- "@better-fetch/fetch": "catalog:",
121
- "better-call": "catalog:",
122
118
  "jose": "^6.1.0",
123
119
  "kysely": "^0.28.5",
124
120
  "nanostores": "^1.0.1"
@@ -1,146 +0,0 @@
1
- import { A as UsageAggregation, E as SubscriptionStatus, S as ProrationBehavior, b as PricingModel, c as BillingInterval, d as CollectionMethod, f as Currency, p as DiscountType, x as ProductType, y as PriceType } from "./errors-vpD21Iku.mjs";
2
- import { c as initGetDefaultModelName, s as initGetDefaultFieldName } from "./get-payment-tables-0FkEj3dw.mjs";
3
- import z$1, { z } from "zod";
4
-
5
- //#region src/db/attributes/get-field-name.ts
6
- const initGetFieldName = ({ schema, usePlural }) => {
7
- const getDefaultModelName = initGetDefaultModelName({
8
- schema,
9
- usePlural
10
- });
11
- const getDefaultFieldName = initGetDefaultFieldName({
12
- schema,
13
- usePlural
14
- });
15
- /**
16
- * Get the field name which is expected to be saved in the database based on the user's schema.
17
- *
18
- * This function is useful if you need to save the field name to the database.
19
- *
20
- * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.
21
- */
22
- function getFieldName({ model: modelName, field: fieldName }) {
23
- const model = getDefaultModelName(modelName);
24
- const field = getDefaultFieldName({
25
- model,
26
- field: fieldName
27
- });
28
- return schema[model]?.fields[field]?.fieldName || field;
29
- }
30
- return getFieldName;
31
- };
32
-
33
- //#endregion
34
- //#region src/db/schema/shared.ts
35
- const sharedCoreSchema = z$1.object({
36
- id: z$1.uuid("id"),
37
- createdAt: z$1.date().default(() => /* @__PURE__ */ new Date()),
38
- updatedAt: z$1.date().default(() => /* @__PURE__ */ new Date())
39
- });
40
- const sharedDeletableSchema = z$1.object({
41
- deleted: z$1.boolean().default(false),
42
- deletedAt: z$1.coerce.date().optional()
43
- });
44
-
45
- //#endregion
46
- //#region src/db/schema/customer.ts
47
- const customerSchema = sharedCoreSchema.extend({
48
- phoneNumber: z$1.string().max(15),
49
- firstName: z$1.string().max(50),
50
- paymentMethodId: z$1.string().optional(),
51
- lastName: z$1.string().max(50),
52
- email: z$1.email().max(255)
53
- });
54
-
55
- //#endregion
56
- //#region src/db/schema/discount.ts
57
- const discountSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
58
- code: z.string().max(50),
59
- name: z.string().max(255).optional(),
60
- description: z.string().optional(),
61
- type: z.enum(DiscountType).default(DiscountType.PERCENTAGE),
62
- value: z.number().positive().min(0),
63
- currency: z.enum(Currency).optional(),
64
- active: z.boolean().default(true),
65
- startsAt: z.coerce.date().optional(),
66
- endsAt: z.coerce.date().optional(),
67
- maxUses: z.number().int().positive().optional(),
68
- maxUsesPerCustomer: z.number().int().positive().optional(),
69
- timesUsed: z.number().int().nonnegative().default(0),
70
- minimumAmount: z.number().positive().optional(),
71
- minimumAmountCurrency: z.enum(Currency).optional(),
72
- maximumDiscountAmount: z.number().positive().optional(),
73
- maximumDiscountAmountCurrency: z.enum(Currency).optional(),
74
- durationInMonths: z.number().int().positive().optional(),
75
- appliesToProductIds: z.array(z.uuid()).default([]),
76
- appliesToPriceIds: z.array(z.uuid()).default([]),
77
- appliesToCustomerIds: z.array(z.uuid()).default([]),
78
- appliesToAllProducts: z.boolean().default(false),
79
- appliesToAllPrices: z.boolean().default(false),
80
- appliesToAllCustomers: z.boolean().default(true),
81
- firstTimeCustomerOnly: z.boolean().default(false),
82
- metadata: z.record(z.string(), z.union([z.string(), z.number()])).optional()
83
- });
84
-
85
- //#endregion
86
- //#region src/db/schema/price.ts
87
- const priceSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
88
- productId: z.uuid().optional(),
89
- unitAmount: z.number().default(0),
90
- currency: z.enum(Currency).default(Currency.KES),
91
- type: z.enum(PriceType).default(PriceType.ONE_TIME),
92
- pricingModel: z.enum(PricingModel).default(PricingModel.FLAT),
93
- billingInterval: z.enum(BillingInterval).default(BillingInterval.MONTH),
94
- billingIntervalCount: z.number().min(1).default(1),
95
- trialPeriodDays: z.number().min(0).default(0),
96
- usageAggregation: z.enum(UsageAggregation).optional(),
97
- active: z.boolean().default(true),
98
- metadata: z.record(z.string(), z.union([z.string(), z.number()])).optional()
99
- });
100
-
101
- //#endregion
102
- //#region src/db/schema/product.ts
103
- const productSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
104
- type: z$1.enum(ProductType),
105
- name: z$1.string().max(255),
106
- description: z$1.string().optional(),
107
- images: z$1.array(z$1.string()).default([]),
108
- defaultPriceId: z$1.uuid().optional(),
109
- marketing_features: z$1.array(z$1.object({ name: z$1.string() })).optional(),
110
- package_dimensions: z$1.object({
111
- height: z$1.number(),
112
- length: z$1.number(),
113
- weight: z$1.number(),
114
- width: z$1.number()
115
- }).optional(),
116
- shippable: z$1.boolean().optional(),
117
- url: z$1.url().optional(),
118
- active: z$1.boolean().default(true),
119
- metadata: z$1.record(z$1.string(), z$1.union([z$1.string(), z$1.number()])).optional()
120
- });
121
-
122
- //#endregion
123
- //#region src/db/schema/subscription.ts
124
- const subscriptionSchema = sharedCoreSchema.extend(sharedDeletableSchema.shape).extend({
125
- customerId: z.uuid(),
126
- paymentMethodId: z.uuid().optional(),
127
- discountId: z.uuid().optional(),
128
- discountEndsAt: z.coerce.date().optional(),
129
- status: z.enum(SubscriptionStatus).default(SubscriptionStatus.INCOMPLETE),
130
- currentBillingPeriodStart: z.coerce.date(),
131
- currentBillingPeriodEnd: z.coerce.date(),
132
- currentTrialStart: z.coerce.date().optional(),
133
- currentTrialEnd: z.coerce.date().optional(),
134
- cancelAtPeriodEnd: z.boolean().default(false),
135
- canceledAt: z.coerce.date().optional(),
136
- cancelAt: z.coerce.date().optional(),
137
- daysUntilDue: z.number().min(0).default(0),
138
- proration: z.enum(ProrationBehavior).default(ProrationBehavior.CREATE_PRORATIONS),
139
- collectionMethod: z.enum(CollectionMethod).default(CollectionMethod.SEND_INVOICE),
140
- metadata: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
141
- subscriptionStartedAt: z.coerce.date(),
142
- subscriptionEndedAt: z.coerce.date().optional()
143
- });
144
-
145
- //#endregion
146
- export { customerSchema as a, initGetFieldName as c, discountSchema as i, productSchema as n, sharedCoreSchema as o, priceSchema as r, sharedDeletableSchema as s, subscriptionSchema as t };
@@ -1 +0,0 @@
1
- export { };
@@ -1,320 +0,0 @@
1
- import { f as runWithEndpointContext } from "./context-_erD9NsC.mjs";
2
- import { i as useMiddleware } from "./api-Dnub-EIf.mjs";
3
- import { n as PecuniaError } from "./errors-vpD21Iku.mjs";
4
- import { a as initGetFieldAttributes, c as initGetDefaultModelName, i as initGetModelName, o as initGetIdField, r as withApplyDefault, s as initGetDefaultFieldName, t as getPaymentTables } from "./get-payment-tables-0FkEj3dw.mjs";
5
- import { n as safeJSONParse } from "./utils-BNmlJWNJ.mjs";
6
- import { createEndpoint } from "better-call";
7
-
8
- //#region src/types/db/adapter/factory/index.ts
9
- const createAsIsTransaction = (adapter) => (fn) => fn(adapter);
10
- const createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => {
11
- const config = {
12
- ...cfg,
13
- supportsBooleans: cfg.supportsBooleans ?? true,
14
- supportsDates: cfg.supportsDates ?? true,
15
- supportsJSON: cfg.supportsJSON ?? false,
16
- adapterName: cfg.adapterName ?? cfg.adapterId,
17
- supportsNumericIds: cfg.supportsNumericIds ?? true,
18
- supportsUUIDs: cfg.supportsUUIDs ?? false,
19
- supportsArrays: cfg.supportsArrays ?? false,
20
- transaction: cfg.transaction ?? false,
21
- disableTransformInput: cfg.disableTransformInput ?? false,
22
- disableTransformOutput: cfg.disableTransformOutput ?? false
23
- };
24
- const schema = getPaymentTables(options);
25
- const debugLog = (..._args) => {};
26
- const getDefaultModelName = initGetDefaultModelName({
27
- usePlural: config.usePlural,
28
- schema
29
- });
30
- const getDefaultFieldName = initGetDefaultFieldName({
31
- usePlural: config.usePlural,
32
- schema
33
- });
34
- const getModelName = initGetModelName({
35
- usePlural: config.usePlural,
36
- schema
37
- });
38
- const getFieldName = initGetDefaultFieldName({
39
- schema,
40
- usePlural: config.usePlural
41
- });
42
- const idField = initGetIdField();
43
- const getFieldAttributes = initGetFieldAttributes({
44
- schema,
45
- options,
46
- usePlural: config.usePlural,
47
- disableIdGeneration: config.disableIdGeneration,
48
- customIdGenerator: config.customIdGenerator
49
- });
50
- const transformInput = async (data, defaultModelName, action) => {
51
- const transformedData = {};
52
- const fields = schema[defaultModelName].fields;
53
- const newMappedKeys = config.mapKeysTransformInput ?? {};
54
- fields.id = idField();
55
- for (const field in fields) {
56
- let value = data[field];
57
- const fieldAttributes = fields[field];
58
- const newFieldName = newMappedKeys[field] || fields[field].fieldName || field;
59
- if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue;
60
- let newValue = withApplyDefault(value, fieldAttributes, action);
61
- if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue);
62
- if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue);
63
- else if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue);
64
- else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString();
65
- else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0;
66
- if (config.customTransformInput) newValue = config.customTransformInput({
67
- data: newValue,
68
- action,
69
- field: newFieldName,
70
- fieldAttributes,
71
- model: getModelName(defaultModelName),
72
- schema,
73
- options
74
- });
75
- if (newValue !== void 0) transformedData[newFieldName] = newValue;
76
- }
77
- return transformedData;
78
- };
79
- const transformOutput = async (data, unsafe_model, select = []) => {
80
- const transformSingleOutput = async (data$1, unsafe_model$1, select$1 = []) => {
81
- if (!data$1) return null;
82
- const newMappedKeys = config.mapKeysTransformOutput ?? {};
83
- const transformedData = {};
84
- const tableSchema = schema[getDefaultModelName(unsafe_model$1)].fields;
85
- for (const key in tableSchema) {
86
- if (select$1.length && !select$1.includes(key)) continue;
87
- const field = tableSchema[key];
88
- if (!field) continue;
89
- const originalKey = field.fieldName || key;
90
- let newValue = data$1[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey];
91
- if (field.transform?.output) newValue = await field.transform.output(newValue);
92
- const newFieldName = newMappedKeys[key] || key;
93
- if (originalKey === "id" || field.references?.field === "id") {
94
- if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue);
95
- } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue);
96
- else if (config.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue);
97
- else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue);
98
- else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1;
99
- if (config.customTransformOutput) newValue = config.customTransformOutput({
100
- data: newValue,
101
- field: newFieldName,
102
- fieldAttributes: field,
103
- select: select$1,
104
- model: getModelName(unsafe_model$1),
105
- schema,
106
- options
107
- });
108
- transformedData[newFieldName] = newValue;
109
- }
110
- return transformedData;
111
- };
112
- return await transformSingleOutput(data, unsafe_model, select);
113
- };
114
- const transformWhereClause = ({ model, where, action }) => {
115
- if (!where) return void 0;
116
- const newMappedKeys = config.mapKeysTransformInput ?? {};
117
- return where.map((w) => {
118
- const { field: unsafe_field, value, operator = "eq", connector = "AND" } = w;
119
- if (operator === "in" && !Array.isArray(value)) throw new PecuniaError("Value must be an array");
120
- const defaultModelName = getDefaultModelName(model);
121
- const defaultFieldName = getDefaultFieldName({
122
- field: unsafe_field,
123
- model
124
- });
125
- const fieldName = newMappedKeys[defaultFieldName] || getFieldName({
126
- field: defaultFieldName,
127
- model: defaultModelName
128
- });
129
- const fieldAttr = getFieldAttributes({
130
- field: defaultFieldName,
131
- model: defaultModelName
132
- });
133
- let newValue = value;
134
- if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString();
135
- if (fieldAttr.type === "boolean" && typeof value === "boolean" && !config.supportsBooleans) newValue = value ? 1 : 0;
136
- if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) newValue = JSON.stringify(value);
137
- if (config.customTransformInput) newValue = config.customTransformInput({
138
- data: newValue,
139
- fieldAttributes: fieldAttr,
140
- field: fieldName,
141
- model: getModelName(model),
142
- schema,
143
- options,
144
- action
145
- });
146
- return {
147
- operator,
148
- connector,
149
- field: fieldName,
150
- value: newValue
151
- };
152
- });
153
- };
154
- const adapterInstance = customAdapter({
155
- options,
156
- schema,
157
- debugLog,
158
- getFieldName,
159
- getModelName,
160
- getDefaultModelName,
161
- getDefaultFieldName,
162
- getFieldAttributes,
163
- transformInput,
164
- transformOutput,
165
- transformWhereClause
166
- });
167
- let lazyLoadTransaction = null;
168
- const adapter = {
169
- transaction: async (cb) => {
170
- if (!lazyLoadTransaction) lazyLoadTransaction = config.transaction ? config.transaction : createAsIsTransaction(adapter);
171
- return lazyLoadTransaction(cb);
172
- },
173
- create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => {
174
- const model = getModelName(unsafeModel);
175
- unsafeModel = getDefaultModelName(unsafeModel);
176
- if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) unsafeData.id = void 0;
177
- let data = unsafeData;
178
- if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create");
179
- const res = await adapterInstance.create({
180
- data,
181
- model
182
- });
183
- let transformed = res;
184
- if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select);
185
- return transformed;
186
- },
187
- update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
188
- unsafeModel = getDefaultModelName(unsafeModel);
189
- const model = getModelName(unsafeModel);
190
- const where = transformWhereClause({
191
- model: unsafeModel,
192
- where: unsafeWhere,
193
- action: "update"
194
- });
195
- let data = unsafeData;
196
- if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
197
- const res = await adapterInstance.update({
198
- model,
199
- where,
200
- update: data
201
- });
202
- if (config.disableTransformOutput) return res;
203
- return await transformOutput(res, unsafeModel, void 0);
204
- },
205
- updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
206
- const model = getModelName(unsafeModel);
207
- const where = transformWhereClause({
208
- model: unsafeModel,
209
- where: unsafeWhere,
210
- action: "updateMany"
211
- });
212
- unsafeModel = getDefaultModelName(unsafeModel);
213
- let data = unsafeData;
214
- if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
215
- return await adapterInstance.updateMany({
216
- model,
217
- where,
218
- update: data
219
- });
220
- },
221
- findOne: async ({ model: unsafeModel, where: unsafeWhere, select }) => {
222
- const model = getModelName(unsafeModel);
223
- const where = transformWhereClause({
224
- model: unsafeModel,
225
- where: unsafeWhere,
226
- action: "findOne"
227
- });
228
- unsafeModel = getDefaultModelName(unsafeModel);
229
- const res = await adapterInstance.findOne({
230
- model,
231
- where,
232
- select
233
- });
234
- if (config.disableTransformOutput) return res;
235
- return await transformOutput(res, unsafeModel, select);
236
- },
237
- findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, sortBy, offset }) => {
238
- const limit = unsafeLimit ?? 100;
239
- const model = getModelName(unsafeModel);
240
- const where = transformWhereClause({
241
- model: unsafeModel,
242
- where: unsafeWhere,
243
- action: "findMany"
244
- });
245
- unsafeModel = getDefaultModelName(unsafeModel);
246
- const res = await adapterInstance.findMany({
247
- model,
248
- where,
249
- limit,
250
- sortBy,
251
- offset
252
- });
253
- if (config.disableTransformOutput) return res;
254
- return await Promise.all(res.map(async (r) => {
255
- return await transformOutput(r, unsafeModel, void 0);
256
- }));
257
- },
258
- delete: async ({ model: unsafeModel, where: unsafeWhere }) => {
259
- const model = getModelName(unsafeModel);
260
- const where = transformWhereClause({
261
- model: unsafeModel,
262
- where: unsafeWhere,
263
- action: "delete"
264
- });
265
- await adapterInstance.delete({
266
- model,
267
- where
268
- });
269
- },
270
- deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => {
271
- const model = getModelName(unsafeModel);
272
- const where = transformWhereClause({
273
- model: unsafeModel,
274
- where: unsafeWhere,
275
- action: "deleteMany"
276
- });
277
- return await adapterInstance.deleteMany({
278
- model,
279
- where
280
- });
281
- },
282
- count: async ({ model: unsafeModel, where: unsafeWhere }) => {
283
- const model = getModelName(unsafeModel);
284
- const where = transformWhereClause({
285
- model: unsafeModel,
286
- where: unsafeWhere,
287
- action: "count"
288
- });
289
- return await adapterInstance.count({
290
- model,
291
- where
292
- });
293
- },
294
- options: {
295
- adapterConfig: config,
296
- ...adapterInstance.options ?? {}
297
- },
298
- id: config.adapterId
299
- };
300
- return adapter;
301
- };
302
-
303
- //#endregion
304
- //#region src/types/middleware/index.ts
305
- function createPecuniaEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {
306
- const path = typeof pathOrOptions === "string" ? pathOrOptions : void 0;
307
- const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions;
308
- const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever;
309
- if (path) return createEndpoint(path, {
310
- ...options,
311
- use: [...options?.use || [], ...useMiddleware]
312
- }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));
313
- return createEndpoint({
314
- ...options,
315
- use: [...options?.use || [], ...useMiddleware]
316
- }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));
317
- }
318
-
319
- //#endregion
320
- export { createAdapterFactory as n, createPecuniaEndpoint as t };
File without changes