@donotdev/functions 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/README.md +1 -1
  2. package/lib/chunks/chunk-522YXGDA.js +23 -0
  3. package/lib/chunks/chunk-522YXGDA.js.map +7 -0
  4. package/lib/chunks/chunk-7ODXXXES.js +151 -0
  5. package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
  6. package/lib/chunks/chunk-CP3NNKO5.js +22 -0
  7. package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
  8. package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
  9. package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
  10. package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
  11. package/lib/chunks/chunk-ICNQCRLV.js +22 -0
  12. package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
  13. package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
  14. package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
  15. package/lib/chunks/chunk-OKRR7ST5.js +22 -0
  16. package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
  17. package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
  18. package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
  19. package/lib/chunks/chunk-TJPJXJEK.js +22 -0
  20. package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
  21. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  22. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  23. package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
  24. package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
  25. package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
  26. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  27. package/lib/firebase/crud/aggregate.d.ts +1 -1
  28. package/lib/firebase/crud/create.d.ts +22 -1
  29. package/lib/firebase/crud/update.d.ts +27 -3
  30. package/lib/firebase/index.js +1 -1
  31. package/lib/firebase/index.js.map +3 -3
  32. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  33. package/lib/shared/billing/createCheckout.d.ts +1 -1
  34. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  35. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
  36. package/lib/shared/billing/index.d.ts +2 -0
  37. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  38. package/lib/shared/billing/stripePinned.d.ts +43 -0
  39. package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
  40. package/lib/shared/crud/bulkCore.d.ts +38 -10
  41. package/lib/shared/crud/index.d.ts +1 -0
  42. package/lib/shared/crud/written.d.ts +21 -0
  43. package/lib/shared/denoEnv.d.ts +25 -0
  44. package/lib/shared/github.d.ts +0 -8
  45. package/lib/shared/index.d.ts +0 -1
  46. package/lib/shared/index.js +1 -1
  47. package/lib/shared/logger.d.ts +14 -14
  48. package/lib/shared/utils/external/subscription.d.ts +0 -8
  49. package/lib/shared/utils.d.ts +13 -10
  50. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  51. package/lib/supabase/crud/bulk.d.ts +7 -0
  52. package/lib/supabase/crud/create.d.ts +5 -9
  53. package/lib/supabase/crud/entityStore.d.ts +67 -14
  54. package/lib/supabase/crud/update.d.ts +7 -10
  55. package/lib/supabase/index.d.ts +5 -0
  56. package/lib/supabase/index.js +1 -1
  57. package/lib/supabase/index.js.map +4 -4
  58. package/lib/vercel/api/crud/create.d.ts +6 -1
  59. package/lib/vercel/api/crud/update.d.ts +8 -1
  60. package/lib/vercel/api/index.js +1 -1
  61. package/lib/vercel/api/index.js.map +3 -3
  62. package/package.json +9 -9
  63. package/src/firebase/auth/getCustomClaims.ts +2 -0
  64. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  65. package/src/firebase/auth/removeCustomClaims.ts +33 -1
  66. package/src/firebase/auth/setCustomClaims.ts +6 -0
  67. package/src/firebase/baseFunction.ts +5 -2
  68. package/src/firebase/billing/changePlan.ts +6 -5
  69. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  70. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  71. package/src/firebase/billing/webhookHandler.ts +4 -4
  72. package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
  73. package/src/firebase/crud/__tests__/create.test.ts +64 -0
  74. package/src/firebase/crud/__tests__/update.test.ts +97 -0
  75. package/src/firebase/crud/aggregate.ts +37 -19
  76. package/src/firebase/crud/bulk.ts +30 -10
  77. package/src/firebase/crud/create.ts +40 -26
  78. package/src/firebase/crud/delete.ts +6 -1
  79. package/src/firebase/crud/get.ts +12 -14
  80. package/src/firebase/crud/list.ts +23 -12
  81. package/src/firebase/crud/update.ts +49 -25
  82. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  83. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  84. package/src/firebase/oauth/exchangeToken.ts +4 -0
  85. package/src/firebase/oauth/getConnections.ts +1 -1
  86. package/src/firebase/oauth/githubAccess.ts +3 -0
  87. package/src/firebase/oauth/refreshToken.ts +1 -0
  88. package/src/firebase/registerCrudFunctions.ts +1 -0
  89. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  90. package/src/shared/__tests__/bulkCore.test.ts +191 -0
  91. package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
  92. package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
  93. package/src/shared/__tests__/utils.test.ts +0 -30
  94. package/src/shared/ai/classifyAIError.ts +18 -10
  95. package/src/shared/ai/createAIRoute.ts +2 -1
  96. package/src/shared/ai/resolveModelTier.ts +2 -1
  97. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  98. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  99. package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
  100. package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
  101. package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
  102. package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
  103. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  104. package/src/shared/billing/checkoutValidation.ts +19 -2
  105. package/src/shared/billing/createCheckout.ts +56 -11
  106. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  107. package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
  108. package/src/shared/billing/index.ts +2 -0
  109. package/src/shared/billing/orderWebhook.ts +69 -1
  110. package/src/shared/billing/stripeClient.ts +2 -1
  111. package/src/shared/billing/stripePinned.ts +71 -0
  112. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  113. package/src/shared/billing/verifyOrderCheckout.ts +142 -0
  114. package/src/shared/billing/webhookHandler.ts +5 -1
  115. package/src/shared/crud/bulkCore.ts +112 -82
  116. package/src/shared/crud/index.ts +1 -0
  117. package/src/shared/crud/written.ts +56 -0
  118. package/src/shared/denoEnv.ts +29 -0
  119. package/src/shared/email/createEmailRoute.ts +2 -2
  120. package/src/shared/errorHandling.ts +8 -8
  121. package/src/shared/firebase.ts +26 -9
  122. package/src/shared/github.ts +15 -5
  123. package/src/shared/index.d.ts +0 -9
  124. package/src/shared/index.ts +0 -1
  125. package/src/shared/logger.ts +37 -38
  126. package/src/shared/utils/external/date.ts +4 -4
  127. package/src/shared/utils/external/subscription.ts +2 -89
  128. package/src/shared/utils/firebaseHelpers.ts +2 -0
  129. package/src/shared/utils/internal/idempotency.ts +3 -0
  130. package/src/shared/utils/internal/monitoring.ts +6 -5
  131. package/src/shared/utils/internal/validation.ts +2 -0
  132. package/src/shared/utils/schemaValidation.ts +1 -0
  133. package/src/shared/utils/validation.ts +10 -20
  134. package/src/shared/utils.ts +4 -42
  135. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  136. package/src/supabase/__tests__/bulk.test.ts +60 -2
  137. package/src/supabase/__tests__/create.test.ts +86 -0
  138. package/src/supabase/__tests__/entityStore.test.ts +91 -25
  139. package/src/supabase/__tests__/update.test.ts +107 -0
  140. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  141. package/src/supabase/auth/deleteAccount.ts +72 -5
  142. package/src/supabase/auth/removeCustomClaims.ts +7 -2
  143. package/src/supabase/auth/setCustomClaims.ts +4 -2
  144. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  145. package/src/supabase/crud/aggregate.ts +85 -72
  146. package/src/supabase/crud/bulk.ts +50 -0
  147. package/src/supabase/crud/create.ts +27 -33
  148. package/src/supabase/crud/delete.ts +2 -1
  149. package/src/supabase/crud/entityStore.ts +107 -18
  150. package/src/supabase/crud/get.ts +5 -13
  151. package/src/supabase/crud/list.ts +28 -21
  152. package/src/supabase/crud/update.ts +29 -24
  153. package/src/supabase/edgeFunction.ts +2 -1
  154. package/src/supabase/email/createEmailFunction.ts +2 -1
  155. package/src/supabase/index.ts +8 -0
  156. package/src/supabase/oauth/exchangeToken.ts +1 -0
  157. package/src/supabase/oauth/getConnections.ts +1 -1
  158. package/src/supabase/oauth/refreshToken.ts +1 -0
  159. package/src/supabase/registerCrudFunctions.ts +1 -0
  160. package/src/supabase/utils/idempotency.ts +1 -1
  161. package/src/supabase/utils/monitoring.ts +1 -0
  162. package/src/vercel/__tests__/bulk.test.ts +16 -8
  163. package/src/vercel/api/billing/change-plan.ts +6 -5
  164. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  165. package/src/vercel/api/crud/bulk.ts +34 -6
  166. package/src/vercel/api/crud/create.ts +22 -21
  167. package/src/vercel/api/crud/delete.ts +5 -2
  168. package/src/vercel/api/crud/get.ts +10 -8
  169. package/src/vercel/api/crud/list.ts +10 -8
  170. package/src/vercel/api/crud/update.ts +25 -20
  171. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  172. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  173. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  174. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  175. package/src/vercel/baseFunction.ts +5 -1
  176. package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
  177. package/lib/chunks/chunk-2IFFIUFV.js +0 -23
  178. package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
  179. package/lib/chunks/chunk-FQSQGOBN.js +0 -22
  180. package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
  181. package/lib/chunks/chunk-G4FO76EA.js +0 -22
  182. package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
  183. package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
  184. package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
  185. package/lib/chunks/chunk-M4JV2JCF.js +0 -22
  186. package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
  187. package/lib/chunks/chunk-OZX5ZG44.js +0 -22
  188. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  189. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  190. package/lib/chunks/chunk-UYI56E6Q.js +0 -151
  191. package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
  192. package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
  193. package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
  194. package/lib/shared/schema.d.ts +0 -56
  195. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  196. package/src/shared/__tests__/schema.test.ts +0 -219
  197. package/src/shared/schema.ts +0 -192
  198. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  199. package/src/shared/utils/functionWrapper.ts +0 -73
  200. /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
  201. /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
  202. /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
  203. /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.js.map} +0 -0
