@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,3 +1,11 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__ from "@doubletie/logger";
2
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_openapi_a95cc8e7__ from "@orpc/openapi";
3
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_openapi_fetch_89b49e61__ from "@orpc/openapi/fetch";
4
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_server_plugins_e445fd4f__ from "@orpc/server/plugins";
5
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_zod_716a28d4__ from "@orpc/zod";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_neverthrow__ from "neverthrow";
7
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__ from "@orpc/server";
8
+ import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__ from "@opentelemetry/api";
1
9
  import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_resources_c7ac8648__ from "@opentelemetry/resources";
2
10
  import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_sdk_node_50b75088__ from "@opentelemetry/sdk-node";
3
11
  import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_sdk_trace_base_5031a705__ from "@opentelemetry/sdk-trace-base";
@@ -5,372 +13,10 @@ import * as __WEBPACK_EXTERNAL_MODULE_defu__ from "defu";
5
13
  import * as __WEBPACK_EXTERNAL_MODULE_superjson__ from "superjson";
6
14
  import * as __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__ from "base-x";
7
15
  import * as __WEBPACK_EXTERNAL_MODULE_zod__ from "zod";
8
- import * as __WEBPACK_EXTERNAL_MODULE_neverthrow__ from "neverthrow";
9
- import * as __WEBPACK_EXTERNAL_MODULE_h3__ from "h3";
10
- import * as __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__ from "@opentelemetry/api";
11
16
  import * as __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__ from "node:crypto";
12
17
  import * as __WEBPACK_EXTERNAL_MODULE_kysely__ from "kysely";
13
18
  import "drizzle-orm";
14
- var __webpack_modules__ = {
15
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js": function(__unused_webpack_module, exports, __webpack_require__) {
16
- exports.ZodError = void 0;
17
- const util_1 = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js");
18
- util_1.util.arrayToEnum([
19
- "invalid_type",
20
- "invalid_literal",
21
- "custom",
22
- "invalid_union",
23
- "invalid_union_discriminator",
24
- "invalid_enum_value",
25
- "unrecognized_keys",
26
- "invalid_arguments",
27
- "invalid_return_type",
28
- "invalid_date",
29
- "invalid_string",
30
- "too_small",
31
- "too_big",
32
- "invalid_intersection_types",
33
- "not_multiple_of",
34
- "not_finite"
35
- ]);
36
- class ZodError extends Error {
37
- get errors() {
38
- return this.issues;
39
- }
40
- constructor(issues){
41
- super();
42
- this.issues = [];
43
- this.addIssue = (sub)=>{
44
- this.issues = [
45
- ...this.issues,
46
- sub
47
- ];
48
- };
49
- this.addIssues = (subs = [])=>{
50
- this.issues = [
51
- ...this.issues,
52
- ...subs
53
- ];
54
- };
55
- const actualProto = new.target.prototype;
56
- if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
57
- else this.__proto__ = actualProto;
58
- this.name = "ZodError";
59
- this.issues = issues;
60
- }
61
- format(_mapper) {
62
- const mapper = _mapper || function(issue) {
63
- return issue.message;
64
- };
65
- const fieldErrors = {
66
- _errors: []
67
- };
68
- const processError = (error)=>{
69
- for (const issue of error.issues)if ("invalid_union" === issue.code) issue.unionErrors.map(processError);
70
- else if ("invalid_return_type" === issue.code) processError(issue.returnTypeError);
71
- else if ("invalid_arguments" === issue.code) processError(issue.argumentsError);
72
- else if (0 === issue.path.length) fieldErrors._errors.push(mapper(issue));
73
- else {
74
- let curr = fieldErrors;
75
- let i = 0;
76
- while(i < issue.path.length){
77
- const el = issue.path[i];
78
- const terminal = i === issue.path.length - 1;
79
- if (terminal) {
80
- curr[el] = curr[el] || {
81
- _errors: []
82
- };
83
- curr[el]._errors.push(mapper(issue));
84
- } else curr[el] = curr[el] || {
85
- _errors: []
86
- };
87
- curr = curr[el];
88
- i++;
89
- }
90
- }
91
- };
92
- processError(this);
93
- return fieldErrors;
94
- }
95
- static assert(value) {
96
- if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
97
- }
98
- toString() {
99
- return this.message;
100
- }
101
- get message() {
102
- return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2);
103
- }
104
- get isEmpty() {
105
- return 0 === this.issues.length;
106
- }
107
- flatten(mapper = (issue)=>issue.message) {
108
- const fieldErrors = {};
109
- const formErrors = [];
110
- for (const sub of this.issues)if (sub.path.length > 0) {
111
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
112
- fieldErrors[sub.path[0]].push(mapper(sub));
113
- } else formErrors.push(mapper(sub));
114
- return {
115
- formErrors,
116
- fieldErrors
117
- };
118
- }
119
- get formErrors() {
120
- return this.flatten();
121
- }
122
- }
123
- exports.ZodError = ZodError;
124
- ZodError.create = (issues)=>{
125
- const error = new ZodError(issues);
126
- return error;
127
- };
128
- },
129
- "../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/helpers/util.js": function(__unused_webpack_module, exports) {
130
- Object.defineProperty(exports, "__esModule", {
131
- value: true
132
- });
133
- exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0;
134
- var util;
135
- (function(util) {
136
- util.assertEqual = (val)=>val;
137
- function assertIs(_arg) {}
138
- util.assertIs = assertIs;
139
- function assertNever(_x) {
140
- throw new Error();
141
- }
142
- util.assertNever = assertNever;
143
- util.arrayToEnum = (items)=>{
144
- const obj = {};
145
- for (const item of items)obj[item] = item;
146
- return obj;
147
- };
148
- util.getValidEnumValues = (obj)=>{
149
- const validKeys = util.objectKeys(obj).filter((k)=>"number" != typeof obj[obj[k]]);
150
- const filtered = {};
151
- for (const k of validKeys)filtered[k] = obj[k];
152
- return util.objectValues(filtered);
153
- };
154
- util.objectValues = (obj)=>util.objectKeys(obj).map(function(e) {
155
- return obj[e];
156
- });
157
- util.objectKeys = "function" == typeof Object.keys ? (obj)=>Object.keys(obj) : (object)=>{
158
- const keys = [];
159
- for(const key in object)if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
160
- return keys;
161
- };
162
- util.find = (arr, checker)=>{
163
- for (const item of arr)if (checker(item)) return item;
164
- };
165
- util.isInteger = "function" == typeof Number.isInteger ? (val)=>Number.isInteger(val) : (val)=>"number" == typeof val && isFinite(val) && Math.floor(val) === val;
166
- function joinValues(array, separator = " | ") {
167
- return array.map((val)=>"string" == typeof val ? `'${val}'` : val).join(separator);
168
- }
169
- util.joinValues = joinValues;
170
- util.jsonStringifyReplacer = (_, value)=>{
171
- if ("bigint" == typeof value) return value.toString();
172
- return value;
173
- };
174
- })(util || (exports.util = util = {}));
175
- var objectUtil;
176
- (function(objectUtil) {
177
- objectUtil.mergeShapes = (first, second)=>({
178
- ...first,
179
- ...second
180
- });
181
- })(objectUtil || (exports.objectUtil = objectUtil = {}));
182
- exports.ZodParsedType = util.arrayToEnum([
183
- "string",
184
- "nan",
185
- "number",
186
- "integer",
187
- "float",
188
- "boolean",
189
- "date",
190
- "bigint",
191
- "symbol",
192
- "function",
193
- "undefined",
194
- "null",
195
- "array",
196
- "object",
197
- "unknown",
198
- "promise",
199
- "void",
200
- "never",
201
- "map",
202
- "set"
203
- ]);
204
- const getParsedType = (data)=>{
205
- const t = typeof data;
206
- switch(t){
207
- case "undefined":
208
- return exports.ZodParsedType.undefined;
209
- case "string":
210
- return exports.ZodParsedType.string;
211
- case "number":
212
- return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number;
213
- case "boolean":
214
- return exports.ZodParsedType.boolean;
215
- case "function":
216
- return exports.ZodParsedType.function;
217
- case "bigint":
218
- return exports.ZodParsedType.bigint;
219
- case "symbol":
220
- return exports.ZodParsedType.symbol;
221
- case "object":
222
- if (Array.isArray(data)) return exports.ZodParsedType.array;
223
- if (null === data) return exports.ZodParsedType.null;
224
- if (data.then && "function" == typeof data.then && data.catch && "function" == typeof data.catch) return exports.ZodParsedType.promise;
225
- if ("undefined" != typeof Map && data instanceof Map) return exports.ZodParsedType.map;
226
- if ("undefined" != typeof Set && data instanceof Set) return exports.ZodParsedType.set;
227
- if ("undefined" != typeof Date && data instanceof Date) return exports.ZodParsedType.date;
228
- return exports.ZodParsedType.object;
229
- default:
230
- return exports.ZodParsedType.unknown;
231
- }
232
- };
233
- exports.getParsedType = getParsedType;
234
- }
235
- };
236
- var __webpack_module_cache__ = {};
237
- function __webpack_require__(moduleId) {
238
- var cachedModule = __webpack_module_cache__[moduleId];
239
- if (void 0 !== cachedModule) return cachedModule.exports;
240
- var module = __webpack_module_cache__[moduleId] = {
241
- exports: {}
242
- };
243
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
244
- return module.exports;
245
- }
246
- (()=>{
247
- __webpack_require__.r = (exports)=>{
248
- if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
249
- value: 'Module'
250
- });
251
- Object.defineProperty(exports, '__esModule', {
252
- value: true
253
- });
254
- };
255
- })();
256
- var pkgs_types_namespaceObject = {};
257
- __webpack_require__.r(pkgs_types_namespaceObject);
258
- function utils_applyDefaultValue(inputValue, field, operation) {
259
- if ('update' === operation) return inputValue;
260
- if (null == inputValue && field.defaultValue) {
261
- if ('function' == typeof field.defaultValue) return field.defaultValue();
262
- return field.defaultValue;
263
- }
264
- return inputValue;
265
- }
266
- const COMMON_TIMEZONES = {
267
- UTC: 'UTC',
268
- GMT: 'GMT',
269
- EASTERN: 'America/New_York',
270
- CENTRAL: 'America/Chicago',
271
- MOUNTAIN: 'America/Denver',
272
- PACIFIC: 'America/Los_Angeles',
273
- LONDON: 'Europe/London',
274
- PARIS: 'Europe/Paris',
275
- BERLIN: 'Europe/Berlin',
276
- TOKYO: 'Asia/Tokyo',
277
- SHANGHAI: 'Asia/Shanghai',
278
- SINGAPORE: 'Asia/Singapore',
279
- SYDNEY: 'Australia/Sydney',
280
- SAO_PAULO: 'America/Sao_Paulo'
281
- };
282
- const b58 = (0, __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__["default"])('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
283
- function id_generator_generateId(prefix) {
284
- const buf = crypto.getRandomValues(new Uint8Array(20));
285
- const EPOCH_TIMESTAMP = 1700000000000;
286
- const t = Date.now() - EPOCH_TIMESTAMP;
287
- const high = Math.floor(t / 0x100000000);
288
- const low = t >>> 0;
289
- buf[0] = high >>> 24 & 255;
290
- buf[1] = high >>> 16 & 255;
291
- buf[2] = high >>> 8 & 255;
292
- buf[3] = 255 & high;
293
- buf[4] = low >>> 24 & 255;
294
- buf[5] = low >>> 16 & 255;
295
- buf[6] = low >>> 8 & 255;
296
- buf[7] = 255 & low;
297
- return `${prefix}_${b58.encode(buf)}`;
298
- }
299
- const fieldConfigSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
300
- required: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
301
- returned: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
302
- input: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
303
- defaultValue: __WEBPACK_EXTERNAL_MODULE_zod__.z.union([
304
- __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
305
- __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
306
- ]).optional(),
307
- transform: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
308
- input: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
309
- __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
310
- __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
311
- ])).optional(),
312
- output: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
313
- __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
314
- __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
315
- ])).optional()
316
- }).optional(),
317
- validator: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
318
- __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
319
- __WEBPACK_EXTERNAL_MODULE_zod__.z["null"]()
320
- ])).optional(),
321
- unique: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
322
- indexed: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
323
- sortable: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
324
- fieldName: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
325
- bigint: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
326
- });
327
- const stringFieldSchema = fieldConfigSchema.extend({
328
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string'),
329
- minLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
330
- maxLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
331
- pattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
332
- });
333
- const numberFieldSchema = fieldConfigSchema.extend({
334
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number'),
335
- min: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
336
- max: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional()
337
- });
338
- const booleanFieldSchema = fieldConfigSchema.extend({
339
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('boolean')
340
- });
341
- const dateFieldSchema = fieldConfigSchema.extend({
342
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('date'),
343
- minDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
344
- maxDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
345
- dateOnly: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false),
346
- format: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
347
- });
348
- const timezoneFieldSchema = fieldConfigSchema.extend({
349
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('timezone'),
350
- validateTimezone: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
351
- suggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional(),
352
- restrictToSuggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
353
- });
354
- const jsonFieldSchema = fieldConfigSchema.extend({
355
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('json'),
356
- validateJson: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true)
357
- });
358
- const stringArrayFieldSchema = fieldConfigSchema.extend({
359
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string[]')
360
- });
361
- const numberArrayFieldSchema = fieldConfigSchema.extend({
362
- type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number[]')
363
- });
364
- __WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
365
- stringFieldSchema,
366
- numberFieldSchema,
367
- booleanFieldSchema,
368
- dateFieldSchema,
369
- timezoneFieldSchema,
370
- jsonFieldSchema,
371
- stringArrayFieldSchema,
372
- numberArrayFieldSchema
373
- ]);
19
+ import * as __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__ from "@orpc/contract";
374
20
  const error_codes_ERROR_CODES = Object.freeze({
375
21
  NOT_FOUND: 'Resource not found',
376
22
  BAD_REQUEST: 'Bad request',
@@ -436,10 +82,10 @@ async function tracing_withSpan(name, fn, attributes = {}) {
436
82
  }
437
83
  });
