@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
@@ -0,0 +1,142 @@
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
+
7
+ import {
8
+ validateVerifyOrderCheckoutRequest,
9
+ validateVerifyOrderCheckoutResult,
10
+ } from '@donotdev/core/server';
11
+ import type {
12
+ StripeBackConfig,
13
+ VerifyOrderCheckoutRequest,
14
+ VerifyOrderCheckoutResult,
15
+ } from '@donotdev/core/server';
16
+
17
+ import { logger } from '../logger.js';
18
+ import { ORDER_ID_METADATA_KEY } from './orderWebhook.js';
19
+
20
+ /** App-owned persisted association, read from authoritative storage (never request metadata). */
21
+ export interface OrderCheckoutBinding {
22
+ orderId: string;
23
+ userId: string;
24
+ sessionId: string;
25
+ billingConfigKey: string;
26
+ }
27
+
28
+ /**
29
+ * Read dependencies only. Separate from StripeSessionProvider so existing checkout
30
+ * providers remain compatible. userId must come from verified handler context.
31
+ */
32
+ export interface VerifyOrderCheckoutDependencies {
33
+ userId: string;
34
+ billingConfig: StripeBackConfig;
35
+ /** Retrieve from Stripe using server credentials; no browser-supplied session objects. */
36
+ retrieveStripeSession(sessionId: string): Promise<Pick<
37
+ Stripe.Checkout.Session,
38
+ 'id' | 'mode' | 'status' | 'payment_status' | 'metadata'
39
+ >>;
40
+ /**
41
+ * Read the persisted order/session binding, scoped to the authenticated owner
42
+ * and config. Return absence if not authorized/found; never infer it from Stripe.
43
+ * The algorithm independently checks every returned binding field.
44
+ */
45
+ resolveOrderBinding(
46
+ request: VerifyOrderCheckoutRequest & { userId: string }
47
+ ): Promise<OrderCheckoutBinding | null | undefined>;
48
+ }
49
+
50
+ /**
51
+ * Verify an owner's StripeOrder session against server config and persisted binding.
52
+ * All validation, authorization and dependency failures expose the same safe error.
53
+ * Server diagnostics contain fixed stage/category labels only, never dependency
54
+ * errors or request/customer data. Logging failure cannot replace the public error.
55
+ * No writes, checkout hooks or fulfillment hooks run. A successful read reports
56
+ * payment state only: complete/unpaid is pending; paid/no_payment_required does not
57
+ * prove onOrderPaid has run. Existing webhook fulfillment remains authoritative.
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * // Inside createSupabaseHandler(..., v.unknown(), (data, ctx) => ...)
62
+ * // The algorithm performs mandatory request validation itself.
63
+ * return verifyOrderCheckoutAlgorithm(data, {
64
+ * userId: ctx.uid,
65
+ * billingConfig,
66
+ * retrieveStripeSession: (id) => stripe.checkout.sessions.retrieve(id),
67
+ * resolveOrderBinding, // app-owned authoritative, read-only resolver
68
+ * });
69
+ * ```
70
+ */
71
+ export async function verifyOrderCheckoutAlgorithm(
72
+ input: unknown,
73
+ dependencies: VerifyOrderCheckoutDependencies
74
+ ): Promise<VerifyOrderCheckoutResult> {
75
+ let stage: 'validation' | 'auth' | 'config' | 'binding' | 'provider' | 'response' = 'validation';
76
+ let category: 'invalid' | 'rejected' | 'unavailable' = 'invalid';
77
+ try {
78
+ const validation = validateVerifyOrderCheckoutRequest(input);
79
+ if (!validation.success) throw new Error();
80
+ const request = validation.output;
81
+ const { userId, billingConfig } = dependencies;
82
+ stage = 'auth';
83
+ category = 'rejected';
84
+ if (typeof userId !== 'string' || !userId.trim()) throw new Error();
85
+
86
+ stage = 'config';
87
+ category = 'invalid';
88
+ if (
89
+ !Object.hasOwn(billingConfig, request.billingConfigKey) ||
90
+ billingConfig[request.billingConfigKey]?.type !== 'StripeOrder'
91
+ ) throw new Error();
92
+
93
+ stage = 'binding';
94
+ category = 'unavailable';
95
+ const binding = await dependencies.resolveOrderBinding({ ...request, userId });
96
+ category = 'rejected';
97
+ if (
98
+ !binding ||
99
+ binding.userId !== userId ||
100
+ binding.sessionId !== request.sessionId ||
101
+ binding.billingConfigKey !== request.billingConfigKey ||
102
+ typeof binding.orderId !== 'string' || !binding.orderId.trim()
103
+ ) throw new Error();
104
+
105
+ stage = 'provider';
106
+ category = 'unavailable';
107
+ const session = await dependencies.retrieveStripeSession(request.sessionId);
108
+ stage = 'response';
109
+ category = 'rejected';
110
+ if (
111
+ session.id !== request.sessionId ||
112
+ session.mode !== 'payment' ||
113
+ session.metadata?.userId !== userId ||
114
+ session.metadata?.billingConfigKey !== request.billingConfigKey ||
115
+ session.metadata?.[ORDER_ID_METADATA_KEY] !== binding.orderId
116
+ ) throw new Error();
117
+
118
+ // Do not map the webhook snapshot: it includes buyer details and arbitrary
119
+ // metadata and has no session status. Only these allowlisted fields leave here.
120
+ category = 'invalid';
121
+ const result = validateVerifyOrderCheckoutResult({
122
+ sessionId: session.id,
123
+ orderId: binding.orderId,
124
+ billingConfigKey: request.billingConfigKey,
125
+ sessionStatus: session.status,
126
+ paymentStatus: session.payment_status,
127
+ });
128
+ if (!result.success) throw new Error();
129
+ return result.output;
130
+ } catch {
131
+ try {
132
+ // Only code-owned labels: never log the caught error, IDs or metadata.
133
+ // Await also contains a rejected promise if the logging backend changes.
134
+ await logger.warn('[Checkout verification] Failed', { stage, category });
135
+ } catch {
136
+ // Diagnostics must never change the fail-closed public contract.
137
+ }
138
+ // Same message/status through existing handler error mapping; no IDs, cause,
139
+ // provider details or distinctions between missing and foreign bindings.
140
+ throw new Error('Checkout verification denied');
141
+ }
142
+ }
@@ -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 });
@@ -28,7 +28,11 @@ import {
28
28
  detectBulkCollisions,
29
29
  DoNotDevError,
30
30
  hasRoleAccess,
31
- DEFAULT_STATUS_VALUE,
31
+ createStatus,
32
+ prepareCreate,
33
+ prepareUpdate,
34
+ statusCan,
35
+ updateCheck,
32
36
  } from '@donotdev/core/server';
