@donotdev/functions 0.2.3 → 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 (113) hide show
  1. package/lib/chunks/{chunk-6NXIK35R.js → chunk-522YXGDA.js} +2 -2
  2. package/lib/chunks/chunk-7ODXXXES.js +151 -0
  3. package/lib/chunks/{chunk-F3WBFWPO.js.map → chunk-7ODXXXES.js.map} +3 -3
  4. package/lib/chunks/chunk-CP3NNKO5.js +22 -0
  5. package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
  6. package/lib/chunks/{chunk-GDIUOJMD.js → chunk-CVYSXC27.js} +2 -2
  7. package/lib/chunks/{chunk-UH445BGK.js → chunk-HZM5X5A7.js} +2 -2
  8. package/lib/chunks/chunk-ICNQCRLV.js +22 -0
  9. package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
  10. package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
  11. package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
  12. package/lib/chunks/{chunk-QXIOO2RL.js → chunk-OKRR7ST5.js} +2 -2
  13. package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
  14. package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
  15. package/lib/chunks/chunk-TJPJXJEK.js +22 -0
  16. package/lib/chunks/{chunk-EZKRLLSQ.js.map → chunk-TJPJXJEK.js.map} +1 -1
  17. package/lib/chunks/{monitoring-LXNVBD3G.js → monitoring-UCBNPPW2.js} +2 -2
  18. package/lib/chunks/{rateLimiter-GG5LPWXJ.js → rateLimiter-XKECWM33.js} +2 -2
  19. package/lib/chunks/{server-NODQAE3F.js → server-24XGDDO3.js} +2 -2
  20. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  21. package/lib/firebase/crud/create.d.ts +22 -1
  22. package/lib/firebase/crud/update.d.ts +27 -3
  23. package/lib/firebase/index.js +1 -1
  24. package/lib/firebase/index.js.map +3 -3
  25. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
  26. package/lib/shared/billing/index.d.ts +2 -0
  27. package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
  28. package/lib/shared/crud/bulkCore.d.ts +38 -10
  29. package/lib/shared/crud/index.d.ts +1 -0
  30. package/lib/shared/crud/written.d.ts +21 -0
  31. package/lib/shared/index.d.ts +0 -1
  32. package/lib/shared/index.js +1 -1
  33. package/lib/shared/utils.d.ts +0 -9
  34. package/lib/supabase/crud/bulk.d.ts +7 -0
  35. package/lib/supabase/crud/create.d.ts +5 -1
  36. package/lib/supabase/crud/entityStore.d.ts +54 -14
  37. package/lib/supabase/crud/update.d.ts +7 -2
  38. package/lib/supabase/index.d.ts +4 -0
  39. package/lib/supabase/index.js +1 -1
  40. package/lib/supabase/index.js.map +3 -3
  41. package/lib/vercel/api/crud/create.d.ts +6 -1
  42. package/lib/vercel/api/crud/update.d.ts +8 -1
  43. package/lib/vercel/api/index.js +1 -1
  44. package/package.json +3 -3
  45. package/src/firebase/auth/removeCustomClaims.ts +31 -1
  46. package/src/firebase/auth/setCustomClaims.ts +3 -0
  47. package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
  48. package/src/firebase/crud/__tests__/create.test.ts +64 -0
  49. package/src/firebase/crud/__tests__/update.test.ts +97 -0
  50. package/src/firebase/crud/aggregate.ts +10 -21
  51. package/src/firebase/crud/bulk.ts +23 -10
  52. package/src/firebase/crud/create.ts +19 -18
  53. package/src/firebase/crud/get.ts +3 -12
  54. package/src/firebase/crud/list.ts +5 -4
  55. package/src/firebase/crud/update.ts +35 -19
  56. package/src/firebase/registerCrudFunctions.ts +1 -0
  57. package/src/shared/__tests__/bulkCore.test.ts +191 -0
  58. package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
  59. package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
  60. package/src/shared/__tests__/utils.test.ts +0 -30
  61. package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
  62. package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
  63. package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
  64. package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
  65. package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
  66. package/src/shared/billing/index.ts +2 -0
  67. package/src/shared/billing/verifyOrderCheckout.ts +142 -0
  68. package/src/shared/crud/bulkCore.ts +110 -81
  69. package/src/shared/crud/index.ts +1 -0
  70. package/src/shared/crud/written.ts +56 -0
  71. package/src/shared/index.d.ts +0 -9
  72. package/src/shared/index.ts +0 -1
  73. package/src/shared/utils.ts +0 -43
  74. package/src/supabase/__tests__/bulk.test.ts +60 -2
  75. package/src/supabase/__tests__/create.test.ts +86 -0
  76. package/src/supabase/__tests__/entityStore.test.ts +91 -25
  77. package/src/supabase/__tests__/update.test.ts +107 -0
  78. package/src/supabase/auth/removeCustomClaims.ts +7 -2
  79. package/src/supabase/auth/setCustomClaims.ts +4 -2
  80. package/src/supabase/crud/bulk.ts +47 -0
  81. package/src/supabase/crud/create.ts +14 -24
  82. package/src/supabase/crud/entityStore.ts +106 -17
  83. package/src/supabase/crud/get.ts +3 -12
  84. package/src/supabase/crud/list.ts +5 -4
  85. package/src/supabase/crud/update.ts +20 -18
  86. package/src/supabase/index.ts +7 -0
  87. package/src/supabase/registerCrudFunctions.ts +1 -0
  88. package/src/vercel/__tests__/bulk.test.ts +16 -8
  89. package/src/vercel/api/crud/bulk.ts +27 -4
  90. package/src/vercel/api/crud/create.ts +17 -19
  91. package/src/vercel/api/crud/get.ts +5 -6
  92. package/src/vercel/api/crud/list.ts +4 -5
  93. package/src/vercel/api/crud/update.ts +20 -18
  94. package/lib/chunks/chunk-EZKRLLSQ.js +0 -22
  95. package/lib/chunks/chunk-F3PHE627.js +0 -22
  96. package/lib/chunks/chunk-F3PHE627.js.map +0 -7
  97. package/lib/chunks/chunk-F3WBFWPO.js +0 -151
  98. package/lib/chunks/chunk-G5DRV3DH.js +0 -22
  99. package/lib/chunks/chunk-G5DRV3DH.js.map +0 -7
  100. package/lib/chunks/chunk-Q2WLRFOE.js +0 -22
  101. package/lib/chunks/chunk-Q2WLRFOE.js.map +0 -7
  102. package/lib/chunks/chunk-W74UL7AY.js +0 -22
  103. package/lib/chunks/chunk-W74UL7AY.js.map +0 -7
  104. package/lib/shared/schema.d.ts +0 -56
  105. package/src/shared/__tests__/schema.test.ts +0 -219
  106. package/src/shared/schema.ts +0 -188
  107. /package/lib/chunks/{chunk-6NXIK35R.js.map → chunk-522YXGDA.js.map} +0 -0
  108. /package/lib/chunks/{chunk-GDIUOJMD.js.map → chunk-CVYSXC27.js.map} +0 -0
  109. /package/lib/chunks/{chunk-UH445BGK.js.map → chunk-HZM5X5A7.js.map} +0 -0
  110. /package/lib/chunks/{chunk-QXIOO2RL.js.map → chunk-OKRR7ST5.js.map} +0 -0
  111. /package/lib/chunks/{monitoring-LXNVBD3G.js.map → monitoring-UCBNPPW2.js.map} +0 -0
  112. /package/lib/chunks/{rateLimiter-GG5LPWXJ.js.map → rateLimiter-XKECWM33.js.map} +0 -0
  113. /package/lib/chunks/{server-NODQAE3F.js.map → server-24XGDDO3.js.map} +0 -0
