@donotdev/functions 0.2.1 → 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.
Files changed (184) hide show
  1. package/README.md +2 -2
  2. package/lib/chunks/chunk-6NXIK35R.js +23 -0
  3. package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
  4. package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
  5. package/lib/chunks/chunk-EZKRLLSQ.js.map +7 -0
  6. package/lib/chunks/chunk-F3PHE627.js +22 -0
  7. package/lib/chunks/chunk-F3PHE627.js.map +7 -0
  8. package/lib/chunks/chunk-F3WBFWPO.js +151 -0
  9. package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
  10. package/lib/chunks/chunk-G5DRV3DH.js +22 -0
  11. package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
  12. package/lib/chunks/{chunk-5IPULSUX.js → chunk-GDIUOJMD.js} +2 -2
  13. package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
  14. package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
  15. package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
  16. package/lib/chunks/chunk-QXIOO2RL.js +22 -0
  17. package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
  18. package/lib/chunks/{chunk-3F4BWKQD.js → chunk-UH445BGK.js} +2 -2
  19. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  20. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  21. package/lib/chunks/chunk-W74UL7AY.js +22 -0
  22. package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
  23. package/lib/chunks/{monitoring-E7JBYBHQ.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/server-NODQAE3F.js +22 -0
  26. package/lib/firebase/billing/index.d.ts +2 -2
  27. package/lib/firebase/crud/aggregate.d.ts +1 -1
  28. package/lib/firebase/index.d.ts +1 -1
  29. package/lib/firebase/index.js +1 -1
  30. package/lib/firebase/index.js.map +4 -4
  31. package/lib/firebase/registerCrudFunctions.d.ts +0 -5
  32. package/lib/shared/billing/checkoutPrice.d.ts +3 -6
  33. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  34. package/lib/shared/billing/createCheckout.d.ts +4 -4
  35. package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
  36. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  37. package/lib/shared/billing/idempotency.d.ts +3 -23
  38. package/lib/shared/billing/idempotencyContract.d.ts +0 -20
  39. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  40. package/lib/shared/billing/stripePinned.d.ts +43 -0
  41. package/lib/shared/denoEnv.d.ts +25 -0
  42. package/lib/shared/github.d.ts +0 -8
  43. package/lib/shared/index.js +1 -1
  44. package/lib/shared/logger.d.ts +14 -14
  45. package/lib/shared/utils/external/subscription.d.ts +0 -8
  46. package/lib/shared/utils/internal/auth.d.ts +1 -5
  47. package/lib/shared/utils.d.ts +12 -83
  48. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  49. package/lib/supabase/crud/create.d.ts +0 -8
  50. package/lib/supabase/crud/entityStore.d.ts +13 -0
  51. package/lib/supabase/crud/update.d.ts +0 -8
  52. package/lib/supabase/index.d.ts +1 -0
  53. package/lib/supabase/index.js +1 -1
  54. package/lib/supabase/index.js.map +4 -4
  55. package/lib/vercel/api/index.js +1 -1
  56. package/lib/vercel/api/index.js.map +3 -3
  57. package/package.json +9 -9
  58. package/src/firebase/auth/getCustomClaims.ts +2 -0
  59. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  60. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  61. package/src/firebase/auth/setCustomClaims.ts +3 -0
  62. package/src/firebase/baseFunction.ts +8 -4
  63. package/src/firebase/billing/changePlan.ts +6 -5
  64. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  65. package/src/firebase/billing/index.d.ts +0 -12
  66. package/src/firebase/billing/index.ts +0 -3
  67. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  68. package/src/firebase/billing/webhookHandler.ts +4 -4
  69. package/src/firebase/crud/aggregate.ts +41 -12
  70. package/src/firebase/crud/bulk.ts +7 -0
  71. package/src/firebase/crud/create.ts +21 -8
  72. package/src/firebase/crud/delete.ts +6 -1
  73. package/src/firebase/crud/get.ts +9 -2
  74. package/src/firebase/crud/list.ts +18 -8
  75. package/src/firebase/crud/update.ts +15 -7
  76. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  77. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  78. package/src/firebase/index.ts +0 -1
  79. package/src/firebase/oauth/disconnect.ts +2 -2
  80. package/src/firebase/oauth/exchangeToken.ts +6 -2
  81. package/src/firebase/oauth/getConnections.ts +3 -3
  82. package/src/firebase/oauth/githubAccess.ts +7 -4
  83. package/src/firebase/oauth/refreshToken.ts +3 -2
  84. package/src/firebase/registerCrudFunctions.ts +0 -19
  85. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  86. package/src/shared/__tests__/idempotency.test.ts +0 -32
  87. package/src/shared/__tests__/utils.test.ts +0 -25
  88. package/src/shared/ai/classifyAIError.ts +18 -10
  89. package/src/shared/ai/createAIRoute.ts +2 -1
  90. package/src/shared/ai/resolveModelTier.ts +2 -1
  91. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
  92. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  93. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  94. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  95. package/src/shared/billing/checkoutPrice.ts +7 -42
  96. package/src/shared/billing/checkoutValidation.ts +19 -2
  97. package/src/shared/billing/createCheckout.ts +59 -30
  98. package/src/shared/billing/firestoreIdempotency.ts +2 -21
  99. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  100. package/src/shared/billing/idempotency.ts +4 -54
  101. package/src/shared/billing/idempotencyContract.ts +0 -21
  102. package/src/shared/billing/orderWebhook.ts +69 -1
  103. package/src/shared/billing/stripeClient.ts +2 -1
  104. package/src/shared/billing/stripePinned.ts +71 -0
  105. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  106. package/src/shared/billing/webhookHandler.ts +5 -1
  107. package/src/shared/crud/bulkCore.ts +3 -2
  108. package/src/shared/denoEnv.ts +29 -0
  109. package/src/shared/email/createEmailRoute.ts +2 -2
  110. package/src/shared/errorHandling.ts +8 -8
  111. package/src/shared/firebase.ts +26 -9
  112. package/src/shared/github.ts +15 -5
  113. package/src/shared/logger.ts +37 -38
  114. package/src/shared/schema.ts +6 -10
  115. package/src/shared/utils/external/date.ts +4 -4
  116. package/src/shared/utils/external/subscription.ts +2 -89
  117. package/src/shared/utils/firebaseHelpers.ts +2 -0
  118. package/src/shared/utils/internal/auth.ts +1 -6
  119. package/src/shared/utils/internal/idempotency.ts +3 -0
  120. package/src/shared/utils/internal/monitoring.ts +6 -5
  121. package/src/shared/utils/internal/validation.ts +2 -0
  122. package/src/shared/utils/schemaValidation.ts +1 -0
  123. package/src/shared/utils/validation.ts +10 -20
  124. package/src/shared/utils.ts +12 -138
  125. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  126. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  127. package/src/supabase/auth/deleteAccount.ts +72 -5
  128. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  129. package/src/supabase/crud/aggregate.ts +85 -72
  130. package/src/supabase/crud/bulk.ts +3 -0
  131. package/src/supabase/crud/create.ts +13 -9
  132. package/src/supabase/crud/delete.ts +2 -1
  133. package/src/supabase/crud/entityStore.ts +1 -1
  134. package/src/supabase/crud/get.ts +2 -1
  135. package/src/supabase/crud/list.ts +23 -17
  136. package/src/supabase/crud/update.ts +9 -6
  137. package/src/supabase/edgeFunction.ts +2 -1
  138. package/src/supabase/email/createEmailFunction.ts +2 -1
  139. package/src/supabase/index.ts +1 -0
  140. package/src/supabase/oauth/exchangeToken.ts +1 -0
  141. package/src/supabase/oauth/getConnections.ts +1 -1
  142. package/src/supabase/oauth/refreshToken.ts +1 -0
  143. package/src/supabase/utils/idempotency.ts +1 -1
  144. package/src/supabase/utils/monitoring.ts +1 -0
  145. package/src/vercel/api/billing/change-plan.ts +6 -5
  146. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  147. package/src/vercel/api/crud/bulk.ts +7 -2
  148. package/src/vercel/api/crud/create.ts +6 -3
  149. package/src/vercel/api/crud/delete.ts +5 -2
  150. package/src/vercel/api/crud/get.ts +5 -2
  151. package/src/vercel/api/crud/list.ts +6 -3
  152. package/src/vercel/api/crud/update.ts +6 -3
  153. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  154. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  155. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  156. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  157. package/src/vercel/baseFunction.ts +5 -1
  158. package/lib/chunks/chunk-5IPULSUX.js.map +0 -7
  159. package/lib/chunks/chunk-6USHTJED.js +0 -22
  160. package/lib/chunks/chunk-6USHTJED.js.map +0 -7
  161. package/lib/chunks/chunk-CXBSROEW.js +0 -23
  162. package/lib/chunks/chunk-CXBSROEW.js.map +0 -7
  163. package/lib/chunks/chunk-GYTCWMXV.js +0 -22
  164. package/lib/chunks/chunk-GYTCWMXV.js.map +0 -7
  165. package/lib/chunks/chunk-LCDLG4VG.js +0 -151
  166. package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
  167. package/lib/chunks/chunk-MQANUSY3.js +0 -22
  168. package/lib/chunks/chunk-MQANUSY3.js.map +0 -7
  169. package/lib/chunks/chunk-OFQVO3FD.js +0 -22
  170. package/lib/chunks/chunk-OFQVO3FD.js.map +0 -7
  171. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  172. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  173. package/lib/chunks/chunk-US2VOP4S.js +0 -22
  174. package/lib/chunks/chunk-US2VOP4S.js.map +0 -7
  175. package/lib/chunks/chunk-YTKDNZNW.js +0 -22
  176. package/lib/chunks/chunk-YTKDNZNW.js.map +0 -7
  177. package/lib/chunks/server-IQ5JNJOM.js +0 -22
  178. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  179. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  180. package/src/shared/utils/functionWrapper.ts +0 -73
  181. /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-UH445BGK.js.map} +0 -0
  182. /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  183. /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  184. /package/lib/chunks/{server-IQ5JNJOM.js.map → server-NODQAE3F.js.map} +0 -0