@@ -32,7 +32,7 @@ export declare function validateCheckoutUrl(url: string, name: string): void;
32
32
  * Sanitize client metadata: enforce string values, strip script injection.
33
33
  * Length limits are checked on the final metadata ({@link assertStripeMetadata}).
34
34
  */
35
- export declare function sanitizeMetadata(metadata: Record<string, any>): Record<string, string>;
35
+ export declare function sanitizeMetadata(metadata: Record<string, unknown>): Record<string, string>;
36
36
  /**
37
37
  * Throw a validation error when metadata exceeds Stripe's limits
38
38
  * ({@link STRIPE_METADATA_LIMITS}), instead of letting Stripe answer 400.
@@ -68,7 +68,7 @@ export interface AuthCheckoutProvider {
68
68
  * 3. `beforeCheckout` hook (block/allow)
69
69
  * 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line
70
70
  * and may set per-order session options (`ResolvedOrder.session`: tax rates,
71
- * payment methods, expiry, invoice footer)
71
+ * payment methods, expiry, invoice footer, existing Stripe customer)
72
72
  * 5. Validate metadata against Stripe limits, create the session through the provider
73
73
  *
74
74
  * Server-owned metadata (`userId`, `billingConfigKey`, `orderId`) is written after
@@ -1,4 +1,4 @@
1
- import type { BillingAuthProvider } from '@donotdev/core/server';
1
+ import type { BillingAuthProvider, StripeBackConfig } from '@donotdev/core/server';
2
2
  /**
3
3
  * Cancel user subscription at period end
4
4
  *
@@ -17,7 +17,7 @@ export declare function cancelUserSubscription(userId: string, authProvider: Bil
17
17
  * @since 0.0.1
18
18
  * @author AMBROISE PARK Consulting
19
19
  */