@@ -12,12 +12,13 @@
12
12
  import type { SupabaseClient } from '@supabase/supabase-js';
13
13
  import * as v from 'valibot';
14
14
 
15
- import { filterVisibleFields } from '@donotdev/core/server';
15
+ import { filterVisibleFields, prepareCreate } from '@donotdev/core/server';
16
16
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
17
17
  import { defaultFieldMapper } from '@donotdev/supabase/server';
18
18
 
19
19
  import { createMetadata } from '../../shared/metadata.js';
20
- import { DoNotDevError, validateDocument } from '../../shared/utils.js';
20
+ import { writtenOf } from '../../shared/crud/written.js';
21
+ import { DoNotDevError } from '../../shared/utils.js';
21
22
  import { createSupabaseHandler } from '../baseFunction.js';
22
23
  import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
23
24
 
@@ -122,8 +123,12 @@ async function checkUniqueKeys(
122
123
  /**
123
124
  * Create a Supabase Edge Function handler for creating an entity.
124
125
  *
126
+ * Status rule: a create without status gets `DEFAULT_STATUS_VALUE`; the CRUD rules
127
+ * picks the draft or create schema; the parse output is inserted, never the raw payload.
128
+ *
125
129
  * @param collection - The Supabase table name
126
- * @param documentSchema - The Valibot schema for document validation
130
+ * @param createDocumentSchema - The create schema (`createSchemas(entity).create`)
131
+ * @param draftDocumentSchema - The draft schema (`createSchemas(entity).draft`)
127
132
  * @param requiredRole - Minimum role required for this operation
128
133
  * @returns A `(req: Request) => Promise<Response>` handler for Deno.serve
129
134
  */
@@ -159,9 +164,9 @@ export function createSupabaseCreateEntity(
159
164
  }
160
165
  }
