sonamu 0.13.10 → 0.14.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 (330) hide show
  1. package/dist/api/caster.d.ts.map +1 -1
  2. package/dist/api/caster.js +2 -1
  3. package/dist/api/code-converters.d.ts +5 -1
  4. package/dist/api/code-converters.d.ts.map +1 -1
  5. package/dist/api/code-converters.js +24 -7
  6. package/dist/api/config.d.ts +7 -0
  7. package/dist/api/config.d.ts.map +1 -1
  8. package/dist/api/config.js +1 -1
  9. package/dist/api/decorators.d.ts +1 -0
  10. package/dist/api/decorators.d.ts.map +1 -1
  11. package/dist/api/decorators.js +1 -1
  12. package/dist/api/guards.d.ts +37 -0
  13. package/dist/api/guards.d.ts.map +1 -0
  14. package/dist/api/guards.js +96 -0
  15. package/dist/api/sonamu.d.ts +14 -1
  16. package/dist/api/sonamu.d.ts.map +1 -1
  17. package/dist/api/sonamu.js +121 -25
  18. package/dist/api/websocket-helpers.d.ts +6 -1
  19. package/dist/api/websocket-helpers.d.ts.map +1 -1
  20. package/dist/api/websocket-helpers.js +7 -4
  21. package/dist/auth/auth-entity-policy.d.ts +32 -0
  22. package/dist/auth/auth-entity-policy.d.ts.map +1 -0
  23. package/dist/auth/auth-entity-policy.js +44 -0
  24. package/dist/auth/auth-secret.d.ts +24 -0
  25. package/dist/auth/auth-secret.d.ts.map +1 -0
  26. package/dist/auth/auth-secret.js +46 -0
  27. package/dist/auth/base-url.d.ts +39 -0
  28. package/dist/auth/base-url.d.ts.map +1 -0
  29. package/dist/auth/base-url.js +84 -0
  30. package/dist/auth/better-auth-entities.js +20 -7
  31. package/dist/auth/better-auth-options.d.ts +15 -0
  32. package/dist/auth/better-auth-options.d.ts.map +1 -0
  33. package/dist/auth/better-auth-options.js +38 -0
  34. package/dist/auth/better-auth-request.d.ts +8 -1
  35. package/dist/auth/better-auth-request.d.ts.map +1 -1
  36. package/dist/auth/better-auth-request.js +26 -3
  37. package/dist/auth/plugins/entity-definitions/admin.d.ts.map +1 -1
  38. package/dist/auth/plugins/entity-definitions/admin.js +6 -1
  39. package/dist/auth/plugins/entity-definitions/anonymous.d.ts.map +1 -1
  40. package/dist/auth/plugins/entity-definitions/anonymous.js +2 -1
  41. package/dist/auth/plugins/entity-definitions/api-key.d.ts.map +1 -1
  42. package/dist/auth/plugins/entity-definitions/api-key.js +18 -2
  43. package/dist/auth/plugins/entity-definitions/audit-log.d.ts.map +1 -1
  44. package/dist/auth/plugins/entity-definitions/audit-log.js +27 -1
  45. package/dist/auth/plugins/entity-definitions/jwt.d.ts.map +1 -1
  46. package/dist/auth/plugins/entity-definitions/jwt.js +4 -2
  47. package/dist/auth/plugins/entity-definitions/organization.d.ts.map +1 -1
  48. package/dist/auth/plugins/entity-definitions/organization.js +15 -1
  49. package/dist/auth/plugins/entity-definitions/passkey.d.ts.map +1 -1
  50. package/dist/auth/plugins/entity-definitions/passkey.js +9 -1
  51. package/dist/auth/plugins/entity-definitions/phone-number.d.ts.map +1 -1
  52. package/dist/auth/plugins/entity-definitions/phone-number.js +2 -1
  53. package/dist/auth/plugins/entity-definitions/sso.d.ts.map +1 -1
  54. package/dist/auth/plugins/entity-definitions/sso.js +7 -3
  55. package/dist/auth/plugins/entity-definitions/two-factor.d.ts.map +1 -1
  56. package/dist/auth/plugins/entity-definitions/two-factor.js +8 -3
  57. package/dist/auth/verify-email-guard.d.ts +37 -0
  58. package/dist/auth/verify-email-guard.d.ts.map +1 -0
  59. package/dist/auth/verify-email-guard.js +48 -0
  60. package/dist/bin/build-config.d.ts.map +1 -1
  61. package/dist/bin/build-config.js +6 -2
  62. package/dist/bin/typecheck-web.js +1 -1
  63. package/dist/cache/decorator.d.ts +12 -0
  64. package/dist/cache/decorator.d.ts.map +1 -1
  65. package/dist/cache/decorator.js +86 -19
  66. package/dist/cache/index.d.ts +1 -1
  67. package/dist/cache/index.d.ts.map +1 -1
  68. package/dist/cache/index.js +3 -3
  69. package/dist/cache/types.d.ts +16 -0
  70. package/dist/cache/types.d.ts.map +1 -1
  71. package/dist/cli/plugin-loader.d.ts +17 -0
  72. package/dist/cli/plugin-loader.d.ts.map +1 -0
  73. package/dist/cli/plugin-loader.js +178 -0
  74. package/dist/cli/plugin.d.ts +65 -0
  75. package/dist/cli/plugin.d.ts.map +1 -0
  76. package/dist/cli/plugin.js +7 -0
  77. package/dist/code-formatting/oxfmt.js +1 -1
  78. package/dist/code-formatting/oxlint.js +1 -1
  79. package/dist/database/db.d.ts +35 -10
  80. package/dist/database/db.d.ts.map +1 -1
  81. package/dist/database/db.js +37 -4
  82. package/dist/database/puri.d.ts +8 -0
  83. package/dist/database/puri.d.ts.map +1 -1
  84. package/dist/database/puri.js +108 -171
  85. package/dist/database/puri.types.d.ts +2 -0
  86. package/dist/database/puri.types.d.ts.map +1 -1
  87. package/dist/database/puri.types.js +1 -1
  88. package/dist/database/sql-expression-brand.d.ts +10 -0
  89. package/dist/database/sql-expression-brand.d.ts.map +1 -0
  90. package/dist/database/sql-expression-brand.js +10 -0
  91. package/dist/dict/en.d.ts +1 -0
  92. package/dist/dict/en.d.ts.map +1 -1
  93. package/dist/dict/en.js +2 -1
  94. package/dist/dict/ko.d.ts +1 -0
  95. package/dist/dict/ko.d.ts.map +1 -1
  96. package/dist/dict/ko.js +2 -1
  97. package/dist/dict/sonamu-dictionary.d.ts +23 -1
  98. package/dist/dict/sonamu-dictionary.d.ts.map +1 -1
  99. package/dist/dict/sonamu-dictionary.js +187 -32
  100. package/dist/entity/entity-codegen-safety.d.ts +105 -0
  101. package/dist/entity/entity-codegen-safety.d.ts.map +1 -0
  102. package/dist/entity/entity-codegen-safety.js +70 -0
  103. package/dist/entity/entity-manager.d.ts +32 -0
  104. package/dist/entity/entity-manager.d.ts.map +1 -1
  105. package/dist/entity/entity-manager.js +21 -2
  106. package/dist/entity/entity.d.ts +5 -2
  107. package/dist/entity/entity.d.ts.map +1 -1
  108. package/dist/entity/entity.js +19 -8
  109. package/dist/env.d.ts +19 -0
  110. package/dist/env.d.ts.map +1 -1
  111. package/dist/env.js +31 -3
  112. package/dist/filter/utils.d.ts +2 -2
  113. package/dist/filter/utils.d.ts.map +1 -1
  114. package/dist/filter/utils.js +16 -11
  115. package/dist/index.d.ts +4 -3
  116. package/dist/index.d.ts.map +1 -1
  117. package/dist/index.js +7 -6
  118. package/dist/logger/configure.d.ts.map +1 -1
  119. package/dist/logger/configure.js +10 -3
  120. package/dist/migration/code-generation.d.ts.map +1 -1
  121. package/dist/migration/code-generation.js +177 -96
  122. package/dist/migration/migrator.d.ts +16 -0
  123. package/dist/migration/migrator.d.ts.map +1 -1
  124. package/dist/migration/migrator.js +28 -3
  125. package/dist/migration/slack-confirm.d.ts +6 -2
  126. package/dist/migration/slack-confirm.d.ts.map +1 -1
  127. package/dist/migration/slack-confirm.js +11 -9
  128. package/dist/ssr/errors.d.ts +13 -0
  129. package/dist/ssr/errors.d.ts.map +1 -0
  130. package/dist/ssr/errors.js +12 -0
  131. package/dist/ssr/index.d.ts +1 -0
  132. package/dist/ssr/index.d.ts.map +1 -1
  133. package/dist/ssr/index.js +5 -2
  134. package/dist/ssr/renderer.d.ts +6 -0
  135. package/dist/ssr/renderer.d.ts.map +1 -1
  136. package/dist/ssr/renderer.js +10 -1
  137. package/dist/storage/base-file.d.ts +6 -2
  138. package/dist/storage/base-file.d.ts.map +1 -1
  139. package/dist/storage/base-file.js +10 -5
  140. package/dist/storage/buffered-file.d.ts +1 -0
  141. package/dist/storage/buffered-file.d.ts.map +1 -1
  142. package/dist/storage/buffered-file.js +5 -2
  143. package/dist/storage/index.d.ts +1 -0
  144. package/dist/storage/index.d.ts.map +1 -1
  145. package/dist/storage/index.js +4 -2
  146. package/dist/storage/upload-safety.d.ts +47 -0
  147. package/dist/storage/upload-safety.d.ts.map +1 -0
  148. package/dist/storage/upload-safety.js +112 -0
  149. package/dist/stream/ws.d.ts +6 -0
  150. package/dist/stream/ws.d.ts.map +1 -1
  151. package/dist/stream/ws.js +52 -6
  152. package/dist/syncer/api-parser.js +6 -1
  153. package/dist/syncer/code-generator.d.ts +2 -0
  154. package/dist/syncer/code-generator.d.ts.map +1 -1
  155. package/dist/syncer/code-generator.js +21 -7
  156. package/dist/template/implementations/entity.template.d.ts.map +1 -1
  157. package/dist/template/implementations/entity.template.js +40 -35
  158. package/dist/template/implementations/generated.template.d.ts +10 -0
  159. package/dist/template/implementations/generated.template.d.ts.map +1 -1
  160. package/dist/template/implementations/generated.template.js +46 -7
  161. package/dist/template/implementations/generated_http.template.d.ts.map +1 -1
  162. package/dist/template/implementations/generated_http.template.js +3 -1
  163. package/dist/template/implementations/init_types.template.d.ts.map +1 -1
  164. package/dist/template/implementations/init_types.template.js +3 -8
  165. package/dist/template/implementations/model.template.d.ts.map +1 -1
  166. package/dist/template/implementations/model.template.js +9 -2
  167. package/dist/template/implementations/sd.template.d.ts +0 -1
  168. package/dist/template/implementations/sd.template.d.ts.map +1 -1
  169. package/dist/template/implementations/sd.template.js +2 -5
  170. package/dist/template/implementations/view_form.template.d.ts.map +1 -1
  171. package/dist/template/implementations/view_form.template.js +8 -6
  172. package/dist/template/implementations/view_list.template.d.ts.map +1 -1
  173. package/dist/template/implementations/view_list.template.js +8 -4
  174. package/dist/testing/dev-test-routes.d.ts.map +1 -1
  175. package/dist/testing/dev-test-routes.js +7 -4
  176. package/dist/tooling/__tests__/helpers/sonamu-test-root.js +1 -1
  177. package/dist/tooling/cdd-service.js +1 -1
  178. package/dist/tooling/index.d.ts +1 -0
  179. package/dist/tooling/index.d.ts.map +1 -1
  180. package/dist/tooling/index.js +3 -1
  181. package/dist/tsdown.api.config.js +1 -1
  182. package/dist/types/types.d.ts +81 -1
  183. package/dist/types/types.d.ts.map +1 -1
  184. package/dist/types/types.js +2 -1
  185. package/dist/ui/__tests__/ui-test-helpers.d.ts +10 -0
  186. package/dist/ui/__tests__/ui-test-helpers.d.ts.map +1 -0
  187. package/dist/ui/__tests__/ui-test-helpers.js +75 -0
  188. package/dist/ui/access-guard.d.ts +42 -0
  189. package/dist/ui/access-guard.d.ts.map +1 -0
  190. package/dist/ui/access-guard.js +94 -0
  191. package/dist/ui/api.d.ts.map +1 -1
  192. package/dist/ui/api.js +40 -95
  193. package/dist/ui/dev-host-guard.d.ts +28 -0
  194. package/dist/ui/dev-host-guard.d.ts.map +1 -0
  195. package/dist/ui/dev-host-guard.js +67 -0
  196. package/dist/ui/migrations-api.d.ts.map +1 -1
  197. package/dist/ui/migrations-api.js +72 -16
  198. package/dist/ui/open-vscode-api.d.ts +4 -0
  199. package/dist/ui/open-vscode-api.d.ts.map +1 -0
  200. package/dist/ui/open-vscode-api.js +65 -0
  201. package/dist/ui/scaffolding-api.d.ts +18 -0
  202. package/dist/ui/scaffolding-api.d.ts.map +1 -0
  203. package/dist/ui/scaffolding-api.js +111 -0
  204. package/dist/ui/ui-db-presets.d.ts +19 -0
  205. package/dist/ui/ui-db-presets.d.ts.map +1 -0
  206. package/dist/ui/ui-db-presets.js +34 -0
  207. package/dist/ui/ui-request-guard.d.ts +11 -0
  208. package/dist/ui/ui-request-guard.d.ts.map +1 -0
  209. package/dist/ui/ui-request-guard.js +38 -0
  210. package/dist/ui-web/assets/{index-QDMyy31K.js → index-BPqP-tug.js} +39 -39
  211. package/dist/ui-web/index.html +2 -1
  212. package/package.json +1 -1
  213. package/src/__tests__/env.test.ts +121 -2
  214. package/src/api/__tests__/code-converters.union.test.ts +97 -0
  215. package/src/api/__tests__/guards.test.ts +233 -0
  216. package/src/api/__tests__/sonamu.auth-secret.test.ts +77 -0
  217. package/src/api/__tests__/sonamu.dev-host-guard.test.ts +130 -0
  218. package/src/api/__tests__/sonamu.guards.test.ts +327 -0
  219. package/src/api/__tests__/sonamu.upload-limits.test.ts +156 -0
  220. package/src/api/__tests__/websocket-helpers.test.ts +101 -0
  221. package/src/api/caster.ts +7 -0
  222. package/src/api/code-converters.ts +44 -12
  223. package/src/api/config.ts +8 -0
  224. package/src/api/decorators.ts +1 -0
  225. package/src/api/guards.ts +130 -0
  226. package/src/api/sonamu.ts +195 -39
  227. package/src/api/websocket-helpers.ts +11 -6
  228. package/src/auth/__tests__/auth-entity-policy.test.ts +59 -0
  229. package/src/auth/__tests__/auth-secret.test.ts +133 -0
  230. package/src/auth/__tests__/base-url-host-poisoning.test.ts +193 -0
  231. package/src/auth/__tests__/base-url.test.ts +117 -0
  232. package/src/auth/__tests__/better-auth-options.test.ts +194 -0
  233. package/src/auth/__tests__/better-auth-request.test.ts +45 -0
  234. package/src/auth/__tests__/verify-email-guard.test.ts +228 -0
  235. package/src/auth/auth-entity-policy.ts +48 -0
  236. package/src/auth/auth-secret.ts +77 -0
  237. package/src/auth/base-url.ts +109 -0
  238. package/src/auth/better-auth-entities.ts +30 -30
  239. package/src/auth/better-auth-options.ts +39 -0
  240. package/src/auth/better-auth-request.ts +28 -1
  241. package/src/auth/plugins/entity-definitions/admin.ts +5 -0
  242. package/src/auth/plugins/entity-definitions/anonymous.ts +9 -1
  243. package/src/auth/plugins/entity-definitions/api-key.ts +53 -16
  244. package/src/auth/plugins/entity-definitions/audit-log.ts +122 -21
  245. package/src/auth/plugins/entity-definitions/jwt.ts +5 -4
  246. package/src/auth/plugins/entity-definitions/organization.ts +26 -6
  247. package/src/auth/plugins/entity-definitions/passkey.ts +8 -7
  248. package/src/auth/plugins/entity-definitions/phone-number.ts +1 -0
  249. package/src/auth/plugins/entity-definitions/sso.ts +20 -15
  250. package/src/auth/plugins/entity-definitions/two-factor.ts +21 -5
  251. package/src/auth/verify-email-guard.ts +82 -0
  252. package/src/bin/__tests__/build-web-command.test.ts +24 -0
  253. package/src/bin/build-config.ts +5 -0
  254. package/src/cache/decorator.ts +116 -21
  255. package/src/cache/index.ts +6 -1
  256. package/src/cache/types.ts +18 -0
  257. package/src/cli/plugin-loader.ts +238 -0
  258. package/src/cli/plugin.ts +82 -0
  259. package/src/database/__tests__/db.test.ts +64 -1
  260. package/src/database/__tests__/puri.test.ts +56 -0
  261. package/src/database/db.ts +56 -6
  262. package/src/database/puri.ts +135 -125
  263. package/src/database/puri.types.test-d.ts +12 -0
  264. package/src/database/puri.types.ts +3 -0
  265. package/src/database/sql-expression-brand.ts +9 -0
  266. package/src/dict/__tests__/sonamu-dictionary.test.ts +217 -0
  267. package/src/dict/en.ts +2 -0
  268. package/src/dict/ko.ts +2 -0
  269. package/src/dict/sonamu-dictionary.ts +298 -38
  270. package/src/entity/__tests__/entity-codegen-safety.test.ts +326 -0
  271. package/src/entity/entity-codegen-safety.ts +126 -0
  272. package/src/entity/entity-manager.ts +29 -1
  273. package/src/entity/entity.ts +26 -12
  274. package/src/env.ts +52 -1
  275. package/src/filter/utils.ts +19 -7
  276. package/src/index.ts +4 -3
  277. package/src/logger/__tests__/configure.test.ts +51 -1
  278. package/src/logger/configure.ts +14 -1
  279. package/src/migration/__tests__/code-generation.escape.test.ts +322 -0
  280. package/src/migration/__tests__/migrator.test.ts +76 -1
  281. package/src/migration/code-generation.ts +247 -117
  282. package/src/migration/migrator.ts +45 -4
  283. package/src/migration/slack-confirm.ts +19 -5
  284. package/src/ssr/__tests__/preload-guard.test.ts +274 -0
  285. package/src/ssr/errors.ts +11 -0
  286. package/src/ssr/index.ts +1 -0
  287. package/src/ssr/renderer.ts +12 -0
  288. package/src/storage/__tests__/upload-safety.test.ts +179 -0
  289. package/src/storage/base-file.ts +8 -4
  290. package/src/storage/buffered-file.ts +3 -1
  291. package/src/storage/index.ts +9 -0
  292. package/src/storage/upload-safety.ts +155 -0
  293. package/src/stream/__tests__/ws.test.ts +97 -0
  294. package/src/stream/ws.ts +67 -5
  295. package/src/syncer/__tests__/api-parser.readonly.test.ts +55 -0
  296. package/src/syncer/__tests__/code-generator-path-containment.test.ts +105 -0
  297. package/src/syncer/api-parser.ts +12 -0
  298. package/src/syncer/code-generator.ts +34 -6
  299. package/src/template/__tests__/generated.template.search-text.test.ts +5 -1
  300. package/src/template/__tests__/model.template.auth-entity.test.ts +42 -0
  301. package/src/template/__tests__/save-params.template.test.ts +219 -0
  302. package/src/template/implementations/entity.template.ts +53 -48
  303. package/src/template/implementations/generated.template.ts +87 -12
  304. package/src/template/implementations/generated_http.template.ts +5 -0
  305. package/src/template/implementations/init_types.template.ts +4 -22
  306. package/src/template/implementations/model.template.ts +15 -1
  307. package/src/template/implementations/sd.template.ts +4 -5
  308. package/src/template/implementations/view_form.template.ts +13 -5
  309. package/src/template/implementations/view_list.template.ts +12 -3
  310. package/src/testing/__tests__/dev-test-routes.test.ts +99 -0
  311. package/src/testing/dev-test-routes.ts +7 -3
  312. package/src/tooling/__tests__/cli-plugins.contract.test.ts +273 -0
  313. package/src/tooling/index.ts +1 -0
  314. package/src/types/types.ts +22 -1
  315. package/src/ui/__tests__/access-guard.test.ts +217 -0
  316. package/src/ui/__tests__/dev-host-guard.test.ts +161 -0
  317. package/src/ui/__tests__/fixture-api.test.ts +92 -0
  318. package/src/ui/__tests__/migrations-api.test.ts +352 -0
  319. package/src/ui/__tests__/open-vscode.test.ts +151 -0
  320. package/src/ui/__tests__/scaffolding-api.test.ts +232 -0
  321. package/src/ui/__tests__/ui-process-routes.test.ts +166 -0
  322. package/src/ui/__tests__/ui-test-helpers.ts +71 -0
  323. package/src/ui/access-guard.ts +115 -0
  324. package/src/ui/api.ts +65 -198
  325. package/src/ui/dev-host-guard.ts +109 -0
  326. package/src/ui/migrations-api.ts +130 -24
  327. package/src/ui/open-vscode-api.ts +82 -0
  328. package/src/ui/scaffolding-api.ts +177 -0
  329. package/src/ui/ui-db-presets.ts +41 -0
  330. package/src/ui/ui-request-guard.ts +53 -0
