@wordrhyme/auto-crud-server 2.0.3 → 2.1.1

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.
package/README.md CHANGED
@@ -1145,6 +1145,11 @@ create index tasks_tenant_created_at_id_idx
1145
1145
  应为真实文本列配置 `pg_trgm` GIN 索引;JSON/custom expression 需要与生成 SQL 一致的
1146
1146
  表达式索引。
1147
1147
 
1148
+ 可信扩展 provider 的 `getMetadata()` 可以通过 `fields[fieldId].search: false`
1149
+ 关闭某个基础字段的全局搜索。该覆盖同时收窄能力元数据、列表、数量统计及导出查询;
1150
+ 未声明覆盖的字段沿用 router 的搜索白名单。`search: true` 不会把白名单以外的基础字段
1151
+ 加入搜索,router 的 `search: false` 仍关闭整个搜索能力。客户端不能通过请求参数扩大范围。
1152
+
1148
1153
  扩展字段筛选与搜索使用可信服务端 provider 的 `buildConditions` 契约。Host 接收
1149
1154
  CRUD target、原表 ID 列、扩展筛选条件和搜索词,返回组织隔离的 SQL `filter` / `search`
1150
1155
  条件(例如关联 `EXISTS`),不返回全量 ID 数组。基础筛选与扩展筛选按 `joinOperator`
@@ -1308,3 +1313,11 @@ const t = initTRPC
1308
1313
  .meta<Partial<CrudResourceMetadata> & { permission?: string }>()
1309
1314
  .create();