438
84
  }
439
- class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error {
440
- code;
85
+ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError {
441
86
  category;
442
87
  meta;
88
+ statusCode;
443
89
  constructor(message, options = {
444
90
  code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
445
91
  status: 500,
@@ -447,22 +93,18 @@ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error
447
93
  cause: void 0,
448
94
  meta: {}
449
95
  }){
450
- super(message, {
451
- cause: options.cause
96
+ super(options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR, {
97
+ message,
98
+ cause: options.cause,
99
+ data: options.meta ?? {}
452
100
  });
453
- this.name = this.constructor.name;
454
- this.code = options.code ?? error_codes_ERROR_CODES.UNKNOWN_ERROR;
455
- this.statusCode = options.status ?? 500;
101
+ this.name = 'DoubleTieError';
456
102
  this.category = options.category ?? ERROR_CATEGORIES.UNEXPECTED;
457
103
  this.meta = options.meta ?? {};
458
- this.data = {
459
- code: this.code,
460
- category: this.category,
461
- meta: this.meta
462
- };
104
+ this.statusCode = options.status ?? 500;
463
105
  tracing_withSpan('create_doubletie_error', async (span)=>{
464
106
  span.setAttributes({
465
- 'error.name': this.name,
107
+ 'error.name': this.constructor.name,
466
108
  'error.message': message,
467
109
  'error.code': this.code,
468
110
  'error.status': this.statusCode,
@@ -482,11 +124,11 @@ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error
482
124
  const validationErrorMessage = this.meta?.validationErrors ? String(this.meta.validationErrors) : void 0;
483
125
  const stackTrace = this.stack ? this.stack.split('\n').map((line)=>line.trim()).filter((line)=>line && !line.includes('Error: ')) : [];
484
126
  return {
485
- statusCode: this.statusCode,
127
+ code: this.code,
486
128
  message: validationErrorMessage || this.message,
487
- statusMessage: this.statusMessage,
129
+ status: this.statusCode,
130
+ defined: true,
488
131
  data: {
489
- code: this.code,
490
132
  category: this.category,
491
133
  meta: this.meta,
492
134
  ...'production' === process.env.NODE_ENV ? {} : {
@@ -537,7 +179,9 @@ class error_class_DoubleTieError extends __WEBPACK_EXTERNAL_MODULE_h3__.H3Error
537
179
  const ErrorSubclass = class extends error_class_DoubleTieError {
538
180
  constructor(message, options){
539
181
  super(message, options);
540
- this.name = name;
182
+ Object.defineProperty(this, 'name', {
183
+ value: name
184
+ });
541
185
  }
542
186
  };
543
187
  Object.defineProperty(ErrorSubclass, 'name', {
@@ -604,94 +248,6 @@ function promiseToResult(promise, errorCode = error_codes_ERROR_CODES.UNKNOWN_ER
604
248
  return result;
605
249
  });
606
250
  }
607
- const validationPipeline = (schema, transformer)=>(data)=>{
608
- const preprocessData = (value)=>{
609
- if ('object' != typeof value || null === value) {
610
- if ('string' == typeof value) try {
611
- if (value.startsWith('[') && value.endsWith(']')) return JSON.parse(value);
612
- if ('true' === value.toLowerCase()) return true;
613
- if ('false' === value.toLowerCase()) return false;
614
- if (value.startsWith('{') && value.endsWith('}')) return JSON.parse(value);
615
- } catch {}
616
- return value;
617
- }
618
- if (Array.isArray(value)) return value.map(preprocessData);
619
- const processed = {};
620
- for (const [key, val] of Object.entries(value))processed[key] = preprocessData(val);
621
- return processed;
622
- };
623
- const preprocessedData = preprocessData(data);
624
- const parseResult = schema.safeParse(preprocessedData);
625
- if (!parseResult.success) return fail('Validation failed', {
626
- code: error_codes_ERROR_CODES.INVALID_REQUEST,
627
- status: 400,
628
- meta: {
629
- validationErrors: parseResult.error.issues
630
- }
631
- });
632
- try {
633
- return (0, __WEBPACK_EXTERNAL_MODULE_neverthrow__.ok)(transformer(parseResult.data));
634
- } catch (error) {
635
- return fail('Error transforming data after validation', {
636
- code: error_codes_ERROR_CODES.BAD_REQUEST,
637
- status: 400,
638
- cause: error instanceof Error ? error : void 0,
639
- meta: {
640
- inputData: parseResult.data
641
- }
642
- });
643
- }
644
- };
645
- function createH3ErrorHandler() {
646
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)((event)=>{
647
- event.context._onError = (error)=>{
648
- event.context.logger.error('Error in H3 error handler', {
649
- error
650
- });
651
- if (error instanceof error_class_DoubleTieError) {
652
- event.context.logger.error('Handling DoubleTieError:', error.statusCode, error.message);
653
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, error);
654
- }
655
- event.context.logger.error('Handling generic error', {
656
- error
657
- });
658
- const dtError = new error_class_DoubleTieError(error instanceof Error ? error.message : String(error), {
659
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
660
- status: 500,
661
- cause: error instanceof Error ? error : void 0
662
- });
663
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, dtError);
664
- };
665
- event.node.req.on('error', (err)=>{
666
- event.context.logger.error('Request error event triggered:', {
667
- err
668
- });
669
- if (event.context._onError) event.context._onError(err);
670
- });
671
- });
672
- }
673
- function withH3ErrorHandling(handler) {
674
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)(async (event)=>{
675
- try {
676
- return await handler(event);
677
- } catch (error) {
678
- event.context.logger.error('Error caught in withH3ErrorHandling:', {
679
- error
680
- });
681
- if (error instanceof error_class_DoubleTieError) {
682
- event.context.logger.error('Handling DoubleTieError in wrapper:', error.statusCode, error.message);
683
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, error);
684
- }
685
- if (event.context._onError && 'function' == typeof event.context._onError) return event.context._onError(error);
686
- const dtError = new error_class_DoubleTieError(error instanceof Error ? error.message : String(error), {
687
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
688
- status: 500,
689
- cause: error instanceof Error ? error : void 0
690
- });
691
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendError)(event, dtError);
692
- }
693
- });
694
- }
695
251
  function createTelemetryOptions(appName = 'c15t', telemetryConfig) {
696
252
  const serviceVersion = process.env.npm_package_version || '1.0.0';
697
253
  const config = {
@@ -705,138 +261,123 @@ function createTelemetryOptions(appName = 'c15t', telemetryConfig) {
705
261
  };
706
262
  return config;
707
263
  }
708
- var ZodError = __webpack_require__("../../node_modules/.pnpm/zod@3.24.2/node_modules/zod/lib/ZodError.js");
709
- const levels = [
710
- 'error',
711
- 'warn',
712
- 'info',
713
- 'success',
714
- 'debug'
715
- ];
716
- function shouldPublishLog(currentLogLevel, logLevel) {
717
- const currentLevelIndex = levels.indexOf(currentLogLevel);
718
- const messageLevelIndex = levels.indexOf(logLevel);
719
- if ('debug' === currentLogLevel) return 'debug' === logLevel;
720
- return messageLevelIndex <= currentLevelIndex;
721
- }
722
- const colors = {
723
- reset: '\x1b[0m',
724
- bright: '\x1b[1m',
725
- dim: '\x1b[2m',
726
- underscore: '\x1b[4m',
727
- blink: '\x1b[5m',
728
- reverse: '\x1b[7m',
729
- hidden: '\x1b[8m',
730
- fg: {
731
- black: '\x1b[30m',
732
- red: '\x1b[31m',
733
- green: '\x1b[32m',
734
- yellow: '\x1b[33m',
735
- blue: '\x1b[34m',
736
- magenta: '\x1b[35m',
737
- cyan: '\x1b[36m',
738
- white: '\x1b[37m'
739
- },
740
- bg: {
741
- black: '\x1b[40m',
742
- red: '\x1b[41m',
743
- green: '\x1b[42m',
744
- yellow: '\x1b[43m',
745
- blue: '\x1b[44m',
746
- magenta: '\x1b[45m',
747
- cyan: '\x1b[46m',
748
- white: '\x1b[47m'
749
- }
750
- };
751
- const levelColors = {
752
- info: colors.fg.blue,
753
- success: colors.fg.green,
754
- warn: colors.fg.yellow,
755
- error: colors.fg.red,
756
- debug: colors.fg.magenta
757
- };
758
- const formatMessage = (level, message, appName = 'c15t')=>{
759
- const timestamp = new Date().toISOString();
760
- return `${colors.dim}${timestamp}${colors.reset} ${levelColors[level]}${level.toUpperCase()}${colors.reset} ${colors.bright}[${appName}]:${colors.reset} ${message}`;
761
- };
762
- const LOGGER_TRACER_NAME = '@doubletie/logger';
763
- const LOG_LEVEL_TO_SPAN_STATUS = {
764
- error: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
765
- warn: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK,
766
- info: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK,
767
- success: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK,
768
- debug: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK
769
- };
770
- const telemetry_getTracer = (options)=>{
771
- if (options?.telemetry?.tracer) return options.telemetry.tracer;
772
- return __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.trace.getTracer(LOGGER_TRACER_NAME);
773
- };
774
- const createLogSpan = (level, message, args = [], options)=>{
775
- if (options?.telemetry?.disabled) return null;
776
- const tracer = telemetry_getTracer(options);
777
- const span = tracer.startSpan('log_entry', {
778
- attributes: {
779
- 'log.level': level,
780
- 'log.message': message,
781
- 'log.has_args': args.length > 0,
782
- ...options?.telemetry?.defaultAttributes || {}
783
- }
784
- });
785
- if (args.length > 0 && 'object' == typeof args[0] && null !== args[0]) {
786
- const data = args[0];
787
- for (const [key, value] of Object.entries(data))if (null != value) span.setAttribute(`log.data.${key}`, String(value));
264
+ var package_namespaceObject = JSON.parse('{"i8":"1.2.0-canary.0"}');
265
+ function utils_applyDefaultValue(inputValue, field, operation) {
266
+ if ('update' === operation) return inputValue;
267
+ if (null == inputValue && field.defaultValue) {
268
+ if ('function' == typeof field.defaultValue) return field.defaultValue();
269
+ return field.defaultValue;
788
270
  }
789
- span.setStatus({
790
- code: LOG_LEVEL_TO_SPAN_STATUS[level],
791
- message: 'error' === level || 'warn' === level ? message : void 0
792
- });
793
- return span;
271
+ return inputValue;
272
+ }
273
+ const COMMON_TIMEZONES = {
274
+ UTC: 'UTC',
275
+ GMT: 'GMT',
276
+ EASTERN: 'America/New_York',
277
+ CENTRAL: 'America/Chicago',
278
+ MOUNTAIN: 'America/Denver',
279
+ PACIFIC: 'America/Los_Angeles',
280
+ LONDON: 'Europe/London',
281
+ PARIS: 'Europe/Paris',
282
+ BERLIN: 'Europe/Berlin',
283
+ TOKYO: 'Asia/Tokyo',
284
+ SHANGHAI: 'Asia/Shanghai',
285
+ SINGAPORE: 'Asia/Singapore',
286
+ SYDNEY: 'Australia/Sydney',
287
+ SAO_PAULO: 'America/Sao_Paulo'
794
288
  };
795
- const withLogSpan = async (level, message, args, operation, options)=>{
796
- const span = createLogSpan(level, message, args, options);
797
- if (!span) return operation();
798
- try {
799
- const result = await operation();
800
- return result;
801
- } catch (error) {
802
- span.setStatus({
803
- code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
804
- message: error instanceof Error ? error.message : String(error)
805
- });
806
- throw error;
807
- } finally{
808
- span.end();
809
- }
810
- };
811
- const createLogger = (options)=>{
812
- if (options && 'object' == typeof options && levels.every((level)=>'function' == typeof options[level])) return options;
813
- const loggerOptions = options;
814
- const enabled = loggerOptions?.disabled !== true;
815
- const logLevel = loggerOptions?.level ?? 'error';
816
- const appName = loggerOptions?.appName ?? 'c15t';
817
- const logFunc = async (level, message, args = [])=>{
818
- if (!enabled || !shouldPublishLog(logLevel, level)) return;
819
- await withLogSpan(level, message, args, async ()=>{
820
- const formattedMessage = formatMessage(level, message, appName);
821
- if (!loggerOptions || 'function' != typeof loggerOptions.log) {
822
- if ('error' === level) console.error(formattedMessage, ...args);
823
- else if ('warn' === level) console.warn(formattedMessage, ...args);
824
- else if ('info' === level) console.log(formattedMessage, ...args);
825
- else if ('debug' === level) console.debug(formattedMessage, ...args);
826
- else if ('success' === level) console.log(formattedMessage, ...args);
827
- return;
828
- }
829
- loggerOptions.log('success' === level ? 'info' : level, message, ...args);
830
- });
831
- };
832
- return Object.fromEntries(levels.map((level)=>[
833
- level,
834
- (...[message, ...args])=>logFunc(level, message, args).catch((error)=>{
835
- console.error('Logger error:', error);
836
- })
837
- ]));
838
- };
839
- const logger_factory_logger = createLogger();
289
+ const b58 = (0, __WEBPACK_EXTERNAL_MODULE_base_x_aeb88370__["default"])('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
290
+ function id_generator_generateId(prefix) {
291
+ const buf = crypto.getRandomValues(new Uint8Array(20));
292
+ const EPOCH_TIMESTAMP = 1700000000000;
293
+ const t = Date.now() - EPOCH_TIMESTAMP;
294
+ const high = Math.floor(t / 0x100000000);
295
+ const low = t >>> 0;
296
+ buf[0] = high >>> 24 & 255;
297
+ buf[1] = high >>> 16 & 255;
298
+ buf[2] = high >>> 8 & 255;
299
+ buf[3] = 255 & high;
300
+ buf[4] = low >>> 24 & 255;
301
+ buf[5] = low >>> 16 & 255;
302
+ buf[6] = low >>> 8 & 255;
303
+ buf[7] = 255 & low;
304
+ return `${prefix}_${b58.encode(buf)}`;
305
+ }
306
+ const fieldConfigSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
307
+ required: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
308
+ returned: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
309
+ input: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
310
+ defaultValue: __WEBPACK_EXTERNAL_MODULE_zod__.z.union([
311
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
312
+ __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
313
+ ]).optional(),
314
+ transform: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
315
+ input: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
316
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
317
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
318
+ ])).optional(),
319
+ output: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
320
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.any(),
321
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.promise(__WEBPACK_EXTERNAL_MODULE_zod__.z.any())
322
+ ])).optional()
323
+ }).optional(),
324
+ validator: __WEBPACK_EXTERNAL_MODULE_zod__.z["function"]().args(__WEBPACK_EXTERNAL_MODULE_zod__.z.any()).returns(__WEBPACK_EXTERNAL_MODULE_zod__.z.union([
325
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
326
+ __WEBPACK_EXTERNAL_MODULE_zod__.z["null"]()
327
+ ])).optional(),
328
+ unique: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
329
+ indexed: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional(),
330
+ sortable: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
331
+ fieldName: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
332
+ bigint: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
333
+ });
334
+ const stringFieldSchema = fieldConfigSchema.extend({
335
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string'),
336
+ minLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
337
+ maxLength: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
338
+ pattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
339
+ });
340
+ const numberFieldSchema = fieldConfigSchema.extend({
341
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number'),
342
+ min: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional(),
343
+ max: __WEBPACK_EXTERNAL_MODULE_zod__.z.number().optional()
344
+ });
345
+ const booleanFieldSchema = fieldConfigSchema.extend({
346
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('boolean')
347
+ });
348
+ const dateFieldSchema = fieldConfigSchema.extend({
349
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('date'),
350
+ minDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
351
+ maxDate: __WEBPACK_EXTERNAL_MODULE_zod__.z.date().optional(),
352
+ dateOnly: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false),
353
+ format: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
354
+ });
355
+ const timezoneFieldSchema = fieldConfigSchema.extend({
356
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('timezone'),
357
+ validateTimezone: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true),
358
+ suggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional(),
359
+ restrictToSuggestedValues: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(false)
360
+ });
361
+ const jsonFieldSchema = fieldConfigSchema.extend({
362
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('json'),
363
+ validateJson: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().default(true)
364
+ });
365
+ const stringArrayFieldSchema = fieldConfigSchema.extend({
366
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('string[]')
367
+ });
368
+ const numberArrayFieldSchema = fieldConfigSchema.extend({
369
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('number[]')
370
+ });
371
+ __WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
372
+ stringFieldSchema,
373
+ numberFieldSchema,
374
+ booleanFieldSchema,
375
+ dateFieldSchema,
376
+ timezoneFieldSchema,
377
+ jsonFieldSchema,
378
+ stringArrayFieldSchema,
379
+ numberArrayFieldSchema
380
+ ]);
840
381
  const schema_auditLogSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
