@c15t/backend 1.0.5 → 1.2.0-canary.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 (462) hide show
  1. package/.turbo/turbo-build.log +33 -39
  2. package/.turbo/turbo-fmt.log +3 -3
  3. package/.turbo/turbo-test.log +531 -0
  4. package/coverage/coverage-final.json +84 -0
  5. package/coverage/coverage-summary.json +85 -0
  6. package/coverage/html/backend/index.html +116 -0
  7. package/coverage/html/backend/rslib.config.ts.html +415 -0
  8. package/coverage/html/backend/src/contracts/consent/index.html +161 -0
  9. package/coverage/html/backend/src/contracts/consent/index.ts.html +112 -0
  10. package/coverage/html/backend/src/contracts/consent/post.contract.ts.html +559 -0
  11. package/coverage/html/backend/src/contracts/consent/show-banner.contract.ts.html +220 -0
  12. package/coverage/html/backend/src/contracts/consent/verify.contract.ts.html +463 -0
  13. package/coverage/html/backend/src/contracts/index.html +116 -0
  14. package/coverage/html/backend/src/contracts/index.ts.html +139 -0
  15. package/coverage/html/backend/src/contracts/meta/index.html +131 -0
  16. package/coverage/html/backend/src/contracts/meta/index.ts.html +100 -0
  17. package/coverage/html/backend/src/contracts/meta/status.contract.ts.html +196 -0
  18. package/coverage/html/backend/src/contracts/shared/index.html +116 -0
  19. package/coverage/html/backend/src/contracts/shared/jurisdiction.schema.ts.html +175 -0
  20. package/coverage/html/backend/src/core.ts.html +1624 -0
  21. package/coverage/html/backend/src/handlers/consent/index.html +161 -0
  22. package/coverage/html/backend/src/handlers/consent/index.ts.html +112 -0
  23. package/coverage/html/backend/src/handlers/consent/post.handler.ts.html +889 -0
  24. package/coverage/html/backend/src/handlers/consent/show-banner.handler.ts.html +535 -0
  25. package/coverage/html/backend/src/handlers/consent/verify.handler.ts.html +1000 -0
  26. package/coverage/html/backend/src/handlers/meta/index.html +131 -0
  27. package/coverage/html/backend/src/handlers/meta/index.ts.html +100 -0
  28. package/coverage/html/backend/src/handlers/meta/status.handler.ts.html +226 -0
  29. package/coverage/html/backend/src/index.html +161 -0
  30. package/coverage/html/backend/src/init.ts.html +1018 -0
  31. package/coverage/html/backend/src/pkgs/api-router/hooks/index.html +116 -0
  32. package/coverage/html/backend/src/pkgs/api-router/hooks/processor.ts.html +544 -0
  33. package/coverage/html/backend/src/pkgs/api-router/index.html +116 -0
  34. package/coverage/html/backend/src/pkgs/api-router/telemetry.ts.html +334 -0
  35. package/coverage/html/backend/src/pkgs/api-router/utils/cors.ts.html +304 -0
  36. package/coverage/html/backend/src/pkgs/api-router/utils/index.html +131 -0
  37. package/coverage/html/backend/src/pkgs/api-router/utils/ip.ts.html +361 -0
  38. package/coverage/html/backend/src/pkgs/data-model/fields/field-factory.ts.html +709 -0
  39. package/coverage/html/backend/src/pkgs/data-model/fields/id-generator.ts.html +256 -0
  40. package/coverage/html/backend/src/pkgs/data-model/fields/index.html +161 -0
  41. package/coverage/html/backend/src/pkgs/data-model/fields/superjson-utils.ts.html +136 -0
  42. package/coverage/html/backend/src/pkgs/data-model/fields/zod-fields.ts.html +496 -0
  43. package/coverage/html/backend/src/pkgs/data-model/hooks/create-hooks.ts.html +349 -0
  44. package/coverage/html/backend/src/pkgs/data-model/hooks/index.html +176 -0
  45. package/coverage/html/backend/src/pkgs/data-model/hooks/update-hooks.ts.html +358 -0
  46. package/coverage/html/backend/src/pkgs/data-model/hooks/update-many-hooks.ts.html +613 -0
  47. package/coverage/html/backend/src/pkgs/data-model/hooks/utils.ts.html +538 -0
  48. package/coverage/html/backend/src/pkgs/data-model/hooks/with-hooks-factory.ts.html +289 -0
  49. package/coverage/html/backend/src/pkgs/db-adapters/adapter-factory.ts.html +289 -0
  50. package/coverage/html/backend/src/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.ts.html +2203 -0
  51. package/coverage/html/backend/src/pkgs/db-adapters/adapters/drizzle-adapter/index.html +116 -0
  52. package/coverage/html/backend/src/pkgs/db-adapters/adapters/index.html +116 -0
  53. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/dialect.ts.html +670 -0
  54. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/index.html +131 -0
  55. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/kysely-adapter.ts.html +3634 -0
  56. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/tests/index.html +116 -0
  57. package/coverage/html/backend/src/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.ts.html +1417 -0
  58. package/coverage/html/backend/src/pkgs/db-adapters/adapters/memory-adapter/index.html +116 -0
  59. package/coverage/html/backend/src/pkgs/db-adapters/adapters/memory-adapter/memory-adapter.ts.html +2071 -0
  60. package/coverage/html/backend/src/pkgs/db-adapters/adapters/prisma-adapter/index.html +116 -0
  61. package/coverage/html/backend/src/pkgs/db-adapters/adapters/prisma-adapter/prisma-adapter.ts.html +1834 -0
  62. package/coverage/html/backend/src/pkgs/db-adapters/adapters/test.ts.html +316 -0
  63. package/coverage/html/backend/src/pkgs/db-adapters/index.html +131 -0
  64. package/coverage/html/backend/src/pkgs/db-adapters/utils.ts.html +238 -0
  65. package/coverage/html/backend/src/pkgs/migrations/get-migration.ts.html +343 -0
  66. package/coverage/html/backend/src/pkgs/migrations/get-schema/get-schema.ts.html +217 -0
  67. package/coverage/html/backend/src/pkgs/migrations/get-schema/index.html +146 -0
  68. package/coverage/html/backend/src/pkgs/migrations/get-schema/process-fields.ts.html +280 -0
  69. package/coverage/html/backend/src/pkgs/migrations/get-schema/process-tables.ts.html +289 -0
  70. package/coverage/html/backend/src/pkgs/migrations/index.html +176 -0
  71. package/coverage/html/backend/src/pkgs/migrations/migration-builders.ts.html +595 -0
  72. package/coverage/html/backend/src/pkgs/migrations/migration-execution.ts.html +301 -0
  73. package/coverage/html/backend/src/pkgs/migrations/schema-comparison.ts.html +694 -0
  74. package/coverage/html/backend/src/pkgs/migrations/type-mapping.ts.html +817 -0
  75. package/coverage/html/backend/src/pkgs/results/core/error-class.ts.html +976 -0
  76. package/coverage/html/backend/src/pkgs/results/core/error-codes.ts.html +703 -0
  77. package/coverage/html/backend/src/pkgs/results/core/index.html +146 -0
  78. package/coverage/html/backend/src/pkgs/results/core/tracing.ts.html +280 -0
  79. package/coverage/html/backend/src/pkgs/results/create-telemetry-options.ts.html +271 -0
  80. package/coverage/html/backend/src/pkgs/results/index.html +131 -0
  81. package/coverage/html/backend/src/pkgs/results/orpc-error-handler.ts.html +496 -0
  82. package/coverage/html/backend/src/pkgs/results/results/index.html +131 -0
  83. package/coverage/html/backend/src/pkgs/results/results/recovery-utils.ts.html +628 -0
  84. package/coverage/html/backend/src/pkgs/results/results/result-helpers.ts.html +1234 -0
  85. package/coverage/html/backend/src/pkgs/utils/env.ts.html +337 -0
  86. package/coverage/html/backend/src/pkgs/utils/index.html +146 -0
  87. package/coverage/html/backend/src/pkgs/utils/logger.ts.html +199 -0
  88. package/coverage/html/backend/src/pkgs/utils/url.ts.html +400 -0
  89. package/coverage/html/backend/src/router.ts.html +109 -0
  90. package/coverage/html/backend/src/schema/audit-log/index.html +146 -0
  91. package/coverage/html/backend/src/schema/audit-log/registry.ts.html +436 -0
  92. package/coverage/html/backend/src/schema/audit-log/schema.ts.html +223 -0
  93. package/coverage/html/backend/src/schema/audit-log/table.ts.html +640 -0
  94. package/coverage/html/backend/src/schema/consent/index.html +146 -0
  95. package/coverage/html/backend/src/schema/consent/registry.ts.html +616 -0
  96. package/coverage/html/backend/src/schema/consent/schema.ts.html +238 -0
  97. package/coverage/html/backend/src/schema/consent/table.ts.html +748 -0
  98. package/coverage/html/backend/src/schema/consent-policy/index.html +146 -0
  99. package/coverage/html/backend/src/schema/consent-policy/registry.ts.html +1063 -0
  100. package/coverage/html/backend/src/schema/consent-policy/schema.ts.html +265 -0
  101. package/coverage/html/backend/src/schema/consent-policy/table.ts.html +535 -0
  102. package/coverage/html/backend/src/schema/consent-purpose/index.html +146 -0
  103. package/coverage/html/backend/src/schema/consent-purpose/registry.ts.html +589 -0
  104. package/coverage/html/backend/src/schema/consent-purpose/schema.ts.html +259 -0
  105. package/coverage/html/backend/src/schema/consent-purpose/table.ts.html +547 -0
  106. package/coverage/html/backend/src/schema/consent-record/index.html +131 -0
  107. package/coverage/html/backend/src/schema/consent-record/schema.ts.html +211 -0
  108. package/coverage/html/backend/src/schema/consent-record/table.ts.html +457 -0
  109. package/coverage/html/backend/src/schema/create-registry.ts.html +148 -0
  110. package/coverage/html/backend/src/schema/definition.ts.html +685 -0
  111. package/coverage/html/backend/src/schema/domain/index.html +146 -0
  112. package/coverage/html/backend/src/schema/domain/registry.ts.html +973 -0
  113. package/coverage/html/backend/src/schema/domain/schema.ts.html +214 -0
  114. package/coverage/html/backend/src/schema/domain/table.ts.html +496 -0
  115. package/coverage/html/backend/src/schema/index.html +146 -0
  116. package/coverage/html/backend/src/schema/schemas.ts.html +166 -0
  117. package/coverage/html/backend/src/schema/subject/index.html +146 -0
  118. package/coverage/html/backend/src/schema/subject/registry.ts.html +973 -0
  119. package/coverage/html/backend/src/schema/subject/schema.ts.html +208 -0
  120. package/coverage/html/backend/src/schema/subject/table.ts.html +499 -0
  121. package/coverage/html/backend/src/server.ts.html +475 -0
  122. package/coverage/html/backend/src/testing/contract-testing.ts.html +1348 -0
  123. package/coverage/html/backend/src/testing/index.html +116 -0
  124. package/coverage/html/base.css +224 -0
  125. package/coverage/html/block-navigation.js +87 -0
  126. package/coverage/html/favicon.png +0 -0
  127. package/coverage/html/index.html +626 -0
  128. package/coverage/html/prettify.css +1 -0
  129. package/coverage/html/prettify.js +2 -0
  130. package/coverage/html/sort-arrow-sprite.png +0 -0
  131. package/coverage/html/sorter.js +196 -0
  132. package/dist/contracts/consent/index.d.ts +401 -0
  133. package/dist/contracts/consent/index.d.ts.map +1 -0
  134. package/dist/contracts/consent/index.test.d.ts +2 -0
  135. package/dist/contracts/consent/index.test.d.ts.map +1 -0
  136. package/dist/contracts/consent/post.contract.d.ts +212 -0
  137. package/dist/contracts/consent/post.contract.d.ts.map +1 -0
  138. package/dist/contracts/consent/post.contract.test.d.ts +2 -0
  139. package/dist/contracts/consent/post.contract.test.d.ts.map +1 -0
  140. package/dist/contracts/consent/show-banner.contract.d.ts +45 -0
  141. package/dist/contracts/consent/show-banner.contract.d.ts.map +1 -0
  142. package/dist/contracts/consent/show-banner.contract.test.d.ts +2 -0
  143. package/dist/contracts/consent/show-banner.contract.test.d.ts.map +1 -0
  144. package/dist/contracts/consent/verify.contract.d.ts +147 -0
  145. package/dist/contracts/consent/verify.contract.d.ts.map +1 -0
  146. package/dist/contracts/consent/verify.contract.test.d.ts +2 -0
  147. package/dist/contracts/consent/verify.contract.test.d.ts.map +1 -0
  148. package/dist/contracts/index.d.ts +963 -0
  149. package/dist/contracts/index.d.ts.map +1 -0
  150. package/dist/contracts/meta/index.d.ts +78 -0
  151. package/dist/contracts/meta/index.d.ts.map +1 -0
  152. package/dist/contracts/meta/index.test.d.ts +2 -0
  153. package/dist/contracts/meta/index.test.d.ts.map +1 -0
  154. package/dist/contracts/meta/status.contract.d.ts +77 -0
  155. package/dist/contracts/meta/status.contract.d.ts.map +1 -0
  156. package/dist/contracts/meta/status.contract.test.d.ts +2 -0
  157. package/dist/contracts/meta/status.contract.test.d.ts.map +1 -0
  158. package/dist/contracts/shared/jurisdiction.schema.d.ts +24 -0
  159. package/dist/contracts/shared/jurisdiction.schema.d.ts.map +1 -0
  160. package/dist/core.cjs +3584 -0
  161. package/dist/core.d.ts +533 -76
  162. package/dist/core.d.ts.map +1 -1
  163. package/dist/{index.js → core.js} +1163 -1286
  164. package/dist/handlers/consent/index.d.ts +401 -0
  165. package/dist/handlers/consent/index.d.ts.map +1 -0
  166. package/dist/handlers/consent/post.handler.d.ts +234 -0
  167. package/dist/handlers/consent/post.handler.d.ts.map +1 -0
  168. package/dist/handlers/consent/show-banner.handler.d.ts +57 -0
  169. package/dist/handlers/consent/show-banner.handler.d.ts.map +1 -0
  170. package/dist/handlers/consent/show-banner.handler.test.d.ts +2 -0
  171. package/dist/handlers/consent/show-banner.handler.test.d.ts.map +1 -0
  172. package/dist/handlers/consent/verify.handler.d.ts +169 -0
  173. package/dist/handlers/consent/verify.handler.d.ts.map +1 -0
  174. package/dist/handlers/meta/index.d.ts +78 -0
  175. package/dist/handlers/meta/index.d.ts.map +1 -0
  176. package/dist/handlers/meta/status.handler.d.ts +76 -0
  177. package/dist/handlers/meta/status.handler.d.ts.map +1 -0
  178. package/dist/init.d.ts.map +1 -1
  179. package/dist/pkgs/api-router/hooks/processor.d.ts.map +1 -1
  180. package/dist/pkgs/api-router/types/router-props.d.ts +1 -1
  181. package/dist/pkgs/api-router/types/router-props.d.ts.map +1 -1
  182. package/dist/pkgs/api-router/utils/cors.d.ts +1 -1
  183. package/dist/pkgs/api-router/utils/cors.d.ts.map +1 -1
  184. package/dist/pkgs/data-model/fields/field-types.d.ts +1 -1
  185. package/dist/pkgs/data-model/fields/zod-fields.d.ts +32 -32
  186. package/dist/pkgs/data-model/index.cjs +1433 -1799
  187. package/dist/pkgs/data-model/index.js +20 -385
  188. package/dist/pkgs/data-model/schema/index.cjs +1402 -1768
  189. package/dist/pkgs/data-model/schema/index.js +20 -385
  190. package/dist/pkgs/db-adapters/adapter-factory.d.ts +2 -2
  191. package/dist/pkgs/db-adapters/adapter-factory.d.ts.map +1 -1
  192. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.d.ts +4 -4
  193. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/index.cjs +19 -151
  194. package/dist/pkgs/db-adapters/adapters/drizzle-adapter/index.js +19 -151
  195. package/dist/pkgs/db-adapters/adapters/kysely-adapter/dialect.d.ts +1 -1
  196. package/dist/pkgs/db-adapters/adapters/kysely-adapter/index.cjs +17 -149
  197. package/dist/pkgs/db-adapters/adapters/kysely-adapter/index.js +17 -149
  198. package/dist/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.d.ts +2 -2
  199. package/dist/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.d.ts.map +1 -1
  200. package/dist/pkgs/db-adapters/adapters/memory-adapter/index.cjs +17 -149
  201. package/dist/pkgs/db-adapters/adapters/memory-adapter/index.js +17 -149
  202. package/dist/pkgs/db-adapters/adapters/prisma-adapter/index.cjs +19 -151
  203. package/dist/pkgs/db-adapters/adapters/prisma-adapter/index.js +19 -151
  204. package/dist/pkgs/db-adapters/index.cjs +31 -153
  205. package/dist/pkgs/db-adapters/index.js +31 -153
  206. package/dist/pkgs/migrations/get-schema/get-schema.d.ts +2 -2
  207. package/dist/pkgs/migrations/get-schema/index.d.ts +1 -1
  208. package/dist/pkgs/migrations/index.cjs +30 -153
  209. package/dist/pkgs/migrations/index.js +30 -153
  210. package/dist/pkgs/migrations/schema-comparison.d.ts.map +1 -1
  211. package/dist/pkgs/results/core/error-class.d.ts +23 -21
  212. package/dist/pkgs/results/core/error-class.d.ts.map +1 -1
  213. package/dist/pkgs/results/index.cjs +17 -150
  214. package/dist/pkgs/results/index.d.ts +0 -3
  215. package/dist/pkgs/results/index.d.ts.map +1 -1
  216. package/dist/pkgs/results/index.js +17 -138
  217. package/dist/pkgs/results/orpc-error-handler.d.ts +65 -0
  218. package/dist/pkgs/results/orpc-error-handler.d.ts.map +1 -0
  219. package/dist/pkgs/results/types.d.ts +7 -7
  220. package/dist/pkgs/results/types.d.ts.map +1 -1
  221. package/dist/pkgs/types/context.d.ts +15 -4
  222. package/dist/pkgs/types/context.d.ts.map +1 -1
  223. package/dist/pkgs/types/endpoints.d.ts +3 -4
  224. package/dist/pkgs/types/endpoints.d.ts.map +1 -1
  225. package/dist/pkgs/types/options.d.ts +2 -3
  226. package/dist/pkgs/types/options.d.ts.map +1 -1
  227. package/dist/pkgs/types/plugins.d.ts +2 -3
  228. package/dist/pkgs/types/plugins.d.ts.map +1 -1
  229. package/dist/pkgs/utils/index.d.ts +1 -0
  230. package/dist/pkgs/utils/index.d.ts.map +1 -1
  231. package/dist/pkgs/utils/logger.d.ts +16 -0
  232. package/dist/pkgs/utils/logger.d.ts.map +1 -0
  233. package/dist/router.cjs +1213 -0
  234. package/dist/router.d.ts +480 -0
  235. package/dist/router.d.ts.map +1 -0
  236. package/dist/router.js +1169 -0
  237. package/dist/schema/audit-log/table.d.ts +1 -1
  238. package/dist/schema/consent/table.d.ts +1 -1
  239. package/dist/schema/consent-policy/registry.d.ts +12 -12
  240. package/dist/schema/consent-policy/schema.d.ts +6 -6
  241. package/dist/schema/consent-policy/table.d.ts +7 -7
  242. package/dist/schema/consent-purpose/registry.d.ts +6 -6
  243. package/dist/schema/consent-purpose/schema.d.ts +6 -6
  244. package/dist/schema/consent-purpose/table.d.ts +7 -7
  245. package/dist/schema/consent-record/table.d.ts +1 -1
  246. package/dist/schema/create-registry.d.ts +32 -32
  247. package/dist/schema/definition.d.ts +19 -19
  248. package/dist/schema/domain/registry.d.ts +10 -10
  249. package/dist/schema/domain/schema.d.ts +5 -5
  250. package/dist/schema/domain/table.d.ts +6 -6
  251. package/dist/schema/index.cjs +1409 -1775
  252. package/dist/schema/index.js +20 -385
  253. package/dist/schema/schemas.d.ts +19 -19
  254. package/dist/schema/subject/registry.d.ts +4 -4
  255. package/dist/schema/subject/schema.d.ts +2 -2
  256. package/dist/schema/subject/table.d.ts +3 -3
  257. package/dist/server.d.ts +2 -0
  258. package/dist/server.d.ts.map +1 -0
  259. package/dist/testing/contract-testing.d.ts +37 -0
  260. package/dist/testing/contract-testing.d.ts.map +1 -0
  261. package/dist/types/context.d.ts +1 -1
  262. package/dist/types/index.d.ts +2 -2
  263. package/dist/types/options.d.ts +33 -2
  264. package/dist/types/options.d.ts.map +1 -1
  265. package/dist/types/plugins.d.ts +3 -4
  266. package/dist/types/plugins.d.ts.map +1 -1
  267. package/package.json +22 -30
  268. package/rslib.config.ts +2 -5
  269. package/src/contracts/consent/index.test.ts +5 -0
  270. package/src/contracts/consent/index.ts +9 -0
  271. package/src/contracts/consent/post.contract.test.ts +526 -0
  272. package/src/contracts/consent/post.contract.ts +160 -0
  273. package/src/contracts/consent/show-banner.contract.test.ts +214 -0
  274. package/src/contracts/consent/show-banner.contract.ts +45 -0
  275. package/src/contracts/consent/verify.contract.test.ts +185 -0
  276. package/src/contracts/consent/verify.contract.ts +126 -0
  277. package/src/contracts/index.ts +18 -0
  278. package/src/contracts/meta/index.test.ts +5 -0
  279. package/src/contracts/meta/index.ts +5 -0
  280. package/src/contracts/meta/status.contract.test.ts +338 -0
  281. package/src/contracts/meta/status.contract.ts +37 -0
  282. package/src/contracts/shared/jurisdiction.schema.ts +30 -0
  283. package/src/core.ts +451 -159
  284. package/src/handlers/consent/index.ts +9 -0
  285. package/src/handlers/consent/post.handler.ts +273 -0
  286. package/src/handlers/consent/show-banner.handler.test.ts +148 -0
  287. package/src/handlers/consent/show-banner.handler.ts +150 -0
  288. package/src/handlers/consent/verify.handler.ts +305 -0
  289. package/src/handlers/meta/index.ts +5 -0
  290. package/src/handlers/meta/status.handler.ts +47 -0
  291. package/src/init.ts +8 -5
  292. package/src/pkgs/api-router/hooks/__tests__/processor.test.ts +6 -0
  293. package/src/pkgs/api-router/hooks/processor.ts +2 -0
  294. package/src/pkgs/api-router/types/router-props.ts +1 -1
  295. package/src/pkgs/api-router/utils/cors.ts +1 -1
  296. package/src/pkgs/data-model/fields/field-types.ts +1 -1
  297. package/src/pkgs/data-model/fields/id-generator.ts +1 -1
  298. package/src/pkgs/db-adapters/README.md +3 -3
  299. package/src/pkgs/db-adapters/adapter-factory.ts +8 -4
  300. package/src/pkgs/db-adapters/adapters/drizzle-adapter/drizzle-adapter.ts +13 -13
  301. package/src/pkgs/db-adapters/adapters/kysely-adapter/dialect.ts +1 -1
  302. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/postgres.test.ts +1 -1
  303. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/sqlite.test.ts +1 -1
  304. package/src/pkgs/db-adapters/adapters/kysely-adapter/tests/test-utils.ts +2 -2
  305. package/src/pkgs/migrations/get-migration.ts +3 -3
  306. package/src/pkgs/migrations/get-schema/get-schema.ts +2 -2
  307. package/src/pkgs/migrations/get-schema/index.ts +1 -1
  308. package/src/pkgs/migrations/migration-builders.ts +2 -2
  309. package/src/pkgs/migrations/migration-execution.ts +2 -2
  310. package/src/pkgs/migrations/schema-comparison.ts +5 -4
  311. package/src/pkgs/results/__tests__/error-class.test.ts +8 -7
  312. package/src/pkgs/results/core/error-class.ts +31 -43
  313. package/src/pkgs/results/index.ts +0 -10
  314. package/src/pkgs/results/orpc-error-handler.ts +137 -0
  315. package/src/pkgs/results/types.ts +8 -7
  316. package/src/pkgs/types/context.ts +18 -4
  317. package/src/pkgs/types/endpoints.ts +3 -5
  318. package/src/pkgs/types/options.ts +2 -3
  319. package/src/pkgs/types/plugins.ts +2 -3
  320. package/src/pkgs/utils/index.ts +1 -0
  321. package/src/pkgs/utils/logger.ts +38 -0
  322. package/src/router.ts +8 -0
  323. package/src/schema/audit-log/table.ts +1 -1
  324. package/src/schema/consent/table.ts +1 -1
  325. package/src/schema/consent-policy/table.ts +1 -1
  326. package/src/schema/consent-purpose/table.ts +1 -1
  327. package/src/schema/consent-record/table.ts +1 -1
  328. package/src/schema/definition.ts +2 -2
  329. package/src/schema/domain/table.ts +1 -1
  330. package/src/schema/subject/table.ts +1 -1
  331. package/src/server.ts +130 -0
  332. package/src/testing/contract-testing.ts +437 -0
  333. package/src/types/context.ts +1 -1
  334. package/src/types/index.ts +2 -2
  335. package/src/types/options.ts +38 -2
  336. package/src/types/plugins.ts +3 -4
  337. package/dist/index.cjs +0 -3701
  338. package/dist/index.d.ts +0 -11
  339. package/dist/index.d.ts.map +0 -1
  340. package/dist/init.test.d.ts +0 -2
  341. package/dist/init.test.d.ts.map +0 -1
  342. package/dist/integrations/cloudflare.cjs +0 -312
  343. package/dist/integrations/cloudflare.d.ts +0 -32
  344. package/dist/integrations/cloudflare.d.ts.map +0 -1
  345. package/dist/integrations/cloudflare.js +0 -278
  346. package/dist/integrations/next.cjs +0 -276
  347. package/dist/integrations/next.d.ts +0 -68
  348. package/dist/integrations/next.d.ts.map +0 -1
  349. package/dist/integrations/next.js +0 -239
  350. package/dist/integrations/node.cjs +0 -257
  351. package/dist/integrations/node.d.ts +0 -29
  352. package/dist/integrations/node.d.ts.map +0 -1
  353. package/dist/integrations/node.js +0 -223
  354. package/dist/pkgs/api-router/index.d.ts +0 -9
  355. package/dist/pkgs/api-router/index.d.ts.map +0 -1
  356. package/dist/pkgs/api-router/utils/define-route.d.ts +0 -87
  357. package/dist/pkgs/api-router/utils/define-route.d.ts.map +0 -1
  358. package/dist/pkgs/logger/__tests__/console-formatter.test.d.ts +0 -2
  359. package/dist/pkgs/logger/__tests__/console-formatter.test.d.ts.map +0 -1
  360. package/dist/pkgs/logger/__tests__/integration.test.d.ts +0 -2
  361. package/dist/pkgs/logger/__tests__/integration.test.d.ts.map +0 -1
  362. package/dist/pkgs/logger/__tests__/log-levels.test.d.ts +0 -2
  363. package/dist/pkgs/logger/__tests__/log-levels.test.d.ts.map +0 -1
  364. package/dist/pkgs/logger/__tests__/logger-factory.test.d.ts +0 -2
  365. package/dist/pkgs/logger/__tests__/logger-factory.test.d.ts.map +0 -1
  366. package/dist/pkgs/logger/__tests__/result-logging.test.d.ts +0 -2
  367. package/dist/pkgs/logger/__tests__/result-logging.test.d.ts.map +0 -1
  368. package/dist/pkgs/logger/__tests__/types.test.d.ts +0 -2
  369. package/dist/pkgs/logger/__tests__/types.test.d.ts.map +0 -1
  370. package/dist/pkgs/logger/console-formatter.d.ts +0 -56
  371. package/dist/pkgs/logger/console-formatter.d.ts.map +0 -1
  372. package/dist/pkgs/logger/index.cjs +0 -240
  373. package/dist/pkgs/logger/index.d.ts +0 -35
  374. package/dist/pkgs/logger/index.d.ts.map +0 -1
  375. package/dist/pkgs/logger/index.js +0 -185
  376. package/dist/pkgs/logger/log-levels.d.ts +0 -29
  377. package/dist/pkgs/logger/log-levels.d.ts.map +0 -1
  378. package/dist/pkgs/logger/logger-factory.d.ts +0 -42
  379. package/dist/pkgs/logger/logger-factory.d.ts.map +0 -1
  380. package/dist/pkgs/logger/result-logging.d.ts +0 -71
  381. package/dist/pkgs/logger/result-logging.d.ts.map +0 -1
  382. package/dist/pkgs/logger/telemetry.d.ts +0 -14
  383. package/dist/pkgs/logger/telemetry.d.ts.map +0 -1
  384. package/dist/pkgs/logger/types.d.ts +0 -121
  385. package/dist/pkgs/logger/types.d.ts.map +0 -1
  386. package/dist/pkgs/results/__tests__/retrieval-pipeline.test.d.ts +0 -2
  387. package/dist/pkgs/results/__tests__/retrieval-pipeline.test.d.ts.map +0 -1
  388. package/dist/pkgs/results/__tests__/validation-pipeline.test.d.ts +0 -2
  389. package/dist/pkgs/results/__tests__/validation-pipeline.test.d.ts.map +0 -1
  390. package/dist/pkgs/results/h3-integration.d.ts +0 -52
  391. package/dist/pkgs/results/h3-integration.d.ts.map +0 -1
  392. package/dist/pkgs/results/pipeline/retrieval-pipeline.d.ts +0 -101
  393. package/dist/pkgs/results/pipeline/retrieval-pipeline.d.ts.map +0 -1
  394. package/dist/pkgs/results/pipeline/validation-pipeline.d.ts +0 -89
  395. package/dist/pkgs/results/pipeline/validation-pipeline.d.ts.map +0 -1
  396. package/dist/response-types.d.ts +0 -19
  397. package/dist/response-types.d.ts.map +0 -1
  398. package/dist/routes/__test__/index.test.d.ts +0 -17
  399. package/dist/routes/__test__/index.test.d.ts.map +0 -1
  400. package/dist/routes/__test__/set-consent.test.d.ts +0 -2
  401. package/dist/routes/__test__/set-consent.test.d.ts.map +0 -1
  402. package/dist/routes/__test__/show-consent-banner.test.d.ts +0 -2
  403. package/dist/routes/__test__/show-consent-banner.test.d.ts.map +0 -1
  404. package/dist/routes/__test__/status.test.d.ts +0 -2
  405. package/dist/routes/__test__/status.test.d.ts.map +0 -1
  406. package/dist/routes/__test__/verify-consent.test.d.ts +0 -2
  407. package/dist/routes/__test__/verify-consent.test.d.ts.map +0 -1
  408. package/dist/routes/index.d.ts +0 -3
  409. package/dist/routes/index.d.ts.map +0 -1
  410. package/dist/routes/set-consent.d.ts +0 -89
  411. package/dist/routes/set-consent.d.ts.map +0 -1
  412. package/dist/routes/show-consent-banner.d.ts +0 -15
  413. package/dist/routes/show-consent-banner.d.ts.map +0 -1
  414. package/dist/routes/status.d.ts +0 -44
  415. package/dist/routes/status.d.ts.map +0 -1
  416. package/dist/routes/types.d.ts +0 -7
  417. package/dist/routes/types.d.ts.map +0 -1
  418. package/dist/routes/verify-consent.d.ts +0 -38
  419. package/dist/routes/verify-consent.d.ts.map +0 -1
  420. package/src/docs/ADVANCED_JSON_HANDLING.md +0 -99
  421. package/src/docs/neverthrow.md +0 -171
  422. package/src/index.ts +0 -34
  423. package/src/init.test.ts +0 -219
  424. package/src/integrations/cloudflare.ts +0 -269
  425. package/src/integrations/next.ts +0 -204
  426. package/src/integrations/node.ts +0 -141
  427. package/src/pkgs/api-router/index.ts +0 -148
  428. package/src/pkgs/api-router/types/h3.d.ts +0 -42
  429. package/src/pkgs/api-router/utils/define-route.ts +0 -410
  430. package/src/pkgs/logger/README.md +0 -213
  431. package/src/pkgs/logger/__tests__/console-formatter.test.ts +0 -67
  432. package/src/pkgs/logger/__tests__/integration.test.ts +0 -184
  433. package/src/pkgs/logger/__tests__/log-levels.test.ts +0 -77
  434. package/src/pkgs/logger/__tests__/logger-factory.test.ts +0 -156
  435. package/src/pkgs/logger/__tests__/result-logging.test.ts +0 -209
  436. package/src/pkgs/logger/__tests__/types.test.ts +0 -94
  437. package/src/pkgs/logger/console-formatter.ts +0 -75
  438. package/src/pkgs/logger/doc.md +0 -569
  439. package/src/pkgs/logger/index.ts +0 -59
  440. package/src/pkgs/logger/log-levels.ts +0 -46
  441. package/src/pkgs/logger/logger-factory.ts +0 -121
  442. package/src/pkgs/logger/result-logging.ts +0 -134
  443. package/src/pkgs/logger/telemetry.ts +0 -96
  444. package/src/pkgs/logger/types.ts +0 -138
  445. package/src/pkgs/results/__tests__/retrieval-pipeline.test.ts +0 -157
  446. package/src/pkgs/results/__tests__/validation-pipeline.test.ts +0 -151
  447. package/src/pkgs/results/h3-integration.ts +0 -142
  448. package/src/pkgs/results/pipeline/retrieval-pipeline.ts +0 -188
  449. package/src/pkgs/results/pipeline/validation-pipeline.ts +0 -164
  450. package/src/plugins/.keep +0 -0
  451. package/src/response-types.ts +0 -29
  452. package/src/routes/__test__/index.test.ts +0 -112
  453. package/src/routes/__test__/set-consent.test.ts +0 -242
  454. package/src/routes/__test__/show-consent-banner.test.ts +0 -98
  455. package/src/routes/__test__/status.test.ts +0 -64
  456. package/src/routes/__test__/verify-consent.test.ts +0 -266
  457. package/src/routes/index.ts +0 -12
  458. package/src/routes/set-consent.ts +0 -249
  459. package/src/routes/show-consent-banner.ts +0 -131
  460. package/src/routes/status.ts +0 -61
  461. package/src/routes/types.ts +0 -7
  462. package/src/routes/verify-consent.ts +0 -206
