sonamu 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/auth/better-auth-entities.d.ts.map +1 -1
  2. package/dist/auth/better-auth-entities.js +35 -35
  3. package/dist/auth/plugins/entity-definitions/admin.js +6 -6
  4. package/dist/auth/plugins/entity-definitions/anonymous.js +2 -2
  5. package/dist/auth/plugins/entity-definitions/api-key.d.ts.map +1 -1
  6. package/dist/auth/plugins/entity-definitions/api-key.js +23 -23
  7. package/dist/auth/plugins/entity-definitions/audit-log.d.ts.map +1 -1
  8. package/dist/auth/plugins/entity-definitions/audit-log.js +28 -28
  9. package/dist/auth/plugins/entity-definitions/jwt.js +6 -6
  10. package/dist/auth/plugins/entity-definitions/organization.js +32 -32
  11. package/dist/auth/plugins/entity-definitions/passkey.js +12 -12
  12. package/dist/auth/plugins/entity-definitions/phone-number.js +3 -3
  13. package/dist/auth/plugins/entity-definitions/sso.js +9 -9
  14. package/dist/auth/plugins/entity-definitions/two-factor.js +11 -11
  15. package/dist/auth/plugins/entity-definitions/username.js +3 -3
  16. package/dist/dict/sonamu-dictionary.js +9 -9
  17. package/dist/dict/types.d.ts +1 -1
  18. package/dist/dict/types.d.ts.map +1 -1
  19. package/dist/entity/entity-codegen-safety.d.ts +2 -1
  20. package/dist/entity/entity-codegen-safety.d.ts.map +1 -1
  21. package/dist/entity/entity-codegen-safety.js +3 -2
  22. package/dist/entity/entity-manager.d.ts +40 -20
  23. package/dist/entity/entity-manager.d.ts.map +1 -1
  24. package/dist/entity/entity.d.ts.map +1 -1
  25. package/dist/entity/entity.js +4 -2
  26. package/dist/index.js +2 -2
  27. package/dist/template/helpers.js +3 -3
  28. package/dist/template/implementations/entity.template.js +4 -4
  29. package/dist/template/implementations/generated.template.d.ts.map +1 -1
  30. package/dist/template/implementations/generated.template.js +3 -4
  31. package/dist/template/implementations/sd.template.js +3 -3
  32. package/dist/template/implementations/view_form.template.js +2 -2
  33. package/dist/template/zod-converter.d.ts +12 -2
  34. package/dist/template/zod-converter.d.ts.map +1 -1
  35. package/dist/template/zod-converter.js +31 -18
  36. package/dist/types/types.d.ts +153 -64
  37. package/dist/types/types.d.ts.map +1 -1
  38. package/dist/types/types.js +19 -7
  39. package/dist/ui/ai-client.js +3 -3
  40. package/dist/ui/api.js +2 -2
  41. package/dist/ui/migrations-api.d.ts.map +1 -1
  42. package/dist/ui/migrations-api.js +2 -2
  43. package/dist/ui-web/assets/{index-BPqP-tug.js → index-CdZtV4yt.js} +46 -46
  44. package/dist/ui-web/assets/index-DbecN7yE.css +1 -0
  45. package/dist/ui-web/index.html +2 -2
  46. package/package.json +3 -1
  47. package/src/auth/better-auth-entities.ts +40 -34
  48. package/src/auth/plugins/entity-definitions/admin.ts +5 -5
  49. package/src/auth/plugins/entity-definitions/anonymous.ts +1 -1
  50. package/src/auth/plugins/entity-definitions/api-key.ts +28 -22
  51. package/src/auth/plugins/entity-definitions/audit-log.ts +34 -27
  52. package/src/auth/plugins/entity-definitions/jwt.ts +5 -5
  53. package/src/auth/plugins/entity-definitions/organization.ts +31 -31
  54. package/src/auth/plugins/entity-definitions/passkey.ts +11 -11
  55. package/src/auth/plugins/entity-definitions/phone-number.ts +2 -2
  56. package/src/auth/plugins/entity-definitions/sso.ts +8 -8
  57. package/src/auth/plugins/entity-definitions/two-factor.ts +10 -10
  58. package/src/auth/plugins/entity-definitions/username.ts +2 -2
  59. package/src/bin/__tests__/zod-compiler-build.test.ts +2 -1
  60. package/src/dict/sonamu-dictionary.ts +6 -6
  61. package/src/dict/types.ts +1 -1
  62. package/src/entity/__tests__/entity-codegen-safety.test.ts +44 -12
  63. package/src/entity/__tests__/entity-subset-query.test.ts +35 -7
  64. package/src/entity/entity-codegen-safety.ts +2 -1
  65. package/src/entity/entity.ts +3 -0
  66. package/src/shared/app.shared.ts.txt +1 -2
  67. package/src/shared/web.shared.ts.txt +1 -2
  68. package/src/template/helpers.ts +3 -3
  69. package/src/template/implementations/entity.template.ts +3 -3
  70. package/src/template/implementations/generated.template.ts +4 -3
  71. package/src/template/implementations/sd.template.ts +2 -2
  72. package/src/template/implementations/view_form.template.ts +1 -1
  73. package/src/template/zod-converter.ts +84 -19
  74. package/src/types/types.ts +42 -8
  75. package/src/ui/__tests__/migrations-api.test.ts +90 -0
  76. package/src/ui/ai-client.ts +2 -2
  77. package/src/ui/api.ts +2 -2
  78. package/src/ui/entity.instructions.md +45 -43
  79. package/src/ui/migrations-api.ts +6 -3
  80. package/dist/ui-web/assets/index-dV7akMFB.css +0 -1
