@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
@@ -9,13 +9,16 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import type { SupabaseClient } from '@supabase/supabase-js';
12
13
  import * as v from 'valibot';
13
14
 
15
+ import { prepareUpdate } from '@donotdev/core/server';
14
16
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
15
17
  import { defaultFieldMapper } from '@donotdev/supabase/server';
16
18
 
17
19
  import { updateMetadata } from '../../shared/metadata.js';
18
- import { DoNotDevError, validateDocument } from '../../shared/utils.js';
20
+ import { writtenOf } from '../../shared/crud/written.js';
21
+ import { DoNotDevError } from '../../shared/utils.js';
19
22
  import { createSupabaseHandler } from '../baseFunction.js';
20
23
  import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
21
24
 
@@ -24,6 +27,7 @@ const mapper = defaultFieldMapper;
24
27
  /** Request payload for updating an entity by ID with optional idempotency. */
25
28
  export type UpdateEntityRequest = {
26
29
  id: string;
30
+ // 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)
27
31
  payload: Record<string, any>;
28
32
  idempotencyKey?: string;
29
33
  };
@@ -44,10 +48,10 @@ function normalizeValue(value: unknown): unknown {
44
48
  async function checkUniqueKeys(
45
49
  collection: string,
46
50
  id: string,
47
- payload: Record<string, any>,
51
+ payload: Record<string, unknown>,
48
52
  uniqueKeys: UniqueKeyDefinition[],
49
53
  isDraft: boolean,
50
- supabaseAdmin: any
54
+ supabaseAdmin: SupabaseClient
51
55
  ): Promise<void> {
52
56
  for (const uniqueKey of uniqueKeys) {
53
57
  if (isDraft && uniqueKey.skipForDrafts === true) continue;
@@ -93,19 +97,27 @@ async function checkUniqueKeys(
93
97
  /**
94
98
  * Create a Supabase Edge Function handler for updating an entity.
95
99
  *
100
+ * CRUD update rules (`prepareUpdate`, core/schemas crud/update), as on the client: the
101
+ * stored row gives the patch its status and a published draft its whole record. The
102
+ * rules' `written` (parsed sent keys) is stored, never the raw payload.
103
+ *
96
104
  * @param collection - The Supabase table name
97
- * @param documentSchema - The Valibot schema for document validation
105
+ * @param documentSchema - The update schema (`createSchemas(entity).update`): validates what a non-draft update writes (the whole merged row when it enters a visible status)
106
+ * @param draftDocumentSchema - The draft schema (`createSchemas(entity).draft`): validates the resulting row of a draft
98
107
  * @param requiredRole - Minimum role required for this operation
99
108
  * @returns A `(req: Request) => Promise<Response>` handler for Deno.serve
100
109
  */
101
110
  export function createSupabaseUpdateEntity(
102
111
  collection: string,
112
+ // 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)
103
113
  documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
114
+ // 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)
115
+ draftDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
104
116
  requiredRole: UserRole
105
117
  ) {
106
118
  const requestSchema = v.object({
107
119
  id: v.pipe(v.string(), v.minLength(1)),
108
- payload: v.record(v.string(), v.any()),
120
+ payload: v.record(v.string(), v.unknown()),
109
121
  idempotencyKey: v.optional(v.string()),
110
122
  });
111
123
 
@@ -118,7 +130,7 @@ export function createSupabaseUpdateEntity(
118
130
 
119
131
  // Idempotency check if key provided
120
132
  if (idempotencyKey) {
121
- const cachedResult = await checkIdempotency<any>(
133
+ const cachedResult = await checkIdempotency<unknown>(
122
134
  supabaseAdmin,
123
135
  idempotencyKey,
124
136
  'update'
@@ -143,11 +155,16 @@ export function createSupabaseUpdateEntity(
143
155
  // `payload` arrives from the client in camelCase. The merge produces a camelCase object
144
156
  // which is later converted back to snake_case via toBackendKeys before the UPDATE query.
145
157
  const merged = {
146
- ...(mapper.fromBackendRow(existing) as Record<string, any>),
158
+ ...(mapper.fromBackendRow(existing) as Record<string, unknown>),
147
159
  ...payload,
148
160
  };
149
- const status = merged.status ?? existing.status;
150
- const isDraft = status === 'draft';
161
+ // CRUD update rules (core/schemas crud/update) on the stored row.
162
+ const stored = mapper.fromBackendRow(existing) as Record<string, unknown>;
163
+ const prepared = prepareUpdate(
164
+ { draft: draftDocumentSchema, update: documentSchema },
165
+ { id, patch: payload, stored }
166
+ );
167
+ const isDraft = prepared.schemaKey === 'draft';
151
168
 
152
169
  // Check unique keys if schema has metadata with uniqueKeys
153
170
  const schemaWithMeta = documentSchema as {
@@ -166,25 +183,13 @@ export function createSupabaseUpdateEntity(
166
183
  );
167
184
  }
168
185
 
169
- // Validate merged document (skip for drafts)
170
- if (!isDraft) {
171
- validateDocument(merged, documentSchema);
172
- }
186
+ const written = writtenOf(prepared, collection, 'update');
173
187
 
174
188
  const metadata = updateMetadata(uid);
175
189
  const snakeMetadata = mapper.toBackendKeys(
176
190
  metadata as Record<string, unknown>
177
191
  );
178
-
179
- const {
180
- createdAt,
181
- updatedAt,
182
- created_at,
183
- updated_at,
184
- id: _id,
185
- ...payloadWithoutTimestamps
186
- } = payload;
187
- const snakePayload = mapper.toBackendKeys(payloadWithoutTimestamps);
192
+ const snakePayload = mapper.toBackendKeys(written);
188
193
 
189
194
  // Update document (DB sets updated_at via trigger)
190
195
  const { data: updated, error } = await supabaseAdmin
@@ -204,7 +209,7 @@ export function createSupabaseUpdateEntity(
204
209
  );
205
210
  }
206
211
 
207
- const result = mapper.fromBackendRow(updated) as Record<string, any>;
212
+ const result = mapper.fromBackendRow(updated) as Record<string, unknown>;
208
213
 
209
214
  // Store result for idempotency if key provided
210
215
  if (idempotencyKey) {
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { createClient } from '@supabase/supabase-js';
17
17
  import type { SupabaseClient } from '@supabase/supabase-js';
18
+ import { getDenoEnv } from '../shared/denoEnv.js';
18
19
 
19
20
  // =============================================================================
20
21
  // Types
@@ -190,7 +191,7 @@ function jsonResponse(
190
191
 
191
192
  function getEnv(key: string): string {
192
193
  if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
193
- return (globalThis as any).Deno?.env?.get(key) ?? '';
194
+ return getDenoEnv()?.get(key) ?? '';
194
195
  }
195
196
  return typeof process !== 'undefined' ? (process.env[key] ?? '') : '';
196
197
  }
@@ -16,6 +16,7 @@ import { SendEmailRequestSchema } from '@donotdev/core/server';
16
16
  import { handleEmailRequest } from '../../shared/email/index.js';
17
17
  import { createResendProvider } from '../../shared/email/resendProvider.js';
18
18
  import { createSupabaseHandler } from '../baseFunction.js';
19
+ import { getDenoEnv } from '../../shared/denoEnv.js';
19
20
 
20
21
  /**
21
22
  * Create a Supabase Edge Function handler for sending emails.
@@ -66,7 +67,7 @@ export function createEmailFunction(config: EmailRouteConfig) {
66
67
 
67
68
  function getEnv(name: string): string | undefined {
68
69
  if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
69
- return (globalThis as any).Deno?.env?.get(name);
70
+ return getDenoEnv()?.get(name);
70
71
  }
71
72
  return typeof process !== 'undefined' ? process.env[name] : undefined;
72
73
  }
@@ -23,6 +23,7 @@ export { createSupabaseAuthProvider } from './helpers/authProvider.js';
23
23
 
24
24
  // Auth
25
25
  export { createDeleteAccount } from './auth/deleteAccount.js';
26
+ export type { DeleteAccountOptions } from './auth/deleteAccount.js';
26
27
  export { createSetCustomClaims } from './auth/setCustomClaims.js';
27
28
  export type { SetCustomClaimsOptions } from './auth/setCustomClaims.js';
28
29
  export { createGetCustomClaims } from './auth/getCustomClaims.js';
@@ -44,6 +45,13 @@ export type {
44
45
  // Custom StripeOrder entry points (app request shape, own StripeSessionProvider)
45
46
  export { createCheckoutAlgorithm } from '../shared/billing/createCheckout.js';
46
47
  export type { StripeSessionProvider } from '../shared/billing/createCheckout.js';
48
+ /** Read-only verification for authenticated app handlers; fulfillment stays in webhooks. */
49
+ export { verifyOrderCheckoutAlgorithm } from '../shared/billing/verifyOrderCheckout.js';
50
+ /** Separate read dependencies; existing checkout providers need no new methods. */
51
+ export type {
52
+ OrderCheckoutBinding,
53
+ VerifyOrderCheckoutDependencies,
54
+ } from '../shared/billing/verifyOrderCheckout.js';
47
55
  export { STRIPE_API_VERSION_PIN } from '../shared/billing/apiVersion.js';
48
56
  export { createCancelSubscription } from './billing/cancelSubscription.js';
49
57
  export { createChangePlan } from './billing/changePlan.js';
@@ -122,6 +122,7 @@ export function createExchangeToken() {
122
122
  );
123
123
  }
124
124
 
125
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: untrusted OAuth token response; needs a valibot schema (strict vs loose expires_in is an open owner decision)
125
126
  const tokenData = (await tokenResponse.json()) as any;
126
127
 
127
128
  // Format credentials
@@ -58,7 +58,7 @@ export function createGetConnections() {
58
58
  throw new Error(`Failed to get connections: ${error.message}`);
59
59
  }
60
60
 
61
- const connections = (rows || []).map((row: any) => {
61
+ const connections = (rows || []).map((row) => {
62
62
  const isExpired = row.credentials?.expiresAt
63
63
  ? row.credentials.expiresAt < Math.floor(Date.now() / 1000)
64
64
  : false;
@@ -94,6 +94,7 @@ export function createRefreshToken() {
94
94
  throw new Error(`Failed to refresh token: ${response.status}`);
95
95
  }
96
96
 
97
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: untrusted OAuth token response; needs a valibot schema (strict vs loose expires_in is an open owner decision)
97
98
  const tokenData = (await response.json()) as any;
98
99
 
99
100
  const credentials = {
@@ -90,6 +90,7 @@ export function createSupabaseCrudFunctions(
90
90
  handlers[`update_${col}`] = createSupabaseUpdateEntity(
91
91
  col,
92
92
  schemas.update,
93
+ schemas.draft,
93
94
  access.update
94
95
  );
95
96
 
@@ -95,7 +95,7 @@ export async function storeIdempotency<T>(
95
95
  id,
96
96
  operation,
97
97
  idempotency_key: idempotencyKey,
98
- result: result as any,
98
+ result,
99
99
  processed_by: uid,
100
100
  expires_at: expiresAt.toISOString(),
101
101
  },
@@ -19,6 +19,7 @@ export interface OperationMetrics {
19
19
  userId?: string;
20
20
  status: 'success' | 'failed' | 'pending';
21
21
  durationMs?: number;
22
+ // 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)
22
23
  metadata?: Record<string, any>;
23
24
  errorCode?: string;
24
25
  errorMessage?: string;
@@ -19,8 +19,10 @@ vi.mock('../../shared/utils/internal/auth.js', () => ({
19
19
  verifyAuthToken: vi.fn(() => Promise.resolve('user-1')),
20
20
  }));
21
21
 
22
- // Collection-name validator: accept everything in tests.
23
- vi.mock('../../shared/utils.js', () => ({
22
+ // Collection-name validator: accept everything in tests (write helpers stay real).
23
+ vi.mock('../../shared/utils.js', async (importOriginal) => ({
24
+ pickWritten: (await importOriginal<typeof import('../../shared/utils.js')>()).pickWritten,
25
+ wholeDocument: (await importOriginal<typeof import('../../shared/utils.js')>()).wholeDocument,
24
26
  validateCollectionName: vi.fn(),
25
27
  DoNotDevError: class DoNotDevError extends Error {
26
28
  code: string;
@@ -102,6 +104,14 @@ vi.mock('@donotdev/firebase/server', () => {
102
104
  getFirebaseAdminFirestore: () => ({
103
105
  collection,
104
106
  runTransaction,
107
+ // Stored rows read before validation (status rule)
108
+ getAll: vi.fn(async (...refs: any[]) =>
109
+ refs.map((ref) => ({
110
+ exists: existingDocIds.has(ref.id),
111
+ id: ref.id,
112
+ data: () => ({}),
113
+ }))
114
+ ),
105
115
  }),
106
116
  };
107
117
  });
@@ -249,8 +259,8 @@ describe('vercel bulk handler — collision rejection', () => {
249
259
  });
250
260
 
251
261
  describe('vercel bulk handler — validation failure', () => {
252
- it('rolls back when an update targets a non-existent doc', async () => {
253
- // `u1` not in existingDocIds → tx.get returns `exists: false` → throw.
262
+ it('rejects an update of a non-existent doc before any write', async () => {
263
+ // `u1` not in existingDocIds → the stored-row read finds nothing → not-found.
254
264
  existingDocIds = new Set();
255
265
  mintedIds = ['new-1'];
256
266
 
@@ -265,10 +275,8 @@ describe('vercel bulk handler — validation failure', () => {
265
275
  await handler(req, res);
266
276
 
267
277
  expect(res._status).toBe(500);
268
- // No writes issued — existence check runs before any tx.set/update/delete.
269
- expect(txSpy!.set).not.toHaveBeenCalled();
270
- expect(txSpy!.update).not.toHaveBeenCalled();
271
- expect(txSpy!.delete).not.toHaveBeenCalled();
278
+ // No transaction opened: the stored rows are read before validation.
279
+ expect(txSpy).toBeUndefined();
272
280
  });
273
281
 
274
282
  it('rejects structurally invalid body (ACL-equivalent schema check)', async () => {
@@ -19,6 +19,7 @@ import { updateUserSubscription } from '../../../shared/billing/helpers/updateUs
19
19
  import { handleError } from '../../../shared/errorHandling.js';
20
20
  import { stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
21
21
  import { createVercelBaseFunction } from '../../baseFunction.js';
22
+ import { isOneOf, pinnedSubscriptionPeriod } from '../../../shared/billing/stripePinned.js';
22
23
 
23
24
  const changePlanSchema = v.object({
24
25
  userId: v.string(),
@@ -86,8 +87,8 @@ async function changePlanLogic(
86
87
  'trialing',
87
88
  'incomplete',
88
89
  ] as const;
89
- const status = validStatuses.includes(updatedSubscription.status as any)
90
- ? (updatedSubscription.status as (typeof validStatuses)[number])
90
+ const status = isOneOf(validStatuses, updatedSubscription.status)
91
+ ? updatedSubscription.status
91
92
  : 'incomplete';
92
93
 
93
94
  // Update Firebase Auth
@@ -97,9 +98,9 @@ async function changePlanLogic(
97
98
  tier: billingItem.tier,
98
99
  status,
99
100
  subscriptionEnd: new Date(
100
- (updatedSubscription as any).current_period_end * 1000
101
+ pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000
101
102
  ).toISOString(),
102
- cancelAtPeriodEnd: (updatedSubscription as any).cancel_at_period_end,
103
+ cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,
103
104
  subscriptionId: updatedSubscription.id,
104
105
  customerId: updatedSubscription.customer as string,
105
106
  },
@@ -107,7 +108,7 @@ async function changePlanLogic(
107
108
  async getUser(uid: string) {
108
109
  return getFirebaseAdminAuth().getUser(uid);
109
110
  },
110
- async setCustomUserClaims(uid: string, claims: Record<string, any>) {
111
+ async setCustomUserClaims(uid: string, claims: Record<string, unknown>) {
111
112
  await getFirebaseAdminAuth().setCustomUserClaims(uid, claims);
112
113
  },
113
114
  }
@@ -17,6 +17,7 @@ import type { RefreshSubscriptionRequest } from '@donotdev/core/server';
17
17
 
18
18
  import { stripe, validateStripeEnvironment } from '../../../shared/billing/stripeClient.js';
19
19
  import { createVercelBaseFunction } from '../../baseFunction.js';
20
+ import { pinnedSubscriptionPeriod } from '../../../shared/billing/stripePinned.js';
20
21
 
21
22
  const refreshSubscriptionStatusSchema = v.object({
22
23
  userId: v.pipe(v.string(), v.minLength(1, 'User ID is required')),
@@ -76,7 +77,7 @@ async function refreshSubscriptionStatusLogic(
76
77
  customerId: subscription.customer,
77
78
  status: subscription.status,
78
79
  currentPeriodEnd: new Date(
79
- (subscription as any).current_period_end * 1000
80
+ pinnedSubscriptionPeriod(subscription).current_period_end * 1000
80
81
  ).toISOString(),
81
82
  };
82
83
 
@@ -113,6 +114,7 @@ async function refreshSubscriptionStatusLogic(
113
114
  * @author AMBROISE PARK Consulting
114
115
  */
115
116
  const refreshSubscriptionStatus = (
117
+ // 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)
116
118
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
117
119
  ) => {
118
120
  const schema = customSchema || refreshSubscriptionStatusSchema;
@@ -23,14 +23,19 @@ import * as v from 'valibot';
23
23
 
24
24
  import {
25
25
  BulkCollisionError,
26
- BulkInsertSchema,
27
26
  BulkRequestSchema,
28
27
  } from '@donotdev/core/server';
29
28
  import type { BulkRequest, BulkResponse } from '@donotdev/core/server';
30
29
 
31
30
  import { executeBulk } from '../../../shared/crud/bulkCore.js';
32
- import { handleError } from '../../../shared/errorHandling.js';
33
- import { prepareForFirestore } from '../../../shared/firebase.js';
31
+ import {
32
+ DoNotDevError,
33
+ handleError,
34
+ } from '../../../shared/errorHandling.js';
35
+ import {
36
+ prepareForFirestore,
37
+ transformFirestoreData,
38
+ } from '../../../shared/firebase.js';
34
39
  import { createMetadata, updateMetadata } from '../../../shared/metadata.js';
35
40
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
36
41
  import { validateCollectionName } from '../../../shared/utils.js';
@@ -41,8 +46,12 @@ import { validateCollectionName } from '../../../shared/utils.js';
41
46
  * structural checks already enforced by {@link BulkRequestSchema}. Both
42
47
  * inserts and update patches are opaque objects at this layer.
43
48
  */
44
- const PASSTHROUGH_INSERT_SCHEMA = BulkInsertSchema;
45
- const PASSTHROUGH_PATCH_SCHEMA = v.record(v.string(), v.unknown());
49
+ // Loose object schemas: no entity here, so the CRUD rules validate nothing beyond the
50
+ // wire shape and report no unknown field (core/schemas crud/prepared `unknownKeysOf`).
51
+ const PASSTHROUGH_INSERT_SCHEMA = v.looseObject({});
52
+ // An object schema (no declared entries): a patch entering a visible status is
53
+ // checked whole (`wholeDocument` needs `entries`), which here accepts any object.
54
+ const PASSTHROUGH_PATCH_SCHEMA = v.looseObject({});
46
55
 
47
56
  /**
48
57
  * HTTP handler for `POST /api/crud/:collection/bulk`.
@@ -118,6 +127,7 @@ export default async function handler(
118
127
  // the structural row schemas so per-row validation is a no-op beyond
119
128
  // what `BulkRequestSchema` already enforces.
120
129
  createSchema: PASSTHROUGH_INSERT_SCHEMA,
130
+ draftCreateSchema: PASSTHROUGH_INSERT_SCHEMA,
121
131
  updateSchema: PASSTHROUGH_PATCH_SCHEMA,
122
132
  // URL-routed handler has no entity ACL config — the per-bucket ACL in
123
133
  // `executeBulk` still enforces "populated bucket requires role", so we
@@ -126,6 +136,22 @@ export default async function handler(
126
136
  access: { create: 'user', update: 'user', delete: 'user' },
127
137
  uid,
128
138
  userRole: 'user',
139
+ // Stored rows of the updated ids (the status rule reads their status).
140
+ readStored: async (ids) => {
141
+ const db = getFirebaseAdminFirestore();
142
+ const col = db.collection(collection as string);
143
+ const snapshots = await db.getAll(...ids.map((id) => col.doc(id)));
144
+ const rows = new Map<string, Record<string, unknown>>();
145
+ for (const snapshot of snapshots) {
146
+ if (snapshot.exists) {
147
+ rows.set(
148
+ snapshot.id,
149
+ transformFirestoreData(snapshot.data() as Record<string, unknown>)
150
+ );
151
+ }
152
+ }
153
+ return rows;
154
+ },
129
155
  mintInsertId: () =>
130
156
  getFirebaseAdminFirestore()
131
157
  .collection(collection as string)
@@ -199,7 +225,9 @@ export default async function handler(
199
225
  } catch (error) {
200
226
  try {
201
227
  handleError(error);
202
- } catch (handledError: any) {
228
+ } catch (handledError) {
229
+ // handleError always throws DoNotDevError; narrow for typed access
230
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
203
231
  // BulkCollisionError surfaces as 400 (invalid-argument) because the
204
232
  // caller sent an incoherent payload — same class as schema failure.
205
233
  const isCollision = error instanceof BulkCollisionError;
@@ -2,7 +2,12 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview Create entity API handler
5
- * @description Vercel API route for creating entities
5
+ * @description Vercel API route for creating entities.
6
+ *
7
+ * The request carries one schema (W22): the caller sends the one
8
+ * `prepareCreate` (core/schemas crud/create) picks (`draft` or `create`). A create
9
+ * without status gets `DEFAULT_STATUS_VALUE`; the parse output is written, never the
10
+ * raw payload.
6
11
  *
7
12
  * @version 0.1.0
8
13
  * @since 0.0.1
@@ -11,19 +16,18 @@
11
16
 
12
17
  import type { NextApiRequest, NextApiResponse } from 'next';
13
18
 
19
+ import { prepareCreate } from '@donotdev/core/server';
14
20
  import type { CreateEntityData } from '@donotdev/core/server';
15
21
 
16
- import { handleError } from '../../../shared/errorHandling.js';
22
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
17
23
  import {
18
24
  prepareForFirestore,
19
25
  transformFirestoreData,
20
26
  } from '../../../shared/firebase.js';
21
27
  import { createMetadata } from '../../../shared/metadata.js';
22
28
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
23
- import {
24
- validateCollectionName,
25
- validateDocument,
26
- } from '../../../shared/utils.js';
29
+ import { writtenOf } from '../../../shared/crud/written.js';
30
+ import { validateCollectionName } from '../../../shared/utils.js';
27
31
 
28
32
  export default async function handler(
29
33
  req: NextApiRequest,
@@ -37,6 +41,7 @@ export default async function handler(
37
41
  // C1: verify JWT — previously only checked header presence.
38
42
  const uid = await verifyAuthToken(req);
39
43
 
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
40
45
  const { schema, payload } = req.body as CreateEntityData<any>;
41
46
 
42
47
  if (!schema || !payload) {
@@ -46,23 +51,17 @@ export default async function handler(
46
51
  // W22: Validate collection name from client-supplied schema
47
52
  validateCollectionName(schema.metadata.collection);
48
53
 
49
- // New records start as drafts unless the caller explicitly sets a status.
50
- const status = payload.status ?? 'draft';
51
-
52
- // Validate the document against the schema.
53
- // Draft handling is schema-driven: `schemas.draft` must convert required
54
- // fields into nullish/optional, so we still validate drafts.
55
- const payloadForValidation = {
56
- ...(payload as Record<string, any>),
57
- status,
58
- };
59
- validateDocument(payloadForValidation, schema);
54
+ // CRUD create rules (core/schemas crud/create), resulting status included.
55
+ // W22: the client supplies one schema, used for drafts and creates alike.
56
+ const written = writtenOf(
57
+ prepareCreate({ create: schema, draft: schema }, payload),
58
+ schema.metadata.collection,
59
+ 'create'
60
+ );
60
61
 
61
62
  // Prepare the document for Firestore and add metadata
62
- // Always ensure status is set
63
63
  const documentData = {
64
- ...prepareForFirestore(payload),
65
- status, // Ensure status is always present
64
+ ...prepareForFirestore(written),
66
65
  ...createMetadata(uid),
67
66
  };
68
67
 
@@ -87,7 +86,9 @@ export default async function handler(
87
86
  } catch (error) {
88
87
  try {
89
88
  handleError(error);
90
- } catch (handledError: any) {
89
+ } catch (handledError) {
90
+ // handleError always throws DoNotDevError; narrow for typed access
91
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
91
92
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
92
93
  return res
93
94
  .status(status)
@@ -13,7 +13,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
13
13
 
14
14
  import type { GetEntityData } from '@donotdev/core/server';
15
15
 
16
- import { handleError } from '../../../shared/errorHandling.js';
16
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
17
17
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
18
18
  import { validateCollectionName } from '../../../shared/utils.js';
19
19
 
@@ -29,6 +29,7 @@ export default async function handler(
29
29
  // C1: verify JWT — previously only checked header presence.
30
30
  const uid = await verifyAuthToken(req);
31
31
 
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
32
33
  const { schema, id } = req.body as { schema: any; id: string };
33
34
 
34
35
  if (!schema || !id) {
@@ -59,7 +60,9 @@ export default async function handler(
59
60
  } catch (error) {
60
61
  try {
61
62
  handleError(error);
62
- } catch (handledError: any) {
63
+ } catch (handledError) {
64
+ // handleError always throws DoNotDevError; narrow for typed access
65
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
63
66
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
64
67
  return res
65
68
  .status(status)
@@ -11,12 +11,11 @@
11
11
 
12
12
  import type { NextApiRequest, NextApiResponse } from 'next';
13
13
 
14
- import { HIDDEN_STATUSES } from '@donotdev/core/server';
14
+ import { filterVisibleFields, isReadableBy } from '@donotdev/core/server';
15
15
  import type { GetEntityData } from '@donotdev/core/server';
16
16
 
17
- import { handleError } from '../../../shared/errorHandling.js';
17
+ import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
18
18
  import { transformFirestoreData } from '../../../shared/firebase.js';
19
- import { filterVisibleFields } from '../../../shared/schema.js';
20
19
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
21
20
  import { validateCollectionName } from '../../../shared/utils.js';
22
21
 
@@ -32,6 +31,7 @@ export default async function handler(
32
31
  // C1: verify JWT — previously only checked header presence.
33
32
  const uid = await verifyAuthToken(req);
34
33
 
34
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: the client supplies the validation schema (known limitation W22); typing needs a server-side entity registry
35
35
  const { schema, id } = req.query as unknown as GetEntityData<any>;
36
36
 
37
37
  // G71: Validate query params are strings (Next.js can pass string[] for repeated params)
@@ -59,9 +59,9 @@ export default async function handler(
59
59
  handleError(new Error('Document not found'));
60
60
  }
61
61
 
62
- // Hide drafts/deleted (Vercel routes treat all requests as non-admin)
62
+ // CRUD rule 4 (core/schemas crud/read); Vercel routes treat all requests as unauthenticated
63
63
  const docData = doc.data();
64
- if ((HIDDEN_STATUSES as readonly string[]).includes(docData?.status)) {
64
+ if (!isReadableBy(docData, undefined)) {
65
65
  handleError(new Error('Document not found'));
66
66
  }
67
67
 
@@ -71,14 +71,16 @@ export default async function handler(
71
71
  ...docData,
72
72
  });
73
73
 
74
- // Filter visible fields based on schema
75
- const filteredData = filterVisibleFields(documentData, schema, false);
74
+ // Core visibility rule; the verified caller is treated as 'user' (non-admin)
75
+ const filteredData = filterVisibleFields(documentData, schema, 'user');
76
76
 
77
77
  return res.status(200).json(filteredData);
78
78
  } catch (error) {
79
79
  try {
80
80
  handleError(error);
81
- } catch (handledError: any) {
81
+ } catch (handledError) {
82
+ // handleError always throws DoNotDevError; narrow for typed access
83
+ if (!(handledError instanceof DoNotDevError)) throw handledError;
82
84
  const status = handledError.code === 'invalid-argument' ? 400 : 500;
83
85
  return res
84
86
  .status(status)