841
382
  id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
842
383
  entityType: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
@@ -1442,7 +983,7 @@ function validateEntityOutput(tableName, data, options) {
1442
983
  try {
1443
984
  return table.schema.parse(processedData);
1444
985
  } catch (error) {
1445
- if (error instanceof ZodError.ZodError) logger_factory_logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
986
+ if (error instanceof __WEBPACK_EXTERNAL_MODULE_zod__.ZodError) __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.logger.error(`[validateEntityOutput] Validation failed for table ${String(tableName)}`, {
1446
987
  table,
1447
988
  issues: error.issues
1448
989
  });
@@ -2567,9 +2108,23 @@ const memoryAdapter = (db)=>(options)=>{
2567
2108
  }
2568
2109
  };
2569
2110
  };
2111
+ let globalLogger;
2112
+ function getLogger(options) {
2113
+ if (!globalLogger) globalLogger = (0, __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.createLogger)({
2114
+ level: 'info',
2115
+ appName: 'c15t',
2116
+ ...options
2117
+ });
2118
+ return globalLogger;
2119
+ }
2120
+ function initLogger(options) {
2121
+ globalLogger = (0, __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.createLogger)(options);
2122
+ return globalLogger;
2123
+ }
2570
2124
  async function getAdapter(options) {
2571
- const logger = createLogger({
2572
- appName: 'c15t'
2125
+ const logger = getLogger({
2126
+ appName: options.appName ?? 'c15t',
2127
+ ...options.logger
2573
2128
  });
2574
2129
  if (!options.database) {
2575
2130
  const tables = definition_getConsentTables(options);
@@ -2639,7 +2194,7 @@ const init = async (options)=>{
2639
2194
  const basePathStr = options.basePath;
2640
2195
  const databaseHooks = options.databaseHooks || [];
2641
2196
  const appName = options.appName || 'c15t';
2642
- const logger = createLogger({
2197
+ const logger = initLogger({
2643
2198
  ...loggerOptions,
2644
2199
  appName: String(appName)
2645
2200
  });
@@ -2655,7 +2210,7 @@ const init = async (options)=>{
2655
2210
  } else {
2656
2211
  const resource = new __WEBPACK_EXTERNAL_MODULE__opentelemetry_resources_c7ac8648__.Resource({
2657
2212
  'service.name': String(appName),
2658
- 'service.version': String(process.env.npm_package_version || '1.0.0'),
2213
+ 'service.version': String(package_namespaceObject.i8 || '1.0.0'),
2659
2214
  ...telemetryOptions?.defaultAttributes || {}
2660
2215
  });
2661
2216
  logger.debug('Initializing telemetry with resource attributes', {
@@ -2728,7 +2283,7 @@ const init = async (options)=>{
2728
2283
  return runPluginInit(ctx);
2729
2284
  });
2730
2285
  } catch (error) {
2731
- const errorLogger = createLogger(options.logger);
2286
+ const errorLogger = getLogger(options.logger);
2732
2287
  errorLogger.error('Initialization failed', {
2733
2288
  error: error instanceof Error ? error.message : String(error),
2734
2289
  stack: error instanceof Error ? error.stack : void 0
@@ -2774,167 +2329,116 @@ function getInternalPlugins(_options) {
2774
2329
  const plugins = [];
2775
2330
  return plugins;
2776
2331
  }
2777
- function defineRoute(pathOrConfig, handlerOrUndefined, options) {
2778
- if ('string' == typeof pathOrConfig && handlerOrUndefined) return {
2779
- path: pathOrConfig,
2780
- handler: handlerOrUndefined,
2781
- options
2782
- };
2783
- const config = pathOrConfig;
2784
- const handler = (0, __WEBPACK_EXTERNAL_MODULE_h3__.defineEventHandler)(async (event)=>{
2785
- const logger = event.context.logger || createLogger();
2786
- logger.debug(`Handling request for ${config.method} ${config.path}`);
2787
- if (!event.context.logger) event.context.logger = logger;
2788
- const validated = {
2789
- body: void 0,
2790
- query: void 0,
2791
- params: void 0
2792
- };
2793
- try {
2794
- if (config.validations?.body) {
2795
- const contentType = event.headers.get('content-type');
2796
- const body = contentType?.includes('multipart/form-data') ? Object.fromEntries(await (0, __WEBPACK_EXTERNAL_MODULE_h3__.readFormData)(event)) : await (0, __WEBPACK_EXTERNAL_MODULE_h3__.readBody)(event);
2797
- logger.debug('Validating request body', {
2798
- body
2799
- });
2800
- const validateBody = validationPipeline(config.validations.body, (data)=>data);
2801
- const result = await validateBody(body);
2802
- result.match((data)=>{
2803
- validated.body = data;
2804
- }, (error)=>{
2805
- logger.error('Validation error (body)', {
2806
- error
2807
- });
2808
- throw new error_class_DoubleTieError('Body validation failed', {
2809
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2810
- status: 422,
2811
- cause: error instanceof Error ? error : void 0,
2812
- meta: {
2813
- validationErrors: error,
2814
- requestPath: config.path,
2815
- requestMethod: config.method
2816
- }
2817
- });
2818
- });
2819
- }
2820
- if (config.validations?.query) {
2821
- const query = getQuery(event);
2822
- logger.debug('Validating query parameters', {
2823
- query
2824
- });
2825
- const validateQuery = validationPipeline(config.validations.query, (data)=>data);
2826
- const result = await validateQuery(query);
2827
- result.match((data)=>{
2828
- validated.query = data;
2829
- }, (error)=>{
2830
- logger.error('Query validation failed', {
2831
- error
2832
- });
2833
- throw new error_class_DoubleTieError('Query validation failed', {
2834
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2835
- status: 422,
2836
- cause: error instanceof Error ? error : void 0,
2837
- meta: {
2838
- validationErrors: error,
2839
- requestPath: config.path,
2840
- requestMethod: config.method
2841
- }
2842
- });
2843
- });
2844
- }
2845
- if (config.validations?.params) {
2846
- const params = getRouterParams(event);
2847
- logger.debug('Validating route parameters', {
2848
- params
2849
- });
2850
- const validateParams = validationPipeline(config.validations.params, (data)=>data);
2851
- const result = await validateParams(params);
2852
- result.match((data)=>{
2853
- validated.params = data;
2854
- }, (error)=>{
2855
- logger.error('Path parameters validation failed', {
2856
- error
2857
- });
2858
- throw new error_class_DoubleTieError('Path parameters validation failed', {
2859
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2860
- status: 422,
2861
- cause: error instanceof Error ? error : void 0,
2862
- meta: {
2863
- validationErrors: error,
2864
- requestPath: config.path,
2865
- requestMethod: config.method
2866
- }
2867
- });
2868
- });
2869
- }
2870
- const eventWithContext = event;
2871
- eventWithContext.context = {
2872
- ...event.context,
2873
- validated
2874
- };
2875
- logger.debug(`Executing handler for ${config.method} ${config.path}`);
2876
- const response = await config.handler(eventWithContext);
2877
- logger.debug(`Handler execution complete for ${config.method} ${config.path}, response type: ${typeof response}`);
2878
- if (null == response) {
2879
- logger.warn(`Handler for ${config.method} ${config.path} returned ${null === response ? 'null' : 'undefined'}`);
2880
- return {};
2881
- }
2882
- if ('boolean' == typeof response || 'number' == typeof response || 'string' == typeof response) {
2883
- logger.warn(`Handler for ${config.method} ${config.path} returned primitive ${typeof response}, wrapping in object`);
2884
- return {
2885
- value: response
2886
- };
2887
- }
2888
- return response;
2889
- } catch (error) {
2890
- if (error instanceof error_class_DoubleTieError) throw error;
2891
- logger.error('Validation failed', {
2892
- error
2893
- });
2894
- let validationErrors = 'Unknown validation error';
2895
- let statusCode = 422;
2896
- if (error instanceof Error) {
2897
- validationErrors = error.message;
2898
- if ('ZodError' === error.name && 'format' in error && 'function' == typeof error.format) try {
2899
- validationErrors = error.format();
2900
- statusCode = 422;
2901
- } catch {
2902
- validationErrors = `Validation error: ${error.message}`;
2903
- }
2904
- }
2905
- logger.error('Validation failed', {
2906
- error,
2907
- validationErrors
2908
- });
2909
- throw new error_class_DoubleTieError('Validation failed', {
2910
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2911
- status: statusCode,
2912
- cause: error instanceof Error ? error : void 0,
2913
- meta: {
2914
- validationErrors,
2915
- requestPath: config.path,
2916
- requestMethod: config.method
2917
- }
2918
- });
2332
+ const API_ROUTER_TRACER_NAME = '@doubletie/api-router';
2333
+ const getTracer = (options)=>{
2334
+ if (options?.telemetry?.tracer) return options.telemetry.tracer;
2335
+ return __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.trace.getTracer(API_ROUTER_TRACER_NAME);
2336
+ };
2337
+ const createRequestSpan = (method, path, options)=>{
2338
+ if (options?.telemetry?.disabled) return null;
2339
+ const tracer = getTracer(options);
2340
+ const span = tracer.startSpan(`${method} ${path}`, {
2341
+ attributes: {
2342
+ 'http.method': method,
2343
+ 'http.path': path,
2344
+ ...options?.telemetry?.defaultAttributes || {}
2919
2345
  }
2920
2346
  });
2921
- return {
2922
- path: config.path,
2923
- method: config.method,
2924
- handler,
2925
- responseType: {}
2926
- };
2927
- }
2928
- function getQuery(event) {
2929
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.getQuery)(event);
2347
+ return span;
2348
+ };
2349
+ const withRequestSpan = async (method, path, operation, options)=>{
2350
+ const span = createRequestSpan(method, path, options);
2351
+ if (!span) return operation();
2352
+ try {
2353
+ const result = await operation();
2354
+ span.setStatus({
2355
+ code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK
2356
+ });
2357
+ return result;
2358
+ } catch (error) {
2359
+ handleSpanError(span, error);
2360
+ throw error;
2361
+ } finally{
2362
+ span.end();
2363
+ }
2364
+ };
2365
+ const handleSpanError = (span, error)=>{
2366
+ span.setStatus({
2367
+ code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
2368
+ message: error instanceof Error ? error.message : String(error)
2369
+ });
2370
+ if (error instanceof Error) {
2371
+ span.setAttribute('error.type', error.name);
2372
+ span.setAttribute('error.message', error.message);
2373
+ if (error.stack) span.setAttribute('error.stack', error.stack);
2374
+ }
2375
+ };
2376
+ const STRIP_REGEX = /^(https?:\/\/)|(wss?:\/\/)|(\/+$)|:\d+/g;
2377
+ function isOriginTrusted(origin, trustedDomains, logger) {
2378
+ try {
2379
+ if (0 === trustedDomains.length) throw new Error('No trusted domains');
2380
+ logger?.debug(`Checking if origin ${origin} is trusted in ${trustedDomains}`);
2381
+ if (trustedDomains.includes('*')) {
2382
+ logger?.debug('Allowing all origins');
2383
+ return true;
2384
+ }
2385
+ const url = new URL(origin);
2386
+ const originHostname = url.hostname.toLowerCase();
2387
+ logger?.debug(`Parsed origin hostname: ${originHostname}`);
2388
+ return trustedDomains.some((domain)=>{
2389
+ if (!domain || '' === domain.trim()) {
2390
+ logger?.debug('Skipping empty domain');
2391
+ return false;
2392
+ }
2393
+ const strippedDomain = domain.replace(STRIP_REGEX, '').toLowerCase();
2394
+ logger?.debug(`Checking against stripped domain: ${strippedDomain}`);
2395
+ if (strippedDomain.startsWith('*.')) {
2396
+ const wildcardDomain = strippedDomain.slice(2);
2397
+ const parts = originHostname.split('.');
2398
+ const isValid = parts.length > 2 && originHostname.endsWith(wildcardDomain);
2399
+ logger?.debug(`Wildcard match result: ${isValid} ${originHostname} ends with ${wildcardDomain} ${parts.length > 2} ${originHostname.endsWith(wildcardDomain)}`);
2400
+ return isValid;
2401
+ }
2402
+ const isMatch = originHostname === strippedDomain;
2403
+ logger?.debug(`Exact match result: ${isMatch} ${originHostname} === ${strippedDomain}`);
2404
+ return isMatch;
2405
+ });
2406
+ } catch (error) {
2407
+ logger?.error('Error validating origin:', error);
2408
+ return false;
2409
+ }
2930
2410
  }
2931
- function getRouterParams(event) {
2932
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.getRouterParams)(event) || {};
2411
+ const DEFAULT_IP_HEADERS = [
2412
+ 'x-client-ip',
2413
+ 'x-forwarded-for',
2414
+ 'cf-connecting-ip',
2415
+ 'fastly-client-ip',
2416
+ 'x-real-ip',
2417
+ 'x-cluster-client-ip',
2418
+ 'x-forwarded',
2419
+ 'forwarded-for',
2420
+ 'forwarded'
2421
+ ];
2422
+ function getIp(req, options) {
2423
+ const advanced = options.advanced || {};
2424
+ if (advanced?.ipAddress?.disableIpTracking) return null;
2425
+ const testIP = '127.0.0.1';
2426
+ if (isTest) return testIP;
2427
+ const ipHeaders = advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;
2428
+ const headers = req instanceof Request ? req.headers : req;
2429
+ for (const key of ipHeaders){
2430
+ const value = headers.get(key);
2431
+ if (value) {
2432
+ const ip = value.split(',')[0]?.trim();
2433
+ if (ip) return ip;
2434
+ }
2435
+ }
2436
+ return null;
2933
2437
  }
2934
2438
  const baseConsentSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2935
2439
  subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2936
2440
  externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2937
- domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2441
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i, 'invalid domain'),
2938
2442
  type: PolicyTypeSchema,
2939
2443
  metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional()
2940
2444
  });
@@ -2959,210 +2463,513 @@ const otherConsentSchema = baseConsentSchema.extend({
2959
2463
  ]),
2960
2464
  preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.boolean()).optional()
2961
2465
  });
2962
- const SetConsentRequestBody = __WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
2963
- cookieBannerSchema,
2964
- policyBasedSchema,
2965
- otherConsentSchema
2966
- ]);
2967
- const setConsent = defineRoute({
2466
+ const postConsentContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2467
+ method: 'POST',
2968
2468
  path: '/consent/set',
2969
- method: 'post',
2970
- validations: {
2971
- body: SetConsentRequestBody
2469
+ description: `Records a user's consent preferences and creates necessary consent records.
2470
+ This endpoint handles various types of consent submissions:
2471
+
2472
+ 1. Cookie Banner Consent:
2473
+ - Records granular cookie preferences
2474
+ - Supports multiple consent purposes
2475
+ - Creates audit trail for compliance
2476
+
2477
+ 2. Policy-Based Consent:
2478
+ - Privacy Policy acceptance
2479
+ - Data Processing Agreement (DPA) consent
2480
+ - Terms and Conditions acceptance
2481
+ - Links consent to specific policy versions
2482
+
2483
+ 3. Other Consent Types:
2484
+ - Marketing communications preferences
2485
+ - Age verification consent
2486
+ - Custom consent types
2487
+
2488
+ The endpoint performs the following operations:
2489
+ - Creates or retrieves subject records
2490
+ - Validates domain and policy information
2491
+ - Creates consent records with audit trails
2492
+ - Records consent purposes and preferences
2493
+ - Generates audit logs for compliance
2494
+
2495
+ Use this endpoint to record user consent and maintain a compliant consent management system.`,
2496
+ tags: [
2497
+ 'consent',
2498
+ 'cookie-banner'
2499
+ ]
2500
+ }).errors({
2501
+ INPUT_VALIDATION_FAILED: {
2502
+ status: 422,
2503
+ message: 'Invalid input parameters',
2504
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2505
+ formErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()),
2506
+ fieldErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.string(), __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()))
2507
+ })
2972
2508
  },
2973
- handler: async (event)=>{
2974
- const logger = event.context.logger || createLogger();
2975
- logger.info('Handling set-consent request');
2976
- const { body } = event.context.validated;
2977
- const { registry, adapter } = event.context;
2978
- const { type, subjectId, externalSubjectId, domain, metadata } = body;
2979
- logger.debug('Request parameters', {
2980
- type,
2981
- subjectId,
2982
- externalSubjectId,
2983
- domain
2984
- });
2985
- try {
2986
- const subject = await registry.findOrCreateSubject({
2987
- subjectId,
2988
- externalSubjectId,
2989
- ipAddress: event.context.ipAddress || 'unknown'
2990
- });
2991
- if (!subject) {
2992
- const errMsg = 'Subject not found or could not be created';
2993
- logger.error(errMsg, {
2994
- subjectId,
2995
- externalSubjectId
2996
- });
2997
- throw new error_class_DoubleTieError(errMsg, {
2998
- code: error_codes_ERROR_CODES.BAD_REQUEST,
2999
- status: 400,
3000
- meta: {
3001
- subjectId,
3002
- externalSubjectId
3003
- }
3004
- });
2509
+ SUBJECT_CREATION_FAILED: {
2510
+ status: 400,
2511
+ message: 'Failed to create or find subject',
2512
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2513
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2514
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
2515
+ })
2516
+ },
2517
+ DOMAIN_CREATION_FAILED: {
2518
+ status: 500,
2519
+ message: 'Failed to create or find domain',
2520
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2521
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2522
+ })
2523
+ },
2524
+ POLICY_NOT_FOUND: {
2525
+ status: 404,
2526
+ message: 'Policy not found',
2527
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2528
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2529
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2530
+ })
2531
+ },
2532
+ POLICY_INACTIVE: {
2533
+ status: 409,
2534
+ message: 'Policy is not active',
2535
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2536
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2537
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2538
+ })
2539
+ },
2540
+ POLICY_CREATION_FAILED: {
2541
+ status: 500,
2542
+ message: 'Failed to create or find policy',
2543
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2544
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2545
+ })
2546
+ },
2547
+ PURPOSE_CREATION_FAILED: {
2548
+ status: 500,
2549
+ message: 'Failed to create consent purpose',
2550
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2551
+ purposeCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2552
+ })
2553
+ },
2554
+ CONSENT_CREATION_FAILED: {
2555
+ status: 500,
2556
+ message: 'Failed to create consent record',
2557
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2558
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2559
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2560
+ })
2561
+ }
2562
+ }).input(__WEBPACK_EXTERNAL_MODULE_zod__.z.discriminatedUnion('type', [
2563
+ cookieBannerSchema,
2564
+ policyBasedSchema,
2565
+ otherConsentSchema
2566
+ ])).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2567
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2568
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2569
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2570
+ domainId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2571
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2572
+ type: PolicyTypeSchema,
2573
+ status: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2574
+ recordId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2575
+ metadata: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.unknown()).optional(),
2576
+ givenAt: __WEBPACK_EXTERNAL_MODULE_zod__.z.date()
2577
+ }));
2578
+ const JurisdictionMessages = {
2579
+ GDPR: 'GDPR or equivalent regulations require a cookie banner.',
2580
+ CH: 'Switzerland requires similar data protection measures.',
2581
+ BR: "Brazil's LGPD requires consent for cookies.",
2582
+ PIPEDA: 'PIPEDA requires consent for data collection.',
2583
+ AU: "Australia's Privacy Act mandates transparency about data collection.",
2584
+ APPI: "Japan's APPI requires consent for data collection.",
2585
+ PIPA: "South Korea's PIPA requires consent for data collection.",
2586
+ NONE: 'No specific requirements'
2587
+ };
2588
+ const JurisdictionCodeSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
2589
+ 'GDPR',
2590
+ 'CH',
2591
+ 'BR',
2592
+ 'PIPEDA',
2593
+ 'AU',
2594
+ 'APPI',
2595
+ 'PIPA',
2596
+ 'NONE'
2597
+ ]);
2598
+ const JurisdictionInfoSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2599
+ code: JurisdictionCodeSchema,
2600
+ message: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2601
+ });
2602
+ const showConsentBannerContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2603
+ method: 'GET',
2604
+ path: '/show-consent-banner',
2605
+ description: `Determines if a user should see a consent banner based on their location and applicable privacy regulations.
2606
+ This endpoint performs the following checks:
2607
+
2608
+ 1. Detects the user's location using various header information:
2609
+ - Cloudflare country headers
2610
+ - Vercel IP country headers
2611
+ - AWS CloudFront headers
2612
+ - Custom country code headers
2613
+
2614
+ 2. Determines the applicable jurisdiction based on the location:
2615
+ - GDPR (EU/EEA/UK)
2616
+ - Swiss Data Protection Act
2617
+ - LGPD (Brazil)
2618
+ - PIPEDA (Canada)
2619
+ - Australian Privacy Principles
2620
+ - APPI (Japan)
2621
+ - PIPA (South Korea)
2622
+
2623
+ 3. Returns detailed information about:
2624
+ - Whether to show the consent banner
2625
+ - The applicable jurisdiction and its requirements
2626
+ - The user's detected location (country and region)
2627
+
2628
+ Use this endpoint to implement geo-targeted consent banners and ensure compliance with regional privacy regulations.`,
2629
+ tags: [
2630
+ 'cookie-banner'
2631
+ ]
2632
+ }).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2633
+ showConsentBanner: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean(),
2634
+ jurisdiction: JurisdictionInfoSchema,
2635
+ location: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2636
+ countryCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2637
+ regionCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable()
2638
+ })
2639
+ }));
2640
+ const verifyConsentInputSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2641
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2642
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2643
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2644
+ type: PolicyTypeSchema,
2645
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2646
+ preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional()
2647
+ }).strict();
2648
+ const verify_contract_consentSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2649
+ id: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2650
+ purposeIds: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string())
2651
+ }).passthrough();
2652
+ const verifyConsentContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2653
+ method: 'POST',
2654
+ path: '/consent/verify',
2655
+ description: `Verifies if a user has given valid consent for a specific policy and domain.
2656
+ This endpoint performs comprehensive consent verification by:
2657
+
2658
+ 1. Validating the subject's identity (using subjectId or externalSubjectId)
2659
+ 2. Verifying the domain's existence and validity
2660
+ 3. Checking if the specified policy exists and is active
2661
+ 4. Validating that all required purposes have been consented to
2662
+ 5. Ensuring the consent record is current and valid
2663
+
2664
+ The endpoint supports different types of consent verification:
2665
+ - Cookie banner consent verification
2666
+ - Privacy policy consent verification
2667
+ - Terms and conditions verification
2668
+ - Marketing communications consent verification
2669
+ - Age verification
2670
+ - Custom consent types
2671
+
2672
+ Use this endpoint to ensure compliance with privacy regulations and to verify user consent before processing personal data.`,
2673
+ tags: [
2674
+ 'consent'
2675
+ ]
2676
+ }).errors({
2677
+ INPUT_VALIDATION_FAILED: {
2678
+ status: 422,
2679
+ message: 'Invalid input parameters',
2680
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2681
+ formErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()),
2682
+ fieldErrors: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.string(), __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional())
2683
+ })
2684
+ },
2685
+ SUBJECT_NOT_FOUND: {
2686
+ status: 404,
2687
+ message: 'Subject not found',
2688
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2689
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
2690
+ externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional()
2691
+ })
2692
+ },
2693
+ DOMAIN_NOT_FOUND: {
2694
+ status: 404,
2695
+ message: 'Domain not found',
2696
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2697
+ domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2698
+ })
2699
+ },
2700
+ POLICY_NOT_FOUND: {
2701
+ status: 404,
2702
+ message: 'Policy not found or invalid',
2703
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2704
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2705
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2706
+ })
2707
+ },
2708
+ PURPOSES_NOT_FOUND: {
2709
+ status: 404,
2710
+ message: 'Could not find all specified purposes',
2711
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2712
+ preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()),
2713
+ foundPurposes: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string())
2714
+ })
2715
+ },
2716
+ COOKIE_BANNER_PREFERENCES_REQUIRED: {
2717
+ status: 400,
2718
+ message: 'Preferences are required for cookie banner consent',
2719
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2720
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.literal('cookie_banner')
2721
+ })
2722
+ },
2723
+ NO_CONSENT_FOUND: {
2724
+ status: 404,
2725
+ message: 'No consent found for the given policy',
2726
+ data: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2727
+ policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2728
+ subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2729
+ domainId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
2730
+ })
2731
+ }
2732
+ }).input(verifyConsentInputSchema).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2733
+ isValid: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean(),
2734
+ reasons: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional(),
2735
+ consent: verify_contract_consentSchema.optional()
2736
+ }));
2737
+ const consentContracts = {
2738
+ post: postConsentContract,
2739
+ showBanner: showConsentBannerContract,
2740
+ verify: verifyConsentContract
2741
+ };
2742
+ const statusContract = __WEBPACK_EXTERNAL_MODULE__orpc_contract_5a058524__.oc.route({
2743
+ method: 'GET',
2744
+ path: '/status',
2745
+ description: `Returns the current operational status and health metrics of the service.
2746
+ This endpoint provides real-time information about:
2747
+ - Overall service status (ok/error)
2748
+ - Current API version
2749
+ - Server timestamp
2750
+ - Storage system status and availability
2751
+ - Client information (IP, User Agent, Region)
2752
+
2753
+ Use this endpoint for health checks, monitoring, and service status verification.`,
2754
+ tags: [
2755
+ 'meta'
2756
+ ]
2757
+ }).output(__WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2758
+ status: __WEBPACK_EXTERNAL_MODULE_zod__.z["enum"]([
2759
+ 'ok',
2760
+ 'error'
2761
+ ]),
2762
+ version: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2763
+ timestamp: __WEBPACK_EXTERNAL_MODULE_zod__.z.date(),
2764
+ storage: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2765
+ type: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
2766
+ available: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean()
2767
+ }),
2768
+ client: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2769
+ ip: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2770
+ userAgent: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2771
+ region: __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
2772
+ countryCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable(),
2773
+ regionCode: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().nullable()
2774
+ })
2775
+ })
2776
+ }));
2777
+ const metaContracts = {
2778
+ status: statusContract
2779
+ };
2780
+ const contracts_config = {
2781
+ consent: consentContracts,
2782
+ meta: metaContracts
2783
+ };
2784
+ const os = (0, __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.implement)(contracts_config);
2785
+ const postConsent = os.consent.post.handler(async ({ input, context })=>{
2786
+ const typedContext = context;
2787
+ const logger = typedContext.logger;
2788
+ logger.info('Handling post-consent request');
2789
+ const { type, subjectId, externalSubjectId, domain, metadata, preferences } = input;
2790
+ logger.debug('Request parameters', {
2791
+ type,
2792
+ subjectId,
2793
+ externalSubjectId,
2794
+ domain
2795
+ });
2796
+ try {
2797
+ const subject = await typedContext.registry.findOrCreateSubject({
2798
+ subjectId,
2799
+ externalSubjectId,
2800
+ ipAddress: typedContext.ipAddress || 'unknown'
2801
+ });
2802
+ if (!subject) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('SUBJECT_CREATION_FAILED', {
2803
+ data: {
2804
+ subjectId,
2805
+ externalSubjectId
3005
2806
  }
3006
- logger.debug('Subject found/created', {
3007
- subjectId: subject.id
3008
- });
3009
- const domainRecord = await registry.findOrCreateDomain(domain);
3010
- const now = new Date();
3011
- let policyId;
3012
- let purposeIds = [];
3013
- if ('policyId' in body) {
3014
- const { policyId: pid } = body;
3015
- policyId = pid;
3016
- if (!policyId) throw new error_class_DoubleTieError('Policy ID is required', {
3017
- code: error_codes_ERROR_CODES.BAD_REQUEST,
3018
- status: 400,
3019
- meta: {
3020
- type
3021
- }
3022
- });
3023
- const policy = await registry.findConsentPolicyById(policyId);
3024
- if (!policy) throw new error_class_DoubleTieError('Policy not found', {
3025
- code: error_codes_ERROR_CODES.NOT_FOUND,
3026
- status: 404,
3027
- meta: {
3028
- policyId
3029
- }
3030
- });
3031
- if (!policy.isActive) throw new error_class_DoubleTieError('Policy is not active', {
3032
- code: error_codes_ERROR_CODES.CONFLICT,
3033
- status: 409,
3034
- meta: {
3035
- policyId
3036
- }
3037
- });
3038
- } else {
3039
- const policy = await registry.findOrCreatePolicy(type);
3040
- if (!policy) throw new error_class_DoubleTieError('Failed to create or find policy', {
3041
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
3042
- status: 500,
3043
- meta: {
3044
- type
3045
- }
3046
- });
3047
- policyId = policy.id;
2807
+ });
2808
+ logger.debug('Subject found/created', {
2809
+ subjectId: subject.id
2810
+ });
2811
+ const domainRecord = await typedContext.registry.findOrCreateDomain(domain);
2812
+ if (!domainRecord) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('DOMAIN_CREATION_FAILED', {
2813
+ data: {
2814
+ domain
3048
2815
  }
3049
- if ('preferences' in body && body.preferences) purposeIds = await Promise.all(Object.entries(body.preferences).filter(([_, isConsented])=>isConsented).map(async ([purposeCode])=>{
3050
- let existingPurpose = await registry.findConsentPurposeByCode(purposeCode);
3051
- if (!existingPurpose) existingPurpose = await registry.createConsentPurpose({
2816
+ });
2817
+ const now = new Date();
2818
+ let policyId;
2819
+ let purposeIds = [];
2820
+ if ('policyId' in input && input.policyId) {
2821
+ policyId = input.policyId;
2822
+ const policy = await typedContext.registry.findConsentPolicyById(policyId);
2823
+ if (!policy) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_NOT_FOUND', {
2824
+ data: {
2825
+ policyId,
2826
+ type
2827
+ }
2828
+ });
2829
+ if (!policy.isActive) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_INACTIVE', {
2830
+ data: {
2831
+ policyId,
2832
+ type
2833
+ }
2834
+ });
2835
+ } else {
2836
+ const policy = await typedContext.registry.findOrCreatePolicy(type);
2837
+ if (!policy) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_CREATION_FAILED', {
2838
+ data: {
2839
+ type
2840
+ }
2841
+ });
2842
+ policyId = policy.id;
2843
+ }
2844
+ if (preferences) {
2845
+ const consentedPurposes = Object.entries(preferences).filter(([_, isConsented])=>isConsented).map(([purposeCode])=>purposeCode);
2846
+ const existingPurposes = await Promise.all(consentedPurposes.map((purposeCode)=>typedContext.registry.findConsentPurposeByCode(purposeCode)));
2847
+ const purposesToCreate = consentedPurposes.filter((_purposeCode, index)=>!existingPurposes[index]);
2848
+ const createdPurposes = await Promise.all(purposesToCreate.map((purposeCode)=>typedContext.registry.createConsentPurpose({
3052
2849
  code: purposeCode,
3053
2850
  name: purposeCode,
3054
2851
  description: `Auto-created consentPurpose for ${purposeCode}`,
3055
2852
  isActive: true,
3056
2853
  isEssential: false,
3057
- dataCategory: 'functional',
3058
2854
  legalBasis: 'consent',
3059
2855
  createdAt: now,
3060
2856
  updatedAt: now
3061
- });
3062
- return existingPurpose.id;
3063
- }));
3064
- const result = await adapter.transaction({
3065
- callback: async (tx)=>{
3066
- const consentRecord = await tx.create({
3067
- model: 'consent',
3068
- data: {
3069
- subjectId: subject.id,
3070
- domainId: domainRecord.id,
3071
- policyId,
3072
- purposeIds,
3073
- status: 'active',
3074
- isActive: true,
3075
- givenAt: now,
3076
- ipAddress: event.context.ipAddress || 'unknown',
3077
- agent: event.context.userAgent || 'unknown',
3078
- history: []
3079
- }
3080
- });
3081
- const record = await tx.create({
3082
- model: 'consentRecord',
3083
- data: {
3084
- subjectId: subject.id,
3085
- consentId: consentRecord.id,
3086
- actionType: 'consent_given',
3087
- details: metadata,
3088
- createdAt: now
3089
- }
3090
- });
3091
- await tx.create({
3092
- model: 'auditLog',
3093
- data: {
3094
- subjectId: subject.id,
3095
- entityType: 'consent',
3096
- entityId: consentRecord.id,
3097
- actionType: 'consent_given',
3098
- details: {
3099
- consentId: consentRecord.id,
3100
- type
3101
- },
3102
- timestamp: now,
3103
- ipAddress: event.context.ipAddress || 'unknown',
3104
- agent: event.context.userAgent || 'unknown'
3105
- }
3106
- });
3107
- return {
3108
- consent: consentRecord,
3109
- record
3110
- };
3111
- }
3112
- });
3113
- if (!result || !result.consent || !result.record) throw new error_class_DoubleTieError('Failed to create consent record', {
3114
- code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
3115
- status: 500,
3116
- meta: {
3117
- subjectId: subject.id,
3118
- domain
2857
+ })));
2858
+ purposeIds = [
2859
+ ...existingPurposes.filter((p)=>null !== p).map((p)=>p.id),
2860
+ ...createdPurposes.filter((p)=>null !== p).map((p)=>p.id)
2861
+ ];
2862
+ if (purposeIds.length !== consentedPurposes.length) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('PURPOSE_CREATION_FAILED', {
2863
+ data: {
2864
+ purposeCode: purposesToCreate[purposeIds.length - consentedPurposes.length]
3119
2865
  }
3120
2866
  });
3121
- const response = {
3122
- id: result.consent.id,
3123
- subjectId: subject.id,
3124
- externalSubjectId: subject.externalId ?? void 0,
3125
- domainId: domainRecord.id,
3126
- domain: domainRecord.name,
3127
- type,
3128
- status: result.consent.status,
3129
- recordId: result.record.id,
3130
- metadata,
3131
- givenAt: result.consent.givenAt.toISOString()
3132
- };
3133
- logger.info('Set-consent successful', {
3134
- consentId: response.id
3135
- });
3136
- return response;
3137
- } catch (error) {
3138
- logger.error('Error in set-consent handler', {
3139
- error: error instanceof Error ? error.message : String(error),
3140
- errorType: error instanceof Error ? error.constructor.name : typeof error
3141
- });
3142
- throw error;
3143
2867
  }
3144
- }
3145
- });
3146
- const show_consent_banner_showConsentBanner = defineRoute({
3147
- path: '/show-consent-banner',
3148
- method: 'get',
3149
- handler: async (event)=>{
3150
- const countryCode = event.headers.get('cf-ipcountry') || event.headers.get('x-vercel-ip-country') || event.headers.get('x-amz-cf-ipcountry') || event.headers.get('x-country-code');
3151
- const regionCode = event.headers.get('x-vercel-ip-country-region') || event.headers.get('x-region-code');
3152
- const { showConsentBanner, jurisdictionCode, message } = checkJurisdiction(countryCode ?? null);
3153
- return {
3154
- showConsentBanner,
3155
- jurisdiction: {
3156
- code: jurisdictionCode,
3157
- message
3158
- },
3159
- location: {
3160
- countryCode,
3161
- regionCode
2868
+ const result = await typedContext.adapter.transaction({
2869
+ callback: async (tx)=>{
2870
+ const consentRecord = await tx.create({
2871
+ model: 'consent',
2872
+ data: {
2873
+ subjectId: subject.id,
2874
+ domainId: domainRecord.id,
2875
+ policyId,
2876
+ purposeIds,
2877
+ status: 'active',
2878
+ isActive: true,
2879
+ givenAt: now,
2880
+ ipAddress: typedContext.ipAddress || 'unknown',
2881
+ agent: typedContext.userAgent || 'unknown',
2882
+ history: []
2883
+ }
2884
+ });
2885
+ const record = await tx.create({
2886
+ model: 'consentRecord',
2887
+ data: {
2888
+ subjectId: subject.id,
2889
+ consentId: consentRecord.id,
2890
+ actionType: 'consent_given',
2891
+ details: metadata,
2892
+ createdAt: now
2893
+ }
2894
+ });
2895
+ await tx.create({
2896
+ model: 'auditLog',
2897
+ data: {
2898
+ subjectId: subject.id,
2899
+ entityType: 'consent',
2900
+ entityId: consentRecord.id,
2901
+ actionType: 'consent_given',
2902
+ details: {
2903
+ consentId: consentRecord.id,
2904
+ type
2905
+ },
2906
+ timestamp: now,
2907
+ ipAddress: typedContext.ipAddress || 'unknown',
2908
+ agent: typedContext.userAgent || 'unknown'
2909
+ }
2910
+ });
2911
+ return {
2912
+ consent: consentRecord,
2913
+ record
2914
+ };
3162
2915
  }
2916
+ });
2917
+ if (!result || !result.consent || !result.record) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('CONSENT_CREATION_FAILED', {
2918
+ data: {
2919
+ subjectId: subject.id,
2920
+ domain
2921
+ }
2922
+ });
2923
+ return {
2924
+ id: result.consent.id,
2925
+ subjectId: subject.id,
2926
+ externalSubjectId: subject.externalId ?? void 0,
2927
+ domainId: domainRecord.id,
2928
+ domain: domainRecord.name,
2929
+ type,
2930
+ status: result.consent.status,
2931
+ recordId: result.record.id,
2932
+ metadata,
2933
+ givenAt: result.consent.givenAt
3163
2934
  };
2935
+ } catch (error) {
2936
+ logger.error('Error in post-consent handler', {
2937
+ error: error instanceof Error ? error.message : String(error),
2938
+ errorType: error instanceof Error ? error.constructor.name : typeof error
2939
+ });
2940
+ if (error instanceof __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError) throw error;
2941
+ throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('INTERNAL_SERVER_ERROR', {
2942
+ message: error instanceof Error ? error.message : String(error)
2943
+ });
3164
2944
  }
3165
2945
  });
2946
+ const show_banner_handler_showConsentBanner = os.consent.showBanner.handler(({ context })=>{
2947
+ const typedContext = context;
2948
+ const headers = typedContext.headers;
2949
+ if (!headers) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('LOCATION_DETECTION_FAILED', {
2950
+ data: {
2951
+ reason: 'No headers found in request context'
2952
+ }
2953
+ });
2954
+ const normalizeHeader = (value)=>{
2955
+ if (!value) return null;
2956
+ return Array.isArray(value) ? value[0] ?? null : value;
2957
+ };
2958
+ const countryCode = normalizeHeader(headers.get('cf-ipcountry')) ?? normalizeHeader(headers.get('x-vercel-ip-country')) ?? normalizeHeader(headers.get('x-amz-cf-ipcountry')) ?? normalizeHeader(headers.get('x-country-code'));
2959
+ const regionCode = normalizeHeader(headers.get('x-vercel-ip-country-region')) ?? normalizeHeader(headers.get('x-region-code'));
2960
+ const { showConsentBanner, jurisdictionCode, message } = checkJurisdiction(countryCode);
2961
+ return {
2962
+ showConsentBanner,
2963
+ jurisdiction: {
2964
+ code: jurisdictionCode,
2965
+ message
2966
+ },
2967
+ location: {
2968
+ countryCode,
2969
+ regionCode
2970
+ }
2971
+ };
2972
+ });
3166
2973
  function checkJurisdiction(countryCode) {
3167
2974
  const jurisdictions = {
3168
2975
  EU: new Set([
@@ -3223,150 +3030,156 @@ function checkJurisdiction(countryCode) {
3223
3030
  };
3224
3031
  let showConsentBanner = false;
3225
3032
  let jurisdictionCode = 'NONE';
3226
- let message = 'No specific requirements';
3227
3033
  if (countryCode) {
3228
- if (jurisdictions.EU.has(countryCode) || jurisdictions.EEA.has(countryCode) || jurisdictions.UK.has(countryCode)) {
3229
- showConsentBanner = true;
3230
- jurisdictionCode = 'GDPR';
3231
- message = 'GDPR or equivalent regulations require a cookie banner.';
3232
- } else if (jurisdictions.CH.has(countryCode)) {
3233
- showConsentBanner = true;
3234
- jurisdictionCode = 'CH';
3235
- message = 'Switzerland requires similar data protection measures.';
3236
- } else if (jurisdictions.BR.has(countryCode)) {
3237
- showConsentBanner = true;
3238
- jurisdictionCode = 'BR';
3239
- message = "Brazil's LGPD requires consent for cookies.";
3240
- } else if (jurisdictions.CA.has(countryCode)) {
3241
- showConsentBanner = true;
3242
- jurisdictionCode = 'PIPEDA';
3243
- message = 'PIPEDA requires consent for data collection.';
3244
- } else if (jurisdictions.AU.has(countryCode)) {
3245
- showConsentBanner = true;
3246
- jurisdictionCode = 'AU';
3247
- message = "Australia's Privacy Act mandates transparency about data collection.";
3248
- } else if (jurisdictions.JP.has(countryCode)) {
3249
- showConsentBanner = true;
3250
- jurisdictionCode = 'APPI';
3251
- message = "Japan's APPI requires consent for data collection.";
3252
- } else if (jurisdictions.KR.has(countryCode)) {
3034
+ const jurisdictionMap = [
3035
+ {
3036
+ sets: [
3037
+ jurisdictions.EU,
3038
+ jurisdictions.EEA,
3039
+ jurisdictions.UK
3040
+ ],
3041
+ code: 'GDPR'
3042
+ },
3043
+ {
3044
+ sets: [
3045
+ jurisdictions.CH
3046
+ ],
3047
+ code: 'CH'
3048
+ },
3049
+ {
3050
+ sets: [
3051
+ jurisdictions.BR
3052
+ ],
3053
+ code: 'BR'
3054
+ },
3055
+ {
3056
+ sets: [
3057
+ jurisdictions.CA
3058
+ ],
3059
+ code: 'PIPEDA'
3060
+ },
3061
+ {
3062
+ sets: [
3063
+ jurisdictions.AU
3064
+ ],
3065
+ code: 'AU'
3066
+ },
3067
+ {
3068
+ sets: [
3069
+ jurisdictions.JP
3070
+ ],
3071
+ code: 'APPI'
3072
+ },
3073
+ {
3074
+ sets: [
3075
+ jurisdictions.KR
3076
+ ],
3077
+ code: 'PIPA'
3078
+ }
3079
+ ];
3080
+ for (const { sets, code } of jurisdictionMap)if (sets.some((set)=>set.has(countryCode))) {
3253
3081
  showConsentBanner = true;
3254
- jurisdictionCode = 'PIPA';
3255
- message = "South Korea's PIPA requires consent for data collection.";
3082
+ jurisdictionCode = code;
3083
+ break;
3256
3084
  }
3257
3085
  }
3086
+ const message = JurisdictionMessages[jurisdictionCode];
3258
3087
  return {
3259
3088
  showConsentBanner,
3260
3089
  jurisdictionCode,
3261
3090
  message
3262
3091
  };
3263
3092
  }
3264
- var package_namespaceObject = {
3265
- i8: "1.0.5"
3266
- };
3267
- const status_status = defineRoute({
3268
- path: '/status',
3269
- method: 'get',
3270
- handler: async (event)=>{
3271
- const response = {
3272
- status: 'ok',
3273
- version: package_namespaceObject.i8,
3274
- timestamp: new Date().toISOString(),
3275
- storage: {
3276
- type: event.context.adapter?.id ?? 'Unavailable',
3277
- available: !!event.context.adapter
3278
- }
3279
- };
3280
- return response;
3281
- }
3282
- });
3283
- const VerifyConsentRequestBody = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
3284
- subjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
3285
- externalSubjectId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
3286
- domain: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
3287
- type: PolicyTypeSchema,
3288
- policyId: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
3289
- preferences: __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string()).optional()
3290
- });
3291
- const verifyConsent = defineRoute({
3292
- path: '/consent/verify',
3293
- method: 'post',
3294
- validations: {
3295
- body: VerifyConsentRequestBody
3296
- },
3297
- handler: async (event)=>{
3298
- const { body } = event.context.validated;
3299
- const { type, subjectId, externalSubjectId, domain, policyId, preferences } = body;
3300
- const { registry } = event.context;
3301
- const subject = await registry.findOrCreateSubject({
3093
+ const verifyConsent = os.consent.verify.handler(async ({ input, context })=>{
3094
+ const typedContext = context;
3095
+ const logger = typedContext.logger;
3096
+ logger.info('Handling verify-consent request');
3097
+ const { type, subjectId, externalSubjectId, domain, policyId, preferences } = input;
3098
+ logger.debug('Request parameters', {
3099
+ type,
3100
+ subjectId,
3101
+ externalSubjectId,
3102
+ domain,
3103
+ policyId,
3104
+ preferences
3105
+ });
3106
+ try {
3107
+ const subject = await typedContext.registry.findOrCreateSubject({
3302
3108
  subjectId,
3303
3109
  externalSubjectId,
3304
- ipAddress: event.context.ipAddress || 'unknown'
3110
+ ipAddress: typedContext.ipAddress || 'unknown'
3305
3111
  });
3306
- if (!subject) return {
3307
- isValid: false,
3308
- reasons: [
3309
- 'Subject not found'
3310
- ]
3311
- };
3312
- const domainRecord = await registry.findDomain(domain);
3313
- if (!domainRecord) return {
3314
- isValid: false,
3315
- reasons: [
3316
- 'Domain not found'
3317
- ]
3318
- };
3319
- if ('cookie_banner' === type && preferences?.length === 0) return {
3320
- isValid: false,
3321
- reasons: [
3322
- 'Preferences are required'
3323
- ]
3324
- };
3325
- const purposePromises = preferences?.map((purpose)=>registry.findConsentPurposeByCode(purpose));
3112
+ if (!subject) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('SUBJECT_NOT_FOUND', {
3113
+ data: {
3114
+ subjectId,
3115
+ externalSubjectId
3116
+ }
3117
+ });
3118
+ const domainRecord = await typedContext.registry.findDomain(domain);
3119
+ if (!domainRecord) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('DOMAIN_NOT_FOUND', {
3120
+ data: {
3121
+ domain
3122
+ }
3123
+ });
3124
+ if ('cookie_banner' === type && (!preferences || 0 === preferences.length)) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('COOKIE_BANNER_PREFERENCES_REQUIRED', {
3125
+ data: {
3126
+ type: 'cookie_banner'
3127
+ }
3128
+ });
3129
+ const purposePromises = preferences?.map((purpose)=>typedContext.registry.findConsentPurposeByCode(purpose));
3326
3130
  const rawPurposes = await Promise.all(purposePromises ?? []);
3327
3131
  const purposeIds = rawPurposes.filter((purpose)=>null !== purpose).map((purpose)=>purpose.id);
3328
- if (purposeIds.length !== (preferences?.length ?? 0)) return {
3329
- isValid: false,
3330
- reasons: [
3331
- 'Could not find all purposes'
3332
- ]
3333
- };
3132
+ if (purposeIds.length !== (preferences?.length ?? 0)) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('PURPOSES_NOT_FOUND', {
3133
+ data: {
3134
+ preferences: preferences ?? [],
3135
+ foundPurposes: rawPurposes.filter((p)=>null !== p).map((p)=>p.code)
3136
+ }
3137
+ });
3334
3138
  if (policyId) {
3335
- const policy = await registry.findConsentPolicyById(policyId);
3336
- if (!policy || policy.type !== type) return {
3337
- isValid: false,
3338
- reasons: [
3339
- 'Policy not found'
3340
- ]
3341
- };
3342
- return await policyConsentGiven({
3139
+ const policy = await typedContext.registry.findConsentPolicyById(policyId);
3140
+ if (!policy || policy.type !== type) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_NOT_FOUND', {
3141
+ data: {
3142
+ policyId,
3143
+ type
3144
+ }
3145
+ });
3146
+ return await checkPolicyConsent({
3343
3147
  policyId: policy.id,
3344
3148
  subjectId: subject.id,
3345
3149
  domainId: domainRecord.id,
3346
3150
  purposeIds,
3347
3151
  type,
3348
- event
3152
+ context: typedContext
3349
3153
  });
3350
3154
  }
3351
- const latestPolicy = await registry.findOrCreatePolicy(type);
3352
- if (!latestPolicy) return {
3353
- isValid: false,
3354
- reasons: [
3355
- 'Failed to find or create latest policy'
3356
- ]
3357
- };
3358
- return await policyConsentGiven({
3155
+ const latestPolicy = await typedContext.registry.findOrCreatePolicy(type);
3156
+ if (!latestPolicy) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('POLICY_NOT_FOUND', {
3157
+ data: {
3158
+ policyId: 'latest',
3159
+ type
3160
+ }
3161
+ });
3162
+ return await checkPolicyConsent({
3359
3163
  policyId: latestPolicy.id,
3360
3164
  subjectId: subject.id,
3361
3165
  domainId: domainRecord.id,
3362
3166
  purposeIds,
3363
3167
  type,
3364
- event
3168
+ context: typedContext
3169
+ });
3170
+ } catch (error) {
3171
+ logger.error('Error in verify-consent handler', {
3172
+ error: error instanceof Error ? error.message : String(error),
3173
+ errorType: error instanceof Error ? error.constructor.name : typeof error
3174
+ });
3175
+ if (error instanceof __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError) throw error;
3176
+ throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('INTERNAL_SERVER_ERROR', {
3177
+ message: error instanceof Error ? error.message : String(error)
3365
3178
  });
3366
3179
  }
3367
3180
  });
3368
- async function policyConsentGiven({ policyId, subjectId, domainId, purposeIds, type, event }) {
3369
- const { registry, adapter } = event.context;
3181
+ async function checkPolicyConsent({ policyId, subjectId, domainId, purposeIds, type, context }) {
3182
+ const { registry, adapter } = context;
3370
3183
  const rawConsents = await adapter.findMany({
3371
3184
  model: 'consent',
3372
3185
  where: [
@@ -3388,13 +3201,12 @@ async function policyConsentGiven({ policyId, subjectId, domainId, purposeIds, t
3388
3201
  direction: 'desc'
3389
3202
  }
3390
3203
  });
3391
- const consents = rawConsents.map((consent)=>validateEntityOutput('consent', consent, {}));
3392
- const filteredConsents = consents.filter((consent)=>{
3204
+ const filteredConsents = rawConsents.filter((consent)=>{
3393
3205
  if (!purposeIds) return true;
3394
3206
  return purposeIds.every((id)=>consent.purposeIds.some((purposeId)=>purposeId === id));
3395
3207
  });
3396
3208
  await registry.createAuditLog({
3397
- subjectId: subjectId,
3209
+ subjectId,
3398
3210
  entityType: 'consent_policy',
3399
3211
  entityId: policyId,
3400
3212
  actionType: 'verify_consent',
@@ -3403,260 +3215,325 @@ async function policyConsentGiven({ policyId, subjectId, domainId, purposeIds, t
3403
3215
  policyId,
3404
3216
  purposeIds,
3405
3217
  success: 0 !== filteredConsents.length,
3406
- consentId: filteredConsents[0]?.id
3218
+ ...filteredConsents.length > 0 ? {
3219
+ consentId: filteredConsents[0]?.id
3220
+ } : {}
3221
+ }
3222
+ });
3223
+ if (0 === rawConsents.length) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('NO_CONSENT_FOUND', {
3224
+ data: {
3225
+ policyId,
3226
+ subjectId,
3227
+ domainId
3228
+ }
3229
+ });
3230
+ if (0 === filteredConsents.length) throw new __WEBPACK_EXTERNAL_MODULE__orpc_server_0dae8408__.ORPCError('NO_CONSENT_FOUND', {
3231
+ data: {
3232
+ policyId,
3233
+ subjectId,
3234
+ domainId
3407
3235
  }
3408
3236
  });
3409
- if (0 === consents.length) return {
3410
- isValid: false,
3411
- reasons: [
3412
- 'No consent found for the given policy'
3413
- ]
3414
- };
3415
3237
  return {
3416
3238
  isValid: true,
3417
3239
  consent: filteredConsents[0]
3418
3240
  };
3419
3241
  }
3420
- const routes = [
3421
- status_status,
3422
- show_consent_banner_showConsentBanner,
3423
- setConsent,
3424
- verifyConsent
3425
- ];
3426
- const API_ROUTER_TRACER_NAME = '@doubletie/api-router';
3427
- const api_router_telemetry_getTracer = (options)=>{
3428
- if (options?.telemetry?.tracer) return options.telemetry.tracer;
3429
- return __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.trace.getTracer(API_ROUTER_TRACER_NAME);
3242
+ const consentHandlers = {
3243
+ post: postConsent,
3244
+ showBanner: show_banner_handler_showConsentBanner,
3245
+ verify: verifyConsent
3430
3246
  };
3431
- const createRequestSpan = (method, path, options)=>{
3432
- if (options?.telemetry?.disabled) return null;
3433
- const tracer = api_router_telemetry_getTracer(options);
3434
- const span = tracer.startSpan(`${method} ${path}`, {
3435
- attributes: {
3436
- 'http.method': method,
3437
- 'http.path': path,
3438
- ...options?.telemetry?.defaultAttributes || {}
3247
+ const statusHandler = os.meta.status.handler(({ context })=>{
3248
+ const typedContext = context;
3249
+ const headers = typedContext.headers;
3250
+ const normalizeHeader = (value)=>{
3251
+ if (!value) return null;
3252
+ return Array.isArray(value) ? value[0] ?? null : value;
3253
+ };
3254
+ const countryCode = normalizeHeader(headers?.get('cf-ipcountry')) ?? normalizeHeader(headers?.get('x-vercel-ip-country')) ?? normalizeHeader(headers?.get('x-amz-cf-ipcountry')) ?? normalizeHeader(headers?.get('x-country-code'));
3255
+ const regionCode = normalizeHeader(headers?.get('x-vercel-ip-country-region')) ?? normalizeHeader(headers?.get('x-region-code'));
3256
+ return {
3257
+ status: 'ok',
3258
+ version: package_namespaceObject.i8,
3259
+ timestamp: new Date(),
3260
+ storage: {
3261
+ type: typedContext.adapter?.id ?? 'MemoryAdapter',
3262
+ available: !!typedContext.adapter
3263
+ },
3264
+ client: {
3265
+ ip: typedContext.ipAddress ?? null,
3266
+ userAgent: typedContext.userAgent ?? null,
3267
+ region: {
3268
+ countryCode,
3269
+ regionCode
3270
+ }
3439
3271
  }
3440
- });
3441
- return span;
3442
- };
3443
- const withRequestSpan = async (method, path, operation, options)=>{
3444
- const span = createRequestSpan(method, path, options);
3445
- if (!span) return operation();
3446
- try {
3447
- const result = await operation();
3448
- span.setStatus({
3449
- code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.OK
3450
- });
3451
- return result;
3452
- } catch (error) {
3453
- handleSpanError(span, error);
3454
- throw error;
3455
- } finally{
3456
- span.end();
3457
- }
3272
+ };
3273
+ });
3274
+ const metaHandlers = {
3275
+ status: statusHandler
3458
3276
  };
3459
- const handleSpanError = (span, error)=>{
3460
- span.setStatus({
3461
- code: __WEBPACK_EXTERNAL_MODULE__opentelemetry_api_87359e78__.SpanStatusCode.ERROR,
3462
- message: error instanceof Error ? error.message : String(error)
3277
+ const router = os.router({
3278
+ consent: consentHandlers,
3279
+ meta: metaHandlers
3280
+ });
3281
+ const c15tInstance = (options)=>{
3282
+ const contextPromise = init(options);
3283
+ const corsOptions = options.trustedOrigins ? {
3284
+ origin: options.trustedOrigins.includes('*') ? '*' : options.trustedOrigins,
3285
+ credentials: true,
3286
+ methods: [
3287
+ 'GET',
3288
+ 'POST',
3289
+ 'PUT',
3290
+ 'DELETE',
3291
+ 'OPTIONS',
3292
+ 'PATCH'
3293
+ ],
3294
+ allowedHeaders: [
3295
+ 'Content-Type',
3296
+ 'Authorization',
3297
+ 'X-Request-ID'
3298
+ ],
3299
+ maxAge: 86400
3300
+ } : {
3301
+ origin: '*',
3302
+ credentials: false,
3303
+ methods: [
3304
+ 'GET',
3305
+ 'POST',
3306
+ 'PUT',
3307
+ 'DELETE',
3308
+ 'OPTIONS',
3309
+ 'PATCH'
3310
+ ],
3311
+ allowedHeaders: [
3312
+ 'Content-Type',
3313
+ 'Authorization',
3314
+ 'X-Request-ID'
3315
+ ],
3316
+ maxAge: 86400
3317
+ };
3318
+ const rpcHandler = new __WEBPACK_EXTERNAL_MODULE__orpc_openapi_fetch_89b49e61__.OpenAPIHandler(router, {
3319
+ plugins: [
3320
+ new __WEBPACK_EXTERNAL_MODULE__orpc_server_plugins_e445fd4f__.CORSPlugin(corsOptions)
3321
+ ]
3463
3322
  });
3464
- if (error instanceof Error) {
3465
- span.setAttribute('error.type', error.name);
3466
- span.setAttribute('error.message', error.message);
3467
- if (error.stack) span.setAttribute('error.stack', error.stack);
3468
- }
3469
- };
3470
- const STRIP_REGEX = /^(https?:\/\/)|(wss?:\/\/)|(\/+$)|:\d+/g;
3471
- function isOriginTrusted(origin, trustedDomains, logger) {
3472
- try {
3473
- if (0 === trustedDomains.length) throw new Error('No trusted domains');
3474
- logger?.debug(`Checking if origin ${origin} is trusted in ${trustedDomains}`);
3475
- if (trustedDomains.includes('*')) {
3476
- logger?.debug('Allowing all origins');
3477
- return true;
3478
- }
3479
- const url = new URL(origin);
3480
- const originHostname = url.hostname.toLowerCase();
3481
- logger?.debug(`Parsed origin hostname: ${originHostname}`);
3482
- return trustedDomains.some((domain)=>{
3483
- if (!domain || '' === domain.trim()) {
3484
- logger?.debug('Skipping empty domain');
3485
- return false;
3323
+ const openAPIGenerator = new __WEBPACK_EXTERNAL_MODULE__orpc_openapi_a95cc8e7__.OpenAPIGenerator({
3324
+ schemaConverters: [
3325
+ new __WEBPACK_EXTERNAL_MODULE__orpc_zod_716a28d4__.ZodToJsonSchemaConverter()
3326
+ ]
3327
+ });
3328
+ const openApiConfig = {
3329
+ enabled: true,
3330
+ specPath: '/spec.json',
3331
+ docsPath: '/docs',
3332
+ ...options.openapi || {}
3333
+ };
3334
+ const defaultOpenApiOptions = {
3335
+ info: {
3336
+ title: options.appName || 'c15t API',
3337
+ version: package_namespaceObject.i8,
3338
+ description: 'API for consent management'
3339
+ },
3340
+ servers: [
3341
+ {
3342
+ url: '/'
3486
3343
  }
3487
- const strippedDomain = domain.replace(STRIP_REGEX, '').toLowerCase();
3488
- logger?.debug(`Checking against stripped domain: ${strippedDomain}`);
3489
- if (strippedDomain.startsWith('*.')) {
3490
- const wildcardDomain = strippedDomain.slice(2);
3491
- const parts = originHostname.split('.');
3492
- const isValid = parts.length > 2 && originHostname.endsWith(wildcardDomain);
3493
- logger?.debug(`Wildcard match result: ${isValid} ${originHostname} ends with ${wildcardDomain} ${parts.length > 2} ${originHostname.endsWith(wildcardDomain)}`);
3494
- return isValid;
3344
+ ],
3345
+ security: [
3346
+ {
3347
+ bearerAuth: []
3495
3348
  }
3496
- const isMatch = originHostname === strippedDomain;
3497
- logger?.debug(`Exact match result: ${isMatch} ${originHostname} === ${strippedDomain}`);
3498
- return isMatch;
3499
- });
3500
- } catch (error) {
3501
- logger?.error('Error validating origin:', error);
3502
- return false;
3503
- }
3504
- }
3505
- const DEFAULT_IP_HEADERS = [
3506
- 'x-client-ip',
3507
- 'x-forwarded-for',
3508
- 'cf-connecting-ip',
3509
- 'fastly-client-ip',
3510
- 'x-real-ip',
3511
- 'x-cluster-client-ip',
3512
- 'x-forwarded',
3513
- 'forwarded-for',
3514
- 'forwarded'
3515
- ];
3516
- function getIp(req, options) {
3517
- const advanced = options.advanced || {};
3518
- if (advanced?.ipAddress?.disableIpTracking) return null;
3519
- const testIP = '127.0.0.1';
3520
- if (isTest) return testIP;
3521
- const ipHeaders = advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;
3522
- const headers = req instanceof Request ? req.headers : req;
3523
- for (const key of ipHeaders){
3524
- const value = headers.get(key);
3525
- if (value) {
3526
- const ip = value.split(',')[0]?.trim();
3527
- if (ip) return ip;
3349
+ ]
3350
+ };
3351
+ const processIp = (request, context)=>{
3352
+ const ip = getIp(request, options);
3353
+ if (ip) context.ipAddress = ip;
3354
+ return context;
3355
+ };
3356
+ const processCors = (request, context)=>{
3357
+ const origin = request.headers.get('origin');
3358
+ if (origin && options.trustedOrigins) {
3359
+ const trusted = isOriginTrusted(origin, options.trustedOrigins, context.logger);
3360
+ context.origin = origin;
3361
+ context.trustedOrigin = trusted;
3528
3362
  }
3529
- }
3530
- return null;
3531
- }
3532
- function createApiHandler({ options, context }) {
3533
- const { logger } = context;
3534
- logger.info('Creating API Handler');
3535
- const app = (0, __WEBPACK_EXTERNAL_MODULE_h3__.createApp)({
3536
- onRequest (event) {
3537
- event.context.ipAddress = getIp(event.headers, options);
3538
- event.context.userAgent = event.node.req.headers['user-agent'] || null;
3539
- event.context.registry = context.registry;
3540
- event.context.adapter = context.adapter;
3541
- event.context.trustedOrigins = context.trustedOrigins;
3542
- event.context.logger = logger;
3543
- logger.debug(`Request received: ${event.method} ${event.path}`);
3544
- },
3545
- onError (error, event) {
3546
- if (event.context._onError && 'function' == typeof event.context._onError) return event.context._onError(error);
3547
- logger.error(`Unhandled API error in ${event.method} ${event.path}`, {
3548
- error: error instanceof Error ? error.message : String(error),
3549
- errorType: error instanceof Error ? error.constructor.name : typeof error
3550
- });
3363
+ return context;
3364
+ };
3365
+ const processTelemetry = (request, context)=>{
3366
+ const url = new URL(request.url);
3367
+ const path = url.pathname;
3368
+ const method = request.method;
3369
+ withRequestSpan(method, path, async ()=>{}, options);
3370
+ context.path = path;
3371
+ context.method = method;
3372
+ context.headers = request.headers;
3373
+ context.userAgent = request.headers.get('user-agent') || void 0;
3374
+ return context;
3375
+ };
3376
+ const getOpenAPISpec = async ()=>{
3377
+ if (getOpenAPISpec.cached) return getOpenAPISpec.cached;
3378
+ const mergedOptions = {
3379
+ ...defaultOpenApiOptions
3380
+ };
3381
+ if (openApiConfig.options) {
3382
+ const userOptions = openApiConfig.options;
3383
+ if (userOptions.info) mergedOptions.info = {
3384
+ ...defaultOpenApiOptions.info,
3385
+ ...userOptions.info
3386
+ };
3387
+ for (const [key, value] of Object.entries(userOptions))if ('info' !== key) mergedOptions[key] = value;
3551
3388
  }
3552
- });
3553
- app.use(createH3ErrorHandler());
3554
- logger.debug('Added error handler middleware');
3555
- app.use((0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)((event)=>{
3556
- if ((0, __WEBPACK_EXTERNAL_MODULE_h3__.handleCors)(event, {
3557
- origin: (originStr)=>isOriginTrusted(originStr, event.context.trustedOrigins, logger),
3558
- methods: [
3559
- 'GET',
3560
- 'POST',
3561
- 'PUT',
3562
- 'DELETE',
3563
- 'PATCH',
3564
- 'OPTIONS'
3565
- ],
3566
- allowHeaders: [
3567
- 'Content-Type',
3568
- 'Authorization'
3569
- ],
3570
- credentials: true,
3571
- maxAge: '600'
3572
- })) return void logger.debug('CORS preflight response sent');
3573
- }));
3574
- const router = (0, __WEBPACK_EXTERNAL_MODULE_h3__.createRouter)();
3575
- app.use(router);
3576
- logger.debug('Router initialized and registered with app');
3577
- for (const route of routes){
3578
- logger.debug(`Registering route: ${route.method} ${route.path}`);
3579
- router[route.method](route.path, withH3ErrorHandling((0, __WEBPACK_EXTERNAL_MODULE_h3__.eventHandler)(async (event)=>{
3580
- logger.debug(`Handling request: ${route.method} ${route.path}`);
3581
- try {
3582
- logger.debug(`Executing handler for ${route.path}`);
3583
- const result = await withRequestSpan(event.method.toUpperCase(), route.path, ()=>route.handler(event), options);
3584
- logger.debug(`Handler completed for ${route.path}`);
3585
- if ('object' == typeof result && null !== result && 'pipe' in result && 'function' == typeof result.pipe) {
3586
- logger.debug(`Sending stream response for ${route.path}`);
3587
- return (0, __WEBPACK_EXTERNAL_MODULE_h3__.sendStream)(event, result);
3389
+ const spec = await openAPIGenerator.generate(router, mergedOptions);
3390
+ getOpenAPISpec.cached = spec;
3391
+ return spec;
3392
+ };
3393
+ const getDocsUI = ()=>{
3394
+ if (openApiConfig.customUiTemplate) return openApiConfig.customUiTemplate;
3395
+ return `
3396
+ <!doctype html>
3397
+ <html>
3398
+ <head>
3399
+ <title>${options.appName || 'c15t API'} Documentation</title>
3400
+ <meta charset="utf-8" />
3401
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
3402
+ <link rel="icon" type="image/svg+xml" href="https://orpc.unnoq.com/icon.svg" />
3403
+ </head>
3404
+ <body>
3405
+ <script
3406
+ id="api-reference"
3407
+ data-url="${encodeURI(openApiConfig.specPath)}">
3408
+ </script>
3409
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
3410
+ </body>
3411
+ </html>
3412
+ `;
3413
+ };
3414
+ const handleOpenApiSpecRequest = async (url)=>{
3415
+ if (openApiConfig.enabled && url.pathname === openApiConfig.specPath) {
3416
+ const spec = await getOpenAPISpec();
3417
+ return new Response(JSON.stringify(spec), {
3418
+ status: 200,
3419
+ headers: {
3420
+ 'Content-Type': 'application/json'
3588
3421
  }
3589
- event.node.res.setHeader('Content-Type', 'application/json');
3590
- return result;
3591
- } catch (error) {
3592
- logger.error(`Error in route handler for ${route.path}`, {
3593
- error: error instanceof Error ? error.message : String(error),
3594
- errorType: error instanceof Error ? error.constructor.name : typeof error
3595
- });
3596
- throw error;
3597
- }
3598
- })));
3599
- }
3600
- const handler = (0, __WEBPACK_EXTERNAL_MODULE_h3__.toWebHandler)(app);
3601
- logger.info('API handler created successfully');
3602
- return {
3603
- handler
3422
+ });
3423
+ }
3424
+ return null;
3604
3425
  };
3605
- }
3606
- const c15tInstance = (options)=>{
3607
- const contextPromise = init(options);
3608
- let webHandler = null;
3609
- const getHandler = async (ctx)=>{
3610
- if (!webHandler) {
3611
- const { handler } = createApiHandler({
3612
- options: ctx.options,
3613
- context: {
3614
- adapter: ctx.adapter,
3615
- registry: ctx.registry,
3616
- trustedOrigins: ctx.trustedOrigins,
3617
- logger: ctx.logger
3426
+ const handleDocsUiRequest = (url)=>{
3427
+ if (openApiConfig.enabled && url.pathname === openApiConfig.docsPath) {
3428
+ const html = getDocsUI();
3429
+ return new Response(html, {
3430
+ status: 200,
3431
+ headers: {
3432
+ 'Content-Type': 'text/html',
3433
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;"
3618
3434
  }
3619
3435
  });
3620
- webHandler = handler;
3621
3436
  }
3622
- return webHandler;
3437
+ return null;
3438
+ };
3439
+ const createDoubleTieErrorResponse = (error)=>{
3440
+ const sanitizedMessage = error.message.replace(/[^\w\s.,;:!?()[\]{}'"+-]/g, '');
3441
+ return new Response(JSON.stringify({
3442
+ code: error.code,
3443
+ message: sanitizedMessage,
3444
+ data: error.meta,
3445
+ status: error.statusCode,
3446
+ defined: true
3447
+ }), {
3448
+ status: error.statusCode,
3449
+ headers: {
3450
+ 'Content-Type': 'application/json'
3451
+ }
3452
+ });
3453
+ };
3454
+ const createUnknownErrorResponse = (error)=>{
3455
+ const message = error instanceof Error ? error.message : String(error);
3456
+ let status = 500;
3457
+ if (error instanceof Error && 'status' in error) {
3458
+ const statusValue = error.status;
3459
+ if ('number' == typeof statusValue && statusValue >= 100 && statusValue < 600) status = statusValue;
3460
+ }
3461
+ return new Response(JSON.stringify({
3462
+ code: error_codes_ERROR_CODES.INTERNAL_SERVER_ERROR,
3463
+ message,
3464
+ status,
3465
+ defined: true,
3466
+ data: {}
3467
+ }), {
3468
+ status,
3469
+ headers: {
3470
+ 'Content-Type': 'application/json'
3471
+ }
3472
+ });
3473
+ };
3474
+ const handleApiRequest = async (request, ctx)=>{
3475
+ const orpcContext = {
3476
+ adapter: ctx.adapter,
3477
+ registry: ctx.registry,
3478
+ logger: ctx.logger,
3479
+ generateId: ctx.generateId,
3480
+ headers: request.headers,
3481
+ userAgent: request.headers.get('user-agent') || void 0
3482
+ };
3483
+ processIp(request, orpcContext);
3484
+ processCors(request, orpcContext);
3485
+ processTelemetry(request, orpcContext);
3486
+ const handlerContext = orpcContext;
3487
+ const { matched, response } = await rpcHandler.handle(request, {
3488
+ prefix: '/',
3489
+ context: handlerContext
3490
+ });
3491
+ if (matched && response) return response;
3492
+ return new Response('Not Found', {
3493
+ status: 404
3494
+ });
3623
3495
  };
3624
3496
  const handler = async (request)=>{
3625
3497
  try {
3626
- const contextResult = await contextPromise;
3627
- return contextResult.match(async (ctx)=>{
3628
- try {
3629
- const handler = await getHandler(ctx);
3630
- const response = await handler(request);
3631
- return (0, __WEBPACK_EXTERNAL_MODULE_neverthrow__.okAsync)(response);
3632
- } catch (error) {
3633
- return failAsync('Request handling failed', {
3634
- code: error_codes_ERROR_CODES.REQUEST_HANDLER_ERROR,
3635
- cause: error instanceof Error ? error : void 0
3636
- });
3637
- }
3638
- }, (error)=>failAsync(`Context initialization failed: ${error.message}`, {
3639
- code: error_codes_ERROR_CODES.INITIALIZATION_FAILED,
3640
- cause: error
3641
- }));
3498
+ const url = new URL(request.url);
3499
+ const openApiResponse = await handleOpenApiSpecRequest(url);
3500
+ if (openApiResponse) return openApiResponse;
3501
+ const docsResponse = handleDocsUiRequest(url);
3502
+ if (docsResponse) return docsResponse;
3503
+ const ctxResult = await contextPromise;
3504
+ if (!ctxResult.isOk()) throw ctxResult.error;
3505
+ const ctx = ctxResult.value;
3506
+ return await handleApiRequest(request, ctx);
3642
3507
  } catch (error) {
3643
- return failAsync(`Unexpected error: ${error instanceof Error ? error.message : String(error)}`, {
3644
- code: error_codes_ERROR_CODES.UNKNOWN_ERROR,
3645
- cause: error instanceof Error ? error : void 0
3646
- });
3508
+ const logger = options.logger ? (0, __WEBPACK_EXTERNAL_MODULE__doubletie_logger_91c58a8f__.createLogger)(options.logger) : console;
3509
+ logger.error('Request handling error:', error);
3510
+ if (error instanceof error_class_DoubleTieError) return createDoubleTieErrorResponse(error);
3511
+ return createUnknownErrorResponse(error);
3647
3512
  }
3648
3513
  };
3514
+ const createNextHandlers = ()=>{
3515
+ const nextHandler = async (request)=>await handler(request);
3516
+ return {
3517
+ GET: nextHandler,
3518
+ POST: nextHandler,
3519
+ PUT: nextHandler,
3520
+ PATCH: nextHandler,
3521
+ DELETE: nextHandler,
3522
+ OPTIONS: nextHandler,
3523
+ HEAD: nextHandler
3524
+ };
3525
+ };
3649
3526
  return {
3650
- handler,
3651
- getApi: async ()=>{
3652
- const contextResult = await contextPromise;
3653
- return contextResult.match(()=>(0, __WEBPACK_EXTERNAL_MODULE_neverthrow__.okAsync)(routes), (error)=>failAsync(`API retrieval failed: ${error.message}`, {
3654
- code: error_codes_ERROR_CODES.API_RETRIEVAL_ERROR,
3655
- cause: error
3656
- }));
3657
- },
3658
3527
  options,
3659
- $context: contextPromise
3528
+ $context: contextPromise.then((result)=>{
3529
+ if (!result.isOk()) throw result.error;
3530
+ return result.value;
3531
+ }),
3532
+ router: router,
3533
+ handler,
3534
+ ...createNextHandlers(),
3535
+ getOpenAPISpec,
3536
+ getDocsUI
3660
3537
  };
3661
3538
  };
3662
- export { pkgs_types_namespaceObject as Types, c15tInstance };
3539
+ export { c15tInstance };