@wordrhyme/auto-crud-server 2.1.1 → 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
@@ -1321,3 +1321,20 @@ Set `counts: true` on `createCrudRouter` to expose `counts({ queries })`. Each q
1321
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
1322
 
1323
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),
@@ -1250,7 +1324,13 @@ function createCrudRouter(config) {
1250
1324
  skipped: zod.z.number(),
1251
1325
  failed: zod.z.array(zod.z.object({
1252
1326
  row: zod.z.number(),
1253
- 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()
1254
1334
  }))
1255
1335
  });
1256
1336
  const resolved = resolveConfig(config);
@@ -1783,7 +1863,7 @@ function createCrudRouter(config) {
1783
1863
  const failed = [];
1784
1864
  for (let i = 0; i < importData$1.rows.length; i++) {
1785
1865
  const row = importData$1.rows[i];
1786
- const result = importSchema.safeParse(row);
1866
+ const result = importSchema.safeParse(row, { reportInput: true });
1787
1867
  if (result.success) {
1788
1868
  const splitRow = splitCrudExtensionWriteInput(result.data, tableColumnNames);
1789
1869
  validRows.push(splitRow);
@@ -1791,7 +1871,8 @@ function createCrudRouter(config) {
1791
1871
  const errors = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
1792
1872
  failed.push({
1793
1873
  row: i,
1794
- errors
1874
+ errors,
1875
+ issues: result.error.issues.map((issue) => importIssue(issue, row))
1795
1876
  });
1796
1877
  if (importData$1.onConflict === "error") return {
1797
1878
  success: 0,
@@ -1943,4 +2024,5 @@ exports.beforeMiddleware = beforeMiddleware;
1943
2024
  exports.composeMiddleware = composeMiddleware;
1944
2025
  exports.createCrudRouter = createCrudRouter;
1945
2026
  exports.publicProcedure = publicProcedure;
1946
- exports.router = router;
2027
+ exports.router = router;
2028
+ exports.tagFilterValueSchema = tagFilterValueSchema;
package/dist/index.d.cts CHANGED
@@ -6,9 +6,9 @@ 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;
@@ -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";
@@ -1087,4 +1155,4 @@ declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
1087
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
@@ -1,4 +1,4 @@
1
- import * as _trpc_server2 from "@trpc/server";
1
+ import * as _trpc_server0 from "@trpc/server";
2
2
  import { AnyColumn, SQL, Table } from "drizzle-orm";
3
3
  import { z } from "zod";
4
4
  import superjson from "superjson";
@@ -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;
@@ -41,13 +41,13 @@ interface Context {
41
41
  db: PostgresJsDatabase<Record<string, never>>;
42
42
  resolveDateRange?: DateRangeResolver;
43
43
  }
44
- declare const router: _trpc_server2.TRPCRouterBuilder<{
44
+ declare const router: _trpc_server0.TRPCRouterBuilder<{
45
45
  ctx: Context;
46
46
  meta: object;
47
- errorShape: _trpc_server2.TRPCDefaultErrorShape;
47
+ errorShape: _trpc_server0.TRPCDefaultErrorShape;
48
48
  transformer: true;
49
49
  }>;
50
- declare const publicProcedure: _trpc_server2.TRPCProcedureBuilder<Context, object, object, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, _trpc_server2.TRPCUnsetMarker, false>;
50
+ declare const publicProcedure: _trpc_server0.TRPCProcedureBuilder<Context, object, object, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, false>;
51
51
  //#endregion
52
52
  //#region src/types/config.d.ts
53
53
  type CrudOperation = 'list' | 'get' | 'create' | 'update' | 'delete' | 'deleteMany' | 'updateMany' | 'upsert' | 'export' | 'import' | 'createMany';
@@ -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";
@@ -1080,12 +1148,12 @@ type CrudHookEventMap<PluginId extends string, ResourceName extends string, TCre
1080
1148
  } } & { [K in `${PluginId}.${ResourceName}.createMany`]: TCreate[] };
1081
1149
  //#endregion
1082
1150
  //#region src/routers/index.d.ts
1083
- declare const appRouter: _trpc_server2.TRPCBuiltRouter<{
1151
+ declare const appRouter: _trpc_server0.TRPCBuiltRouter<{
1084
1152
  ctx: Context;
1085
1153
  meta: object;
1086
- errorShape: _trpc_server2.TRPCDefaultErrorShape;
1154
+ errorShape: _trpc_server0.TRPCDefaultErrorShape;
1087
1155
  transformer: true;
1088
- }, _trpc_server2.TRPCDecorateCreateRouterOptions<{}>>;
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),
@@ -1219,7 +1293,13 @@ function createCrudRouter(config) {
1219
1293
  skipped: z.number(),
1220
1294
  failed: z.array(z.object({
1221
1295
  row: z.number(),
1222
- 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()
1223
1303
  }))
1224
1304
  });
1225
1305
  const resolved = resolveConfig(config);
@@ -1752,7 +1832,7 @@ function createCrudRouter(config) {
1752
1832
  const failed = [];
1753
1833
  for (let i = 0; i < importData$1.rows.length; i++) {
1754
1834
  const row = importData$1.rows[i];
1755
- const result = importSchema.safeParse(row);
1835
+ const result = importSchema.safeParse(row, { reportInput: true });
1756
1836
  if (result.success) {
1757
1837
  const splitRow = splitCrudExtensionWriteInput(result.data, tableColumnNames);
1758
1838
  validRows.push(splitRow);
@@ -1760,7 +1840,8 @@ function createCrudRouter(config) {
1760
1840
  const errors = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
1761
1841
  failed.push({
1762
1842
  row: i,
1763
- errors
1843
+ errors,
1844
+ issues: result.error.issues.map((issue) => importIssue(issue, row))
1764
1845
  });
1765
1846
  if (importData$1.onConflict === "error") return {
1766
1847
  success: 0,
@@ -1902,4 +1983,4 @@ function composeMiddleware(...middlewares) {
1902
1983
  const appRouter = router({});
1903
1984
 
1904
1985
  //#endregion
1905
- 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.1",
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",
@@ -50,9 +50,9 @@
50
50
  "zod": "^4.3.6",
51
51
  "@internal/eslint-config": "0.3.0",
52
52
  "@internal/tsconfig": "0.1.0",
53
- "@internal/prettier-config": "0.0.1",
54
53
  "@internal/tsdown-config": "0.1.0",
55
- "@internal/vitest-config": "0.1.0"
54
+ "@internal/vitest-config": "0.1.0",
55
+ "@internal/prettier-config": "0.0.1"
56
56
  },
57
57
  "prettier": "@internal/prettier-config",
58
58
  "scripts": {