33
37
  import type {
34
38
  BulkRequest,
@@ -37,6 +41,8 @@ import type {
37
41
  UserRole,
38
42
  } from '@donotdev/core/server';
39
43
 
44
+ import { writtenOf } from './written.js';
45
+
40
46
  // =============================================================================
41
47
  // Public types
42
48
  // =============================================================================
@@ -46,16 +52,19 @@ import type {
46
52
  * the parsed output) so callers can pass entity-specific schemas generated by
47
53
  * `createSchemas()` without fighting variance.
48
54
  */
55
+ // 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
56
  export type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;
50
57
 
51
58
  /**
52
59
  * A prepared insert row passed to the caller-supplied `transact` callback.
53
60
  * When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted
54
- * value; otherwise it carries whatever id (if any) the client supplied and
55
- * the storage layer is expected to mint its own.
61
+ * value (a client id never addresses a stored document). Otherwise it is the
62
+ * id the client supplied (a pre-minted id other rows reference, BULK_ACROSS.md
63
+ * "Pre-Minted IDs"), also kept on `row.id`, or the empty string when the
64
+ * storage layer mints its own.
56
65
  */
57
66
  export interface PreparedInsert {
58
- /** Minted insert id, or the empty string when the target mints its own. */
67
+ /** Minted id, else the client-supplied id, else the empty string (the target mints its own). */
59
68
  id: string;
60
69
  /** Fully stamped row ready for storage. */
61
70
  row: Record<string, unknown>;
@@ -93,10 +102,28 @@ export interface ExecuteBulkParams<TRow = unknown> {
93
102
  ops: BulkRequest;
94
103
  /** Valibot schema validating each insert row. */
95
104
  createSchema: BulkRowSchema;
96
- /** Valibot schema validating each insert row when status === 'draft'. */
105
+ /**
106
+ * `createSchemas(entity).draft`: drafts saved incomplete (CRUD rule 5). Required as soon
107
+ * as a draft row is sent: a draft without it is rejected (`invalid-argument`), never
108
+ * validated as a create.
109
+ */
97
110
  draftCreateSchema?: BulkRowSchema;
98
- /** Valibot schema validating each update patch. */
111
+ /** `createSchemas(entity).update`: update patches (CRUD rules 2, 5). */
99
112
  updateSchema: BulkRowSchema;
113
+ /**
114
+ * Reads the stored rows of the updated ids (application field names, keyed by id).
115
+ * Called once, before validation, when the bulk carries updates: the stored row
116
+ * gives each patch its status and a published draft its whole record
117
+ * (`prepareUpdate`, as on the client). An updated id missing
118
+ * from the result is rejected (`not-found`). Required as soon as the bulk carries
119
+ * updates: an update without it is rejected (`internal`, a configuration error),
120
+ * never validated by its patch status alone. Every target passes it: Firestore,
121
+ * Supabase and Vercel read their store; the GraphQL / REST-CRUD server aids
122
+ * forward the consumer's `readStored` option.
123
+ */
124
+ readStored?: (
125
+ ids: readonly string[]
126
+ ) => Promise<ReadonlyMap<string, Record<string, unknown>>>;
100
127
  /** Per-bucket required roles. Missing entries are treated as "no bucket allowed". */
101
128
  access: EntityAccessConfig;
102
129
  /** Authenticated caller id (for metadata + audit). */
@@ -184,12 +211,17 @@ const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
184
211
  * 4. Per-bucket ACL — for each populated bucket, asserts the caller's role
185
212
  * clears the corresponding `access.{create|update|delete}`. A missing
186
213
  * role on a populated bucket is a configuration error and is rejected.
187
- * 5. Per-row validation — inserts against `createSchema`, updates against
188
- * `updateSchema`. The first failure throws a `DoNotDevError` prefixed
189
- * with `inserts[i]` or `updates[i]` so callers can pinpoint the row.
214
+ * 5. Per-row validation — the CRUD rules (`prepareCreate` / `prepareUpdate`,
215
+ * core/schemas crud/), the stored rows read once with `readStored` (updates
216
+ * without it → `internal`; an updated id with no stored row → `not-found`).
217
+ * The first failure throws `validation-failed` (wire: `invalid-argument`)
218
+ * naming `inserts[i]` / `updates[i]`. Unknown fields are logged, not written.
219
+ * What is stored is the rules' `written`, never the raw row.
190
220
  * 6. Id minting — if `mintInsertId` is supplied, every insert gets a fresh
191
- * id stamped onto its {@link PreparedInsert}. Otherwise `id` is `""` and
192
- * the storage layer mints its own.
221
+ * id stamped onto its {@link PreparedInsert}. Otherwise a client-supplied
222
+ * `id` is kept (on the row and as `PreparedInsert.id`; the create schema
223
+ * excludes it, it is restored after validation), else `id` is `""` and the
224
+ * storage layer mints its own.
193
225
  * 7. Metadata stamping — `stampInsertMetadata` / `stampUpdateMetadata` run
194
226
  * per row / per patch if provided.
195
227
  * 8. `transact(prepared)` runs exactly once. Must be atomic. Throws
@@ -211,8 +243,12 @@ const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
211
243
  * @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row
212
244
  * validation failure, or collision (wrapped for callers that only rethrow
213
245
  * `DoNotDevError`).
246
+ * @throws {DoNotDevError} `not-found` when an updated id has no stored row
247
+ * (`readStored`).
214
248
  * @throws {DoNotDevError} `permission-denied` when the caller's role cannot
215
249
  * satisfy a populated bucket's access requirement.
250
+ * @throws {DoNotDevError} `internal` when the bulk carries updates but no
251
+ * `readStored` is configured.
216
252
  * @throws {DoNotDevError} `internal` when the `transact` return value fails
217
253
  * {@link BulkResponseSchema}.
218
254
  *
@@ -229,6 +265,7 @@ const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
229
265
  * access,
230
266
  * uid,
231
267
  * userRole,
268
+ * readStored: async (ids) => new Map((await db.getRows(ids)).map((row) => [row.id, row])),
232
269
  * mintInsertId: () => crypto.randomUUID(),
233
270
  * stampInsertMetadata: (row, uid) => ({
234
271
  * ...row,
@@ -268,6 +305,7 @@ export async function executeBulk<TRow = unknown>(
268
305
  uid,
269
306
  userRole,
270
307
  transact,
308
+ readStored,
271
309
  mintInsertId,
272
310
  stampInsertMetadata,
273
311
  stampUpdateMetadata,
@@ -281,7 +319,7 @@ export async function executeBulk<TRow = unknown>(
281
319
  const messages = parsed.issues
282
320
  .map(
283
321
  (issue) =>
284
- `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
322
+ `${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`
285
323
  )
286
324
  .join('; ');
287
325
  throw new DoNotDevError(
@@ -358,52 +396,82 @@ export async function executeBulk<TRow = unknown>(
358
396
  }
359
397
  }
360
398
 
361
- // 5. Per-row validation. First failure wins — prefixed with its bucket
362
- // index so callers can point at the offending row.
399
+ // 5. Per-row validation: the CRUD rules (core/schemas crud/: `prepareCreate`,
400
+ // `prepareUpdate`), as on the client. First failure wins, named by its bucket
401
+ // index. What is stored is the rules' `written`, never the raw row.
402
+ const noDraftSchema = (locator: string): never => {
403
+ throw new DoNotDevError(
404
+ `Validation failed on ${locator}: draft row sent to ${collection} but no draft schema is configured`,
405
+ 'invalid-argument'
406
+ );
407
+ };
408
+ // Without a draft schema, no draft row passes the guards below: `create` only fills the slot.
409
+ const schemas = {
410
+ create: createSchema,
411
+ draft: draftCreateSchema ?? createSchema,
412
+ update: updateSchema,
413
+ };
414
+ const insertRows: { row: Record<string, unknown>; id: string | null }[] = [];
363
415
  for (let i = 0; i < inserts.length; i++) {
364
- const row = inserts[i]!;
365
- const rowObj = row as unknown as Record<string, unknown>;
366
- const status =
367
- (rowObj.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
368
- const isDraft = status === 'draft';
369
- const schemaToUse =
370
- isDraft && draftCreateSchema ? draftCreateSchema : createSchema;
371
- // Only inject default `status` when validating against the draft schema.
372
- // This avoids breaking createSchema-only tests/entities that don't define
373
- // `status` in their schema shape (valibot's `v.object` is strict by
374
- // default).
375
- const payloadForValidation =
376
- isDraft && draftCreateSchema ? { ...rowObj, status } : rowObj;
377
- validateRow(payloadForValidation, schemaToUse, `inserts[${i}]`);
416
+ const rowObj = inserts[i]! as unknown as Record<string, unknown>;
417
+ if (!draftCreateSchema && statusCan(createStatus(rowObj), 'saveIncomplete')) noDraftSchema(`inserts[${i}]`);
418
+ const row = writtenOf(prepareCreate(schemas, rowObj), collection, `inserts[${i}]`);
419
+ // A client id is a pre-minted id other rows reference: the rules never write
420
+ // `id`, so it travels beside the row.
421
+ insertRows.push({ row, id: typeof rowObj.id === 'string' ? rowObj.id : null });
378
422
  }
423
+ // The stored rows give each patch its status and the publish check its record.
424
+ if (updates.length > 0 && !readStored) {
425
+ throw new DoNotDevError(
426
+ `Bulk update requested on ${collection} but no readStored is configured: the stored row decides each patch's rules`,
427
+ 'internal'
428
+ );
429
+ }
430
+ const stored =
431
+ updates.length > 0 && readStored
432
+ ? await readStored(updates.map((u) => u.id))
433
+ : new Map<string, Record<string, unknown>>();
434
+ const updatePatches: Record<string, unknown>[] = [];
379
435
  for (let i = 0; i < updates.length; i++) {
380
- validateRow(updates[i]!.patch, updateSchema, `updates[${i}]`);
436
+ const { id, patch } = updates[i]!;
437
+ const locator = `updates[${i}]`;
438
+ const storedRow = stored.get(id);
439
+ if (!storedRow) {
440
+ throw new DoNotDevError(
441
+ `Document not found on ${locator}: ${collection}/${id}`,
442
+ 'not-found'
443
+ );
444
+ }
445
+ if (!draftCreateSchema && updateCheck(patch as Record<string, unknown>, storedRow).schemaKey === 'draft') {
446
+ noDraftSchema(locator);
447
+ }
448
+ updatePatches.push(
449
+ writtenOf(
450
+ prepareUpdate(schemas, { id, patch: patch as Record<string, unknown>, stored: storedRow }),
451
+ collection,
452
+ locator
453
+ )
454
+ );
381
455
  }
382
456
 
383
457
  // 6. Id minting (if provided). Minting at this layer means `transact`
384
458
  // receives stable ids — crucial for Firestore's retry-able transaction
385
459
  // callbacks where the callback body may run more than once.
386
- const preparedInserts: PreparedInsert[] = inserts.map((row) => {
387
- const rowRecord = row as unknown as Record<string, unknown>;
388
- // Always ensure status is present for storage + downstream schema
389
- // stamping. Validation may have used `draftCreateSchema` to relax
390
- // required-field enforcement, but storage should still persist a
391
- // concrete status value.
392
- const status =
393
- (rowRecord.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
394
- const id = mintInsertId ? mintInsertId() : '';
395
- const stamped = stampInsertMetadata
396
- ? stampInsertMetadata({ ...rowRecord, status }, uid)
397
- : ({ ...rowRecord, status } as Record<string, unknown>);
460
+ // Without minting, a client id is kept (row + PreparedInsert.id) for the
461
+ // target to store; with minting, the minted id wins.
462
+ const preparedInserts: PreparedInsert[] = insertRows.map(({ row, id: clientId }) => {
463
+ const id = mintInsertId ? mintInsertId() : (clientId ?? '');
464
+ const withId = !mintInsertId && clientId !== null ? { ...row, id: clientId } : row;
465
+ const stamped = stampInsertMetadata ? stampInsertMetadata(withId, uid) : withId;
398
466
  return { id, row: stamped };
399
467
  });
400
468
 
401
469
  // 7. Update metadata stamping.
402
- const preparedUpdates: PreparedUpdate[] = updates.map((u) => ({
470
+ const preparedUpdates: PreparedUpdate[] = updates.map((u, i) => ({
403
471
  id: u.id,
404
472
  patch: stampUpdateMetadata
405
- ? stampUpdateMetadata(u.patch as Record<string, unknown>, uid)
406
- : (u.patch as Record<string, unknown>),
473
+ ? stampUpdateMetadata(updatePatches[i]!, uid)
474
+ : updatePatches[i]!,
407
475
  }));
408
476
 
409
477
  // 8. Atomic dispatch. Propagates any `transact` error verbatim — the
@@ -443,41 +511,3 @@ export async function executeBulk<TRow = unknown>(
443
511
  // =============================================================================
444
512
  // Internal helpers
445
513
  // =============================================================================
446
-
447
- /**
448
- * Validate a row against a Valibot schema and rethrow a `DoNotDevError`
449
- * prefixed with the bucket position so callers can point at the offending
450
- * row. Keeps the hot path free of try/catch overhead when no schema is
451
- * supplied.
452
- *
453
- * @param value - Row or patch to validate.
454
- * @param schema - Valibot schema.
455
- * @param locator - Human-readable pointer such as `inserts[2]`.
456
- *
457
- * @example
458
- * ```typescript
459
- * validateRow(inserts[i], createSchema, `inserts[${i}]`);
460
- * ```
461
- *
462
- * @internal
463
- */
464
- function validateRow(
465
- value: unknown,
466
- schema: BulkRowSchema,
467
- locator: string
468
- ): void {
469
- const parsed = v.safeParse(schema, value);
470
- if (parsed.success) return;
471
-
472
- const messages = parsed.issues
473
- .map(
474
- (issue) =>
475
- `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
476
- )
477
- .join('; ');
478
- throw new DoNotDevError(
479
- `Validation failed on ${locator}: ${messages}`,
480
- 'invalid-argument',
481
- { details: { validationErrors: parsed.issues } }
482
- );
483
- }
@@ -21,3 +21,4 @@ export {
21
21
  type PreparedUpdate,
22
22
  type BulkRowSchema,
23
23
  } from './bulkCore.js';
24
+ export { writtenOf } from './written.js';
@@ -0,0 +1,56 @@
1
+ // packages/functions/src/shared/crud/written.ts
2
+
3
+ /**
4
+ * @fileoverview What a server write stores
5
+ * @description The server side of a CRUD rule result (`prepareCreate` / `prepareUpdate` /
6
+ * `prepareRemove`, core/schemas crud/): logs the unknown fields (CRUD rule 8: neither
7
+ * silent nor blocking) and returns the stored values or throws. Every server write site
8
+ * (bulk, create, update, entity store) calls it.
9
+ *
10
+ * @version 0.1.0
11
+ * @since 0.3.0
12
+ * @author AMBROISE PARK Consulting
13
+ */
14
+
15
+ import { DoNotDevError } from '@donotdev/core/server';
16
+ import type { PreparedWrite } from '@donotdev/core/server';
17
+
18
+ /**
19
+ * The values a server write stores.
20
+ *
21
+ * @param result - The CRUD rule result
22
+ * @param collection - Collection written (named in the log and the error)
23
+ * @param locator - Write site / row (e.g. `update`, `inserts[2]`)
24
+ * @returns The rule's `written`
25
+ * @throws {DoNotDevError} `invalid-argument` with `details.validationErrors` (the server wire
26
+ * contract, a Firebase `FunctionsErrorCode`) when the write is invalid
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const row = writtenOf(prepareCreate(schemas, payload), collection, 'create');
31
+ * ```
32
+ *
33
+ * @version 0.1.0
34
+ * @since 0.3.0
35
+ * @author AMBROISE PARK Consulting
36
+ */
37
+ export function writtenOf(
38
+ result: PreparedWrite,
39
+ collection: string,
40
+ locator: string
41
+ ): Record<string, unknown> {
42
+ if (result.unknownKeys.length > 0) {
43
+ console.warn(
44
+ `[dndev] ${collection} ${locator}: fields the entity does not have, not written: ${result.unknownKeys.join(', ')}`
45
+ );
46
+ }
47
+ if (result.ok) return result.written;
48
+ const messages = result.issues
49
+ .map((issue) => `${issue.path?.map((p) => String(p.key)).join('.') || 'root'}: ${issue.message}`)
50
+ .join('; ');
51
+ throw new DoNotDevError(
52
+ `Validation failed on ${collection} ${locator}: ${messages}`,
53
+ 'invalid-argument',
54
+ { details: { validationErrors: result.issues } }
55
+ );
56
+ }
@@ -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
  }