@wordrhyme/auto-crud-server 2.1.0 → 2.2.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.
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`
@@ -1316,3 +1321,20 @@ Set `counts: true` on `createCrudRouter` to expose `counts({ queries })`. Each q
1316
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.
1317
1322
 
1318
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.
1324
+
1325
+ ## 结构化标签条件
1326
+
1327
+ 列表与导出共享标签条件协议:
1328
+
1329
+ ```ts
1330
+ {
1331
+ id: 'tags', variant: 'tags', operator: 'matches', filterId: 'tags',
1332
+ value: { include: ['vip'], exclude: ['blocked'], match: 'any' },
1333
+ }
1334
+ ```
1335
+
1336
+ 固定字段对应动态标签 ID;包含与排除不能有同一个 ID。标签条件内部是 `(任一/全部正选) AND (无反选)`,然后与普通条件按照 `joinOperator` 组合。客户端应删除空标签条件;服务端 provider 应拒绝空条件和不存在的 ID。
1337
+
1338
+ 为 CRUD extension provider 实现 `buildConditions({ id, entityId, filters, joinOperator, search })`,返回 `{ filter?: SQL, search?: SQL }`。这属于可信进程内接口,客户端不能提供 SQL。使用 `entityId` 与标签关联表构造相关 `EXISTS` 查询,列表、总数和导出会在原有数据权限条件内组合这些谓词,无须先取一批实体 ID。
1339
+
1340
+ 扩展筛选统一通过既有 `buildConditions` 接口生成 SQL。标签字段不直接映射为基础表列,应由扩展 provider 提供条件和读取投影;赋值服务负责校验租户、字段及记录更新权限。
package/dist/index.cjs CHANGED
@@ -38,6 +38,65 @@ date_fns_endOfDay = __toESM(date_fns_endOfDay);
38
38
  let date_fns_startOfDay = require("date-fns/startOfDay");
39
39
  date_fns_startOfDay = __toESM(date_fns_startOfDay);
40
40
 
41
+ //#region src/lib/import-errors.ts
42
+ const runtime = zod.z;
43
+ const PARAMS = [
44
+ "values",
45
+ "options",
46
+ "expected",
47
+ "origin",
48
+ "type",
49
+ "minimum",
50
+ "maximum",
51
+ "inclusive",
52
+ "exact",
53
+ "format",
54
+ "validation",
55
+ "pattern",
56
+ "prefix",
57
+ "suffix",
58
+ "includes",
59
+ "divisor",
60
+ "multipleOf",
61
+ "keys"
62
+ ];
63
+ function importIssue(issue, row) {
64
+ const detail = issue;
65
+ const input = Object.hasOwn(detail, "input") ? detail["input"] : issue.path.reduce((value, key) => value != null && typeof value === "object" ? value[key] : void 0, row);
66
+ const defaultError = (runtime.config?.().localeError ?? runtime.defaultErrorMap)?.({
67
+ ...detail,
68
+ input
69
+ }, {
70
+ data: input,
71
+ defaultError: ""
72
+ });
73
+ const defaultMessage = typeof defaultError === "string" ? defaultError : defaultError?.message;
74
+ if (issue.code === "custom" || detail["exact"] === true || issue.message !== defaultMessage) return null;
75
+ const params = Object.fromEntries(PARAMS.filter((key) => detail[key] !== void 0).map((key) => [key, typeof detail[key] === "bigint" ? String(detail[key]) : detail[key]]));
76
+ if (issue.code === "invalid_type") params["received"] = typeof detail["received"] === "string" ? detail["received"] : input === null ? "null" : Array.isArray(input) ? "array" : typeof input === "number" && Number.isNaN(input) ? "nan" : typeof input;
77
+ let code = issue.code;
78
+ if (code === "invalid_enum_value") {
79
+ code = "invalid_value";
80
+ params["values"] = params["options"];
81
+ } else if (code === "invalid_literal") {
82
+ code = "invalid_value";
83
+ params["values"] = [params["expected"]];
84
+ } else if (code === "invalid_string") {
85
+ if (typeof params["validation"] !== "string" || params["validation"] === "regex") return null;
86
+ code = "invalid_format";
87
+ params["format"] = params["validation"];
88
+ }
89
+ if (params["type"] !== void 0) params["origin"] = params["type"];
90
+ if (params["multipleOf"] !== void 0) params["divisor"] = params["multipleOf"];
91
+ return {
92
+ code,
93
+ path: issue.path.map(String),
94
+ message: issue.message,
95
+ params
96
+ };
97
+ }
98
+
99
+ //#endregion
41
100
  //#region src/trpc.ts
42
101
  const t = __trpc_server.initTRPC.context().create({ transformer: superjson.default });
43
102
  const router = t.router;
@@ -155,6 +214,7 @@ function resolvedDateCondition(expr, operator, range) {
155
214
  function filterColumns({ table, filters, joinOperator, resolveColumn, resolveDateRange }) {
156
215
  const joinFn = joinOperator === "and" ? drizzle_orm.and : drizzle_orm.or;
157
216
  const validConditions = filters.map((filter) => {
217
+ if (filter.variant === "tags") throw new Error("Tag filters require an extension buildConditions provider");
158
218
  const column = resolveColumn ? resolveColumn(filter.id) : getColumn(table, filter.id);
159
219
  if (!column) return void 0;
160
220
  const expr = column;
@@ -470,7 +530,8 @@ const dataTableConfig = {
470
530
  "dateRange",
471
531
  "boolean",
472
532
  "select",
473
- "multiSelect"
533
+ "multiSelect",
534
+ "tags"
474
535
  ],
475
536
  operators: [
476
537
  "iLike",
@@ -486,7 +547,8 @@ const dataTableConfig = {
486
547
  "gt",
487
548
  "gte",
488
549
  "isBetween",
489
- "isRelativeToToday"
550
+ "isRelativeToToday",
551
+ "matches"
490
552
  ],
491
553
  joinOperators: ["and", "or"]
492
554
  };
@@ -602,13 +664,25 @@ function resolveConfig(config) {
602
664
  function resolveMetaProcedure(config, fallback) {
603
665
  return isProcedureMap(config) ? config.meta ?? fallback : fallback;
604
666
  }
605
- const filterItemSchema = zod.z.object({
667
+ const tagFilterValueSchema = zod.z.object({
668
+ include: zod.z.array(zod.z.string().min(1)).max(100),
669
+ exclude: zod.z.array(zod.z.string().min(1)).max(100),
670
+ match: zod.z.enum(["any", "all"])
671
+ }).strict().refine(({ include, exclude }) => !include.some((id) => exclude.includes(id)), "A tag cannot be both included and excluded");
672
+ const ordinaryFilterSchema = zod.z.object({
606
673
  id: zod.z.string(),
607
674
  value: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]),
608
- variant: zod.z.enum(dataTableConfig.filterVariants),
609
- operator: zod.z.enum(dataTableConfig.operators),
675
+ variant: zod.z.enum(dataTableConfig.filterVariants.filter((variant) => variant !== "tags")),
676
+ operator: zod.z.enum(dataTableConfig.operators.filter((operator) => operator !== "matches")),
610
677
  filterId: zod.z.string()
611
678
  });
679
+ const filterItemSchema = zod.z.union([ordinaryFilterSchema, zod.z.object({
680
+ id: zod.z.string(),
681
+ filterId: zod.z.string(),
682
+ variant: zod.z.literal("tags"),
683
+ operator: zod.z.literal("matches"),
684
+ value: tagFilterValueSchema
685
+ })]);
612
686
  const baseListInputSchema = zod.z.object({
613
687
  page: zod.z.number().min(1).default(1),
614
688
  perPage: zod.z.number().min(1).max(100).default(10),
@@ -777,10 +851,22 @@ function mergeCrudCapabilities(base, extension, disabled) {
777
851
  sort: mergeFieldCapability(base.sort, extension?.sort, disabled.sort)
778
852
  };
779
853
  }
854
+ function allowsSearch(fields, id) {
855
+ const field = fields?.[id];
856
+ return !(field && typeof field === "object" && "search" in field && field.search === false);
857
+ }
780
858
  function withCrudCapabilities(metadata, capabilities, disabled) {
859
+ const merged = mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled);
860
+ const fields = merged.search.fields.filter((id) => allowsSearch(metadata?.fields, id));
781
861
  return {
782
862
  ...metadata ?? {},
783
- capabilities: mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled)
863
+ capabilities: {
864
+ ...merged,
865
+ search: {
866
+ enabled: merged.search.enabled && (merged.search.fields.length === 0 || fields.length > 0 || metadata?.capabilities?.search?.enabled === true && metadata.capabilities.search.fields.length === 0),
867
+ fields
868
+ }
869
+ }
784
870
  };
785
871
  }
786
872
  function getTableColumn(table, columnId) {
@@ -1238,7 +1324,13 @@ function createCrudRouter(config) {
1238
1324
  skipped: zod.z.number(),
1239
1325
  failed: zod.z.array(zod.z.object({
1240
1326
  row: zod.z.number(),
1241
- errors: zod.z.array(zod.z.string())
1327
+ errors: zod.z.array(zod.z.string()),
1328
+ issues: zod.z.array(zod.z.object({
1329
+ code: zod.z.string(),
1330
+ path: zod.z.array(zod.z.string()),
1331
+ message: zod.z.string(),
1332
+ params: zod.z.record(zod.z.string(), zod.z.unknown())
1333
+ }).nullable()).optional()
1242
1334
  }))
1243
1335
  });
1244
1336
  const resolved = resolveConfig(config);
@@ -1328,8 +1420,17 @@ function createCrudRouter(config) {
1328
1420
  message: `Forbidden: Cannot ${operation} this resource`
1329
1421
  });
1330
1422
  };
1423
+ const querySearch = async (ctx, search) => {
1424
+ if (!search?.trim() || !Array.isArray(searchColumns)) return searchColumns;
1425
+ const target = readCrudTarget(config);
1426
+ const provider = resolveCrudExtensions(ctx, config);
1427
+ if (!target || !provider?.getMetadata) return searchColumns;
1428
+ const metadata = await provider.getMetadata({ id: target.id });
1429
+ return searchColumns.filter((column) => allowsSearch(metadata.fields, getColumnRefId(column)));
1430
+ };
1331
1431
  const queryWhere = async (ctx, input) => {
1332
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, input);
1432
+ const columns = await querySearch(ctx, input.search);
1433
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, input);
1333
1434
  const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
1334
1435
  const filterCondition = validatedFilters?.length ? filterColumns({
1335
1436
  table,
@@ -1346,7 +1447,7 @@ function createCrudRouter(config) {
1346
1447
  },
1347
1448
  resolveDateRange: ctx.resolveDateRange
1348
1449
  }) : void 0;
1349
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1450
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1350
1451
  return {
1351
1452
  effectiveInput,
1352
1453
  where: buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition))
@@ -1677,7 +1778,8 @@ function createCrudRouter(config) {
1677
1778
  export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
1678
1779
  await withGuard(ctx, "export");
1679
1780
  const doExport = async (exportInput$1) => {
1680
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, {
1781
+ const columns = await querySearch(ctx, exportInput$1.search);
1782
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
1681
1783
  page: 1,
1682
1784
  perPage: Math.min(Math.max(exportInput$1.limit ?? maxExportSize, 1), maxExportSize),
1683
1785
  joinOperator: exportInput$1.joinOperator ?? "and",
@@ -1700,7 +1802,7 @@ function createCrudRouter(config) {
1700
1802
  },
1701
1803
  resolveDateRange: ctx.resolveDateRange
1702
1804
  }) : void 0;
1703
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1805
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1704
1806
  const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1705
1807
  let query = ctx.db.select().from(table).$dynamic();
1706
1808
  if (where) query = query.where(where);
@@ -1761,7 +1863,7 @@ function createCrudRouter(config) {
1761
1863
  const failed = [];
1762
1864
  for (let i = 0; i < importData$1.rows.length; i++) {
1763
1865
  const row = importData$1.rows[i];
1764
- const result = importSchema.safeParse(row);
1866
+ const result = importSchema.safeParse(row, { reportInput: true });
1765
1867
  if (result.success) {
1766
1868
  const splitRow = splitCrudExtensionWriteInput(result.data, tableColumnNames);
1767
1869
  validRows.push(splitRow);
@@ -1769,7 +1871,8 @@ function createCrudRouter(config) {
1769
1871
  const errors = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
1770
1872
  failed.push({
1771
1873
  row: i,
1772
- errors
1874
+ errors,
1875
+ issues: result.error.issues.map((issue) => importIssue(issue, row))
1773
1876
  });
1774
1877
  if (importData$1.onConflict === "error") return {
1775
1878
  success: 0,
@@ -1921,4 +2024,5 @@ exports.beforeMiddleware = beforeMiddleware;
1921
2024
  exports.composeMiddleware = composeMiddleware;
1922
2025
  exports.createCrudRouter = createCrudRouter;
1923
2026
  exports.publicProcedure = publicProcedure;
1924
- exports.router = router;
2027
+ exports.router = router;
2028
+ exports.tagFilterValueSchema = tagFilterValueSchema;
package/dist/index.d.cts CHANGED
@@ -1,14 +1,14 @@
1
1
  import { AnyColumn, SQL, Table } from "drizzle-orm";
2
2
  import { PgTable } from "drizzle-orm/pg-core";
3
3
  import { z } from "zod";
4
- import * as _trpc_server0 from "@trpc/server";
4
+ import * as _trpc_server2 from "@trpc/server";
5
5
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
6
6
 
7
7
  //#region src/lib/filter-columns.d.ts
8
8
  /** 过滤器变体类型 */
9
- type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect';
9
+ type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect' | 'tags';
10
10
  /** 过滤器操作符 */
11
- type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty';
11
+ type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty' | 'matches';
12
12
  /** 扩展的列过滤器 */
13
13
  interface ExtendedColumnFilter<T extends Table = Table> {
14
14
  id: keyof T | string;
@@ -40,13 +40,13 @@ interface Context {
40
40
  db: PostgresJsDatabase<Record<string, never>>;
41
41
  resolveDateRange?: DateRangeResolver;
42
42
  }
43
- declare const router: _trpc_server0.TRPCRouterBuilder<{
43
+ declare const router: _trpc_server2.TRPCRouterBuilder<{
44
44
  ctx: Context;
45
45
  meta: object;
46
- errorShape: _trpc_server0.TRPCDefaultErrorShape;
46
+ errorShape: _trpc_server2.TRPCDefaultErrorShape;
47
47
  transformer: true;
48
48
  }>;
49
- declare const publicProcedure: _trpc_server0.TRPCProcedureBuilder<Context, object, object, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, false>;
49
+ declare const publicProcedure: _trpc_server2.TRPCProcedureBuilder<Context, object, object, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, false>;
50
50
  //#endregion
51
51
  //#region src/types/config.d.ts
52
52
  type CrudOperation = 'list' | 'get' | 'create' | 'update' | 'delete' | 'deleteMany' | 'updateMany' | 'upsert' | 'export' | 'import' | 'createMany';
@@ -139,7 +139,11 @@ interface ListInput {
139
139
  search?: string;
140
140
  filters?: Array<{
141
141
  id: string;
142
- value: string | string[];
142
+ value: string | string[] | {
143
+ include: string[];
144
+ exclude: string[];
145
+ match: 'any' | 'all';
146
+ };
143
147
  variant: string;
144
148
  operator: string;
145
149
  filterId: string;
@@ -183,7 +187,11 @@ interface ExportInput {
183
187
  search?: string;
184
188
  filters?: Array<{
185
189
  id: string;
186
- value: string | string[];
190
+ value: string | string[] | {
191
+ include: string[];
192
+ exclude: string[];
193
+ match: 'any' | 'all';
194
+ };
187
195
  variant: string;
188
196
  operator: string;
189
197
  filterId: string;
@@ -201,7 +209,11 @@ interface CrudExtensionMetadata {
201
209
  }
202
210
  interface CrudExtensionFilter {
203
211
  id: string;
204
- value: string | string[];
212
+ value: string | string[] | {
213
+ include: string[];
214
+ exclude: string[];
215
+ match: 'any' | 'all';
216
+ };
205
217
  variant: string;
206
218
  operator: string;
207
219
  filterId?: string | undefined;
@@ -293,11 +305,20 @@ interface ExportResult<TSelect> {
293
305
  /**
294
306
  * 导入行失败详情
295
307
  */
308
+ /** Serializable validation details; excludes the submitted cell value. */
309
+ interface ImportIssue {
310
+ code: string;
311
+ path: string[];
312
+ message: string;
313
+ params: Record<string, unknown>;
314
+ }
296
315
  interface ImportFailedRow {
297
316
  /** 行号(0-indexed) */
298
317
  row: number;
299
318
  /** 验证错误信息列表 */
300
319
  errors: string[];
320
+ /** Optional details for localized presentation; errors remains backwards compatible. */
321
+ issues?: Array<ImportIssue | null>;
301
322
  }
302
323
  /**
303
324
  * 导入结果类型
@@ -843,6 +864,14 @@ interface CrudProcedures {
843
864
  type CrudRouterReturn = ReturnType<typeof router> & {
844
865
  procedures: CrudProcedures;
845
866
  };
867
+ declare const tagFilterValueSchema: z.ZodObject<{
868
+ include: z.ZodArray<z.ZodString>;
869
+ exclude: z.ZodArray<z.ZodString>;
870
+ match: z.ZodEnum<{
871
+ any: "any";
872
+ all: "all";
873
+ }>;
874
+ }, z.core.$strict>;
846
875
  declare const baseListInputSchema: z.ZodObject<{
847
876
  page: z.ZodDefault<z.ZodNumber>;
848
877
  perPage: z.ZodDefault<z.ZodNumber>;
@@ -851,7 +880,7 @@ declare const baseListInputSchema: z.ZodObject<{
851
880
  desc: z.ZodBoolean;
852
881
  }, z.core.$strip>>>;
853
882
  search: z.ZodOptional<z.ZodString>;
854
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
883
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
855
884
  id: z.ZodString;
856
885
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
857
886
  variant: z.ZodEnum<{
@@ -881,7 +910,20 @@ declare const baseListInputSchema: z.ZodObject<{
881
910
  notInArray: "notInArray";
882
911
  }>;
883
912
  filterId: z.ZodString;
884
- }, z.core.$strip>>>;
913
+ }, z.core.$strip>, z.ZodObject<{
914
+ id: z.ZodString;
915
+ filterId: z.ZodString;
916
+ variant: z.ZodLiteral<"tags">;
917
+ operator: z.ZodLiteral<"matches">;
918
+ value: z.ZodObject<{
919
+ include: z.ZodArray<z.ZodString>;
920
+ exclude: z.ZodArray<z.ZodString>;
921
+ match: z.ZodEnum<{
922
+ any: "any";
923
+ all: "all";
924
+ }>;
925
+ }, z.core.$strict>;
926
+ }, z.core.$strip>]>>>;
885
927
  joinOperator: z.ZodDefault<z.ZodEnum<{
886
928
  and: "and";
887
929
  or: "or";
@@ -896,7 +938,7 @@ declare const baseExportInputSchema: z.ZodObject<{
896
938
  desc: z.ZodBoolean;
897
939
  }, z.core.$strip>>>;
898
940
  search: z.ZodOptional<z.ZodString>;
899
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
941
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
900
942
  id: z.ZodString;
901
943
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
902
944
  variant: z.ZodEnum<{
@@ -926,7 +968,20 @@ declare const baseExportInputSchema: z.ZodObject<{
926
968
  notInArray: "notInArray";
927
969
  }>;
928
970
  filterId: z.ZodString;
929
- }, z.core.$strip>>>;
971
+ }, z.core.$strip>, z.ZodObject<{
972
+ id: z.ZodString;
973
+ filterId: z.ZodString;
974
+ variant: z.ZodLiteral<"tags">;
975
+ operator: z.ZodLiteral<"matches">;
976
+ value: z.ZodObject<{
977
+ include: z.ZodArray<z.ZodString>;
978
+ exclude: z.ZodArray<z.ZodString>;
979
+ match: z.ZodEnum<{
980
+ any: "any";
981
+ all: "all";
982
+ }>;
983
+ }, z.core.$strict>;
984
+ }, z.core.$strip>]>>>;
930
985
  joinOperator: z.ZodDefault<z.ZodEnum<{
931
986
  and: "and";
932
987
  or: "or";
@@ -936,7 +991,7 @@ declare const baseExportInputSchema: z.ZodObject<{
936
991
  declare const baseCountsInputSchema: z.ZodObject<{
937
992
  queries: z.ZodArray<z.ZodObject<{
938
993
  search: z.ZodOptional<z.ZodString>;
939
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
994
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
940
995
  id: z.ZodString;
941
996
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
942
997
  variant: z.ZodEnum<{
@@ -966,7 +1021,20 @@ declare const baseCountsInputSchema: z.ZodObject<{
966
1021
  notInArray: "notInArray";
967
1022
  }>;
968
1023
  filterId: z.ZodString;
969
- }, z.core.$strip>>>;
1024
+ }, z.core.$strip>, z.ZodObject<{
1025
+ id: z.ZodString;
1026
+ filterId: z.ZodString;
1027
+ variant: z.ZodLiteral<"tags">;
1028
+ operator: z.ZodLiteral<"matches">;
1029
+ value: z.ZodObject<{
1030
+ include: z.ZodArray<z.ZodString>;
1031
+ exclude: z.ZodArray<z.ZodString>;
1032
+ match: z.ZodEnum<{
1033
+ any: "any";
1034
+ all: "all";
1035
+ }>;
1036
+ }, z.core.$strict>;
1037
+ }, z.core.$strip>]>>>;
970
1038
  joinOperator: z.ZodDefault<z.ZodEnum<{
971
1039
  and: "and";
972
1040
  or: "or";
@@ -1079,12 +1147,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
1079
1147
  } } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
1080
1148
  //#endregion
1081
1149
  //#region src/routers/index.d.ts
1082
- declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
1150
+ declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
1083
1151
  ctx: Context;
1084
1152
  meta: object;
1085
- errorShape: _trpc_server0.TRPCDefaultErrorShape;
1153
+ errorShape: _trpc_server2.TRPCDefaultErrorShape;
1086
1154
  transformer: true;
1087
- }, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
1155
+ }, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
1088
1156
  type AppRouter = typeof appRouter;
1089
1157
  //#endregion
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 };
1158
+ 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 ImportIssue, 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, tagFilterValueSchema };
package/dist/index.d.ts CHANGED
@@ -7,9 +7,9 @@ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
7
7
 
8
8
  //#region src/lib/filter-columns.d.ts
9
9
  /** 过滤器变体类型 */
10
- type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect';
10
+ type FilterVariant = 'text' | 'number' | 'range' | 'date' | 'dateRange' | 'boolean' | 'select' | 'multiSelect' | 'tags';
11
11
  /** 过滤器操作符 */
12
- type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty';
12
+ type FilterOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'iLike' | 'notILike' | 'inArray' | 'notInArray' | 'isBetween' | 'isRelativeToToday' | 'isEmpty' | 'isNotEmpty' | 'matches';
13
13
  /** 扩展的列过滤器 */
14
14
  interface ExtendedColumnFilter<T extends Table = Table> {
15
15
  id: keyof T | string;
@@ -140,7 +140,11 @@ interface ListInput {
140
140
  search?: string;
141
141
  filters?: Array<{
142
142
  id: string;
143
- value: string | string[];
143
+ value: string | string[] | {
144
+ include: string[];
145
+ exclude: string[];
146
+ match: 'any' | 'all';
147
+ };
144
148
  variant: string;
145
149
  operator: string;
146
150
  filterId: string;
@@ -184,7 +188,11 @@ interface ExportInput {
184
188
  search?: string;
185
189
  filters?: Array<{
186
190
  id: string;
187
- value: string | string[];
191
+ value: string | string[] | {
192
+ include: string[];
193
+ exclude: string[];
194
+ match: 'any' | 'all';
195
+ };
188
196
  variant: string;
189
197
  operator: string;
190
198
  filterId: string;
@@ -202,7 +210,11 @@ interface CrudExtensionMetadata {
202
210
  }
203
211
  interface CrudExtensionFilter {
204
212
  id: string;
205
- value: string | string[];
213
+ value: string | string[] | {
214
+ include: string[];
215
+ exclude: string[];
216
+ match: 'any' | 'all';
217
+ };
206
218
  variant: string;
207
219
  operator: string;
208
220
  filterId?: string | undefined;
@@ -294,11 +306,20 @@ interface ExportResult<TSelect> {
294
306
  /**
295
307
  * 导入行失败详情
296
308
  */
309
+ /** Serializable validation details; excludes the submitted cell value. */
310
+ interface ImportIssue {
311
+ code: string;
312
+ path: string[];
313
+ message: string;
314
+ params: Record<string, unknown>;
315
+ }
297
316
  interface ImportFailedRow {
298
317
  /** 行号(0-indexed) */
299
318
  row: number;
300
319
  /** 验证错误信息列表 */
301
320
  errors: string[];
321
+ /** Optional details for localized presentation; errors remains backwards compatible. */
322
+ issues?: Array<ImportIssue | null>;
302
323
  }
303
324
  /**
304
325
  * 导入结果类型
@@ -844,6 +865,14 @@ interface CrudProcedures {
844
865
  type CrudRouterReturn = ReturnType<typeof router> & {
845
866
  procedures: CrudProcedures;
846
867
  };
868
+ declare const tagFilterValueSchema: z.ZodObject<{
869
+ include: z.ZodArray<z.ZodString>;
870
+ exclude: z.ZodArray<z.ZodString>;
871
+ match: z.ZodEnum<{
872
+ any: "any";
873
+ all: "all";
874
+ }>;
875
+ }, z.core.$strict>;
847
876
  declare const baseListInputSchema: z.ZodObject<{
848
877
  page: z.ZodDefault<z.ZodNumber>;
849
878
  perPage: z.ZodDefault<z.ZodNumber>;
@@ -852,7 +881,7 @@ declare const baseListInputSchema: z.ZodObject<{
852
881
  desc: z.ZodBoolean;
853
882
  }, z.core.$strip>>>;
854
883
  search: z.ZodOptional<z.ZodString>;
855
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
884
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
856
885
  id: z.ZodString;
857
886
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
858
887
  variant: z.ZodEnum<{
@@ -882,7 +911,20 @@ declare const baseListInputSchema: z.ZodObject<{
882
911
  notInArray: "notInArray";
883
912
  }>;
884
913
  filterId: z.ZodString;
885
- }, z.core.$strip>>>;
914
+ }, z.core.$strip>, z.ZodObject<{
915
+ id: z.ZodString;
916
+ filterId: z.ZodString;
917
+ variant: z.ZodLiteral<"tags">;
918
+ operator: z.ZodLiteral<"matches">;
919
+ value: z.ZodObject<{
920
+ include: z.ZodArray<z.ZodString>;
921
+ exclude: z.ZodArray<z.ZodString>;
922
+ match: z.ZodEnum<{
923
+ any: "any";
924
+ all: "all";
925
+ }>;
926
+ }, z.core.$strict>;
927
+ }, z.core.$strip>]>>>;
886
928
  joinOperator: z.ZodDefault<z.ZodEnum<{
887
929
  and: "and";
888
930
  or: "or";
@@ -897,7 +939,7 @@ declare const baseExportInputSchema: z.ZodObject<{
897
939
  desc: z.ZodBoolean;
898
940
  }, z.core.$strip>>>;
899
941
  search: z.ZodOptional<z.ZodString>;
900
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
942
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
901
943
  id: z.ZodString;
902
944
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
903
945
  variant: z.ZodEnum<{
@@ -927,7 +969,20 @@ declare const baseExportInputSchema: z.ZodObject<{
927
969
  notInArray: "notInArray";
928
970
  }>;
929
971
  filterId: z.ZodString;
930
- }, z.core.$strip>>>;
972
+ }, z.core.$strip>, z.ZodObject<{
973
+ id: z.ZodString;
974
+ filterId: z.ZodString;
975
+ variant: z.ZodLiteral<"tags">;
976
+ operator: z.ZodLiteral<"matches">;
977
+ value: z.ZodObject<{
978
+ include: z.ZodArray<z.ZodString>;
979
+ exclude: z.ZodArray<z.ZodString>;
980
+ match: z.ZodEnum<{
981
+ any: "any";
982
+ all: "all";
983
+ }>;
984
+ }, z.core.$strict>;
985
+ }, z.core.$strip>]>>>;
931
986
  joinOperator: z.ZodDefault<z.ZodEnum<{
932
987
  and: "and";
933
988
  or: "or";
@@ -937,7 +992,7 @@ declare const baseExportInputSchema: z.ZodObject<{
937
992
  declare const baseCountsInputSchema: z.ZodObject<{
938
993
  queries: z.ZodArray<z.ZodObject<{
939
994
  search: z.ZodOptional<z.ZodString>;
940
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
995
+ filters: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
941
996
  id: z.ZodString;
942
997
  value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
943
998
  variant: z.ZodEnum<{
@@ -967,7 +1022,20 @@ declare const baseCountsInputSchema: z.ZodObject<{
967
1022
  notInArray: "notInArray";
968
1023
  }>;
969
1024
  filterId: z.ZodString;
970
- }, z.core.$strip>>>;
1025
+ }, z.core.$strip>, z.ZodObject<{
1026
+ id: z.ZodString;
1027
+ filterId: z.ZodString;
1028
+ variant: z.ZodLiteral<"tags">;
1029
+ operator: z.ZodLiteral<"matches">;
1030
+ value: z.ZodObject<{
1031
+ include: z.ZodArray<z.ZodString>;
1032
+ exclude: z.ZodArray<z.ZodString>;
1033
+ match: z.ZodEnum<{
1034
+ any: "any";
1035
+ all: "all";
1036
+ }>;
1037
+ }, z.core.$strict>;
1038
+ }, z.core.$strip>]>>>;
971
1039
  joinOperator: z.ZodDefault<z.ZodEnum<{
972
1040
  and: "and";
973
1041
  or: "or";
@@ -1088,4 +1156,4 @@ declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
1088
1156
  }, _trpc_server0.TRPCDecorateCreateRouterOptions<{}>>;
1089
1157
  type AppRouter = typeof appRouter;
1090
1158
  //#endregion
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 };
1159
+ 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 ImportIssue, 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, tagFilterValueSchema };
package/dist/index.js CHANGED
@@ -7,6 +7,65 @@ import { addDays } from "date-fns/addDays";
7
7
  import { endOfDay } from "date-fns/endOfDay";
8
8
  import { startOfDay } from "date-fns/startOfDay";
9
9
 
10
+ //#region src/lib/import-errors.ts
11
+ const runtime = z;
12
+ const PARAMS = [
13
+ "values",
14
+ "options",
15
+ "expected",
16
+ "origin",
17
+ "type",
18
+ "minimum",
19
+ "maximum",
20
+ "inclusive",
21
+ "exact",
22
+ "format",
23
+ "validation",
24
+ "pattern",
25
+ "prefix",
26
+ "suffix",
27
+ "includes",
28
+ "divisor",
29
+ "multipleOf",
30
+ "keys"
31
+ ];
32
+ function importIssue(issue, row) {
33
+ const detail = issue;
34
+ const input = Object.hasOwn(detail, "input") ? detail["input"] : issue.path.reduce((value, key) => value != null && typeof value === "object" ? value[key] : void 0, row);
35
+ const defaultError = (runtime.config?.().localeError ?? runtime.defaultErrorMap)?.({
36
+ ...detail,
37
+ input
38
+ }, {
39
+ data: input,
40
+ defaultError: ""
41
+ });
42
+ const defaultMessage = typeof defaultError === "string" ? defaultError : defaultError?.message;
43
+ if (issue.code === "custom" || detail["exact"] === true || issue.message !== defaultMessage) return null;
44
+ const params = Object.fromEntries(PARAMS.filter((key) => detail[key] !== void 0).map((key) => [key, typeof detail[key] === "bigint" ? String(detail[key]) : detail[key]]));
45
+ if (issue.code === "invalid_type") params["received"] = typeof detail["received"] === "string" ? detail["received"] : input === null ? "null" : Array.isArray(input) ? "array" : typeof input === "number" && Number.isNaN(input) ? "nan" : typeof input;
46
+ let code = issue.code;
47
+ if (code === "invalid_enum_value") {
48
+ code = "invalid_value";
49
+ params["values"] = params["options"];
50
+ } else if (code === "invalid_literal") {
51
+ code = "invalid_value";
52
+ params["values"] = [params["expected"]];
53
+ } else if (code === "invalid_string") {
54
+ if (typeof params["validation"] !== "string" || params["validation"] === "regex") return null;
55
+ code = "invalid_format";
56
+ params["format"] = params["validation"];
57
+ }
58
+ if (params["type"] !== void 0) params["origin"] = params["type"];
59
+ if (params["multipleOf"] !== void 0) params["divisor"] = params["multipleOf"];
60
+ return {
61
+ code,
62
+ path: issue.path.map(String),
63
+ message: issue.message,
64
+ params
65
+ };
66
+ }
67
+
68
+ //#endregion
10
69
  //#region src/trpc.ts
11
70
  const t = initTRPC.context().create({ transformer: superjson });
12
71
  const router = t.router;
@@ -124,6 +183,7 @@ function resolvedDateCondition(expr, operator, range) {
124
183
  function filterColumns({ table, filters, joinOperator, resolveColumn, resolveDateRange }) {
125
184
  const joinFn = joinOperator === "and" ? and : or;
126
185
  const validConditions = filters.map((filter) => {
186
+ if (filter.variant === "tags") throw new Error("Tag filters require an extension buildConditions provider");
127
187
  const column = resolveColumn ? resolveColumn(filter.id) : getColumn(table, filter.id);
128
188
  if (!column) return void 0;
129
189
  const expr = column;
@@ -439,7 +499,8 @@ const dataTableConfig = {
439
499
  "dateRange",
440
500
  "boolean",
441
501
  "select",
442
- "multiSelect"
502
+ "multiSelect",
503
+ "tags"
443
504
  ],
444
505
  operators: [
445
506
  "iLike",
@@ -455,7 +516,8 @@ const dataTableConfig = {
455
516
  "gt",
456
517
  "gte",
457
518
  "isBetween",
458
- "isRelativeToToday"
519
+ "isRelativeToToday",
520
+ "matches"
459
521
  ],
460
522
  joinOperators: ["and", "or"]
461
523
  };
@@ -571,13 +633,25 @@ function resolveConfig(config) {
571
633
  function resolveMetaProcedure(config, fallback) {
572
634
  return isProcedureMap(config) ? config.meta ?? fallback : fallback;
573
635
  }
574
- const filterItemSchema = z.object({
636
+ const tagFilterValueSchema = z.object({
637
+ include: z.array(z.string().min(1)).max(100),
638
+ exclude: z.array(z.string().min(1)).max(100),
639
+ match: z.enum(["any", "all"])
640
+ }).strict().refine(({ include, exclude }) => !include.some((id) => exclude.includes(id)), "A tag cannot be both included and excluded");
641
+ const ordinaryFilterSchema = z.object({
575
642
  id: z.string(),
576
643
  value: z.union([z.string(), z.array(z.string())]),
577
- variant: z.enum(dataTableConfig.filterVariants),
578
- operator: z.enum(dataTableConfig.operators),
644
+ variant: z.enum(dataTableConfig.filterVariants.filter((variant) => variant !== "tags")),
645
+ operator: z.enum(dataTableConfig.operators.filter((operator) => operator !== "matches")),
579
646
  filterId: z.string()
580
647
  });
648
+ const filterItemSchema = z.union([ordinaryFilterSchema, z.object({
649
+ id: z.string(),
650
+ filterId: z.string(),
651
+ variant: z.literal("tags"),
652
+ operator: z.literal("matches"),
653
+ value: tagFilterValueSchema
654
+ })]);
581
655
  const baseListInputSchema = z.object({
582
656
  page: z.number().min(1).default(1),
583
657
  perPage: z.number().min(1).max(100).default(10),
@@ -746,10 +820,22 @@ function mergeCrudCapabilities(base, extension, disabled) {
746
820
  sort: mergeFieldCapability(base.sort, extension?.sort, disabled.sort)
747
821
  };
748
822
  }
823
+ function allowsSearch(fields, id) {
824
+ const field = fields?.[id];
825
+ return !(field && typeof field === "object" && "search" in field && field.search === false);
826
+ }
749
827
  function withCrudCapabilities(metadata, capabilities, disabled) {
828
+ const merged = mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled);
829
+ const fields = merged.search.fields.filter((id) => allowsSearch(metadata?.fields, id));
750
830
  return {
751
831
  ...metadata ?? {},
752
- capabilities: mergeCrudCapabilities(capabilities, metadata?.capabilities, disabled)
832
+ capabilities: {
833
+ ...merged,
834
+ search: {
835
+ enabled: merged.search.enabled && (merged.search.fields.length === 0 || fields.length > 0 || metadata?.capabilities?.search?.enabled === true && metadata.capabilities.search.fields.length === 0),
836
+ fields
837
+ }
838
+ }
753
839
  };
754
840
  }
755
841
  function getTableColumn(table, columnId) {
@@ -1207,7 +1293,13 @@ function createCrudRouter(config) {
1207
1293
  skipped: z.number(),
1208
1294
  failed: z.array(z.object({
1209
1295
  row: z.number(),
1210
- errors: z.array(z.string())
1296
+ errors: z.array(z.string()),
1297
+ issues: z.array(z.object({
1298
+ code: z.string(),
1299
+ path: z.array(z.string()),
1300
+ message: z.string(),
1301
+ params: z.record(z.string(), z.unknown())
1302
+ }).nullable()).optional()
1211
1303
  }))
1212
1304
  });
1213
1305
  const resolved = resolveConfig(config);
@@ -1297,8 +1389,17 @@ function createCrudRouter(config) {
1297
1389
  message: `Forbidden: Cannot ${operation} this resource`
1298
1390
  });
1299
1391
  };
1392
+ const querySearch = async (ctx, search) => {
1393
+ if (!search?.trim() || !Array.isArray(searchColumns)) return searchColumns;
1394
+ const target = readCrudTarget(config);
1395
+ const provider = resolveCrudExtensions(ctx, config);
1396
+ if (!target || !provider?.getMetadata) return searchColumns;
1397
+ const metadata = await provider.getMetadata({ id: target.id });
1398
+ return searchColumns.filter((column) => allowsSearch(metadata.fields, getColumnRefId(column)));
1399
+ };
1300
1400
  const queryWhere = async (ctx, input) => {
1301
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, input);
1401
+ const columns = await querySearch(ctx, input.search);
1402
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, input);
1302
1403
  const validatedFilters = effectiveInput.filters?.filter((filter) => validateColumn(filter.id, filterableColumns));
1303
1404
  const filterCondition = validatedFilters?.length ? filterColumns({
1304
1405
  table,
@@ -1315,7 +1416,7 @@ function createCrudRouter(config) {
1315
1416
  },
1316
1417
  resolveDateRange: ctx.resolveDateRange
1317
1418
  }) : void 0;
1318
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1419
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1319
1420
  return {
1320
1421
  effectiveInput,
1321
1422
  where: buildWhere(ctx, "list", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition))
@@ -1646,7 +1747,8 @@ function createCrudRouter(config) {
1646
1747
  export: resolved.procedureFactory("export").input(resolvedExportInputSchema).output(exportOutputSchema).query(async ({ ctx, input }) => {
1647
1748
  await withGuard(ctx, "export");
1648
1749
  const doExport = async (exportInput$1) => {
1649
- const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, searchColumns, {
1750
+ const columns = await querySearch(ctx, exportInput$1.search);
1751
+ const effectiveInput = await applyCrudExtensionFilters(ctx, config, table, idField, filterableColumns, columns, {
1650
1752
  page: 1,
1651
1753
  perPage: Math.min(Math.max(exportInput$1.limit ?? maxExportSize, 1), maxExportSize),
1652
1754
  joinOperator: exportInput$1.joinOperator ?? "and",
@@ -1669,7 +1771,7 @@ function createCrudRouter(config) {
1669
1771
  },
1670
1772
  resolveDateRange: ctx.resolveDateRange
1671
1773
  }) : void 0;
1672
- const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, searchColumns);
1774
+ const searchCondition = buildCrudSearchWithExtensions(table, effectiveInput, columns);
1673
1775
  const where = buildWhere(ctx, "export", combineConditions(combineExtensionFilter(filterCondition, effectiveInput), searchCondition));
1674
1776
  let query = ctx.db.select().from(table).$dynamic();
1675
1777
  if (where) query = query.where(where);
@@ -1730,7 +1832,7 @@ function createCrudRouter(config) {
1730
1832
  const failed = [];
1731
1833
  for (let i = 0; i < importData$1.rows.length; i++) {
1732
1834
  const row = importData$1.rows[i];
1733
- const result = importSchema.safeParse(row);
1835
+ const result = importSchema.safeParse(row, { reportInput: true });
1734
1836
  if (result.success) {
1735
1837
  const splitRow = splitCrudExtensionWriteInput(result.data, tableColumnNames);
1736
1838
  validRows.push(splitRow);
@@ -1738,7 +1840,8 @@ function createCrudRouter(config) {
1738
1840
  const errors = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
1739
1841
  failed.push({
1740
1842
  row: i,
1741
- errors
1843
+ errors,
1844
+ issues: result.error.issues.map((issue) => importIssue(issue, row))
1742
1845
  });
1743
1846
  if (importData$1.onConflict === "error") return {
1744
1847
  success: 0,
@@ -1880,4 +1983,4 @@ function composeMiddleware(...middlewares) {
1880
1983
  const appRouter = router({});
1881
1984
 
1882
1985
  //#endregion
1883
- export { afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router };
1986
+ export { afterMiddleware, appRouter, baseCountsInputSchema, baseExportInputSchema, baseGetInputSchema, baseListInputSchema, beforeMiddleware, composeMiddleware, createCrudRouter, publicProcedure, router, tagFilterValueSchema };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wordrhyme/auto-crud-server",
3
3
  "type": "module",
4
- "version": "2.1.0",
4
+ "version": "2.2.0",
5
5
  "description": "tRPC server utilities for auto-crud - automatic CRUD routers for Drizzle ORM",
6
6
  "author": "wordrhyme",
7
7
  "license": "MIT",
@@ -49,8 +49,8 @@
49
49
  "vitest": "^4.0.18",
50
50
  "zod": "^4.3.6",
51
51
  "@internal/eslint-config": "0.3.0",
52
- "@internal/tsdown-config": "0.1.0",
53
52
  "@internal/tsconfig": "0.1.0",
53
+ "@internal/tsdown-config": "0.1.0",
54
54
  "@internal/vitest-config": "0.1.0",
55
55
  "@internal/prettier-config": "0.0.1"
56
56
  },