@donotdev/functions 0.2.2 → 0.2.3
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/README.md +1 -1
- package/lib/chunks/chunk-6NXIK35R.js +23 -0
- package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
- package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
- package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-EZKRLLSQ.js.map} +1 -1
- package/lib/chunks/chunk-F3PHE627.js +22 -0
- package/lib/chunks/chunk-F3PHE627.js.map +7 -0
- package/lib/chunks/chunk-F3WBFWPO.js +151 -0
- package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
- package/lib/chunks/chunk-G5DRV3DH.js +22 -0
- package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
- package/lib/chunks/{chunk-2A4FPYNB.js → chunk-GDIUOJMD.js} +2 -2
- package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
- package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
- package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
- package/lib/chunks/chunk-QXIOO2RL.js +22 -0
- package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
- package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-UH445BGK.js} +2 -2
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/chunk-W74UL7AY.js +22 -0
- package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
- package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-LXNVBD3G.js} +2 -2
- package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-GG5LPWXJ.js} +2 -2
- package/lib/chunks/{server-RYGEBS2B.js → server-NODQAE3F.js} +2 -2
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
- package/lib/shared/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- package/lib/shared/index.js +1 -1
- package/lib/shared/logger.d.ts +14 -14
- package/lib/shared/utils/external/subscription.d.ts +0 -8
- package/lib/shared/utils.d.ts +15 -3
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/create.d.ts +0 -8
- package/lib/supabase/crud/entityStore.d.ts +13 -0
- package/lib/supabase/crud/update.d.ts +0 -8
- package/lib/supabase/index.d.ts +1 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +3 -3
- package/package.json +9 -9
- package/src/firebase/auth/getCustomClaims.ts +2 -0
- package/src/firebase/auth/getUserAuthStatus.ts +2 -0
- package/src/firebase/auth/removeCustomClaims.ts +2 -0
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- package/src/firebase/baseFunction.ts +5 -2
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/aggregate.ts +41 -12
- package/src/firebase/crud/bulk.ts +7 -0
- package/src/firebase/crud/create.ts +21 -8
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +9 -2
- package/src/firebase/crud/list.ts +18 -8
- package/src/firebase/crud/update.ts +15 -7
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -0
- package/src/firebase/oauth/getConnections.ts +1 -1
- package/src/firebase/oauth/githubAccess.ts +3 -0
- package/src/firebase/oauth/refreshToken.ts +1 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/ai/classifyAIError.ts +18 -10
- package/src/shared/ai/createAIRoute.ts +2 -1
- package/src/shared/ai/resolveModelTier.ts +2 -1
- package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
- package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +56 -11
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/orderWebhook.ts +69 -1
- package/src/shared/billing/stripeClient.ts +2 -1
- package/src/shared/billing/stripePinned.ts +71 -0
- package/src/shared/billing/tierWebhookEvents.ts +3 -2
- package/src/shared/billing/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +3 -2
- package/src/shared/denoEnv.ts +29 -0
- package/src/shared/email/createEmailRoute.ts +2 -2
- package/src/shared/errorHandling.ts +8 -8
- package/src/shared/firebase.ts +26 -9
- package/src/shared/github.ts +15 -5
- package/src/shared/logger.ts +37 -38
- package/src/shared/schema.ts +6 -10
- package/src/shared/utils/external/date.ts +4 -4
- package/src/shared/utils/external/subscription.ts +2 -89
- package/src/shared/utils/firebaseHelpers.ts +2 -0
- package/src/shared/utils/internal/idempotency.ts +3 -0
- package/src/shared/utils/internal/monitoring.ts +6 -5
- package/src/shared/utils/internal/validation.ts +2 -0
- package/src/shared/utils/schemaValidation.ts +1 -0
- package/src/shared/utils/validation.ts +10 -20
- package/src/shared/utils.ts +12 -7
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +3 -0
- package/src/supabase/crud/create.ts +13 -9
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +1 -1
- package/src/supabase/crud/get.ts +2 -1
- package/src/supabase/crud/list.ts +23 -17
- package/src/supabase/crud/update.ts +9 -6
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +1 -0
- package/src/supabase/oauth/exchangeToken.ts +1 -0
- package/src/supabase/oauth/getConnections.ts +1 -1
- package/src/supabase/oauth/refreshToken.ts +1 -0
- package/src/supabase/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- package/src/vercel/api/billing/change-plan.ts +6 -5
- package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
- package/src/vercel/api/crud/bulk.ts +7 -2
- package/src/vercel/api/crud/create.ts +6 -3
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +5 -2
- package/src/vercel/api/crud/list.ts +6 -3
- package/src/vercel/api/crud/update.ts +6 -3
- package/src/vercel/api/oauth/check-github-access.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +5 -2
- package/src/vercel/api/oauth/grant-github-access.ts +1 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
- package/src/vercel/baseFunction.ts +5 -1
- package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
- package/lib/chunks/chunk-2IFFIUFV.js +0 -23
- package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
- package/lib/chunks/chunk-FQSQGOBN.js +0 -22
- package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
- package/lib/chunks/chunk-G4FO76EA.js +0 -22
- package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
- package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
- package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
- package/lib/chunks/chunk-M4JV2JCF.js +0 -22
- package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
- package/lib/chunks/chunk-OZX5ZG44.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-UYI56E6Q.js +0 -151
- package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
- package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
- package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
- package/lib/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-UH445BGK.js.map} +0 -0
- /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-LXNVBD3G.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
- /package/lib/chunks/{server-RYGEBS2B.js.map → server-NODQAE3F.js.map} +0 -0
|
@@ -9,11 +9,7 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import type {
|
|
13
|
-
SubscriptionStatus,
|
|
14
|
-
SubscriptionClaims,
|
|
15
|
-
} from '@donotdev/core/server';
|
|
16
|
-
import { SUBSCRIPTION_STATUS } from '@donotdev/core/server';
|
|
12
|
+
import type { SubscriptionClaims } from '@donotdev/core/server';
|
|
17
13
|
import {
|
|
18
14
|
getFirebaseAdminAuth,
|
|
19
15
|
getFirebaseAdminFirestore,
|
|
@@ -42,90 +38,6 @@ export function getTierFromPriceId(priceId: string): string {
|
|
|
42
38
|
return tierMapping[priceId] || 'free';
|
|
43
39
|
}
|
|
44
40
|
|
|
45
|
-
/**
|
|
46
|
-
* Validates subscription status and updates Firebase custom claims
|
|
47
|
-
*
|
|
48
|
-
* @version 0.1.0
|
|
49
|
-
* @since 0.0.1
|
|
50
|
-
* @author AMBROISE PARK Consulting
|
|
51
|
-
*/
|
|
52
|
-
export async function updateFirebaseUserSubscription(
|
|
53
|
-
firebaseUid: string,
|
|
54
|
-
subscription: any
|
|
55
|
-
): Promise<void> {
|
|
56
|
-
if (!firebaseUid) {
|
|
57
|
-
throw new Error('Firebase UID is required to update subscription');
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const priceId = subscription.items?.data?.[0]?.price?.id;
|
|
61
|
-
const tier = getTierFromPriceId(priceId);
|
|
62
|
-
|
|
63
|
-
// Validate status: must be a framework value OR a valid custom consumer value (non-empty string)
|
|
64
|
-
// Default to 'incomplete' if invalid/empty
|
|
65
|
-
const frameworkStatuses = Object.values(SUBSCRIPTION_STATUS);
|
|
66
|
-
const rawStatus = subscription.status || '';
|
|
67
|
-
const isValidFrameworkStatus = frameworkStatuses.includes(rawStatus as any);
|
|
68
|
-
const isValidCustomStatus =
|
|
69
|
-
typeof rawStatus === 'string' && rawStatus.trim().length > 0;
|
|
70
|
-
|
|
71
|
-
const status: SubscriptionStatus =
|
|
72
|
-
isValidFrameworkStatus || isValidCustomStatus
|
|
73
|
-
? (rawStatus as SubscriptionStatus)
|
|
74
|
-
: SUBSCRIPTION_STATUS.INCOMPLETE;
|
|
75
|
-
|
|
76
|
-
const subscriptionClaims: SubscriptionClaims = {
|
|
77
|
-
tier,
|
|
78
|
-
subscriptionId: subscription.id,
|
|
79
|
-
customerId: subscription.customer,
|
|
80
|
-
status,
|
|
81
|
-
subscriptionEnd: subscription.current_period_end
|
|
82
|
-
? new Date(subscription.current_period_end * 1000).toISOString()
|
|
83
|
-
: null,
|
|
84
|
-
cancelAtPeriodEnd: subscription.cancel_at_period_end || false,
|
|
85
|
-
updatedAt: new Date().toISOString(),
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
try {
|
|
89
|
-
const auth = getFirebaseAdminAuth();
|
|
90
|
-
const db = getFirebaseAdminFirestore();
|
|
91
|
-
|
|
92
|
-
// Read existing claims and merge to avoid overwriting other claims
|
|
93
|
-
const user = await auth.getUser(firebaseUid);
|
|
94
|
-
const currentClaims = user.customClaims || {};
|
|
95
|
-
|
|
96
|
-
// Update Firebase Auth custom claims
|
|
97
|
-
await auth.setCustomUserClaims(firebaseUid, {
|
|
98
|
-
...currentClaims,
|
|
99
|
-
subscription: subscriptionClaims,
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
// Also save to Firestore for redundancy and querying
|
|
103
|
-
await db
|
|
104
|
-
.collection('subscriptions')
|
|
105
|
-
.doc(firebaseUid)
|
|
106
|
-
.set(
|
|
107
|
-
{
|
|
108
|
-
...subscriptionClaims,
|
|
109
|
-
priceId,
|
|
110
|
-
createdAt: subscription.created
|
|
111
|
-
? new Date(subscription.created * 1000).toISOString()
|
|
112
|
-
: new Date().toISOString(),
|
|
113
|
-
updatedAt: new Date().toISOString(),
|
|
114
|
-
},
|
|
115
|
-
{ merge: true }
|
|
116
|
-
);
|
|
117
|
-
|
|
118
|
-
console.log(`Subscription updated for user ${firebaseUid}:`, {
|
|
119
|
-
tier,
|
|
120
|
-
status: subscription.status,
|
|
121
|
-
subscriptionId: subscription.id,
|
|
122
|
-
});
|
|
123
|
-
} catch (error) {
|
|
124
|
-
console.error('Failed to update user subscription:', error);
|
|
125
|
-
throw new Error('Failed to update user subscription');
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
41
|
/**
|
|
130
42
|
* Cancels user subscription and resets to free tier
|
|
131
43
|
*
|
|
@@ -135,6 +47,7 @@ export async function updateFirebaseUserSubscription(
|
|
|
135
47
|
*/
|
|
136
48
|
export async function cancelUserSubscription(
|
|
137
49
|
firebaseUid: string,
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
138
51
|
subscription: any
|
|
139
52
|
): Promise<void> {
|
|
140
53
|
if (!firebaseUid) {
|
|
@@ -23,6 +23,7 @@ import { withSchemaValidation } from './schemaValidation.js';
|
|
|
23
23
|
* @author AMBROISE PARK Consulting
|
|
24
24
|
*/
|
|
25
25
|
export function createFirebaseCallable<TRequest, TResponse>(
|
|
26
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
26
27
|
config: any,
|
|
27
28
|
defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,
|
|
28
29
|
handler: (
|
|
@@ -56,6 +57,7 @@ export function createFirebaseCallable<TRequest, TResponse>(
|
|
|
56
57
|
* @author AMBROISE PARK Consulting
|
|
57
58
|
*/
|
|
58
59
|
export function createFirebaseFunctionExports<TRequest, TResponse>(
|
|
60
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
59
61
|
config: any,
|
|
60
62
|
defaultSchema: v.BaseSchema<unknown, TRequest, v.BaseIssue<unknown>>,
|
|
61
63
|
handler: (
|
|
@@ -14,6 +14,7 @@ import { logger } from 'firebase-functions/v2';
|
|
|
14
14
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
15
15
|
|
|
16
16
|
/** Stored result of a previously processed idempotent operation. */
|
|
17
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
17
18
|
export interface IdempotencyResult<T = any> {
|
|
18
19
|
result: T;
|
|
19
20
|
processedAt: string;
|
|
@@ -27,6 +28,7 @@ export interface IdempotencyResult<T = any> {
|
|
|
27
28
|
* @since 0.0.1
|
|
28
29
|
* @author AMBROISE PARK Consulting
|
|
29
30
|
*/
|
|
31
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
30
32
|
export async function checkIdempotency<T = any>(
|
|
31
33
|
key: string,
|
|
32
34
|
operation: string
|
|
@@ -70,6 +72,7 @@ export async function checkIdempotency<T = any>(
|
|
|
70
72
|
* @since 0.0.1
|
|
71
73
|
* @author AMBROISE PARK Consulting
|
|
72
74
|
*/
|
|
75
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
73
76
|
export async function storeIdempotencyResult<T = any>(
|
|
74
77
|
key: string,
|
|
75
78
|
operation: string,
|
|
@@ -35,6 +35,7 @@ export interface PaymentMetrics {
|
|
|
35
35
|
currency?: string;
|
|
36
36
|
status: 'success' | 'failed' | 'pending';
|
|
37
37
|
timestamp: string;
|
|
38
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
38
39
|
metadata?: Record<string, any>;
|
|
39
40
|
}
|
|
40
41
|
|
|
@@ -109,7 +110,7 @@ export async function checkPaymentFailureRate(
|
|
|
109
110
|
|
|
110
111
|
const totalPayments = recentMetrics.size;
|
|
111
112
|
const failedPayments = recentMetrics.docs.filter(
|
|
112
|
-
(doc
|
|
113
|
+
(doc) => doc.data().status === 'failed'
|
|
113
114
|
).length;
|
|
114
115
|
|
|
115
116
|
const failureRate = (failedPayments / totalPayments) * 100;
|
|
@@ -157,7 +158,7 @@ export async function checkPaymentVolume(
|
|
|
157
158
|
.get();
|
|
158
159
|
|
|
159
160
|
let totalVolume = 0;
|
|
160
|
-
todayMetrics.docs.forEach((doc
|
|
161
|
+
todayMetrics.docs.forEach((doc) => {
|
|
161
162
|
const data = doc.data();
|
|
162
163
|
if (data.amount && data.currency === 'usd') {
|
|
163
164
|
totalVolume += data.amount / 100; // Convert cents to dollars
|
|
@@ -284,7 +285,7 @@ export async function getPaymentMetricsSummary(
|
|
|
284
285
|
let failedPayments = 0;
|
|
285
286
|
let totalVolume = 0;
|
|
286
287
|
|
|
287
|
-
metrics.docs.forEach((doc
|
|
288
|
+
metrics.docs.forEach((doc) => {
|
|
288
289
|
const data = doc.data();
|
|
289
290
|
totalPayments++;
|
|
290
291
|
|
|
@@ -349,7 +350,7 @@ export async function cleanupOldMetrics(
|
|
|
349
350
|
|
|
350
351
|
if (!oldMetrics.empty) {
|
|
351
352
|
const batch = db.batch();
|
|
352
|
-
oldMetrics.docs.forEach((doc
|
|
353
|
+
oldMetrics.docs.forEach((doc) => batch.delete(doc.ref));
|
|
353
354
|
await batch.commit();
|
|
354
355
|
}
|
|
355
356
|
|
|
@@ -365,7 +366,7 @@ export async function cleanupOldMetrics(
|
|
|
365
366
|
|
|
366
367
|
if (!oldAlerts.empty) {
|
|
367
368
|
const batch = db.batch();
|
|
368
|
-
oldAlerts.docs.forEach((doc
|
|
369
|
+
oldAlerts.docs.forEach((doc) => batch.delete(doc.ref));
|
|
369
370
|
await batch.commit();
|
|
370
371
|
}
|
|
371
372
|
|
|
@@ -20,6 +20,7 @@ import { DoNotDevError } from '@donotdev/core/server';
|
|
|
20
20
|
* @since 0.0.1
|
|
21
21
|
* @author AMBROISE PARK Consulting
|
|
22
22
|
*/
|
|
23
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
23
24
|
export function safeJsonParse<T = any>(json: string): T | null {
|
|
24
25
|
try {
|
|
25
26
|
return JSON.parse(json);
|
|
@@ -64,6 +65,7 @@ export function validateCollectionName(name: string): void {
|
|
|
64
65
|
* @since 0.0.1
|
|
65
66
|
* @author AMBROISE PARK Consulting
|
|
66
67
|
*/
|
|
68
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
67
69
|
export function validateDocument(data: any, schema?: any): void {
|
|
68
70
|
// G63: Throw DoNotDevError instead of plain Error for consistent error handling
|
|
69
71
|
if (!data || typeof data !== 'object') {
|
|
@@ -21,6 +21,7 @@ import * as v from 'valibot';
|
|
|
21
21
|
* @author AMBROISE PARK Consulting
|
|
22
22
|
*/
|
|
23
23
|
export function validateRequestData<T>(
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
24
25
|
data: any,
|
|
25
26
|
defaultSchema: v.BaseSchema<unknown, T, v.BaseIssue<unknown>>,
|
|
26
27
|
customSchema?: v.BaseSchema<unknown, T, v.BaseIssue<unknown>>
|
|
@@ -57,6 +57,7 @@ export const StripeValidationSchemas = {
|
|
|
57
57
|
export interface ValidationResult {
|
|
58
58
|
isValid: boolean;
|
|
59
59
|
errors: string[];
|
|
60
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
60
61
|
data?: any;
|
|
61
62
|
}
|
|
62
63
|
|
|
@@ -67,6 +68,7 @@ export interface ValidationResult {
|
|
|
67
68
|
* @since 0.0.1
|
|
68
69
|
* @author AMBROISE PARK Consulting
|
|
69
70
|
*/
|
|
71
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
70
72
|
export function validateWebhookEvent(data: any): ValidationResult {
|
|
71
73
|
try {
|
|
72
74
|
const validatedData = v.parse(StripeValidationSchemas.webhookEvent, data);
|
|
@@ -76,16 +78,9 @@ export function validateWebhookEvent(data: any): ValidationResult {
|
|
|
76
78
|
errors: [],
|
|
77
79
|
};
|
|
78
80
|
} catch (error) {
|
|
79
|
-
if (
|
|
80
|
-
error
|
|
81
|
-
|
|
82
|
-
'issues' in error &&
|
|
83
|
-
((error instanceof Error && error.name === 'ValiError') ||
|
|
84
|
-
(error as any).name === 'ValiError')
|
|
85
|
-
) {
|
|
86
|
-
const valiError = error as any;
|
|
87
|
-
const errors = valiError.issues.map(
|
|
88
|
-
(err: v.BaseIssue<unknown>) =>
|
|
81
|
+
if (v.isValiError(error)) {
|
|
82
|
+
const errors = error.issues.map(
|
|
83
|
+
(err) =>
|
|
89
84
|
`${err.path?.map((p) => p.key).join('.') || ''}: ${err.message}`
|
|
90
85
|
);
|
|
91
86
|
logger.warn('Webhook event validation failed', { errors, data });
|
|
@@ -108,6 +103,7 @@ export function validateWebhookEvent(data: any): ValidationResult {
|
|
|
108
103
|
* @since 0.0.1
|
|
109
104
|
* @author AMBROISE PARK Consulting
|
|
110
105
|
*/
|
|
106
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
111
107
|
export function validatePurchaseRequest(data: any): ValidationResult {
|
|
112
108
|
try {
|
|
113
109
|
const validatedData = v.parse(
|
|
@@ -120,16 +116,9 @@ export function validatePurchaseRequest(data: any): ValidationResult {
|
|
|
120
116
|
errors: [],
|
|
121
117
|
};
|
|
122
118
|
} catch (error) {
|
|
123
|
-
if (
|
|
124
|
-
error
|
|
125
|
-
|
|
126
|
-
'issues' in error &&
|
|
127
|
-
((error instanceof Error && error.name === 'ValiError') ||
|
|
128
|
-
(error as any).name === 'ValiError')
|
|
129
|
-
) {
|
|
130
|
-
const valiError = error as any;
|
|
131
|
-
const errors = valiError.issues.map(
|
|
132
|
-
(err: v.BaseIssue<unknown>) =>
|
|
119
|
+
if (v.isValiError(error)) {
|
|
120
|
+
const errors = error.issues.map(
|
|
121
|
+
(err) =>
|
|
133
122
|
`${err.path?.map((p) => p.key).join('.') || ''}: ${err.message}`
|
|
134
123
|
);
|
|
135
124
|
logger.warn('Purchase request validation failed', { errors, data });
|
|
@@ -223,6 +212,7 @@ export function validateUrl(url: string, name: string = 'URL'): string {
|
|
|
223
212
|
* @author AMBROISE PARK Consulting
|
|
224
213
|
*/
|
|
225
214
|
export function validateMetadata(
|
|
215
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
226
216
|
metadata: Record<string, any>
|
|
227
217
|
): Record<string, string> {
|
|
228
218
|
const sanitized: Record<string, string> = {};
|
package/src/shared/utils.ts
CHANGED
|
@@ -33,7 +33,9 @@ export { DoNotDevError };
|
|
|
33
33
|
* @since 0.0.1
|
|
34
34
|
* @author AMBROISE PARK Consulting
|
|
35
35
|
*/
|
|
36
|
-
export function getUserRole(
|
|
36
|
+
export function getUserRole(
|
|
37
|
+
auth: { uid?: string; token?: Record<string, unknown> } | null | undefined
|
|
38
|
+
): UserRole {
|
|
37
39
|
if (!auth?.uid) return 'guest';
|
|
38
40
|
|
|
39
41
|
// Check role claim (standard pattern: auth.token.role = 'admin' | 'super' | etc.)
|
|
@@ -74,7 +76,7 @@ export function createErrorResponse(error: unknown): {
|
|
|
74
76
|
error: {
|
|
75
77
|
code: string;
|
|
76
78
|
message: string;
|
|
77
|
-
details?:
|
|
79
|
+
details?: Record<string, unknown>;
|
|
78
80
|
};
|
|
79
81
|
} {
|
|
80
82
|
if (error instanceof DoNotDevError) {
|
|
@@ -114,7 +116,10 @@ export function createErrorResponse(error: unknown): {
|
|
|
114
116
|
* @since 0.0.1
|
|
115
117
|
* @author AMBROISE PARK Consulting
|
|
116
118
|
*/
|
|
117
|
-
export function validateDocument(
|
|
119
|
+
export function validateDocument(
|
|
120
|
+
data: unknown,
|
|
121
|
+
schema?: v.GenericSchema
|
|
122
|
+
): void {
|
|
118
123
|
if (!data || typeof data !== 'object') {
|
|
119
124
|
throw new Error('Invalid document data');
|
|
120
125
|
}
|
|
@@ -127,12 +132,12 @@ export function validateDocument(data: any, schema?: any): void {
|
|
|
127
132
|
if (schema) {
|
|
128
133
|
try {
|
|
129
134
|
v.parse(schema, data);
|
|
130
|
-
} catch (error
|
|
131
|
-
if (error
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (v.isValiError(error)) {
|
|
132
137
|
const messages = error.issues
|
|
133
138
|
.map(
|
|
134
|
-
(issue
|
|
135
|
-
`${issue.path?.map((p
|
|
139
|
+
(issue) =>
|
|
140
|
+
`${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`
|
|
136
141
|
)
|
|
137
142
|
.join('; ');
|
|
138
143
|
throw new DoNotDevError(
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Unit tests for `createSupabaseAggregateEntities`.
|
|
3
|
+
* @description Regression: filters were applied on `from()` (no filter methods) and
|
|
4
|
+
* grouping called a non-existent `.group()`, so any `where` or `groupBy` threw.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import * as v from 'valibot';
|
|
8
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
9
|
+
|
|
10
|
+
vi.mock('../baseFunction.js', () => ({
|
|
11
|
+
createSupabaseHandler: vi.fn(
|
|
12
|
+
(_operationName: string, _schema: unknown, handler: any) => handler
|
|
13
|
+
),
|
|
14
|
+
}));
|
|
15
|
+
|
|
16
|
+
vi.mock('@donotdev/supabase/server', () => ({
|
|
17
|
+
defaultFieldMapper: {
|
|
18
|
+
toBackendField: (f: string) =>
|
|
19
|
+
f.replace(/[A-Z]/g, (m) => `_${m.toLowerCase()}`),
|
|
20
|
+
},
|
|
21
|
+
}));
|
|
22
|
+
|
|
23
|
+
import { createSupabaseAggregateEntities } from '../crud/aggregate.js';
|
|
24
|
+
|
|
25
|
+
type Result = { data: unknown[] | null; error: null; count: number | null };
|
|
26
|
+
|
|
27
|
+
/** Minimal PostgREST stub: from() has only select(); filters live on the builder. */
|
|
28
|
+
function setup(result: Result) {
|
|
29
|
+
const calls: Array<[string, ...unknown[]]> = [];
|
|
30
|
+
const builder: Record<string, unknown> = {
|
|
31
|
+
then: (resolve: (r: Result) => unknown) => resolve(result),
|
|
32
|
+
};
|
|
33
|
+
for (const op of [
|
|
34
|
+
'eq',
|
|
35
|
+
'neq',
|
|
36
|
+
'gt',
|
|
37
|
+
'gte',
|
|
38
|
+
'lt',
|
|
39
|
+
'lte',
|
|
40
|
+
'in',
|
|
41
|
+
'not',
|
|
42
|
+
'contains',
|
|
43
|
+
]) {
|
|
44
|
+
builder[op] = (...args: unknown[]) => {
|
|
45
|
+
calls.push([op, ...args]);
|
|
46
|
+
return builder;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const select = vi.fn((...args: unknown[]) => {
|
|
50
|
+
calls.push(['select', ...args]);
|
|
51
|
+
return builder;
|
|
52
|
+
});
|
|
53
|
+
const supabaseAdmin = { from: vi.fn(() => ({ select })) };
|
|
54
|
+
const handler = createSupabaseAggregateEntities(
|
|
55
|
+
'orders',
|
|
56
|
+
v.object({}),
|
|
57
|
+
'user'
|
|
58
|
+
) as unknown as (data: unknown, ctx: unknown) => Promise<{ value: unknown }>;
|
|
59
|
+
return {
|
|
60
|
+
calls,
|
|
61
|
+
run: (data: unknown) => handler(data, { supabaseAdmin }),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
describe('createSupabaseAggregateEntities', () => {
|
|
66
|
+
it('applies where filters after select', async () => {
|
|
67
|
+
const { calls, run } = setup({ data: null, error: null, count: 3 });
|
|
68
|
+
const res = await run({
|
|
69
|
+
where: [['status', '==', 'paid']],
|
|
70
|
+
aggregate: { field: 'id', operation: 'count' },
|
|
71
|
+
});
|
|
72
|
+
expect(res.value).toBe(3);
|
|
73
|
+
expect(calls).toEqual([
|
|
74
|
+
['select', '*', { count: 'exact', head: true }],
|
|
75
|
+
['eq', 'status', 'paid'],
|
|
76
|
+
]);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('sums a column over filtered rows', async () => {
|
|
80
|
+
const { calls, run } = setup({
|
|
81
|
+
data: [
|
|
82
|
+
{ total_amount: 10 },
|
|
83
|
+
{ total_amount: '5' },
|
|
84
|
+
{ total_amount: null },
|
|
85
|
+
],
|
|
86
|
+
error: null,
|
|
87
|
+
count: null,
|
|
88
|
+
});
|
|
89
|
+
const res = await run({
|
|
90
|
+
where: [['amount', '>', 0]],
|
|
91
|
+
aggregate: { field: 'totalAmount', operation: 'sum' },
|
|
92
|
+
});
|
|
93
|
+
expect(res.value).toBe(15);
|
|
94
|
+
expect(calls[0]).toEqual(['select', 'total_amount']);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('groups rows in JS for every operation', async () => {
|
|
98
|
+
const rows = [
|
|
99
|
+
{ customer_id: 'a', status: 'paid', total: 10 },
|
|
100
|
+
{ customer_id: 'a', status: 'paid', total: 30 },
|
|
101
|
+
{ customer_id: 'b', status: 'paid', total: 5 },
|
|
102
|
+
{ customer_id: 'b', status: 'open', total: 7 },
|
|
103
|
+
];
|
|
104
|
+
const { calls, run } = setup({ data: rows, error: null, count: null });
|
|
105
|
+
|
|
106
|
+
const avg = await run({
|
|
107
|
+
where: [['total', '>=', 0]],
|
|
108
|
+
aggregate: { field: 'total', operation: 'avg' },
|
|
109
|
+
groupBy: ['customerId', 'status'],
|
|
110
|
+
});
|
|
111
|
+
expect(avg.value).toEqual({ 'a|paid': 20, 'b|paid': 5, 'b|open': 7 });
|
|
112
|
+
expect(calls[0]).toEqual(['select', 'customer_id, status, total']);
|
|
113
|
+
expect(calls[1]).toEqual(['gte', 'total', 0]);
|
|
114
|
+
|
|
115
|
+
const count = await run({
|
|
116
|
+
aggregate: { field: 'id', operation: 'count' },
|
|
117
|
+
groupBy: ['customerId'],
|
|
118
|
+
});
|
|
119
|
+
expect(count.value).toEqual({ a: 2, b: 2 });
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('throws on a query error', async () => {
|
|
123
|
+
const { run } = setup({
|
|
124
|
+
data: null,
|
|
125
|
+
error: { message: 'boom' } as never,
|
|
126
|
+
count: null,
|
|
127
|
+
});
|
|
128
|
+
await expect(
|
|
129
|
+
run({ aggregate: { field: 'id', operation: 'count' } })
|
|
130
|
+
).rejects.toThrow(/boom/);
|
|
131
|
+
});
|
|
132
|
+
});
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Unit tests for `createDeleteAccount`.
|
|
3
|
+
* @description `beforeDelete` runs first; a throw refuses the deletion with a 409
|
|
4
|
+
* carrying the error's message and code, and the auth user is kept.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
8
|
+
|
|
9
|
+
vi.mock('../../baseFunction.js', () => ({
|
|
10
|
+
createSupabaseHandler: vi.fn(
|
|
11
|
+
(_operationName: string, _schema: unknown, handler: any) => handler
|
|
12
|
+
),
|
|
13
|
+
}));
|
|
14
|
+
|
|
15
|
+
import { createDeleteAccount } from '../deleteAccount.js';
|
|
16
|
+
|
|
17
|
+
type Handler = (data: unknown, ctx: unknown) => Promise<unknown>;
|
|
18
|
+
|
|
19
|
+
function setup(deleteError: unknown = null) {
|
|
20
|
+
const order: string[] = [];
|
|
21
|
+
const deleteUser = vi.fn(async () => {
|
|
22
|
+
order.push('deleteUser');
|
|
23
|
+
return { error: deleteError };
|
|
24
|
+
});
|
|
25
|
+
const ctx = {
|
|
26
|
+
uid: 'user-1',
|
|
27
|
+
userRole: 'user',
|
|
28
|
+
supabaseAdmin: { auth: { admin: { deleteUser } } },
|
|
29
|
+
};
|
|
30
|
+
return { ctx, deleteUser, order };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('createDeleteAccount', () => {
|
|
34
|
+
it('deletes the caller without options (unchanged behaviour)', async () => {
|
|
35
|
+
const { ctx, deleteUser } = setup();
|
|
36
|
+
const handler = createDeleteAccount() as unknown as Handler;
|
|
37
|
+
await expect(handler({}, ctx)).resolves.toEqual({ success: true });
|
|
38
|
+
expect(deleteUser).toHaveBeenCalledWith('user-1');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('runs beforeDelete with the context before deleting the user', async () => {
|
|
42
|
+
const { ctx, deleteUser, order } = setup();
|
|
43
|
+
const beforeDelete = vi.fn(async (c: unknown) => {
|
|
44
|
+
expect(c).toBe(ctx);
|
|
45
|
+
order.push('beforeDelete');
|
|
46
|
+
});
|
|
47
|
+
const handler = createDeleteAccount({ beforeDelete }) as unknown as Handler;
|
|
48
|
+
await expect(handler({}, ctx)).resolves.toEqual({ success: true });
|
|
49
|
+
expect(order).toEqual(['beforeDelete', 'deleteUser']);
|
|
50
|
+
expect(deleteUser).toHaveBeenCalledTimes(1);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('refuses with 409 { error, code } and keeps the user when beforeDelete throws', async () => {
|
|
54
|
+
const { ctx, deleteUser } = setup();
|
|
55
|
+
const refusal = Object.assign(new Error('open_orders'), { code: 'P0001' });
|
|
56
|
+
const handler = createDeleteAccount({
|
|
57
|
+
beforeDelete: async () => {
|
|
58
|
+
throw refusal;
|
|
59
|
+
},
|
|
60
|
+
}) as unknown as Handler;
|
|
61
|
+
const res = (await handler({}, ctx)) as Response;
|
|
62
|
+
expect(res).toBeInstanceOf(Response);
|
|
63
|
+
expect(res.status).toBe(409);
|
|
64
|
+
expect(await res.json()).toEqual({ error: 'open_orders', code: 'P0001' });
|
|
65
|
+
expect(deleteUser).not.toHaveBeenCalled();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('refuses an error without a code with its message only', async () => {
|
|
69
|
+
const { ctx, deleteUser } = setup();
|
|
70
|
+
const handler = createDeleteAccount({
|
|
71
|
+
beforeDelete: async () => {
|
|
72
|
+
throw new Error('unpaid_terms');
|
|
73
|
+
},
|
|
74
|
+
}) as unknown as Handler;
|
|
75
|
+
const res = (await handler({}, ctx)) as Response;
|
|
76
|
+
expect(res.status).toBe(409);
|
|
77
|
+
expect(await res.json()).toEqual({ error: 'unpaid_terms' });
|
|
78
|
+
expect(deleteUser).not.toHaveBeenCalled();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('refuses a plain-object rejection (PostgREST { message, code } shape)', async () => {
|
|
82
|
+
const { ctx, deleteUser } = setup();
|
|
83
|
+
const handler = createDeleteAccount({
|
|
84
|
+
beforeDelete: async () => {
|
|
85
|
+
// eslint-disable-next-line @typescript-eslint/only-throw-error -- why: PostgREST rejects with plain objects
|
|
86
|
+
throw { message: 'open_orders', code: 'P0001', details: null };
|
|
87
|
+
},
|
|
88
|
+
}) as unknown as Handler;
|
|
89
|
+
const res = (await handler({}, ctx)) as Response;
|
|
90
|
+
expect(await res.json()).toEqual({ error: 'open_orders', code: 'P0001' });
|
|
91
|
+
expect(deleteUser).not.toHaveBeenCalled();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('throws when Supabase fails to delete the user', async () => {
|
|
95
|
+
const failure = new Error('db down');
|
|
96
|
+
const { ctx } = setup(failure);
|
|
97
|
+
const handler = createDeleteAccount({
|
|
98
|
+
beforeDelete: async () => {},
|
|
99
|
+
}) as unknown as Handler;
|
|
100
|
+
await expect(handler({}, ctx)).rejects.toBe(failure);
|
|
101
|
+
});
|
|
102
|
+
});
|