1310
1315
  ```
1316
+
1317
+ ## Optional batch counts
1318
+
1319
+ Set `counts: true` on `createCrudRouter` to expose `counts({ queries })`. Each query has a unique `key` and the ordinary list `filters`, `joinOperator`, and optional `search`. A batch accepts 1–100 queries and returns `{ counts: { [key]: number } }` from one conditional aggregate SQL query.
1320
+
1321
+ This route uses the list procedure, guard, scope, soft deletion and extension conditions. It does not load or enrich rows. Keep the supplied database scoped to the caller. Counts are disabled by default. If list middleware transforms filters or enforces additional visibility restrictions, supply the equivalent transformation through `middleware.counts({ ctx, input, next })` before opting in; row enrichment middleware is deliberately not executed.
1322
+
1323
+ The database provider must implement governed `$counts(table, predicates)`, applying the same tenant, row and field observation rules as scalar counts. Missing support returns `PRECONDITION_FAILED`; this route never falls back to raw aggregation or repeated list calls. Deliver the Host capability before enabling counts in consumers, and pin a published Components version containing this route.
package/dist/index.cjs CHANGED
@@ -777,10 +777,22 @@ function mergeCrudCapabilities(base, extension, disabled) {
777
777
  sort: mergeFieldCapability(base.sort, extension?.sort, disabled.sort)
778
778
  };
779
779
  }
780
+ function allowsSearch(fields, id) {
781
+ const field = fields?.[id];
782
+ return !(field && typeof field === "object" && "search" in field && field.search === false);
783
+ }
780
784
  function withCrudCapabilities(metadata, capabilities, disabled) {
785
+ const merged = mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled);
786
+ const fields = merged.search.fields.filter((id) => allowsSearch(metadata?.fields, id));
781
787
  return {
782
788
  ...metadata ?? {},
783
- capabilities: mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled)
789
+ capabilities: {
790
+ ...merged,
791
+ search: {
792
+ enabled: merged.search.enabled && (merged.search.fields.length === 0 || fields.length > 0 || metadata?.capabilities?.search?.enabled === true && metadata.capabilities.search.fields.length === 0),
793
+ fields
794
+ }
795
+ }
784
796
  };
785
797
  }
786
798
  function getTableColumn(table, columnId) {
@@ -1157,6 +1169,15 @@ function combineConditions(...conditions) {
1157
1169
  if (filtered.length === 1) return filtered[0];
1158
1170
  return (0, drizzle_orm.and)(...filtered);
1159
1171
  }
1172
+ const baseCountsInputSchema = zod.z.object({ queries: zod.z.array(baseListInputSchema.pick({
1173
+ filters: true,
1174
+ search: true,
1175
+ joinOperator: true
1176
+ }).extend({ key: zod.z.string().trim().min(1).max(100).refine((key) => ![
1177
+ "__proto__",
1178
+ "constructor",
1179
+ "prototype"
1180
+ ].includes(key), { message: "Count query key is reserved" }) }).strict()).min(1).max(100) }).strict().refine((input) => new Set(input.queries.map((query) => query.key)).size === input.queries.length, { message: "Count query keys must be unique" });
1160
1181
  /**
1161
1182
  * 创建 CRUD Router
1162
1183
  *
@@ -1319,6 +1340,39 @@ function createCrudRouter(config) {
1319
1340
  message: `Forbidden: Cannot ${operation} this resource`
1320
1341
  });
1321
1342
  };
1343
+ const querySearch = async (ctx, search) => {
1344
+ if (!search?.trim() || !Array.isArray(searchColumns)) return searchColumns;
1345
+ const target = readCrudTarget(config);
1346
+ const provider = resolveCrudExtensions(ctx, config);
1347
+ if (!target || !provider?.getMetadata) return searchColumns;
1348
+ const metadata = await provider.getMetadata({ id: target.id });
1349
+ return searchColumns.filter((column) => allowsSearch(metadata.fields, getColumnRefId(column)));
1350
+ };
1351
+ const queryWhere = async (ctx, input) => {
1352
+ const columns = await querySearch(ctx, input.search);
1353
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, input);
1354
+ const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
1355
+ const filterCondition = validatedFilters?.length ? filterColumns({
1356
+ table,
1357
+ filters: validatedFilters,
1358
+ joinOperator: effectiveInput.joinOperator,
1359
+ resolveColumn: (columnId) => {
1360
+ const id = String(columnId);
1361
+ if (id === idField) return getTableColumn(table, idField);
1362
+ return resolveColumnTarget({
1363
+ table,
1364
+ columnId: id,
1365
+ allowedColumns: filterableColumns
1366
+ });
1367
+ },
1368
+ resolveDateRange: ctx.resolveDateRange
1369
+ }) : void 0;
1370
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1371
+ return {
1372
+ effectiveInput,
1373
+ where: buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition))
1374
+ };
1375
+ };
1322
1376
  const procedures = {
1323
1377
  meta: metaProcedure.output(metadataOutputSchema).query(async ({ ctx }) => {
1324
1378
  await withGuard(ctx, "list");
@@ -1328,29 +1382,35 @@ function createCrudRouter(config) {
1328
1382
  if (!provider?.getMetadata) return withCrudCapabilities({}, capabilities, disabledCapabilities);
1329
1383
  return withCrudCapabilities(await provider.getMetadata({ id: target.id }), capabilities, disabledCapabilities);
1330
1384
  }),
1385
+ ...config.counts ? { counts: resolved.procedureFactory("list").input(baseCountsInputSchema).output(zod.z.object({ counts: zod.z.record(zod.z.string(), zod.z.number().int().nonnegative()) })).query(async ({ ctx, input }) => {
1386
+ await withGuard(ctx, "list");
1387
+ const count = async (batch) => {
1388
+ if (typeof ctx.db.$counts !== "function") throw new __trpc_server.TRPCError({
1389
+ code: "PRECONDITION_FAILED",
1390
+ message: "Batch counts require a database provider with scoped $counts support"
1391
+ });
1392
+ const conditions = Object.create(null);
1393
+ for (const query of batch.queries) {
1394
+ const { where } = await queryWhere(ctx, {
1395
+ ...query,
1396
+ page: 1,
1397
+ perPage: 1
1398
+ });
1399
+ conditions[query.key] = where;
1400
+ }
1401
+ return { counts: await ctx.db.$counts(table, conditions) };
1402
+ };
1403
+ return m.counts ? m.counts({
1404
+ ctx,
1405
+ input,
1406
+ next: async (modified) => count(modified ?? input)
1407
+ }) : count(input);
1408
+ }) } : {},
1331
1409
  list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
1332
1410
  await withGuard(ctx, "list");
1333
1411
  const doList = async (listInput$1) => {
1334
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, listInput$1);
1412
+ const { effectiveInput, where } = await queryWhere(ctx, listInput$1);
1335
1413
  const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
1336
- const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
1337
- const filterCondition = validatedFilters?.length ? filterColumns({
1338
- table,
1339
- filters: validatedFilters,
1340
- joinOperator: effectiveInput.joinOperator,
1341
- resolveColumn: (columnId) => {
1342
- const id = String(columnId);
1343
- if (id === idField) return getTableColumn(table, idField);
1344
- return resolveColumnTarget({
1345
- table,
1346
- columnId: id,
1347
- allowedColumns: filterableColumns
1348
- });
1349
- },
1350
- resolveDateRange: ctx.resolveDateRange
1351
- }) : void 0;
1352
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1353
- const where = buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1354
1414
  let query = ctx.db.select().from(table).$dynamic();
1355
1415
  if (where) query = query.where(where);
1356
1416
  const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
@@ -1494,6 +1554,10 @@ function createCrudRouter(config) {
1494
1554
  let deleted;
1495
1555
  if (softDelete) [deleted] = await writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(where).returning();
1496
1556
  else [deleted] = await writeCtx.db.delete(table).where(where).returning();
1557
+ if (!deleted) throw new __trpc_server.TRPCError({
1558
+ code: "NOT_FOUND",
1559
+ message: "Resource not found or access denied"
1560
+ });
1497
1561
  await emitCrudWriteLifecycle(writeCtx, config, "delete", {
1498
1562
  id: input,
1499
1563
  row: deleted,
@@ -1515,8 +1579,29 @@ function createCrudRouter(config) {
1515
1579
  await withGuard(ctx, "deleteMany");
1516
1580
  const where = buildWhere(ctx, "deleteMany", (0, drizzle_orm.inArray)(getIdColumn(), input));
1517
1581
  const doDeleteMany = async () => {
1518
- if (softDelete) return { deleted: (await ctx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(where).returning({ id: getIdColumn() })).length };
1519
- else return { deleted: (await ctx.db.delete(table).where(where).returning({ id: getIdColumn() })).length };
1582
+ return runCrudExtensionWriteTransaction(ctx, config, {
1583
+ data: {},
1584
+ rawValues: { ids: input },
1585
+ baseValues: {},
1586
+ extraValues: null
1587
+ }, async (writeCtx) => {
1588
+ const emitLifecycle = shouldWrapCrudLifecycleTransaction(writeCtx, config);
1589
+ const existingRows = emitLifecycle && softDelete ? await writeCtx.db.select().from(table).where(where).for("update") : [];
1590
+ const existingById = new Map(existingRows.map((row) => [row[idField], row]));
1591
+ const deleteWhere = emitLifecycle && softDelete ? (0, drizzle_orm.and)(where, (0, drizzle_orm.inArray)(getIdColumn(), [...existingById.keys()])) : where;
1592
+ const query = softDelete ? writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(deleteWhere) : writeCtx.db.delete(table).where(where);
1593
+ const deleted = emitLifecycle ? await query.returning() : await query.returning({ id: getIdColumn() });
1594
+ if (emitLifecycle) for (const row of deleted) {
1595
+ const id = row[idField];
1596
+ await emitCrudWriteLifecycle(writeCtx, config, "delete", {
1597
+ id,
1598
+ row,
1599
+ existing: softDelete ? existingById.get(id) : row,
1600
+ entityId: id
1601
+ });
1602
+ }
1603
+ return { deleted: deleted.length };
1604
+ });
1520
1605
  };
1521
1606
  if (m.deleteMany) return m.deleteMany({
1522
1607
  ctx,
@@ -1613,7 +1698,8 @@ function createCrudRouter(config) {
1613
1698
  export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
1614
1699
  await withGuard(ctx, "export");
1615
1700
  const doExport = async (exportInput$1) => {
1616
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, {
1701
+ const columns = await querySearch(ctx, exportInput$1.search);
1702
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
1617
1703
  page: 1,
1618
1704
  perPage: Math.min(Math.max(exportInput$1.limit ?? maxExportSize, 1), maxExportSize),
1619
1705
  joinOperator: exportInput$1.joinOperator ?? "and",
@@ -1636,7 +1722,7 @@ function createCrudRouter(config) {
1636
1722
  },
1637
1723
  resolveDateRange: ctx.resolveDateRange
1638
1724
  }) : void 0;
1639
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1725
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1640
1726
  const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1641
1727
  let query = ctx.db.select().from(table).$dynamic();
1642
1728
  if (where) query = query.where(where);
@@ -1849,6 +1935,7 @@ const appRouter = router({});
1849
1935
  //#endregion
1850
1936
  exports.afterMiddleware = afterMiddleware;
1851
1937
  exports.appRouter = appRouter;
1938
+ exports.baseCountsInputSchema = baseCountsInputSchema;
1852
1939
  exports.baseExportInputSchema = baseExportInputSchema;
1853
1940
  exports.baseGetInputSchema = baseGetInputSchema;
1854
1941
  exports.baseListInputSchema = baseListInputSchema;
package/dist/index.d.cts CHANGED
@@ -146,9 +146,17 @@ interface ListInput {
146
146
  }>;
147
147
  joinOperator: 'and' | 'or';
148
148
  }
149
- /**
150
- * 列表查询结果类型
151
- */
149
+ /** Named filters for a single batch count. */
150
+ type CountQuery = Pick<ListInput, 'search' | 'filters' | 'joinOperator'> & {
151
+ key: string;
152
+ };
153
+ interface CountsInput {
154
+ queries: CountQuery[];
155
+ }
156
+ interface CountsResult {
157
+ counts: Record<string, number>;
158
+ }
159
+ /** 列表查询结果类型 */
152
160
  interface ListResult<TSelect> {
153
161
  data: TSelect[];
154
162
  total: number;
@@ -419,6 +427,12 @@ interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknow
419
427
  * 列表查询包装器
420
428
  */
421
429
  list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<ListResult<TSelect>>;
430
+ /** Batch counts use list authorization, but do not run row enrichment. */
431
+ counts?: (params: {
432
+ ctx: TContext;
433
+ input: CountsInput;
434
+ next: (input?: CountsInput) => Promise<CountsResult>;
435
+ }) => Promise<CountsResult>;
422
436
  /**
423
437
  * 单条查询包装器
424
438
  */
@@ -581,6 +595,8 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
581
595
  * - provider/function: explicitly use this provider.
582
596
  */
583
597
  extensions?: CrudExtensionsConfig<TContext>;
598
+ /** Opt in after supplying any list-specific filter transformations in middleware.counts. */
599
+ counts?: boolean;
584
600
  /**
585
601
  * 主 Schema(用于 create/upsert 输入验证)
586
602
  * - 如果不传,自动从 table 派生并排除 omitFields
@@ -804,6 +820,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
804
820
  middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput>;
805
821
  }
806
822
  interface CrudProcedures {
823
+ counts?: AnyProcedure;
807
824
  meta: AnyProcedure;
808
825
  list: AnyProcedure;
809
826
  get: AnyProcedure;
@@ -916,6 +933,47 @@ declare const baseExportInputSchema: z.ZodObject<{
916
933
  }>>;
917
934
  limit: z.ZodOptional<z.ZodNumber>;
918
935
  }, z.core.$strip>;
936
+ declare const baseCountsInputSchema: z.ZodObject<{
937
+ queries: z.ZodArray<z.ZodObject<{
938
+ search: z.ZodOptional<z.ZodString>;
939
+ filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
940
+ id: z.ZodString;
941
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
942
+ variant: z.ZodEnum<{
943
+ number: "number";
944
+ boolean: "boolean";
945
+ date: "date";
946
+ text: "text";
947
+ range: "range";
948
+ dateRange: "dateRange";
949
+ select: "select";
950
+ multiSelect: "multiSelect";
951
+ }>;
952
+ operator: z.ZodEnum<{
953
+ iLike: "iLike";
954
+ notILike: "notILike";
955
+ eq: "eq";
956
+ ne: "ne";
957
+ isEmpty: "isEmpty";
958
+ isNotEmpty: "isNotEmpty";
959
+ lt: "lt";
960
+ lte: "lte";
961
+ gt: "gt";
962
+ gte: "gte";
963
+ isBetween: "isBetween";
964
+ isRelativeToToday: "isRelativeToToday";
965
+ inArray: "inArray";
966
+ notInArray: "notInArray";
967
+ }>;
968
+ filterId: z.ZodString;
969
+ }, z.core.$strip>>>;
970
+ joinOperator: z.ZodDefault<z.ZodEnum<{
971
+ and: "and";
972
+ or: "or";
973
+ }>>;
974
+ key: z.ZodString;
975
+ }, z.core.$strict>>;
976
+ }, z.core.$strict>;
919
977
  /**
920
978
  * 创建 CRUD Router
921
979
  *
@@ -1029,4 +1087,4 @@ declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
1029
1087
  }, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
1030
1088
  type AppRouter = typeof appRouter;
1031
1089
  //#endregion
1032
- export { type AnyProcedure, type AppRouter, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
1090
+ export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
package/dist/index.d.ts CHANGED
@@ -147,9 +147,17 @@ interface ListInput {
147
147
  }>;
148
148
  joinOperator: 'and' | 'or';
149
149
  }
150
- /**
151
- * 列表查询结果类型
152
- */
150
+ /** Named filters for a single batch count. */
151
+ type CountQuery = Pick<ListInput, 'search' | 'filters' | 'joinOperator'> & {
152
+ key: string;
153
+ };
154
+ interface CountsInput {
155
+ queries: CountQuery[];
156
+ }
157
+ interface CountsResult {
158
+ counts: Record<string, number>;
159
+ }
160
+ /** 列表查询结果类型 */
153
161
  interface ListResult<TSelect> {
154
162
  data: TSelect[];
155
163
  total: number;
@@ -420,6 +428,12 @@ interface CrudMiddleware<TContext = unknown, TSelect = unknown, TInsert = unknow
420
428
  * 列表查询包装器
421
429
  */
422
430
  list?: (params: ListMiddlewareParams<TContext, TSelect, TListInput>) => Promise<ListResult<TSelect>>;
431
+ /** Batch counts use list authorization, but do not run row enrichment. */
432
+ counts?: (params: {
433
+ ctx: TContext;
434
+ input: CountsInput;
435
+ next: (input?: CountsInput) => Promise<CountsResult>;
436
+ }) => Promise<CountsResult>;
423
437
  /**
424
438
  * 单条查询包装器
425
439
  */
@@ -582,6 +596,8 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
582
596
  * - provider/function: explicitly use this provider.
583
597
  */
584
598
  extensions?: CrudExtensionsConfig<TContext>;
599
+ /** Opt in after supplying any list-specific filter transformations in middleware.counts. */
600
+ counts?: boolean;
585
601
  /**
586
602
  * 主 Schema(用于 create/upsert 输入验证)
587
603
  * - 如果不传,自动从 table 派生并排除 omitFields
@@ -805,6 +821,7 @@ interface CrudRouterConfig<TTable extends PgTable = PgTable, TContext = unknown,
805
821
  middleware?: CrudMiddleware<TContext, TSelect, TInsert, TUpdate, TListInput, TGetInput, TExportInput>;
806
822
  }
807
823
  interface CrudProcedures {
824
+ counts?: AnyProcedure;
808
825
  meta: AnyProcedure;
809
826
  list: AnyProcedure;
810
827
  get: AnyProcedure;
@@ -917,6 +934,47 @@ declare const baseExportInputSchema: z.ZodObject<{
917
934
  }>>;
918
935
  limit: z.ZodOptional<z.ZodNumber>;
919
936
  }, z.core.$strip>;
937
+ declare const baseCountsInputSchema: z.ZodObject<{
938
+ queries: z.ZodArray<z.ZodObject<{
939
+ search: z.ZodOptional<z.ZodString>;
940
+ filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
941
+ id: z.ZodString;
942
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
943
+ variant: z.ZodEnum<{
944
+ number: "number";
945
+ boolean: "boolean";
946
+ date: "date";
947
+ text: "text";
948
+ range: "range";
949
+ dateRange: "dateRange";
950
+ select: "select";
951
+ multiSelect: "multiSelect";
952
+ }>;
953
+ operator: z.ZodEnum<{
954
+ iLike: "iLike";
955
+ notILike: "notILike";
956
+ eq: "eq";
957
+ ne: "ne";
958
+ isEmpty: "isEmpty";
959
+ isNotEmpty: "isNotEmpty";
960
+ lt: "lt";
961
+ lte: "lte";
962
+ gt: "gt";
963
+ gte: "gte";
964
+ isBetween: "isBetween";
965
+ isRelativeToToday: "isRelativeToToday";
966
+ inArray: "inArray";
967
+ notInArray: "notInArray";
968
+ }>;
969
+ filterId: z.ZodString;
970
+ }, z.core.$strip>>>;
971
+ joinOperator: z.ZodDefault<z.ZodEnum<{
972
+ and: "and";
973
+ or: "or";
974
+ }>>;
975
+ key: z.ZodString;
976
+ }, z.core.$strict>>;
977
+ }, z.core.$strict>;
920
978
  /**
921
979
  * 创建 CRUD Router
922
980
  *
@@ -1030,4 +1088,4 @@ declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
1030
1088
  }, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
1031
1089
  type AppRouter = typeof appRouter;
1032
1090
  //#endregion
1033
- export { type AnyProcedure, type AppRouter, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
1091
+ export { type AnyProcedure, type AppRouter, type CountQuery, type CountsInput, type CountsResult, type CreateManyMiddlewareParams, type CreateMiddlewareParams, type CrudCapabilityMetadata, type CrudColumnCapability, type CrudColumnConfig, type CrudColumnExpression, type CrudColumnRef, type CrudExtensionFilter, type CrudExtensionMetadata, type CrudExtensionValueWrite, type CrudExtensionsConfig, type CrudExtensionsProvider, type CrudHookEventMap, type CrudMiddleware, type CrudOperation, type CrudProcedures, type CrudResourceMetadata, type CrudRouterConfig, type DateFilterRange, type DateRangeResolver, type DeleteManyMiddlewareParams, type DeleteMiddlewareParams, type ExportInput, type ExportMiddlewareParams, type ExportResult, type ExtendedColumnFilter, type FilterOperator, type FilterVariant, type GetInput, type GetMiddlewareParams, type ImportFailedRow, type ImportInput, type ImportMiddlewareParams, type ImportResult, type ListInput, type ListMiddlewareParams, type ListResult, type ProcedureConfig, type ProcedureFactory, type ProcedureMap, type SoftDeleteConfig, type SoftDeleteOption, type UpdateManyMiddlewareParams, type UpdateMiddlewareParams, type UpsertMiddlewareParams, type WriteOperation, afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
package/dist/index.js CHANGED
@@ -746,10 +746,22 @@ function mergeCrudCapabilities(base, extension, disabled) {
746
746
  sort: mergeFieldCapability(base.sort, extension?.sort, disabled.sort)
747
747
  };
748
748
  }
749
+ function allowsSearch(fields, id) {
750
+ const field = fields?.[id];
751
+ return !(field && typeof field === "object" && "search" in field && field.search === false);
752
+ }
749
753
  function withCrudCapabilities(metadata, capabilities, disabled) {
754
+ const merged = mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled);
755
+ const fields = merged.search.fields.filter((id) => allowsSearch(metadata?.fields, id));
750
756
  return {
751
757
  ...metadata ?? {},
752
- capabilities: mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled)
758
+ capabilities: {
759
+ ...merged,
760
+ search: {
761
+ enabled: merged.search.enabled && (merged.search.fields.length === 0 || fields.length > 0 || metadata?.capabilities?.search?.enabled === true && metadata.capabilities.search.fields.length === 0),
762
+ fields
763
+ }
764
+ }
753
765
  };
754
766
  }
755
767
  function getTableColumn(table, columnId) {
@@ -1126,6 +1138,15 @@ function combineConditions(...conditions) {
1126
1138
  if (filtered.length === 1) return filtered[0];
1127
1139
  return and(...filtered);
1128
1140
  }
1141
+ const baseCountsInputSchema = z.object({ queries: z.array(baseListInputSchema.pick({
1142
+ filters: true,
1143
+ search: true,
1144
+ joinOperator: true
1145
+ }).extend({ key: z.string().trim().min(1).max(100).refine((key) => ![
1146
+ "__proto__",
1147
+ "constructor",
1148
+ "prototype"
1149
+ ].includes(key), { message: "Count query key is reserved" }) }).strict()).min(1).max(100) }).strict().refine((input) => new Set(input.queries.map((query) => query.key)).size === input.queries.length, { message: "Count query keys must be unique" });
1129
1150
  /**
1130
1151
  * 创建 CRUD Router
1131
1152
  *
@@ -1288,6 +1309,39 @@ function createCrudRouter(config) {
1288
1309
  message: `Forbidden: Cannot ${operation} this resource`
1289
1310
  });
1290
1311
  };
1312
+ const querySearch = async (ctx, search) => {
1313
+ if (!search?.trim() || !Array.isArray(searchColumns)) return searchColumns;
1314
+ const target = readCrudTarget(config);
1315
+ const provider = resolveCrudExtensions(ctx, config);
1316
+ if (!target || !provider?.getMetadata) return searchColumns;
1317
+ const metadata = await provider.getMetadata({ id: target.id });
1318
+ return searchColumns.filter((column) => allowsSearch(metadata.fields, getColumnRefId(column)));
1319
+ };
1320
+ const queryWhere = async (ctx, input) => {
1321
+ const columns = await querySearch(ctx, input.search);
1322
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, input);
1323
+ const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
1324
+ const filterCondition = validatedFilters?.length ? filterColumns({
1325
+ table,
1326
+ filters: validatedFilters,
1327
+ joinOperator: effectiveInput.joinOperator,
1328
+ resolveColumn: (columnId) => {
1329
+ const id = String(columnId);
1330
+ if (id === idField) return getTableColumn(table, idField);
1331
+ return resolveColumnTarget({
1332
+ table,
1333
+ columnId: id,
1334
+ allowedColumns: filterableColumns
1335
+ });
1336
+ },
1337
+ resolveDateRange: ctx.resolveDateRange
1338
+ }) : void 0;
1339
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1340
+ return {
1341
+ effectiveInput,
1342
+ where: buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition))
1343
+ };
1344
+ };
1291
1345
  const procedures = {
1292
1346
  meta: metaProcedure.output(metadataOutputSchema).query(async ({ ctx }) => {
1293
1347
  await withGuard(ctx, "list");
@@ -1297,29 +1351,35 @@ function createCrudRouter(config) {
1297
1351
  if (!provider?.getMetadata) return withCrudCapabilities({}, capabilities, disabledCapabilities);
1298
1352
  return withCrudCapabilities(await provider.getMetadata({ id: target.id }), capabilities, disabledCapabilities);
1299
1353
  }),
1354
+ ...config.counts ? { counts: resolved.procedureFactory("list").input(baseCountsInputSchema).output(z.object({ counts: z.record(z.string(), z.number().int().nonnegative()) })).query(async ({ ctx, input }) => {
1355
+ await withGuard(ctx, "list");
1356
+ const count = async (batch) => {
1357
+ if (typeof ctx.db.$counts !== "function") throw new TRPCError({
1358
+ code: "PRECONDITION_FAILED",
1359
+ message: "Batch counts require a database provider with scoped $counts support"
1360
+ });
1361
+ const conditions = Object.create(null);
1362
+ for (const query of batch.queries) {
1363
+ const { where } = await queryWhere(ctx, {
1364
+ ...query,
1365
+ page: 1,
1366
+ perPage: 1
1367
+ });
1368
+ conditions[query.key] = where;
1369
+ }
1370
+ return { counts: await ctx.db.$counts(table, conditions) };
1371
+ };
1372
+ return m.counts ? m.counts({
1373
+ ctx,
1374
+ input,
1375
+ next: async (modified) => count(modified ?? input)
1376
+ }) : count(input);
1377
+ }) } : {},
1300
1378
  list: resolved.procedureFactory("list").input(resolvedListInputSchema).output(listOutputSchema).query(async ({ ctx, input }) => {
1301
1379
  await withGuard(ctx, "list");
1302
1380
  const doList = async (listInput$1) => {
1303
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, listInput$1);
1381
+ const { effectiveInput, where } = await queryWhere(ctx, listInput$1);
1304
1382
  const offset = (effectiveInput.page - 1) * effectiveInput.perPage;
1305
- const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
1306
- const filterCondition = validatedFilters?.length ? filterColumns({
1307
- table,
1308
- filters: validatedFilters,
1309
- joinOperator: effectiveInput.joinOperator,
1310
- resolveColumn: (columnId) => {
1311
- const id = String(columnId);
1312
- if (id === idField) return getTableColumn(table, idField);
1313
- return resolveColumnTarget({
1314
- table,
1315
- columnId: id,
1316
- allowedColumns: filterableColumns
1317
- });
1318
- },
1319
- resolveDateRange: ctx.resolveDateRange
1320
- }) : void 0;
1321
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1322
- const where = buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1323
1383
  let query = ctx.db.select().from(table).$dynamic();
1324
1384
  if (where) query = query.where(where);
1325
1385
  const orderByExpressions = buildOrderByExpressions(effectiveInput.sort, true);
@@ -1463,6 +1523,10 @@ function createCrudRouter(config) {
1463
1523
  let deleted;
1464
1524
  if (softDelete) [deleted] = await writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(where).returning();
1465
1525
  else [deleted] = await writeCtx.db.delete(table).where(where).returning();
1526
+ if (!deleted) throw new TRPCError({
1527
+ code: "NOT_FOUND",
1528
+ message: "Resource not found or access denied"
1529
+ });
1466
1530
  await emitCrudWriteLifecycle(writeCtx, config, "delete", {
1467
1531
  id: input,
1468
1532
  row: deleted,
@@ -1484,8 +1548,29 @@ function createCrudRouter(config) {
1484
1548
  await withGuard(ctx, "deleteMany");
1485
1549
  const where = buildWhere(ctx, "deleteMany", inArray(getIdColumn(), input));
1486
1550
  const doDeleteMany = async () => {
1487
- if (softDelete) return { deleted: (await ctx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(where).returning({ id: getIdColumn() })).length };
1488
- else return { deleted: (await ctx.db.delete(table).where(where).returning({ id: getIdColumn() })).length };
1551
+ return runCrudExtensionWriteTransaction(ctx, config, {
1552
+ data: {},
1553
+ rawValues: { ids: input },
1554
+ baseValues: {},
1555
+ extraValues: null
1556
+ }, async (writeCtx) => {
1557
+ const emitLifecycle = shouldWrapCrudLifecycleTransaction(writeCtx, config);
1558
+ const existingRows = emitLifecycle && softDelete ? await writeCtx.db.select().from(table).where(where).for("update") : [];
1559
+ const existingById = new Map(existingRows.map((row) => [row[idField], row]));
1560
+ const deleteWhere = emitLifecycle && softDelete ? and(where, inArray(getIdColumn(), [...existingById.keys()])) : where;
1561
+ const query = softDelete ? writeCtx.db.update(table).set({ [softDelete.column]: softDelete.getValue() }).where(deleteWhere) : writeCtx.db.delete(table).where(where);
1562
+ const deleted = emitLifecycle ? await query.returning() : await query.returning({ id: getIdColumn() });
1563
+ if (emitLifecycle) for (const row of deleted) {
1564
+ const id = row[idField];
1565
+ await emitCrudWriteLifecycle(writeCtx, config, "delete", {
1566
+ id,
1567
+ row,
1568
+ existing: softDelete ? existingById.get(id) : row,
1569
+ entityId: id
1570
+ });
1571
+ }
1572
+ return { deleted: deleted.length };
1573
+ });
1489
1574
  };
1490
1575
  if (m.deleteMany) return m.deleteMany({
1491
1576
  ctx,
@@ -1582,7 +1667,8 @@ function createCrudRouter(config) {
1582
1667
  export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
1583
1668
  await withGuard(ctx, "export");
1584
1669
  const doExport = async (exportInput$1) => {
1585
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, {
1670
+ const columns = await querySearch(ctx, exportInput$1.search);
1671
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
1586
1672
  page: 1,
1587
1673
  perPage: Math.min(Math.max(exportInput$1.limit ?? maxExportSize, 1), maxExportSize),
1588
1674
  joinOperator: exportInput$1.joinOperator ?? "and",
@@ -1605,7 +1691,7 @@ function createCrudRouter(config) {
1605
1691
  },
1606
1692
  resolveDateRange: ctx.resolveDateRange
1607
1693
  }) : void 0;
1608
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1694
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1609
1695
  const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1610
1696
  let query = ctx.db.select().from(table).$dynamic();
1611
1697
  if (where) query = query.where(where);
@@ -1816,4 +1902,4 @@ function composeMiddleware(...middlewares) {
1816
1902
  const appRouter = router({});
1817
1903
 
1818
1904
  //#endregion
1819
- export { afterMiddleware, appRouter, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
1905
+ export { afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wordrhyme/auto-crud-server",
3
3
  "type": "module",
4
- "version": "2.0.3",
4
+ "version": "2.1.1",
5
5
  "description": "tRPC server utilities for auto-crud - automatic CRUD routers for Drizzle ORM",
6
6
  "author": "wordrhyme",
7
7
  "license": "MIT",
@@ -49,10 +49,10 @@
49
49
  "vitest": "^4.0.18",
50
50
  "zod": "^4.3.6",
51
51
  "@internal/eslint-config": "0.3.0",
52
- "@internal/prettier-config": "0.0.1",
53
52
  "@internal/tsconfig": "0.1.0",
54
- "@internal/vitest-config": "0.1.0",
55
- "@internal/tsdown-config": "0.1.0"
53
+ "@internal/prettier-config": "0.0.1",
54
+ "@internal/tsdown-config": "0.1.0",
55
+ "@internal/vitest-config": "0.1.0"
56
56
  },
57
57
  "prettier": "@internal/prettier-config",
58
58
  "scripts": {