@@ -40,6 +40,7 @@ describe("TypeScript 7 Web 빌드 정책", () => {
40
40
  expect(stdout).toBe(argument);
41
41
  });
42
42
 
43
+ // tsc 하위 프로세스를 세 번 실행하므로, 여러 패키지 테스트가 함께 도는 CI에서는 기본 5초를 넘깁니다.
43
44
  it("선언을 만들지 않는 앱은 모든 project reference를 타입 검사한다", async () => {
44
45
  const webRoot = await mkdtemp(path.join(process.cwd(), ".sonamu-web-typecheck-test-"));
45
46
  webTypecheckRoots.push(webRoot);
@@ -85,7 +86,7 @@ describe("TypeScript 7 Web 빌드 정책", () => {
85
86
  expect(command).not.toContain("tsc -b");
86
87
  expect(command).not.toContain("typecheck-web");
87
88
  }
88
- });
89
+ }, 30_000);
89
90
  });
90
91
 
91
92
  describe("API zod-compiler 빌드 정책", () => {
@@ -677,9 +677,9 @@ export class SonamuDictionary {
677
677
  }
678
678
 
679
679
  // entity.{EntityId}.{propName}
680
- const propDescMatch = key.match(/^entity\.([A-Z][a-zA-Z0-9]*)\.([a-z_][a-z0-9_]*)$/);
681
- if (propDescMatch) {
682
- return { type: "propDesc", entityId: propDescMatch[1], propName: propDescMatch[2] };
680
+ const propTitleMatch = key.match(/^entity\.([A-Z][a-zA-Z0-9]*)\.([a-z_][a-z0-9_]*)$/);
681
+ if (propTitleMatch) {
682
+ return { type: "propTitle", entityId: propTitleMatch[1], propName: propTitleMatch[2] };
683
683
  }
684
684
 
685
685
  // enum.{EnumId}.{value}
@@ -713,12 +713,12 @@ export class SonamuDictionary {
713
713
  return false;
714
714
  }
715
715
 
716
- case "propDesc": {
716
+ case "propTitle": {
717
717
  try {
718
718
  const entity = EntityManager.get(keyInfo.entityId);
719
719
  const propIndex = entity.props.findIndex((p) => p.name === keyInfo.propName);
720
- if (propIndex !== -1 && entity.props[propIndex].desc !== value) {
721
- entity.props[propIndex].desc = value;
720
+ if (propIndex !== -1 && entity.props[propIndex].title !== value) {
721
+ entity.props[propIndex].title = value;
722
722
  await entity.save();
723
723
  return true;
724
724
  }
package/src/dict/types.ts CHANGED
@@ -24,7 +24,7 @@ export type DictionaryRow = {
24
24
  */
25
25
  export type EntityKeyInfo =
26
26
  | { type: "entityTitle"; entityId: string }
27
- | { type: "propDesc"; entityId: string; propName: string }
27
+ | { type: "propTitle"; entityId: string; propName: string }
28
28
  | { type: "enumLabel"; enumId: string; enumValue: string }
29
29
  | { type: "other" };
30
30
 
@@ -28,10 +28,10 @@ function baseEntity(id = "SafetyTag"): EntityJson {
28
28
  title: "태그",
29
29
  table: "safety_tags",
30
30
  props: [
31
- { name: "id", type: "integer", desc: "ID" },
32
- { name: "name", type: "string", desc: "이름", length: 100 },
33
- { name: "kind", type: "enum", id: "SafetyTagKind", desc: "종류" },
34
- { name: "files", type: "json", id: "SonamuFile[]", desc: "파일" },
31
+ { name: "id", type: "integer", title: "ID" },
32
+ { name: "name", type: "string", title: "이름", length: 100 },
33
+ { name: "kind", type: "enum", id: "SafetyTagKind", title: "종류" },
34
+ { name: "files", type: "json", id: "SonamuFile[]", title: "파일" },
35
35
  ],
36
36
  indexes: [],
37
37
  subsets: { A: ["id", "name", "kind"] },
@@ -74,7 +74,7 @@ describe("assertEntityJsonCodegenSafe", () => {
74
74
 
75
75
  it("prop 이름에 따옴표·괄호가 들어가면 거부한다", () => {
76
76
  const json = baseEntity();
77
- json.props.push({ name: PROP_NAME_PAYLOAD, type: "string", desc: "x", nullable: true });
77
+ json.props.push({ name: PROP_NAME_PAYLOAD, type: "string", title: "x", nullable: true });
78
78
  expectRejected(json, "props.4.name");
79
79
  });
80
80
 
@@ -114,7 +114,7 @@ describe("assertEntityJsonCodegenSafe", () => {
114
114
  type: "relation",
115
115
  relationType: "BelongsToOne",
116
116
  with: "User\n evil()",
117
- desc: "소유자",
117
+ title: "소유자",
118
118
  }),
119
119
  "props.4.with",
120
120
  ],
@@ -127,7 +127,7 @@ describe("assertEntityJsonCodegenSafe", () => {
127
127
  relationType: "HasMany",
128
128
  with: "User",
129
129
  joinColumn: "tag_id",
130
- desc: "멤버",
130
+ title: "멤버",
131
131
  }) && Object.assign(json.props[4], { relationType: "HasMany\nevil()" }),
132
132
  "props.4.relationType",
133
133
  ],
@@ -164,7 +164,7 @@ describe("엔티티 쓰기·로드 경로의 강제 검증", () => {
164
164
 
165
165
  it("EntityManager.register는 prop 이름 주입을 거부하고 등록하지 않는다", async () => {
166
166
  const json = baseEntity("SafetyRegister");
167
- json.props.push({ name: PROP_NAME_PAYLOAD, type: "string", desc: "x" });
167
+ json.props.push({ name: PROP_NAME_PAYLOAD, type: "string", title: "x" });
168
168
 
169
169
  await expect(EntityManager.register(json)).rejects.toThrow("props.4.name");
170
170
  expect(EntityManager.exists("SafetyRegister")).toBe(false);
@@ -192,7 +192,7 @@ describe("엔티티 쓰기·로드 경로의 강제 검증", () => {
192
192
  EntityManager.get("SafetySaved").createProp({
193
193
  name: PROP_NAME_PAYLOAD,
194
194
  type: "string",
195
- desc: "x",
195
+ title: "x",
196
196
  nullable: true,
197
197
  }),
198
198
  ).rejects.toThrow("props.4.name");
@@ -283,8 +283,8 @@ describe("자유 문자열의 생성 코드 출력", () => {
283
283
  title: "소유자",
284
284
  table: "safety_owners",
285
285
  props: [
286
- { name: "id", type: "integer", desc: "ID" },
287
- { name: "name", type: "string", desc: "이름" },
286
+ { name: "id", type: "integer", title: "ID" },
287
+ { name: "name", type: "string", title: "이름" },
288
288
  ],
289
289
  indexes: [],
290
290
  subsets: {},
@@ -297,7 +297,7 @@ describe("자유 문자열의 생성 코드 출력", () => {
297
297
  relationType: "BelongsToOne",
298
298
  with: "SafetyOwner",
299
299
  customJoinClause: clause,
300
- desc: "소유자",
300
+ title: "소유자",
301
301
  });
302
302
  tagJson.subsets = { A: ["id", "owner.name"] };
303
303
  const owner = new Entity(ownerJson);
@@ -319,6 +319,38 @@ describe("자유 문자열의 생성 코드 출력", () => {
319
319
  statements.forEach(visit);
320
320
  expect(rawStrings).toEqual([clause]);
321
321
  });
322
+
323
+ it("서브셋 칸의 title·description은 메타 호출 인자의 문자열 리터럴로만 출력된다", () => {
324
+ const json = baseEntity();
325
+ Object.assign(json.props[1], { title: FREE_TEXT_PAYLOAD, description: "줄1\r줄2\u2028줄3\n" });
326
+ const entity = new Entity(json);
327
+ vi.spyOn(EntityManager, "get").mockReturnValue(entity);
328
+ const sourceCode = new Template__generated().getSubsetSourceCode(entity);
329
+
330
+ const statements = parseGenerated(sourceCode?.lines.join("\n") ?? "");
331
+ // 서브셋 A의 const·type, SubsetMapping, SubsetKey const·type 외에 주입된 문장이 없어야 한다.
332
+ expect(statements).toHaveLength(5);
333
+ const titles: string[] = [];
334
+ const descriptions: string[] = [];
335
+ const visit = (node: ts.Node) => {
336
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
337
+ const method = node.expression.name.text;
338
+ const [arg] = node.arguments;
339
+ if (method === "meta" && arg !== undefined && ts.isObjectLiteralExpression(arg)) {
340
+ for (const property of arg.properties) {
341
+ assert(ts.isPropertyAssignment(property) && ts.isIdentifier(property.name));
342
+ const key = property.name.text;
343
+ expect(["title", "description"]).toContain(key);
344
+ (key === "title" ? titles : descriptions).push(stringLiteralText(property.initializer));
345
+ }
346
+ }
347
+ }
348
+ ts.forEachChild(node, visit);
349
+ };
350
+ statements.forEach(visit);
351
+ expect(titles).toEqual(["ID", FREE_TEXT_PAYLOAD, "종류"]);
352
+ expect(descriptions).toEqual(["줄1\r줄2\u2028줄3\n"]);
353
+ });
322
354
  });
323
355
 
324
356
  function assert(condition: boolean): asserts condition {
@@ -8,16 +8,16 @@ const chatRoomJson: EntityJson = {
8
8
  id: "ChatRoom",
9
9
  table: "chat_rooms",
10
10
  props: [
11
- { name: "id", type: "integer", desc: "ID" },
12
- { name: "name", type: "string", desc: "이름" },
13
- { name: "case", type: "relation", relationType: "BelongsToOne", with: "Case", desc: "케이스" },
11
+ { name: "id", type: "integer", title: "ID" },
12
+ { name: "name", type: "string", title: "이름" },
13
+ { name: "case", type: "relation", relationType: "BelongsToOne", with: "Case", title: "케이스" },
14
14
  {
15
15
  name: "owned_cases",
16
16
  type: "relation",
17
17
  relationType: "HasMany",
18
18
  with: "Case",
19
19
  joinColumn: "owner_id",
20
- desc: "소유 케이스",
20
+ title: "소유 케이스",
21
21
  },
22
22
  ],
23
23
  indexes: [],
@@ -29,7 +29,7 @@ const caseJson: EntityJson = {
29
29
  id: "Case",
30
30
  table: "cases",
31
31
  props: [
32
- { name: "id", type: "integer", desc: "ID" },
32
+ { name: "id", type: "integer", title: "ID" },
33
33
  {
34
34
  name: "chat_room",
35
35
  type: "relation",
@@ -37,14 +37,14 @@ const caseJson: EntityJson = {
37
37
  with: "ChatRoom",
38
38
  hasJoinColumn: false,
39
39
  nullable: true,
40
- desc: "채팅방",
40
+ title: "채팅방",
41
41
  },
42
42
  {
43
43
  name: "owner",
44
44
  type: "relation",
45
45
  relationType: "BelongsToOne",
46
46
  with: "ChatRoom",
47
- desc: "소유 채팅방",
47
+ title: "소유 채팅방",
48
48
  },
49
49
  ],
50
50
  indexes: [],
@@ -116,3 +116,31 @@ describe("Entity.resolveSubsetQuery", () => {
116
116
  expect(caseEntity.getSubsetAutoInternalFields("A")).toEqual(["owner.id"]);
117
117
  });
118
118
  });
119
+
120
+ describe("Entity.fieldExprsToPropNodes", () => {
121
+ afterEach(() => {
122
+ vi.restoreAllMocks();
123
+ });
124
+
125
+ it("관계의 id만 고르면 FK 칸이 관계의 제목·설명을 이어받는다", () => {
126
+ const chatRoom = new Entity(chatRoomJson);
127
+ const caseEntity = new Entity({
128
+ ...caseJson,
129
+ props: caseJson.props.map((prop) =>
130
+ prop.name === "owner" ? { ...prop, description: "케이스를 가진 채팅방" } : prop,
131
+ ),
132
+ });
133
+ vi.spyOn(EntityManager, "get").mockImplementation((id: string) =>
134
+ id === "ChatRoom" ? chatRoom : caseEntity,
135
+ );
136
+
137
+ const [node] = caseEntity.fieldExprsToPropNodes(["owner.id"]);
138
+
139
+ expect(node?.prop).toMatchObject({
140
+ name: "owner_id",
141
+ type: "integer",
142
+ title: "소유 채팅방",
143
+ description: "케이스를 가진 채팅방",
144
+ });
145
+ });
146
+ });
@@ -42,7 +42,8 @@ const EnumValuesSchema = z.record(z.string(), z.string());
42
42
  const CodegenSafePropSchema = z.looseObject({
43
43
  name: identifier("prop 이름"),
44
44
  type: z.string(),
45
- desc: z.string().optional(),
45
+ title: z.string().optional(),
46
+ description: z.string().optional(),
46
47
  id: patterned(TYPE_REFERENCE_PATTERN, "prop id").optional(),
47
48
  with: identifier("relation 대상 entity id").optional(),
48
49
  relationType: identifier("relationType").optional(),
@@ -773,6 +773,7 @@ export class Entity {
773
773
  (groupedFieldExprs[0] === "id" || groupedFieldExprs[0] === "id?")
774
774
  ) {
775
775
  // id 하나만 있는지 체크해서, 하나만 있으면 상위 prop으로 id를 리턴
776
+ // 타입은 대상 엔티티의 id를 따르되, 이름·제목·설명은 이 칸이 가리키는 관계의 것을 씁니다.
776
777
  const idProp = relEntity.propsDict.id;
777
778
  return {
778
779
  nodeType: "plain" as const,
@@ -780,6 +781,8 @@ export class Entity {
780
781
  ...idProp,
781
782
  name: `${key}_id`,
782
783
  nullable: prop.nullable,
784
+ title: prop.title,
785
+ description: prop.description,
783
786
  },
784
787
  };
785
788
  }
@@ -341,8 +341,7 @@ export const SQLDateTimeString = z
341
341
  message: "잘못된 SQLDate 타입",
342
342
  })
343
343
  .min(10)
344
- .max(19)
345
- .describe("SQLDateTimeString");
344
+ .max(19);
346
345
  export type SQLDateTimeString = z.infer<typeof SQLDateTimeString>;
347
346
 
348
347
  /*
@@ -289,8 +289,7 @@ export const SQLDateTimeString = z
289
289
  message: "잘못된 SQLDate 타입",
290
290
  })
291
291
  .min(10)
292
- .max(19)
293
- .describe("SQLDateTimeString");
292
+ .max(19);
294
293
  export type SQLDateTimeString = z.infer<typeof SQLDateTimeString>;
295
294
 
296
295
  /**
@@ -25,8 +25,8 @@ export function getLabel(entityId: string, enumId: string): string {
25
25
  const enumProp = EntityManager.get(entityId).props.find(
26
26
  (prop) => `${entityId}${inflection.camelize(prop.name)}` === enumId,
27
27
  );
28
- if (enumProp?.desc) {
29
- return enumProp.desc;
28
+ if (enumProp?.title) {
29
+ return enumProp.title;
30
30
  }
31
31
  return enumId;
32
32
  }
@@ -44,7 +44,7 @@ export function getEnumInfoFromColName(entityId: string, colName: string): EnumC
44
44
  id: prop.id,
45
45
  targetEntityId: entityId,
46
46
  targetEntityNames: EntityManager.getNamesFromId(entityId),
47
- title: prop.desc ?? prop.id,
47
+ title: prop.title ?? prop.id,
48
48
  };
49
49
  } else {
50
50
  const idCandidate = inflection.camelize(
@@ -51,7 +51,7 @@ export class Template__entity extends Template {
51
51
  props: options.props?.length
52
52
  ? options.props
53
53
  : [
54
- { name: "id", type: "integer", desc: "ID" },
54
+ { name: "id", type: "integer", title: "ID" },
55
55
  ...(parent
56
56
  ? [
57
57
  {
@@ -61,14 +61,14 @@ export class Template__entity extends Template {
61
61
  with: parentId,
62
62
  onUpdate: "CASCADE",
63
63
  onDelete: "CASCADE",
64
- desc: parent.entity.title,
64
+ title: parent.entity.title,
65
65
  },
66
66
  ]
67
67
  : []),
68
68
  {
69
69
  name: "created_at",
70
70
  type: "date",
71
- desc: "등록일시",
71
+ title: "등록일시",
72
72
  dbDefault: "CURRENT_TIMESTAMP",
73
73
  },
74
74
  ],
@@ -128,7 +128,6 @@ export class Template__generated extends Template {
128
128
  const builtInSchemas = sourceCode.importKeys.filter((key) => builtInSchemaNames.includes(key));
129
129
  const sonamuImports = [
130
130
  "zArrayable",
131
- "SQLDateTimeString",
132
131
  "SubsetQuery",
133
132
  "SonamuQueryMode",
134
133
  "ApplySonamuFilter",
@@ -163,9 +162,10 @@ export class Template__generated extends Template {
163
162
  .filter(([, enumLabel]) => Object.keys(enumLabel).length > 0)
164
163
  .flatMap(([enumId, enumLabel]) => [
165
164
  // enum 키는 자유 문자열이므로 JSON 문자열 리터럴로 출력합니다.
165
+ // SonamuEnumId는 필터 UI가 enum.{EnumId}.{값} 라벨 키를 만들 때 읽습니다.
166
166
  `export const ${enumId} = z.enum([${Object.keys(enumLabel).map((el) =>
167
167
  JSON.stringify(el),
168
- )}]).describe(${JSON.stringify(enumId)});`,
168
+ )}]).meta({ SonamuEnumId: ${JSON.stringify(enumId)} });`,
169
169
  `export type ${enumId} = z.infer<typeof ${enumId}>;`,
170
170
  `export const ${enumId}Label = ${JSON.stringify(enumLabel)};`,
171
171
  ]),
@@ -460,7 +460,8 @@ z.object({
460
460
  };
461
461
 
462
462
  // EntityPropNode[]로 ZodTypeDef(string)을 가져옴
463
- const body = propNodeToZodTypeDef(propNode, importKeys);
463
+ // 서브셋은 API 응답 스키마라 칸의 title·description을 메타로 실어 명세에 나오게 합니다.
464
+ const body = propNodeToZodTypeDef(propNode, importKeys, { withPropMeta: true });
464
465
 
465
466
  return [
466
467
  `export const ${schemaName} = ${body.replace(/,$/, "")};`,
@@ -386,8 +386,8 @@ SD.enumLabels = (enumName: string): Record<string, LocalizedString> => {
386
386
 
387
387
  // prop labels (entity.json에서 관리)
388
388
  for (const prop of entity.props) {
389
- if (prop.desc) {
390
- labels.push({ key: `entity.${entityId}.${prop.name}`, value: prop.desc });
389
+ if (prop.title) {
390
+ labels.push({ key: `entity.${entityId}.${prop.name}`, value: prop.title });
391
391
  }
392
392
  }
393
393
 
@@ -222,7 +222,7 @@ export class Template__view_form extends Template {
222
222
  .filter((col) => col.name !== "id")
223
223
  .map((col) => {
224
224
  const propCandidate = entity.props.find((prop) => prop.name === col.name);
225
- col.label = propCandidate?.desc ?? col.label;
225
+ col.label = propCandidate?.title ?? col.label;
226
226
  return col;
227
227
  });
228
228
 
@@ -53,6 +53,7 @@ import {
53
53
  isVectorArrayProp,
54
54
  isVectorSingleProp,
55
55
  isVirtualProp,
56
+ getSonamuType,
56
57
  SonamuFileArraySchema,
57
58
  SonamuFileSchema,
58
59
  } from "../types/types";
@@ -93,7 +94,9 @@ export const BUILT_IN_TYPES = {
93
94
  } as const;
94
95
 
95
96
  function getBuiltInSchemaName(zodType: z.ZodType): string | undefined {
96
- const matched = Object.entries(BUILT_IN_TYPES).find(([typeId]) => zodType.description === typeId);
97
+ const matched = Object.entries(BUILT_IN_TYPES).find(
98
+ ([typeId]) => getSonamuType(zodType) === typeId,
99
+ );
97
100
  return matched?.[1].schemaName;
98
101
  }
99
102
 
@@ -210,7 +213,8 @@ export async function getZodTypeById(zodTypeId: string): Promise<z.ZodTypeAny> {
210
213
  if (!builtInType) {
211
214
  throw new Error(`내장 타입 ${zodTypeId}의 스키마가 정의되지 않았습니다`);
212
215
  }
213
- return builtInType.schema.describe(zodTypeId);
216
+ // 내장 스키마는 정의할 때 이미 타입 표식을 걸어 두었습니다.
217
+ return builtInType.schema;
214
218
  }
215
219
 
216
220
  // 프로젝트에서 정의한 타입 동적 로드
@@ -225,7 +229,9 @@ export async function getZodTypeById(zodTypeId: string): Promise<z.ZodTypeAny> {
225
229
  if (!imported[zodTypeId]) {
226
230
  throw new Error(`존재하지 않는 zodTypeId ${zodTypeId}`);
227
231
  }
228
- return imported[zodTypeId].describe(zodTypeId);
232
+ // `.meta()`는 복제본에 메타를 걸므로 사용자 스키마는 그대로입니다. 복제본은 사용자가 단 description 등을 키별로 물려받습니다.
233
+ const marked: z.ZodTypeAny = imported[zodTypeId].meta({ SonamuType: zodTypeId });
234
+ return marked;
229
235
  }
230
236
 
231
237
  /**
@@ -336,10 +342,67 @@ export async function propToZodType(prop: EntityProp): Promise<z.ZodTypeAny> {
336
342
  return zodType;
337
343
  }
338
344
 
345
+ /**
346
+ * 생성 코드에 칸 메타를 실을지 정하는 옵션입니다.
347
+ */
348
+ export type PropZodTypeDefOptions = {
349
+ /**
350
+ * true이면 칸의 title·description을 `.meta({ title, description })`로 싣습니다.
351
+ * `z.toJSONSchema` 결과에 그대로 나옵니다. 서브셋 스키마에서 켭니다.
352
+ */
353
+ withPropMeta?: boolean;
354
+ };
355
+
356
+ /**
357
+ * 생성 코드의 `.meta()`에 싣는 칸 메타입니다.
358
+ *
359
+ * zod 기본 레지스트리 메타에 평평한 키로 실립니다. `title`·`description`은 zod 표준 키이고,
360
+ * `Sonamu`로 시작하는 키는 Sonamu와 react-components가 읽는 표식입니다.
361
+ */
362
+ type PropMeta = {
363
+ /** 칸의 표시 이름 */
364
+ title?: string;
365
+ /** 칸의 뜻 */
366
+ description?: string;
367
+ /** numeric 칸 표시. 필터 UI가 읽습니다. */
368
+ SonamuPropType?: "numeric";
369
+ };
370
+
371
+ /**
372
+ * 칸의 zod 정의 코드 뒤에 붙일 `.meta({...})` 코드를 만듭니다.
373
+ *
374
+ * `.nullable()` 뒤 맨 바깥에 붙여 nullable 칸도 메타가 바깥에 실리게 합니다.
375
+ */
376
+ function propMetaCode(
377
+ prop: { title?: string; description?: string },
378
+ options: PropZodTypeDefOptions,
379
+ extraMeta: PropMeta = {},
380
+ ): string {
381
+ const meta: PropMeta = {};
382
+ if (options.withPropMeta && prop.title) {
383
+ meta.title = prop.title;
384
+ }
385
+ if (options.withPropMeta && prop.description) {
386
+ meta.description = prop.description;
387
+ }
388
+ Object.assign(meta, extraMeta);
389
+
390
+ if (Object.keys(meta).length === 0) {
391
+ return "";
392
+ }
393
+ // 값은 자유 문자열이므로 JSON 문자열 리터럴로 출력합니다.
394
+ const entries = Object.entries(meta).map(([key, value]) => `${key}: ${JSON.stringify(value)}`);
395
+ return `.meta({ ${entries.join(", ")} })`;
396
+ }
397
+
339
398
  /**
340
399
  * EntityProp을 Zod 타입 정의 코드 문자열로 변환합니다.
341
400
  */
342
- export function propToZodTypeDef(prop: EntityProp, injectImportKeys: string[]): string {
401
+ export function propToZodTypeDef(
402
+ prop: EntityProp,
403
+ injectImportKeys: string[],
404
+ options: PropZodTypeDefOptions = {},
405
+ ): string {
343
406
  let stmt: string;
344
407
  if (isIntegerSingleProp(prop)) {
345
408
  stmt = `${prop.name}: z.int()`;
@@ -456,9 +519,9 @@ export function propToZodTypeDef(prop: EntityProp, injectImportKeys: string[]):
456
519
  }
457
520
 
458
521
  // numeric 타입의 경우 nullable 이후에 meta 추가 (메타데이터가 최상위 레벨에 있어야 함)
459
- if (isNumericSingleProp(prop) || isNumericArrayProp(prop)) {
460
- stmt += '.meta({ SonamuPropType: "numeric" })';
461
- }
522
+ const numericMeta: PropMeta =
523
+ isNumericSingleProp(prop) || isNumericArrayProp(prop) ? { SonamuPropType: "numeric" } : {};
524
+ stmt += propMetaCode(prop, options, numericMeta);
462
525
 
463
526
  return `${stmt},`;
464
527
  }
@@ -467,28 +530,32 @@ export function propToZodTypeDef(prop: EntityProp, injectImportKeys: string[]):
467
530
  * EntityPropNode를 Zod 타입 정의 코드 문자열로 변환합니다.
468
531
  * plain, array, object 노드 타입을 재귀적으로 처리하여 중첩 구조를 지원합니다.
469
532
  */
470
- export function propNodeToZodTypeDef(propNode: EntityPropNode, injectImportKeys: string[]): string {
533
+ export function propNodeToZodTypeDef(
534
+ propNode: EntityPropNode,
535
+ injectImportKeys: string[],
536
+ options: PropZodTypeDefOptions = {},
537
+ ): string {
471
538
  if (propNode.nodeType === "plain") {
472
- return propToZodTypeDef(propNode.prop, injectImportKeys);
539
+ return propToZodTypeDef(propNode.prop, injectImportKeys, options);
473
540
  } else if (propNode.nodeType === "array") {
474
541
  return [
475
542
  propNode.prop ? `${propNode.prop.name}: ` : "",
476
543
  "z.array(z.object({",
477
544
  propNode.children
478
- .map((childPropNode) => propNodeToZodTypeDef(childPropNode, injectImportKeys))
545
+ .map((childPropNode) => propNodeToZodTypeDef(childPropNode, injectImportKeys, options))
479
546
  .join("\n"),
480
547
  "",
481
- "})),",
548
+ `}))${propNode.prop ? propMetaCode(propNode.prop, options) : ""},`,
482
549
  ].join("\n");
483
550
  } else if (propNode.nodeType === "object") {
484
551
  return [
485
552
  propNode.prop ? `${propNode.prop.name}: ` : "",
486
553
  "z.object({",
487
554
  propNode.children
488
- .map((childPropNode) => propNodeToZodTypeDef(childPropNode, injectImportKeys))
555
+ .map((childPropNode) => propNodeToZodTypeDef(childPropNode, injectImportKeys, options))
489
556
  .join("\n"),
490
557
  "",
491
- `})${propNode.prop?.nullable ? ".nullable()" : ""},`,
558
+ `})${propNode.prop?.nullable ? ".nullable()" : ""}${propNode.prop ? propMetaCode(propNode.prop, options) : ""},`,
492
559
  ].join("\n");
493
560
  } else {
494
561
  throw Error;
@@ -791,7 +858,7 @@ export function zodTypeToRenderingNode(
791
858
  /**
792
859
  * 케이스 처리 순서
793
860
  *
794
- * 1. 특수 케이스 (description 기반)
861
+ * 1. 특수 케이스 (Sonamu 타입 표식 기반)
795
862
  * - SonamuFile/SonamuFile[] : z.object/z.array이지만 파일 업로드용 내장 타입
796
863
  *
797
864
  * 2. 일반 케이스 (instanceof 기반)
@@ -804,12 +871,12 @@ export function zodTypeToRenderingNode(
804
871
  */
805
872
 
806
873
  // 특수 케이스: SonamuFile[] 타입 감지
807
- if (zodType.description === "SonamuFile[]") {
874
+ if (getSonamuType(zodType) === "SonamuFile[]") {
808
875
  return { ...def, renderType: "json-sonamufile-array" };
809
876
  }
810
877
 
811
878
  // 특수 케이스: SonamuFile 단일 타입 감지
812
- if (zodType.description === "SonamuFile") {
879
+ if (getSonamuType(zodType) === "SonamuFile") {
813
880
  return { ...def, renderType: "json-sonamufile" };
814
881
  }
815
882
 
@@ -889,9 +956,7 @@ function resolveRenderType(key: string, zodType: z.ZodTypeAny): RenderingNode["r
889
956
  } else if (zodType instanceof z.core.$ZodString) {
890
957
  // NOTE: z.ZodString으로 비교하면 z.url(), z.email() 등의 타입에서 문제가 생기므로 z.core.$ZodString으로 비교함
891
958
  // FIXME: email이나 url 타입 등에 대한 처리가 필요함
892
- if (zodType.description === "SQLDateTimeString") {
893
- return "string-datetime";
894
- } else if (key.endsWith("date")) {
959
+ if (key.endsWith("date")) {
895
960
  return "string-date";
896
961
  } else if (key === "id") {
897
962
  return "string-id";