@@ -49,27 +49,6 @@ export interface IdempotencyStore {
49
49
  release(eventId: string, ownerToken: string): Promise<boolean>;
50
50
  }
51
51
 
52
- /**
53
- * Store with the 0.1.x accessors.
54
- *
55
- * @deprecated Use {@link IdempotencyStore}: `reserve` returns three states and
56
- * an owner token; `checkAndReserve` and `isProcessed` do not.
57
- * @version 0.2.0
58
- * @since 0.2.0
59
- * @author AMBROISE PARK Consulting
60
- */
61
- export interface LegacyIdempotencyStore extends IdempotencyStore {
62
- /** 0.1.x: `true` when the event must be skipped (processed or live lease). */
63
- checkAndReserve(eventId: string): Promise<boolean>;
64
- /** Whether the event was processed (non-atomic read). */
65
- isProcessed(eventId: string): Promise<boolean>;
66
- /**
67
- * Mark processed. Without `ownerToken` (0.1.x call) the write is unconditional.
68
- * @throws {ReservationLostError} When `ownerToken` is given and no longer owns the event
69
- */
70
- markProcessed(eventId: string, ownerToken?: string): Promise<void>;
71
- }
72
-
73
52
  /**
74
53
  * Thrown by `markProcessed` when the caller no longer owns the reservation:
75
54
  * its lease expired and another delivery retook the event, or the row is gone.
@@ -3,7 +3,8 @@
3
3
  /**
4
4
  * @fileoverview StripeOrder webhook handling
5
5
  * @description Maps Checkout Session events of one-time, multi-line orders to the
6
- * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`).
6
+ * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`), and
7
+ * `customer.tax_id.updated` to `onTaxIdUpdated`.
7
8
  * Hook errors propagate: the webhook answers non-2xx and Stripe retries.
8
9
  *
9
10
  * @version 0.2.0
@@ -18,7 +19,9 @@ import type {
18
19
  CheckoutSessionSnapshot,
19
20
  OrderHookContext,
20
21
  PaidLineItem,
22
+ StripeBackConfig,
21
23
  StripeOrderBackItem,
24
+ TaxIdSnapshot,
22
25
  } from '@donotdev/core/server';
23
26
 
24
27
  import { logger } from '../logger.js';
@@ -267,3 +270,68 @@ export async function handleOrderSessionEvent(
267
270
  return;
268
271
  }
269
272
  }
273
+
274
+ /**
275
+ * Map a Stripe TaxId to the provider-neutral snapshot given to `onTaxIdUpdated`.
276
+ *
277
+ * @param taxId - TaxId from a `customer.tax_id.updated` event
278
+ * @returns Snapshot
279
+ *
280
+ * @version 0.2.0
281
+ * @since 0.2.3
282
+ * @author AMBROISE PARK Consulting
283
+ */
284
+ export function toTaxIdSnapshot(taxId: Stripe.TaxId): TaxIdSnapshot {
285
+ return {
286
+ id: taxId.id,
287
+ customerId: idOf(taxId.customer),
288
+ type: taxId.type,
289
+ value: taxId.value,
290
+ country: taxId.country,
291
+ verification: taxId.verification && {
292
+ status: taxId.verification.status,
293
+ verifiedName: taxId.verification.verified_name,
294
+ verifiedAddress: taxId.verification.verified_address,
295
+ },
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Handle `customer.tax_id.updated`: run `onTaxIdUpdated` of every StripeOrder item
301
+ * that defines it, once per distinct function. Called by `processWebhook` after
302
+ * signature verification and idempotency reservation (same path as order events).
303
+ *
304
+ * @param eventId - Stripe event ID
305
+ * @param taxId - TaxId from the event
306
+ * @param config - App back config
307
+ * @throws When a hook throws (the webhook answers non-2xx and Stripe retries)
308
+ *
309
+ * @version 0.2.0
310
+ * @since 0.2.3
311
+ * @author AMBROISE PARK Consulting
312
+ */
313
+ export async function handleTaxIdUpdated(
314
+ eventId: string,
315
+ taxId: Stripe.TaxId,
316
+ config: StripeBackConfig
317
+ ): Promise<void> {
318
+ const snapshot = toTaxIdSnapshot(taxId);
319
+ const ran = new Set<StripeOrderBackItem['onTaxIdUpdated']>();
320
+ for (const [billingConfigKey, item] of Object.entries(config)) {
321
+ if (item.type !== 'StripeOrder' || !item.onTaxIdUpdated) continue;
322
+ if (ran.has(item.onTaxIdUpdated)) continue;
323
+ ran.add(item.onTaxIdUpdated);
324
+ await item.onTaxIdUpdated(snapshot, { billingConfigKey, eventId });
325
+ logger.info('[Webhook] Tax ID updated', {
326
+ taxIdId: snapshot.id,
327
+ status: snapshot.verification?.status ?? null,
328
+ billingConfigKey,
329
+ operation: 'tax_id_updated',
330
+ });
331
+ }
332
+ if (ran.size === 0) {
333
+ logger.debug('[Webhook] customer.tax_id.updated without onTaxIdUpdated hook', {
334
+ eventId,
335
+ });
336
+ }
337
+ }
@@ -34,7 +34,8 @@ export function initStripe(apiKey: string) {
34
34
  const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;
35
35
 
36
36
  _stripe = new Stripe(apiKey, {
37
- apiVersion: apiVersion as any,
37
+ // why: SDK types accept only the latest API version; the pinned/env version is older by design
38
+ apiVersion: apiVersion as Stripe.LatestApiVersion,
38
39
  });
39
40
  return _stripe;
40
41
  }
@@ -0,0 +1,71 @@
1
+ // packages/functions/src/shared/billing/stripePinned.ts
2
+
3
+ /**
4
+ * @fileoverview Typed access to Stripe fields of the pinned API version
5
+ * @description The Stripe SDK types follow the latest API version only, while
6
+ * requests run at `STRIPE_API_VERSION_PIN` (pre-basil). Fields that basil
7
+ * moved (subscription period, invoice subscription) are read here, through one
8
+ * documented cast, instead of `as any` at every call site. Internal: not
9
+ * re-exported from any package entry.
10
+ *
11
+ * @version 0.1.0
12
+ * @since 0.2.2
13
+ * @author AMBROISE PARK Consulting
14
+ */
15
+
16
+ import type Stripe from 'stripe';
17
+
18
+ /** Subscription fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */
19
+ interface PinnedSubscriptionFields {
20
+ current_period_start: number;
21
+ current_period_end: number;
22
+ }
23
+
24
+ /** Invoice fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */
25
+ interface PinnedInvoiceFields {
26
+ /** Not expanded in webhook payloads: the subscription id, or null for one-off invoices. */
27
+ subscription: string | null;
28
+ }
29
+
30
+ /**
31
+ * Period fields of a subscription at the pinned API version.
32
+ *
33
+ * @version 0.1.0
34
+ * @since 0.2.2
35
+ * @author AMBROISE PARK Consulting
36
+ */
37
+ export function pinnedSubscriptionPeriod(
38
+ subscription: Stripe.Subscription
39
+ ): PinnedSubscriptionFields {
40
+ // why: SDK v20 types track the latest API (period moved to items); runtime is pinned pre-basil
41
+ return subscription as unknown as PinnedSubscriptionFields;
42
+ }
43
+
44
+ /**
45
+ * Subscription id of an invoice at the pinned API version.
46
+ *
47
+ * @version 0.1.0
48
+ * @since 0.2.2
49
+ * @author AMBROISE PARK Consulting
50
+ */
51
+ export function pinnedInvoiceSubscriptionId(
52
+ invoice: Stripe.Invoice
53
+ ): string | null {
54
+ // why: SDK v20 types track the latest API (moved to invoice.parent); runtime is pinned pre-basil
55
+ return (invoice as unknown as PinnedInvoiceFields).subscription;
56
+ }
57
+
58
+ /**
59
+ * Narrows a value to one of a readonly list of literals.
60
+ *
61
+ * @version 0.1.0
62
+ * @since 0.2.2
63
+ * @author AMBROISE PARK Consulting
64
+ */
65
+ export function isOneOf<T extends string>(
66
+ values: readonly T[],
67
+ value: string
68
+ ): value is T {
69
+ const list: readonly string[] = values;
70
+ return list.includes(value);
71
+ }
@@ -23,6 +23,7 @@ import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from
23
23
  import { handleError } from '../errorHandling.js';
24
24
  import { logger } from '../logger.js';
25
25
  import type { OrderSessionEventType } from './orderWebhook.js';
26
+ import { pinnedInvoiceSubscriptionId, pinnedSubscriptionPeriod } from './stripePinned.js';
26
27
 
27
28
  /**
28
29
  * Checkout Session event of a StripePayment / StripeSubscription item.
@@ -224,7 +225,7 @@ export async function handleInvoicePaymentSucceeded(
224
225
  stripe: Stripe,
225
226
  authProvider: BillingAuthProvider | null
226
227
  ): Promise<void> {
227
- const subscriptionId = (invoice as any).subscription as string;
228
+ const subscriptionId = pinnedInvoiceSubscriptionId(invoice);
228
229
  if (!subscriptionId) return;
229
230
 
230
231
  // ✅ FIX: Fetch subscription to get metadata
@@ -322,7 +323,7 @@ export async function handleSubscriptionDeleted(
322
323
  tier: SUBSCRIPTION_TIERS.FREE,
323
324
  status: SUBSCRIPTION_STATUS.CANCELED,
324
325
  subscriptionEnd: new Date(
325
- (subscription as any).current_period_end * 1000
326
+ pinnedSubscriptionPeriod(subscription).current_period_end * 1000
326
327
  ).toISOString(),
327
328
  subscriptionId: subscription.id,
328
329
  customerId: subscription.customer as string,
@@ -20,7 +20,7 @@ import { handleError } from '../errorHandling.js';
20
20
  import { logger } from '../logger.js';
21
21
  import { ReservationLostError } from './idempotencyContract.js';
22
22
  import type { IdempotencyStore } from './idempotencyContract.js';
23
- import { handleOrderSessionEvent } from './orderWebhook.js';
23
+ import { handleOrderSessionEvent, handleTaxIdUpdated } from './orderWebhook.js';
24
24
  import type { OrderSessionEventType } from './orderWebhook.js';
25
25
  import {
26
26
  handleInvoicePaymentSucceeded,
@@ -275,6 +275,10 @@ async function routeEvent(
275
275
  await handlePaymentFailed(event.data.object as Stripe.Invoice, config);
276
276
  break;
277
277
 
278
+ case 'customer.tax_id.updated':
279
+ await handleTaxIdUpdated(event.id, event.data.object, config);
280
+ break;
281
+
278
282
  default:
279
283
  // W23: Use structured logger instead of console.log in production
280
284
  logger.debug('[Webhook] Unhandled event type', { type: event.type });
@@ -46,6 +46,7 @@ import type {
46
46
  * the parsed output) so callers can pass entity-specific schemas generated by
47
47
  * `createSchemas()` without fighting variance.
48
48
  */
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
49
50
  export type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;
50
51
 
51
52
  /**
@@ -281,7 +282,7 @@ export async function executeBulk<TRow = unknown>(
281
282
  const messages = parsed.issues
282
283
  .map(
283
284
  (issue) =>
284
- `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
285
+ `${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`
285
286
  )
286
287
  .join('; ');
287
288
  throw new DoNotDevError(
@@ -472,7 +473,7 @@ function validateRow(
472
473
  const messages = parsed.issues
473
474
  .map(
474
475
  (issue) =>
475
- `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
476
+ `${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`
476
477
  )
477
478
  .join('; ');
478
479
  throw new DoNotDevError(
@@ -0,0 +1,29 @@
1
+ // packages/functions/src/shared/denoEnv.ts
2
+
3
+ /**
4
+ * @fileoverview Typed access to the Deno env from cross-runtime code
5
+ * @description Supabase Edge Functions run on Deno, Firebase/Vercel on Node.
6
+ * This package compiles against the Node lib types, which have no `Deno`
7
+ * global. Internal: not re-exported from any package entry.
8
+ *
9
+ * @version 0.1.0
10
+ * @since 0.2.2
11
+ * @author AMBROISE PARK Consulting
12
+ */
13
+
14
+ /** The part of the Deno namespace read by this package. */
15
+ interface DenoEnvNamespace {
16
+ env?: { get(key: string): string | undefined };
17
+ }
18
+
19
+ /**
20
+ * Deno env accessor, when running on Deno.
21
+ *
22
+ * @version 0.1.0
23
+ * @since 0.2.2
24
+ * @author AMBROISE PARK Consulting
25
+ */
26
+ export function getDenoEnv(): DenoEnvNamespace['env'] {
27
+ // why: the Deno global is absent from the Node lib types this package compiles against
28
+ return (globalThis as { Deno?: DenoEnvNamespace }).Deno?.env;
29
+ }
@@ -62,8 +62,8 @@ export async function handleEmailRequest(
62
62
 
63
63
  // Render template with locale
64
64
  const locale = request.locale || 'fr';
65
- const subject = template.subject(request.data as any, locale);
66
- const html = template.html(request.data as any, locale);
65
+ const subject = template.subject(request.data, locale);
66
+ const html = template.html(request.data, locale);
67
67
 
68
68
  // Send via provider
69
69
  const result = await provider.send({
@@ -10,7 +10,7 @@
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
12
 
13
- import type { EntityHookError } from '@donotdev/core/server';
13
+ import type { EntityHookError, ErrorCode } from '@donotdev/core/server';
14
14
  import { DoNotDevError } from '@donotdev/core/server';
15
15
 
16
16
  // Re-export DoNotDevError so existing imports from this module continue to work
@@ -40,12 +40,12 @@ export function handleError(error: unknown): never {
40
40
  }
41
41
 
42
42
  // Error classification logic (same for all platforms)
43
- let code: string;
43
+ let code: ErrorCode;
44
44
  let message: string;
45
- let details: any;
45
+ let details: unknown;
46
46
 
47
47
  if (error instanceof DoNotDevError) {
48
- code = error.code as string;
48
+ code = error.code;
49
49
  message = error.message;
50
50
  details = error.details;
51
51
  } else if (
@@ -53,17 +53,17 @@ export function handleError(error: unknown): never {
53
53
  typeof error === 'object' &&
54
54
  'issues' in error &&
55
55
  ((error instanceof Error && error.name === 'ValiError') ||
56
- (error as any).name === 'ValiError')
56
+ ('name' in error && error.name === 'ValiError'))
57
57
  ) {
58
58
  code = 'invalid-argument';
59
59
  message = 'Validation failed';
60
- details = { validationErrors: (error as any).issues };
60
+ details = { validationErrors: error.issues };
61
61
  } else if (
62
62
  error &&
63
63
  typeof error === 'object' &&
64
64
  'type' in error &&
65
65
  ((error instanceof Error && error.name === 'EntityHookError') ||
66
- (error as any).name === 'EntityHookError')
66
+ ('name' in error && error.name === 'EntityHookError'))
67
67
  ) {
68
68
  const entityError = error as EntityHookError;
69
69
  switch (entityError.type) {
@@ -104,7 +104,7 @@ export function handleError(error: unknown): never {
104
104
 
105
105
  throw new DoNotDevError(
106
106
  message,
107
- code as any,
107
+ code,
108
108
  details ? { details } : undefined
109
109
  );
110
110
  }
@@ -89,6 +89,7 @@ export function toISOString(timestamp: FirestoreTimestamp): string {
89
89
  * @since 0.0.1
90
90
  * @author AMBROISE PARK Consulting
91
91
  */
92
+ // 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)
92
93
  export function isTimestamp(value: any): value is FirestoreTimestamp {
93
94
  return (
94
95
  value &&
@@ -100,6 +101,23 @@ export function isTimestamp(value: any): value is FirestoreTimestamp {
100
101
  );
101
102
  }
102
103
 
104
+ /**
105
+ * Whether a value looks like a Firestore DocumentSnapshot (id, ref, data()).
106
+ */
107
+ function isDocumentSnapshotLike(value: object): value is {
108
+ id: unknown;
109
+ ref: unknown;
110
+ // why: Firestore DocumentSnapshot.data() contract; the return is not checked at runtime
111
+ data: () => Record<string, unknown> | undefined;
112
+ } {
113
+ return (
114
+ 'id' in value &&
115
+ 'ref' in value &&
116
+ 'data' in value &&
117
+ typeof value.data === 'function'
118
+ );
119
+ }
120
+
103
121
  /**
104
122
  * Recursively transforms Firestore data to application format by converting Timestamps to ISO strings.
105
123
  * @param data - The data to transform
@@ -110,6 +128,7 @@ export function isTimestamp(value: any): value is FirestoreTimestamp {
110
128
  * @since 0.0.1
111
129
  * @author AMBROISE PARK Consulting
112
130
  */
131
+ // 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)
113
132
  export function transformFirestoreData<T = any>(
114
133
  data: T,
115
134
  includeDocumentIds: boolean = false
@@ -121,12 +140,9 @@ export function transformFirestoreData<T = any>(
121
140
  includeDocumentIds &&
122
141
  typeof data === 'object' &&
123
142
  data !== null &&
124
- 'id' in data &&
125
- 'ref' in data &&
126
- 'data' in data &&
127
- typeof (data as any).data === 'function'
143
+ isDocumentSnapshotLike(data)
128
144
  ) {
129
- const doc = data as any;
145
+ const doc = data;
130
146
  const documentData = doc.data();
131
147
  return {
132
148
  id: doc.id,
@@ -146,8 +162,8 @@ export function transformFirestoreData<T = any>(
146
162
 
147
163
  // Handle objects recursively
148
164
  if (typeof data === 'object' && data !== null) {
149
- const transformed: Record<string, any> = {};
150
- for (const [key, value] of Object.entries(data as Record<string, any>)) {
165
+ const transformed: Record<string, unknown> = {};
166
+ for (const [key, value] of Object.entries(data)) {
151
167
  transformed[key] = transformFirestoreData(value);
152
168
  }
153
169
  return transformed as T;
@@ -168,6 +184,7 @@ export function transformFirestoreData<T = any>(
168
184
  * @since 0.0.1
169
185
  * @author AMBROISE PARK Consulting
170
186
  */
187
+ // 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)
171
188
  export function prepareForFirestore<T = any>(
172
189
  data: T,
173
190
  removeFields: string[] = []
@@ -183,8 +200,8 @@ export function prepareForFirestore<T = any>(
183
200
 
184
201
  // Handle objects recursively
185
202
  if (typeof data === 'object' && data !== null) {
186
- const prepared: Record<string, any> = {};
187
- for (const [key, value] of Object.entries(data as Record<string, any>)) {
203
+ const prepared: Record<string, unknown> = {};
204
+ for (const [key, value] of Object.entries(data)) {
188
205
  // Skip fields that should be removed
189
206
  if (removeFields.includes(key)) {
190
207
  continue;
@@ -9,6 +9,8 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import * as v from 'valibot';
13
+
12
14
  /** Configuration for authenticating with the GitHub API. */
13
15
  export interface GitHubApiConfig {
14
16
  accessToken: string;
@@ -51,6 +53,12 @@ export interface GitHubApiError {
51
53
  status?: number;
52
54
  }
53
55
 
56
+ /** Error body shape returned by the GitHub API on non-2xx responses (untrusted). */
57
+ const GitHubErrorBodySchema = v.object({
58
+ message: v.optional(v.string()),
59
+ documentation_url: v.optional(v.string()),
60
+ });
61
+
54
62
  /** Pattern for valid GitHub usernames, org names, repo names, and team slugs */
55
63
  const SAFE_GITHUB_NAME = /^[a-zA-Z0-9_.-]+$/;
56
64
 
@@ -158,8 +166,8 @@ export class GitHubApiService {
158
166
  method: 'GET',
159
167
  });
160
168
  return true;
161
- } catch (error: any) {
162
- if (error.message?.includes('404')) {
169
+ } catch (error) {
170
+ if (error instanceof Error && error.message.includes('404')) {
163
171
  return false;
164
172
  }
165
173
  console.error('Failed to check collaborator status:', error);
@@ -276,8 +284,8 @@ export class GitHubApiService {
276
284
  }
277
285
  );
278
286
  return true;
279
- } catch (error: any) {
280
- if (error.message?.includes('404')) {
287
+ } catch (error) {
288
+ if (error instanceof Error && error.message.includes('404')) {
281
289
  return false;
282
290
  }
283
291
  console.error('Failed to check team membership:', error);
@@ -310,7 +318,9 @@ export class GitHubApiService {
310
318
  });
311
319
 
312
320
  if (!response.ok) {
313
- const errorData = (await response.json().catch(() => ({}))) as any;
321
+ const errorBody: unknown = await response.json().catch(() => ({}));
322
+ const parsed = v.safeParse(GitHubErrorBodySchema, errorBody);
323
+ const errorData = parsed.success ? parsed.output : {};
314
324
  const error: GitHubApiError = {
315
325
  message:
316
326
  errorData.message ||
@@ -23,14 +23,15 @@
23
23
  * @author AMBROISE PARK Consulting
24
24
  */
25
25
 
26
- // Node-only metadata (pid, version) is added when running on Node; Deno runtimes
27
- // (Supabase Edge) log without it. Server-only by package: @donotdev/functions is
28
- // never imported by client code, so no runtime browser check (Supabase Edge
29
- // defines `window`, which made such a check throw on every edge function).
30
- const _isNodeEnv = typeof process !== 'undefined' && !!process.versions?.node;
26
+ // Server-only by package: @donotdev/functions is never imported by client code,
27
+ // so no runtime browser check (Supabase Edge defines `window`, which made such a
28
+ // check throw on every edge function).
31
29
 
32
30
  let sentryEnabled = false;
33
- let sentryClient: any = null;
31
+ let sentryClient: Pick<
32
+ typeof import('@sentry/node'),
33
+ 'captureException' | 'captureMessage'
34
+ > | null = null;
34
35
 
35
36
  // Initialize Sentry lazily to avoid Firebase Functions issues
36
37
  let sentryInitialized = false;
@@ -88,9 +89,9 @@ export interface LogEntry {
88
89
  level: LogLevel;
89
90
  message: string;
90
91
  timestamp: string;
91
- context?: Record<string, any>;
92
+ context?: Record<string, unknown>;
92
93
  error?: Error;
93
- metadata?: Record<string, any>;
94
+ metadata?: Record<string, unknown>;
94
95
  }
95
96
 
96
97
  /**
@@ -130,7 +131,7 @@ export const logger = {
130
131
  * @since 0.0.1
131
132
  * @author AMBROISE PARK Consulting
132
133
  */
133
- debug(message: string, context?: Record<string, any>): void {
134
+ debug(message: string, context?: Record<string, unknown>): void {
134
135
  this.log(LogLevel.DEBUG, message, context);
135
136
  },
136
137
 
@@ -143,7 +144,7 @@ export const logger = {
143
144
  * @since 0.0.1
144
145
  * @author AMBROISE PARK Consulting
145
146
  */
146
- info(message: string, context?: Record<string, any>): void {
147
+ info(message: string, context?: Record<string, unknown>): void {
147
148
  this.log(LogLevel.INFO, message, context);
148
149
  },
149
150
 
@@ -156,7 +157,7 @@ export const logger = {
156
157
  * @since 0.0.1
157
158
  * @author AMBROISE PARK Consulting
158
159
  */
159
- warn(message: string, context?: Record<string, any>): void {
160
+ warn(message: string, context?: Record<string, unknown>): void {
160
161
  this.log(LogLevel.WARN, message, context);
161
162
  },
162
163
 
@@ -169,7 +170,10 @@ export const logger = {
169
170
  * @since 0.0.1
170
171
  * @author AMBROISE PARK Consulting
171
172
  */
172
- async error(message: string, context?: Record<string, any>): Promise<void> {
173
+ async error(
174
+ message: string,
175
+ context?: Record<string, unknown>
176
+ ): Promise<void> {
173
177
  this.log(LogLevel.ERROR, message, context);
174
178
 
175
179
  // Initialize Sentry lazily if needed
@@ -201,7 +205,10 @@ export const logger = {
201
205
  * @since 0.0.1
202
206
  * @author AMBROISE PARK Consulting
203
207
  */
204
- async fatal(message: string, context?: Record<string, any>): Promise<void> {
208
+ async fatal(
209
+ message: string,
210
+ context?: Record<string, unknown>
211
+ ): Promise<void> {
205
212
  this.log(LogLevel.FATAL, message, context);
206
213
 
207
214
  // Initialize Sentry lazily if needed
@@ -236,26 +243,12 @@ export const logger = {
236
243
  * @since 0.0.1
237
244
  * @author AMBROISE PARK Consulting
238
245
  */
239
- log(level: LogLevel, message: string, context?: Record<string, any>): void {
246
+ log(
247
+ level: LogLevel,
248
+ message: string,
249
+ context?: Record<string, unknown>
250
+ ): void {
240
251
  const timestamp = new Date().toISOString();
241
- const logEntry: LogEntry = {
242
- level,
243
- message,
244
- timestamp,
245
- context,
246
- error: context?.error,
247
- metadata: {
248
- ...(_isNodeEnv
249
- ? {
250
- pid: process.pid,
251
- nodeVersion: process.version,
252
- platform: process.platform,
253
- }
254
- : {}),
255
- ...context?.metadata,
256
- },
257
- };
258
-
259
252
  // Format log entry for console output
260
253
  const levelName = LogLevel[level];
261
254
  const contextStr = context ? ` ${JSON.stringify(context)}` : '';
@@ -302,21 +295,27 @@ export const logger = {
302
295
  * @param context - Additional context to include in all logs
303
296
  * @returns Child logger instance
304
297
  */
305
- export function createChildLogger(context: Record<string, any>) {
298
+ export function createChildLogger(context: Record<string, unknown>) {
306
299
  return {
307
- debug: (message: string, additionalContext?: Record<string, any>) => {
300
+ debug: (message: string, additionalContext?: Record<string, unknown>) => {
308
301
  logger.debug(message, { ...context, ...additionalContext });
309
302
  },
310
- info: (message: string, additionalContext?: Record<string, any>) => {
303
+ info: (message: string, additionalContext?: Record<string, unknown>) => {
311
304
  logger.info(message, { ...context, ...additionalContext });
312
305
  },
313
- warn: (message: string, additionalContext?: Record<string, any>) => {
306
+ warn: (message: string, additionalContext?: Record<string, unknown>) => {
314
307
  logger.warn(message, { ...context, ...additionalContext });
315
308
  },
316
- error: async (message: string, additionalContext?: Record<string, any>) => {
309
+ error: async (
310
+ message: string,
311
+ additionalContext?: Record<string, unknown>
312
+ ) => {
317
313
  await logger.error(message, { ...context, ...additionalContext });
318
314
  },
319
- fatal: async (message: string, additionalContext?: Record<string, any>) => {
315
+ fatal: async (
316
+ message: string,
317
+ additionalContext?: Record<string, unknown>
318
+ ) => {
320
319
  await logger.fatal(message, { ...context, ...additionalContext });
321
320
  },
322
321
  };