161
166
 
162
- // New records start as drafts unless the caller explicitly sets a status.
163
- const status = payload.status ?? 'draft';
164
- const isDraft = status === 'draft';
167
+ // CRUD create rules (core/schemas crud/create), as on the client.
168
+ const schemas = { create: createDocumentSchema, draft: draftDocumentSchema };
169
+ const isDraft = prepareCreate(schemas, payload).schemaKey === 'draft';
165
170
 
166
171
  // Check unique keys if schema has metadata with uniqueKeys
167
172
  const schemaWithMeta = createDocumentSchema as {
@@ -194,35 +199,20 @@ export function createSupabaseCreateEntity(
194
199
  ? normalizePayloadForUniqueKeys(payload, uniqueKeys)
195
200
  : payload;
196
201
 
197
- // Validate against the appropriate schema.
198
- // Drafts must validate with `schemas.draft` so required fields become
199
- // nullish/optional (instead of failing strict `schemas.create`).
200
- const payloadForValidation = { ...normalizedPayload, status };
201
- validateDocument(
202
- payloadForValidation,
203
- isDraft ? draftDocumentSchema : createDocumentSchema
204
- );
202
+ // Insert the rules' `written` (resulting status included), never the raw payload.
203
+ const written = writtenOf(prepareCreate(schemas, normalizedPayload), collection, 'create');
205
204
 
206
205
  const metadata = createMetadata(uid);
207
206
  const snakeMetadata = mapper.toBackendKeys(
208
207
  metadata as Record<string, unknown>
209
208
  );
210
-
211
- const {
212
- createdAt,
213
- updatedAt,
214
- created_at,
215
- updated_at,
216
- ...payloadWithoutTimestamps
217
- } = normalizedPayload;
218
- const snakePayload = mapper.toBackendKeys(payloadWithoutTimestamps);
209
+ const snakePayload = mapper.toBackendKeys(written);
219
210
 
220
211
  // Insert document (DB sets created_at/updated_at via triggers)
221
212
  const { data: inserted, error } = await supabaseAdmin
222
213
  .from(collection)
223
214
  .insert({
224
215
  ...snakePayload,
225
- status,
226
216
  ...snakeMetadata,
227
217
  })
228
218
  .select()
@@ -10,20 +10,39 @@
10
10
  * database policy hides them from non-admin users; the service role bypasses that
11
11
  * policy, so the store re-applies it on reads).
12
12
  *
13
- * No role or visibility masking: the caller is trusted server code. Atomic
14
- * multi-table writes stay in SQL functions (`client.rpc`).
13
+ * No role or visibility masking: the caller is trusted server code. Writes are
14
+ * still validated: each insert row / patch against the schema of its resulting
15
+ * status (the CRUD rules: `create`, `draft` or `update`; a patch reads the matched
16
+ * rows first, their stored status counts), and the parse output is what is written.
17
+ * A caller-chosen insert `id` is kept. Insert and patch types come from the descriptor (`CreateInput`,
18
+ * `DraftInput`, `UpdatePatch`: write classes `program`, `user`, `derived`).
19
+ * Atomic multi-table writes stay in SQL functions (`client.rpc`).
15
20
  *
16
- * @version 0.1.0
21
+ * @version 0.2.0
17
22
  * @since 0.5.0
18
23
  * @author AMBROISE PARK Consulting
19
24
  */
20
25
 
21
26
  import type { SupabaseClient } from '@supabase/supabase-js';
22
27
 
23
- import { HIDDEN_STATUSES } from '@donotdev/core/server';
24
- import type { AnyEntity, InferEntityRow } from '@donotdev/core/server';
28
+
29
+ import {
30
+ createSchemas,
31
+ HIDDEN_STATUSES,
32
+ prepareCreate,
33
+ prepareRemove,
34
+ prepareUpdate,
35
+ } from '@donotdev/core/server';
36
+ import type {
37
+ AnyEntity,
38
+ CreateInput,
39
+ DraftInput,
40
+ InferEntityRow,
41
+ UpdatePatch,
42
+ } from '@donotdev/core/server';
25
43
  import { createEntityAwareMapper } from '@donotdev/supabase/server';
26
44
 
45
+ import { writtenOf } from '../../shared/crud/written.js';
27
46
  import { DoNotDevError } from '../../shared/utils.js';
28
47
 
29
48
  /** Filter operators, same vocabulary as the list handler and the client CRUD. */
@@ -53,21 +72,55 @@ export interface EntityStoreQuery {
53
72
  includeHidden?: boolean;
54
73
  }
55
74
 
56
- /** Values written to a row: any subset of its fields; `null` clears a nullable column. */
75
+ /**
76
+ * Loose write values: any subset of the row's fields; `null` clears a nullable column.
77
+ * Default insert / patch type of {@link EntityStore}; `createEntityStore` narrows
78
+ * them to the descriptor types.
79
+ */
57
80
  export type EntityStoreValues<Row> = { [K in keyof Row]?: Row[K] | null };
58
81
 
59
- /** Entity-aware CRUD bound to one entity and one Supabase client. */
60
- export interface EntityStore<Row> {
82
+ /**
83
+ * Insert row of an entity store: a create, or a draft (`status: 'draft'`), with an
84
+ * optional caller-chosen `id` (write class never, but a minted id is allowed on
85
+ * insert: other rows may reference it).
86
+ */
87
+ export type EntityStoreInsert<E extends AnyEntity> = (CreateInput<E> | DraftInput<E>) & { id?: string };
88
+
89
+ /** Patch of an entity store: an update, or a draft write (`status: 'draft'`). */
90
+ export type EntityStorePatch<E extends AnyEntity> = UpdatePatch<E> | DraftInput<E>;
91
+
92
+ /**
93
+ * Entity-aware CRUD bound to one entity and one Supabase client.
94
+ *
95
+ * @template Row - Stored row
96
+ * @template Insert - Insert row type
97
+ * @template Patch - Update patch type
98
+ */
99
+ export interface EntityStore<Row, Insert = EntityStoreValues<Row>, Patch = EntityStoreValues<Row>> {
61
100
  /** Rows matching the query. */
62
101
  list(query?: EntityStoreQuery): Promise<Row[]>;
63
102
  /** The single row matching the query, or null; more than one row is an error. */
64
103
  find(query: EntityStoreQuery): Promise<Row | null>;
65
104
  /** Row by id, or null (hidden rows only with `includeHidden`). */
66
105
  get(id: string, options?: Pick<EntityStoreQuery, 'includeHidden' | 'select'>): Promise<Row | null>;
67
- /** Inserts rows and returns them as stored (database defaults and triggers applied). */
68
- insert(values: readonly EntityStoreValues<Row>[]): Promise<Row[]>;
69
- /** Updates the rows matching `where` (hidden rows included) and returns them as stored. */
70
- update(where: readonly EntityStoreCondition[], patch: EntityStoreValues<Row>): Promise<Row[]>;
106
+ /**
107
+ * Validates and inserts rows (CRUD create rules, `prepareCreate`); returns them as
108
+ * stored (database defaults and triggers applied). Unknown fields are logged, not
109
+ * written. A row's string `id` is kept (a minted id other rows reference); without
110
+ * one the database mints it.
111
+ */
112
+ insert(values: readonly Insert[]): Promise<Row[]>;
113
+ /**
114
+ * Validates the patch against each row matching `where` (hidden rows included; CRUD
115
+ * update rules, `prepareUpdate` on each stored row), then updates those rows; returns
116
+ * them as stored. Unknown fields are logged, not written.
117
+ */
118
+ update(where: readonly EntityStoreCondition[], patch: Patch): Promise<Row[]>;
119
+ /**
120
+ * Logical delete (CRUD rule 3) of the rows matching `where`: the update
121
+ * `{ status: 'deleted' }`. The hard delete is not part of the store.
122
+ */
123
+ remove(where: readonly EntityStoreCondition[]): Promise<void>;
71
124
  }
72
125
 
73
126
  const SAFE_FIELD_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
@@ -145,7 +198,8 @@ function applyCondition<Q extends Filterable>(query: Q, column: string, operator
145
198
  *
146
199
  * @param client - Supabase client the store runs with (service role in Edge Functions)
147
200
  * @param entity - Entity from `defineEntity()`; its collection is the table
148
- * @returns Store whose rows use the entity field names
201
+ * @returns Store whose rows use the entity field names; writes validated per status
202
+ * @throws DoNotDevError `invalid-argument` on an unknown field or a write that fails its schema
149
203
  *
150
204
  * @example
151
205
  * ```typescript
@@ -157,11 +211,15 @@ function applyCondition<Q extends Filterable>(query: Q, column: string, operator
157
211
  * const rows = await products.list({ where: [['id', 'in', ids]], select: ['name', 'sku'] });
158
212
  * ```
159
213
  *
160
- * @version 0.1.0
214
+ * @version 0.2.0
161
215
  * @since 0.5.0
162
216
  */
163
- export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, entity: E): EntityStore<InferEntityRow<E>> {
217
+ export function createEntityStore<E extends AnyEntity>(
218
+ client: SupabaseClient,
219
+ entity: E
220
+ ): EntityStore<InferEntityRow<E>, EntityStoreInsert<E>, EntityStorePatch<E>> {
164
221
  type Row = InferEntityRow<E>;
222
+ const schemas = createSchemas(entity);
165
223
  const fieldNames = Object.keys(entity.fields);
166
224
  const known = new Set(fieldNames);
167
225
  const mapper = createEntityAwareMapper(fieldNames);
@@ -185,6 +243,17 @@ export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, e
185
243
  return out;
186
244
  };
187
245
 
246
+ const insertRow = (row: object): Record<string, unknown> => {
247
+ const values = row as Record<string, unknown>;
248
+ const written = writtenOf(prepareCreate(schemas, values), table, 'insert');
249
+ // The rules never write `id`: a caller-chosen id is kept.
250
+ return toColumns(typeof values.id === 'string' ? { ...written, id: values.id } : written);
251
+ };
252
+
253
+ /** The patch as written to one stored row (CRUD update rules). */
254
+ const patchFor = (patch: Record<string, unknown>, stored: Record<string, unknown>): Record<string, unknown> =>
255
+ writtenOf(prepareUpdate(schemas, { id: String(stored.id), patch, stored }), table, 'update');
256
+
188
257
  const fromRows = (data: unknown): Row[] => ((data ?? []) as Record<string, unknown>[]).map((row) => mapper.fromBackendRow(row) as Row);
189
258
 
190
259
  const fail = (operation: string, error: { message: string }): never => {
@@ -224,7 +293,7 @@ export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, e
224
293
  async insert(values) {
225
294
  if (values.length === 0) return [];
226
295
  const { data, error } = await from()
227
- .insert(values.map((v) => toColumns(v as Record<string, unknown>)))
296
+ .insert(values.map(insertRow))
228
297
  .select('*');
229
298
  if (error) fail('insert', error);
230
299
  return fromRows(data);
@@ -232,9 +301,29 @@ export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, e
232
301
 
233
302
  async update(where, patch) {
234
303
  if (where.length === 0) throw new DoNotDevError(`${entity.name}: update without a condition`, 'invalid-argument');
235
- const { data, error } = await filtered(from().update(toColumns(patch as Record<string, unknown>)), where, true).select('*');
304
+ const values = patch as Record<string, unknown>;
305
+ // Each stored row gives the patch its status and a published draft its record.
306
+ const targets = await list({ where, includeHidden: true });
307
+ if (targets.length === 0) return [];
308
+ let written: Record<string, unknown> = {};
309
+ for (const row of targets) written = patchFor(values, row as Record<string, unknown>);
310
+ // Only the validated rows: `where` again (concurrency guards) and their ids.
311
+ const ids = targets.map((row) => (row as Record<string, unknown>).id);
312
+ const { data, error } = await filtered(from().update(toColumns(written)), [...where, ['id', 'in', ids]], true).select('*');
236
313
  if (error) fail('update', error);
237
314
  return fromRows(data);
238
315
  },
316
+
317
+ async remove(where) {
318
+ if (where.length === 0) throw new DoNotDevError(`${entity.name}: remove without a condition`, 'invalid-argument');
319
+ const targets = await list({ where, includeHidden: true, select: ['id'] });
320
+ const first = targets[0] as Record<string, unknown> | undefined;
321
+ if (!first) return;
322
+ // CRUD rule 3 (core/schemas crud/update `prepareRemove`): the same patch for every row.
323
+ const written = writtenOf(prepareRemove(schemas, String(first.id)), table, 'remove');
324
+ const ids = targets.map((row) => (row as Record<string, unknown>).id);
325
+ const { error } = await filtered(from().update(toColumns(written)), [...where, ['id', 'in', ids]], true).select('id');
326
+ if (error) fail('remove', error);
327
+ },
239
328
  };
240
329
  }
@@ -11,11 +11,7 @@
11
11
 
12
12
  import * as v from 'valibot';
13
13
 
14
- import {
15
- filterVisibleFields,
16
- hasRoleAccess,
17
- HIDDEN_STATUSES,
18
- } from '@donotdev/core/server';
14
+ import { filterVisibleFields, isReadableBy } from '@donotdev/core/server';
19
15
  import type { EntityOwnershipConfig, UserRole } from '@donotdev/core/server';
20
16
  import {
21
17
  createEntityAwareMapper,
@@ -67,13 +63,8 @@ export function createSupabaseGetEntity(
67
63
  throw new DoNotDevError('Entity not found', 'not-found');
68
64
  }
69
65
 
70
- const isAdmin = hasRoleAccess(userRole, 'admin');
71
-
72
- // Hide drafts/deleted from non-admin users (security: hidden statuses never reach public)
73
- if (
74
- !isAdmin &&
75
- (HIDDEN_STATUSES as readonly string[]).includes(row.status)
76
- ) {
66
+ // CRUD rule 4 (core/schemas crud/read): hidden statuses never reach non-admins
67
+ if (!isReadableBy(row, userRole)) {
77
68
  throw new DoNotDevError('Entity not found', 'not-found');
78
69
  }
79
70
 
@@ -16,7 +16,7 @@ import * as v from 'valibot';
16
16
  import {
17
17
  filterVisibleFields,
18
18
  hasRoleAccess,
19
- HIDDEN_STATUSES,
19
+ hiddenStatusesFor,
20
20
  } from '@donotdev/core/server';
21
21
  import type {
22
22
  EntityOwnershipConfig,
@@ -217,9 +217,10 @@ export function createSupabaseListEntities(
217
217
  .from(collection)
218
218
  .select(selectFields, { count: 'exact' });
219
219
 
220
- // Filter out hidden statuses for non-admin users
221
- if (!isAdmin) {
222
- query = query.not('status', 'in', [...HIDDEN_STATUSES]);
220
+ // CRUD rule 4 (core/schemas crud/read): hidden statuses never reach non-admins
221
+ const hidden = hiddenStatusesFor(userRole);
222
+ if (hidden.length > 0) {
223
+ query = query.not('status', 'in', [...hidden]);
223
224
  }
224
225
 
225
226
  // Ownership: when set and not admin, listCard = public condition, list = mine filter
@@ -12,11 +12,13 @@
12
12
  import type { SupabaseClient } from '@supabase/supabase-js';
13
13
  import * as v from 'valibot';
14
14
 
15
+ import { prepareUpdate } from '@donotdev/core/server';
15
16
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
16
17
  import { defaultFieldMapper } from '@donotdev/supabase/server';
17
18
 
18
19
  import { updateMetadata } from '../../shared/metadata.js';
19
- import { DoNotDevError, validateDocument } from '../../shared/utils.js';
20
+ import { writtenOf } from '../../shared/crud/written.js';
21
+ import { DoNotDevError } from '../../shared/utils.js';
20
22
  import { createSupabaseHandler } from '../baseFunction.js';
21
23
  import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
22
24
 
@@ -95,8 +97,13 @@ async function checkUniqueKeys(
95
97
  /**
96
98
  * Create a Supabase Edge Function handler for updating an entity.
97
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
+ *
98
104
  * @param collection - The Supabase table name
99
- * @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
100
107
  * @param requiredRole - Minimum role required for this operation
101
108
  * @returns A `(req: Request) => Promise<Response>` handler for Deno.serve
102
109
  */
@@ -104,6 +111,8 @@ export function createSupabaseUpdateEntity(
104
111
  collection: string,
105
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)
106
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>>,
107
116
  requiredRole: UserRole
108
117
  ) {
109
118
  const requestSchema = v.object({
@@ -149,8 +158,13 @@ export function createSupabaseUpdateEntity(
149
158
  ...(mapper.fromBackendRow(existing) as Record<string, unknown>),
150
159
  ...payload,
151
160
  };
152
- const status = merged.status ?? existing.status;
153
- 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';
154
168
 
155
169
  // Check unique keys if schema has metadata with uniqueKeys
156
170
  const schemaWithMeta = documentSchema as {
@@ -169,25 +183,13 @@ export function createSupabaseUpdateEntity(
169
183
  );
170
184
  }
171
185
 
172
- // Validate merged document (skip for drafts)
173
- if (!isDraft) {
174
- validateDocument(merged, documentSchema);
175
- }
186
+ const written = writtenOf(prepared, collection, 'update');
176
187
 
177
188
  const metadata = updateMetadata(uid);
178
189
  const snakeMetadata = mapper.toBackendKeys(
179
190
  metadata as Record<string, unknown>
180
191
  );
181
-
182
- const {
183
- createdAt,
184
- updatedAt,
185
- created_at,
186
- updated_at,
187
- id: _id,
188
- ...payloadWithoutTimestamps
189
- } = payload;
190
- const snakePayload = mapper.toBackendKeys(payloadWithoutTimestamps);
192
+ const snakePayload = mapper.toBackendKeys(written);
191
193
 
192
194
  // Update document (DB sets updated_at via trigger)
193
195
  const { data: updated, error } = await supabaseAdmin
@@ -45,6 +45,13 @@ export type {
45
45
  // Custom StripeOrder entry points (app request shape, own StripeSessionProvider)
46
46
  export { createCheckoutAlgorithm } from '../shared/billing/createCheckout.js';
47
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';
48
55
  export { STRIPE_API_VERSION_PIN } from '../shared/billing/apiVersion.js';
49
56
  export { createCancelSubscription } from './billing/cancelSubscription.js';
50
57
  export { createChangePlan } from './billing/changePlan.js';
@@ -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
 
@@ -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 () => {
@@ -23,7 +23,6 @@ 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';
@@ -33,7 +32,10 @@ import {
33
32
  DoNotDevError,
34
33
  handleError,
35
34
  } from '../../../shared/errorHandling.js';
36
- import { prepareForFirestore } from '../../../shared/firebase.js';
35
+ import {
36
+ prepareForFirestore,
37
+ transformFirestoreData,
38
+ } from '../../../shared/firebase.js';
37
39
  import { createMetadata, updateMetadata } from '../../../shared/metadata.js';
38
40
  import { verifyAuthToken } from '../../../shared/utils/internal/auth.js';
39
41
  import { validateCollectionName } from '../../../shared/utils.js';
@@ -44,8 +46,12 @@ import { validateCollectionName } from '../../../shared/utils.js';
44
46
  * structural checks already enforced by {@link BulkRequestSchema}. Both
45
47
  * inserts and update patches are opaque objects at this layer.
46
48
  */
47
- const PASSTHROUGH_INSERT_SCHEMA = BulkInsertSchema;
48
- 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({});
49
55
 
50
56
  /**
51
57
  * HTTP handler for `POST /api/crud/:collection/bulk`.
@@ -121,6 +127,7 @@ export default async function handler(
121
127
  // the structural row schemas so per-row validation is a no-op beyond
122
128
  // what `BulkRequestSchema` already enforces.
123
129
  createSchema: PASSTHROUGH_INSERT_SCHEMA,
130
+ draftCreateSchema: PASSTHROUGH_INSERT_SCHEMA,
124
131
  updateSchema: PASSTHROUGH_PATCH_SCHEMA,
125
132
  // URL-routed handler has no entity ACL config — the per-bucket ACL in
126
133
  // `executeBulk` still enforces "populated bucket requires role", so we
@@ -129,6 +136,22 @@ export default async function handler(
129
136
  access: { create: 'user', update: 'user', delete: 'user' },
130
137
  uid,
131
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
+ },
132
155
  mintInsertId: () =>
133
156
  getFirebaseAdminFirestore()
134
157
  .collection(collection as string)
@@ -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,6 +16,7 @@
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
22
  import { DoNotDevError, handleError } from '../../../shared/errorHandling.js';
@@ -20,10 +26,8 @@ import {
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,
@@ -47,23 +51,17 @@ export default async function handler(
47
51
  // W22: Validate collection name from client-supplied schema
48
52
  validateCollectionName(schema.metadata.collection);
49
53
 
50
- // New records start as drafts unless the caller explicitly sets a status.
51
- const status = payload.status ?? 'draft';
52
-
53
- // Validate the document against the schema.
54
- // Draft handling is schema-driven: `schemas.draft` must convert required
55
- // fields into nullish/optional, so we still validate drafts.
56
- const payloadForValidation = {
57
- ...payload,
58
- status,
59
- };
60
- 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
+ );
61
61
 
62
62
  // Prepare the document for Firestore and add metadata
63
- // Always ensure status is set
64
63
  const documentData = {
65
- ...prepareForFirestore(payload),
66
- status, // Ensure status is always present
64
+ ...prepareForFirestore(written),
67
65
  ...createMetadata(uid),
68
66
  };
69
67
 
@@ -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
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
 
@@ -60,9 +59,9 @@ export default async function handler(
60
59
  handleError(new Error('Document not found'));
61
60
  }
62
61
 
63
- // 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
64
63
  const docData = doc.data();
65
- if ((HIDDEN_STATUSES as readonly string[]).includes(docData?.status)) {
64
+ if (!isReadableBy(docData, undefined)) {
66
65
  handleError(new Error('Document not found'));
67
66
  }
68
67
 
@@ -72,8 +71,8 @@ export default async function handler(
72
71
  ...docData,
73
72
  });
74
73
 
75
- // Filter visible fields based on schema
76
- 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');
77
76
 
78
77
  return res.status(200).json(filteredData);
79
78
  } catch (error) {