@@ -1,236 +1,5 @@
1
1
  "use strict";
2
- var __webpack_modules__ = {
3
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js": function(__unused_webpack_module, exports1, __webpack_require__) {
4
- exports1.ZodError = void 0;
5
- const util_1 = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js");
6
- util_1.util.arrayToEnum([
7
- "invalid_type",
8
- "invalid_literal",
9
- "custom",
10
- "invalid_union",
11
- "invalid_union_discriminator",
12
- "invalid_enum_value",
13
- "unrecognized_keys",
14
- "invalid_arguments",
15
- "invalid_return_type",
16
- "invalid_date",
17
- "invalid_string",
18
- "too_small",
19
- "too_big",
20
- "invalid_intersection_types",
21
- "not_multiple_of",
22
- "not_finite"
23
- ]);
24
- class ZodError extends Error {
25
- get errors() {
26
- return this.issues;
27
- }
28
- constructor(issues){
29
- super();
30
- this.issues = [];
31
- this.addIssue = (sub)=>{
32
- this.issues = [
33
- ...this.issues,
34
- sub
35
- ];
36
- };
37
- this.addIssues = (subs = [])=>{
38
- this.issues = [
39
- ...this.issues,
40
- ...subs
41
- ];
42
- };
43
- const actualProto = new.target.prototype;
44
- if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
45
- else this.__proto__ = actualProto;
46
- this.name = "ZodError";
47
- this.issues = issues;
48
- }
49
- format(_mapper) {
50
- const mapper = _mapper || function(issue) {
51
- return issue.message;
52
- };
53
- const fieldErrors = {
54
- _errors: []
55
- };
56
- const processError = (error)=>{
57
- for (const issue of error.issues)if ("invalid_union" === issue.code) issue.unionErrors.map(processError);
58
- else if ("invalid_return_type" === issue.code) processError(issue.returnTypeError);
59
- else if ("invalid_arguments" === issue.code) processError(issue.argumentsError);
60
- else if (0 === issue.path.length) fieldErrors._errors.push(mapper(issue));
61
- else {
62
- let curr = fieldErrors;
63
- let i = 0;
64
- while(i < issue.path.length){
65
- const el = issue.path[i];
66
- const terminal = i === issue.path.length - 1;
67
- if (terminal) {
68
- curr[el] = curr[el] || {
69
- _errors: []
70
- };
71
- curr[el]._errors.push(mapper(issue));
72
- } else curr[el] = curr[el] || {
73
- _errors: []
74
- };
75
- curr = curr[el];
76
- i++;
77
- }
78
- }
79
- };
80
- processError(this);
81
- return fieldErrors;
82
- }
83
- static assert(value) {
84
- if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
85
- }
86
- toString() {
87
- return this.message;
88
- }
89
- get message() {
90
- return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2);
91
- }
92
- get isEmpty() {
93
- return 0 === this.issues.length;
94
- }
95
- flatten(mapper = (issue)=>issue.message) {
96
- const fieldErrors = {};
97
- const formErrors = [];
98
- for (const sub of this.issues)if (sub.path.length > 0) {
99
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
100
- fieldErrors[sub.path[0]].push(mapper(sub));
101
- } else formErrors.push(mapper(sub));
102
- return {
103
- formErrors,
104
- fieldErrors
105
- };
106
- }
107
- get formErrors() {
108
- return this.flatten();
109
- }
110
- }
111
- exports1.ZodError = ZodError;
112
- ZodError.create = (issues)=>{
113
- const error = new ZodError(issues);
114
- return error;
115
- };
116
- },
117
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js": function(__unused_webpack_module, exports1) {
118
- Object.defineProperty(exports1, "__esModule", {
119
- value: true
120
- });
121
- exports1.getParsedType = exports1.ZodParsedType = exports1.objectUtil = exports1.util = void 0;
122
- var util;
123
- (function(util) {
124
- util.assertEqual = (val)=>val;
125
- function assertIs(_arg) {}
126
- util.assertIs = assertIs;
127
- function assertNever(_x) {
128
- throw new Error();
129
- }
130
- util.assertNever = assertNever;
131
- util.arrayToEnum = (items)=>{
132
- const obj = {};
133
- for (const item of items)obj[item] = item;
134
- return obj;
135
- };
136
- util.getValidEnumValues = (obj)=>{
137
- const validKeys = util.objectKeys(obj).filter((k)=>"number" != typeof obj[obj[k]]);
138
- const filtered = {};
139
- for (const k of validKeys)filtered[k] = obj[k];
140
- return util.objectValues(filtered);
141
- };
142
- util.objectValues = (obj)=>util.objectKeys(obj).map(function(e) {
143
- return obj[e];
144
- });
145
- util.objectKeys = "function" == typeof Object.keys ? (obj)=>Object.keys(obj) : (object)=>{
146
- const keys = [];
147
- for(const key in object)if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
148
- return keys;
149
- };
150
- util.find = (arr, checker)=>{
151
- for (const item of arr)if (checker(item)) return item;
152
- };
153
- util.isInteger = "function" == typeof Number.isInteger ? (val)=>Number.isInteger(val) : (val)=>"number" == typeof val && isFinite(val) && Math.floor(val) === val;
154
- function joinValues(array, separator = " | ") {
155
- return array.map((val)=>"string" == typeof val ? `'${val}'` : val).join(separator);
156
- }
157
- util.joinValues = joinValues;
158
- util.jsonStringifyReplacer = (_, value)=>{
159
- if ("bigint" == typeof value) return value.toString();
160
- return value;
161
- };
162
- })(util || (exports1.util = util = {}));
163
- var objectUtil;
164
- (function(objectUtil) {
165
- objectUtil.mergeShapes = (first, second)=>({
166
- ...first,
167
- ...second
168
- });
169
- })(objectUtil || (exports1.objectUtil = objectUtil = {}));
170
- exports1.ZodParsedType = util.arrayToEnum([
171
- "string",
172
- "nan",
173
- "number",
174
- "integer",
175
- "float",
176
- "boolean",
177
- "date",
178
- "bigint",
179
- "symbol",
180
- "function",
181
- "undefined",
182
- "null",
183
- "array",
184
- "object",
185
- "unknown",
186
- "promise",
187
- "void",
188
- "never",
189
- "map",
190
- "set"
191
- ]);
192
- const getParsedType = (data)=>{
193
- const t = typeof data;
194
- switch(t){
195
- case "undefined":
196
- return exports1.ZodParsedType.undefined;
197
- case "string":
198
- return exports1.ZodParsedType.string;
199
- case "number":
200
- return isNaN(data) ? exports1.ZodParsedType.nan : exports1.ZodParsedType.number;
201
- case "boolean":
202
- return exports1.ZodParsedType.boolean;
203
- case "function":
204
- return exports1.ZodParsedType.function;
205
- case "bigint":
206
- return exports1.ZodParsedType.bigint;
207
- case "symbol":
208
- return exports1.ZodParsedType.symbol;
209
- case "object":
210
- if (Array.isArray(data)) return exports1.ZodParsedType.array;
211
- if (null === data) return exports1.ZodParsedType.null;
212
- if (data.then && "function" == typeof data.then && data.catch && "function" == typeof data.catch) return exports1.ZodParsedType.promise;
213
- if ("undefined" != typeof Map && data instanceof Map) return exports1.ZodParsedType.map;
214
- if ("undefined" != typeof Set && data instanceof Set) return exports1.ZodParsedType.set;
215
- if ("undefined" != typeof Date && data instanceof Date) return exports1.ZodParsedType.date;
216
- return exports1.ZodParsedType.object;
217
- default:
218
- return exports1.ZodParsedType.unknown;
219
- }
220
- };
221
- exports1.getParsedType = getParsedType;
222
- }
223
- };
224
- var __webpack_module_cache__ = {};
225
- function __webpack_require__(moduleId) {
226
- var cachedModule = __webpack_module_cache__[moduleId];
227
- if (void 0 !== cachedModule) return cachedModule.exports;
228
- var module = __webpack_module_cache__[moduleId] = {
229
- exports: {}
230
- };
231
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
232
- return module.exports;
233
- }
2
+ var __webpack_require__ = {};
234
3
  (()=>{
235
4
  __webpack_require__.n = (module)=>{
236
5
  var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
@@ -262,1614 +31,1479 @@ function __webpack_require__(moduleId) {
262
31
  };
263
32
  })();
264
33
  var __webpack_exports__ = {};
265
- (()=>{
266
- __webpack_require__.r(__webpack_exports__);
267
- __webpack_require__.d(__webpack_exports__, {
268
- getConsentPolicyTable: ()=>getConsentPolicyTable,
269
- getDomainTable: ()=>getDomainTable,
270
- getConsentTable: ()=>getConsentTable,
271
- getAuditLogTable: ()=>getAuditLogTable,
272
- purposeSchema: ()=>purposeSchema,
273
- consentRegistry: ()=>consentRegistry,
274
- domainSchema: ()=>domainSchema,
275
- getSubjectTable: ()=>getSubjectTable,
276
- policyRegistry: ()=>policyRegistry,
277
- getPurposeTable: ()=>getPurposeTable,
278
- schemas: ()=>schemas,
279
- auditLogRegistry: ()=>auditLogRegistry,
280
- getConsentTables: ()=>getConsentTables,
281
- consentRecordSchema: ()=>consentRecordSchema,
282
- subjectRegistry: ()=>subjectRegistry,
283
- subjectSchema: ()=>subjectSchema,
284
- getConsentRecordTable: ()=>getConsentRecordTable,
285
- consentPolicySchema: ()=>consentPolicySchema,
286
- consentSchema: ()=>consentSchema,
287
- auditLogSchema: ()=>auditLogSchema,
288
- PolicyTypeSchema: ()=>PolicyTypeSchema,
289
- consentPurposeRegistry: ()=>consentPurposeRegistry,
290
- domainRegistry: ()=>domainRegistry
291
- });
292
- const COMMON_TIMEZONES = {
293
- UTC: 'UTC',
294
- GMT: 'GMT',
295
- EASTERN: 'America/New_York',
296
- CENTRAL: 'America/Chicago',
297
- MOUNTAIN: 'America/Denver',
298
- PACIFIC: 'America/Los_Angeles',
299
- LONDON: 'Europe/London',
300
- PARIS: 'Europe/Paris',
301
- BERLIN: 'Europe/Berlin',
302
- TOKYO: 'Asia/Tokyo',
303
- SHANGHAI: 'Asia/Shanghai',
304
- SINGAPORE: 'Asia/Singapore',
305
- SYDNEY: 'Australia/Sydney',
306
- SAO_PAULO: 'America/Sao_Paulo'
307
- };
308
- const external_base_x_namespaceObject = require("base-x");
309
- var external_base_x_default = /*#__PURE__*/ __webpack_require__.n(external_base_x_namespaceObject);
310
- external_base_x_default()('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
311
- const external_zod_namespaceObject = require("zod");
312
- const fieldConfigSchema = external_zod_namespaceObject.z.object({
313
- required: external_zod_namespaceObject.z.boolean().default(true),
314
- returned: external_zod_namespaceObject.z.boolean().default(true),
315
- input: external_zod_namespaceObject.z.boolean().default(true),
316
- defaultValue: external_zod_namespaceObject.z.union([
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ getConsentPolicyTable: ()=>getConsentPolicyTable,
37
+ getDomainTable: ()=>getDomainTable,
38
+ getConsentTable: ()=>getConsentTable,
39
+ getAuditLogTable: ()=>getAuditLogTable,
40
+ purposeSchema: ()=>purposeSchema,
41
+ consentRegistry: ()=>consentRegistry,
42
+ domainSchema: ()=>domainSchema,
43
+ getSubjectTable: ()=>getSubjectTable,
44
+ policyRegistry: ()=>policyRegistry,
45
+ getPurposeTable: ()=>getPurposeTable,
46
+ schemas: ()=>schemas,
47
+ auditLogRegistry: ()=>auditLogRegistry,
48
+ getConsentTables: ()=>getConsentTables,
49
+ consentRecordSchema: ()=>consentRecordSchema,
50
+ subjectRegistry: ()=>subjectRegistry,
51
+ subjectSchema: ()=>subjectSchema,
52
+ getConsentRecordTable: ()=>getConsentRecordTable,
53
+ consentPolicySchema: ()=>consentPolicySchema,
54
+ consentSchema: ()=>consentSchema,
55
+ auditLogSchema: ()=>auditLogSchema,
56
+ PolicyTypeSchema: ()=>PolicyTypeSchema,
57
+ consentPurposeRegistry: ()=>consentPurposeRegistry,
58
+ domainRegistry: ()=>domainRegistry
59
+ });
60
+ const COMMON_TIMEZONES = {
61
+ UTC: 'UTC',
62
+ GMT: 'GMT',
63
+ EASTERN: 'America/New_York',
64
+ CENTRAL: 'America/Chicago',
65
+ MOUNTAIN: 'America/Denver',
66
+ PACIFIC: 'America/Los_Angeles',
67
+ LONDON: 'Europe/London',
68
+ PARIS: 'Europe/Paris',
69
+ BERLIN: 'Europe/Berlin',
70
+ TOKYO: 'Asia/Tokyo',
71
+ SHANGHAI: 'Asia/Shanghai',
72
+ SINGAPORE: 'Asia/Singapore',
73
+ SYDNEY: 'Australia/Sydney',
74
+ SAO_PAULO: 'America/Sao_Paulo'
75
+ };
76
+ const external_base_x_namespaceObject = require("base-x");
77
+ var external_base_x_default = /*#__PURE__*/ __webpack_require__.n(external_base_x_namespaceObject);
78
+ external_base_x_default()('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
79
+ const external_zod_namespaceObject = require("zod");
80
+ const fieldConfigSchema = external_zod_namespaceObject.z.object({
81
+ required: external_zod_namespaceObject.z.boolean().default(true),
82
+ returned: external_zod_namespaceObject.z.boolean().default(true),
83
+ input: external_zod_namespaceObject.z.boolean().default(true),
84
+ defaultValue: external_zod_namespaceObject.z.union([
85
+ external_zod_namespaceObject.z.any(),
86
+ external_zod_namespaceObject.z["function"]().returns(external_zod_namespaceObject.z.any())
87
+ ]).optional(),
88
+ transform: external_zod_namespaceObject.z.object({
89
+ input: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
317
90
  external_zod_namespaceObject.z.any(),
318
- external_zod_namespaceObject.z["function"]().returns(external_zod_namespaceObject.z.any())
319
- ]).optional(),
320
- transform: external_zod_namespaceObject.z.object({
321
- input: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
322
- external_zod_namespaceObject.z.any(),
323
- external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
324
- ])).optional(),
325
- output: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
326
- external_zod_namespaceObject.z.any(),
327
- external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
328
- ])).optional()
329
- }).optional(),
330
- validator: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
331
- external_zod_namespaceObject.z.string(),
332
- external_zod_namespaceObject.z["null"]()
91
+ external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
333
92
  ])).optional(),
