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