20
- export declare function changeUserPlan(userId: string, newPriceId: string, billingConfigKey: string, billingConfig: Record<string, any>, authProvider: BillingAuthProvider): Promise<{
20
+ export declare function changeUserPlan(userId: string, newPriceId: string, billingConfigKey: string, billingConfig: StripeBackConfig, authProvider: BillingAuthProvider): Promise<{
21
21
  success: boolean;
22
22
  newTier: string;
23
23
  newPrice: number;
@@ -1,15 +1,9 @@
1
- /**
2
- * @fileoverview User subscription update utilities
3
- * @description Functions for updating user subscription data
4
- *
5
- * @version 0.1.0
6
- * @since 0.0.1
7
- * @author AMBROISE PARK Consulting
8
- */
9
1
  import type { BillingAuthProvider, SubscriptionUpdate } from '@donotdev/core/server';
10
2
  /**
11
3
  * Platform-agnostic subscription update using dependency injection
12
4
  * Works on Firebase Functions, Vercel, AWS Lambda, etc.
5
+ * Validates canonical auth claims; one-time payments may have no billing customer.
6
+ * Billing identifiers are preserved when supplied, never fabricated from a user ID.
13
7
  *
14
8
  * @version 0.1.0
15
9
  * @since 0.0.1
@@ -7,6 +7,8 @@
7
7
  * @author AMBROISE PARK Consulting
8
8
  */
9
9
  export * from './createCheckout.js';
10
+ /** Read-only order verification and its separate retrieval/binding dependencies. */
11
+ export * from './verifyOrderCheckout.js';
10
12
  export * from './helpers/index.js';
11
13
  export * from './webhookHandler.js';
12
14
  export * from './idempotency.js';
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * @fileoverview StripeOrder webhook handling
3
3
  * @description Maps Checkout Session events of one-time, multi-line orders to the
4
- * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`).
4
+ * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`), and
5
+ * `customer.tax_id.updated` to `onTaxIdUpdated`.
5
6
  * Hook errors propagate: the webhook answers non-2xx and Stripe retries.
6
7
  *
7
8
  * @version 0.2.0
@@ -9,7 +10,7 @@
9
10
  * @author AMBROISE PARK Consulting
10
11
  */
11
12
  import type Stripe from 'stripe';
12
- import type { CheckoutSessionSnapshot, PaidLineItem, StripeOrderBackItem } from '@donotdev/core/server';
13
+ import type { CheckoutSessionSnapshot, PaidLineItem, StripeBackConfig, StripeOrderBackItem, TaxIdSnapshot } from '@donotdev/core/server';
13
14
  /**
14
15
  * Checkout Session events that concern orders.
15
16
  *
@@ -73,3 +74,29 @@ export declare function listPaidLineItems(stripe: Stripe, sessionId: string): Pr
73
74
  * @author AMBROISE PARK Consulting
74
75
  */
75
76
  export declare function handleOrderSessionEvent(eventType: OrderSessionEventType, eventId: string, apiVersion: string | null, session: Stripe.Checkout.Session, billingConfigKey: string, orderItem: StripeOrderBackItem, stripe: Stripe): Promise<void>;
77
+ /**
78
+ * Map a Stripe TaxId to the provider-neutral snapshot given to `onTaxIdUpdated`.
79
+ *
80
+ * @param taxId - TaxId from a `customer.tax_id.updated` event
81
+ * @returns Snapshot
82
+ *
83
+ * @version 0.2.0
84
+ * @since 0.2.3
85
+ * @author AMBROISE PARK Consulting
86
+ */
87
+ export declare function toTaxIdSnapshot(taxId: Stripe.TaxId): TaxIdSnapshot;
88
+ /**
89
+ * Handle `customer.tax_id.updated`: run `onTaxIdUpdated` of every StripeOrder item
90
+ * that defines it, once per distinct function. Called by `processWebhook` after
91
+ * signature verification and idempotency reservation (same path as order events).
92
+ *
93
+ * @param eventId - Stripe event ID
94
+ * @param taxId - TaxId from the event
95
+ * @param config - App back config
96
+ * @throws When a hook throws (the webhook answers non-2xx and Stripe retries)
97
+ *
98
+ * @version 0.2.0
99
+ * @since 0.2.3
100
+ * @author AMBROISE PARK Consulting
101
+ */
102
+ export declare function handleTaxIdUpdated(eventId: string, taxId: Stripe.TaxId, config: StripeBackConfig): Promise<void>;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @fileoverview Typed access to Stripe fields of the pinned API version
3
+ * @description The Stripe SDK types follow the latest API version only, while
4
+ * requests run at `STRIPE_API_VERSION_PIN` (pre-basil). Fields that basil
5
+ * moved (subscription period, invoice subscription) are read here, through one
6
+ * documented cast, instead of `as any` at every call site. Internal: not
7
+ * re-exported from any package entry.
8
+ *
9
+ * @version 0.1.0
10
+ * @since 0.2.2
11
+ * @author AMBROISE PARK Consulting
12
+ */
13
+ import type Stripe from 'stripe';
14
+ /** Subscription fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */
15
+ interface PinnedSubscriptionFields {
16
+ current_period_start: number;
17
+ current_period_end: number;
18
+ }
19
+ /**
20
+ * Period fields of a subscription at the pinned API version.
21
+ *
22
+ * @version 0.1.0
23
+ * @since 0.2.2
24
+ * @author AMBROISE PARK Consulting
25
+ */
26
+ export declare function pinnedSubscriptionPeriod(subscription: Stripe.Subscription): PinnedSubscriptionFields;
27
+ /**
28
+ * Subscription id of an invoice at the pinned API version.
29
+ *
30
+ * @version 0.1.0
31
+ * @since 0.2.2
32
+ * @author AMBROISE PARK Consulting
33
+ */
34
+ export declare function pinnedInvoiceSubscriptionId(invoice: Stripe.Invoice): string | null;
35
+ /**
36
+ * Narrows a value to one of a readonly list of literals.
37
+ *
38
+ * @version 0.1.0
39
+ * @since 0.2.2
40
+ * @author AMBROISE PARK Consulting
41
+ */
42
+ export declare function isOneOf<T extends string>(values: readonly T[], value: string): value is T;
43
+ export {};
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Read-only StripeOrder verification for an authenticated return-page handler.
3
+ * Persisted app binding is mandatory; Stripe metadata is corroboration, not authority.
4
+ */
5
+ import type Stripe from 'stripe';
6
+ import type { StripeBackConfig, VerifyOrderCheckoutRequest, VerifyOrderCheckoutResult } from '@donotdev/core/server';
7
+ /** App-owned persisted association, read from authoritative storage (never request metadata). */
8
+ export interface OrderCheckoutBinding {
9
+ orderId: string;
10
+ userId: string;
11
+ sessionId: string;
12
+ billingConfigKey: string;
13
+ }
14
+ /**
15
+ * Read dependencies only. Separate from StripeSessionProvider so existing checkout
16
+ * providers remain compatible. userId must come from verified handler context.
17
+ */
18
+ export interface VerifyOrderCheckoutDependencies {
19
+ userId: string;
20
+ billingConfig: StripeBackConfig;
21
+ /** Retrieve from Stripe using server credentials; no browser-supplied session objects. */
22
+ retrieveStripeSession(sessionId: string): Promise<Pick<Stripe.Checkout.Session, 'id' | 'mode' | 'status' | 'payment_status' | 'metadata'>>;
23
+ /**
24
+ * Read the persisted order/session binding, scoped to the authenticated owner
25
+ * and config. Return absence if not authorized/found; never infer it from Stripe.
26
+ * The algorithm independently checks every returned binding field.
27
+ */
28
+ resolveOrderBinding(request: VerifyOrderCheckoutRequest & {
29
+ userId: string;
30
+ }): Promise<OrderCheckoutBinding | null | undefined>;
31
+ }
32
+ /**
33
+ * Verify an owner's StripeOrder session against server config and persisted binding.
34
+ * All validation, authorization and dependency failures expose the same safe error.
35
+ * Server diagnostics contain fixed stage/category labels only, never dependency
36
+ * errors or request/customer data. Logging failure cannot replace the public error.
37
+ * No writes, checkout hooks or fulfillment hooks run. A successful read reports
38
+ * payment state only: complete/unpaid is pending; paid/no_payment_required does not
39
+ * prove onOrderPaid has run. Existing webhook fulfillment remains authoritative.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * // Inside createSupabaseHandler(..., v.unknown(), (data, ctx) => ...)
44
+ * // The algorithm performs mandatory request validation itself.
45
+ * return verifyOrderCheckoutAlgorithm(data, {
46
+ * userId: ctx.uid,
47
+ * billingConfig,
48
+ * retrieveStripeSession: (id) => stripe.checkout.sessions.retrieve(id),
49
+ * resolveOrderBinding, // app-owned authoritative, read-only resolver
50
+ * });
51
+ * ```
52
+ */
53
+ export declare function verifyOrderCheckoutAlgorithm(input: unknown, dependencies: VerifyOrderCheckoutDependencies): Promise<VerifyOrderCheckoutResult>;
@@ -27,11 +27,13 @@ export type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;
27
27
  /**
28
28
  * A prepared insert row passed to the caller-supplied `transact` callback.
29
29
  * When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted
30
- * value; otherwise it carries whatever id (if any) the client supplied and
31
- * the storage layer is expected to mint its own.
30
+ * value (a client id never addresses a stored document). Otherwise it is the
31
+ * id the client supplied (a pre-minted id other rows reference, BULK_ACROSS.md
32
+ * "Pre-Minted IDs"), also kept on `row.id`, or the empty string when the
33
+ * storage layer mints its own.
32
34
  */
33
35
  export interface PreparedInsert {
34
- /** Minted insert id, or the empty string when the target mints its own. */
36
+ /** Minted id, else the client-supplied id, else the empty string (the target mints its own). */
35
37
  id: string;
36
38
  /** Fully stamped row ready for storage. */
37
39
  row: Record<string, unknown>;
@@ -66,10 +68,26 @@ export interface ExecuteBulkParams<TRow = unknown> {
66
68
  ops: BulkRequest;
67
69
  /** Valibot schema validating each insert row. */
68
70
  createSchema: BulkRowSchema;
69
- /** Valibot schema validating each insert row when status === 'draft'. */
71
+ /**
72
+ * `createSchemas(entity).draft`: drafts saved incomplete (CRUD rule 5). Required as soon
73
+ * as a draft row is sent: a draft without it is rejected (`invalid-argument`), never
74
+ * validated as a create.
75
+ */
70
76
  draftCreateSchema?: BulkRowSchema;
71
- /** Valibot schema validating each update patch. */
77
+ /** `createSchemas(entity).update`: update patches (CRUD rules 2, 5). */
72
78
  updateSchema: BulkRowSchema;
79
+ /**
80
+ * Reads the stored rows of the updated ids (application field names, keyed by id).
81
+ * Called once, before validation, when the bulk carries updates: the stored row
82
+ * gives each patch its status and a published draft its whole record
83
+ * (`prepareUpdate`, as on the client). An updated id missing
84
+ * from the result is rejected (`not-found`). Required as soon as the bulk carries
85
+ * updates: an update without it is rejected (`internal`, a configuration error),
86
+ * never validated by its patch status alone. Every target passes it: Firestore,
87
+ * Supabase and Vercel read their store; the GraphQL / REST-CRUD server aids
88
+ * forward the consumer's `readStored` option.
89
+ */
90
+ readStored?: (ids: readonly string[]) => Promise<ReadonlyMap<string, Record<string, unknown>>>;
73
91
  /** Per-bucket required roles. Missing entries are treated as "no bucket allowed". */
74
92
  access: EntityAccessConfig;
75
93
  /** Authenticated caller id (for metadata + audit). */
@@ -137,12 +155,17 @@ export interface ExecuteBulkParams<TRow = unknown> {
137
155
  * 4. Per-bucket ACL — for each populated bucket, asserts the caller's role
138
156
  * clears the corresponding `access.{create|update|delete}`. A missing
139
157
  * role on a populated bucket is a configuration error and is rejected.
140
- * 5. Per-row validation — inserts against `createSchema`, updates against
141
- * `updateSchema`. The first failure throws a `DoNotDevError` prefixed
142
- * with `inserts[i]` or `updates[i]` so callers can pinpoint the row.
158
+ * 5. Per-row validation — the CRUD rules (`prepareCreate` / `prepareUpdate`,
159
+ * core/schemas crud/), the stored rows read once with `readStored` (updates
160
+ * without it → `internal`; an updated id with no stored row → `not-found`).
161
+ * The first failure throws `validation-failed` (wire: `invalid-argument`)
162
+ * naming `inserts[i]` / `updates[i]`. Unknown fields are logged, not written.
163
+ * What is stored is the rules' `written`, never the raw row.
143
164
  * 6. Id minting — if `mintInsertId` is supplied, every insert gets a fresh
144
- * id stamped onto its {@link PreparedInsert}. Otherwise `id` is `""` and
145
- * the storage layer mints its own.
165
+ * id stamped onto its {@link PreparedInsert}. Otherwise a client-supplied
166
+ * `id` is kept (on the row and as `PreparedInsert.id`; the create schema
167
+ * excludes it, it is restored after validation), else `id` is `""` and the
168
+ * storage layer mints its own.
146
169
  * 7. Metadata stamping — `stampInsertMetadata` / `stampUpdateMetadata` run
147
170
  * per row / per patch if provided.
148
171
  * 8. `transact(prepared)` runs exactly once. Must be atomic. Throws
@@ -164,8 +187,12 @@ export interface ExecuteBulkParams<TRow = unknown> {
164
187
  * @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row
165
188
  * validation failure, or collision (wrapped for callers that only rethrow
166
189
  * `DoNotDevError`).
190
+ * @throws {DoNotDevError} `not-found` when an updated id has no stored row
191
+ * (`readStored`).
167
192
  * @throws {DoNotDevError} `permission-denied` when the caller's role cannot
168
193
  * satisfy a populated bucket's access requirement.
194
+ * @throws {DoNotDevError} `internal` when the bulk carries updates but no
195
+ * `readStored` is configured.
169
196
  * @throws {DoNotDevError} `internal` when the `transact` return value fails
170
197
  * {@link BulkResponseSchema}.
171
198
  *
@@ -182,6 +209,7 @@ export interface ExecuteBulkParams<TRow = unknown> {
182
209
  * access,
183
210
  * uid,
184
211
  * userRole,
212
+ * readStored: async (ids) => new Map((await db.getRows(ids)).map((row) => [row.id, row])),
185
213
  * mintInsertId: () => crypto.randomUUID(),
186
214
  * stampInsertMetadata: (row, uid) => ({
187
215
  * ...row,
@@ -11,3 +11,4 @@
11
11
  * @author AMBROISE PARK Consulting
12
12
  */
13
13
  export { executeBulk, type ExecuteBulkParams, type PreparedBulk, type PreparedInsert, type PreparedUpdate, type BulkRowSchema, } from './bulkCore.js';
14
+ export { writtenOf } from './written.js';
@@ -0,0 +1,21 @@
1
+ import type { PreparedWrite } from '@donotdev/core/server';
2
+ /**
3
+ * The values a server write stores.
4
+ *
5
+ * @param result - The CRUD rule result
6
+ * @param collection - Collection written (named in the log and the error)
7
+ * @param locator - Write site / row (e.g. `update`, `inserts[2]`)
8
+ * @returns The rule's `written`
9
+ * @throws {DoNotDevError} `invalid-argument` with `details.validationErrors` (the server wire
10
+ * contract, a Firebase `FunctionsErrorCode`) when the write is invalid
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const row = writtenOf(prepareCreate(schemas, payload), collection, 'create');
15
+ * ```
16
+ *
17
+ * @version 0.1.0
18
+ * @since 0.3.0
19
+ * @author AMBROISE PARK Consulting
20
+ */
21
+ export declare function writtenOf(result: PreparedWrite, collection: string, locator: string): Record<string, unknown>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @fileoverview Typed access to the Deno env from cross-runtime code
3
+ * @description Supabase Edge Functions run on Deno, Firebase/Vercel on Node.
4
+ * This package compiles against the Node lib types, which have no `Deno`
5
+ * global. Internal: not re-exported from any package entry.
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.2.2
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+ /** The part of the Deno namespace read by this package. */
12
+ interface DenoEnvNamespace {
13
+ env?: {
14
+ get(key: string): string | undefined;
15
+ };
16
+ }
17
+ /**
18
+ * Deno env accessor, when running on Deno.
19
+ *
20
+ * @version 0.1.0
21
+ * @since 0.2.2
22
+ * @author AMBROISE PARK Consulting
23
+ */
24
+ export declare function getDenoEnv(): DenoEnvNamespace['env'];
25
+ export {};
@@ -1,11 +1,3 @@
1
- /**
2
- * @fileoverview GitHub API Service for functions
3
- * @description Server-safe GitHub API utilities for repository management
4
- *
5
- * @version 0.1.0
6
- * @since 0.0.1
7
- * @author AMBROISE PARK Consulting
8
- */
9
1
  /** Configuration for authenticating with the GitHub API. */
10
2
  export interface GitHubApiConfig {
11
3
  accessToken: string;
@@ -9,7 +9,6 @@
9
9
  export * from './errorHandling.js';
10
10
  export * from './github.js';
11
11
  export * from './metadata.js';
12
- export * from './schema.js';
13
12
  export * from './utils/index.js';
14
13
  export * from './crud/index.js';
15
14
  export * from './ai/index.js';
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{A as E,B as F,C as G,D as N,E as O,F as P,G as $,H as aa,I as ba,J as Aa,K as Ba,L as Ca,M as Da,N as Ea,O as Fa,P as Ga,a as c,b as d,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y,v as z,w as A,x as B,y as C,z as D}from"../chunks/chunk-LSM5Y2E5.js";import{a as H,b as I,c as J,d as K,e as L,f as M,g as ua,h as xa}from"../chunks/chunk-OZX5ZG44.js";import{a as e,b as f,c as ca,d as ya,e as za}from"../chunks/chunk-M4JV2JCF.js";import{a as b,b as da,c as ea,d as fa,e as ga,f as ha,i as ia,j as ja,k as ka,l as la,m as ma,n as na,o as oa,p as pa,q as qa,r as ra,s as sa,u as ta,v as va,w as wa}from"../chunks/chunk-UYI56E6Q.js";import"../chunks/chunk-2IFFIUFV.js";import{L as a}from"../chunks/chunk-G4FO76EA.js";import{a as Q,b as R,c as S,d as T,e as U}from"../chunks/chunk-2A4FPYNB.js";import{a as V,b as W,c as X,d as Y,e as Z,f as _}from"../chunks/chunk-PJCJ5H2O.js";import"../chunks/chunk-PWAGW4R6.js";import"../chunks/chunk-AYY7UXNI.js";export{H as AuthBackendSchema,_ as DEFAULT_RATE_LIMITS,a as DoNotDevError,c as GitHubApiService,ia as MIN_ORDER_API_VERSION,ja as ORDER_ID_METADATA_KEY,ka as PRODUCT_ID_METADATA_KEY,ra as RESERVATION_LEASE_MS,qa as ReservationLostError,j as StripeValidationSchemas,va as WEBHOOK_EVENTS_SQL,sa as WEBHOOK_EVENT_RETENTION_MS,K as assertAdmin,J as assertAuthenticated,da as calculateCost,C as calculateSubscriptionEndDate,F as cancelUserSubscription,O as checkIdempotency,R as checkPaymentFailureRate,S as checkPaymentVolume,V as checkRateLimit,W as checkRateLimitWithFirestore,ga as classifyAIError,U as cleanupOldMetrics,oa as createCheckoutAlgorithm,x as createFirebaseCallable,v as createFirebaseFunction,y as createFirebaseFunctionExports,ua as createFirestoreIdempotencyStore,d as createGitHubApiService,xa as createInMemoryIdempotencyStore,e as createMetadata,za as createResendProvider,wa as createSupabaseIdempotencyStore,Ca as createTimestamp,A as createVercelApiHandler,w as createVercelFunction,z as createVercelHandler,Aa as exchangeTokenAlgorithm,ca as executeBulk,i as filterVisibleFields,D as findReferences,T as getPaymentMetricsSummary,Z as getRateLimitStatus,E as getTierFromPriceId,G as getUserSubscription,h as getVisibleFields,Ba as grantAccessAlgorithm,ea as handleAIRequest,ya as handleEmailRequest,b as handleError,na as handleOrderSessionEvent,N as initializeFirebaseAdmin,g as isFieldVisible,Ea as isTimestamp,ma as listPaidLineItems,ha as mapClassifiedToHTTP,I as parseAuthBackend,Ga as prepareForFirestore,ta as processWebhook,Q as recordPaymentMetrics,X as resetRateLimit,Y as resetRateLimitInFirestore,fa as resolveModelForTier,$ as safeJsonParse,P as storeIdempotencyResult,la as toCheckoutSessionSnapshot,B as toISOString,Da as toTimestamp,Fa as transformFirestoreData,f as updateMetadata,pa as updateUserSubscription,aa as validateCollectionName,ba as validateDocument,n as validateEmail,m as validateGitHubUsername,r as validateMetadata,l as validatePurchaseRequest,s as validateRequestData,o as validateStripePriceId,p as validateStripeSessionId,q as validateUrl,k as validateWebhookEvent,M as verifyAuthToken,L as verifyToken,t as withSchemaValidation,u as withVercelSchemaValidation};
21
+ import{A as K,B as L,C as M,D as Y,E as Z,F as _,G as Ba,H as Ca,I as Da,J as Ea,K as Fa,L as Ga,M as Ha,a as c,b as d,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y,v as z,w as A,x as B,y as C,z as D}from"../chunks/chunk-CP3NNKO5.js";import{a as E,b as F,c as G,d as H,e as I,f as J,g as va,h as ya}from"../chunks/chunk-TJPJXJEK.js";import{a as e,b as f,c as $,d as aa,e as pa,f as za,g as Aa}from"../chunks/chunk-PDBNKSBQ.js";import{A as xa,a as b,b as ba,d as ca,e as da,f as ea,g as fa,j as ga,k as ha,l as ia,m as ja,n as ka,o as la,p as ma,q as na,r as oa,s as qa,t as ra,u as sa,v as ta,y as ua,z as wa}from"../chunks/chunk-7ODXXXES.js";import"../chunks/chunk-522YXGDA.js";import{S as a}from"../chunks/chunk-ICNQCRLV.js";import{a as N,b as O,c as P,d as Q,e as R}from"../chunks/chunk-CVYSXC27.js";import{a as S,b as T,c as U,d as V,e as W,f as X}from"../chunks/chunk-HZM5X5A7.js";import"../chunks/chunk-W6W4L44F.js";import"../chunks/chunk-AYY7UXNI.js";export{E as AuthBackendSchema,X as DEFAULT_RATE_LIMITS,a as DoNotDevError,c as GitHubApiService,ga as MIN_ORDER_API_VERSION,ha as ORDER_ID_METADATA_KEY,ia as PRODUCT_ID_METADATA_KEY,sa as RESERVATION_LEASE_MS,ra as ReservationLostError,g as StripeValidationSchemas,wa as WEBHOOK_EVENTS_SQL,ta as WEBHOOK_EVENT_RETENTION_MS,H as assertAdmin,G as assertAuthenticated,ba as calculateCost,z as calculateSubscriptionEndDate,C as cancelUserSubscription,L as checkIdempotency,O as checkPaymentFailureRate,P as checkPaymentVolume,S as checkRateLimit,T as checkRateLimitWithFirestore,ea as classifyAIError,R as cleanupOldMetrics,oa as createCheckoutAlgorithm,u as createFirebaseCallable,s as createFirebaseFunction,v as createFirebaseFunctionExports,va as createFirestoreIdempotencyStore,d as createGitHubApiService,ya as createInMemoryIdempotencyStore,e as createMetadata,Aa as createResendProvider,xa as createSupabaseIdempotencyStore,Da as createTimestamp,x as createVercelApiHandler,t as createVercelFunction,w as createVercelHandler,Ba as exchangeTokenAlgorithm,aa as executeBulk,A as findReferences,Q as getPaymentMetricsSummary,W as getRateLimitStatus,B as getTierFromPriceId,D as getUserSubscription,Ca as grantAccessAlgorithm,ca as handleAIRequest,za as handleEmailRequest,b as handleError,la as handleOrderSessionEvent,na as handleTaxIdUpdated,K as initializeFirebaseAdmin,Fa as isTimestamp,ka as listPaidLineItems,fa as mapClassifiedToHTTP,F as parseAuthBackend,Ha as prepareForFirestore,ua as processWebhook,N as recordPaymentMetrics,U as resetRateLimit,V as resetRateLimitInFirestore,da as resolveModelForTier,Y as safeJsonParse,M as storeIdempotencyResult,ja as toCheckoutSessionSnapshot,y as toISOString,ma as toTaxIdSnapshot,Ea as toTimestamp,Ga as transformFirestoreData,f as updateMetadata,qa as updateUserSubscription,Z as validateCollectionName,_ as validateDocument,k as validateEmail,j as validateGitHubUsername,o as validateMetadata,i as validatePurchaseRequest,p as validateRequestData,l as validateStripePriceId,m as validateStripeSessionId,n as validateUrl,h as validateWebhookEvent,J as verifyAuthToken,pa as verifyOrderCheckoutAlgorithm,I as verifyToken,q as withSchemaValidation,r as withVercelSchemaValidation,$ as writtenOf};
22
22
  //# sourceMappingURL=index.js.map
@@ -15,9 +15,9 @@ export interface LogEntry {
15
15
  level: LogLevel;
16
16
  message: string;
17
17
  timestamp: string;
18
- context?: Record<string, any>;
18
+ context?: Record<string, unknown>;
19
19
  error?: Error;
20
- metadata?: Record<string, any>;
20
+ metadata?: Record<string, unknown>;
21
21
  }
22
22
  /**
23
23
  * Server-side logger with Sentry integration
@@ -56,7 +56,7 @@ export declare const logger: {
56
56
  * @since 0.0.1
57
57
  * @author AMBROISE PARK Consulting
58
58
  */
59
- debug(message: string, context?: Record<string, any>): void;
59
+ debug(message: string, context?: Record<string, unknown>): void;
60
60
  /**
61
61
  * Log informational messages
62
62
  * @param message - Log message
@@ -66,7 +66,7 @@ export declare const logger: {
66
66
  * @since 0.0.1
67
67
  * @author AMBROISE PARK Consulting
68
68
  */
69
- info(message: string, context?: Record<string, any>): void;
69
+ info(message: string, context?: Record<string, unknown>): void;
70
70
  /**
71
71
  * Log warning messages
72
72
  * @param message - Log message
@@ -76,7 +76,7 @@ export declare const logger: {
76
76
  * @since 0.0.1
77
77
  * @author AMBROISE PARK Consulting
78
78
  */
79
- warn(message: string, context?: Record<string, any>): void;
79
+ warn(message: string, context?: Record<string, unknown>): void;
80
80
  /**
81
81
  * Log error messages with Sentry integration
82
82
  * @param message - Log message
@@ -86,7 +86,7 @@ export declare const logger: {
86
86
  * @since 0.0.1
87
87
  * @author AMBROISE PARK Consulting
88
88
  */
89
- error(message: string, context?: Record<string, any>): Promise<void>;
89
+ error(message: string, context?: Record<string, unknown>): Promise<void>;
90
90
  /**
91
91
  * Log fatal errors with Sentry integration
92
92
  * @param message - Log message
@@ -96,7 +96,7 @@ export declare const logger: {
96
96
  * @since 0.0.1
97
97
  * @author AMBROISE PARK Consulting
98
98
  */
99
- fatal(message: string, context?: Record<string, any>): Promise<void>;
99
+ fatal(message: string, context?: Record<string, unknown>): Promise<void>;
100
100
  /**
101
101
  * Core logging method
102
102
  * @param level - Log level
@@ -109,7 +109,7 @@ export declare const logger: {
109
109
  * @since 0.0.1
110
110
  * @author AMBROISE PARK Consulting
111
111
  */
112
- log(level: LogLevel, message: string, context?: Record<string, any>): void;
112
+ log(level: LogLevel, message: string, context?: Record<string, unknown>): void;
113
113
  /**
114
114
  * Check if Sentry is enabled
115
115
  * @returns True if Sentry is available and configured
@@ -126,10 +126,10 @@ export declare const logger: {
126
126
  * @param context - Additional context to include in all logs
127
127
  * @returns Child logger instance
128
128
  */
129
- export declare function createChildLogger(context: Record<string, any>): {
130
- debug: (message: string, additionalContext?: Record<string, any>) => void;
131
- info: (message: string, additionalContext?: Record<string, any>) => void;
132
- warn: (message: string, additionalContext?: Record<string, any>) => void;
133
- error: (message: string, additionalContext?: Record<string, any>) => Promise<void>;
134
- fatal: (message: string, additionalContext?: Record<string, any>) => Promise<void>;
129
+ export declare function createChildLogger(context: Record<string, unknown>): {
130
+ debug: (message: string, additionalContext?: Record<string, unknown>) => void;
131
+ info: (message: string, additionalContext?: Record<string, unknown>) => void;
132
+ warn: (message: string, additionalContext?: Record<string, unknown>) => void;
133
+ error: (message: string, additionalContext?: Record<string, unknown>) => Promise<void>;
134
+ fatal: (message: string, additionalContext?: Record<string, unknown>) => Promise<void>;
135
135
  };
@@ -15,14 +15,6 @@ import type { SubscriptionClaims } from '@donotdev/core/server';
15
15
  * @author AMBROISE PARK Consulting
16
16
  */
17
17
  export declare function getTierFromPriceId(priceId: string): string;
18
- /**
19
- * Validates subscription status and updates Firebase custom claims
20
- *
21
- * @version 0.1.0
22
- * @since 0.0.1
23
- * @author AMBROISE PARK Consulting
24
- */
25
- export declare function updateFirebaseUserSubscription(firebaseUid: string, subscription: any): Promise<void>;
26
18
  /**
27
19
  * Cancels user subscription and resets to free tier
28
20
  *
@@ -1,3 +1,11 @@
1
+ /**
2
+ * @fileoverview Shared utilities for Firebase and Vercel functions
3
+ * @description Common utilities that can be used by both Firebase and Vercel function implementations
4
+ *
5
+ * @version 0.1.0
6
+ * @since 0.0.1
7
+ * @author AMBROISE PARK Consulting
8
+ */
1
9
  import { DoNotDevError } from '@donotdev/core/server';
2
10
  import type { UserRole } from '@donotdev/core/server';
3
11
  export { DoNotDevError };
@@ -17,7 +25,10 @@ export { DoNotDevError };
17
25
  * @since 0.0.1
18
26
  * @author AMBROISE PARK Consulting
19
27
  */
20
- export declare function getUserRole(auth: any): UserRole;
28
+ export declare function getUserRole(auth: {
29
+ uid?: string;
30
+ token?: Record<string, unknown>;
31
+ } | null | undefined): UserRole;
21
32
  /**
22
33
  * Creates a standardized success response
23
34
  *
@@ -41,17 +52,9 @@ export declare function createErrorResponse(error: unknown): {
41
52
  error: {
42
53
  code: string;
43
54
  message: string;
44
- details?: any;
55
+ details?: Record<string, unknown>;
45
56
  };
46
57
  };
47
- /**
48
- * Validates document data
49
- *
50
- * @version 0.1.0
51
- * @since 0.0.1
52
- * @author AMBROISE PARK Consulting
53
- */
54
- export declare function validateDocument(data: any, schema?: any): void;
55
58
  /**
56
59
  * Validates a Firestore collection name from client-supplied schema.
57
60
  *
@@ -1,6 +1,25 @@
1
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
2
+ /**
3
+ * Options for {@link createDeleteAccount}.
4
+ *
5
+ * @version 0.2.0
6
+ * @since 0.2.3
7
+ */
8
+ export interface DeleteAccountOptions {
9
+ /**
10
+ * Runs before the auth user is deleted (close the account, anonymize data, cancel
11
+ * subscriptions...). Throwing refuses the deletion: the user is NOT deleted and the
12
+ * client receives HTTP 409 `{ error: message, code }` (`code` when the thrown error
13
+ * carries a string `code`). The message and code reach the browser unmasked, so
14
+ * throw client-safe values only — a refusal code such as `open_orders` that the
15
+ * client translates under `auth:deleteAccount.errors.<code>` (see `useDeleteAccount`).
16
+ */
17
+ beforeDelete?: (ctx: SupabaseHandlerContext) => Promise<void>;
18
+ }
1
19
  /**
2
20
  * Create a Supabase Edge Function handler for account deletion.
3
21
  *
22
+ * @param options - Optional `beforeDelete` step; without it, deletes the user directly
4
23
  * @returns `(req: Request) => Promise<Response>` handler
5
24
  *
6
25
  * @example
@@ -10,7 +29,20 @@
10
29
  * Deno.serve(createDeleteAccount());
11
30
  * ```
12
31
  *
13
- * @version 0.1.0
32
+ * @example
33
+ * ```typescript
34
+ * // Refuse while the account still has open orders (the SQL function raises 'open_orders')
35
+ * Deno.serve(
36
+ * createDeleteAccount({
37
+ * beforeDelete: async ({ supabaseAdmin, uid }) => {
38
+ * const { error } = await supabaseAdmin.rpc('close_my_account', { p_uid: uid });
39
+ * if (error) throw error; // → 409 { error: 'open_orders', code: 'P0001' }
40
+ * },
41
+ * })
42
+ * );
43
+ * ```
44
+ *
45
+ * @version 0.2.0
14
46
  * @since 0.5.0
15
47
  */
16
- export declare function createDeleteAccount(): (req: Request) => Promise<Response>;
48
+ export declare function createDeleteAccount(options?: DeleteAccountOptions): (req: Request) => Promise<Response>;
@@ -27,6 +27,13 @@ export type BulkEntityRequest = BulkRequest;
27
27
  * which wraps `BEGIN ... COMMIT` — any failure triggers `ROLLBACK` and the
28
28
  * client observes a rejected promise with no partial state.
29
29
  *
30
+ * The stored rows of the updated ids are read before the RPC (their status picks
31
+ * each patch's schema, the CRUD rules). The statuses read are passed as
32
+ * `p_expected_statuses`; `crud_bulk` locks each updated row (`FOR UPDATE`) and
33
+ * rejects the whole bulk (`unavailable`, nothing written) when a status changed in
34
+ * between. Requires the `crud_bulk_status_guard` migration (5-argument
35
+ * `crud_bulk`); against an older database the RPC call fails (function not found).
36
+ *
30
37
  * The factory returns a handler that is auto-registered as `bulk_${collection}`
31
38
  * by {@link createSupabaseCrudFunctions}.
32
39
  *
@@ -1,11 +1,3 @@
1
- /**
2
- * @fileoverview Generic handler to create an entity in Supabase.
3
- * @description Provides a reusable implementation for creating documents in PostgreSQL with validation.
4
- *
5
- * @version 0.1.0
6
- * @since 0.5.0
7
- * @author AMBROISE PARK Consulting
8
- */
9
1
  import * as v from 'valibot';
10
2
  import type { UserRole } from '@donotdev/core/server';
11
3
  /** Request payload for creating an entity with optional idempotency. */
@@ -16,8 +8,12 @@ export type CreateEntityRequest = {
16
8
  /**
17
9
  * Create a Supabase Edge Function handler for creating an entity.
18
10
  *
11
+ * Status rule: a create without status gets `DEFAULT_STATUS_VALUE`; the CRUD rules
12
+ * picks the draft or create schema; the parse output is inserted, never the raw payload.
13
+ *
19
14
  * @param collection - The Supabase table name
20
- * @param documentSchema - The Valibot schema for document validation
15
+ * @param createDocumentSchema - The create schema (`createSchemas(entity).create`)
16
+ * @param draftDocumentSchema - The draft schema (`createSchemas(entity).draft`)
21
17
  * @param requiredRole - Minimum role required for this operation
22
18
  * @returns A `(req: Request) => Promise<Response>` handler for Deno.serve
23
19
  */