@@ -0,0 +1,326 @@
1
+ import { mkdtemp, readFile, rm, writeFile, mkdir } from "fs/promises";
2
+ import { tmpdir } from "os";
3
+ import path from "path";
4
+
5
+ import ts from "@typescript/typescript6";
6
+ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
7
+
8
+ import { Sonamu } from "../../api";
9
+ import { renderTemplate } from "../../syncer/code-generator";
10
+ import { Template__entity } from "../../template/implementations/entity.template";
11
+ import { Template__generated } from "../../template/implementations/generated.template";
12
+ import { Template__sd } from "../../template/implementations/sd.template";
13
+ import { type EntityJson } from "../../types/types";
14
+ import { type AbsolutePath } from "../../utils/path-utils";
15
+ import { Entity } from "../entity";
16
+ import { assertEntityJsonCodegenSafe } from "../entity-codegen-safety";
17
+ import { EntityManager } from "../entity-manager";
18
+
19
+ // 감사 PoC(GEN-04)에서 쓰인 형태의 페이로드. 실행되지 않고 문자열로만 다룬다.
20
+ const PROP_NAME_PAYLOAD =
21
+ "zz: z.string().nullable(), yy: (process.getBuiltinModule('node:child_process').execSync('id'), z.string().nullable()), xx";
22
+ const ENUM_ID_PAYLOAD = "TagZ = process.getBuiltinModule('node:child_process').execSync('id'); /*";
23
+ const FREE_TEXT_PAYLOAD = 'a"]);import("node:child_process");`${process.exit()}`\r\u2028*/ //';
24
+
25
+ function baseEntity(id = "SafetyTag"): EntityJson {
26
+ return {
27
+ id,
28
+ title: "태그",
29
+ table: "safety_tags",
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: "파일" },
35
+ ],
36
+ indexes: [],
37
+ subsets: { A: ["id", "name", "kind"] },
38
+ enums: {
39
+ SafetyTagKind: { a: "에이", "id-desc": "ID최신순" },
40
+ SafetyTagOrderBy: { "id-desc": "ID최신순" },
41
+ },
42
+ };
43
+ }
44
+
45
+ /** 생성 코드를 TypeScript로 파싱해 문법 오류가 없는지 확인하고 문장 목록을 돌려준다. */
46
+ function parseGenerated(code: string): ts.NodeArray<ts.Statement> {
47
+ const { diagnostics = [] } = ts.transpileModule(code, { reportDiagnostics: true });
48
+ expect(diagnostics.map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n"))).toEqual([]);
49
+ return ts.createSourceFile("generated.ts", code, ts.ScriptTarget.Latest, true).statements;
50
+ }
51
+
52
+ /** 문자열 리터럴 노드의 값을 꺼낸다. 다른 노드면 테스트를 실패시킨다. */
53
+ function stringLiteralText(node: ts.Node | undefined): string {
54
+ assert(node !== undefined && ts.isStringLiteral(node));
55
+ return node.text;
56
+ }
57
+
58
+ function expectRejected(json: EntityJson, pathFragment: string) {
59
+ expect(() => assertEntityJsonCodegenSafe(json)).toThrow(pathFragment);
60
+ }
61
+
62
+ /** 경로가 `/`로 시작하는 절대 경로인지 확인해 `AbsolutePath`로 좁힌다. */
63
+ function isAbsolutePath(value: string): value is AbsolutePath {
64
+ return value.startsWith("/");
65
+ }
66
+
67
+ describe("assertEntityJsonCodegenSafe", () => {
68
+ it("정상 엔티티는 통과한다 (enum 키·라벨·제목 같은 자유 문자열 포함)", () => {
69
+ const json = baseEntity();
70
+ json.title = FREE_TEXT_PAYLOAD;
71
+ json.enums.SafetyTagKind = { [FREE_TEXT_PAYLOAD]: FREE_TEXT_PAYLOAD };
72
+ expect(() => assertEntityJsonCodegenSafe(json)).not.toThrow();
73
+ });
74
+
75
+ it("prop 이름에 따옴표·괄호가 들어가면 거부한다", () => {
76
+ const json = baseEntity();
77
+ json.props.push({ name: PROP_NAME_PAYLOAD, type: "string", desc: "x", nullable: true });
78
+ expectRejected(json, "props.4.name");
79
+ });
80
+
81
+ it("enumId에 코드가 들어가면 거부한다", () => {
82
+ const json = baseEntity();
83
+ json.enums[ENUM_ID_PAYLOAD] = { k: "*/ //" };
84
+ expectRejected(json, "enumId에는 영문자, 숫자, _, $만 쓸 수 있습니다");
85
+ });
86
+
87
+ it.each([
88
+ ["entity id", (json: EntityJson) => (json.id = 'Tag"); evil(); ("'), "id"],
89
+ ["parentId", (json: EntityJson) => (json.parentId = "Parent()"), "parentId"],
90
+ ["table", (json: EntityJson) => (json.table = 'tags"; evil(); "'), "table"],
91
+ ["table 경로 이동", (json: EntityJson) => (json.table = "../../etc"), "table"],
92
+ ["subset 키", (json: EntityJson) => (json.subsets["A = evil(); //"] = ["id"]), "subsets"],
93
+ ["subset 필드", (json: EntityJson) => (json.subsets.A = ['id"]); evil(); (["']), "subsets.A.0"],
94
+ [
95
+ "prop id",
96
+ (json: EntityJson) => Object.assign(json.props[2], { id: "Kind; evil()" }),
97
+ "props.2.id",
98
+ ],
99
+ [
100
+ "zodFormat",
101
+ (json: EntityJson) => Object.assign(json.props[1], { zodFormat: "email(); evil" }),
102
+ "props.1.zodFormat",
103
+ ],
104
+ [
105
+ "length",
106
+ (json: EntityJson) => Object.assign(json.props[1], { length: "1); evil(" }),
107
+ "props.1.length",
108
+ ],
109
+ [
110
+ "relation 대상",
111
+ (json: EntityJson) =>
112
+ json.props.push({
113
+ name: "owner",
114
+ type: "relation",
115
+ relationType: "BelongsToOne",
116
+ with: "User\n evil()",
117
+ desc: "소유자",
118
+ }),
119
+ "props.4.with",
120
+ ],
121
+ [
122
+ "relationType 개행",
123
+ (json: EntityJson) =>
124
+ json.props.push({
125
+ name: "members",
126
+ type: "relation",
127
+ relationType: "HasMany",
128
+ with: "User",
129
+ joinColumn: "tag_id",
130
+ desc: "멤버",
131
+ }) && Object.assign(json.props[4], { relationType: "HasMany\nevil()" }),
132
+ "props.4.relationType",
133
+ ],
134
+ ])("%s 위치의 주입 값을 거부한다", (_label, mutate, pathFragment) => {
135
+ const json = baseEntity();
136
+ mutate(json);
137
+ expectRejected(json, pathFragment);
138
+ });
139
+ });
140
+
141
+ describe("엔티티 쓰기·로드 경로의 강제 검증", () => {
142
+ let apiRoot: AbsolutePath;
143
+ let jsonPath: string;
144
+
145
+ beforeAll(async () => {
146
+ const tempRoot = await mkdtemp(path.join(tmpdir(), "sonamu-son622-"));
147
+ // Sonamu.apiRootPath는 절대 경로만 받으므로 임시 디렉터리 경로를 실제로 검사해 좁힌다.
148
+ if (!isAbsolutePath(tempRoot)) {
149
+ throw new Error(`임시 디렉터리가 절대 경로가 아닙니다: ${tempRoot}`);
150
+ }
151
+ apiRoot = tempRoot;
152
+ jsonPath = path.join(apiRoot, "src/application/safety-saved/safety-saved.entity.json");
153
+ await mkdir(path.dirname(jsonPath), { recursive: true });
154
+ Sonamu.apiRootPath = apiRoot;
155
+ });
156
+
157
+ afterAll(async () => {
158
+ await rm(apiRoot, { recursive: true, force: true });
159
+ });
160
+
161
+ afterEach(() => {
162
+ vi.restoreAllMocks();
163
+ });
164
+
165
+ it("EntityManager.register는 prop 이름 주입을 거부하고 등록하지 않는다", async () => {
166
+ const json = baseEntity("SafetyRegister");
167
+ json.props.push({ name: PROP_NAME_PAYLOAD, type: "string", desc: "x" });
168
+
169
+ await expect(EntityManager.register(json)).rejects.toThrow("props.4.name");
170
+ expect(EntityManager.exists("SafetyRegister")).toBe(false);
171
+ });
172
+
173
+ it("Entity.save는 주입 값을 파일에 쓰지 않고 메모리의 엔티티를 디스크 상태로 되돌린다", async () => {
174
+ const original = JSON.stringify(baseEntity("SafetySaved"));
175
+ await writeFile(jsonPath, original);
176
+ await EntityManager.registerFromFile(jsonPath);
177
+
178
+ const entity = EntityManager.get("SafetySaved");
179
+ entity.enumLabels[ENUM_ID_PAYLOAD] = { k: "*/ //" };
180
+
181
+ await expect(entity.save()).rejects.toThrow("enums");
182
+ expect(await readFile(jsonPath, "utf8")).toBe(original);
183
+ expect(Object.keys(EntityManager.get("SafetySaved").enumLabels)).not.toContain(ENUM_ID_PAYLOAD);
184
+ });
185
+
186
+ it("Entity.createProp(UI createProp 경로)도 prop 이름 주입을 거부한다", async () => {
187
+ const original = JSON.stringify(baseEntity("SafetySaved"));
188
+ await writeFile(jsonPath, original);
189
+ await EntityManager.registerFromFile(jsonPath);
190
+
191
+ await expect(
192
+ EntityManager.get("SafetySaved").createProp({
193
+ name: PROP_NAME_PAYLOAD,
194
+ type: "string",
195
+ desc: "x",
196
+ nullable: true,
197
+ }),
198
+ ).rejects.toThrow("props.4.name");
199
+ expect(await readFile(jsonPath, "utf8")).toBe(original);
200
+ expect(EntityManager.get("SafetySaved").props.map((p) => p.name)).not.toContain(
201
+ PROP_NAME_PAYLOAD,
202
+ );
203
+ });
204
+
205
+ it("메모리에서만 바뀐 주입 값은 코드 생성 직전에 막는다", async () => {
206
+ await writeFile(jsonPath, JSON.stringify(baseEntity("SafetySaved")));
207
+ await EntityManager.registerFromFile(jsonPath);
208
+ const entity = EntityManager.get("SafetySaved");
209
+ entity.table = 'tags"; evil(); "';
210
+
211
+ try {
212
+ await expect(renderTemplate("generated", {})).rejects.toThrow("table");
213
+ } finally {
214
+ await EntityManager.registerFromFile(jsonPath);
215
+ }
216
+ });
217
+
218
+ it("새 엔티티 템플릿(UI create 경로)도 table 주입을 거부한다", () => {
219
+ const template = new Template__entity();
220
+ expect(() =>
221
+ template.render({ entityId: "SafetyCreated", title: "생성", table: 'x"); evil(); ("' }),
222
+ ).toThrow("table");
223
+ });
224
+ });
225
+
226
+ describe("자유 문자열의 생성 코드 출력", () => {
227
+ afterEach(() => {
228
+ vi.restoreAllMocks();
229
+ });
230
+
231
+ it("enum 키는 z.enum 배열 안의 문자열 리터럴로만 출력된다", () => {
232
+ const json = baseEntity();
233
+ const keys = [FREE_TEXT_PAYLOAD, 'a"b', "c\\"];
234
+ json.enums.SafetyTagKind = Object.fromEntries(keys.map((key) => [key, "라벨"]));
235
+ const sourceCode = new Template__generated().getEnumsSourceCode(new Entity(json));
236
+
237
+ const statements = parseGenerated(sourceCode?.lines.join("\n") ?? "");
238
+ // 엔티티의 enum 2개 × (const, type, Label) 외에 주입된 문장이 없어야 한다.
239
+ expect(statements).toHaveLength(6);
240
+ const [enumDecl] = statements;
241
+ assert(ts.isVariableStatement(enumDecl));
242
+ const describeCall = enumDecl.declarationList.declarations[0].initializer;
243
+ assert(describeCall !== undefined && ts.isCallExpression(describeCall));
244
+ assert(ts.isPropertyAccessExpression(describeCall.expression));
245
+ const enumCall = describeCall.expression.expression;
246
+ assert(ts.isCallExpression(enumCall));
247
+ const [array] = enumCall.arguments;
248
+ assert(ts.isArrayLiteralExpression(array));
249
+ expect(array.elements.map((el) => stringLiteralText(el))).toEqual(keys);
250
+ });
251
+
252
+ it("sd 라벨의 키와 값은 개행·U+2028이 있어도 문자열 리터럴로만 출력된다", () => {
253
+ const template = new Template__sd();
254
+ const labels = [
255
+ { key: `enum.SafetyTagKind.${FREE_TEXT_PAYLOAD}`, value: FREE_TEXT_PAYLOAD },
256
+ { key: "entity.SafetyTag", value: "줄1\r줄2\u2028줄3\n" },
257
+ ];
258
+ const code = template["generateEntityLabelsCode"](labels);
259
+
260
+ const statements = parseGenerated(code);
261
+ expect(statements).toHaveLength(1);
262
+ const [decl] = statements;
263
+ assert(ts.isVariableStatement(decl));
264
+ const asExpr = decl.declarationList.declarations[0].initializer;
265
+ assert(asExpr !== undefined && ts.isAsExpression(asExpr));
266
+ const objectLiteral = asExpr.expression;
267
+ assert(ts.isObjectLiteralExpression(objectLiteral));
268
+ expect(
269
+ objectLiteral.properties.map((property) => {
270
+ assert(ts.isPropertyAssignment(property));
271
+ return {
272
+ key: stringLiteralText(property.name),
273
+ value: stringLiteralText(property.initializer),
274
+ };
275
+ }),
276
+ ).toEqual(labels);
277
+ });
278
+
279
+ it("customJoinClause는 knex.raw·Puri.rawString 인자의 문자열 리터럴로만 출력된다", () => {
280
+ const clause = 'owner.id = tags.owner_id ${process.exit()} `"); evil(); ("';
281
+ const ownerJson: EntityJson = {
282
+ id: "SafetyOwner",
283
+ title: "소유자",
284
+ table: "safety_owners",
285
+ props: [
286
+ { name: "id", type: "integer", desc: "ID" },
287
+ { name: "name", type: "string", desc: "이름" },
288
+ ],
289
+ indexes: [],
290
+ subsets: {},
291
+ enums: {},
292
+ };
293
+ const tagJson = baseEntity();
294
+ tagJson.props.push({
295
+ name: "owner",
296
+ type: "relation",
297
+ relationType: "BelongsToOne",
298
+ with: "SafetyOwner",
299
+ customJoinClause: clause,
300
+ desc: "소유자",
301
+ });
302
+ tagJson.subsets = { A: ["id", "owner.name"] };
303
+ const owner = new Entity(ownerJson);
304
+ const tag = new Entity(tagJson);
305
+ vi.spyOn(EntityManager, "get").mockImplementation((id: string) =>
306
+ id === "SafetyOwner" ? owner : tag,
307
+ );
308
+
309
+ const code = tag.getPuriSubsetQuery("A");
310
+ const statements = parseGenerated(code);
311
+ expect(statements).toHaveLength(1);
312
+ const rawStrings: string[] = [];
313
+ const visit = (node: ts.Node) => {
314
+ if (ts.isCallExpression(node) && node.expression.getText().endsWith("knex.raw")) {
315
+ rawStrings.push(stringLiteralText(node.arguments[0]));
316
+ }
317
+ ts.forEachChild(node, visit);
318
+ };
319
+ statements.forEach(visit);
320
+ expect(rawStrings).toEqual([clause]);
321
+ });
322
+ });
323
+
324
+ function assert(condition: boolean): asserts condition {
325
+ expect(condition).toBeTruthy();
326
+ }
@@ -0,0 +1,126 @@
1
+ import { z } from "zod";
2
+
3
+ import { type LocalizedString } from "../dict/types";
4
+ import { BadRequestException } from "../exceptions/so-exceptions";
5
+ import { ZodStringFormat } from "../types/types";
6
+
7
+ /**
8
+ * 생성 TS에 따옴표 없이 식별자로 들어가는 값의 형식입니다.
9
+ * (entity id, prop 이름, enumId, 테이블명 등)
10
+ *
11
+ * JS가 허용하는 비ASCII 식별자(예: 한글 prop 이름)도 거부하므로, 그런 이름을 쓰던
12
+ * entity.json은 고쳐야 합니다.
13
+ */
14
+ export const CODE_IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
15
+
16
+ /** prop.id(타입 참조): 식별자 또는 `SonamuFile[]` 같은 배열 표기 */
17
+ export const TYPE_REFERENCE_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*(\[\])?$/;
18
+
19
+ /** subset 키: `${Entity}Subset${key}`처럼 식별자 뒤에 붙으므로 숫자로 시작해도 됩니다. */
20
+ export const SUBSET_KEY_PATTERN = /^[A-Za-z0-9_$]+$/;
21
+
22
+ /** subset 필드: prop 이름을 .으로 이은 경로 */
23
+ export const SUBSET_FIELD_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/;
24
+
25
+ function patterned(pattern: RegExp, label: string) {
26
+ return z.string().regex(pattern, {
27
+ error: (iss) =>
28
+ `${label}에는 영문자, 숫자, _, $만 쓸 수 있습니다. 입력값: ${JSON.stringify(iss.input)}`,
29
+ });
30
+ }
31
+
32
+ const identifier = (label: string) => patterned(CODE_IDENTIFIER_PATTERN, label);
33
+ const finiteNumber = z.number().finite();
34
+
35
+ const SubsetFieldSchema = z.union([
36
+ patterned(SUBSET_FIELD_PATTERN, "subset 필드"),
37
+ z.looseObject({ field: patterned(SUBSET_FIELD_PATTERN, "subset 필드") }),
38
+ ]);
39
+
40
+ const EnumValuesSchema = z.record(z.string(), z.string());
41
+
42
+ const CodegenSafePropSchema = z.looseObject({
43
+ name: identifier("prop 이름"),
44
+ type: z.string(),
45
+ desc: z.string().optional(),
46
+ id: patterned(TYPE_REFERENCE_PATTERN, "prop id").optional(),
47
+ with: identifier("relation 대상 entity id").optional(),
48
+ relationType: identifier("relationType").optional(),
49
+ joinTable: identifier("joinTable").optional(),
50
+ joinColumn: identifier("joinColumn").optional(),
51
+ fromColumn: identifier("fromColumn").optional(),
52
+ customJoinClause: z.string().optional(),
53
+ zodFormat: ZodStringFormat.optional(),
54
+ length: finiteNumber.optional(),
55
+ precision: finiteNumber.optional(),
56
+ scale: finiteNumber.optional(),
57
+ dimensions: finiteNumber.optional(),
58
+ sourceColumns: z.array(z.looseObject({ name: identifier("searchText source 컬럼") })).optional(),
59
+ });
60
+
61
+ /**
62
+ * entity.json 중 생성 코드(TS)에 들어가는 필드만 검사하는 스키마입니다.
63
+ *
64
+ * 전체 EntityJsonSchema는 하위 호환을 위해 로드 시 경고만 하므로, 코드 주입에 쓰일 수 있는
65
+ * 필드는 이 스키마로 따로 강제합니다. 자유 문자열(title, desc, enum 키·라벨, customJoinClause)은
66
+ * 형식을 제한하지 않고 템플릿에서 JSON.stringify로 출력합니다.
67
+ * 인덱스·dbDefault·generated.expression은 마이그레이션 코드 생성 쪽에서 다룹니다.
68
+ */
69
+ export const EntityCodegenSafetySchema = z.looseObject({
70
+ id: identifier("entity id"),
71
+ parentId: identifier("parentId").optional(),
72
+ title: z.string().optional(),
73
+ table: identifier("table"),
74
+ props: z.array(CodegenSafePropSchema).optional(),
75
+ subsets: z
76
+ .record(
77
+ patterned(SUBSET_KEY_PATTERN, "subset 키"),
78
+ z.union([z.array(SubsetFieldSchema), z.looseObject({ fields: z.array(SubsetFieldSchema) })]),
79
+ )
80
+ .optional(),
81
+ enums: z
82
+ .record(
83
+ identifier("enumId"),
84
+ z.union([EnumValuesSchema, z.looseObject({ values: EnumValuesSchema })]),
85
+ )
86
+ .optional(),
87
+ });
88
+
89
+ /**
90
+ * assertEntityJsonCodegenSafe가 받는 값의 모양입니다.
91
+ *
92
+ * 파일에서 읽은 EntityJson뿐 아니라 TemplateOptions(Zod 스키마)로 만든 새 entity.json도
93
+ * 받아야 하므로, 이 검사가 실제로 읽는 필드의 구조만 요구합니다.
94
+ */
95
+ export type EntityCodegenSafetyInput = z.input<typeof EntityCodegenSafetySchema>;
96
+
97
+ /**
98
+ * entity.json이 생성 코드에 안전하게 들어갈 수 있는지 검사하고, 아니면 400 예외를 던집니다.
99
+ *
100
+ * 정적 타입은 구조만 보장하고 UI API·파일에서 온 값의 형식은 실제로 검증되지 않았으므로 런타임에 다시 검사합니다.
101
+ *
102
+ * @param json 검사할 entity.json 값
103
+ * @param source 오류 메시지에 붙일 출처(파일 경로 등)
104
+ */
105
+ export function assertEntityJsonCodegenSafe(json: EntityCodegenSafetyInput, source?: string): void {
106
+ const result = EntityCodegenSafetySchema.safeParse(json);
107
+ if (result.success) {
108
+ return;
109
+ }
110
+
111
+ const details = result.error.issues
112
+ .map((issue) => {
113
+ // record 키 오류는 "Invalid key in record"만 남으므로 키 패턴의 실제 메시지를 꺼내 보여줍니다.
114
+ const message =
115
+ issue.code === "invalid_key"
116
+ ? issue.issues.map((keyIssue) => keyIssue.message).join(", ")
117
+ : issue.message;
118
+ return ` - ${issue.path.join(".") || "(root)"}: ${message}`;
119
+ })
120
+ .join("\n");
121
+ const message = `entity.json(${source ?? JSON.stringify(json.id)})에 생성 코드에 쓸 수 없는 값이 있습니다.\n${details}`;
122
+ throw new BadRequestException(
123
+ /* SAFETY: Zod 검증 오류를 사람이 읽을 메시지로 그대로 전달한다(sonamu.ts의 API 검증 오류와 같은 방식). */ message as LocalizedString,
124
+ { zodError: result.error },
125
+ );
126
+ }
@@ -20,6 +20,7 @@ import { importMembers } from "../utils/esm-utils";
20
20
  import { type AbsolutePath } from "../utils/path-utils";
21
21
  import { runtimePath } from "../utils/path-utils";
22
22
  import { type Entity } from "./entity";
23
+ import { assertEntityJsonCodegenSafe } from "./entity-codegen-safety";
23
24
 
24
25
  export type EntityNamesRecord = Record<
25
26
  "fs" | "fsPlural" | "camel" | "camelPlural" | "capital" | "capitalPlural" | "upper" | "constant",
@@ -78,6 +79,7 @@ class EntityManagerClass {
78
79
  await this.register(json, {
79
80
  deferSearchTextJsonSourceValidation: true,
80
81
  apiRootPath,
82
+ source: path.relative(apiRootPath, file),
81
83
  });
82
84
  }
83
85
 
@@ -103,8 +105,15 @@ class EntityManagerClass {
103
105
 
104
106
  async register(
105
107
  json: EntityJson,
106
- options: { deferSearchTextJsonSourceValidation?: boolean; apiRootPath?: string } = {},
108
+ options: {
109
+ deferSearchTextJsonSourceValidation?: boolean;
110
+ apiRootPath?: string;
111
+ /** 검증 오류 메시지에 표시할 출처(entity.json 경로) */
112
+ source?: string;
113
+ } = {},
107
114
  ): Promise<void> {
115
+ // 생성 코드에 그대로 들어가는 값은 등록 전에 강제 검증합니다(스키마 경고와 달리 로드를 중단).
116
+ assertEntityJsonCodegenSafe(json, options.source);
108
117
  const { Entity } = await import("./entity");
109
118
  const entity = new Entity(json);
110
119
  await entity.registerModulePaths(options.apiRootPath);
@@ -115,6 +124,25 @@ class EntityManagerClass {
115
124
  this.entities.set(json.id, entity);
116
125
  }
117
126
 
127
+ /**
128
+ * 디스크의 entity.json을 다시 읽어 등록합니다.
129
+ * 저장이 거부된 뒤 메모리에 남은 값을 마지막으로 저장된 상태로 되돌릴 때 씁니다.
130
+ */
131
+ async registerFromFile(jsonPath: string): Promise<void> {
132
+ const json = parseEntityJson((await readFile(jsonPath)).toString());
133
+ await this.register(json, { source: jsonPath });
134
+ }
135
+
136
+ /**
137
+ * 등록된 모든 엔티티가 생성 코드에 안전하게 들어갈 수 있는지 검사합니다.
138
+ * 코드 생성 직전의 마지막 방어선으로, 저장을 거치지 않고 메모리에서 바뀐 값도 막습니다.
139
+ */
140
+ assertAllCodegenSafe(): void {
141
+ for (const entity of this.entities.values()) {
142
+ assertEntityJsonCodegenSafe(entity.toJson());
143
+ }
144
+ }
145
+
118
146
  async validateAllRegisteredSearchTextJsonSources(apiRootPath?: string): Promise<void> {
119
147
  for (const entity of this.entities.values()) {
120
148
  await this.validateSearchTextJsonSources(entity, apiRootPath);
@@ -41,6 +41,7 @@ import { exists } from "../utils/fs-utils";
41
41
  import { runtimePath } from "../utils/path-utils";
42
42
  import { isStringValue } from "../utils/runtime-value";
43
43
  import { assertDefined, nonNullable } from "../utils/utils";
44
+ import { assertEntityJsonCodegenSafe } from "./entity-codegen-safety";
44
45
 
45
46
  type NestedSelect = { [key: string]: string | NestedSelect };
46
47
  import { EntityManager } from "./entity-manager";
@@ -261,9 +262,9 @@ export class Entity {
261
262
  const joinMethod = join.join === "inner" ? "join" : "leftJoin";
262
263
 
263
264
  if ("custom" in join) {
264
- // custom join clause는 raw 사용
265
+ // custom join clause는 raw 사용 (자유 문자열이므로 JSON 문자열 리터럴로 출력)
265
266
  lines.push(
266
- `.${joinMethod}({ ${join.as}: "${join.table}" }, qbWrapper.knex.raw(\`${join.custom}\`))`,
267
+ `.${joinMethod}({ ${join.as}: "${join.table}" }, qbWrapper.knex.raw(${JSON.stringify(join.custom)}))`,
267
268
  );
268
269
  } else {
269
270
  lines.push(`.${joinMethod}({ ${join.as}: "${join.table}" }, "${join.from}", "${join.to}")`);
@@ -419,7 +420,7 @@ export class Entity {
419
420
  // custom join clause는 callback 형태의 on 메서드로 처리합니다.
420
421
  loaderLines.push(
421
422
  `.${joinMethod}({ ${join.as}: "${join.table}" }, (j) => {`,
422
- `j.on(Puri.rawString("${join.custom}"));`,
423
+ `j.on(Puri.rawString(${JSON.stringify(join.custom)}));`,
423
424
  "})",
424
425
  );
425
426
  } else {
@@ -451,7 +452,7 @@ export class Entity {
451
452
  // custom join clause는 callback 형태의 on 메서드로 처리합니다.
452
453
  loaderLines.push(
453
454
  `.${joinMethod}({ ${join.as}: "${join.table}" }, (j) => {`,
454
- `j.on(Puri.rawString("${join.custom}"));`,
455
+ `j.on(Puri.rawString(${JSON.stringify(join.custom)}));`,
455
456
  "})",
456
457
  );
457
458
  } else {
@@ -873,14 +874,17 @@ export class Entity {
873
874
  /**
874
875
  * 필터링 가능한 props 반환
875
876
  *
876
- * - 일반 prop
877
- * - FK를 생성하는 relation (BelongsToOne, OneToOne with hasJoinColumn)
877
+ * sonamuFilter는 HTTP 요청에서 그대로 들어오므로 `toFilter: true`로 명시한 prop만 허용합니다.
878
+ * subset에서 숨긴 컬럼(비밀번호 해시 등)이 count 응답을 통해 추출되는 것을 막기 위함입니다.
879
+ *
880
+ * - `toFilter: true`인 일반 prop
881
+ * - `toFilter: true`이면서 FK를 생성하는 relation (BelongsToOne, OneToOne with hasJoinColumn)
878
882
  * → {name}_id 형태의 가상 integer prop으로 변환
879
883
  */
880
884
  getFilterableProps(): EntityProp[] {
881
885
  return this.props.flatMap((prop): EntityProp | EntityProp[] => {
882
- // Virtual prop 제외
883
- if (isVirtualProp(prop)) {
886
+ // toFilter를 켜지 않은 prop과 virtual prop은 필터 대상이 아님
887
+ if (prop.toFilter !== true || isVirtualProp(prop)) {
884
888
  return [];
885
889
  }
886
890
 
@@ -1014,6 +1018,20 @@ export class Entity {
1014
1018
  }
1015
1019
 
1016
1020
  async save(): Promise<void> {
1021
+ const jsonPath = path.join(
1022
+ Sonamu.apiRootPath,
1023
+ `src/application/${this.names.parentFs}/${this.names.fs}.entity.json`,
1024
+ );
1025
+
1026
+ // 생성 코드에 들어갈 수 없는 값은 파일에 쓰기 전에 거부합니다.
1027
+ try {
1028
+ assertEntityJsonCodegenSafe(this.toJson());
1029
+ } catch (error) {
1030
+ // 호출부가 이미 메모리의 엔티티를 바꿨으므로, 거부된 값이 다음 코드 생성에 쓰이지 않게 디스크 상태로 되돌립니다.
1031
+ await EntityManager.registerFromFile(jsonPath);
1032
+ throw error;
1033
+ }
1034
+
1017
1035
  // sort: subsets
1018
1036
  const subsetRows = this.getSubsetRows();
1019
1037
  this.subsets = Object.fromEntries(
@@ -1028,10 +1046,6 @@ export class Entity {
1028
1046
  );
1029
1047
 
1030
1048
  // save
1031
- const jsonPath = path.join(
1032
- Sonamu.apiRootPath,
1033
- `src/application/${this.names.parentFs}/${this.names.fs}.entity.json`,
1034
- );
1035
1049
  const json = this.toJson();
1036
1050
  await writeFile(jsonPath, await formatCode(JSON.stringify(json), jsonPath));
1037
1051
 
package/src/env.ts CHANGED
@@ -41,6 +41,56 @@ function readDotenvFile(filePath: string): EnvironmentSnapshot {
41
41
  return dotenv.parse(readFileSync(filePath));
42
42
  }
43
43
 
44
+ /**
45
+ * 런타임 NODE_ENV가 비어 있을 때 사용할 Sonamu 환경을 결정합니다.
46
+ *
47
+ * 우선순위는 런타임 `NODE_ENV` > `.env.local`의 `NODE_ENV` > `.env`의 `NODE_ENV` > `fallback` 입니다.
48
+ * 환경별 파일(`.env.{environment}`)은 환경이 정해진 뒤에 읽으므로 판정에 쓰지 않습니다.
49
+ * `env`는 읽기만 하고 바꾸지 않으며, 정해진 값이 Sonamu 환경이 아니면 에러를 던집니다.
50
+ */
51
+ export function resolveSonamuEnvironment(
52
+ rootPath: string,
53
+ fallback: SonamuEnvironment,
54
+ env: NodeJS.ProcessEnv = process.env,
55
+ ): SonamuEnvironment {
56
+ if (env.NODE_ENV !== undefined && env.NODE_ENV !== "") {
57
+ return getSonamuEnvironment(env);
58
+ }
59
+
60
+ const dotenvNodeEnv =
61
+ readDotenvFile(path.join(rootPath, ".env.local")).NODE_ENV ||
62
+ readDotenvFile(path.join(rootPath, ".env")).NODE_ENV;
63
+
64
+ return getSonamuEnvironment({ NODE_ENV: dotenvNodeEnv || fallback });
65
+ }
66
+
67
+ /**
68
+ * {@link resolveSonamuEnvironment}로 결정한 환경을 `env.NODE_ENV`에 기록하고 돌려줍니다.
69
+ */
70
+ export function ensureSonamuEnvironment(
71
+ rootPath: string,
72
+ fallback: SonamuEnvironment,
73
+ env: NodeJS.ProcessEnv = process.env,
74
+ ): SonamuEnvironment {
75
+ const environment = resolveSonamuEnvironment(rootPath, fallback, env);
76
+ env.NODE_ENV = environment;
77
+ return environment;
78
+ }
79
+
80
+ /**
81
+ * 서버 프로세스의 환경을 확정합니다.
82
+ *
83
+ * 소스 실행(`sonamu dev`의 `HOT=yes`, vitest)이 아닌 빌드 산출물 실행은 NODE_ENV가 없으면
84
+ * production으로 봅니다. 미설정을 development로 보면 Sonamu UI와 dev 라우트가 프로덕션 포트에 열립니다.
85
+ */
86
+ export function ensureServerEnvironment(
87
+ rootPath: string,
88
+ env: NodeJS.ProcessEnv = process.env,
89
+ ): SonamuEnvironment {
90
+ const isSourceRuntime = env.HOT === "yes" || env.VITEST === "true";
91
+ return ensureSonamuEnvironment(rootPath, isSourceRuntime ? "development" : "production", env);
92
+ }
93
+
44
94
  function assertEnvironmentDotenvExists(rootPath: string, environment: SonamuEnvironment): void {
45
95
  const commonEnvPath = path.join(rootPath, ".env");
46
96
  const environmentEnvPath = path.join(rootPath, `.env.${environment}`);
@@ -100,7 +150,8 @@ export function readAllEnvironmentSnapshots(
100
150
  }
101
151
 
102
152
  export function applyCurrentSnapshotToProcessEnv(rootPath: string): EnvironmentSnapshot {
103
- const environment = getSonamuEnvironment();
153
+ // 개발 도구(sync, migrate 등)는 NODE_ENV 없이 실행되므로 기본값은 development로 유지합니다.
154
+ const environment = resolveSonamuEnvironment(rootPath, "development");
104
155
  const snapshot = readEnvironmentSnapshot(rootPath, environment);
105
156
 
106
157
  for (const [key, value] of Object.entries(snapshot)) {