334
- unique: external_zod_namespaceObject.z.boolean().optional(),
335
- indexed: external_zod_namespaceObject.z.boolean().optional(),
336
- sortable: external_zod_namespaceObject.z.boolean().default(true),
337
- fieldName: external_zod_namespaceObject.z.string().optional(),
338
- bigint: external_zod_namespaceObject.z.boolean().default(false)
339
- });
340
- const stringFieldSchema = fieldConfigSchema.extend({
341
- type: external_zod_namespaceObject.z.literal('string'),
342
- minLength: external_zod_namespaceObject.z.number().optional(),
343
- maxLength: external_zod_namespaceObject.z.number().optional(),
344
- pattern: external_zod_namespaceObject.z.string().optional()
345
- });
346
- const numberFieldSchema = fieldConfigSchema.extend({
347
- type: external_zod_namespaceObject.z.literal('number'),
348
- min: external_zod_namespaceObject.z.number().optional(),
349
- max: external_zod_namespaceObject.z.number().optional()
350
- });
351
- const booleanFieldSchema = fieldConfigSchema.extend({
352
- type: external_zod_namespaceObject.z.literal('boolean')
353
- });
354
- const dateFieldSchema = fieldConfigSchema.extend({
355
- type: external_zod_namespaceObject.z.literal('date'),
356
- minDate: external_zod_namespaceObject.z.date().optional(),
357
- maxDate: external_zod_namespaceObject.z.date().optional(),
358
- dateOnly: external_zod_namespaceObject.z.boolean().default(false),
359
- format: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional()
360
- });
361
- const timezoneFieldSchema = fieldConfigSchema.extend({
362
- type: external_zod_namespaceObject.z.literal('timezone'),
363
- validateTimezone: external_zod_namespaceObject.z.boolean().default(true),
364
- suggestedValues: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional(),
365
- restrictToSuggestedValues: external_zod_namespaceObject.z.boolean().default(false)
366
- });
367
- const jsonFieldSchema = fieldConfigSchema.extend({
368
- type: external_zod_namespaceObject.z.literal('json'),
369
- validateJson: external_zod_namespaceObject.z.boolean().default(true)
370
- });
371
- const stringArrayFieldSchema = fieldConfigSchema.extend({
372
- type: external_zod_namespaceObject.z.literal('string[]')
373
- });
374
- const numberArrayFieldSchema = fieldConfigSchema.extend({
375
- type: external_zod_namespaceObject.z.literal('number[]')
376
- });
377
- external_zod_namespaceObject.z.discriminatedUnion('type', [
378
- stringFieldSchema,
379
- numberFieldSchema,
380
- booleanFieldSchema,
381
- dateFieldSchema,
382
- timezoneFieldSchema,
383
- jsonFieldSchema,
384
- stringArrayFieldSchema,
385
- numberArrayFieldSchema
386
- ]);
387
- require("neverthrow");
388
- const external_h3_namespaceObject = require("h3");
389
- const error_codes_ERROR_CODES = Object.freeze({
390
- NOT_FOUND: 'Resource not found',
391
- BAD_REQUEST: 'Bad request',
392
- CONFLICT: 'Conflict with current state',
393
- MISSING_REQUIRED_PARAMETER: 'Missing required parameter',
394
- UNAUTHORIZED: 'Unauthorized',
395
- FORBIDDEN: 'Forbidden',
396
- INTERNAL_SERVER_ERROR: 'Internal server error',
397
- INITIALIZATION_FAILED: 'Initialization failed',
398
- DATABASE_CONNECTION_ERROR: 'Database connection error',
399
- DATABASE_QUERY_ERROR: 'Database query error',
400
- INVALID_CONFIGURATION: 'Invalid configuration',
401
- REQUEST_HANDLER_ERROR: 'Request handler error',
402
- INVALID_REQUEST: 'Invalid request',
403
- UNKNOWN_ERROR: 'Unknown error',
404
- NETWORK_ERROR: 'Network error',
405
- PLUGIN_INITIALIZATION_FAILED: 'Plugin initialization failed',
406
- API_RETRIEVAL_ERROR: 'API retrieval error',
407
- VALIDATION_ERROR: 'Validation error',
408
- UNEXPECTED: 'Unexpected error'
409
- });
410
- const ERROR_CATEGORIES = Object.freeze({
411
- VALIDATION: 'validation',
412
- AUTHORIZATION: 'authorization',
413
- STORAGE: 'storage',
414
- NETWORK: 'network',
415
- PLUGIN: 'plugin',
416
- CONFIGURATION: 'configuration',
417
- UNEXPECTED: 'unexpected'
418
- });
419
- const api_namespaceObject = require("@opentelemetry/api");
420
- const tracing_tracer = api_namespaceObject.trace.getTracer('@doubletie/results');
421
- async function tracing_withSpan(name, fn, attributes = {}) {
422
- return await tracing_tracer.startActiveSpan(name, async (span)=>{
423
- try {
424
- span.setAttributes(attributes);
425
- const result = await fn(span);
426
- span.setStatus({
427
- code: api_namespaceObject.SpanStatusCode.OK
428
- });
429
- span.end();
430
- return result;
431
- } catch (error) {
432
- if (error instanceof error_class_DoubleTieError) {
433
- span.setAttributes({
434
- 'error.type': 'DoubleTieError',
435
- 'error.code': error.code,
436
- 'error.statusCode': error.statusCode,
437
- 'error.message': error.message
438
- });
439
- if (error.meta) span.setAttributes({
440
- 'error.meta': JSON.stringify(error.meta)
441
- });
442
- } else span.setAttributes({
443
- 'error.type': error instanceof Error ? error.constructor.name : 'Unknown',
444
- 'error.message': error instanceof Error ? error.message : String(error)
445
- });
446
- span.setStatus({
447
- code: api_namespaceObject.SpanStatusCode.ERROR,
448
- message: error instanceof Error ? error.message : String(error)
449
- });
450
- span.end();
451
- throw error;
452
- }
453
- });
454
- }
455
- class error_class_DoubleTieError extends external_h3_namespaceObject.H3Error {
456
- code;
457
- category;
458
- meta;
459
- constructor(message, options = {
460
- code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
461
- status: 500,
462
- category: ERROR_CATEGORIES.UNEXPECTED,
463
- cause: void 0,
464
- meta: {}
465
- }){
466
- super(message, {
467
- cause: options.cause
93
+ output: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
94
+ external_zod_namespaceObject.z.any(),
95
+ external_zod_namespaceObject.z.promise(external_zod_namespaceObject.z.any())
96
+ ])).optional()
97
+ }).optional(),
98
+ validator: external_zod_namespaceObject.z["function"]().args(external_zod_namespaceObject.z.any()).returns(external_zod_namespaceObject.z.union([
99
+ external_zod_namespaceObject.z.string(),
100
+ external_zod_namespaceObject.z["null"]()
101
+ ])).optional(),
102
+ unique: external_zod_namespaceObject.z.boolean().optional(),
103
+ indexed: external_zod_namespaceObject.z.boolean().optional(),
104
+ sortable: external_zod_namespaceObject.z.boolean().default(true),
105
+ fieldName: external_zod_namespaceObject.z.string().optional(),
106
+ bigint: external_zod_namespaceObject.z.boolean().default(false)
107
+ });
108
+ const stringFieldSchema = fieldConfigSchema.extend({
109
+ type: external_zod_namespaceObject.z.literal('string'),
110
+ minLength: external_zod_namespaceObject.z.number().optional(),
111
+ maxLength: external_zod_namespaceObject.z.number().optional(),
112
+ pattern: external_zod_namespaceObject.z.string().optional()
113
+ });
114
+ const numberFieldSchema = fieldConfigSchema.extend({
115
+ type: external_zod_namespaceObject.z.literal('number'),
116
+ min: external_zod_namespaceObject.z.number().optional(),
117
+ max: external_zod_namespaceObject.z.number().optional()
118
+ });
119
+ const booleanFieldSchema = fieldConfigSchema.extend({
120
+ type: external_zod_namespaceObject.z.literal('boolean')
121
+ });
122
+ const dateFieldSchema = fieldConfigSchema.extend({
123
+ type: external_zod_namespaceObject.z.literal('date'),
124
+ minDate: external_zod_namespaceObject.z.date().optional(),
125
+ maxDate: external_zod_namespaceObject.z.date().optional(),
126
+ dateOnly: external_zod_namespaceObject.z.boolean().default(false),
127
+ format: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional()
128
+ });
129
+ const timezoneFieldSchema = fieldConfigSchema.extend({
130
+ type: external_zod_namespaceObject.z.literal('timezone'),
131
+ validateTimezone: external_zod_namespaceObject.z.boolean().default(true),
132
+ suggestedValues: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional(),
133
+ restrictToSuggestedValues: external_zod_namespaceObject.z.boolean().default(false)
134
+ });
135
+ const jsonFieldSchema = fieldConfigSchema.extend({
136
+ type: external_zod_namespaceObject.z.literal('json'),
137
+ validateJson: external_zod_namespaceObject.z.boolean().default(true)
138
+ });
139
+ const stringArrayFieldSchema = fieldConfigSchema.extend({
140
+ type: external_zod_namespaceObject.z.literal('string[]')
141
+ });
142
+ const numberArrayFieldSchema = fieldConfigSchema.extend({
143
+ type: external_zod_namespaceObject.z.literal('number[]')
144
+ });
145
+ external_zod_namespaceObject.z.discriminatedUnion('type', [
146
+ stringFieldSchema,
147
+ numberFieldSchema,
148
+ booleanFieldSchema,
149
+ dateFieldSchema,
150
+ timezoneFieldSchema,
151
+ jsonFieldSchema,
152
+ stringArrayFieldSchema,
153
+ numberArrayFieldSchema
154
+ ]);
155
+ require("neverthrow");
156
+ const server_namespaceObject = require("@orpc/server");
157
+ const error_codes_ERROR_CODES = Object.freeze({
158
+ NOT_FOUND: 'Resource not found',
159
+ BAD_REQUEST: 'Bad request',
160
+ CONFLICT: 'Conflict with current state',
161
+ MISSING_REQUIRED_PARAMETER: 'Missing required parameter',
162
+ UNAUTHORIZED: 'Unauthorized',
163
+ FORBIDDEN: 'Forbidden',
164
+ INTERNAL_SERVER_ERROR: 'Internal server error',
165
+ INITIALIZATION_FAILED: 'Initialization failed',
166
+ DATABASE_CONNECTION_ERROR: 'Database connection error',
167
+ DATABASE_QUERY_ERROR: 'Database query error',
168
+ INVALID_CONFIGURATION: 'Invalid configuration',
169
+ REQUEST_HANDLER_ERROR: 'Request handler error',
170
+ INVALID_REQUEST: 'Invalid request',
171
+ UNKNOWN_ERROR: 'Unknown error',
172
+ NETWORK_ERROR: 'Network error',
173
+ PLUGIN_INITIALIZATION_FAILED: 'Plugin initialization failed',
174
+ API_RETRIEVAL_ERROR: 'API retrieval error',
175
+ VALIDATION_ERROR: 'Validation error',
176
+ UNEXPECTED: 'Unexpected error'
177
+ });
178
+ const ERROR_CATEGORIES = Object.freeze({
179
+ VALIDATION: 'validation',
180
+ AUTHORIZATION: 'authorization',
181
+ STORAGE: 'storage',
182
+ NETWORK: 'network',
183
+ PLUGIN: 'plugin',
184
+ CONFIGURATION: 'configuration',
185
+ UNEXPECTED: 'unexpected'
186
+ });
187
+ const api_namespaceObject = require("@opentelemetry/api");
188
+ const tracer = api_namespaceObject.trace.getTracer('@doubletie/results');
189
+ async function tracing_withSpan(name, fn, attributes = {}) {
190
+ return await tracer.startActiveSpan(name, async (span)=>{
191
+ try {
192
+ span.setAttributes(attributes);
193
+ const result = await fn(span);
194
+ span.setStatus({
195
+ code: api_namespaceObject.SpanStatusCode.OK
468
196
  });
469
- this.name = this.constructor.name;
470
- this.code = options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR;
471
- this.statusCode = options.status ?? 500;
472
- this.category = options.category ?? ERROR_CATEGORIES.UNEXPECTED;
473
- this.meta = options.meta ?? {};
474
- this.data = {
475
- code: this.code,
476
- category: this.category,
477
- meta: this.meta
478
- };
479
- tracing_withSpan('create_doubletie_error', async (span)=>{
197
+ span.end();
198
+ return result;
199
+ } catch (error) {
200
+ if (error instanceof error_class_DoubleTieError) {
480
201
  span.setAttributes({
481
- 'error.name': this.name,
482
- 'error.message': message,
483
- 'error.code': this.code,
484
- 'error.status': this.statusCode,
485
- 'error.category': this.category,
486
- 'error.has_cause': !!this.cause,
487
- 'error.cause_type': this.cause instanceof Error ? this.cause.constructor.name : typeof this.cause,
488
- 'error.has_meta': !!this.meta
202
+ 'error.type': 'DoubleTieError',
203
+ 'error.code': error.code,
204
+ 'error.statusCode': error.statusCode,
205
+ 'error.message': error.message
489
206
  });
490
- if (this.cause instanceof Error) span.recordException(this.cause);
491
- });
492
- if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
493
- }
494
- static isDoubleTieError(error) {
495
- return error instanceof error_class_DoubleTieError;
496
- }
497
- toJSON() {
498
- const validationErrorMessage = this.meta?.validationErrors ? String(this.meta.validationErrors) : void 0;
499
- const stackTrace = this.stack ? this.stack.split('\n').map((line)=>line.trim()).filter((line)=>line && !line.includes('Error: ')) : [];
500
- return {
501
- statusCode: this.statusCode,
502
- message: validationErrorMessage || this.message,
503
- statusMessage: this.statusMessage,
504
- data: {
505
- code: this.code,
506
- category: this.category,
507
- meta: this.meta,
508
- ...'production' === process.env.NODE_ENV ? {} : {
509
- stack: stackTrace
510
- },
511
- ...validationErrorMessage && this.message ? {
512
- originalMessage: this.message
513
- } : {},
514
- ...this.cause ? {
515
- cause: this.cause instanceof Error ? {
516
- name: this.cause.name,
517
- message: this.cause.message,
518
- stack: this.cause.stack ? this.cause.stack.split('\n').map((line)=>line.trim()) : void 0
519
- } : this.cause
520
- } : {}
521
- }
522
- };
523
- }
524
- static fromResponse(response, data) {
525
- let message = `HTTP error ${response.status}`;
526
- let errorCode = `HTTP ${response.status}`;
527
- let errorMeta = {};
528
- if (data && 'object' == typeof data && null !== data) {
529
- const errorObj = data;
530
- if ('string' == typeof errorObj.message) message = errorObj.message;
531
- if ('string' == typeof errorObj.code) errorCode = errorObj.code;
532
- if ('object' == typeof errorObj.data && null !== errorObj.data) errorMeta = errorObj.data;
533
- }
534
- return new error_class_DoubleTieError(message, {
535
- code: errorCode,
536
- status: response.status,
537
- meta: errorMeta
538
- });
539
- }
540
- withMeta(additionalMeta) {
541
- return new error_class_DoubleTieError(this.message, {
542
- code: this.code,
543
- status: this.statusCode,
544
- category: this.category,
545
- cause: this.cause instanceof Error ? this.cause : void 0,
546
- meta: {
547
- ...this.meta,
548
- ...additionalMeta
549
- }
550
- });
551
- }
552
- static createSubclass(name) {
553
- const ErrorSubclass = class extends error_class_DoubleTieError {
554
- constructor(message, options){
555
- super(message, options);
556
- this.name = name;
557
- }
558
- };
559
- Object.defineProperty(ErrorSubclass, 'name', {
560
- value: name
207
+ if (error.meta) span.setAttributes({
208
+ 'error.meta': JSON.stringify(error.meta)
209
+ });
210
+ } else span.setAttributes({
211
+ 'error.type': error instanceof Error ? error.constructor.name : 'Unknown',
212
+ 'error.message': error instanceof Error ? error.message : String(error)
561
213
  });
562
- return ErrorSubclass;
563
- }
564
- static formatValidationError(error) {
565
- if (!error.meta) return error.message;
566
- let formattedMessage = `${error.message} (${error.code})`;
567
- if (error.meta.validationErrors) formattedMessage += `\nValidation Errors: ${JSON.stringify(error.meta.validationErrors, null, 2)}`;
568
- const otherMeta = Object.fromEntries(Object.entries(error.meta).filter(([key])=>'validationErrors' !== key));
569
- if (Object.keys(otherMeta).length > 0) formattedMessage += `\nAdditional Context: ${JSON.stringify(otherMeta, null, 2)}`;
570
- return formattedMessage;
571
- }
572
- }
573
- var ZodError = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js");
574
- const colors = {
575
- reset: '\x1b[0m',
576
- bright: '\x1b[1m',
577
- dim: '\x1b[2m',
578
- underscore: '\x1b[4m',
579
- blink: '\x1b[5m',
580
- reverse: '\x1b[7m',
581
- hidden: '\x1b[8m',
582
- fg: {
583
- black: '\x1b[30m',
584
- red: '\x1b[31m',
585
- green: '\x1b[32m',
586
- yellow: '\x1b[33m',
587
- blue: '\x1b[34m',
588
- magenta: '\x1b[35m',
589
- cyan: '\x1b[36m',
590
- white: '\x1b[37m'
591
- },
592
- bg: {
593
- black: '\x1b[40m',
594
- red: '\x1b[41m',
595
- green: '\x1b[42m',
596
- yellow: '\x1b[43m',
597
- blue: '\x1b[44m',
598
- magenta: '\x1b[45m',
599
- cyan: '\x1b[46m',
600
- white: '\x1b[47m'
601
- }
602
- };
603
- const levelColors = {
604
- info: colors.fg.blue,
605
- success: colors.fg.green,
606
- warn: colors.fg.yellow,
607
- error: colors.fg.red,
608
- debug: colors.fg.magenta
609
- };
610
- const formatMessage = (level, message, appName = 'c15t')=>{
611
- const timestamp = new Date().toISOString();
612
- return `${colors.dim}${timestamp}${colors.reset} ${levelColors[level]}${level.toUpperCase()}${colors.reset} ${colors.bright}[${appName}]:${colors.reset} ${message}`;
613
- };
614
- const levels = [
615
- 'error',
616
- 'warn',
617
- 'info',
618
- 'success',
619
- 'debug'
620
- ];
621
- function shouldPublishLog(currentLogLevel, logLevel) {
622
- const currentLevelIndex = levels.indexOf(currentLogLevel);
623
- const messageLevelIndex = levels.indexOf(logLevel);
624
- if ('debug' === currentLogLevel) return 'debug' === logLevel;
625
- return messageLevelIndex <= currentLevelIndex;
626
- }
627
- const LOGGER_TRACER_NAME = '@doubletie/logger';
628
- const LOG_LEVEL_TO_SPAN_STATUS = {
629
- error: api_namespaceObject.SpanStatusCode.ERROR,
630
- warn: api_namespaceObject.SpanStatusCode.OK,
631
- info: api_namespaceObject.SpanStatusCode.OK,
632
- success: api_namespaceObject.SpanStatusCode.OK,
633
- debug: api_namespaceObject.SpanStatusCode.OK
634
- };
635
- const telemetry_getTracer = (options)=>{
636
- if (options?.telemetry?.tracer) return options.telemetry.tracer;
637
- return api_namespaceObject.trace.getTracer(LOGGER_TRACER_NAME);
638
- };
639
- const createLogSpan = (level, message, args = [], options)=>{
640
- if (options?.telemetry?.disabled) return null;
641
- const tracer = telemetry_getTracer(options);
642
- const span = tracer.startSpan('log_entry', {
643
- attributes: {
644
- 'log.level': level,
645
- 'log.message': message,
646
- 'log.has_args': args.length > 0,
647
- ...options?.telemetry?.defaultAttributes || {}
648
- }
649
- });
650
- if (args.length > 0 && 'object' == typeof args[0] && null !== args[0]) {
651
- const data = args[0];
652
- for (const [key, value] of Object.entries(data))if (null != value) span.setAttribute(`log.data.${key}`, String(value));
653
- }
654
- span.setStatus({
655
- code: LOG_LEVEL_TO_SPAN_STATUS[level],
656
- message: 'error' === level || 'warn' === level ? message : void 0
657
- });
658
- return span;
659
- };
660
- const withLogSpan = async (level, message, args, operation, options)=>{
661
- const span = createLogSpan(level, message, args, options);
662
- if (!span) return operation();
663
- try {
664
- const result = await operation();
665
- return result;
666
- } catch (error) {
667
214
  span.setStatus({
668
215
  code: api_namespaceObject.SpanStatusCode.ERROR,
669
216
  message: error instanceof Error ? error.message : String(error)
670
217
  });
671
- throw error;
672
- } finally{
673
218
  span.end();
219
+ throw error;
674
220
  }
675
- };
676
- const createLogger = (options)=>{
677
- if (options && 'object' == typeof options && levels.every((level)=>'function' == typeof options[level])) return options;
678
- const loggerOptions = options;
679
- const enabled = loggerOptions?.disabled !== true;
680
- const logLevel = loggerOptions?.level ?? 'error';
681
- const appName = loggerOptions?.appName ?? 'c15t';
682
- const logFunc = async (level, message, args = [])=>{
683
- if (!enabled || !shouldPublishLog(logLevel, level)) return;
684
- await withLogSpan(level, message, args, async ()=>{
685
- const formattedMessage = formatMessage(level, message, appName);
686
- if (!loggerOptions || 'function' != typeof loggerOptions.log) {
687
- if ('error' === level) console.error(formattedMessage, ...args);
688
- else if ('warn' === level) console.warn(formattedMessage, ...args);
689
- else if ('info' === level) console.log(formattedMessage, ...args);
690
- else if ('debug' === level) console.debug(formattedMessage, ...args);
691
- else if ('success' === level) console.log(formattedMessage, ...args);
692
- return;
693
- }
694
- loggerOptions.log('success' === level ? 'info' : level, message, ...args);
695
- });
696
- };
697
- return Object.fromEntries(levels.map((level)=>[
698
- level,
699
- (...[message, ...args])=>logFunc(level, message, args).catch((error)=>{
700
- console.error('Logger error:', error);
701
- })
702
- ]));
703
- };
704
- const logger_factory_logger = createLogger();
705
- const auditLogSchema = external_zod_namespaceObject.z.object({
706
- id: external_zod_namespaceObject.z.string(),
707
- entityType: external_zod_namespaceObject.z.string(),
708
- entityId: external_zod_namespaceObject.z.string(),
709
- actionType: external_zod_namespaceObject.z.string(),
710
- subjectId: external_zod_namespaceObject.z.string().optional(),
711
- ipAddress: external_zod_namespaceObject.z.string().optional(),
712
- userAgent: external_zod_namespaceObject.z.string().optional(),
713
- changes: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
714
- metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
715
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date())
716
- });
717
- function getAuditLogTable(options, auditLogFields) {
718
- const auditLogConfig = options.tables?.auditLog;
719
- const subjectConfig = options.tables?.subject;
720
- return {
721
- entityName: auditLogConfig?.entityName || 'auditLog',
722
- entityPrefix: auditLogConfig?.entityPrefix || 'log',
723
- schema: auditLogSchema,
724
- fields: {
725
- entityType: {
726
- type: 'string',
727
- required: true,
728
- fieldName: auditLogConfig?.fields?.entityType || 'entityType'
729
- },
730
- entityId: {
731
- type: 'string',
732
- required: true,
733
- fieldName: auditLogConfig?.fields?.entityId || 'entityId'
734
- },
735
- actionType: {
736
- type: 'string',
737
- required: true,
738
- fieldName: auditLogConfig?.fields?.actionType || 'actionType'
739
- },
740
- subjectId: {
741
- type: 'string',
742
- required: false,
743
- fieldName: auditLogConfig?.fields?.subjectId || 'subjectId',
744
- references: {
745
- model: subjectConfig?.entityName || 'subject',
746
- field: 'id'
747
- }
748
- },
749
- ipAddress: {
750
- type: 'string',
751
- required: false,
752
- fieldName: auditLogConfig?.fields?.ipAddress || 'ipAddress'
753
- },
754
- userAgent: {
755
- type: 'string',
756
- required: false,
757
- fieldName: auditLogConfig?.fields?.userAgent || 'userAgent'
758
- },
759
- changes: {
760
- type: 'json',
761
- required: false,
762
- fieldName: auditLogConfig?.fields?.changes || 'changes'
763
- },
764
- metadata: {
765
- type: 'json',
766
- required: false,
767
- fieldName: auditLogConfig?.fields?.metadata || 'metadata'
768
- },
769
- createdAt: {
770
- type: 'date',
771
- defaultValue: ()=>new Date(),
772
- required: true,
773
- fieldName: auditLogConfig?.fields?.createdAt || 'createdAt'
774
- },
775
- eventTimezone: {
776
- type: 'timezone',
777
- required: true,
778
- defaultValue: COMMON_TIMEZONES.UTC,
779
- fieldName: auditLogConfig?.fields?.eventTimezone || 'eventTimezone'
780
- },
781
- ...auditLogFields || {},
782
- ...auditLogConfig?.additionalFields || {}
783
- },
784
- indexes: [
785
- {
786
- name: 'entity_index',
787
- fields: [
788
- 'entityType',
789
- 'entityId'
790
- ]
791
- },
792
- {
793
- name: 'action_type_index',
794
- fields: [
795
- 'actionType'
796
- ]
797
- },
798
- {
799
- name: 'subject_id_index',
800
- fields: [
801
- 'subjectId'
802
- ]
803
- },
804
- {
805
- name: 'created_at_index',
806
- fields: [
807
- 'createdAt'
808
- ]
809
- }
810
- ],
811
- order: 5
812
- };
813
- }
814
- const PolicyTypeSchema = external_zod_namespaceObject.z["enum"]([
815
- 'cookie_banner',
816
- 'privacy_policy',
817
- 'dpa',
818
- 'terms_and_conditions',
819
- 'marketing_communications',
820
- 'age_verification',
821
- 'other'
822
- ]);
823
- const consentPolicySchema = external_zod_namespaceObject.z.object({
824
- id: external_zod_namespaceObject.z.string(),
825
- version: external_zod_namespaceObject.z.string(),
826
- type: PolicyTypeSchema,
827
- name: external_zod_namespaceObject.z.string(),
828
- effectiveDate: external_zod_namespaceObject.z.date(),
829
- expirationDate: external_zod_namespaceObject.z.date().nullable().optional(),
830
- content: external_zod_namespaceObject.z.string(),
831
- contentHash: external_zod_namespaceObject.z.string(),
832
- isActive: external_zod_namespaceObject.z.boolean().default(true),
833
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
834
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
835
221
  });
836
- function getConsentPolicyTable(options, policyFields) {
837
- const consentPolicyConfig = options.tables?.consentPolicy;
838
- return {
839
- entityName: consentPolicyConfig?.entityName || 'consentPolicy',
840
- entityPrefix: consentPolicyConfig?.entityPrefix || 'pol',
841
- schema: consentPolicySchema,
842
- fields: {
843
- version: {
844
- type: 'string',
845
- required: true,
846
- fieldName: consentPolicyConfig?.fields?.version || 'version'
847
- },
848
- type: {
849
- type: 'string',
850
- required: true,
851
- fieldName: consentPolicyConfig?.fields?.type || 'type'
852
- },
853
- name: {
854
- type: 'string',
855
- required: true,
856
- fieldName: consentPolicyConfig?.fields?.name || 'name'
857
- },
858
- effectiveDate: {
859
- type: 'date',
860
- required: true,
861
- fieldName: consentPolicyConfig?.fields?.effectiveDate || 'effectiveDate'
862
- },
863
- expirationDate: {
864
- type: 'date',
865
- required: false,
866
- fieldName: consentPolicyConfig?.fields?.expirationDate || 'expirationDate'
867
- },
868
- content: {
869
- type: 'string',
870
- required: true,
871
- fieldName: consentPolicyConfig?.fields?.content || 'content'
872
- },
873
- contentHash: {
874
- type: 'string',
875
- required: true,
876
- fieldName: consentPolicyConfig?.fields?.contentHash || 'contentHash'
877
- },
878
- isActive: {
879
- type: 'boolean',
880
- defaultValue: true,
881
- required: true,
882
- fieldName: consentPolicyConfig?.fields?.isActive || 'isActive'
883
- },
884
- createdAt: {
885
- type: 'date',
886
- defaultValue: ()=>new Date(),
887
- required: true,
888
- fieldName: consentPolicyConfig?.fields?.createdAt || 'createdAt'
889
- },
890
- ...policyFields || {},
891
- ...consentPolicyConfig?.additionalFields || {}
892
- },
893
- order: 2
894
- };
222
+ }
223
+ class error_class_DoubleTieError extends server_namespaceObject.ORPCError {
224
+ category;
225
+ meta;
226
+ statusCode;
227
+ constructor(message, options = {
228
+ code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
229
+ status: 500,
230
+ category: ERROR_CATEGORIES.UNEXPECTED,
231
+ cause: void 0,
232
+ meta: {}
233
+ }){
234
+ super(options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR, {
235
+ message,
236
+ cause: options.cause,
237
+ data: options.meta ?? {}
238
+ });
239
+ this.name = 'DoubleTieError';
240
+ this.category = options.category ?? ERROR_CATEGORIES.UNEXPECTED;
241
+ this.meta = options.meta ?? {};
242
+ this.statusCode = options.status ?? 500;
243
+ tracing_withSpan('create_doubletie_error', async (span)=>{
244
+ span.setAttributes({
245
+ 'error.name': this.constructor.name,
246
+ 'error.message': message,
247
+ 'error.code': this.code,
248
+ 'error.status': this.statusCode,
249
+ 'error.category': this.category,
250
+ 'error.has_cause': !!this.cause,
251
+ 'error.cause_type': this.cause instanceof Error ? this.cause.constructor.name : typeof this.cause,
252
+ 'error.has_meta': !!this.meta
253
+ });
254
+ if (this.cause instanceof Error) span.recordException(this.cause);
255
+ });
256
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
895
257
  }
896
- const purposeSchema = external_zod_namespaceObject.z.object({
897
- id: external_zod_namespaceObject.z.string(),
898
- code: external_zod_namespaceObject.z.string(),
899
- name: external_zod_namespaceObject.z.string(),
900
- description: external_zod_namespaceObject.z.string(),
901
- isEssential: external_zod_namespaceObject.z.boolean().default(false),
902
- dataCategory: external_zod_namespaceObject.z.string().optional(),
903
- legalBasis: external_zod_namespaceObject.z.string().optional(),
904
- isActive: external_zod_namespaceObject.z.boolean().default(true),
905
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
906
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
907
- });
908
- function getPurposeTable(options, purposeFields) {
909
- const purposeConfig = options.tables?.consentPurpose;
910
- return {
911
- entityName: purposeConfig?.entityName || 'consentPurpose',
912
- entityPrefix: purposeConfig?.entityPrefix || 'pur',
913
- schema: purposeSchema,
914
- fields: {
915
- code: {
916
- type: 'string',
917
- required: true,
918
- fieldName: purposeConfig?.fields?.code || 'code'
919
- },
920
- name: {
921
- type: 'string',
922
- required: true,
923
- fieldName: purposeConfig?.fields?.name || 'name'
924
- },
925
- description: {
926
- type: 'string',
927
- required: true,
928
- fieldName: purposeConfig?.fields?.description || "description"
929
- },
930
- isEssential: {
931
- type: 'boolean',
932
- defaultValue: ()=>false,
933
- required: true,
934
- fieldName: purposeConfig?.fields?.isEssential || 'isEssential'
935
- },
936
- dataCategory: {
937
- type: 'string',
938
- required: false,
939
- fieldName: purposeConfig?.fields?.dataCategory || 'dataCategory'
940
- },
941
- legalBasis: {
942
- type: 'string',
943
- required: false,
944
- fieldName: purposeConfig?.fields?.legalBasis || 'legalBasis'
945
- },
946
- isActive: {
947
- type: 'boolean',
948
- defaultValue: true,
949
- required: true,
950
- fieldName: purposeConfig?.fields?.isActive || 'isActive'
951
- },
952
- createdAt: {
953
- type: 'date',
954
- defaultValue: ()=>new Date(),
955
- required: true,
956
- fieldName: purposeConfig?.fields?.createdAt || 'createdAt'
957
- },
958
- updatedAt: {
959
- type: 'date',
960
- defaultValue: ()=>new Date(),
961
- required: true,
962
- fieldName: purposeConfig?.fields?.updatedAt || 'updatedAt'
963
- },
964
- ...purposeFields || {},
965
- ...purposeConfig?.additionalFields || {}
966
- },
967
- order: 1
968
- };
258
+ static isDoubleTieError(error) {
259
+ return error instanceof error_class_DoubleTieError;
969
260
  }
970
- const consentRecordSchema = external_zod_namespaceObject.z.object({
971
- id: external_zod_namespaceObject.z.string(),
972
- subjectId: external_zod_namespaceObject.z.string(),
973
- consentId: external_zod_namespaceObject.z.string().optional(),
974
- actionType: external_zod_namespaceObject.z.string(),
975
- details: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
976
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
977
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
978
- });
979
- function getConsentRecordTable(options, recordFields) {
980
- const recordConfig = options.tables?.record;
981
- const subjectConfig = options.tables?.subject;
982
- const consentConfig = options.tables?.consent;
261
+ toJSON() {
262
+ const validationErrorMessage = this.meta?.validationErrors ? String(this.meta.validationErrors) : void 0;
263
+ const stackTrace = this.stack ? this.stack.split('\n').map((line)=>line.trim()).filter((line)=>line && !line.includes('Error: ')) : [];
983
264
  return {
984
- entityName: recordConfig?.entityName || 'consentRecord',
985
- entityPrefix: recordConfig?.entityPrefix || 'rec',
986
- schema: consentRecordSchema,
987
- fields: {
988
- subjectId: {
989
- type: 'string',
990
- required: true,
991
- fieldName: recordConfig?.fields?.subjectId || 'subjectId',
992
- references: {
993
- model: subjectConfig?.entityName || 'subject',
994
- field: 'id'
995
- }
996
- },
997
- consentId: {
998
- type: 'string',
999
- required: false,
1000
- fieldName: recordConfig?.fields?.consentId || 'consentId',
1001
- references: {
1002
- model: consentConfig?.entityName || 'consent',
1003
- field: 'id'
1004
- }
1005
- },
1006
- actionType: {
1007
- type: 'string',
1008
- required: true,
1009
- fieldName: recordConfig?.fields?.actionType || 'actionType'
1010
- },
1011
- details: {
1012
- type: 'json',
1013
- required: false,
1014
- fieldName: recordConfig?.fields?.details || 'details'
1015
- },
1016
- createdAt: {
1017
- type: 'date',
1018
- defaultValue: ()=>new Date(),
1019
- required: true,
1020
- fieldName: recordConfig?.fields?.createdAt || 'createdAt'
265
+ code: this.code,
266
+ message: validationErrorMessage || this.message,
267
+ status: this.statusCode,
268
+ defined: true,
269
+ data: {
270
+ category: this.category,
271
+ meta: this.meta,
272
+ ...'production' === process.env.NODE_ENV ? {} : {
273
+ stack: stackTrace
1021
274
  },
1022
- ...recordFields || {},
1023
- ...recordConfig?.additionalFields || {}
1024
- },
1025
- order: 4
275
+ ...validationErrorMessage && this.message ? {
276
+ originalMessage: this.message
277
+ } : {},
278
+ ...this.cause ? {
279
+ cause: this.cause instanceof Error ? {
280
+ name: this.cause.name,
281
+ message: this.cause.message,
282
+ stack: this.cause.stack ? this.cause.stack.split('\n').map((line)=>line.trim()) : void 0
283
+ } : this.cause
284
+ } : {}
285
+ }
1026
286
  };
1027
287
  }
1028
- const consentSchema = external_zod_namespaceObject.z.object({
1029
- id: external_zod_namespaceObject.z.string(),
1030
- subjectId: external_zod_namespaceObject.z.string(),
1031
- domainId: external_zod_namespaceObject.z.string(),
1032
- purposeIds: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()),
1033
- metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).nullable().optional(),
1034
- policyId: external_zod_namespaceObject.z.string().optional(),
1035
- ipAddress: external_zod_namespaceObject.z.string().nullable().optional(),
1036
- userAgent: external_zod_namespaceObject.z.string().nullable().optional(),
1037
- status: external_zod_namespaceObject.z["enum"]([
1038
- 'active',
1039
- 'withdrawn',
1040
- 'expired'
1041
- ]).default('active'),
1042
- withdrawalReason: external_zod_namespaceObject.z.string().nullable().optional(),
1043
- givenAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1044
- validUntil: external_zod_namespaceObject.z.date().nullable().optional(),
1045
- isActive: external_zod_namespaceObject.z.boolean().default(true)
1046
- });
1047
- function getConsentTable(options, consentFields) {
1048
- const consentConfig = options.tables?.consent;
1049
- const subjectConfig = options.tables?.subject;
1050
- const domainConfig = options.tables?.domain;
1051
- const policyConfig = options.tables?.consentPolicy;
1052
- return {
1053
- entityName: consentConfig?.entityName || 'consent',
1054
- entityPrefix: consentConfig?.entityPrefix || 'cns',
1055
- schema: consentSchema,
1056
- fields: {
1057
- subjectId: {
1058
- type: 'string',
1059
- required: true,
1060
- fieldName: consentConfig?.fields?.subjectId || 'subjectId',
1061
- references: {
1062
- model: subjectConfig?.entityName || 'subject',
1063
- field: 'id'
1064
- }
1065
- },
1066
- domainId: {
1067
- type: 'string',
1068
- required: true,
1069
- fieldName: consentConfig?.fields?.domainId || 'domainId',
1070
- references: {
1071
- model: domainConfig?.entityName || 'domain',
1072
- field: 'id'
1073
- }
1074
- },
1075
- purposeIds: {
1076
- type: 'json',
1077
- required: false,
1078
- fieldName: consentConfig?.fields?.purposeIds || 'purposeIds'
1079
- },
1080
- metadata: {
1081
- type: 'json',
1082
- required: false,
1083
- fieldName: consentConfig?.fields?.metadata || 'metadata'
1084
- },
1085
- policyId: {
1086
- type: 'string',
1087
- required: false,
1088
- fieldName: consentConfig?.fields?.policyId || 'policyId',
1089
- references: {
1090
- model: policyConfig?.entityName || 'consentPolicy',
1091
- field: 'id'
1092
- }
1093
- },
1094
- ipAddress: {
1095
- type: 'string',
1096
- required: false,
1097
- fieldName: consentConfig?.fields?.ipAddress || 'ipAddress'
1098
- },
1099
- userAgent: {
1100
- type: 'string',
1101
- required: false,
1102
- fieldName: consentConfig?.fields?.userAgent || 'userAgent'
1103
- },
1104
- status: {
1105
- type: 'string',
1106
- defaultValue: ()=>'active',
1107
- required: true,
1108
- fieldName: consentConfig?.fields?.status || 'status'
1109
- },
1110
- withdrawalReason: {
1111
- type: 'string',
1112
- required: false,
1113
- fieldName: consentConfig?.fields?.withdrawalReason || 'withdrawalReason'
1114
- },
1115
- givenAt: {
1116
- type: 'date',
1117
- defaultValue: ()=>new Date(),
1118
- required: true,
1119
- fieldName: consentConfig?.fields?.givenAt || 'givenAt'
1120
- },
1121
- validUntil: {
1122
- type: 'date',
1123
- required: false,
1124
- fieldName: consentConfig?.fields?.validUntil || 'validUntil',
1125
- transform: {
1126
- input: (val, data)=>{
1127
- if (val) return val;
1128
- const expiresIn = consentConfig?.expiresIn || 31536000;
1129
- const givenAt = data.givenAt instanceof Date ? data.givenAt : new Date();
1130
- if (expiresIn > 0) {
1131
- const validUntil = new Date(givenAt);
1132
- validUntil.setSeconds(validUntil.getSeconds() + expiresIn);
1133
- return validUntil;
1134
- }
1135
- }
1136
- }
1137
- },
1138
- isActive: {
1139
- type: 'boolean',
1140
- defaultValue: true,
1141
- required: true,
1142
- fieldName: consentConfig?.fields?.isActive || 'isActive'
1143
- },
1144
- ...consentFields || {},
1145
- ...consentConfig?.additionalFields || {}
1146
- },
1147
- order: 3
1148
- };
288
+ static fromResponse(response, data) {
289
+ let message = `HTTP error ${response.status}`;
290
+ let errorCode = `HTTP ${response.status}`;
291
+ let errorMeta = {};
292
+ if (data && 'object' == typeof data && null !== data) {
293
+ const errorObj = data;
294
+ if ('string' == typeof errorObj.message) message = errorObj.message;
295
+ if ('string' == typeof errorObj.code) errorCode = errorObj.code;
296
+ if ('object' == typeof errorObj.data && null !== errorObj.data) errorMeta = errorObj.data;
297
+ }
298
+ return new error_class_DoubleTieError(message, {
299
+ code: errorCode,
300
+ status: response.status,
301
+ meta: errorMeta
302
+ });
1149
303
  }
1150
- const domainSchema = external_zod_namespaceObject.z.object({
1151
- id: external_zod_namespaceObject.z.string(),
1152
- name: external_zod_namespaceObject.z.string().min(1),
1153
- description: external_zod_namespaceObject.z.string().optional(),
1154
- allowedOrigins: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional().default([]),
1155
- isVerified: external_zod_namespaceObject.z.boolean().default(true),
1156
- isActive: external_zod_namespaceObject.z.boolean().default(true),
1157
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1158
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1159
- });
1160
- function getDomainTable(options, domainFields) {
1161
- const domainConfig = options.tables?.domain;
1162
- return {
1163
- entityName: domainConfig?.entityName || 'domain',
1164
- entityPrefix: domainConfig?.entityPrefix || 'dom',
1165
- schema: domainSchema,
1166
- fields: {
1167
- name: {
1168
- type: 'string',
1169
- required: true,
1170
- unique: true,
1171
- fieldName: domainConfig?.fields?.name || 'name'
1172
- },
1173
- description: {
1174
- type: 'string',
1175
- required: false,
1176
- fieldName: domainConfig?.fields?.description || "description"
1177
- },
1178
- allowedOrigins: {
1179
- type: 'json',
1180
- defaultValue: ()=>[],
1181
- required: false,
1182
- fieldName: domainConfig?.fields?.allowedOrigins || 'allowedOrigins'
1183
- },
1184
- isVerified: {
1185
- type: 'boolean',
1186
- defaultValue: true,
1187
- required: true,
1188
- fieldName: domainConfig?.fields?.isVerified || 'isVerified'
1189
- },
1190
- isActive: {
1191
- type: 'boolean',
1192
- defaultValue: true,
1193
- required: true,
1194
- fieldName: domainConfig?.fields?.isActive || 'isActive'
1195
- },
1196
- createdAt: {
1197
- type: 'date',
1198
- defaultValue: ()=>new Date(),
1199
- required: true,
1200
- fieldName: domainConfig?.fields?.createdAt || 'createdAt'
1201
- },
1202
- updatedAt: {
1203
- type: 'date',
1204
- required: false,
1205
- fieldName: domainConfig?.fields?.updatedAt || 'updatedAt'
1206
- },
1207
- ...domainFields || {},
1208
- ...domainConfig?.additionalFields || {}
1209
- },
1210
- order: 1
1211
- };
304
+ withMeta(additionalMeta) {
305
+ return new error_class_DoubleTieError(this.message, {
306
+ code: this.code,
307
+ status: this.statusCode,
308
+ category: this.category,
309
+ cause: this.cause instanceof Error ? this.cause : void 0,
310
+ meta: {
311
+ ...this.meta,
312
+ ...additionalMeta
313
+ }
314
+ });
1212
315
  }
1213
- const subjectSchema = external_zod_namespaceObject.z.object({
1214
- id: external_zod_namespaceObject.z.string(),
1215
- isIdentified: external_zod_namespaceObject.z.boolean().default(false),
1216
- externalId: external_zod_namespaceObject.z.string().nullable().optional(),
1217
- identityProvider: external_zod_namespaceObject.z.string().optional(),
1218
- lastIpAddress: external_zod_namespaceObject.z.string().optional(),
1219
- createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
1220
- updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
1221
- });
1222
- function getSubjectTable(options, subjectFields) {
1223
- const subjectConfig = options.tables?.subject;
1224
- return {
1225
- entityName: subjectConfig?.entityName || 'subject',
1226
- entityPrefix: subjectConfig?.entityPrefix || 'sub',
1227
- schema: subjectSchema,
1228
- fields: {
1229
- isIdentified: {
1230
- type: 'boolean',
1231
- defaultValue: ()=>false,
1232
- required: true,
1233
- fieldName: subjectConfig?.fields?.isIdentified || 'isIdentified'
1234
- },
1235
- externalId: {
1236
- type: 'string',
1237
- required: false,
1238
- fieldName: subjectConfig?.fields?.externalId || 'externalId'
1239
- },
1240
- identityProvider: {
1241
- type: 'string',
1242
- required: false,
1243
- fieldName: subjectConfig?.fields?.identityProvider || 'identityProvider'
1244
- },
1245
- lastIpAddress: {
1246
- type: 'string',
1247
- required: false,
1248
- fieldName: subjectConfig?.fields?.lastIpAddress || 'lastIpAddress'
1249
- },
1250
- createdAt: {
1251
- type: 'date',
1252
- defaultValue: ()=>new Date(),
1253
- required: true,
1254
- fieldName: subjectConfig?.fields?.createdAt || 'createdAt'
1255
- },
1256
- updatedAt: {
1257
- type: 'date',
1258
- defaultValue: ()=>new Date(),
1259
- required: true,
1260
- fieldName: subjectConfig?.fields?.updatedAt || 'updatedAt'
1261
- },
1262
- subjectTimezone: {
1263
- type: 'timezone',
1264
- required: false,
1265
- defaultValue: COMMON_TIMEZONES.UTC,
1266
- fieldName: subjectConfig?.fields?.subjectTimezone || 'subjectTimezone'
1267
- },
1268
- ...subjectFields || {},
1269
- ...subjectConfig?.additionalFields || {}
1270
- },
1271
- order: 1
316
+ static createSubclass(name) {
317
+ const ErrorSubclass = class extends error_class_DoubleTieError {
318
+ constructor(message, options){
319
+ super(message, options);
320
+ Object.defineProperty(this, 'name', {
321
+ value: name
322
+ });
323
+ }
1272
324
  };
325
+ Object.defineProperty(ErrorSubclass, 'name', {
326
+ value: name
327
+ });
328
+ return ErrorSubclass;
1273
329
  }
1274
- const getConsentTables = (options)=>{
1275
- const pluginSchema = options.plugins?.reduce((acc, plugin)=>{
1276
- const schema = plugin.schema;
1277
- if (!schema) return acc;
1278
- for (const [key, value] of Object.entries(schema))acc[key] = {
1279
- fields: {
1280
- ...acc[key]?.fields,
1281
- ...value.fields
1282
- },
1283
- entityName: key
1284
- };
1285
- return acc;
1286
- }, {});
1287
- const { subject, consentPurpose, consentPolicy, domain, geoLocation, consent, consentPurposeJunction, record, consentGeoLocation, consentWithdrawal, auditLog, ...pluginTables } = pluginSchema || {};
1288
- return {
1289
- subject: getSubjectTable(options, subject?.fields),
1290
- consentPurpose: getPurposeTable(options, consentPurpose?.fields),
1291
- consentPolicy: getConsentPolicyTable(options, consentPolicy?.fields),
1292
- domain: getDomainTable(options, domain?.fields),
1293
- consent: getConsentTable(options, consent?.fields),
1294
- consentRecord: getConsentRecordTable(options, record?.fields),
1295
- auditLog: getAuditLogTable(options, auditLog?.fields),
1296
- ...pluginTables
1297
- };
1298
- };
1299
- function validateEntityOutput(tableName, data, options) {
1300
- const tables = getConsentTables(options);
1301
- const table = tables[tableName];
1302
- if (!table) throw new Error(`Table ${tableName} not found`);
1303
- const processedData = {
1304
- ...data
1305
- };
1306
- for (const [field, def] of Object.entries(table.fields))if ('date' === def.type && 'string' == typeof processedData[field]) processedData[field] = new Date(processedData[field]);
1307
- try {
1308
- return table.schema.parse(processedData);
1309
- } catch (error) {
1310
- if (error instanceof ZodError.ZodError) logger_factory_logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
1311
- table,
1312
- issues: error.issues
1313
- });
1314
- throw error;
1315
- }
330
+ static formatValidationError(error) {
331
+ if (!error.meta) return error.message;
332
+ let formattedMessage = `${error.message} (${error.code})`;
333
+ if (error.meta.validationErrors) formattedMessage += `\nValidation Errors: ${JSON.stringify(error.meta.validationErrors, null, 2)}`;
334
+ const otherMeta = Object.fromEntries(Object.entries(error.meta).filter(([key])=>'validationErrors' !== key));
335
+ if (Object.keys(otherMeta).length > 0) formattedMessage += `\nAdditional Context: ${JSON.stringify(otherMeta, null, 2)}`;
336
+ return formattedMessage;
1316
337
  }
1317
- function subjectRegistry({ adapter, ...ctx }) {
1318
- const { createWithHooks } = getWithHooks(adapter, ctx);
1319
- return {
1320
- createSubject: async (subject, context)=>{
1321
- const createdSubject = await createWithHooks({
1322
- data: {
1323
- createdAt: new Date(),
1324
- updatedAt: new Date(),
1325
- ...subject
1326
- },
1327
- model: 'subject',
1328
- customFn: void 0,
1329
- context
1330
- });
1331
- return createdSubject ? validateEntityOutput('subject', createdSubject, ctx.options) : null;
338
+ }
339
+ const logger_namespaceObject = require("@doubletie/logger");
340
+ const auditLogSchema = external_zod_namespaceObject.z.object({
341
+ id: external_zod_namespaceObject.z.string(),
342
+ entityType: external_zod_namespaceObject.z.string(),
343
+ entityId: external_zod_namespaceObject.z.string(),
344
+ actionType: external_zod_namespaceObject.z.string(),
345
+ subjectId: external_zod_namespaceObject.z.string().optional(),
346
+ ipAddress: external_zod_namespaceObject.z.string().optional(),
347
+ userAgent: external_zod_namespaceObject.z.string().optional(),
348
+ changes: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
349
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
350
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date())
351
+ });
352
+ function getAuditLogTable(options, auditLogFields) {
353
+ const auditLogConfig = options.tables?.auditLog;
354
+ const subjectConfig = options.tables?.subject;
355
+ return {
356
+ entityName: auditLogConfig?.entityName || 'auditLog',
357
+ entityPrefix: auditLogConfig?.entityPrefix || 'log',
358
+ schema: auditLogSchema,
359
+ fields: {
360
+ entityType: {
361
+ type: 'string',
362
+ required: true,
363
+ fieldName: auditLogConfig?.fields?.entityType || 'entityType'
1332
364
  },
1333
- findOrCreateSubject: async function({ subjectId, externalSubjectId, ipAddress = 'unknown', context }) {
1334
- if (subjectId && externalSubjectId) {
1335
- const [subjectById, subjectByExternalId] = await Promise.all([
1336
- this.findSubjectById(subjectId),
1337
- this.findSubjectByExternalId(externalSubjectId)
1338
- ]);
1339
- if (!subjectById || !subjectByExternalId) {
1340
- ctx.logger?.error('Subject validation failed: One or both subjects not found', {
1341
- providedSubjectId: subjectId,
1342
- providedExternalId: externalSubjectId,
1343
- subjectByIdFound: !!subjectById,
1344
- subjectByExternalIdFound: !!subjectByExternalId
1345
- });
1346
- throw new error_class_DoubleTieError('The specified subject could not be found. Please verify the subject identifiers and try again.', {
1347
- code: error_codes_ERROR_CODES.NOT_FOUND,
1348
- status: 404,
1349
- meta: {
1350
- providedSubjectId: subjectId,
1351
- providedExternalId: externalSubjectId
1352
- }
1353
- });
1354
- }
1355
- if (subjectById.id !== subjectByExternalId.id) {
1356
- ctx.logger?.warn('Subject validation failed: IDs do not match the same subject', {
1357
- providedSubjectId: subjectId,
1358
- providedExternalId: externalSubjectId,
1359
- subjectByIdId: subjectById.id,
1360
- subjectByExternalIdId: subjectByExternalId.id
1361
- });
1362
- throw new error_class_DoubleTieError('The provided subjectId and externalSubjectId do not match the same subject. Please ensure both identifiers refer to the same subject.', {
1363
- code: error_codes_ERROR_CODES.CONFLICT,
1364
- status: 409,
1365
- meta: {
1366
- providedSubjectId: subjectId,
1367
- providedExternalId: externalSubjectId,
1368
- subjectByIdId: subjectById.id,
1369
- subjectByExternalIdId: subjectByExternalId.id
1370
- }
1371
- });
1372
- }
1373
- return subjectById;
365
+ entityId: {
366
+ type: 'string',
367
+ required: true,
368
+ fieldName: auditLogConfig?.fields?.entityId || 'entityId'
369
+ },
370
+ actionType: {
371
+ type: 'string',
372
+ required: true,
373
+ fieldName: auditLogConfig?.fields?.actionType || 'actionType'
374
+ },
375
+ subjectId: {
376
+ type: 'string',
377
+ required: false,
378
+ fieldName: auditLogConfig?.fields?.subjectId || 'subjectId',
379
+ references: {
380
+ model: subjectConfig?.entityName || 'subject',
381
+ field: 'id'
1374
382
  }
1375
- if (subjectId) {
1376
- const subject = await this.findSubjectById(subjectId);
1377
- if (subject) return subject;
1378
- throw new error_class_DoubleTieError('Subject not found by subjectId', {
1379
- code: error_codes_ERROR_CODES.NOT_FOUND,
1380
- status: 404
1381
- });
383
+ },
384
+ ipAddress: {
385
+ type: 'string',
386
+ required: false,
387
+ fieldName: auditLogConfig?.fields?.ipAddress || 'ipAddress'
388
+ },
389
+ userAgent: {
390
+ type: 'string',
391
+ required: false,
392
+ fieldName: auditLogConfig?.fields?.userAgent || 'userAgent'
393
+ },
394
+ changes: {
395
+ type: 'json',
396
+ required: false,
397
+ fieldName: auditLogConfig?.fields?.changes || 'changes'
398
+ },
399
+ metadata: {
400
+ type: 'json',
401
+ required: false,
402
+ fieldName: auditLogConfig?.fields?.metadata || 'metadata'
403
+ },
404
+ createdAt: {
405
+ type: 'date',
406
+ defaultValue: ()=>new Date(),
407
+ required: true,
408
+ fieldName: auditLogConfig?.fields?.createdAt || 'createdAt'
409
+ },
410
+ eventTimezone: {
411
+ type: 'timezone',
412
+ required: true,
413
+ defaultValue: COMMON_TIMEZONES.UTC,
414
+ fieldName: auditLogConfig?.fields?.eventTimezone || 'eventTimezone'
415
+ },
416
+ ...auditLogFields || {},
417
+ ...auditLogConfig?.additionalFields || {}
418
+ },
419
+ indexes: [
420
+ {
421
+ name: 'entity_index',
422
+ fields: [
423
+ 'entityType',
424
+ 'entityId'
425
+ ]
426
+ },
427
+ {
428
+ name: 'action_type_index',
429
+ fields: [
430
+ 'actionType'
431
+ ]
432
+ },
433
+ {
434
+ name: 'subject_id_index',
435
+ fields: [
436
+ 'subjectId'
437
+ ]
438
+ },
439
+ {
440
+ name: 'created_at_index',
441
+ fields: [
442
+ 'createdAt'
443
+ ]
444
+ }
445
+ ],
446
+ order: 5
447
+ };
448
+ }
449
+ const PolicyTypeSchema = external_zod_namespaceObject.z["enum"]([
450
+ 'cookie_banner',
451
+ 'privacy_policy',
452
+ 'dpa',
453
+ 'terms_and_conditions',
454
+ 'marketing_communications',
455
+ 'age_verification',
456
+ 'other'
457
+ ]);
458
+ const consentPolicySchema = external_zod_namespaceObject.z.object({
459
+ id: external_zod_namespaceObject.z.string(),
460
+ version: external_zod_namespaceObject.z.string(),
461
+ type: PolicyTypeSchema,
462
+ name: external_zod_namespaceObject.z.string(),
463
+ effectiveDate: external_zod_namespaceObject.z.date(),
464
+ expirationDate: external_zod_namespaceObject.z.date().nullable().optional(),
465
+ content: external_zod_namespaceObject.z.string(),
466
+ contentHash: external_zod_namespaceObject.z.string(),
467
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
468
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
469
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
470
+ });
471
+ function getConsentPolicyTable(options, policyFields) {
472
+ const consentPolicyConfig = options.tables?.consentPolicy;
473
+ return {
474
+ entityName: consentPolicyConfig?.entityName || 'consentPolicy',
475
+ entityPrefix: consentPolicyConfig?.entityPrefix || 'pol',
476
+ schema: consentPolicySchema,
477
+ fields: {
478
+ version: {
479
+ type: 'string',
480
+ required: true,
481
+ fieldName: consentPolicyConfig?.fields?.version || 'version'
482
+ },
483
+ type: {
484
+ type: 'string',
485
+ required: true,
486
+ fieldName: consentPolicyConfig?.fields?.type || 'type'
487
+ },
488
+ name: {
489
+ type: 'string',
490
+ required: true,
491
+ fieldName: consentPolicyConfig?.fields?.name || 'name'
492
+ },
493
+ effectiveDate: {
494
+ type: 'date',
495
+ required: true,
496
+ fieldName: consentPolicyConfig?.fields?.effectiveDate || 'effectiveDate'
497
+ },
498
+ expirationDate: {
499
+ type: 'date',
500
+ required: false,
501
+ fieldName: consentPolicyConfig?.fields?.expirationDate || 'expirationDate'
502
+ },
503
+ content: {
504
+ type: 'string',
505
+ required: true,
506
+ fieldName: consentPolicyConfig?.fields?.content || 'content'
507
+ },
508
+ contentHash: {
509
+ type: 'string',
510
+ required: true,
511
+ fieldName: consentPolicyConfig?.fields?.contentHash || 'contentHash'
512
+ },
513
+ isActive: {
514
+ type: 'boolean',
515
+ defaultValue: true,
516
+ required: true,
517
+ fieldName: consentPolicyConfig?.fields?.isActive || 'isActive'
518
+ },
519
+ createdAt: {
520
+ type: 'date',
521
+ defaultValue: ()=>new Date(),
522
+ required: true,
523
+ fieldName: consentPolicyConfig?.fields?.createdAt || 'createdAt'
524
+ },
525
+ ...policyFields || {},
526
+ ...consentPolicyConfig?.additionalFields || {}
527
+ },
528
+ order: 2
529
+ };
530
+ }
531
+ const purposeSchema = external_zod_namespaceObject.z.object({
532
+ id: external_zod_namespaceObject.z.string(),
533
+ code: external_zod_namespaceObject.z.string(),
534
+ name: external_zod_namespaceObject.z.string(),
535
+ description: external_zod_namespaceObject.z.string(),
536
+ isEssential: external_zod_namespaceObject.z.boolean().default(false),
537
+ dataCategory: external_zod_namespaceObject.z.string().optional(),
538
+ legalBasis: external_zod_namespaceObject.z.string().optional(),
539
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
540
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
541
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
542
+ });
543
+ function getPurposeTable(options, purposeFields) {
544
+ const purposeConfig = options.tables?.consentPurpose;
545
+ return {
546
+ entityName: purposeConfig?.entityName || 'consentPurpose',
547
+ entityPrefix: purposeConfig?.entityPrefix || 'pur',
548
+ schema: purposeSchema,
549
+ fields: {
550
+ code: {
551
+ type: 'string',
552
+ required: true,
553
+ fieldName: purposeConfig?.fields?.code || 'code'
554
+ },
555
+ name: {
556
+ type: 'string',
557
+ required: true,
558
+ fieldName: purposeConfig?.fields?.name || 'name'
559
+ },
560
+ description: {
561
+ type: 'string',
562
+ required: true,
563
+ fieldName: purposeConfig?.fields?.description || "description"
564
+ },
565
+ isEssential: {
566
+ type: 'boolean',
567
+ defaultValue: ()=>false,
568
+ required: true,
569
+ fieldName: purposeConfig?.fields?.isEssential || 'isEssential'
570
+ },
571
+ dataCategory: {
572
+ type: 'string',
573
+ required: false,
574
+ fieldName: purposeConfig?.fields?.dataCategory || 'dataCategory'
575
+ },
576
+ legalBasis: {
577
+ type: 'string',
578
+ required: false,
579
+ fieldName: purposeConfig?.fields?.legalBasis || 'legalBasis'
580
+ },
581
+ isActive: {
582
+ type: 'boolean',
583
+ defaultValue: true,
584
+ required: true,
585
+ fieldName: purposeConfig?.fields?.isActive || 'isActive'
586
+ },
587
+ createdAt: {
588
+ type: 'date',
589
+ defaultValue: ()=>new Date(),
590
+ required: true,
591
+ fieldName: purposeConfig?.fields?.createdAt || 'createdAt'
592
+ },
593
+ updatedAt: {
594
+ type: 'date',
595
+ defaultValue: ()=>new Date(),
596
+ required: true,
597
+ fieldName: purposeConfig?.fields?.updatedAt || 'updatedAt'
598
+ },
599
+ ...purposeFields || {},
600
+ ...purposeConfig?.additionalFields || {}
601
+ },
602
+ order: 1
603
+ };
604
+ }
605
+ const consentRecordSchema = external_zod_namespaceObject.z.object({
606
+ id: external_zod_namespaceObject.z.string(),
607
+ subjectId: external_zod_namespaceObject.z.string(),
608
+ consentId: external_zod_namespaceObject.z.string().optional(),
609
+ actionType: external_zod_namespaceObject.z.string(),
610
+ details: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).optional(),
611
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
612
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
613
+ });
614
+ function getConsentRecordTable(options, recordFields) {
615
+ const recordConfig = options.tables?.record;
616
+ const subjectConfig = options.tables?.subject;
617
+ const consentConfig = options.tables?.consent;
618
+ return {
619
+ entityName: recordConfig?.entityName || 'consentRecord',
620
+ entityPrefix: recordConfig?.entityPrefix || 'rec',
621
+ schema: consentRecordSchema,
622
+ fields: {
623
+ subjectId: {
624
+ type: 'string',
625
+ required: true,
626
+ fieldName: recordConfig?.fields?.subjectId || 'subjectId',
627
+ references: {
628
+ model: subjectConfig?.entityName || 'subject',
629
+ field: 'id'
1382
630
  }
1383
- if (externalSubjectId) try {
1384
- const subject = await this.findSubjectByExternalId(externalSubjectId);
1385
- if (subject) {
1386
- ctx.logger?.debug('Found existing subject by external ID', {
1387
- externalSubjectId
1388
- });
1389
- return subject;
1390
- }
1391
- ctx.logger?.info('Creating new subject with external ID', {
1392
- externalSubjectId
1393
- });
1394
- return await this.createSubject({
1395
- externalId: externalSubjectId,
1396
- identityProvider: 'external',
1397
- lastIpAddress: ipAddress,
1398
- isIdentified: true
1399
- }, context);
1400
- } catch (error) {
1401
- if (error instanceof Error && error.message.includes('unique constraint')) {
1402
- ctx.logger?.info('Handling duplicate key violation for external ID', {
1403
- externalSubjectId
1404
- });
1405
- const subject = await this.findSubjectByExternalId(externalSubjectId);
1406
- if (subject) return subject;
631
+ },
632
+ consentId: {
633
+ type: 'string',
634
+ required: false,
635
+ fieldName: recordConfig?.fields?.consentId || 'consentId',
636
+ references: {
637
+ model: consentConfig?.entityName || 'consent',
638
+ field: 'id'
639
+ }
640
+ },
641
+ actionType: {
642
+ type: 'string',
643
+ required: true,
644
+ fieldName: recordConfig?.fields?.actionType || 'actionType'
645
+ },
646
+ details: {
647
+ type: 'json',
648
+ required: false,
649
+ fieldName: recordConfig?.fields?.details || 'details'
650
+ },
651
+ createdAt: {
652
+ type: 'date',
653
+ defaultValue: ()=>new Date(),
654
+ required: true,
655
+ fieldName: recordConfig?.fields?.createdAt || 'createdAt'
656
+ },
657
+ ...recordFields || {},
658
+ ...recordConfig?.additionalFields || {}
659
+ },
660
+ order: 4
661
+ };
662
+ }
663
+ const consentSchema = external_zod_namespaceObject.z.object({
664
+ id: external_zod_namespaceObject.z.string(),
665
+ subjectId: external_zod_namespaceObject.z.string(),
666
+ domainId: external_zod_namespaceObject.z.string(),
667
+ purposeIds: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()),
668
+ metadata: external_zod_namespaceObject.z.record(external_zod_namespaceObject.z.unknown()).nullable().optional(),
669
+ policyId: external_zod_namespaceObject.z.string().optional(),
670
+ ipAddress: external_zod_namespaceObject.z.string().nullable().optional(),
671
+ userAgent: external_zod_namespaceObject.z.string().nullable().optional(),
672
+ status: external_zod_namespaceObject.z["enum"]([
673
+ 'active',
674
+ 'withdrawn',
675
+ 'expired'
676
+ ]).default('active'),
677
+ withdrawalReason: external_zod_namespaceObject.z.string().nullable().optional(),
678
+ givenAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
679
+ validUntil: external_zod_namespaceObject.z.date().nullable().optional(),
680
+ isActive: external_zod_namespaceObject.z.boolean().default(true)
681
+ });
682
+ function getConsentTable(options, consentFields) {
683
+ const consentConfig = options.tables?.consent;
684
+ const subjectConfig = options.tables?.subject;
685
+ const domainConfig = options.tables?.domain;
686
+ const policyConfig = options.tables?.consentPolicy;
687
+ return {
688
+ entityName: consentConfig?.entityName || 'consent',
689
+ entityPrefix: consentConfig?.entityPrefix || 'cns',
690
+ schema: consentSchema,
691
+ fields: {
692
+ subjectId: {
693
+ type: 'string',
694
+ required: true,
695
+ fieldName: consentConfig?.fields?.subjectId || 'subjectId',
696
+ references: {
697
+ model: subjectConfig?.entityName || 'subject',
698
+ field: 'id'
699
+ }
700
+ },
701
+ domainId: {
702
+ type: 'string',
703
+ required: true,
704
+ fieldName: consentConfig?.fields?.domainId || 'domainId',
705
+ references: {
706
+ model: domainConfig?.entityName || 'domain',
707
+ field: 'id'
708
+ }
709
+ },
710
+ purposeIds: {
711
+ type: 'json',
712
+ required: false,
713
+ fieldName: consentConfig?.fields?.purposeIds || 'purposeIds'
714
+ },
715
+ metadata: {
716
+ type: 'json',
717
+ required: false,
718
+ fieldName: consentConfig?.fields?.metadata || 'metadata'
719
+ },
720
+ policyId: {
721
+ type: 'string',
722
+ required: false,
723
+ fieldName: consentConfig?.fields?.policyId || 'policyId',
724
+ references: {
725
+ model: policyConfig?.entityName || 'consentPolicy',
726
+ field: 'id'
727
+ }
728
+ },
729
+ ipAddress: {
730
+ type: 'string',
731
+ required: false,
732
+ fieldName: consentConfig?.fields?.ipAddress || 'ipAddress'
733
+ },
734
+ userAgent: {
735
+ type: 'string',
736
+ required: false,
737
+ fieldName: consentConfig?.fields?.userAgent || 'userAgent'
738
+ },
739
+ status: {
740
+ type: 'string',
741
+ defaultValue: ()=>'active',
742
+ required: true,
743
+ fieldName: consentConfig?.fields?.status || 'status'
744
+ },
745
+ withdrawalReason: {
746
+ type: 'string',
747
+ required: false,
748
+ fieldName: consentConfig?.fields?.withdrawalReason || 'withdrawalReason'
749
+ },
750
+ givenAt: {
751
+ type: 'date',
752
+ defaultValue: ()=>new Date(),
753
+ required: true,
754
+ fieldName: consentConfig?.fields?.givenAt || 'givenAt'
755
+ },
756
+ validUntil: {
757
+ type: 'date',
758
+ required: false,
759
+ fieldName: consentConfig?.fields?.validUntil || 'validUntil',
760
+ transform: {
761
+ input: (val, data)=>{
762
+ if (val) return val;
763
+ const expiresIn = consentConfig?.expiresIn || 31536000;
764
+ const givenAt = data.givenAt instanceof Date ? data.givenAt : new Date();
765
+ if (expiresIn > 0) {
766
+ const validUntil = new Date(givenAt);
767
+ validUntil.setSeconds(validUntil.getSeconds() + expiresIn);
768
+ return validUntil;
769
+ }
1407
770
  }
1408
- ctx.logger?.error('Failed to create or find subject with external ID', {
1409
- externalSubjectId,
1410
- error: error instanceof Error ? error.message : 'Unknown error'
771
+ }
772
+ },
773
+ isActive: {
774
+ type: 'boolean',
775
+ defaultValue: true,
776
+ required: true,
777
+ fieldName: consentConfig?.fields?.isActive || 'isActive'
778
+ },
779
+ ...consentFields || {},
780
+ ...consentConfig?.additionalFields || {}
781
+ },
782
+ order: 3
783
+ };
784
+ }
785
+ const domainSchema = external_zod_namespaceObject.z.object({
786
+ id: external_zod_namespaceObject.z.string(),
787
+ name: external_zod_namespaceObject.z.string().min(1),
788
+ description: external_zod_namespaceObject.z.string().optional(),
789
+ allowedOrigins: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string()).optional().default([]),
790
+ isVerified: external_zod_namespaceObject.z.boolean().default(true),
791
+ isActive: external_zod_namespaceObject.z.boolean().default(true),
792
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
793
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
794
+ });
795
+ function getDomainTable(options, domainFields) {
796
+ const domainConfig = options.tables?.domain;
797
+ return {
798
+ entityName: domainConfig?.entityName || 'domain',
799
+ entityPrefix: domainConfig?.entityPrefix || 'dom',
800
+ schema: domainSchema,
801
+ fields: {
802
+ name: {
803
+ type: 'string',
804
+ required: true,
805
+ unique: true,
806
+ fieldName: domainConfig?.fields?.name || 'name'
807
+ },
808
+ description: {
809
+ type: 'string',
810
+ required: false,
811
+ fieldName: domainConfig?.fields?.description || "description"
812
+ },
813
+ allowedOrigins: {
814
+ type: 'json',
815
+ defaultValue: ()=>[],
816
+ required: false,
817
+ fieldName: domainConfig?.fields?.allowedOrigins || 'allowedOrigins'
818
+ },
819
+ isVerified: {
820
+ type: 'boolean',
821
+ defaultValue: true,
822
+ required: true,
823
+ fieldName: domainConfig?.fields?.isVerified || 'isVerified'
824
+ },
825
+ isActive: {
826
+ type: 'boolean',
827
+ defaultValue: true,
828
+ required: true,
829
+ fieldName: domainConfig?.fields?.isActive || 'isActive'
830
+ },
831
+ createdAt: {
832
+ type: 'date',
833
+ defaultValue: ()=>new Date(),
834
+ required: true,
835
+ fieldName: domainConfig?.fields?.createdAt || 'createdAt'
836
+ },
837
+ updatedAt: {
838
+ type: 'date',
839
+ required: false,
840
+ fieldName: domainConfig?.fields?.updatedAt || 'updatedAt'
841
+ },
842
+ ...domainFields || {},
843
+ ...domainConfig?.additionalFields || {}
844
+ },
845
+ order: 1
846
+ };
847
+ }
848
+ const subjectSchema = external_zod_namespaceObject.z.object({
849
+ id: external_zod_namespaceObject.z.string(),
850
+ isIdentified: external_zod_namespaceObject.z.boolean().default(false),
851
+ externalId: external_zod_namespaceObject.z.string().nullable().optional(),
852
+ identityProvider: external_zod_namespaceObject.z.string().optional(),
853
+ lastIpAddress: external_zod_namespaceObject.z.string().optional(),
854
+ createdAt: external_zod_namespaceObject.z.date().default(()=>new Date()),
855
+ updatedAt: external_zod_namespaceObject.z.date().default(()=>new Date())
856
+ });
857
+ function getSubjectTable(options, subjectFields) {
858
+ const subjectConfig = options.tables?.subject;
859
+ return {
860
+ entityName: subjectConfig?.entityName || 'subject',
861
+ entityPrefix: subjectConfig?.entityPrefix || 'sub',
862
+ schema: subjectSchema,
863
+ fields: {
864
+ isIdentified: {
865
+ type: 'boolean',
866
+ defaultValue: ()=>false,
867
+ required: true,
868
+ fieldName: subjectConfig?.fields?.isIdentified || 'isIdentified'
869
+ },
870
+ externalId: {
871
+ type: 'string',
872
+ required: false,
873
+ fieldName: subjectConfig?.fields?.externalId || 'externalId'
874
+ },
875
+ identityProvider: {
876
+ type: 'string',
877
+ required: false,
878
+ fieldName: subjectConfig?.fields?.identityProvider || 'identityProvider'
879
+ },
880
+ lastIpAddress: {
881
+ type: 'string',
882
+ required: false,
883
+ fieldName: subjectConfig?.fields?.lastIpAddress || 'lastIpAddress'
884
+ },
885
+ createdAt: {
886
+ type: 'date',
887
+ defaultValue: ()=>new Date(),
888
+ required: true,
889
+ fieldName: subjectConfig?.fields?.createdAt || 'createdAt'
890
+ },
891
+ updatedAt: {
892
+ type: 'date',
893
+ defaultValue: ()=>new Date(),
894
+ required: true,
895
+ fieldName: subjectConfig?.fields?.updatedAt || 'updatedAt'
896
+ },
897
+ subjectTimezone: {
898
+ type: 'timezone',
899
+ required: false,
900
+ defaultValue: COMMON_TIMEZONES.UTC,
901
+ fieldName: subjectConfig?.fields?.subjectTimezone || 'subjectTimezone'
902
+ },
903
+ ...subjectFields || {},
904
+ ...subjectConfig?.additionalFields || {}
905
+ },
906
+ order: 1
907
+ };
908
+ }
909
+ const getConsentTables = (options)=>{
910
+ const pluginSchema = options.plugins?.reduce((acc, plugin)=>{
911
+ const schema = plugin.schema;
912
+ if (!schema) return acc;
913
+ for (const [key, value] of Object.entries(schema))acc[key] = {
914
+ fields: {
915
+ ...acc[key]?.fields,
916
+ ...value.fields
917
+ },
918
+ entityName: key
919
+ };
920
+ return acc;
921
+ }, {});
922
+ const { subject, consentPurpose, consentPolicy, domain, geoLocation, consent, consentPurposeJunction, record, consentGeoLocation, consentWithdrawal, auditLog, ...pluginTables } = pluginSchema || {};
923
+ return {
924
+ subject: getSubjectTable(options, subject?.fields),
925
+ consentPurpose: getPurposeTable(options, consentPurpose?.fields),
926
+ consentPolicy: getConsentPolicyTable(options, consentPolicy?.fields),
927
+ domain: getDomainTable(options, domain?.fields),
928
+ consent: getConsentTable(options, consent?.fields),
929
+ consentRecord: getConsentRecordTable(options, record?.fields),
930
+ auditLog: getAuditLogTable(options, auditLog?.fields),
931
+ ...pluginTables
932
+ };
933
+ };
934
+ function validateEntityOutput(tableName, data, options) {
935
+ const tables = getConsentTables(options);
936
+ const table = tables[tableName];
937
+ if (!table) throw new Error(`Table ${tableName} not found`);
938
+ const processedData = {
939
+ ...data
940
+ };
941
+ for (const [field, def] of Object.entries(table.fields))if ('date' === def.type && 'string' == typeof processedData[field]) processedData[field] = new Date(processedData[field]);
942
+ try {
943
+ return table.schema.parse(processedData);
944
+ } catch (error) {
945
+ if (error instanceof external_zod_namespaceObject.ZodError) logger_namespaceObject.logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
946
+ table,
947
+ issues: error.issues
948
+ });
949
+ throw error;
950
+ }
951
+ }
952
+ function subjectRegistry({ adapter, ...ctx }) {
953
+ const { createWithHooks } = getWithHooks(adapter, ctx);
954
+ return {
955
+ createSubject: async (subject, context)=>{
956
+ const createdSubject = await createWithHooks({
957
+ data: {
958
+ createdAt: new Date(),
959
+ updatedAt: new Date(),
960
+ ...subject
961
+ },
962
+ model: 'subject',
963
+ customFn: void 0,
964
+ context
965
+ });
966
+ return createdSubject ? validateEntityOutput('subject', createdSubject, ctx.options) : null;
967
+ },
968
+ findOrCreateSubject: async function({ subjectId, externalSubjectId, ipAddress = 'unknown', context }) {
969
+ if (subjectId && externalSubjectId) {
970
+ const [subjectById, subjectByExternalId] = await Promise.all([
971
+ this.findSubjectById(subjectId),
972
+ this.findSubjectByExternalId(externalSubjectId)
973
+ ]);
974
+ if (!subjectById || !subjectByExternalId) {
975
+ ctx.logger?.error('Subject validation failed: One or both subjects not found', {
976
+ providedSubjectId: subjectId,
977
+ providedExternalId: externalSubjectId,
978
+ subjectByIdFound: !!subjectById,
979
+ subjectByExternalIdFound: !!subjectByExternalId
1411
980
  });
1412
- throw new error_class_DoubleTieError('Failed to create or find subject with external ID', {
1413
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1414
- status: 500,
981
+ throw new error_class_DoubleTieError('The specified subject could not be found. Please verify the subject identifiers and try again.', {
982
+ code: error_codes_ERROR_CODES.NOT_FOUND,
983
+ status: 404,
1415
984
  meta: {
1416
- error: error instanceof Error ? error.message : 'Unknown error'
985
+ providedSubjectId: subjectId,
986
+ providedExternalId: externalSubjectId
1417
987
  }
1418
988
  });
1419
989
  }
1420
- try {
1421
- ctx.logger?.info('Creating new anonymous subject');
1422
- return await this.createSubject({
1423
- externalId: null,
1424
- identityProvider: 'anonymous',
1425
- lastIpAddress: ipAddress,
1426
- isIdentified: false
1427
- }, context);
1428
- } catch (error) {
1429
- ctx.logger?.error('Failed to create anonymous subject', {
1430
- ipAddress,
1431
- error: error instanceof Error ? error.message : 'Unknown error'
990
+ if (subjectById.id !== subjectByExternalId.id) {
991
+ ctx.logger?.warn('Subject validation failed: IDs do not match the same subject', {
992
+ providedSubjectId: subjectId,
993
+ providedExternalId: externalSubjectId,
994
+ subjectByIdId: subjectById.id,
995
+ subjectByExternalIdId: subjectByExternalId.id
1432
996
  });
1433
- throw new error_class_DoubleTieError('Failed to create anonymous subject', {
1434
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1435
- status: 500,
997
+ throw new error_class_DoubleTieError('The provided subjectId and externalSubjectId do not match the same subject. Please ensure both identifiers refer to the same subject.', {
998
+ code: error_codes_ERROR_CODES.CONFLICT,
999
+ status: 409,
1436
1000
  meta: {
1437
- error: error instanceof Error ? error.message : 'Unknown error'
1001
+ providedSubjectId: subjectId,
1002
+ providedExternalId: externalSubjectId,
1003
+ subjectByIdId: subjectById.id,
1004
+ subjectByExternalIdId: subjectByExternalId.id
1438
1005
  }
1439
1006
  });
1440
1007
  }
1441
- },
1442
- findSubjectById: async (subjectId)=>{
1443
- const subject = await adapter.findOne({
1444
- model: 'subject',
1445
- where: [
1446
- {
1447
- field: 'id',
1448
- value: subjectId
1449
- }
1450
- ]
1451
- });
1452
- return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1453
- },
1454
- findSubjectByExternalId: async (externalId)=>{
1455
- const subject = await adapter.findOne({
1456
- model: 'subject',
1457
- where: [
1458
- {
1459
- field: 'externalId',
1460
- value: externalId
1461
- }
1462
- ]
1463
- });
1464
- return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1008
+ return subjectById;
1465
1009
  }
1466
- };
1467
- }
1468
- function consentRegistry({ adapter, ...ctx }) {
1469
- const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
1470
- const registry = {
1471
- createConsent: async (consent, context)=>{
1472
- const createdConsent = await createWithHooks({
1473
- data: {
1474
- createdAt: new Date(),
1475
- ...consent
1476
- },
1477
- model: 'consent',
1478
- context
1010
+ if (subjectId) {
1011
+ const subject = await this.findSubjectById(subjectId);
1012
+ if (subject) return subject;
1013
+ throw new error_class_DoubleTieError('Subject not found by subjectId', {
1014
+ code: error_codes_ERROR_CODES.NOT_FOUND,
1015
+ status: 404
1479
1016
  });
1480
- if (!createdConsent) throw new error_class_DoubleTieError('Failed to create consent - operation returned null', {
1481
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1482
- status: 500
1483
- });
1484
- return createdConsent;
1485
- },
1486
- updateConsent: async (consentId, data, context)=>{
1487
- const consent = await updateWithHooks({
1488
- data: {
1489
- ...data
1490
- },
1491
- where: [
1492
- {
1493
- field: 'id',
1494
- value: consentId
1495
- }
1496
- ],
1497
- model: 'consent',
1498
- context
1499
- });
1500
- return consent ? validateEntityOutput('consent', consent, ctx.options) : null;
1501
1017
  }
1502
- };
1503
- return registry;
1504
- }
1505
- const external_node_crypto_namespaceObject = require("node:crypto");
1506
- function generatePolicyPlaceholder(name, date) {
1507
- const content = `[PLACEHOLDER] This is an automatically generated version of the ${name} policy.\n\nThis placeholder content should be replaced with actual policy terms before being presented to users.\n\nGenerated on: ${date.toISOString()}`;
1508
- const contentHash = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(content).digest('hex');
1509
- return {
1510
- content,
1511
- contentHash
1512
- };
1513
- }
1514
- function policyRegistry({ adapter, ...ctx }) {
1515
- const { createWithHooks } = getWithHooks(adapter, ctx);
1516
- const registry = {
1517
- createConsentPolicy: async (policy, context)=>{
1518
- const createdPolicy = await createWithHooks({
1519
- data: {
1520
- createdAt: new Date(),
1521
- ...policy
1522
- },
1523
- model: 'consentPolicy',
1524
- context
1525
- });
1526
- if (!createdPolicy) throw new error_class_DoubleTieError('Failed to create consent policy - operation returned null', {
1527
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1528
- status: 500
1529
- });
1530
- return createdPolicy;
1531
- },
1532
- findPolicies: async (params = {})=>{
1533
- const whereConditions = [];
1534
- if (!params.includeInactive) whereConditions.push({
1535
- field: 'isActive',
1536
- value: true
1537
- });
1538
- if (params.domainId) whereConditions.push({
1539
- field: 'id',
1540
- value: params.domainId
1541
- });
1542
- if (params.version) whereConditions.push({
1543
- field: 'version',
1544
- value: params.version
1545
- });
1546
- const policies = await adapter.findMany({
1547
- model: 'consentPolicy',
1548
- where: whereConditions,
1549
- sortBy: {
1550
- field: 'effectiveDate',
1551
- direction: 'desc'
1552
- }
1553
- });
1554
- return policies.map((policy)=>validateEntityOutput('consentPolicy', policy, ctx.options));
1555
- },
1556
- findConsentPolicyById: async (policyId)=>{
1557
- const policy = await adapter.findOne({
1558
- model: 'consentPolicy',
1559
- where: [
1560
- {
1561
- field: 'id',
1562
- value: policyId
1563
- }
1564
- ]
1018
+ if (externalSubjectId) try {
1019
+ const subject = await this.findSubjectByExternalId(externalSubjectId);
1020
+ if (subject) {
1021
+ ctx.logger?.debug('Found existing subject by external ID', {
1022
+ externalSubjectId
1023
+ });
1024
+ return subject;
1025
+ }
1026
+ ctx.logger?.info('Creating new subject with external ID', {
1027
+ externalSubjectId
1565
1028
  });
1566
- return policy ? validateEntityOutput('consentPolicy', policy, ctx.options) : null;
1567
- },
1568
- findOrCreatePolicy: async (type)=>adapter.transaction({
1569
- callback: async (txAdapter)=>{
1570
- const now = new Date();
1571
- const txRegistry = policyRegistry({
1572
- adapter: txAdapter,
1573
- ...ctx
1574
- });
1575
- const rawLatestPolicy = await txAdapter.findOne({
1576
- model: 'consentPolicy',
1577
- where: [
1578
- {
1579
- field: 'isActive',
1580
- value: true
1581
- },
1582
- {
1583
- field: 'type',
1584
- value: type
1585
- }
1586
- ],
1587
- sortBy: {
1588
- field: 'effectiveDate',
1589
- direction: 'desc'
1590
- }
1591
- });
1592
- const latestPolicy = rawLatestPolicy ? validateEntityOutput('consentPolicy', rawLatestPolicy, ctx.options) : null;
1593
- if (latestPolicy) return latestPolicy;
1594
- const { content: defaultContent, contentHash } = generatePolicyPlaceholder(type, now);
1595
- return txRegistry.createConsentPolicy({
1596
- version: '1.0.0',
1597
- type,
1598
- name: type,
1599
- effectiveDate: now,
1600
- content: defaultContent,
1601
- contentHash,
1602
- isActive: true,
1603
- updatedAt: now,
1604
- expirationDate: null
1605
- });
1606
- }
1607
- })
1608
- };
1609
- return registry;
1610
- }
1611
- function consentPurposeRegistry({ adapter, ...ctx }) {
1612
- const { createWithHooks } = getWithHooks(adapter, ctx);
1613
- return {
1614
- createConsentPurpose: async (consentPurpose, context)=>{
1615
- const createdPurpose = await createWithHooks({
1616
- data: {
1617
- id: consentPurpose.id || '',
1618
- createdAt: new Date(),
1619
- updatedAt: new Date(),
1620
- ...consentPurpose
1621
- },
1622
- model: 'consentPurpose',
1623
- context
1029
+ return await this.createSubject({
1030
+ externalId: externalSubjectId,
1031
+ identityProvider: 'external',
1032
+ lastIpAddress: ipAddress,
1033
+ isIdentified: true
1034
+ }, context);
1035
+ } catch (error) {
1036
+ if (error instanceof Error && error.message.includes('unique constraint')) {
1037
+ ctx.logger?.info('Handling duplicate key violation for external ID', {
1038
+ externalSubjectId
1039
+ });
1040
+ const subject = await this.findSubjectByExternalId(externalSubjectId);
1041
+ if (subject) return subject;
1042
+ }
1043
+ ctx.logger?.error('Failed to create or find subject with external ID', {
1044
+ externalSubjectId,
1045
+ error: error instanceof Error ? error.message : 'Unknown error'
1624
1046
  });
1625
- if (!createdPurpose) throw new error_class_DoubleTieError('Failed to create consent purpose - operation returned null', {
1047
+ throw new error_class_DoubleTieError('Failed to create or find subject with external ID', {
1626
1048
  code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1627
- status: 500
1628
- });
1629
- return validateEntityOutput('consentPurpose', createdPurpose, ctx.options);
1630
- },
1631
- findConsentPurposeByCode: async (code)=>{
1632
- const consentPurpose = await adapter.findOne({
1633
- model: 'consentPurpose',
1634
- where: [
1635
- {
1636
- field: 'code',
1637
- value: code
1638
- }
1639
- ]
1049
+ status: 500,
1050
+ meta: {
1051
+ error: error instanceof Error ? error.message : 'Unknown error'
1052
+ }
1640
1053
  });
1641
- return consentPurpose ? validateEntityOutput('consentPurpose', consentPurpose, ctx.options) : null;
1642
1054
  }
1643
- };
1644
- }
1645
- function domainRegistry({ adapter, ...ctx }) {
1646
- const { createWithHooks } = getWithHooks(adapter, ctx);
1647
- const registry = {
1648
- createDomain: async (domain, context)=>{
1649
- const createdDomain = await createWithHooks({
1650
- data: {
1651
- ...domain,
1652
- createdAt: new Date(),
1653
- updatedAt: new Date()
1654
- },
1655
- model: 'domain',
1656
- customFn: void 0,
1657
- context
1658
- });
1659
- if (!createdDomain) throw new error_class_DoubleTieError('Failed to create domain - operation returned null', {
1660
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1661
- status: 500
1662
- });
1663
- return createdDomain;
1664
- },
1665
- findOrCreateDomain: async function(name, context) {
1666
- const existingDomain = await this.findDomainByName(name);
1667
- if (existingDomain) return existingDomain;
1668
- const domain = await this.createDomain({
1669
- name,
1670
- description: `Auto-created domain for ${name}`,
1671
- isActive: true,
1672
- isVerified: true,
1673
- allowedOrigins: []
1055
+ try {
1056
+ ctx.logger?.info('Creating new anonymous subject');
1057
+ return await this.createSubject({
1058
+ externalId: null,
1059
+ identityProvider: 'anonymous',
1060
+ lastIpAddress: ipAddress,
1061
+ isIdentified: false
1674
1062
  }, context);
1675
- if (!domain) throw new error_class_DoubleTieError('Failed to create domain', {
1676
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1677
- status: 503
1678
- });
1679
- return domain;
1680
- },
1681
- findDomains: async (params = {})=>{
1682
- const whereConditions = [];
1683
- if (!params.includeInactive) whereConditions.push({
1684
- field: 'isActive',
1685
- value: true
1686
- });
1687
- if (params.name) whereConditions.push({
1688
- field: 'name',
1689
- value: params.name
1063
+ } catch (error) {
1064
+ ctx.logger?.error('Failed to create anonymous subject', {
1065
+ ipAddress,
1066
+ error: error instanceof Error ? error.message : 'Unknown error'
1690
1067
  });
1691
- const domains = await adapter.findMany({
1692
- model: 'domain',
1693
- where: whereConditions,
1694
- sortBy: {
1695
- field: 'name',
1696
- direction: 'asc'
1068
+ throw new error_class_DoubleTieError('Failed to create anonymous subject', {
1069
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1070
+ status: 500,
1071
+ meta: {
1072
+ error: error instanceof Error ? error.message : 'Unknown error'
1697
1073
  }
1698
1074
  });
1699
- return domains.map((domain)=>validateEntityOutput('domain', domain, ctx.options));
1700
- },
1701
- findDomain: async (name)=>{
1702
- const domains = await registry.findDomains({
1703
- name,
1704
- includeInactive: false
1705
- });
1706
- return domains[0] || null;
1707
- },
1708
- findDomainByName: async (name)=>{
1709
- const domain = await adapter.findOne({
1710
- model: 'domain',
1711
- where: [
1712
- {
1713
- field: 'name',
1714
- value: name
1715
- }
1716
- ]
1717
- });
1718
- return domain ? validateEntityOutput('domain', domain, ctx.options) : null;
1719
1075
  }
1720
- };
1721
- return registry;
1722
- }
1723
- async function processHooks(data, model, operation, phase, hooks, context) {
1724
- let currentData = {
1725
- ...data
1726
- };
1727
- for (const hookSet of hooks){
1728
- const modelHooks = hookSet[model];
1729
- if (!modelHooks) continue;
1730
- const operationHooks = modelHooks[operation];
1731
- if (!operationHooks) continue;
1732
- const hookFn = operationHooks[phase];
1733
- if (hookFn) if ('before' === phase) {
1734
- const result = await hookFn(currentData, context);
1735
- if (result && 'object' == typeof result && 'kind' in result) switch(result.kind){
1736
- case 'abort':
1737
- return null;
1738
- case 'transform':
1739
- {
1740
- const transformData = result.data;
1741
- currentData = {
1742
- ...currentData,
1743
- ...transformData
1744
- };
1745
- break;
1076
+ },
1077
+ findSubjectById: async (subjectId)=>{
1078
+ const subject = await adapter.findOne({
1079
+ model: 'subject',
1080
+ where: [
1081
+ {
1082
+ field: 'id',
1083
+ value: subjectId
1084
+ }
1085
+ ]
1086
+ });
1087
+ return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1088
+ },
1089
+ findSubjectByExternalId: async (externalId)=>{
1090
+ const subject = await adapter.findOne({
1091
+ model: 'subject',
1092
+ where: [
1093
+ {
1094
+ field: 'externalId',
1095
+ value: externalId
1096
+ }
1097
+ ]
1098
+ });
1099
+ return subject ? validateEntityOutput('subject', subject, ctx.options) : null;
1100
+ }
1101
+ };
1102
+ }
1103
+ function consentRegistry({ adapter, ...ctx }) {
1104
+ const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
1105
+ const registry = {
1106
+ createConsent: async (consent, context)=>{
1107
+ const createdConsent = await createWithHooks({
1108
+ data: {
1109
+ createdAt: new Date(),
1110
+ ...consent
1111
+ },
1112
+ model: 'consent',
1113
+ context
1114
+ });
1115
+ if (!createdConsent) throw new error_class_DoubleTieError('Failed to create consent - operation returned null', {
1116
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1117
+ status: 500
1118
+ });
1119
+ return createdConsent;
1120
+ },
1121
+ updateConsent: async (consentId, data, context)=>{
1122
+ const consent = await updateWithHooks({
1123
+ data: {
1124
+ ...data
1125
+ },
1126
+ where: [
1127
+ {
1128
+ field: 'id',
1129
+ value: consentId
1130
+ }
1131
+ ],
1132
+ model: 'consent',
1133
+ context
1134
+ });
1135
+ return consent ? validateEntityOutput('consent', consent, ctx.options) : null;
1136
+ }
1137
+ };
1138
+ return registry;
1139
+ }
1140
+ const external_node_crypto_namespaceObject = require("node:crypto");
1141
+ function generatePolicyPlaceholder(name, date) {
1142
+ const content = `[PLACEHOLDER] This is an automatically generated version of the ${name} policy.\n\nThis placeholder content should be replaced with actual policy terms before being presented to users.\n\nGenerated on: ${date.toISOString()}`;
1143
+ const contentHash = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(content).digest('hex');
1144
+ return {
1145
+ content,
1146
+ contentHash
1147
+ };
1148
+ }
1149
+ function policyRegistry({ adapter, ...ctx }) {
1150
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1151
+ const registry = {
1152
+ createConsentPolicy: async (policy, context)=>{
1153
+ const createdPolicy = await createWithHooks({
1154
+ data: {
1155
+ createdAt: new Date(),
1156
+ ...policy
1157
+ },
1158
+ model: 'consentPolicy',
1159
+ context
1160
+ });
1161
+ if (!createdPolicy) throw new error_class_DoubleTieError('Failed to create consent policy - operation returned null', {
1162
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1163
+ status: 500
1164
+ });
1165
+ return createdPolicy;
1166
+ },
1167
+ findPolicies: async (params = {})=>{
1168
+ const whereConditions = [];
1169
+ if (!params.includeInactive) whereConditions.push({
1170
+ field: 'isActive',
1171
+ value: true
1172
+ });
1173
+ if (params.domainId) whereConditions.push({
1174
+ field: 'id',
1175
+ value: params.domainId
1176
+ });
1177
+ if (params.version) whereConditions.push({
1178
+ field: 'version',
1179
+ value: params.version
1180
+ });
1181
+ const policies = await adapter.findMany({
1182
+ model: 'consentPolicy',
1183
+ where: whereConditions,
1184
+ sortBy: {
1185
+ field: 'effectiveDate',
1186
+ direction: 'desc'
1187
+ }
1188
+ });
1189
+ return policies.map((policy)=>validateEntityOutput('consentPolicy', policy, ctx.options));
1190
+ },
1191
+ findConsentPolicyById: async (policyId)=>{
1192
+ const policy = await adapter.findOne({
1193
+ model: 'consentPolicy',
1194
+ where: [
1195
+ {
1196
+ field: 'id',
1197
+ value: policyId
1198
+ }
1199
+ ]
1200
+ });
1201
+ return policy ? validateEntityOutput('consentPolicy', policy, ctx.options) : null;
1202
+ },
1203
+ findOrCreatePolicy: async (type)=>adapter.transaction({
1204
+ callback: async (txAdapter)=>{
1205
+ const now = new Date();
1206
+ const txRegistry = policyRegistry({
1207
+ adapter: txAdapter,
1208
+ ...ctx
1209
+ });
1210
+ const rawLatestPolicy = await txAdapter.findOne({
1211
+ model: 'consentPolicy',
1212
+ where: [
1213
+ {
1214
+ field: 'isActive',
1215
+ value: true
1216
+ },
1217
+ {
1218
+ field: 'type',
1219
+ value: type
1220
+ }
1221
+ ],
1222
+ sortBy: {
1223
+ field: 'effectiveDate',
1224
+ direction: 'desc'
1746
1225
  }
1747
- default:
1748
- break;
1226
+ });
1227
+ const latestPolicy = rawLatestPolicy ? validateEntityOutput('consentPolicy', rawLatestPolicy, ctx.options) : null;
1228
+ if (latestPolicy) return latestPolicy;
1229
+ const { content: defaultContent, contentHash } = generatePolicyPlaceholder(type, now);
1230
+ return txRegistry.createConsentPolicy({
1231
+ version: '1.0.0',
1232
+ type,
1233
+ name: type,
1234
+ effectiveDate: now,
1235
+ content: defaultContent,
1236
+ contentHash,
1237
+ isActive: true,
1238
+ updatedAt: now,
1239
+ expirationDate: null
1240
+ });
1749
1241
  }
1750
- } else await hookFn(currentData, context);
1242
+ })
1243
+ };
1244
+ return registry;
1245
+ }
1246
+ function consentPurposeRegistry({ adapter, ...ctx }) {
1247
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1248
+ return {
1249
+ createConsentPurpose: async (consentPurpose, context)=>{
1250
+ const createdPurpose = await createWithHooks({
1251
+ data: {
1252
+ id: consentPurpose.id || '',
1253
+ createdAt: new Date(),
1254
+ updatedAt: new Date(),
1255
+ ...consentPurpose
1256
+ },
1257
+ model: 'consentPurpose',
1258
+ context
1259
+ });
1260
+ if (!createdPurpose) throw new error_class_DoubleTieError('Failed to create consent purpose - operation returned null', {
1261
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1262
+ status: 500
1263
+ });
1264
+ return validateEntityOutput('consentPurpose', createdPurpose, ctx.options);
1265
+ },
1266
+ findConsentPurposeByCode: async (code)=>{
1267
+ const consentPurpose = await adapter.findOne({
1268
+ model: 'consentPurpose',
1269
+ where: [
1270
+ {
1271
+ field: 'code',
1272
+ value: code
1273
+ }
1274
+ ]
1275
+ });
1276
+ return consentPurpose ? validateEntityOutput('consentPurpose', consentPurpose, ctx.options) : null;
1751
1277
  }
1752
- return currentData;
1278
+ };
1279
+ }
1280
+ function domainRegistry({ adapter, ...ctx }) {
1281
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1282
+ const registry = {
1283
+ createDomain: async (domain, context)=>{
1284
+ const createdDomain = await createWithHooks({
1285
+ data: {
1286
+ ...domain,
1287
+ createdAt: new Date(),
1288
+ updatedAt: new Date()
1289
+ },
1290
+ model: 'domain',
1291
+ customFn: void 0,
1292
+ context
1293
+ });
1294
+ if (!createdDomain) throw new error_class_DoubleTieError('Failed to create domain - operation returned null', {
1295
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1296
+ status: 500
1297
+ });
1298
+ return createdDomain;
1299
+ },
1300
+ findOrCreateDomain: async function(name, context) {
1301
+ const existingDomain = await this.findDomainByName(name);
1302
+ if (existingDomain) return existingDomain;
1303
+ const domain = await this.createDomain({
1304
+ name,
1305
+ description: `Auto-created domain for ${name}`,
1306
+ isActive: true,
1307
+ isVerified: true,
1308
+ allowedOrigins: []
1309
+ }, context);
1310
+ if (!domain) throw new error_class_DoubleTieError('Failed to create domain', {
1311
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1312
+ status: 503
1313
+ });
1314
+ return domain;
1315
+ },
1316
+ findDomains: async (params = {})=>{
1317
+ const whereConditions = [];
1318
+ if (!params.includeInactive) whereConditions.push({
1319
+ field: 'isActive',
1320
+ value: true
1321
+ });
1322
+ if (params.name) whereConditions.push({
1323
+ field: 'name',
1324
+ value: params.name
1325
+ });
1326
+ const domains = await adapter.findMany({
1327
+ model: 'domain',
1328
+ where: whereConditions,
1329
+ sortBy: {
1330
+ field: 'name',
1331
+ direction: 'asc'
1332
+ }
1333
+ });
1334
+ return domains.map((domain)=>validateEntityOutput('domain', domain, ctx.options));
1335
+ },
1336
+ findDomain: async (name)=>{
1337
+ const domains = await registry.findDomains({
1338
+ name,
1339
+ includeInactive: false
1340
+ });
1341
+ return domains[0] || null;
1342
+ },
1343
+ findDomainByName: async (name)=>{
1344
+ const domain = await adapter.findOne({
1345
+ model: 'domain',
1346
+ where: [
1347
+ {
1348
+ field: 'name',
1349
+ value: name
1350
+ }
1351
+ ]
1352
+ });
1353
+ return domain ? validateEntityOutput('domain', domain, ctx.options) : null;
1354
+ }
1355
+ };
1356
+ return registry;
1357
+ }
1358
+ async function processHooks(data, model, operation, phase, hooks, context) {
1359
+ let currentData = {
1360
+ ...data
1361
+ };
1362
+ for (const hookSet of hooks){
1363
+ const modelHooks = hookSet[model];
1364
+ if (!modelHooks) continue;
1365
+ const operationHooks = modelHooks[operation];
1366
+ if (!operationHooks) continue;
1367
+ const hookFn = operationHooks[phase];
1368
+ if (hookFn) if ('before' === phase) {
1369
+ const result = await hookFn(currentData, context);
1370
+ if (result && 'object' == typeof result && 'kind' in result) switch(result.kind){
1371
+ case 'abort':
1372
+ return null;
1373
+ case 'transform':
1374
+ {
1375
+ const transformData = result.data;
1376
+ currentData = {
1377
+ ...currentData,
1378
+ ...transformData
1379
+ };
1380
+ break;
1381
+ }
1382
+ default:
1383
+ break;
1384
+ }
1385
+ } else await hookFn(currentData, context);
1753
1386
  }
1754
- async function processAfterHooksForMany(records, model, hooks, context) {
1755
- if (!records.length) return;
1756
- for (const record of records)await processHooks(record, model, 'update', 'after', hooks, context);
1387
+ return currentData;
1388
+ }
1389
+ async function processAfterHooksForMany(records, model, hooks, context) {
1390
+ if (!records.length) return;
1391
+ for (const record of records)await processHooks(record, model, 'update', 'after', hooks, context);
1392
+ }
1393
+ async function create_hooks_createWithHooks(adapter, ctx, props) {
1394
+ const { data, model, customFn, context } = props;
1395
+ const hooks = ctx.hooks || [];
1396
+ const transformedData = await processHooks(data, model, 'create', 'before', hooks, context);
1397
+ if (null === transformedData) return null;
1398
+ let created = null;
1399
+ if (customFn) {
1400
+ created = await customFn.fn(transformedData);
1401
+ if (!customFn.executeMainFn && created) return created;
1757
1402
  }
1758
- async function create_hooks_createWithHooks(adapter, ctx, props) {
1759
- const { data, model, customFn, context } = props;
1760
- const hooks = ctx.hooks || [];
1761
- const transformedData = await processHooks(data, model, 'create', 'before', hooks, context);
1762
- if (null === transformedData) return null;
1763
- let created = null;
1764
- if (customFn) {
1765
- created = await customFn.fn(transformedData);
1766
- if (!customFn.executeMainFn && created) return created;
1767
- }
1768
- if (!created) created = await adapter.create({
1769
- model: model,
1770
- data: transformedData
1771
- });
1772
- if (created) await processHooks(created, model, 'create', 'after', hooks, context);
1773
- return created;
1403
+ if (!created) created = await adapter.create({
1404
+ model: model,
1405
+ data: transformedData
1406
+ });
1407
+ if (created) await processHooks(created, model, 'create', 'after', hooks, context);
1408
+ return created;
1409
+ }
1410
+ async function update_hooks_updateWithHooks(adapter, ctx, props) {
1411
+ const { data, where, model, customFn, context } = props;
1412
+ const hooks = ctx.hooks || [];
1413
+ const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
1414
+ if (null === transformedData) return null;
1415
+ let updated = null;
1416
+ if (customFn) {
1417
+ const result = await customFn.fn(transformedData);
1418
+ updated = result;
1419
+ if (!customFn.executeMainFn && updated) return updated;
1774
1420
  }
1775
- async function update_hooks_updateWithHooks(adapter, ctx, props) {
1776
- const { data, where, model, customFn, context } = props;
1777
- const hooks = ctx.hooks || [];
1778
- const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
1779
- if (null === transformedData) return null;
1780
- let updated = null;
1781
- if (customFn) {
1782
- const result = await customFn.fn(transformedData);
1783
- updated = result;
1784
- if (!customFn.executeMainFn && updated) return updated;
1785
- }
1786
- if (!updated) updated = await adapter.update({
1421
+ if (!updated) updated = await adapter.update({
1422
+ model: model,
1423
+ update: transformedData,
1424
+ where
1425
+ });
1426
+ if (updated) await processHooks(updated, model, 'update', 'after', hooks, context);
1427
+ return updated;
1428
+ }
1429
+ async function executeCustomFunction(data, customFn) {
1430
+ if (!customFn) return {
1431
+ result: null,
1432
+ shouldContinue: true
1433
+ };
1434
+ const result = await customFn.fn(data);
1435
+ const shouldContinue = !result || !!customFn.executeMainFn;
1436
+ return {
1437
+ result,
1438
+ shouldContinue
1439
+ };
1440
+ }
1441
+ function processUpdateManyResult(result) {
1442
+ if (Array.isArray(result)) return result;
1443
+ if ('number' == typeof result && result > 0) return [];
1444
+ return null;
1445
+ }
1446
+ async function updateManyWithHooks(adapter, ctx, props) {
1447
+ const { data, where, model, customFn, context } = props;
1448
+ const hooks = ctx.hooks || [];
1449
+ const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
1450
+ if (null === transformedData) return null;
1451
+ const { result: customResult, shouldContinue } = await executeCustomFunction(transformedData, customFn);
1452
+ if (customResult && !shouldContinue) return customResult;
1453
+ let updated = customResult;
1454
+ if (!updated) {
1455
+ const adapterResult = await adapter.updateMany({
1787
1456
  model: model,
1788
1457
  update: transformedData,
1789
1458
  where
1790
1459
  });
1791
- if (updated) await processHooks(updated, model, 'update', 'after', hooks, context);
1792
- return updated;
1460
+ updated = processUpdateManyResult(adapterResult);
1793
1461
  }
1794
- async function executeCustomFunction(data, customFn) {
1795
- if (!customFn) return {
1796
- result: null,
1797
- shouldContinue: true
1798
- };
1799
- const result = await customFn.fn(data);
1800
- const shouldContinue = !result || !!customFn.executeMainFn;
1801
- return {
1802
- result,
1803
- shouldContinue
1804
- };
1805
- }
1806
- function processUpdateManyResult(result) {
1807
- if (Array.isArray(result)) return result;
1808
- if ('number' == typeof result && result > 0) return [];
1809
- return null;
1810
- }
1811
- async function updateManyWithHooks(adapter, ctx, props) {
1812
- const { data, where, model, customFn, context } = props;
1813
- const hooks = ctx.hooks || [];
1814
- const transformedData = await processHooks(data, model, 'update', 'before', hooks, context);
1815
- if (null === transformedData) return null;
1816
- const { result: customResult, shouldContinue } = await executeCustomFunction(transformedData, customFn);
1817
- if (customResult && !shouldContinue) return customResult;
1818
- let updated = customResult;
1819
- if (!updated) {
1820
- const adapterResult = await adapter.updateMany({
1821
- model: model,
1822
- update: transformedData,
1823
- where
1462
+ if (updated && updated.length > 0) await processAfterHooksForMany(updated, model, hooks, context);
1463
+ return updated;
1464
+ }
1465
+ function getWithHooks(adapter, ctx) {
1466
+ return {
1467
+ createWithHooks: ({ data, model, customFn, context })=>create_hooks_createWithHooks(adapter, ctx, {
1468
+ data,
1469
+ model,
1470
+ customFn,
1471
+ context
1472
+ }),
1473
+ updateWithHooks: (props)=>update_hooks_updateWithHooks(adapter, ctx, props),
1474
+ updateManyWithHooks: (props)=>updateManyWithHooks(adapter, ctx, props)
1475
+ };
1476
+ }
1477
+ function auditLogRegistry({ adapter, ...ctx }) {
1478
+ const { createWithHooks } = getWithHooks(adapter, ctx);
1479
+ return {
1480
+ createAuditLog: async (auditLog, context)=>{
1481
+ const createdLog = await createWithHooks({
1482
+ data: {
1483
+ createdAt: new Date(),
1484
+ ...auditLog
1485
+ },
1486
+ model: 'auditLog',
1487
+ customFn: void 0,
1488
+ context
1489
+ });
1490
+ if (!createdLog) throw new error_class_DoubleTieError('Failed to create audit log - operation returned null', {
1491
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1492
+ status: 500
1824
1493
  });
1825
- updated = processUpdateManyResult(adapterResult);
1494
+ return createdLog;
1826
1495
  }
1827
- if (updated && updated.length > 0) await processAfterHooksForMany(updated, model, hooks, context);
1828
- return updated;
1829
- }
1830
- function getWithHooks(adapter, ctx) {
1831
- return {
1832
- createWithHooks: ({ data, model, customFn, context })=>create_hooks_createWithHooks(adapter, ctx, {
1833
- data,
1834
- model,
1835
- customFn,
1836
- context
1837
- }),
1838
- updateWithHooks: (props)=>update_hooks_updateWithHooks(adapter, ctx, props),
1839
- updateManyWithHooks: (props)=>updateManyWithHooks(adapter, ctx, props)
1840
- };
1841
- }
1842
- function auditLogRegistry({ adapter, ...ctx }) {
1843
- const { createWithHooks } = getWithHooks(adapter, ctx);
1844
- return {
1845
- createAuditLog: async (auditLog, context)=>{
1846
- const createdLog = await createWithHooks({
1847
- data: {
1848
- createdAt: new Date(),
1849
- ...auditLog
1850
- },
1851
- model: 'auditLog',
1852
- customFn: void 0,
1853
- context
1854
- });
1855
- if (!createdLog) throw new error_class_DoubleTieError('Failed to create audit log - operation returned null', {
1856
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
1857
- status: 500
1858
- });
1859
- return createdLog;
1860
- }
1861
- };
1862
- }
1863
- const schemas = {
1864
- auditLog: auditLogSchema,
1865
- consent: consentSchema,
1866
- consentPolicy: consentPolicySchema,
1867
- consentPurpose: purposeSchema,
1868
- consentRecord: consentRecordSchema,
1869
- domain: domainSchema,
1870
- subject: subjectSchema
1871
1496
  };
1872
- })();
1497
+ }
1498
+ const schemas = {
1499
+ auditLog: auditLogSchema,
1500
+ consent: consentSchema,
1501
+ consentPolicy: consentPolicySchema,
1502
+ consentPurpose: purposeSchema,
1503
+ consentRecord: consentRecordSchema,
1504
+ domain: domainSchema,
1505
+ subject: subjectSchema
1506
+ };
1873
1507
  exports.PolicyTypeSchema = __webpack_exports__.PolicyTypeSchema;
1874
1508
  exports.auditLogRegistry = __webpack_exports__.auditLogRegistry;
1875
1509
  exports.auditLogSchema = __webpack_exports__.auditLogSchema;