@consenti/api 0.2.0 → 0.4.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 (79) hide show
  1. package/README.md +578 -143
  2. package/dist/chunk-COR72NFQ.js +2 -0
  3. package/dist/chunk-COR72NFQ.js.map +1 -0
  4. package/dist/chunk-S2IEYESR.js +2 -0
  5. package/dist/chunk-S2IEYESR.js.map +1 -0
  6. package/dist/dashboard/assets/ApiConfig-CZMtYRfK.js +1 -0
  7. package/dist/dashboard/assets/ArchivedProfileList-BlQ2gEWz.js +1 -0
  8. package/dist/dashboard/assets/AuditLog-BpZoAFOe.js +1 -0
  9. package/dist/dashboard/assets/ChangePassword-BZkP2dXQ.js +1 -0
  10. package/dist/dashboard/assets/ConfirmDialog-BDlnfTdx.js +1 -0
  11. package/dist/dashboard/assets/ConsentList-DgJMrhih.js +1 -0
  12. package/dist/dashboard/assets/ConsentTemplateEditor-DA7B5aI_.js +1 -0
  13. package/dist/dashboard/assets/ConsentTemplateList-DMPd2y5s.js +1 -0
  14. package/dist/dashboard/assets/HeadingTagInput-D2S9xDMJ.js +1 -0
  15. package/dist/dashboard/assets/HowItWorks-CJCrdr3o.js +1 -0
  16. package/dist/dashboard/assets/PermissionGate-C69dhwV1.js +1 -0
  17. package/dist/dashboard/assets/PreviewPane-D7mDeBT8.js +38 -0
  18. package/dist/dashboard/assets/ProfileEditor-CSFdOweN.js +2 -0
  19. package/dist/dashboard/assets/ProfileList-C4cIDrM6.js +1 -0
  20. package/dist/dashboard/assets/ProfileVersionHistory-CX5-Oupy.js +3 -0
  21. package/dist/dashboard/assets/RecordDetailModal-DIpGxfqA.js +1 -0
  22. package/dist/dashboard/assets/Reports-B1Ww0ovT.js +1 -0
  23. package/dist/dashboard/assets/RoleList-CQ1GjR0W.js +1 -0
  24. package/dist/dashboard/assets/Select-C_JusbT5.js +1 -0
  25. package/dist/dashboard/assets/Settings-sIMVWQ0V.js +1 -0
  26. package/dist/dashboard/assets/SetupWizard-ChFBxqo3.js +1 -0
  27. package/dist/dashboard/assets/Table-BUxoz0YR.js +1 -0
  28. package/dist/dashboard/assets/TenantList-DCsT7ghb.js +1 -0
  29. package/dist/dashboard/assets/UITemplateEditor-BAaMnuOU.js +2 -0
  30. package/dist/dashboard/assets/UITemplateList-C3UMbnfs.js +1 -0
  31. package/dist/dashboard/assets/UserList-CHGNnS50.js +1 -0
  32. package/dist/dashboard/assets/VendorList-C-sswM1A.js +1 -0
  33. package/dist/dashboard/assets/VisitorList-DNB9Ia72.js +1 -0
  34. package/dist/dashboard/assets/check-D0g4XvmN.js +1 -0
  35. package/dist/dashboard/assets/client-CYntrO2g.js +1 -0
  36. package/dist/dashboard/assets/copy-DEi_W2TM.js +1 -0
  37. package/dist/dashboard/assets/createLucideIcon-DAiYBrnd.js +1 -0
  38. package/dist/dashboard/assets/de-jwngydrC.js +25 -0
  39. package/dist/dashboard/assets/debounce-DlvAAT2V.js +1 -0
  40. package/dist/dashboard/assets/dist-GoiMJCTt.js +1 -0
  41. package/dist/dashboard/assets/es-B6Jp0OPe.js +25 -0
  42. package/dist/dashboard/assets/external-link-CFZxxe3W.js +1 -0
  43. package/dist/dashboard/assets/fr-CshYcQPW.js +25 -0
  44. package/dist/dashboard/assets/index-Cr5M1Qy_.css +2 -0
  45. package/dist/dashboard/assets/index-Tr_BcjkN.js +26 -0
  46. package/dist/dashboard/assets/ja-CgjZNBrc.js +25 -0
  47. package/dist/dashboard/assets/profiles-C_SuoLJD.js +1 -0
  48. package/dist/dashboard/assets/roles-D7L936FV.js +1 -0
  49. package/dist/dashboard/assets/rotate-ccw-clock-6y2NDrJ7.js +1 -0
  50. package/dist/dashboard/assets/search-DKwfLBOv.js +1 -0
  51. package/dist/dashboard/assets/templates-CIyMjskA.js +1 -0
  52. package/dist/dashboard/assets/templates-DY68xNys.js +1 -0
  53. package/dist/dashboard/assets/trash-2-eX9s6x8V.js +1 -0
  54. package/dist/dashboard/assets/trash-O30ycMcz.js +1 -0
  55. package/dist/dashboard/assets/useHashQuery-BDjUPXDR.js +1 -0
  56. package/dist/dashboard/assets/users-BRrNOK0W.js +1 -0
  57. package/dist/dashboard/assets/x-BhZiH8AL.js +1 -0
  58. package/dist/dashboard/assets/zh-CN-BnLZkfBC.js +25 -0
  59. package/dist/dashboard/index.html +4 -2
  60. package/dist/dist-QJYW5KUK.js +2 -0
  61. package/dist/dist-QJYW5KUK.js.map +1 -0
  62. package/dist/index.cjs +90 -101
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +847 -150
  65. package/dist/index.d.ts +847 -150
  66. package/dist/index.js +90 -101
  67. package/dist/index.js.map +1 -1
  68. package/dist/profiles-FCX454HS.js +2 -0
  69. package/dist/profiles-FCX454HS.js.map +1 -0
  70. package/dist/widget/widget.css +1 -1
  71. package/dist/widget/widget.js +1 -1
  72. package/package.json +32 -17
  73. package/dist/dashboard/assets/de-DwE2aQfW.js +0 -5
  74. package/dist/dashboard/assets/es-Dq88TWkB.js +0 -5
  75. package/dist/dashboard/assets/fr-o_Pyg8eR.js +0 -5
  76. package/dist/dashboard/assets/index-BSsYDdb9.js +0 -40
  77. package/dist/dashboard/assets/index-bOTGevzl.css +0 -2
  78. package/dist/dashboard/assets/ja-CwgXYmpD.js +0 -5
  79. package/dist/dashboard/assets/zh-CN-ety9KoQ0.js +0 -5
package/dist/index.cjs CHANGED
@@ -1,150 +1,139 @@
1
- "use strict";var Ss=Object.create;var Ve=Object.defineProperty;var As=Object.getOwnPropertyDescriptor;var Ts=Object.getOwnPropertyNames;var Cs=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var Is=(s,e)=>{for(var t in e)Ve(s,t,{get:e[t],enumerable:!0})},on=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ts(e))!vs.call(s,i)&&i!==t&&Ve(s,i,{get:()=>e[i],enumerable:!(n=As(e,i))||n.enumerable});return s};var q=(s,e,t)=>(t=s!=null?Ss(Cs(s)):{},on(e||!s||!s.__esModule?Ve(t,"default",{value:s,enumerable:!0}):t,s)),Ps=s=>on(Ve({},"__esModule",{value:!0}),s);var zo={};Is(zo,{MongoDBAdapter:()=>ye,MySQLAdapter:()=>he,PostgreSQLAdapter:()=>_e,SQLiteAdapter:()=>ce,createConsenti:()=>Yo,dashboardDir:()=>$o});module.exports=Ps(zo);var bs=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,R=bs();var ds=require("node:events"),Re=require("node:fs/promises"),M=require("node:path"),Qt=require("node:url");var We=class{plugins=[];register(e){this.plugins=e}async initialize(e){for(let t of this.plugins)try{await t.initialize?.(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" initialize failed:`,n)}}async destroy(){for(let e of this.plugins)try{await e.destroy?.()}catch(t){console.warn(`[Consenti] Plugin "${e.name}" destroy failed:`,t)}}async runBeforeConsentSave(e){let t=e;for(let n of this.plugins)if(n.beforeConsentSave)try{t=await n.beforeConsentSave(t)}catch(i){console.warn(`[Consenti] Plugin "${n.name}" beforeConsentSave failed:`,i)}return t}async runAfterConsentSave(e){for(let t of this.plugins)if(t.afterConsentSave)try{await t.afterConsentSave(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" afterConsentSave failed:`,n)}}async runBeforeConsentUpdate(e){let t=e;for(let n of this.plugins)if(n.beforeConsentUpdate)try{t=await n.beforeConsentUpdate(t)}catch(i){console.warn(`[Consenti] Plugin "${n.name}" beforeConsentUpdate failed:`,i)}return t}async runAfterConsentUpdate(e){for(let t of this.plugins)if(t.afterConsentUpdate)try{await t.afterConsentUpdate(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" afterConsentUpdate failed:`,n)}}async runAfterProfileFetch(e){let t=e;for(let n of this.plugins)if(n.afterProfileFetch)try{t=await n.afterProfileFetch(t)}catch(i){console.warn(`[Consenti] Plugin "${n.name}" afterProfileFetch failed:`,i)}return t}async runBeforeUserCreate(e){let t=e;for(let n of this.plugins)if(n.beforeUserCreate)try{t=await n.beforeUserCreate(t)}catch(i){console.warn(`[Consenti] Plugin "${n.name}" beforeUserCreate failed:`,i)}return t}async runAfterUserCreate(e){for(let t of this.plugins)if(t.afterUserCreate)try{await t.afterUserCreate(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" afterUserCreate failed:`,n)}}};var bt=require("node:fs"),rn=require("node:path");function an(s,e,t={},n={}){let i={};return n.type!==void 0&&(i.type=n.type),n.gpc!==void 0&&(i.gpc=n.gpc),{appName:t.appName??"Consenti",appLogoPath:t?.appLogoPath??"/logo-dark.svg",hidePoweredBy:t.hidePoweredBy??!1,basePath:e,compliance:i}}function cn(s){return`<script>(function(){function d(o){if(o&&typeof o==='object')Object.keys(o).forEach(function(k){d(o[k])});return Object.freeze(o)}Object.defineProperty(window,'__CONSENTI_CONFIG__',{value:d(${JSON.stringify(s).replace(/<\/script>/gi,"<\\/script>")}),writable:false,configurable:false,enumerable:true})})()</script>`}function Te(s,e){let t=Buffer.from(s).toString("utf-8");return t.includes("</head>")?t.replace("</head>",`${e}</head>`):t.replace("</body>",`${e}</body>`)}var Os="https://vendor-list.consensu.org/v3/vendor-list.json";var re=null,ln=0,Ce=null;function Ds(s){return typeof s=="object"&&s!==null&&"vendors"in s&&"purposes"in s&&typeof s.vendors=="object"&&typeof s.purposes=="object"}async function ae(){if(re&&Date.now()-ln<6048e5)return re;try{let s=await fetch(Os,{signal:AbortSignal.timeout(15e3)});if(!s.ok)return re;let e=await s.json();return Ds(e)&&(re=e,ln=Date.now()),re}catch{return re}}function dn(){Ce||(ae(),Ce=setInterval(()=>{ae()},6048e5))}function un(){Ce&&(clearInterval(Ce),Ce=null)}var pn={ConsentRecord:{type:"object",properties:{id:{type:"string"},visitorId:{type:"string"},profileId:{type:"string"},profileVersion:{type:"integer"},locale:{type:"string"},consentJson:{type:"object",additionalProperties:{type:"string",enum:["granted","denied","objected"]}},gpcDetected:{type:"boolean"},source:{type:"string",enum:["banner","api","import"]},ageVerified:{type:"boolean"},tcfString:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}}},CreateConsentInput:{type:"object",required:["visitorId","profileId","consentJson"],properties:{visitorId:{type:"string"},profileId:{type:"string"},consentJson:{type:"object",additionalProperties:{type:"string"}},gpcDetected:{type:"boolean",default:!1},source:{type:"string",enum:["banner","api","import"],default:"banner"},ageVerified:{type:"boolean"},parentalConsentToken:{type:"string"},tcfString:{type:"string"}}}},Ot={openapi:"3.1.0",info:{title:"Consenti Public API",version:"0.1.0",description:"Visitor-facing endpoints for reading consent profiles and submitting/verifying consent. Rate-limited; no authentication required.",license:{name:"Apache 2.0",url:"https://www.apache.org/licenses/LICENSE-2.0"}},servers:[{url:"/consenti/api",description:"Consenti Public API"}],paths:{"/v1/profiles/{id}":{get:{tags:["Profile"],summary:"Get profile in its default locale",description:"Returns the resolved profile with banner and modal content for the profile's default locale. Includes `currentLocale`, `locales`, `cookies`, `mainBanner`, `preferenceModal`, and optionally `gpcBanner`.",parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Resolved profile for the default locale"},404:{description:"Profile not found"}}}},"/v1/profiles/{id}/{locale}":{get:{tags:["Profile"],summary:"Get profile resolved for a specific locale",description:"Same response shape as `GET /v1/profiles/{id}` but resolved for the requested locale, falling back to the default locale for any missing translations.",parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}},{name:"locale",in:"path",required:!0,schema:{type:"string",example:"fr"}}],responses:{200:{description:"Resolved profile for the requested locale"},404:{description:"Profile not found"}}}},"/v1/consent":{post:{tags:["Consent"],summary:"Submit consent",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/CreateConsentInput"}}}},responses:{200:{description:"Consent created or updated",content:{"application/json":{schema:{$ref:"#/components/schemas/ConsentRecord"}}}},400:{description:"Validation error"}}}},"/v1/consent/{visitorId}":{get:{tags:["Consent"],summary:"Get consent for visitor",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Consent record",content:{"application/json":{schema:{$ref:"#/components/schemas/ConsentRecord"}}}},404:{description:"Not found"}}},put:{tags:["Consent"],summary:"Update consent",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Updated consent"}}},delete:{tags:["Consent"],summary:"GDPR erasure \u2014 delete all consent data for visitor",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Erased successfully"}}}},"/v1/consent/{visitorId}/verify":{get:{tags:["Consent"],summary:"Verify consent validity",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Verification result"}}}}},components:{schemas:pn}},Dt={openapi:"3.1.0",info:{title:"Consenti Admin API",version:"0.1.0",description:"Authenticated endpoints for managing profiles, consent records, users, analytics, and exports. All routes (except `/auth/login`) require `Authorization: Bearer <JWT>`. Obtain a token via `POST /auth/login`.",license:{name:"Apache 2.0",url:"https://www.apache.org/licenses/LICENSE-2.0"}},servers:[{url:"/consenti/admin",description:"Consenti Admin API"}],paths:{"/auth/login":{post:{tags:["Auth"],summary:"Login with email + password",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{email:{type:"string"},password:{type:"string"}}}}}},responses:{200:{description:"JWT token"}}}},"/auth/me":{get:{tags:["Auth"],summary:"Get current user",security:[{BearerAuth:[]}],responses:{200:{description:"Current admin user info"}}}},"/auth/logout":{post:{tags:["Auth"],summary:"Invalidate session",security:[{BearerAuth:[]}],responses:{200:{description:"Logged out"}}}},"/auth/oidc/authorize":{get:{tags:["Auth"],summary:"Start OIDC authorization (PKCE)",responses:{302:{description:"Redirect to OIDC provider"}}}},"/auth/oidc/callback":{get:{tags:["Auth"],summary:"OIDC callback \u2014 exchange code for token",responses:{200:{description:"JWT token"}}}},"/auth/saml/metadata":{get:{tags:["Auth"],summary:"SAML SP metadata XML",responses:{200:{description:"SAML metadata XML",content:{"application/xml":{}}}}}},"/auth/saml/acs":{post:{tags:["Auth"],summary:"SAML Assertion Consumer Service",responses:{200:{description:"JWT token"}}}},"/auth/totp/setup":{post:{tags:["Auth"],summary:"Setup TOTP MFA",security:[{BearerAuth:[]}],responses:{200:{description:"TOTP secret and QR URL"}}}},"/auth/totp/verify":{post:{tags:["Auth"],summary:"Verify and enable TOTP",security:[{BearerAuth:[]}],responses:{200:{description:"TOTP enabled"}}}},"/profiles":{get:{tags:["Profiles"],summary:"List profiles",security:[{BearerAuth:[]}],responses:{200:{description:"Array of profiles"}}},post:{tags:["Profiles"],summary:"Create profile",security:[{BearerAuth:[]}],responses:{201:{description:"Created profile"}}}},"/consents":{get:{tags:["Consents"],summary:"List consent records",security:[{BearerAuth:[]}],parameters:[{name:"page",in:"query",schema:{type:"integer"}},{name:"profileId",in:"query",schema:{type:"string"}},{name:"from",in:"query",schema:{type:"string",format:"date"}},{name:"to",in:"query",schema:{type:"string",format:"date"}}],responses:{200:{description:"Paginated consent records"}}}},"/stats/overview":{get:{tags:["Stats"],summary:"Overview statistics",security:[{BearerAuth:[]}],responses:{200:{description:"Totals and acceptance rates"}}}},"/stats/timeline":{get:{tags:["Stats"],summary:"Daily consent timeline",security:[{BearerAuth:[]}],parameters:[{name:"days",in:"query",schema:{type:"integer",default:30}}],responses:{200:{description:"Array of date+count"}}}},"/stats/countries":{get:{tags:["Stats"],summary:"Consent by country",security:[{BearerAuth:[]}],responses:{200:{description:"Country counts"}}}},"/stats/gpc":{get:{tags:["Stats"],summary:"GPC detection stats",security:[{BearerAuth:[]}],responses:{200:{description:"GPC rate and counts"}}}},"/export/consents":{get:{tags:["Export"],summary:"Export consent records",security:[{BearerAuth:[]}],parameters:[{name:"format",in:"query",schema:{type:"string",enum:["csv","json"]}},{name:"from",in:"query",schema:{type:"string",format:"date"}},{name:"to",in:"query",schema:{type:"string",format:"date"}}],responses:{200:{description:"CSV or JSON download"}}}},"/tenants":{get:{tags:["Sites"],summary:"List all sites/tenants",security:[{BearerAuth:[]}],responses:{200:{description:"Array of tenants"}}},post:{tags:["Sites"],summary:"Create a site/tenant",security:[{BearerAuth:[]}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{name:{type:"string"},slug:{type:"string"}},required:["name","slug"]}}}},responses:{201:{description:"Created tenant"}}}},"/tenants/{id}":{put:{tags:["Sites"],summary:"Update a site/tenant",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Updated tenant"}}},delete:{tags:["Sites"],summary:"Delete a site/tenant",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Deleted"}}}}},components:{securitySchemes:{BearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}},schemas:pn}};var w=require("node:crypto");function de(){return`prof_${(0,w.randomBytes)(20).toString("hex")}`}function mn(s){return(0,w.createHash)("sha256").update(s).digest("hex")}function gn(s){return(0,w.createHash)("sha256").update(s).digest("hex")}function fn(s,e){return(0,w.createHmac)("sha256",e).update(s).digest("hex")}function ve(s){let e=(0,w.randomBytes)(16).toString("hex"),t=(0,w.scryptSync)(s,e,64).toString("hex");return`${e}:${t}`}function yn(s,e){let[t,n]=e.split(":");if(!t||!n)return!1;let i=(0,w.scryptSync)(s,t,64).toString("hex");return(0,w.timingSafeEqual)(Buffer.from(n,"hex"),Buffer.from(i,"hex"))}function Lt(s,e,t=3600){let n=Math.floor(Date.now()/1e3),i=btoa(JSON.stringify({alg:"HS256",typ:"JWT"})).replace(/=/g,""),o=btoa(JSON.stringify({...s,iat:n,exp:n+t})).replace(/=/g,""),r=fn(`${i}.${o}`,e).match(/.{2}/g).map(c=>String.fromCharCode(parseInt(c,16))).join(""),a=btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return`${i}.${o}.${a}`}function Je(s,e){let t=s.split(".");if(t.length!==3)return null;let[n,i,o]=t;if(!n||!i||!o)return null;let r=fn(`${n}.${i}`,e),a=atob(o.replace(/-/g,"+").replace(/_/g,"/")),c=Array.from(a).map(d=>d.charCodeAt(0).toString(16).padStart(2,"0")).join(""),l=Buffer.from(r,"hex"),u=Buffer.from(c,"hex");if(l.length!==u.length||!(0,w.timingSafeEqual)(l,u))return null;try{let d=JSON.parse(atob(i)),p=d.exp;return typeof p=="number"&&Date.now()/1e3>p?null:d}catch{return null}}var K=require("node:fs"),H=require("node:path"),hn=require("node:url"),Ls={"node:sqlite":"consenti.db","better-sqlite3":"consenti.db","node-sqlite3-wasm":"consenti.db",sqlite:"consenti.db",json:"consenti-data.json",mongodb:"",mysql:"",postgresql:""},Us=(0,H.dirname)((0,hn.fileURLToPath)(R));function ks(s){let e=s.includes("node_modules"),t=s.startsWith((0,H.resolve)(Us,"..",".."));return e||t}function Q(s,e){let t=(0,H.resolve)(s),n=(0,H.extname)(t);if(n&&(console.warn(`[consenti] storage.path "${s}" looks like a file path (has extension "${n}"). Treating parent directory as storage root. Update your config to pass a directory path.`),t=(0,H.dirname)(t)),ks(t))throw new Error(`[consenti] storage.path "${t}" is inside the package installation directory. Choose a writable directory outside node_modules.`);(0,K.existsSync)(t)||(0,K.mkdirSync)(t,{recursive:!0});try{(0,K.accessSync)(t,K.constants.W_OK)}catch{throw new Error(`[consenti] storage.path "${t}" is not writable.`)}let i=(0,H.join)(t,"db"),o=(0,H.join)(t,"profiles"),r=(0,H.join)(t,"logs");(0,K.mkdirSync)(i,{recursive:!0}),(0,K.mkdirSync)(o,{recursive:!0}),(0,K.mkdirSync)(r,{recursive:!0});let a=Ls[e]??"consenti.db",c=a?(0,H.join)(i,a):"";return{basePath:t,dbPath:c,profilesDir:o,logsDir:r}}var _n={name:"tenants",cols:[{n:"id",t:"pk"},{n:"name",t:"text"},{n:"slug",t:"text",unique:!0},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},En={name:"profiles",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"name",t:"text"},{n:"default_locale",t:"text_sm",def:"en"},{n:"version",t:"int",def:1},{n:"profile_json",t:"json"},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},Ns={name:"consent_records",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"visitor_id",t:"text"},{n:"profile_id",t:"text",ref:"profiles"},{n:"profile_version",t:"int"},{n:"locale",t:"text_sm"},{n:"consent_json",t:"json"},{n:"gpc_detected",t:"bool",def:!1},{n:"source",t:"text_sm"},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}],uq:[{cols:["visitor_id","profile_id"]}]},Ms={name:"consent_records",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"visitor_id",t:"text"},{n:"profile_id",t:"text",ref:"profiles"},{n:"profile_version",t:"int"},{n:"locale",t:"text_sm"},{n:"consent_json",t:"json"},{n:"gpc_detected",t:"bool",def:!1},{n:"source",t:"text_sm"},{n:"age_verified",t:"bool",def:!1},{n:"parental_consent_token",t:"longtext",null:!0},{n:"tcf_string",t:"longtext",null:!0},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}],uq:[{cols:["visitor_id","profile_id"]}]},wn={name:"consent_history",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"consent_record_id",t:"text",ref:"consent_records"},{n:"visitor_id",t:"text"},{n:"old_json",t:"json",null:!0},{n:"new_json",t:"json"},{n:"action",t:"text_sm"},{n:"created_at",t:"ts",def:"$now"}]},Rn={name:"visitors",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"visitor_id",t:"text",unique:!0},{n:"country",t:"text_geo",null:!0},{n:"region",t:"text_md",null:!0},{n:"city",t:"text_md",null:!0},{n:"ip_hash",t:"text_hash",null:!0},{n:"user_agent_hash",t:"text_hash",null:!0},{n:"first_seen",t:"ts",def:"$now"},{n:"last_seen",t:"ts",def:"$now",mysqlUpd:!0}]},Gs={name:"users",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"name",t:"text"},{n:"email",t:"text",unique:!0},{n:"password_hash",t:"text"},{n:"is_active",t:"bool",def:!0},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},xs={name:"users",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"name",t:"text"},{n:"email",t:"text",unique:!0},{n:"password_hash",t:"text"},{n:"is_active",t:"bool",def:!0},{n:"totp_secret",t:"longtext",null:!0},{n:"totp_enabled",t:"bool",def:!1},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},Sn={name:"roles",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"name",t:"text_md"},{n:"description",t:"text",null:!0}]},An={name:"permissions",cols:[{n:"id",t:"pk"},{n:"name",t:"text_md",unique:!0},{n:"description",t:"text",null:!0}]},Fs={name:"user_roles",cols:[{n:"user_id",t:"text",ref:"users"},{n:"role_id",t:"text",ref:"roles"}],pk:["user_id","role_id"]},Hs={name:"user_roles",cols:[{n:"user_id",t:"text",ref:"users"},{n:"role_id",t:"text",ref:"roles"},{n:"tenant_id",t:"text",def:"default"}],pk:["user_id","role_id","tenant_id"]},Tn={name:"role_permissions",cols:[{n:"role_id",t:"text",ref:"roles"},{n:"permission_id",t:"text",ref:"permissions"}],pk:["role_id","permission_id"]},Cn={name:"audit_logs",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"user_id",t:"text",null:!0},{n:"action",t:"text_md"},{n:"resource_type",t:"text_md"},{n:"resource_id",t:"text",null:!0},{n:"old_data",t:"json",null:!0},{n:"new_data",t:"json",null:!0},{n:"created_at",t:"ts",def:"$now"}]},js={name:"api_keys",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants",onDel:"CASCADE"},{n:"key_hash",t:"text_hash",unique:!0},{n:"name",t:"text"},{n:"is_active",t:"bool",def:!0},{n:"created_at",t:"ts",def:"$now"}]},$s={name:"cookie_templates",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants",onDel:"CASCADE"},{n:"name",t:"text"},{n:"cookies_json",t:"json",def:"$arr"},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},Bs={name:"ui_templates",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants",onDel:"CASCADE"},{n:"name",t:"text"},{n:"settings_json",t:"json",def:"$obj"},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},Vs=[_n,En,Ns,wn,Rn,Gs,Sn,An,Fs,Tn,Cn],Ws=[_n,En,Ms,wn,Rn,xs,Sn,An,Hs,Tn,Cn],vn=[js],In=[$s,Bs];function Js(s){return s==="$now"?"DEFAULT (datetime('now'))":s==="$arr"?"DEFAULT '[]'":s==="$obj"?"DEFAULT '{}'":s===!0?"DEFAULT 1":s===!1?"DEFAULT 0":typeof s=="string"?`DEFAULT '${s}'`:`DEFAULT ${s}`}function qs(s){if(s.t==="pk")return`${s.n} TEXT PRIMARY KEY`;let e=s.t==="int"||s.t==="bool"?"INTEGER":"TEXT",t=[`${s.n} ${e}`];return s.null||t.push("NOT NULL"),s.def!==void 0&&t.push(Js(s.def)),s.unique&&t.push("UNIQUE"),s.ref&&(t.push(`REFERENCES ${s.ref}(id)`),s.onDel&&t.push(`ON DELETE ${s.onDel}`)),t.join(" ")}function Ks(s){let e=s.cols.map(t=>` ${qs(t)}`);if(s.pk&&e.push(` PRIMARY KEY (${s.pk.join(", ")})`),s.uq)for(let t of s.uq)e.push(` UNIQUE(${t.cols.join(", ")})`);return`CREATE TABLE IF NOT EXISTS ${s.name} (
1
+ "use strict";var tc=Object.create;var gt=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var ic=Object.getOwnPropertyNames;var oc=Object.getPrototypeOf,rc=Object.prototype.hasOwnProperty;var T=(i,e)=>()=>(i&&(e=i(i=0)),e);var Pn=(i,e)=>{for(var t in e)gt(i,t,{get:e[t],enumerable:!0})},Li=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ic(e))!rc.call(i,o)&&o!==t&&gt(i,o,{get:()=>e[o],enumerable:!(n=nc(e,o))||n.enumerable});return i};var Z=(i,e,t)=>(t=i!=null?tc(oc(i)):{},Li(e||!i||!i.__esModule?gt(t,"default",{value:i,enumerable:!0}):t,i)),sc=i=>Li(gt({},"__esModule",{value:!0}),i);var ac,f,p=T(()=>{"use strict";ac=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,f=ac()});var Vt,Vn=T(()=>{"use strict";p();Vt={complianceGroup:"opt-in",gpcMode:"ignore",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1},functionality_storage:{purpose:"functional",listenGpc:!1},personalization_storage:{purpose:"preferences",listenGpc:!1},analytics_storage:{purpose:"analytics",listenGpc:!0},ad_storage:{purpose:"marketing",listenGpc:!0,cpraCategory:"sharing"}},translations:{en:{mainBanner:{position:"bottom",heading:"We value your privacy",htmlText:"We use cookies and similar technologies to enhance your browsing experience, analyse site traffic, and show you personalised content. Non-essential cookies require your consent under the GDPR and ePrivacy Directive.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"reject-optional":{text:"Reject Optional",style:"primary",action:"custom",cookies:"!"},"manage-preferences":{text:"Manage Preferences",style:"text",action:"manage"}}},gpcBanner:{position:"bottom",heading:"Global Privacy Control detected",htmlText:"Your browser is sending a Global Privacy Control signal. We have applied your preference and will not set non-essential cookies unless you change your settings below.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"confirm-settings":{text:"Confirm Settings",style:"primary",action:"custom",cookies:"!"},"manage-preferences":{text:"Manage Preferences",style:"text",action:"manage"}}},preferenceModal:{position:"right",heading:"Privacy Preferences",subheading:"Manage your consent settings for each category below.",htmlText:"You can choose which cookie categories you allow. Your choices apply to this site only. Essential cookies cannot be disabled as they are required for the site to function correctly.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"reject-optional":{text:"Reject Optional",style:"primary",action:"custom",cookies:"!"},"save-preferences":{text:"Save My Preferences",style:"primary",action:"submit"}},categories:{necessary:{heading:"Strictly Necessary",htmlText:"These cookies are required for the website to function and cannot be disabled. They are usually set in response to actions you take, such as setting your privacy preferences, logging in, or filling in forms.",legalBasis:"mandatory",cookies:["security_storage"]},functional:{heading:"Functional",htmlText:"These cookies enable enhanced functionality and personalisation. They may be set by us or by third-party providers whose services we have added to our pages. If you do not allow these cookies, some or all of these features may not function properly.",legalBasis:"consent",cookies:["functionality_storage","personalization_storage"]},analytics:{heading:"Analytics",htmlText:"These cookies allow us to count visits and traffic sources so we can measure and improve site performance. They help us understand which pages are most and least popular. All information collected is aggregated and therefore anonymous.",legalBasis:"consent",cookies:["analytics_storage"]},marketing:{heading:"Marketing",htmlText:"These cookies may be set through our site by advertising partners to build a profile of your interests and show you relevant adverts on other sites. They do not store personal information directly but identify your browser and device uniquely.",legalBasis:"consent",cookies:["ad_storage"]}}}}}}});var Wt,Wn=T(()=>{"use strict";p();Wt={complianceGroup:"opt-out",gpcMode:"honor",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1},functionality_storage:{purpose:"functional",listenGpc:!0},personalization_storage:{purpose:"preferences",listenGpc:!0},analytics_storage:{purpose:"analytics",listenGpc:!0},ad_storage:{purpose:"marketing",listenGpc:!0,cpraCategory:"sharing"}},translations:{en:{mainBanner:{position:"bottom",heading:"We use cookies",htmlText:"We and our partners use cookies and similar tracking technologies to improve your experience, analyse site usage, and show relevant advertising. You may opt out of the sale or sharing of your personal data at any time.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"do-not-sell-share":{text:"Do Not Sell or Share My Personal Information",style:"secondary",action:"custom",cookies:"!"},"manage-preferences":{text:"Manage Preferences",style:"text",action:"manage"}}},gpcBanner:{position:"bottom",heading:"Your opt-out has been applied",htmlText:"Your browser sent a Global Privacy Control signal. We have automatically opted you out of the sale and sharing of your personal data as required by applicable US state privacy laws.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"confirm-opt-out":{text:"Confirm Opt-Out",style:"secondary",action:"custom",cookies:"!"},"manage-preferences":{text:"Manage Preferences",style:"text",action:"manage"}}},preferenceModal:{position:"right",heading:"Cookie Preferences",subheading:"Manage your data preferences. You may opt out of non-essential uses at any time.",htmlText:"Under applicable US state privacy laws, you have the right to opt out of the sale and sharing of your personal data. Toggle the categories below to exercise your rights.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"opt-out-all":{text:"Opt Out of All",style:"secondary",action:"custom",cookies:"!"},"save-choices":{text:"Save My Choices",style:"primary",action:"submit"}},categories:{necessary:{heading:"Strictly Necessary",htmlText:"These cookies are required for the website to operate and cannot be disabled. They do not involve the sale or sharing of personal data.",legalBasis:"mandatory",cookies:["security_storage"]},functional:{heading:"Functional",htmlText:"These cookies improve the functionality of the site. Disabling them may affect how the site operates. You may opt out at any time.",legalBasis:"consent",cookies:["functionality_storage","personalization_storage"]},analytics:{heading:"Analytics",htmlText:"Analytics cookies help us understand how visitors interact with the site. Opting out prevents your data from being included in usage statistics.",legalBasis:"consent",cookies:["analytics_storage"]},marketing:{heading:"Sale / Sharing of Personal Data",htmlText:"These cookies involve the sale or sharing of your personal data with advertising partners for targeted advertising. You have the right to opt out of this under applicable US state privacy laws.",legalBasis:"consent",cookies:["ad_storage"]}}}}}}});var qt,qn=T(()=>{"use strict";p();qt={complianceGroup:"opt-out-strict",gpcMode:"honor",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1},functionality_storage:{purpose:"functional",listenGpc:!0,cpraCategory:"sharing"},personalization_storage:{purpose:"preferences",listenGpc:!0,cpraCategory:"sharing"},analytics_storage:{purpose:"analytics",listenGpc:!0,cpraCategory:"sharing"},ad_storage:{purpose:"marketing",listenGpc:!0,cpraCategory:"sharing"},sensitive_info_storage:{purpose:"marketing",listenGpc:!0,cpraCategory:"sensitive"}},translations:{en:{mainBanner:{position:"bottom",heading:"Your California Privacy Rights",htmlText:"Under the California Privacy Rights Act (CPRA), you have the right to opt out of the sale, sharing, and use of sensitive personal information. We use cookies and tracking technologies that may involve the sale or sharing of your data with third parties.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"opt-out-sale-sharing-sensitive":{text:"Opt Out of Sale, Sharing & Sensitive Use",style:"secondary",action:"custom",cookies:"!"},manage:{text:"Manage",style:"text",action:"manage"}}},gpcBanner:{position:"bottom",heading:"GPC opt-out applied automatically",htmlText:"Your browser sent a Global Privacy Control signal. Under the CPRA, we are required to honor this as a Do Not Sell or Share My Personal Information request. Your opt-out has been applied automatically.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"confirm-opt-out":{text:"Confirm Opt-Out",style:"secondary",action:"custom",cookies:"!"},"review-choices":{text:"Review Choices",style:"text",action:"manage"}}},preferenceModal:{position:"right",heading:"Privacy Rights Center",subheading:"Manage your CPRA rights: opt out of sale, sharing, and limit the use of sensitive personal information.",htmlText:"As a California resident, you have the right under CPRA to opt out of the sale and sharing of your personal information, including for cross-context behavioral advertising, and to limit the use of your sensitive personal information. Toggle each category below to exercise your rights.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"opt-out-sale-sharing-sensitive":{text:"Opt Out of Sale, Sharing & Sensitive Use",style:"secondary",action:"custom",cookies:"!"},"save-choices":{text:"Save My Choices",style:"primary",action:"submit"}},categories:{necessary:{heading:"Strictly Necessary",htmlText:"Essential to deliver the service. These cookies are not sold or shared and cannot be disabled.",legalBasis:"mandatory",cookies:["security_storage"]},functional:{heading:"Functional & Personalisation",htmlText:"Improve site functionality and remember your preferences. May involve sharing of browsing data.",legalBasis:"consent",cookies:["functionality_storage","personalization_storage"]},analytics:{heading:"Analytics (Sharing)",htmlText:'Measure site performance. Analytics data may be shared with third-party providers, which constitutes "sharing" under CPRA.',legalBasis:"consent",cookies:["analytics_storage"]},marketing:{heading:"Sale & Sharing of Personal Data",htmlText:"Advertising and retargeting cookies that involve the sale or sharing of your personal data with third-party advertisers for cross-context behavioural advertising.",legalBasis:"consent",cookies:["ad_storage"]},sensitive:{heading:"Sensitive Personal Information",htmlText:"Some technologies may use sensitive personal information as defined by CPRA (e.g. precise geolocation, health data). You have the right to limit such use.",legalBasis:"consent",cookies:["sensitive_info_storage"]}}}}}}});var Jt,Jn=T(()=>{"use strict";p();Jt={complianceGroup:"opt-in-dpdpa",gpcMode:"ignore",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1},functionality_storage:{purpose:"functional",listenGpc:!1},personalization_storage:{purpose:"preferences",listenGpc:!1},analytics_storage:{purpose:"analytics",listenGpc:!1},ad_storage:{purpose:"marketing",listenGpc:!1}},translations:{en:{mainBanner:{position:"bottom",heading:"Data Protection Notice",htmlText:"We are the Data Fiduciary under India's Digital Personal Data Protection Act (DPDPA). Your explicit consent is required before we process your personal data using non-essential cookies. You may withdraw consent at any time without affecting prior processing.",buttons:{"consent-all":{text:"I Consent",style:"primary",action:"custom",cookies:"*"},"deny-all":{text:"I Do Not Consent",style:"secondary",action:"custom",cookies:"!"},"review-choices":{text:"Review Choices",style:"text",action:"manage"}}},preferenceModal:{position:"right",heading:"Consent Preferences",subheading:"Review the purposes for which we process your personal data and provide or withdraw consent for each.",htmlText:"Under the Digital Personal Data Protection Act (DPDPA) 2023, you have the right to give, manage, and withdraw consent for personal data processing. Legitimate interest is not a valid legal basis under the DPDPA \u2014 all data processing requires your explicit consent.",buttons:{"consent-all":{text:"Give Consent to All",style:"primary",action:"custom",cookies:"*"},"withdraw-all":{text:"Withdraw All Consent",style:"secondary",action:"custom",cookies:"!"},"save-choices":{text:"Save Choices",style:"secondary",action:"submit"}},categories:{necessary:{heading:"Strictly Necessary",htmlText:"Required to deliver the core service. No personal data is shared and consent is not required for these.",legalBasis:"mandatory",cookies:["security_storage"]},functional:{heading:"Functional",htmlText:"Enable enhanced features and personalisation. Your explicit consent is required under the DPDPA before we process data for these purposes.",legalBasis:"consent",cookies:["functionality_storage","personalization_storage"]},analytics:{heading:"Analytics",htmlText:"Help us understand how you interact with the site. Your consent is required before any analytics data is collected.",legalBasis:"consent",cookies:["analytics_storage"]},marketing:{heading:"Marketing & Advertising",htmlText:"Allow personalised advertising based on your browsing activity. Requires your explicit consent under the DPDPA.",legalBasis:"consent",cookies:["ad_storage"]}}}}}}});var zt,zn=T(()=>{"use strict";p();zt={complianceGroup:"opt-in-china",gpcMode:"ignore",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1},functionality_storage:{purpose:"functional",listenGpc:!1},personalization_storage:{purpose:"preferences",listenGpc:!1},analytics_storage:{purpose:"analytics",listenGpc:!1},ad_storage:{purpose:"marketing",listenGpc:!1}},translations:{en:{mainBanner:{position:"bottom",heading:"Personal Information Processing Notice",htmlText:"In accordance with China's Personal Information Protection Law (PIPL), Data Security Law (DSL), and Cybersecurity Law (CSL), we process personal information only for specified, explicit, and legitimate purposes with minimum data collection. Your consent is required for non-essential cookies.",buttons:{"agree-all":{text:"Agree to All",style:"primary",action:"custom",cookies:"*"},"reject-non-necessary":{text:"Reject Non-Necessary",style:"secondary",action:"custom",cookies:"!"},"manage-preferences":{text:"Manage Preferences",style:"text",action:"manage"}}},preferenceModal:{position:"right",heading:"Personal Information Processing Settings",subheading:"Review the purpose and scope of each category of personal information processing.",htmlText:"Under the PIPL, you have the right to know, decide, and restrict the processing of your personal information. Processing is limited to the stated purposes. Cross-border transfers of your data, if any, are handled in accordance with Chapter III of the PIPL, including security assessments or standard contracts where applicable.",buttons:{"agree-all":{text:"Agree to All",style:"primary",action:"custom",cookies:"*"},"disagree-all":{text:"Disagree to All",style:"secondary",action:"custom",cookies:"!"},"confirm-settings":{text:"Confirm Settings",style:"primary",action:"submit"}},categories:{necessary:{heading:"Necessary for Service",htmlText:"Required to deliver the core service and ensure network security under the CSL. Cannot be disabled.",legalBasis:"mandatory",cookies:["security_storage"]},functional:{heading:"Functionality & Personalisation",htmlText:"Enable enhanced features. Personal information is processed only for the stated purposes and retained for no longer than necessary.",legalBasis:"consent",cookies:["functionality_storage","personalization_storage"]},analytics:{heading:"Statistical Analysis",htmlText:"Collect and analyse usage data to improve the service. Data is processed within China unless cross-border transfer requirements are satisfied.",legalBasis:"consent",cookies:["analytics_storage"]},marketing:{heading:"Targeted Advertising",htmlText:"Personalise advertisements based on your interactions. Requires explicit consent under PIPL. You may withdraw consent and object to personalised advertising at any time.",legalBasis:"consent",cookies:["ad_storage"]}}}}}}});var Kt,Kn=T(()=>{"use strict";p();Kt={complianceGroup:"opt-in-brazil",gpcMode:"ignore",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1},functionality_storage:{purpose:"functional",listenGpc:!1},personalization_storage:{purpose:"preferences",listenGpc:!1},analytics_storage:{purpose:"analytics",listenGpc:!1},ad_storage:{purpose:"marketing",listenGpc:!1}},translations:{en:{mainBanner:{position:"bottom",heading:"We value your privacy",htmlText:"In accordance with Brazil's Lei Geral de Prote\xE7\xE3o de Dados (LGPD), we process personal data only with a valid legal basis. Non-essential cookies require your prior consent. You may withdraw consent at any time. Legitimate interest applies where noted.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"reject-optional":{text:"Reject Optional",style:"secondary",action:"custom",cookies:"!"},manage:{text:"Manage",style:"text",action:"manage"}}},preferenceModal:{position:"right",heading:"Privacy Preferences",subheading:"Review and manage your data processing preferences under the LGPD.",htmlText:"You have rights under the LGPD including: access, correction, deletion, portability, and withdrawal of consent. Categories based on legitimate interest are indicated below \u2014 you may object to these at any time.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"reject-optional":{text:"Reject Optional",style:"secondary",action:"custom",cookies:"!"},"save-preferences":{text:"Save My Preferences",style:"primary",action:"submit"}},categories:{necessary:{heading:"Strictly Necessary",htmlText:"Essential for the service to function. Legal basis: fulfillment of a contract or legal obligation. Cannot be disabled.",legalBasis:"mandatory",cookies:["security_storage"]},functional:{heading:"Functional",htmlText:"Enhance site functionality and remember your settings. Legal basis: legitimate interest (LGPD Art. 7, X). You may object to this processing at any time.",legalBasis:"legitimate_interest",legitimateInterestDescription:"Remembering a visitor's in-session preferences (e.g. layout, saved settings) is necessary to deliver the functionality they engaged with, has minimal privacy impact since no data is shared with third parties, and is limited to what a visitor would reasonably expect from using the site, per the balancing test required by LGPD Art. 10.",cookies:["functionality_storage","personalization_storage"]},analytics:{heading:"Analytics",htmlText:"Help us understand how visitors use the site so we can improve it. Legal basis: your consent.",legalBasis:"consent",cookies:["analytics_storage"]},marketing:{heading:"Marketing & Advertising",htmlText:"Personalise ads and measure campaign effectiveness. Legal basis: your consent. You may withdraw consent at any time without affecting the lawfulness of prior processing.",legalBasis:"consent",cookies:["ad_storage"]}}}}}}});var Yt,Yn=T(()=>{"use strict";p();Yt={complianceGroup:"general-privacy-consent",gpcMode:"ignore",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1},functionality_storage:{purpose:"functional",listenGpc:!1},personalization_storage:{purpose:"preferences",listenGpc:!1},analytics_storage:{purpose:"analytics",listenGpc:!1},ad_storage:{purpose:"marketing",listenGpc:!1}},translations:{en:{mainBanner:{position:"bottom",heading:"We use cookies",htmlText:"We use cookies to improve your browsing experience, analyse site traffic, and show you relevant content. By continuing to use this site, you accept our use of cookies. You can manage your preferences at any time.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"reject-marketing":{text:"Reject Marketing",style:"secondary",action:"custom",cookies:["security_storage","functionality_storage","personalization_storage","analytics_storage"]},"manage-preferences":{text:"Manage Preferences",style:"text",action:"manage"}}},preferenceModal:{position:"right",heading:"Cookie Settings",subheading:"We document the legal basis for each category of cookie we use.",htmlText:"A privacy notice or consent framework applies in your jurisdiction. While a strict cookie consent banner may not be legally required, we document our legal basis for processing to follow privacy best practices.",buttons:{"accept-all":{text:"Accept All",style:"primary",action:"custom",cookies:"*"},"necessary-only":{text:"Necessary Only",style:"secondary",action:"custom",cookies:"!"},"save-preferences":{text:"Save My Settings",style:"primary",action:"submit"}},categories:{necessary:{heading:"Strictly Necessary",htmlText:"Required to deliver the service. No optional data processing takes place. Cannot be disabled.",legalBasis:"mandatory",cookies:["security_storage"]},functional:{heading:"Functional",htmlText:"Improve how the site works and remember your preferences. Legal basis: legitimate interest.",legalBasis:"legitimate_interest",legitimateInterestDescription:"Remembering a visitor's in-session preferences (e.g. layout, saved settings) is a low-privacy-impact processing activity that a visitor would reasonably expect from using the site, and is necessary to deliver the functionality they engaged with \u2014 our interest in providing it is not overridden by the visitor's privacy interest, since no data leaves the site and nothing is used for profiling or advertising.",cookies:["functionality_storage","personalization_storage"]},analytics:{heading:"Analytics",htmlText:"Help us understand usage patterns to improve the site. Legal basis: legitimate interest. Data is aggregated and anonymised where possible.",legalBasis:"legitimate_interest",legitimateInterestDescription:"Measuring aggregate, anonymised site usage to improve performance and content is a reasonable, low-risk business interest that does not identify individual visitors or feed advertising/profiling, and is proportionate to the minimal impact on visitor privacy.",cookies:["analytics_storage"]},marketing:{heading:"Marketing",htmlText:"Personalise advertising and measure campaign reach. Legal basis: your consent. You may withdraw consent at any time.",legalBasis:"consent",cookies:["ad_storage"]}}}}}}});var Qt,Qn=T(()=>{"use strict";p();Qt={complianceGroup:"notice-only",gpcMode:"ignore",defaultLocale:"en",expiryDays:365,cookies:{security_storage:{purpose:"necessary",listenGpc:!1}},translations:{en:{mainBanner:{position:"bottom",heading:"This site uses essential cookies only",htmlText:"We use strictly necessary cookies to ensure this website functions correctly. No tracking, advertising, or analytics cookies are used. No specific cookie consent law applies in your jurisdiction.",buttons:{ok:{text:"OK",style:"primary",action:"close"}}},preferenceModal:{position:"right",heading:"Cookie Information",subheading:"We only use cookies that are strictly necessary for this site to work.",htmlText:"This site does not use optional cookies. The only cookie set is required to maintain basic security and session integrity. You cannot disable it without affecting site functionality.",buttons:{close:{text:"Close",style:"primary",action:"close"}},categories:{necessary:{heading:"Strictly Necessary",htmlText:"Required for the site to function. These cookies do not track you and cannot be disabled.",legalBasis:"mandatory",cookies:["security_storage"]}}}}}}});var xo,Mo=T(()=>{"use strict";p();xo={mainBanner:{heading:"Wir sch\xE4tzen Ihre Privatsph\xE4re",htmlText:"Wir verwenden Cookies, um Ihre Browser-Erfahrung zu verbessern, personalisierte Inhalte oder Anzeigen bereitzustellen und unseren Datenverkehr zu analysieren. Mit dem Klicken auf <strong>Alle akzeptieren</strong> stimmen Sie der Verwendung von Cookies zu. Sie k\xF6nnen Ihre Einstellungen jederzeit \xE4ndern.",buttons:{"accept-all":"Alle akzeptieren","reject-optional":"Alle ablehnen","manage-preferences":"Einstellungen verwalten"}},gpcBanner:{heading:"Datenschutzpr\xE4ferenz erkannt",htmlText:"Ihr Browser hat ein Global Privacy Control (GPC) Signal gesendet. Wir haben Ihre Datenschutzpr\xE4ferenz ber\xFCcksichtigt.",buttons:{"accept-all":"Einstellungen \xFCberpr\xFCfen","confirm-settings":"Weiter"}},preferenceModal:{heading:"Datenschutzeinstellungen",subheading:"W\xE4hlen Sie aus, welche Cookies Sie erlauben.",htmlText:"Wir verwenden verschiedene Cookie-Typen. Sie k\xF6nnen die einzelnen Kategorien aktivieren oder deaktivieren. Notwendige Cookies k\xF6nnen nicht deaktiviert werden.",buttons:{"accept-all":"Alle akzeptieren","reject-optional":"Alle ablehnen","save-preferences":"Auswahl speichern"},categories:{"cat-necessary":{heading:"Unbedingt erforderlich",htmlText:"Diese Cookies sind f\xFCr das Funktionieren der Website unbedingt erforderlich und k\xF6nnen nicht deaktiviert werden."},"cat-functional":{heading:"Funktional",htmlText:"Erm\xF6glichen erweiterte Funktionen wie gespeicherte Pr\xE4ferenzen und Personalisierung."},"cat-preferences":{heading:"Pr\xE4ferenzen",htmlText:"Speichern Ihre pers\xF6nlichen Einstellungen und Pr\xE4ferenzen f\xFCr zuk\xFCnftige Besuche."},"cat-analytics":{heading:"Analyse",htmlText:"Helfen uns zu verstehen, wie Besucher mit unserer Website interagieren."},"cat-marketing":{heading:"Marketing",htmlText:"Werden verwendet, um Ihnen relevante Werbung anzuzeigen."}}}}});var Uo,Go=T(()=>{"use strict";p();Uo={mainBanner:{heading:"Valoramos su privacidad",htmlText:"Utilizamos cookies para mejorar su experiencia de navegaci\xF3n, mostrar anuncios o contenido personalizados y analizar nuestro tr\xE1fico. Al hacer clic en <strong>Aceptar todo</strong>, consiente el uso de cookies. Puede cambiar sus preferencias en cualquier momento.",buttons:{"accept-all":"Aceptar todo","reject-optional":"Rechazar todo","manage-preferences":"Gestionar preferencias"}},gpcBanner:{heading:"Preferencia de privacidad reconocida",htmlText:"Su navegador ha enviado una se\xF1al Global Privacy Control (GPC). Hemos aplicado su preferencia de privacidad.",buttons:{"accept-all":"Revisar preferencias","confirm-settings":"Continuar"}},preferenceModal:{heading:"Preferencias de privacidad",subheading:"Elija qu\xE9 cookies desea permitir.",htmlText:"Utilizamos distintos tipos de cookies. Puede activar o desactivar cada categor\xEDa. Las cookies necesarias no pueden desactivarse.",buttons:{"accept-all":"Aceptar todo","reject-optional":"Rechazar todo","save-preferences":"Guardar selecci\xF3n"},categories:{"cat-necessary":{heading:"Estrictamente necesarias",htmlText:"Estas cookies son imprescindibles para el funcionamiento del sitio web y no pueden desactivarse."},"cat-functional":{heading:"Funcionales",htmlText:"Permiten funciones avanzadas como preferencias guardadas y personalizaci\xF3n."},"cat-preferences":{heading:"Preferencias",htmlText:"Guardan su configuraci\xF3n personal y preferencias para visitas futuras."},"cat-analytics":{heading:"Anal\xEDticas",htmlText:"Nos ayudan a entender c\xF3mo los visitantes interact\xFAan con nuestro sitio web."},"cat-marketing":{heading:"Marketing",htmlText:"Se utilizan para mostrarle publicidad relevante."}}}}});var jo,Bo=T(()=>{"use strict";p();jo={mainBanner:{heading:"Nous respectons votre vie priv\xE9e",htmlText:"Nous utilisons des cookies pour am\xE9liorer votre exp\xE9rience de navigation, afficher des publicit\xE9s ou du contenu personnalis\xE9s et analyser notre trafic. En cliquant sur <strong>Tout accepter</strong>, vous consentez \xE0 l'utilisation des cookies. Vous pouvez modifier vos pr\xE9f\xE9rences \xE0 tout moment.",buttons:{"accept-all":"Tout accepter","reject-optional":"Tout refuser","manage-preferences":"G\xE9rer les pr\xE9f\xE9rences"}},gpcBanner:{heading:"Pr\xE9f\xE9rence de confidentialit\xE9 reconnue",htmlText:"Votre navigateur a envoy\xE9 un signal Global Privacy Control (GPC). Nous avons appliqu\xE9 votre pr\xE9f\xE9rence de confidentialit\xE9.",buttons:{"accept-all":"V\xE9rifier les pr\xE9f\xE9rences","confirm-settings":"Continuer"}},preferenceModal:{heading:"Param\xE8tres de confidentialit\xE9",subheading:"Choisissez les cookies que vous souhaitez autoriser.",htmlText:"Nous utilisons diff\xE9rents types de cookies. Vous pouvez activer ou d\xE9sactiver chaque cat\xE9gorie. Les cookies n\xE9cessaires ne peuvent pas \xEAtre d\xE9sactiv\xE9s.",buttons:{"accept-all":"Tout accepter","reject-optional":"Tout refuser","save-preferences":"Enregistrer la s\xE9lection"},categories:{"cat-necessary":{heading:"Strictement n\xE9cessaires",htmlText:"Ces cookies sont indispensables au fonctionnement du site web et ne peuvent pas \xEAtre d\xE9sactiv\xE9s."},"cat-functional":{heading:"Fonctionnels",htmlText:"Permettent des fonctionnalit\xE9s avanc\xE9es comme les pr\xE9f\xE9rences enregistr\xE9es et la personnalisation."},"cat-preferences":{heading:"Pr\xE9f\xE9rences",htmlText:"Sauvegardent vos param\xE8tres personnels et pr\xE9f\xE9rences pour les visites futures."},"cat-analytics":{heading:"Analytiques",htmlText:"Nous aident \xE0 comprendre comment les visiteurs interagissent avec notre site web."},"cat-marketing":{heading:"Marketing",htmlText:"Sont utilis\xE9s pour vous afficher des publicit\xE9s pertinentes."}}}}});var Fo,$o=T(()=>{"use strict";p();Fo={mainBanner:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u3092\u5927\u5207\u306B\u3057\u3066\u3044\u307E\u3059",htmlText:"\u30D6\u30E9\u30A6\u30B8\u30F3\u30B0\u4F53\u9A13\u306E\u5411\u4E0A\u3001\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u5E83\u544A\u30FB\u30B3\u30F3\u30C6\u30F3\u30C4\u306E\u8868\u793A\u3001\u30C8\u30E9\u30D5\u30A3\u30C3\u30AF\u5206\u6790\u306E\u305F\u3081\u306BCookie\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002<strong>\u3059\u3079\u3066\u540C\u610F</strong>\u3092\u30AF\u30EA\u30C3\u30AF\u3059\u308B\u3053\u3068\u3067\u3001Cookie\u306E\u4F7F\u7528\u306B\u540C\u610F\u3057\u305F\u3053\u3068\u306B\u306A\u308A\u307E\u3059\u3002\u8A2D\u5B9A\u306F\u3044\u3064\u3067\u3082\u5909\u66F4\u3067\u304D\u307E\u3059\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","reject-optional":"\u3059\u3079\u3066\u62D2\u5426","manage-preferences":"\u8A2D\u5B9A\u3092\u7BA1\u7406"}},gpcBanner:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A\u304C\u691C\u51FA\u3055\u308C\u307E\u3057\u305F",htmlText:"\u30D6\u30E9\u30A6\u30B6\u304B\u3089Global Privacy Control\uFF08GPC\uFF09\u30B7\u30B0\u30CA\u30EB\u304C\u9001\u4FE1\u3055\u308C\u307E\u3057\u305F\u3002\u304A\u5BA2\u69D8\u306E\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A\u3092\u9069\u7528\u3057\u307E\u3057\u305F\u3002",buttons:{"accept-all":"\u8A2D\u5B9A\u3092\u78BA\u8A8D","confirm-settings":"\u7D9A\u884C"}},preferenceModal:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A",subheading:"\u8A31\u53EF\u3059\u308BCookie\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",htmlText:"\u3055\u307E\u3056\u307E\u306A\u7A2E\u985E\u306ECookie\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002\u5404\u30AB\u30C6\u30B4\u30EA\u3092\u6709\u52B9\u307E\u305F\u306F\u7121\u52B9\u306B\u3059\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u3059\u3002\u5FC5\u9808Cookie\u306F\u7121\u52B9\u306B\u3067\u304D\u307E\u305B\u3093\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","reject-optional":"\u3059\u3079\u3066\u62D2\u5426","save-preferences":"\u9078\u629E\u3092\u4FDD\u5B58"},categories:{"cat-necessary":{heading:"\u5FC5\u9808",htmlText:"\u3053\u308C\u3089\u306ECookie\u306F\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u306E\u6A5F\u80FD\u306B\u4E0D\u53EF\u6B20\u3067\u3042\u308A\u3001\u7121\u52B9\u306B\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002"},"cat-functional":{heading:"\u6A5F\u80FD",htmlText:"\u4FDD\u5B58\u3055\u308C\u305F\u8A2D\u5B9A\u3084\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BC\u30FC\u30B7\u30E7\u30F3\u306A\u3069\u306E\u9AD8\u5EA6\u306A\u6A5F\u80FD\u3092\u6709\u52B9\u306B\u3057\u307E\u3059\u3002"},"cat-preferences":{heading:"\u8A2D\u5B9A",htmlText:"\u5C06\u6765\u306E\u8A2A\u554F\u306E\u305F\u3081\u306B\u500B\u4EBA\u8A2D\u5B9A\u3084\u597D\u307F\u3092\u4FDD\u5B58\u3057\u307E\u3059\u3002"},"cat-analytics":{heading:"\u5206\u6790",htmlText:"\u8A2A\u554F\u8005\u304C\u3069\u306E\u3088\u3046\u306B\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u3092\u5229\u7528\u3057\u3066\u3044\u308B\u304B\u3092\u7406\u89E3\u3059\u308B\u306E\u306B\u5F79\u7ACB\u3061\u307E\u3059\u3002"},"cat-marketing":{heading:"\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0",htmlText:"\u95A2\u9023\u3059\u308B\u5E83\u544A\u3092\u8868\u793A\u3059\u308B\u305F\u3081\u306B\u4F7F\u7528\u3055\u308C\u307E\u3059\u3002"}}}}});var Ho,Vo=T(()=>{"use strict";p();Ho={mainBanner:{heading:"Wir verwenden Cookies",htmlText:"Wir verwenden Cookies, um unsere Dienste zu verbessern. Sie k\xF6nnen dem Verkauf oder der Weitergabe Ihrer pers\xF6nlichen Daten jederzeit widersprechen.",buttons:{"accept-all":"Alle akzeptieren","do-not-sell-share":"Nicht verkaufen oder weitergeben","manage-preferences":"Einstellungen verwalten"}},gpcBanner:{heading:"GPC erkannt \u2013 Opt-out angewendet",htmlText:"Ihr Browser hat ein Global Privacy Control Signal gesendet. Wir haben Sie vom Verkauf und der Weitergabe Ihrer Daten abgemeldet.",buttons:{"accept-all":"Einstellungen \xFCberpr\xFCfen","confirm-opt-out":"Weiter"}},preferenceModal:{heading:"Datenschutzeinstellungen",subheading:"W\xE4hlen Sie Ihre Datenschutzoptionen.",buttons:{"accept-all":"Alle akzeptieren","opt-out-all":"Nicht verkaufen oder weitergeben","save-choices":"Auswahl speichern"},categories:{"cat-necessary":{heading:"Unbedingt erforderlich",htmlText:"Diese Cookies sind f\xFCr das Funktionieren der Website unbedingt erforderlich."},"cat-functional":{heading:"Funktional",htmlText:"Erm\xF6glichen erweiterte Funktionen und Personalisierung."},"cat-preferences":{heading:"Pr\xE4ferenzen",htmlText:"Speichern Ihre Einstellungen f\xFCr zuk\xFCnftige Besuche."},"cat-analytics":{heading:"Analyse",htmlText:"Helfen uns zu verstehen, wie Besucher unsere Website nutzen."},"cat-marketing":{heading:"Werbung / Verkauf",htmlText:"Erm\xF6glichen gezielte Werbung. Sie k\xF6nnen dem Verkauf Ihrer Daten widersprechen."}}}}});var Wo,qo=T(()=>{"use strict";p();Wo={mainBanner:{heading:"Utilizamos cookies",htmlText:"Utilizamos cookies para mejorar nuestros servicios. Puede oponerse a la venta o al intercambio de sus datos personales en cualquier momento.",buttons:{"accept-all":"Aceptar todo","do-not-sell-share":"No vender ni compartir","manage-preferences":"Gestionar preferencias"}},gpcBanner:{heading:"GPC detectado \u2013 exclusi\xF3n aplicada",htmlText:"Su navegador ha enviado una se\xF1al Global Privacy Control. Le hemos excluido de la venta y el intercambio de sus datos.",buttons:{"accept-all":"Revisar preferencias","confirm-opt-out":"Continuar"}},preferenceModal:{heading:"Preferencias de privacidad",subheading:"Elija sus opciones de privacidad.",buttons:{"accept-all":"Aceptar todo","opt-out-all":"No vender ni compartir","save-choices":"Guardar selecci\xF3n"},categories:{"cat-necessary":{heading:"Estrictamente necesarias",htmlText:"Imprescindibles para el funcionamiento del sitio web."},"cat-functional":{heading:"Funcionales",htmlText:"Permiten funciones avanzadas y personalizaci\xF3n."},"cat-preferences":{heading:"Preferencias",htmlText:"Guardan su configuraci\xF3n para visitas futuras."},"cat-analytics":{heading:"Anal\xEDticas",htmlText:"Nos ayudan a entender c\xF3mo los visitantes utilizan nuestro sitio."},"cat-marketing":{heading:"Publicidad / Venta",htmlText:"Permiten publicidad dirigida. Puede oponerse a la venta de sus datos."}}}}});var Jo,zo=T(()=>{"use strict";p();Jo={mainBanner:{heading:"Nous utilisons des cookies",htmlText:"Nous utilisons des cookies pour am\xE9liorer nos services. Vous pouvez vous opposer \xE0 la vente ou au partage de vos donn\xE9es personnelles \xE0 tout moment.",buttons:{"accept-all":"Tout accepter","do-not-sell-share":"Ne pas vendre ni partager","manage-preferences":"G\xE9rer les pr\xE9f\xE9rences"}},gpcBanner:{heading:"GPC d\xE9tect\xE9 \u2013 exclusion appliqu\xE9e",htmlText:"Votre navigateur a envoy\xE9 un signal Global Privacy Control. Nous avons appliqu\xE9 votre demande de ne pas vendre ni partager vos donn\xE9es.",buttons:{"accept-all":"V\xE9rifier les pr\xE9f\xE9rences","confirm-opt-out":"Continuer"}},preferenceModal:{heading:"Param\xE8tres de confidentialit\xE9",subheading:"Choisissez vos options de confidentialit\xE9.",buttons:{"accept-all":"Tout accepter","opt-out-all":"Ne pas vendre ni partager","save-choices":"Enregistrer la s\xE9lection"},categories:{"cat-necessary":{heading:"Strictement n\xE9cessaires",htmlText:"Indispensables au fonctionnement du site web."},"cat-functional":{heading:"Fonctionnels",htmlText:"Permettent des fonctionnalit\xE9s avanc\xE9es et la personnalisation."},"cat-preferences":{heading:"Pr\xE9f\xE9rences",htmlText:"Sauvegardent vos param\xE8tres pour les visites futures."},"cat-analytics":{heading:"Analytiques",htmlText:"Nous aident \xE0 comprendre comment les visiteurs utilisent notre site."},"cat-marketing":{heading:"Publicit\xE9 / Vente",htmlText:"Permettent la publicit\xE9 cibl\xE9e. Vous pouvez vous opposer \xE0 la vente de vos donn\xE9es."}}}}});var Ko,Yo=T(()=>{"use strict";p();Ko={mainBanner:{heading:"Cookie\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059",htmlText:"\u30B5\u30FC\u30D3\u30B9\u5411\u4E0A\u306E\u305F\u3081\u306BCookie\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002\u500B\u4EBA\u30C7\u30FC\u30BF\u306E\u8CA9\u58F2\u3084\u5171\u6709\u306B\u306F\u3044\u3064\u3067\u3082\u7570\u8B70\u3092\u7533\u3057\u7ACB\u3066\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u3059\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","do-not-sell-share":"\u8CA9\u58F2\u30FB\u5171\u6709\u3057\u306A\u3044","manage-preferences":"\u8A2D\u5B9A\u3092\u7BA1\u7406"}},gpcBanner:{heading:"GPC\u691C\u51FA \u2013 \u30AA\u30D7\u30C8\u30A2\u30A6\u30C8\u9069\u7528\u6E08\u307F",htmlText:"\u30D6\u30E9\u30A6\u30B6\u304B\u3089Global Privacy Control\u30B7\u30B0\u30CA\u30EB\u304C\u9001\u4FE1\u3055\u308C\u307E\u3057\u305F\u3002\u30C7\u30FC\u30BF\u306E\u8CA9\u58F2\u304A\u3088\u3073\u5171\u6709\u304B\u3089\u30AA\u30D7\u30C8\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F\u3002",buttons:{"accept-all":"\u8A2D\u5B9A\u3092\u78BA\u8A8D","confirm-opt-out":"\u7D9A\u884C"}},preferenceModal:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A",subheading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","opt-out-all":"\u8CA9\u58F2\u30FB\u5171\u6709\u3057\u306A\u3044","save-choices":"\u9078\u629E\u3092\u4FDD\u5B58"},categories:{"cat-necessary":{heading:"\u5FC5\u9808",htmlText:"\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u306E\u6A5F\u80FD\u306B\u4E0D\u53EF\u6B20\u3067\u3059\u3002"},"cat-functional":{heading:"\u6A5F\u80FD",htmlText:"\u9AD8\u5EA6\u306A\u6A5F\u80FD\u3068\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BC\u30FC\u30B7\u30E7\u30F3\u3092\u6709\u52B9\u306B\u3057\u307E\u3059\u3002"},"cat-preferences":{heading:"\u8A2D\u5B9A",htmlText:"\u5C06\u6765\u306E\u8A2A\u554F\u306E\u305F\u3081\u306B\u8A2D\u5B9A\u3092\u4FDD\u5B58\u3057\u307E\u3059\u3002"},"cat-analytics":{heading:"\u5206\u6790",htmlText:"\u8A2A\u554F\u8005\u306E\u30B5\u30A4\u30C8\u5229\u7528\u72B6\u6CC1\u3092\u628A\u63E1\u3059\u308B\u306E\u306B\u5F79\u7ACB\u3061\u307E\u3059\u3002"},"cat-marketing":{heading:"\u5E83\u544A\u30FB\u8CA9\u58F2",htmlText:"\u30BF\u30FC\u30B2\u30C3\u30C8\u5E83\u544A\u3092\u53EF\u80FD\u306B\u3057\u307E\u3059\u3002\u30C7\u30FC\u30BF\u306E\u8CA9\u58F2\u306B\u7570\u8B70\u3092\u7533\u3057\u7ACB\u3066\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u3059\u3002"}}}}});var Qo,Zo=T(()=>{"use strict";p();Qo={mainBanner:{heading:"Datenschutzrechte in Kalifornien",htmlText:"Gem\xE4\xDF dem California Privacy Rights Act (CPRA) haben Sie das Recht, dem Verkauf, der Weitergabe und der Verwendung Ihrer pers\xF6nlichen Daten zu widersprechen.",buttons:{"accept-all":"Alle akzeptieren","opt-out-sale-sharing-sensitive":"Meine Daten nicht verkaufen oder teilen",manage:"Einstellungen verwalten"}},gpcBanner:{heading:"GPC erkannt \u2013 CPRA-Opt-out angewendet",htmlText:"Ihr Global Privacy Control Signal wurde erkannt. Ihr Recht auf Opt-out gem\xE4\xDF CPRA wurde automatisch angewendet.",buttons:{"accept-all":"Einstellungen \xFCberpr\xFCfen","confirm-opt-out":"Weiter"}},preferenceModal:{heading:"Datenschutzeinstellungen (CPRA)",subheading:"Verwalten Sie Ihre Datenschutzrechte.",buttons:{"accept-all":"Alle akzeptieren","opt-out-sale-sharing-sensitive":"Meine Daten nicht verkaufen oder teilen","save-choices":"Auswahl speichern"},categories:{"cat-necessary":{heading:"Unbedingt erforderlich",htmlText:"F\xFCr den Betrieb der Website unbedingt erforderlich."},"cat-functional":{heading:"Funktional",htmlText:"Erm\xF6glichen erweiterte Funktionen."},"cat-preferences":{heading:"Pr\xE4ferenzen",htmlText:"Speichern Ihre pers\xF6nlichen Einstellungen."},"cat-analytics":{heading:"Analyse",htmlText:"Helfen uns, die Website-Nutzung zu verstehen."},"cat-marketing":{heading:"Verkauf / Weitergabe (CPRA)",htmlText:"Verkauf und Weitergabe pers\xF6nlicher Daten gem\xE4\xDF CPRA. Sie k\xF6nnen widersprechen."}}}}});var Xo,er=T(()=>{"use strict";p();Xo={mainBanner:{heading:"Derechos de privacidad en California",htmlText:"De acuerdo con la Ley de Derechos de Privacidad de California (CPRA), tiene derecho a oponerse a la venta, el intercambio y el uso de sus datos personales.",buttons:{"accept-all":"Aceptar todo","opt-out-sale-sharing-sensitive":"No vender ni compartir mis datos",manage:"Gestionar preferencias"}},gpcBanner:{heading:"GPC detectado \u2013 exclusi\xF3n CPRA aplicada",htmlText:"Se ha detectado su se\xF1al Global Privacy Control. Su derecho de exclusi\xF3n seg\xFAn la CPRA se ha aplicado autom\xE1ticamente.",buttons:{"accept-all":"Revisar preferencias","confirm-opt-out":"Continuar"}},preferenceModal:{heading:"Configuraci\xF3n de privacidad (CPRA)",subheading:"Administre sus derechos de privacidad.",buttons:{"accept-all":"Aceptar todo","opt-out-sale-sharing-sensitive":"No vender ni compartir mis datos","save-choices":"Guardar selecci\xF3n"},categories:{"cat-necessary":{heading:"Estrictamente necesarias",htmlText:"Imprescindibles para el funcionamiento del sitio."},"cat-functional":{heading:"Funcionales",htmlText:"Permiten funciones avanzadas."},"cat-preferences":{heading:"Preferencias",htmlText:"Guardan su configuraci\xF3n personal."},"cat-analytics":{heading:"Anal\xEDticas",htmlText:"Nos ayudan a entender el uso del sitio."},"cat-marketing":{heading:"Venta / Intercambio (CPRA)",htmlText:"Venta e intercambio de datos personales seg\xFAn la CPRA. Puede oponerse."}}}}});var tr,nr=T(()=>{"use strict";p();tr={mainBanner:{heading:"Droits \xE0 la vie priv\xE9e en Californie",htmlText:"Conform\xE9ment au California Privacy Rights Act (CPRA), vous avez le droit de vous opposer \xE0 la vente, au partage et \xE0 l'utilisation de vos donn\xE9es personnelles.",buttons:{"accept-all":"Tout accepter","opt-out-sale-sharing-sensitive":"Ne pas vendre ni partager mes donn\xE9es",manage:"G\xE9rer les pr\xE9f\xE9rences"}},gpcBanner:{heading:"GPC d\xE9tect\xE9 \u2013 exclusion CPRA appliqu\xE9e",htmlText:"Votre signal Global Privacy Control a \xE9t\xE9 d\xE9tect\xE9. Votre droit d'exclusion selon la CPRA a \xE9t\xE9 appliqu\xE9 automatiquement.",buttons:{"accept-all":"V\xE9rifier les pr\xE9f\xE9rences","confirm-opt-out":"Continuer"}},preferenceModal:{heading:"Param\xE8tres de confidentialit\xE9 (CPRA)",subheading:"G\xE9rez vos droits \xE0 la vie priv\xE9e.",buttons:{"accept-all":"Tout accepter","opt-out-sale-sharing-sensitive":"Ne pas vendre ni partager mes donn\xE9es","save-choices":"Enregistrer la s\xE9lection"},categories:{"cat-necessary":{heading:"Strictement n\xE9cessaires",htmlText:"Indispensables au fonctionnement du site."},"cat-functional":{heading:"Fonctionnels",htmlText:"Permettent des fonctionnalit\xE9s avanc\xE9es."},"cat-preferences":{heading:"Pr\xE9f\xE9rences",htmlText:"Sauvegardent vos param\xE8tres personnels."},"cat-analytics":{heading:"Analytiques",htmlText:"Nous aident \xE0 comprendre l'utilisation du site."},"cat-marketing":{heading:"Vente / Partage (CPRA)",htmlText:"Vente et partage de donn\xE9es personnelles selon la CPRA. Vous pouvez vous y opposer."}}}}});var ir,or=T(()=>{"use strict";p();ir={mainBanner:{heading:"\u30AB\u30EA\u30D5\u30A9\u30EB\u30CB\u30A2\u5DDE\u306E\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u6A29",htmlText:"\u30AB\u30EA\u30D5\u30A9\u30EB\u30CB\u30A2\u30FB\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u6A29\u6CD5\uFF08CPRA\uFF09\u306B\u57FA\u3065\u304D\u3001\u304A\u5BA2\u69D8\u306B\u306F\u500B\u4EBA\u30C7\u30FC\u30BF\u306E\u8CA9\u58F2\u30FB\u5171\u6709\u30FB\u5229\u7528\u306B\u7570\u8B70\u3092\u7533\u3057\u7ACB\u3066\u308B\u6A29\u5229\u304C\u3042\u308A\u307E\u3059\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","opt-out-sale-sharing-sensitive":"\u8CA9\u58F2\u30FB\u5171\u6709\u3057\u306A\u3044",manage:"\u8A2D\u5B9A\u3092\u7BA1\u7406"}},gpcBanner:{heading:"GPC\u691C\u51FA \u2013 CPRA\u30AA\u30D7\u30C8\u30A2\u30A6\u30C8\u9069\u7528\u6E08\u307F",htmlText:"\u30D6\u30E9\u30A6\u30B6\u304B\u3089Global Privacy Control\u30B7\u30B0\u30CA\u30EB\u304C\u691C\u51FA\u3055\u308C\u307E\u3057\u305F\u3002CPRA\u306B\u57FA\u3065\u304F\u30AA\u30D7\u30C8\u30A2\u30A6\u30C8\u6A29\u304C\u81EA\u52D5\u7684\u306B\u9069\u7528\u3055\u308C\u307E\u3057\u305F\u3002",buttons:{"accept-all":"\u8A2D\u5B9A\u3092\u78BA\u8A8D","confirm-opt-out":"\u7D9A\u884C"}},preferenceModal:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A\uFF08CPRA\uFF09",subheading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u6A29\u3092\u7BA1\u7406\u3057\u3066\u304F\u3060\u3055\u3044\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","opt-out-sale-sharing-sensitive":"\u8CA9\u58F2\u30FB\u5171\u6709\u3057\u306A\u3044","save-choices":"\u9078\u629E\u3092\u4FDD\u5B58"},categories:{"cat-necessary":{heading:"\u5FC5\u9808",htmlText:"\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u306E\u52D5\u4F5C\u306B\u4E0D\u53EF\u6B20\u3067\u3059\u3002"},"cat-functional":{heading:"\u6A5F\u80FD",htmlText:"\u9AD8\u5EA6\u306A\u6A5F\u80FD\u3092\u6709\u52B9\u306B\u3057\u307E\u3059\u3002"},"cat-preferences":{heading:"\u8A2D\u5B9A",htmlText:"\u500B\u4EBA\u8A2D\u5B9A\u3092\u4FDD\u5B58\u3057\u307E\u3059\u3002"},"cat-analytics":{heading:"\u5206\u6790",htmlText:"\u30B5\u30A4\u30C8\u5229\u7528\u72B6\u6CC1\u306E\u628A\u63E1\u306B\u5F79\u7ACB\u3066\u307E\u3059\u3002"},"cat-marketing":{heading:"\u8CA9\u58F2\u30FB\u5171\u6709\uFF08CPRA\uFF09",htmlText:"CPRA\u306B\u57FA\u3065\u304F\u500B\u4EBA\u30C7\u30FC\u30BF\u306E\u8CA9\u58F2\u304A\u3088\u3073\u5171\u6709\u3002\u7570\u8B70\u3092\u7533\u3057\u7ACB\u3066\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u3059\u3002"}}}}});var rr,sr=T(()=>{"use strict";p();rr={mainBanner:{heading:"Datenschutzhinweis",htmlText:"Wir sind der f\xFCr die Datenverarbeitung Verantwortliche gem\xE4\xDF dem Digitalen Personaldatenschutzgesetz (DPDPA) Indiens. Ihre Einwilligung ist erforderlich, bevor wir Ihre personenbezogenen Daten verarbeiten.",buttons:{"consent-all":"Ich stimme zu","deny-all":"Ich stimme nicht zu","review-choices":"Auswahl \xFCberpr\xFCfen"}},preferenceModal:{heading:"Datenschutzeinstellungen (DPDPA)",subheading:"Bitte w\xE4hlen Sie aus, in welche Verarbeitungen Sie einwilligen.",buttons:{"consent-all":"Ich stimme zu","withdraw-all":"Ich stimme nicht zu","save-choices":"Auswahl speichern"},categories:{"cat-necessary":{heading:"Unbedingt erforderlich",htmlText:"F\xFCr den Betrieb der Website unbedingt erforderlich. Keine Einwilligung erforderlich."},"cat-functional":{heading:"Funktional",htmlText:"Erm\xF6glichen erweiterte Funktionen. Ihre Einwilligung ist gem\xE4\xDF DPDPA erforderlich."},"cat-preferences":{heading:"Pr\xE4ferenzen",htmlText:"Speichern Ihre pers\xF6nlichen Einstellungen. Einwilligung gem\xE4\xDF DPDPA erforderlich."},"cat-analytics":{heading:"Analyse",htmlText:"Helfen uns, die Website-Nutzung zu verstehen. Einwilligung gem\xE4\xDF DPDPA erforderlich."},"cat-marketing":{heading:"Marketing",htmlText:"Erm\xF6glichen personalisierte Werbung. Einwilligung gem\xE4\xDF DPDPA erforderlich."}}}}});var ar,cr=T(()=>{"use strict";p();ar={mainBanner:{heading:"Aviso de protecci\xF3n de datos",htmlText:"Somos el Fiduciario de Datos seg\xFAn la Ley de Protecci\xF3n de Datos Digitales Personales (DPDPA) de India. Su consentimiento es necesario antes de que procesemos sus datos personales.",buttons:{"consent-all":"Doy mi consentimiento","deny-all":"No doy mi consentimiento","review-choices":"Revisar opciones"}},preferenceModal:{heading:"Configuraci\xF3n de privacidad (DPDPA)",subheading:"Elija en qu\xE9 procesamientos desea dar su consentimiento.",buttons:{"consent-all":"Doy mi consentimiento","withdraw-all":"No doy mi consentimiento","save-choices":"Guardar selecci\xF3n"},categories:{"cat-necessary":{heading:"Estrictamente necesarias",htmlText:"Imprescindibles para el funcionamiento del sitio. No requieren consentimiento."},"cat-functional":{heading:"Funcionales",htmlText:"Permiten funciones avanzadas. Su consentimiento es requerido seg\xFAn la DPDPA."},"cat-preferences":{heading:"Preferencias",htmlText:"Guardan su configuraci\xF3n personal. Se requiere consentimiento seg\xFAn la DPDPA."},"cat-analytics":{heading:"Anal\xEDticas",htmlText:"Nos ayudan a entender el uso del sitio. Se requiere consentimiento seg\xFAn la DPDPA."},"cat-marketing":{heading:"Marketing",htmlText:"Permiten publicidad personalizada. Se requiere consentimiento seg\xFAn la DPDPA."}}}}});var lr,dr=T(()=>{"use strict";p();lr={mainBanner:{heading:"Avis de protection des donn\xE9es",htmlText:"Nous sommes le Fiduciaire de donn\xE9es au sens de la loi indienne sur la protection des donn\xE9es personnelles num\xE9riques (DPDPA). Votre consentement est requis avant que nous traitions vos donn\xE9es personnelles.",buttons:{"consent-all":"Je consens","deny-all":"Je ne consens pas","review-choices":"Examiner les choix"}},preferenceModal:{heading:"Param\xE8tres de confidentialit\xE9 (DPDPA)",subheading:"Choisissez les traitements auxquels vous consentez.",buttons:{"consent-all":"Je consens","withdraw-all":"Je ne consens pas","save-choices":"Enregistrer la s\xE9lection"},categories:{"cat-necessary":{heading:"Strictement n\xE9cessaires",htmlText:"Indispensables au fonctionnement du site. Aucun consentement requis."},"cat-functional":{heading:"Fonctionnels",htmlText:"Permettent des fonctionnalit\xE9s avanc\xE9es. Votre consentement est requis selon la DPDPA."},"cat-preferences":{heading:"Pr\xE9f\xE9rences",htmlText:"Sauvegardent vos param\xE8tres personnels. Consentement requis selon la DPDPA."},"cat-analytics":{heading:"Analytiques",htmlText:"Nous aident \xE0 comprendre l'utilisation du site. Consentement requis selon la DPDPA."},"cat-marketing":{heading:"Marketing",htmlText:"Permettent la publicit\xE9 personnalis\xE9e. Consentement requis selon la DPDPA."}}}}});var ur,pr=T(()=>{"use strict";p();ur={mainBanner:{heading:"\u30C7\u30FC\u30BF\u4FDD\u8B77\u306B\u95A2\u3059\u308B\u304A\u77E5\u3089\u305B",htmlText:"\u5F53\u793E\u306F\u30A4\u30F3\u30C9\u306E\u30C7\u30B8\u30BF\u30EB\u500B\u4EBA\u30C7\u30FC\u30BF\u4FDD\u8B77\u6CD5\uFF08DPDPA\uFF09\u306B\u57FA\u3065\u304F\u30C7\u30FC\u30BF\u53D7\u8A17\u8005\u3067\u3059\u3002\u304A\u5BA2\u69D8\u306E\u500B\u4EBA\u30C7\u30FC\u30BF\u3092\u51E6\u7406\u3059\u308B\u524D\u306B\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002",buttons:{"consent-all":"\u540C\u610F\u3059\u308B","deny-all":"\u540C\u610F\u3057\u306A\u3044","review-choices":"\u9078\u629E\u3092\u78BA\u8A8D"}},preferenceModal:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A\uFF08DPDPA\uFF09",subheading:"\u540C\u610F\u3059\u308B\u51E6\u7406\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",buttons:{"consent-all":"\u540C\u610F\u3059\u308B","withdraw-all":"\u540C\u610F\u3057\u306A\u3044","save-choices":"\u9078\u629E\u3092\u4FDD\u5B58"},categories:{"cat-necessary":{heading:"\u5FC5\u9808",htmlText:"\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u306E\u52D5\u4F5C\u306B\u4E0D\u53EF\u6B20\u3067\u3059\u3002\u540C\u610F\u306F\u4E0D\u8981\u3067\u3059\u3002"},"cat-functional":{heading:"\u6A5F\u80FD",htmlText:"\u9AD8\u5EA6\u306A\u6A5F\u80FD\u3092\u6709\u52B9\u306B\u3057\u307E\u3059\u3002DPDPA\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"},"cat-preferences":{heading:"\u8A2D\u5B9A",htmlText:"\u500B\u4EBA\u8A2D\u5B9A\u3092\u4FDD\u5B58\u3057\u307E\u3059\u3002DPDPA\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"},"cat-analytics":{heading:"\u5206\u6790",htmlText:"\u30B5\u30A4\u30C8\u5229\u7528\u72B6\u6CC1\u306E\u628A\u63E1\u306B\u4F7F\u7528\u3057\u307E\u3059\u3002DPDPA\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"},"cat-marketing":{heading:"\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0",htmlText:"\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u5E83\u544A\u3092\u53EF\u80FD\u306B\u3057\u307E\u3059\u3002DPDPA\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"}}}}});var mr,gr=T(()=>{"use strict";p();mr={mainBanner:{heading:"Hinweis zur Verarbeitung personenbezogener Daten",htmlText:"Gem\xE4\xDF dem Gesetz zum Schutz personenbezogener Daten (PIPL) m\xFCssen wir Sie vor der Verarbeitung Ihrer Daten informieren. Wir verarbeiten Daten nur zu den angegebenen Zwecken auf Grundlage Ihrer Einwilligung.",buttons:{"agree-all":"Zustimmen","reject-non-necessary":"Ablehnen","manage-preferences":"Einstellungen"}},preferenceModal:{heading:"Datenschutzeinstellungen (PIPL)",subheading:"Bitte w\xE4hlen Sie, welcher Datenverarbeitung Sie zustimmen.",buttons:{"agree-all":"Zustimmen","disagree-all":"Ablehnen","confirm-settings":"Auswahl speichern"},categories:{"cat-necessary":{heading:"Unbedingt erforderlich",htmlText:"F\xFCr den Betrieb der Website unbedingt erforderlich. Zweck: Sicherheit und grundlegende Funktionalit\xE4t."},"cat-functional":{heading:"Funktional",htmlText:"Zweck: Verbesserung der Benutzererfahrung. Einwilligung gem\xE4\xDF PIPL erforderlich."},"cat-preferences":{heading:"Pr\xE4ferenzen",htmlText:"Zweck: Speicherung personalisierter Einstellungen. Einwilligung gem\xE4\xDF PIPL erforderlich."},"cat-analytics":{heading:"Analyse",htmlText:"Zweck: Statistiken zur Website-Nutzung. Einwilligung gem\xE4\xDF PIPL erforderlich."},"cat-marketing":{heading:"Marketing",htmlText:"Zweck: Personalisierte Werbung. Einwilligung gem\xE4\xDF PIPL erforderlich."}}}}});var fr,hr=T(()=>{"use strict";p();fr={mainBanner:{heading:"Aviso de tratamiento de informaci\xF3n personal",htmlText:"De conformidad con la Ley de Protecci\xF3n de Informaci\xF3n Personal (PIPL), debemos informarle antes de tratar sus datos. Solo procesamos datos con fines espec\xEDficos y con su consentimiento.",buttons:{"agree-all":"Aceptar","reject-non-necessary":"Rechazar","manage-preferences":"Configuraci\xF3n"}},preferenceModal:{heading:"Configuraci\xF3n de privacidad (PIPL)",subheading:"Elija qu\xE9 tratamientos de datos acepta.",buttons:{"agree-all":"Aceptar","disagree-all":"Rechazar","confirm-settings":"Guardar selecci\xF3n"},categories:{"cat-necessary":{heading:"Estrictamente necesarias",htmlText:"Imprescindibles para el sitio. Finalidad: seguridad y funcionalidad b\xE1sica."},"cat-functional":{heading:"Funcionales",htmlText:"Finalidad: mejorar la experiencia del usuario. Se requiere consentimiento seg\xFAn la PIPL."},"cat-preferences":{heading:"Preferencias",htmlText:"Finalidad: guardar configuraci\xF3n personalizada. Se requiere consentimiento seg\xFAn la PIPL."},"cat-analytics":{heading:"Anal\xEDticas",htmlText:"Finalidad: estad\xEDsticas de uso del sitio. Se requiere consentimiento seg\xFAn la PIPL."},"cat-marketing":{heading:"Marketing",htmlText:"Finalidad: publicidad personalizada. Se requiere consentimiento seg\xFAn la PIPL."}}}}});var yr,_r=T(()=>{"use strict";p();yr={mainBanner:{heading:"Avis de traitement des informations personnelles",htmlText:"Conform\xE9ment \xE0 la loi sur la protection des informations personnelles (PIPL), nous devons vous informer avant tout traitement. Nous traitons les donn\xE9es \xE0 des fins sp\xE9cifiques uniquement, avec votre consentement.",buttons:{"agree-all":"Accepter","reject-non-necessary":"Refuser","manage-preferences":"Param\xE8tres"}},preferenceModal:{heading:"Param\xE8tres de confidentialit\xE9 (PIPL)",subheading:"Choisissez les traitements de donn\xE9es que vous acceptez.",buttons:{"agree-all":"Accepter","disagree-all":"Refuser","confirm-settings":"Enregistrer la s\xE9lection"},categories:{"cat-necessary":{heading:"Strictement n\xE9cessaires",htmlText:"Indispensables au site. Finalit\xE9 : s\xE9curit\xE9 et fonctionnalit\xE9 de base."},"cat-functional":{heading:"Fonctionnels",htmlText:"Finalit\xE9 : am\xE9liorer l'exp\xE9rience utilisateur. Consentement requis selon la PIPL."},"cat-preferences":{heading:"Pr\xE9f\xE9rences",htmlText:"Finalit\xE9 : sauvegarder les param\xE8tres personnalis\xE9s. Consentement requis selon la PIPL."},"cat-analytics":{heading:"Analytiques",htmlText:"Finalit\xE9 : statistiques d'utilisation du site. Consentement requis selon la PIPL."},"cat-marketing":{heading:"Marketing",htmlText:"Finalit\xE9 : publicit\xE9 personnalis\xE9e. Consentement requis selon la PIPL."}}}}});var wr,Er=T(()=>{"use strict";p();wr={mainBanner:{heading:"\u500B\u4EBA\u60C5\u5831\u51E6\u7406\u306B\u95A2\u3059\u308B\u304A\u77E5\u3089\u305B",htmlText:"\u500B\u4EBA\u60C5\u5831\u4FDD\u8B77\u6CD5\uFF08PIPL\uFF09\u306B\u57FA\u3065\u304D\u3001\u30C7\u30FC\u30BF\u51E6\u7406\u306E\u524D\u306B\u304A\u77E5\u3089\u305B\u3059\u308B\u7FA9\u52D9\u304C\u3042\u308A\u307E\u3059\u3002\u304A\u5BA2\u69D8\u306E\u540C\u610F\u3092\u5F97\u305F\u7279\u5B9A\u306E\u76EE\u7684\u306B\u306E\u307F\u30C7\u30FC\u30BF\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002",buttons:{"agree-all":"\u540C\u610F\u3059\u308B","reject-non-necessary":"\u62D2\u5426\u3059\u308B","manage-preferences":"\u8A2D\u5B9A"}},preferenceModal:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A\uFF08PIPL\uFF09",subheading:"\u540C\u610F\u3059\u308B\u30C7\u30FC\u30BF\u51E6\u7406\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",buttons:{"agree-all":"\u540C\u610F\u3059\u308B","disagree-all":"\u62D2\u5426\u3059\u308B","confirm-settings":"\u9078\u629E\u3092\u4FDD\u5B58"},categories:{"cat-necessary":{heading:"\u5FC5\u9808",htmlText:"\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u306B\u4E0D\u53EF\u6B20\u3067\u3059\u3002\u76EE\u7684\uFF1A\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u3068\u57FA\u672C\u6A5F\u80FD\u3002"},"cat-functional":{heading:"\u6A5F\u80FD",htmlText:"\u76EE\u7684\uFF1A\u30E6\u30FC\u30B6\u30FC\u4F53\u9A13\u306E\u5411\u4E0A\u3002PIPL\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"},"cat-preferences":{heading:"\u8A2D\u5B9A",htmlText:"\u76EE\u7684\uFF1A\u500B\u4EBA\u8A2D\u5B9A\u306E\u4FDD\u5B58\u3002PIPL\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"},"cat-analytics":{heading:"\u5206\u6790",htmlText:"\u76EE\u7684\uFF1A\u30B5\u30A4\u30C8\u5229\u7528\u7D71\u8A08\u3002PIPL\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"},"cat-marketing":{heading:"\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0",htmlText:"\u76EE\u7684\uFF1A\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u5E83\u544A\u3002PIPL\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"}}}}});var Rr,Sr=T(()=>{"use strict";p();Rr={mainBanner:{heading:"Wir sch\xE4tzen Ihre Privatsph\xE4re",htmlText:"Gem\xE4\xDF dem brasilianischen Datenschutzgesetz (LGPD) verarbeiten wir Ihre personenbezogenen Daten auf Grundlage Ihrer Einwilligung oder unseres berechtigten Interesses, sofern anwendbar. Sie k\xF6nnen Ihre Wahl jederzeit \xE4ndern.",buttons:{"accept-all":"Alle akzeptieren","reject-optional":"Alle ablehnen",manage:"Verwalten"}},preferenceModal:{heading:"Datenschutzeinstellungen (LGPD)",subheading:"W\xE4hlen Sie Ihre Datenschutzoptionen.",buttons:{"accept-all":"Alle akzeptieren","reject-optional":"Alle ablehnen","save-preferences":"Auswahl speichern"},categories:{"cat-necessary":{heading:"Unbedingt erforderlich",htmlText:"F\xFCr den Betrieb der Website unbedingt erforderlich."},"cat-functional":{heading:"Funktional",htmlText:"Erm\xF6glichen erweiterte Funktionen. Rechtsgrundlage: berechtigtes Interesse (LGPD Art. 10)."},"cat-preferences":{heading:"Pr\xE4ferenzen",htmlText:"Speichern Ihre Einstellungen. Rechtsgrundlage: berechtigtes Interesse (LGPD Art. 10)."},"cat-analytics":{heading:"Analyse",htmlText:"Helfen uns, die Website-Nutzung zu verstehen. Einwilligung gem\xE4\xDF LGPD erforderlich."},"cat-marketing":{heading:"Marketing",htmlText:"Erm\xF6glichen personalisierte Werbung. Einwilligung gem\xE4\xDF LGPD erforderlich."}}}}});var vr,Cr=T(()=>{"use strict";p();vr={mainBanner:{heading:"Valoramos su privacidad",htmlText:"De acuerdo con la Ley General de Protecci\xF3n de Datos (LGPD) de Brasil, tratamos sus datos personales con su consentimiento o con base en inter\xE9s leg\xEDtimo cuando corresponda. Puede cambiar sus preferencias en cualquier momento.",buttons:{"accept-all":"Aceptar todo","reject-optional":"Rechazar todo",manage:"Gestionar"}},preferenceModal:{heading:"Configuraci\xF3n de privacidad (LGPD)",subheading:"Elija sus opciones de privacidad.",buttons:{"accept-all":"Aceptar todo","reject-optional":"Rechazar todo","save-preferences":"Guardar selecci\xF3n"},categories:{"cat-necessary":{heading:"Estrictamente necesarias",htmlText:"Imprescindibles para el funcionamiento del sitio."},"cat-functional":{heading:"Funcionales",htmlText:"Permiten funciones avanzadas. Base legal: inter\xE9s leg\xEDtimo (LGPD Art. 10)."},"cat-preferences":{heading:"Preferencias",htmlText:"Guardan su configuraci\xF3n. Base legal: inter\xE9s leg\xEDtimo (LGPD Art. 10)."},"cat-analytics":{heading:"Anal\xEDticas",htmlText:"Nos ayudan a comprender el uso del sitio. Se requiere consentimiento seg\xFAn la LGPD."},"cat-marketing":{heading:"Marketing",htmlText:"Permiten publicidad personalizada. Se requiere consentimiento seg\xFAn la LGPD."}}}}});var Ar,Pr=T(()=>{"use strict";p();Ar={mainBanner:{heading:"Nous respectons votre vie priv\xE9e",htmlText:"Conform\xE9ment \xE0 la loi br\xE9silienne sur la protection des donn\xE9es (LGPD), nous traitons vos donn\xE9es personnelles sur la base de votre consentement ou d'un int\xE9r\xEAt l\xE9gitime, selon le cas. Vous pouvez modifier vos pr\xE9f\xE9rences \xE0 tout moment.",buttons:{"accept-all":"Tout accepter","reject-optional":"Tout refuser",manage:"G\xE9rer"}},preferenceModal:{heading:"Param\xE8tres de confidentialit\xE9 (LGPD)",subheading:"Choisissez vos options de confidentialit\xE9.",buttons:{"accept-all":"Tout accepter","reject-optional":"Tout refuser","save-preferences":"Enregistrer la s\xE9lection"},categories:{"cat-necessary":{heading:"Strictement n\xE9cessaires",htmlText:"Indispensables au fonctionnement du site."},"cat-functional":{heading:"Fonctionnels",htmlText:"Permettent des fonctionnalit\xE9s avanc\xE9es. Base l\xE9gale : int\xE9r\xEAt l\xE9gitime (LGPD Art. 10)."},"cat-preferences":{heading:"Pr\xE9f\xE9rences",htmlText:"Sauvegardent vos param\xE8tres. Base l\xE9gale : int\xE9r\xEAt l\xE9gitime (LGPD Art. 10)."},"cat-analytics":{heading:"Analytiques",htmlText:"Nous aident \xE0 comprendre l'utilisation du site. Consentement requis selon la LGPD."},"cat-marketing":{heading:"Marketing",htmlText:"Permettent la publicit\xE9 personnalis\xE9e. Consentement requis selon la LGPD."}}}}});var Tr,Ir=T(()=>{"use strict";p();Tr={mainBanner:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u3092\u5927\u5207\u306B\u3057\u3066\u3044\u307E\u3059",htmlText:"\u30D6\u30E9\u30B8\u30EB\u306E\u4E00\u822C\u30C7\u30FC\u30BF\u4FDD\u8B77\u6CD5\uFF08LGPD\uFF09\u306B\u57FA\u3065\u304D\u3001\u304A\u5BA2\u69D8\u306E\u540C\u610F\u307E\u305F\u306F\u6B63\u5F53\u306A\u5229\u76CA\u3092\u6839\u62E0\u3068\u3057\u3066\u500B\u4EBA\u30C7\u30FC\u30BF\u3092\u51E6\u7406\u3057\u307E\u3059\u3002\u8A2D\u5B9A\u306F\u3044\u3064\u3067\u3082\u5909\u66F4\u3067\u304D\u307E\u3059\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","reject-optional":"\u3059\u3079\u3066\u62D2\u5426",manage:"\u7BA1\u7406\u3059\u308B"}},preferenceModal:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A\uFF08LGPD\uFF09",subheading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","reject-optional":"\u3059\u3079\u3066\u62D2\u5426","save-preferences":"\u9078\u629E\u3092\u4FDD\u5B58"},categories:{"cat-necessary":{heading:"\u5FC5\u9808",htmlText:"\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u306E\u52D5\u4F5C\u306B\u4E0D\u53EF\u6B20\u3067\u3059\u3002"},"cat-functional":{heading:"\u6A5F\u80FD",htmlText:"\u9AD8\u5EA6\u306A\u6A5F\u80FD\u3092\u6709\u52B9\u306B\u3057\u307E\u3059\u3002\u6CD5\u7684\u6839\u62E0\uFF1A\u6B63\u5F53\u306A\u5229\u76CA\uFF08LGPD\u7B2C10\u6761\uFF09\u3002"},"cat-preferences":{heading:"\u8A2D\u5B9A",htmlText:"\u8A2D\u5B9A\u3092\u4FDD\u5B58\u3057\u307E\u3059\u3002\u6CD5\u7684\u6839\u62E0\uFF1A\u6B63\u5F53\u306A\u5229\u76CA\uFF08LGPD\u7B2C10\u6761\uFF09\u3002"},"cat-analytics":{heading:"\u5206\u6790",htmlText:"\u30B5\u30A4\u30C8\u5229\u7528\u72B6\u6CC1\u306E\u628A\u63E1\u306B\u5F79\u7ACB\u3066\u307E\u3059\u3002LGPD\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"},"cat-marketing":{heading:"\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0",htmlText:"\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u5E83\u544A\u3092\u53EF\u80FD\u306B\u3057\u307E\u3059\u3002LGPD\u306B\u57FA\u3065\u304D\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"}}}}});var br,Or=T(()=>{"use strict";p();br={mainBanner:{heading:"Wir verwenden Cookies",htmlText:"Wir verwenden Cookies und \xE4hnliche Technologien, um unsere Dienste bereitzustellen und zu verbessern. F\xFCr Marketing-Cookies ist Ihre Einwilligung erforderlich. Andere Cookies basieren auf unserem berechtigten Interesse.",buttons:{"accept-all":"Alle akzeptieren","reject-marketing":"Marketing ablehnen","manage-preferences":"Einstellungen verwalten"}},preferenceModal:{heading:"Datenschutzeinstellungen",subheading:"W\xE4hlen Sie Ihre Cookie-Pr\xE4ferenzen.",buttons:{"accept-all":"Alle akzeptieren","necessary-only":"Marketing ablehnen","save-preferences":"Auswahl speichern"},categories:{"cat-necessary":{heading:"Unbedingt erforderlich",htmlText:"F\xFCr den Betrieb der Website unbedingt erforderlich."},"cat-functional":{heading:"Funktional",htmlText:"Erm\xF6glichen erweiterte Funktionen. Rechtsgrundlage: berechtigtes Interesse."},"cat-preferences":{heading:"Pr\xE4ferenzen",htmlText:"Speichern Ihre pers\xF6nlichen Einstellungen. Rechtsgrundlage: berechtigtes Interesse."},"cat-analytics":{heading:"Analyse",htmlText:"Helfen uns, die Website-Nutzung zu verstehen. Rechtsgrundlage: berechtigtes Interesse."},"cat-marketing":{heading:"Marketing",htmlText:"Erm\xF6glichen personalisierte Werbung. Ihre Einwilligung ist erforderlich."}}}}});var Dr,kr=T(()=>{"use strict";p();Dr={mainBanner:{heading:"Usamos cookies",htmlText:"Utilizamos cookies y tecnolog\xEDas similares para ofrecer y mejorar nuestros servicios. Las cookies de marketing requieren su consentimiento. Las dem\xE1s se basan en inter\xE9s leg\xEDtimo.",buttons:{"accept-all":"Aceptar todo","reject-marketing":"Rechazar marketing","manage-preferences":"Gestionar preferencias"}},preferenceModal:{heading:"Configuraci\xF3n de privacidad",subheading:"Elija sus preferencias de cookies.",buttons:{"accept-all":"Aceptar todo","necessary-only":"Rechazar marketing","save-preferences":"Guardar selecci\xF3n"},categories:{"cat-necessary":{heading:"Estrictamente necesarias",htmlText:"Imprescindibles para el funcionamiento del sitio."},"cat-functional":{heading:"Funcionales",htmlText:"Permiten funciones avanzadas. Base legal: inter\xE9s leg\xEDtimo."},"cat-preferences":{heading:"Preferencias",htmlText:"Guardan su configuraci\xF3n personal. Base legal: inter\xE9s leg\xEDtimo."},"cat-analytics":{heading:"Anal\xEDticas",htmlText:"Nos ayudan a entender el uso del sitio. Base legal: inter\xE9s leg\xEDtimo."},"cat-marketing":{heading:"Marketing",htmlText:"Permiten publicidad personalizada. Se requiere su consentimiento."}}}}});var Lr,Nr=T(()=>{"use strict";p();Lr={mainBanner:{heading:"Nous utilisons des cookies",htmlText:"Nous utilisons des cookies et des technologies similaires pour fournir et am\xE9liorer nos services. Les cookies marketing n\xE9cessitent votre consentement. Les autres reposent sur notre int\xE9r\xEAt l\xE9gitime.",buttons:{"accept-all":"Tout accepter","reject-marketing":"Refuser le marketing","manage-preferences":"G\xE9rer les pr\xE9f\xE9rences"}},preferenceModal:{heading:"Param\xE8tres de confidentialit\xE9",subheading:"Choisissez vos pr\xE9f\xE9rences en mati\xE8re de cookies.",buttons:{"accept-all":"Tout accepter","necessary-only":"Refuser le marketing","save-preferences":"Enregistrer la s\xE9lection"},categories:{"cat-necessary":{heading:"Strictement n\xE9cessaires",htmlText:"Indispensables au fonctionnement du site."},"cat-functional":{heading:"Fonctionnels",htmlText:"Permettent des fonctionnalit\xE9s avanc\xE9es. Base l\xE9gale : int\xE9r\xEAt l\xE9gitime."},"cat-preferences":{heading:"Pr\xE9f\xE9rences",htmlText:"Sauvegardent vos param\xE8tres personnels. Base l\xE9gale : int\xE9r\xEAt l\xE9gitime."},"cat-analytics":{heading:"Analytiques",htmlText:"Nous aident \xE0 comprendre l'utilisation du site. Base l\xE9gale : int\xE9r\xEAt l\xE9gitime."},"cat-marketing":{heading:"Marketing",htmlText:"Permettent la publicit\xE9 personnalis\xE9e. Votre consentement est requis."}}}}});var xr,Mr=T(()=>{"use strict";p();xr={mainBanner:{heading:"Cookie\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059",htmlText:"\u30B5\u30FC\u30D3\u30B9\u306E\u63D0\u4F9B\u30FB\u6539\u5584\u306E\u305F\u3081\u306BCookie\u304A\u3088\u3073\u985E\u4F3C\u6280\u8853\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0Cookie\u306B\u306F\u304A\u5BA2\u69D8\u306E\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002\u305D\u306E\u4ED6\u306F\u6B63\u5F53\u306A\u5229\u76CA\u3092\u6839\u62E0\u3068\u3057\u3066\u3044\u307E\u3059\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","reject-marketing":"\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u3092\u62D2\u5426","manage-preferences":"\u8A2D\u5B9A\u3092\u7BA1\u7406"}},preferenceModal:{heading:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A",subheading:"Cookie\u306E\u8A2D\u5B9A\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",buttons:{"accept-all":"\u3059\u3079\u3066\u540C\u610F","necessary-only":"\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u3092\u62D2\u5426","save-preferences":"\u9078\u629E\u3092\u4FDD\u5B58"},categories:{"cat-necessary":{heading:"\u5FC5\u9808",htmlText:"\u30A6\u30A7\u30D6\u30B5\u30A4\u30C8\u306E\u52D5\u4F5C\u306B\u4E0D\u53EF\u6B20\u3067\u3059\u3002"},"cat-functional":{heading:"\u6A5F\u80FD",htmlText:"\u9AD8\u5EA6\u306A\u6A5F\u80FD\u3092\u6709\u52B9\u306B\u3057\u307E\u3059\u3002\u6CD5\u7684\u6839\u62E0\uFF1A\u6B63\u5F53\u306A\u5229\u76CA\u3002"},"cat-preferences":{heading:"\u8A2D\u5B9A",htmlText:"\u500B\u4EBA\u8A2D\u5B9A\u3092\u4FDD\u5B58\u3057\u307E\u3059\u3002\u6CD5\u7684\u6839\u62E0\uFF1A\u6B63\u5F53\u306A\u5229\u76CA\u3002"},"cat-analytics":{heading:"\u5206\u6790",htmlText:"\u30B5\u30A4\u30C8\u5229\u7528\u72B6\u6CC1\u306E\u628A\u63E1\u306B\u5F79\u7ACB\u3066\u307E\u3059\u3002\u6CD5\u7684\u6839\u62E0\uFF1A\u6B63\u5F53\u306A\u5229\u76CA\u3002"},"cat-marketing":{heading:"\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0",htmlText:"\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u5E83\u544A\u3092\u53EF\u80FD\u306B\u3057\u307E\u3059\u3002\u304A\u5BA2\u69D8\u306E\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059\u3002"}}}}});var Ur,Gr=T(()=>{"use strict";p();Ur={mainBanner:{heading:"Diese Website verwendet nur notwendige Cookies",htmlText:"Wir verwenden ausschlie\xDFlich technisch notwendige Cookies, die f\xFCr den Betrieb der Website erforderlich sind. Es werden keine Marketing- oder Analyse-Cookies eingesetzt.",buttons:{ok:"OK"}},preferenceModal:{heading:"Cookie-Informationen",buttons:{close:"Schlie\xDFen"},categories:{"cat-necessary":{heading:"Notwendige Cookies",htmlText:"Technisch notwendige Cookies, die f\xFCr den ordnungsgem\xE4\xDFen Betrieb der Website erforderlich sind. Sie k\xF6nnen nicht deaktiviert werden."}}}}});var jr,Br=T(()=>{"use strict";p();jr={mainBanner:{heading:"Este sitio solo usa cookies esenciales",htmlText:"\xDAnicamente utilizamos cookies t\xE9cnicamente necesarias para el funcionamiento del sitio. No utilizamos cookies de marketing ni anal\xEDticas.",buttons:{ok:"Aceptar"}},preferenceModal:{heading:"Informaci\xF3n sobre cookies",buttons:{close:"Cerrar"},categories:{"cat-necessary":{heading:"Cookies necesarias",htmlText:"Cookies t\xE9cnicamente necesarias para el correcto funcionamiento del sitio. No pueden desactivarse."}}}}});var Fr,$r=T(()=>{"use strict";p();Fr={mainBanner:{heading:"Ce site utilise uniquement des cookies essentiels",htmlText:"Nous n'utilisons que des cookies techniquement n\xE9cessaires au bon fonctionnement du site. Aucun cookie de marketing ou d'analyse n'est utilis\xE9.",buttons:{ok:"OK"}},preferenceModal:{heading:"Informations sur les cookies",buttons:{close:"Fermer"},categories:{"cat-necessary":{heading:"Cookies n\xE9cessaires",htmlText:"Cookies techniquement n\xE9cessaires au bon fonctionnement du site. Ils ne peuvent pas \xEAtre d\xE9sactiv\xE9s."}}}}});var Hr,Vr=T(()=>{"use strict";p();Hr={mainBanner:{heading:"\u5F53\u30B5\u30A4\u30C8\u306F\u5FC5\u9808Cookie\u306E\u307F\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059",htmlText:"\u30B5\u30A4\u30C8\u306E\u6B63\u5E38\u306A\u52D5\u4F5C\u306B\u5FC5\u8981\u306A\u6280\u8853\u7684Cookie\u306E\u307F\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002\u30DE\u30FC\u30B1\u30C6\u30A3\u30F3\u30B0\u3084\u5206\u6790\u306ECookie\u306F\u4F7F\u7528\u3057\u3066\u3044\u307E\u305B\u3093\u3002",buttons:{ok:"OK"}},preferenceModal:{heading:"Cookie\u306B\u95A2\u3059\u308B\u60C5\u5831",buttons:{close:"\u9589\u3058\u308B"},categories:{"cat-necessary":{heading:"\u5FC5\u9808Cookie",htmlText:"\u30B5\u30A4\u30C8\u306E\u6B63\u5E38\u306A\u52D5\u4F5C\u306B\u5FC5\u8981\u306A\u6280\u8853\u7684Cookie\u3067\u3059\u3002\u7121\u52B9\u306B\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002"}}}}});var Wr={};Pn(Wr,{DEFAULT_PROFILES:()=>Zt,GENERAL_PRIVACY_CONSENT_EN_PROFILE:()=>Yt,GENERIC_AGE_GATE_TEXT:()=>gl,GENERIC_GPC_BANNER_TEXT:()=>ml,NOTICE_ONLY_EN_PROFILE:()=>Qt,OPT_IN_BRAZIL_EN_PROFILE:()=>Kt,OPT_IN_CHINA_EN_PROFILE:()=>zt,OPT_IN_DPDPA_EN_PROFILE:()=>Jt,OPT_IN_EN_PROFILE:()=>Vt,OPT_OUT_EN_PROFILE:()=>Wt,OPT_OUT_STRICT_EN_PROFILE:()=>qt,resolveLocaleTranslation:()=>fl});function Zn(i,e){let t={};for(let[n,o]of Object.entries(i))t[n]=e[n]!==void 0?{...o,text:e[n]}:o;return t}function fl(i,e){let n=Zt[i]?.translations.en;if(!n)return;if(e==="en")return n;let o=pl[i]?.[e];if(!o)return;let r={};for(let[s,a]of Object.entries(n.preferenceModal.categories)){let c=o.preferenceModal.categories[`cat-${s}`];r[s]=c?{...a,heading:c.heading,htmlText:c.htmlText}:a}return{mainBanner:{...n.mainBanner,heading:o.mainBanner.heading,htmlText:o.mainBanner.htmlText,buttons:Zn(n.mainBanner.buttons,o.mainBanner.buttons)},...n.gpcBanner?{gpcBanner:o.gpcBanner?{...n.gpcBanner,heading:o.gpcBanner.heading,htmlText:o.gpcBanner.htmlText,buttons:Zn(n.gpcBanner.buttons,o.gpcBanner.buttons)}:n.gpcBanner}:{},preferenceModal:{...n.preferenceModal,heading:o.preferenceModal.heading,...o.preferenceModal.subheading?{subheading:o.preferenceModal.subheading}:{},...o.preferenceModal.htmlText?{htmlText:o.preferenceModal.htmlText}:{},buttons:Zn(n.preferenceModal.buttons,o.preferenceModal.buttons),categories:r}}}var Zt,pl,ml,gl,Xn=T(()=>{"use strict";p();Vn();Wn();qn();Jn();zn();Kn();Yn();Qn();Mo();Go();Bo();$o();Vo();qo();zo();Yo();Zo();er();nr();or();sr();cr();dr();pr();gr();hr();_r();Er();Sr();Cr();Pr();Ir();Or();kr();Nr();Mr();Gr();Br();$r();Vr();Vn();Wn();qn();Jn();zn();Kn();Yn();Qn();Zt={"opt-in":Vt,"opt-out":Wt,"opt-out-strict":qt,"opt-in-dpdpa":Jt,"opt-in-china":zt,"opt-in-brazil":Kt,"general-privacy-consent":Yt,"notice-only":Qt},pl={"opt-in":{de:xo,es:Uo,fr:jo,ja:Fo},"opt-out":{de:Ho,es:Wo,fr:Jo,ja:Ko},"opt-out-strict":{de:Qo,es:Xo,fr:tr,ja:ir},"opt-in-dpdpa":{de:rr,es:ar,fr:lr,ja:ur},"opt-in-china":{de:mr,es:fr,fr:yr,ja:wr},"opt-in-brazil":{de:Rr,es:vr,fr:Ar,ja:Tr},"general-privacy-consent":{de:br,es:Dr,fr:Lr,ja:xr},"notice-only":{de:Ur,es:jr,fr:Fr,ja:Hr}},ml={en:{heading:"Global Privacy Control detected",htmlText:"Your browser sent a Global Privacy Control signal. We have applied your privacy preference accordingly \u2014 you can review or change your choices below."},de:{heading:"Global Privacy Control erkannt",htmlText:"Ihr Browser hat ein Global-Privacy-Control-Signal gesendet. Wir haben Ihre Datenschutzeinstellung entsprechend angewendet \u2014 Sie k\xF6nnen Ihre Auswahl unten \xFCberpr\xFCfen oder \xE4ndern."},es:{heading:"Control de privacidad global detectado",htmlText:"Su navegador envi\xF3 una se\xF1al de Global Privacy Control. Hemos aplicado su preferencia de privacidad en consecuencia; puede revisar o cambiar sus opciones a continuaci\xF3n."},fr:{heading:"Contr\xF4le de confidentialit\xE9 global d\xE9tect\xE9",htmlText:"Votre navigateur a envoy\xE9 un signal Global Privacy Control. Nous avons appliqu\xE9 votre pr\xE9f\xE9rence de confidentialit\xE9 en cons\xE9quence \u2014 vous pouvez v\xE9rifier ou modifier vos choix ci-dessous."},ja:{heading:"\u30B0\u30ED\u30FC\u30D0\u30EB\u30FB\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u30FB\u30B3\u30F3\u30C8\u30ED\u30FC\u30EB\u3092\u691C\u51FA\u3057\u307E\u3057\u305F",htmlText:"\u304A\u4F7F\u3044\u306E\u30D6\u30E9\u30A6\u30B6\u304B\u3089Global Privacy Control\u4FE1\u53F7\u304C\u9001\u4FE1\u3055\u308C\u307E\u3057\u305F\u3002\u3053\u308C\u306B\u5FDC\u3058\u3066\u304A\u5BA2\u69D8\u306E\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u8A2D\u5B9A\u3092\u9069\u7528\u3057\u307E\u3057\u305F\u3002\u4EE5\u4E0B\u3067\u9078\u629E\u5185\u5BB9\u3092\u78BA\u8A8D\u30FB\u5909\u66F4\u3044\u305F\u3060\u3051\u307E\u3059\u3002"}},gl={en:{heading:"Are you 16 or older?",htmlText:"Please confirm your age before we show you cookie preferences.",confirmButtonLabel:"Yes",denyButtonLabel:"No",parentalConsent:{heading:"Parental consent required",htmlText:"Only strictly necessary cookies will be used until a parent or guardian verifies consent on your behalf.",confirmButtonLabel:"OK"}},de:{heading:"Bist du 16 Jahre oder \xE4lter?",htmlText:"Bitte best\xE4tige dein Alter, bevor wir dir die Cookie-Einstellungen anzeigen.",confirmButtonLabel:"Ja",denyButtonLabel:"Nein",parentalConsent:{heading:"Elterliche Zustimmung erforderlich",htmlText:"Bis ein Elternteil oder Erziehungsberechtigter die Zustimmung in deinem Namen best\xE4tigt, werden nur unbedingt erforderliche Cookies verwendet.",confirmButtonLabel:"OK"}},es:{heading:"\xBFTienes 16 a\xF1os o m\xE1s?",htmlText:"Confirma tu edad antes de mostrarte las preferencias de cookies.",confirmButtonLabel:"S\xED",denyButtonLabel:"No",parentalConsent:{heading:"Se requiere consentimiento parental",htmlText:"Solo se utilizar\xE1n las cookies estrictamente necesarias hasta que un padre, madre o tutor confirme el consentimiento en tu nombre.",confirmButtonLabel:"Aceptar"}},fr:{heading:"Avez-vous 16 ans ou plus\xA0?",htmlText:"Merci de confirmer votre \xE2ge avant que nous vous montrions les pr\xE9f\xE9rences de cookies.",confirmButtonLabel:"Oui",denyButtonLabel:"Non",parentalConsent:{heading:"Consentement parental requis",htmlText:"Seuls les cookies strictement n\xE9cessaires seront utilis\xE9s jusqu\u2019\xE0 ce qu\u2019un parent ou tuteur confirme son consentement en votre nom.",confirmButtonLabel:"OK"}},ja:{heading:"16\u6B73\u4EE5\u4E0A\u3067\u3059\u304B?",htmlText:"Cookie\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3059\u308B\u524D\u306B\u3001\u5E74\u9F62\u3092\u3054\u78BA\u8A8D\u304F\u3060\u3055\u3044\u3002",confirmButtonLabel:"\u306F\u3044",denyButtonLabel:"\u3044\u3044\u3048",parentalConsent:{heading:"\u4FDD\u8B77\u8005\u306E\u540C\u610F\u304C\u5FC5\u8981\u3067\u3059",htmlText:"\u4FDD\u8B77\u8005\u304C\u540C\u610F\u3092\u78BA\u8A8D\u3059\u308B\u307E\u3067\u3001\u5FC5\u8981\u6700\u5C0F\u9650\u306ECookie\u306E\u307F\u304C\u4F7F\u7528\u3055\u308C\u307E\u3059\u3002",confirmButtonLabel:"OK"}}}});function hl(i,e){let t;return function(...n){t!==void 0&&clearTimeout(t),t=setTimeout(()=>{i.apply(this,n)},e)}}var qr=T(()=>{"use strict";p()});function yl(i,e){let t=0;return function(...n){let o=Date.now();o-t>=e&&(t=o,i.apply(this,n))}}var Jr=T(()=>{"use strict";p()});function _l(){return typeof process>"u"||process.env.NO_COLOR?!1:process.env.FORCE_COLOR?!0:!!process.stdout?.isTTY}function fe(i,e){return t=>_l()?`\x1B[${i}m${t}\x1B[${e}m`:t}function El(i,e=10){let t=i.toUpperCase().padEnd(e);return wl[i](t)}function Sl(i,e){let{symbol:t,paint:n}=Rl[i];return`${n(t)} ${e}`}var Y,wl,Rl,zr=T(()=>{"use strict";p();Y={bold:fe(1,22),dim:fe(2,22),red:fe(31,39),green:fe(32,39),yellow:fe(33,39),blue:fe(34,39),magenta:fe(35,39),cyan:fe(36,39),gray:fe(90,39)},wl={pass:i=>Y.bold(Y.green(i)),fail:i=>Y.bold(Y.red(i)),error:i=>Y.bold(Y.red(i)),"not-applicable":i=>Y.gray(i),"new-baseline":i=>Y.bold(Y.blue(i))};Rl={info:{symbol:"\u2139",paint:Y.cyan},success:{symbol:"\u2713",paint:Y.green},warn:{symbol:"\u26A0",paint:Y.yellow},error:{symbol:"\u2717",paint:Y.red}}});function Il(i){return Kr[i.id]??"functional"}function Dl(i,e){for(let t of Object.values(e))if(t.cookies.includes(i))return t}function xe(i){let e=new Map;for(let t of Object.values(i))for(let n of t.cookies)e.set(n,t);return e}function Me(i,e){return e.get(i)?.legalBasis??"consent"}function ei(i,e){return Me(i,e)==="mandatory"}function xl(i){if(!i||typeof i!="object")return!1;let e=i;if(typeof e.version!="string")return!1;let t=e.countries;return!t||typeof t!="object"?!1:Object.values(t).every(n=>!!n&&typeof n=="object"&&typeof n.complianceGroup=="string")}async function ni(i,e){let t={map:Ie};if(i===void 0||i==="default")return t;let n,o;if(typeof i=="string")try{if(o=await fetch(i),!o.ok)return e(`compliance.complianceMap fetch from "${i}" failed (HTTP ${o.status}) \u2014 falling back to the embedded map.`),t;n=await o.json()}catch(s){return e(`compliance.complianceMap fetch from "${i}" failed (${s instanceof Error?s.message:String(s)}) \u2014 falling back to the embedded map.`),t}else n=i;if(!xl(n))return e(`compliance.complianceMap ${typeof i=="string"?`at "${i}"`:"object"} failed validation \u2014 falling back to the embedded map.`),t;for(let[s,a]of Object.entries(n.countries))a.overriddenRegions&&a.default===void 0&&e(`compliance.complianceMap country "${s}" has overriddenRegions but no explicit default \u2014 falling back to complianceGroup ("${a.complianceGroup}"), which may under-comply for regions not listed.`);let r={map:n};return o&&(r.response=o),r}var Xt,Xe,vl,Cl,Al,en,Pl,Tl,Kr,bl,Ol,ti,Ie,kl,Ll,Nl,Yr=T(()=>{"use strict";p();Xt=["opt-in","opt-out","opt-out-strict","opt-in-dpdpa","opt-in-china","opt-in-brazil","general-privacy-consent","notice-only"],Xe={"opt-out-strict":{label:"Opt-out Strict (CPRA / California)",description:"California CPRA: opt-out with sale/sharing/sensitive categories required. GPC must be honored. Stricter than general US state laws.",compliances:["cpra"],defaultGpc:"honor",gpcAutoHonor:!0,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!0,requiresDpdpaDisclosure:!1},"opt-out":{label:"Opt-out (US State Laws)",description:"US state privacy laws. Collect first, allow opt-out of sale/share. Covers CCPA and all state-level equivalents.",compliances:["ccpa","vcdpa","cpa-co","ctdpa","ucpa","icdpa-ia","icdpa-in","tipa","mcdpa-mt","mcdpa-mn","ocpa","tdpsa","dpdpa-de","njdpa","nhpa","ndpa-ne","modpa","kcdpa","ridtpa"],defaultGpc:"honor",gpcAutoHonor:!0,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"notice-only":{label:"Notice Only",description:"A privacy notice is generally sufficient. No dedicated cookie banner law is encoded for this jurisdiction.",compliances:["privacy-fj","privacy-pg"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"opt-in":{label:"Standard Opt-in (GDPR)",description:"GDPR / ePrivacy style: prior consent required before non-essential cookies. Granular consent, easy reject, easy withdrawal.",compliances:["gdpr","eprivacy","uk-gdpr","pecr","revfadp","kvkk","pdpa-th","pdpl-sa","uae-pdpl","difc-dpl","adgm-dpr","qpdl-qa","pdpl-bh","pdpl-om","law25"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!0,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"opt-in-dpdpa":{label:"Opt-in (India DPDPA)",description:"India's Digital Personal Data Protection Act. Opt-in consent with data fiduciary disclosure. No legitimate interest basis.",compliances:["dpdpa"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!0},"opt-in-china":{label:"Opt-in (China PIPL / DSL)",description:"China PIPL + DSL + CSL: strict opt-in with purpose specification, data minimisation, and cross-border transfer controls.",compliances:["pipl","dsl-cn","csl-cn"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"opt-in-brazil":{label:"Opt-in (Brazil LGPD)",description:"Brazil LGPD: opt-in consent required. Legitimate interest is a valid basis. Analytics and advertising may differ in treatment.",compliances:["lgpd"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"general-privacy-consent":{label:"General Privacy Consent",description:"Privacy notice or consent rules exist but the jurisdiction does not have a GDPR/PECR-style strict cookie banner law. Documenting legal basis is best practice.",compliances:["pipeda","popia","appi","pipa-kr","pdpa-sg","pdpa-my","dpa-ph","pdp-id","pdpd-vn","privacy-au","privacy-nz","pdpl-hk","pdpa-mo","pdpl-tw","privacy-bn","privacy-lk","privacy-np","privacy-kw","privacy-il","ndpa-ng","dpa-ke","dpa-gh","dpa-ug","dpa-rw","dpa-mu","dpa-bw","dpa-zm","dpa-zw","dpa-eg","dpa-ma","dpa-tn","dpa-dz","lfpdppp","lpdp-ar","lpdp-pe","law1581-co","law18331-uy","law19628-cl","lopdp-ec","lpdp-cr","data-protection-pa","data-protection-do"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1}},vl=[{value:"ignore",label:"Ignore",description:"Do not check or respond to the GPC browser signal."},{value:"honor",label:"Honor",description:"Respect GPC as a valid opt-out signal. Show GPC variant banner once."},{value:"strict",label:"Strict",description:"Silently deny all non-mandatory cookies when GPC is detected. No banner shown."}],Cl=[{value:"mandatory",label:"Strictly Necessary",description:"Required for the service to function. No consent needed."},{value:"consent",label:"Consent",description:"Requires explicit user agreement. User can withdraw at any time."},{value:"legitimate_interest",label:"Legitimate Interest",description:"Based on legitimate business interest. User has the right to object."}],Al=[{value:"sale",label:"Sale",description:"Sale of personal data to third parties for their own use."},{value:"sharing",label:"Sharing",description:"Sharing for cross-context behavioral advertising (even without payment)."},{value:"sensitive",label:"Sensitive",description:"Sensitive personal information (geolocation, health, race, biometrics, etc.). Requires opt-in even in California."}],en=["necessary","functional","preferences","analytics","marketing"],Pl=[{value:"necessary",label:"Necessary",description:"Strictly required to deliver the service or ensure security/compliance. Always granted."},{value:"functional",label:"Functional",description:"Optional features that enhance functionality but are not essential."},{value:"preferences",label:"Preferences",description:'Remember user choices and personalize the experience ("Remember me").'},{value:"analytics",label:"Analytics",description:"Measure usage and performance to improve the product."},{value:"marketing",label:"Marketing",description:"Advertising, profiling, cross-site tracking, retargeting, ad personalization."}],Tl={necessary:{legalBasis:"mandatory",listenGpc:!1},functional:{legalBasis:"legitimate_interest",listenGpc:!1},preferences:{legalBasis:"legitimate_interest",listenGpc:!1},analytics:{legalBasis:"consent",listenGpc:!0},marketing:{legalBasis:"consent",listenGpc:!0,cpraCategory:"sharing"}},Kr={security_storage:"necessary",functionality_storage:"functional",personalization_storage:"preferences",analytics_storage:"analytics",ad_storage:"marketing",ad_user_data:"marketing",ad_personalization:"marketing"};bl=[{id:1,name:"Store and/or access information on a device",description:"Cookies, device identifiers, or other information can be stored or accessed on your device."},{id:2,name:"Select basic ads",description:"Ads can be shown based on the content you're viewing, the app you're using, or your approximate location."},{id:3,name:"Create a personalised ads profile",description:"A profile can be built about you and your interests to show you personalised ads."},{id:4,name:"Select personalised ads",description:"Personalised ads can be shown to you based on a profile about you."},{id:5,name:"Create a personalised content profile",description:"A profile can be built about you and your interests to show you personalised content."},{id:6,name:"Select personalised content",description:"Personalised content can be shown to you based on a profile about you."},{id:7,name:"Measure ad performance",description:"The performance and effectiveness of ads that you see or interact with can be measured."},{id:8,name:"Measure content performance",description:"The performance and effectiveness of content that you see or interact with can be measured."},{id:9,name:"Apply market research to generate audience insights",description:"Market research can be used to learn more about the audiences who visit sites or use apps."},{id:10,name:"Develop and improve products",description:"Your data can be used to improve existing systems and software, and to develop new products."},{id:11,name:"Use limited data to select content",description:"Content can be selected based on limited data such as the website you are visiting."}],Ol=[{id:1,name:"Use precise geolocation data",description:"Your precise location (within a radius of less than 500 metres) can be used."},{id:2,name:"Actively scan device characteristics for identification",description:"Your device can be identified based on a scan of your device's unique combination of characteristics."}];ti={"opt-in":{categoryErrors:[{rule:"legal-basis-required",field:"legalBasis",check:i=>!i.legalBasis,message:i=>`Category "${i}" must have a legal basis set (Consent, Legitimate Interest, or Strictly Necessary) for GDPR compliance.`}],categoryWarnings:[{rule:"legitimate-interest-balancing-test-recommended",field:"legitimateInterestDescription",check:i=>i.legalBasis==="legitimate_interest"&&!String(i.legitimateInterestDescription??"").trim(),message:i=>`Category "${i}" relies on Legitimate Interest but has no balancing-test description. GDPR Art. 6(1)(f) requires you to conduct and be able to demonstrate a Legitimate Interests Assessment \u2014 note that Art. 5(3) ePrivacy still requires consent (LI cannot substitute) for the cookie storage/access itself, so this basis should only cover the downstream processing purpose, not the placement of a non-essential cookie.`,suggestion:`Document your Legitimate Interests Assessment in the category's "Legitimate Interest Description" field.`}],cookieErrors:[],cookieWarnings:[{rule:"pre-grant-opt-in-risk",field:"preGrant",check:(i,e)=>e==="consent"&&i.preGrant===!0,message:i=>`Parameter "${i}" is pre-granted, which may violate GDPR's opt-in requirement. Only use "Pre Grant" on custom profiles targeting jurisdictions where pre-granted consent is valid.`,suggestion:'Disable "Pre Grant" unless this profile specifically targets a jurisdiction that permits pre-granted consent.'}]},"opt-out":{categoryErrors:[],categoryWarnings:[],cookieErrors:[],cookieWarnings:[{rule:"gpc-recommended",field:"listenGpc",check:(i,e)=>e!=="mandatory"&&!i.listenGpc,message:i=>`Parameter "${i}" does not listen for the GPC signal. US state privacy laws require honoring GPC for opt-out of sale/sharing.`,suggestion:'Enable "Listen for GPC signal" on this parameter.'}]},"opt-out-strict":{categoryErrors:[],categoryWarnings:[],cookieErrors:[{rule:"cpra-category-required",field:"cpraCategory",check:(i,e)=>e!=="mandatory"&&!i.cpraCategory,message:i=>`Parameter "${i}" must have a CPRA category (Sale, Sharing, or Sensitive) assigned. Required under CPRA for all non-necessary parameters.`},{rule:"gpc-strict-required",field:"listenGpc",check:i=>(i.cpraCategory==="sale"||i.cpraCategory==="sharing")&&!i.listenGpc,message:i=>`Parameter "${i}" is tagged Sale/Sharing but does not listen for the GPC signal. 11 CCR \xA77025 requires honoring GPC as a Do Not Sell/Share My Personal Information request for these parameters \u2014 this is mandatory, not optional.`}],cookieWarnings:[]},"opt-in-dpdpa":{categoryErrors:[{rule:"no-li-allowed",field:"legalBasis",check:i=>i.legalBasis==="legitimate_interest",message:i=>`Category "${i}" uses Legitimate Interest, which is not a valid legal basis under India's DPDPA. Use Consent or Strictly Necessary.`},{rule:"legal-basis-required",field:"legalBasis",check:i=>!i.legalBasis,message:i=>`Category "${i}" must have a legal basis set (Consent or Strictly Necessary) for DPDPA compliance.`}],categoryWarnings:[],cookieErrors:[],cookieWarnings:[{rule:"pre-grant-opt-in-risk",field:"preGrant",check:(i,e)=>e==="consent"&&i.preGrant===!0,message:i=>`Parameter "${i}" is pre-granted, which may violate DPDPA's opt-in requirement. Only use "Pre Grant" on custom profiles targeting jurisdictions where pre-granted consent is valid.`,suggestion:'Disable "Pre Grant" unless this profile specifically targets a jurisdiction that permits pre-granted consent.'}]},"opt-in-china":{categoryErrors:[{rule:"no-li-allowed",field:"legalBasis",check:i=>i.legalBasis==="legitimate_interest",message:i=>`Category "${i}" uses Legitimate Interest, which is not one of PIPL Article 13's enumerated legal bases. Use Consent or Strictly Necessary.`},{rule:"legal-basis-required",field:"legalBasis",check:i=>!i.legalBasis,message:i=>`Category "${i}" must have a legal basis set for China PIPL compliance. Consent is the primary valid basis.`}],categoryWarnings:[],cookieErrors:[],cookieWarnings:[{rule:"pre-grant-opt-in-risk",field:"preGrant",check:(i,e)=>e==="consent"&&i.preGrant===!0,message:i=>`Parameter "${i}" is pre-granted, which may violate PIPL's opt-in requirement. Only use "Pre Grant" on custom profiles targeting jurisdictions where pre-granted consent is valid.`,suggestion:'Disable "Pre Grant" unless this profile specifically targets a jurisdiction that permits pre-granted consent.'}]},"opt-in-brazil":{categoryErrors:[{rule:"legal-basis-required",field:"legalBasis",check:i=>!i.legalBasis,message:i=>`Category "${i}" must have a legal basis set. Brazil's LGPD requires one of ten legal bases; Consent or Legitimate Interest are most common for parameters.`}],categoryWarnings:[{rule:"legitimate-interest-balancing-test-recommended",field:"legitimateInterestDescription",check:i=>i.legalBasis==="legitimate_interest"&&!String(i.legitimateInterestDescription??"").trim(),message:i=>`Category "${i}" relies on Legitimate Interest but has no balancing-test description. LGPD Art. 10 requires the legitimate interest basis to be documented and, on request, made available to the ANPD as a Data Protection Impact Report (relat\xF3rio de impacto).`,suggestion:`Document your legitimate interest assessment in the category's "Legitimate Interest Description" field.`}],cookieErrors:[],cookieWarnings:[{rule:"pre-grant-opt-in-risk",field:"preGrant",check:(i,e)=>e==="consent"&&i.preGrant===!0,message:i=>`Parameter "${i}" is pre-granted, which may violate LGPD's opt-in requirement. Only use "Pre Grant" on custom profiles targeting jurisdictions where pre-granted consent is valid.`,suggestion:'Disable "Pre Grant" unless this profile specifically targets a jurisdiction that permits pre-granted consent.'}]},"general-privacy-consent":{categoryErrors:[],categoryWarnings:[{rule:"legal-basis-recommended",field:"legalBasis",check:i=>!i.legalBasis,message:i=>`Category "${i}" has no legal basis documented. While a strict cookie banner may not be legally required in this jurisdiction, documenting legal basis is a privacy best practice.`,suggestion:"Set a legal basis to improve compliance documentation and future-proof against stricter enforcement."},{rule:"legitimate-interest-balancing-test-recommended",field:"legitimateInterestDescription",check:i=>i.legalBasis==="legitimate_interest"&&!String(i.legitimateInterestDescription??"").trim(),message:i=>`Category "${i}" relies on Legitimate Interest but has no balancing-test description documented. Most legitimate-interest-style bases in this jurisdiction group expect a documented justification, and it future-proofs the profile against stricter enforcement.`,suggestion:`Document your legitimate interest justification in the category's "Legitimate Interest Description" field.`}],cookieErrors:[],cookieWarnings:[]},"notice-only":{categoryErrors:[],categoryWarnings:[],cookieErrors:[],cookieWarnings:[]}},Ie={version:"2026-07",countries:{AT:{name:"Austria",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Austria (GDPR)",locales:["de-AT"],compliance:["gdpr","eprivacy"],timezones:["Europe/Vienna"]},BE:{name:"Belgium",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Belgium (GDPR)",locales:["nl-BE","fr-BE"],compliance:["gdpr","eprivacy"],timezones:["Europe/Brussels"]},BG:{name:"Bulgaria",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Bulgaria (GDPR)",locales:["bg-BG"],compliance:["gdpr","eprivacy"],timezones:["Europe/Sofia"]},HR:{name:"Croatia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Croatia (GDPR)",locales:["hr-HR"],compliance:["gdpr","eprivacy"],timezones:["Europe/Zagreb"]},CY:{name:"Cyprus",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Cyprus (GDPR)",locales:["el-CY"],compliance:["gdpr","eprivacy"],timezones:["Asia/Nicosia"]},CZ:{name:"Czechia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Czechia (GDPR)",locales:["cs-CZ"],compliance:["gdpr","eprivacy"],timezones:["Europe/Prague"]},DK:{name:"Denmark",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Denmark (GDPR)",locales:["da-DK"],compliance:["gdpr","eprivacy"],timezones:["Europe/Copenhagen"]},EE:{name:"Estonia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Estonia (GDPR)",locales:["et-EE"],compliance:["gdpr","eprivacy"],timezones:["Europe/Tallinn"]},FI:{name:"Finland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Finland (GDPR)",locales:["fi-FI"],compliance:["gdpr","eprivacy"],timezones:["Europe/Helsinki"]},FR:{name:"France",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"France (GDPR)",locales:["fr-FR"],compliance:["gdpr","eprivacy"],timezones:["Europe/Paris"]},DE:{name:"Germany",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Germany (GDPR)",locales:["de-DE"],compliance:["gdpr","eprivacy"],timezones:["Europe/Berlin"]},GR:{name:"Greece",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Greece (GDPR)",locales:["el-GR"],compliance:["gdpr","eprivacy"],timezones:["Europe/Athens"]},HU:{name:"Hungary",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Hungary (GDPR)",locales:["hu-HU"],compliance:["gdpr","eprivacy"],timezones:["Europe/Budapest"]},IE:{name:"Ireland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Ireland (GDPR)",locales:["en"],compliance:["gdpr","eprivacy"],timezones:["Europe/Dublin"]},IT:{name:"Italy",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Italy (GDPR)",locales:["it-IT"],compliance:["gdpr","eprivacy"],timezones:["Europe/Rome"]},LV:{name:"Latvia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Latvia (GDPR)",locales:["lv-LV"],compliance:["gdpr","eprivacy"],timezones:["Europe/Riga"]},LT:{name:"Lithuania",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Lithuania (GDPR)",locales:["lt-LT"],compliance:["gdpr","eprivacy"],timezones:["Europe/Vilnius"]},LU:{name:"Luxembourg",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Luxembourg (GDPR)",locales:["fr-LU","de-LU"],compliance:["gdpr","eprivacy"],timezones:["Europe/Luxembourg"]},MT:{name:"Malta",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Malta (GDPR)",locales:["mt-MT","en"],compliance:["gdpr","eprivacy"],timezones:["Europe/Malta"]},NL:{name:"Netherlands",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Netherlands (GDPR)",locales:["nl-NL"],compliance:["gdpr","eprivacy"],timezones:["Europe/Amsterdam"]},PL:{name:"Poland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Poland (GDPR)",locales:["pl-PL"],compliance:["gdpr","eprivacy"],timezones:["Europe/Warsaw"]},PT:{name:"Portugal",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Portugal (GDPR)",locales:["pt-PT"],compliance:["gdpr","eprivacy"],timezones:["Europe/Lisbon","Atlantic/Madeira","Atlantic/Azores"]},RO:{name:"Romania",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Romania (GDPR)",locales:["ro-RO"],compliance:["gdpr","eprivacy"],timezones:["Europe/Bucharest"]},SK:{name:"Slovakia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Slovakia (GDPR)",locales:["sk-SK"],compliance:["gdpr","eprivacy"],timezones:["Europe/Bratislava"]},SI:{name:"Slovenia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Slovenia (GDPR)",locales:["sl-SI"],compliance:["gdpr","eprivacy"],timezones:["Europe/Ljubljana"]},ES:{name:"Spain",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Spain (GDPR)",locales:["es-ES"],compliance:["gdpr","eprivacy"],timezones:["Europe/Madrid","Africa/Ceuta","Atlantic/Canary"]},SE:{name:"Sweden",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Sweden (GDPR)",locales:["sv-SE"],compliance:["gdpr","eprivacy"],timezones:["Europe/Stockholm"]},IS:{name:"Iceland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Iceland (GDPR via EEA)",locales:["is-IS"],compliance:["gdpr","eprivacy"],timezones:["Atlantic/Reykjavik"]},LI:{name:"Liechtenstein",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Liechtenstein (GDPR via EEA)",locales:["de-LI"],compliance:["gdpr","eprivacy"],timezones:["Europe/Vaduz"]},NO:{name:"Norway",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Norway (GDPR via EEA)",locales:["nb-NO"],compliance:["gdpr","eprivacy"],timezones:["Europe/Oslo","Arctic/Longyearbyen"]},AD:{name:"Andorra",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Andorra (GDPR-aligned)",locales:["ca-AD"],compliance:["gdpr"],timezones:["Europe/Andorra"]},AL:{name:"Albania",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Albania (GDPR-aligned)",locales:["sq-AL"],compliance:["gdpr"],timezones:["Europe/Tirane"]},BA:{name:"Bosnia and Herzegovina",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Bosnia and Herzegovina (GDPR-aligned)",locales:["bs-BA","sr-Latn-BA"],compliance:["gdpr"],timezones:["Europe/Sarajevo"]},GG:{name:"Guernsey",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Guernsey (DPA based on GDPR)",locales:["en"],compliance:["gdpr"],timezones:["Europe/Guernsey"]},GI:{name:"Gibraltar",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Gibraltar (DPA based on UK GDPR)",locales:["en"],compliance:["uk-gdpr"],timezones:["Europe/Gibraltar"]},GL:{name:"Greenland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Greenland (Danish GDPR implementation)",locales:["da-GL"],compliance:["gdpr"],timezones:["America/Nuuk","America/Danmarkshavn","America/Scoresbysund","America/Thule"]},MC:{name:"Monaco",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Monaco (GDPR-aligned)",locales:["fr-MC"],compliance:["gdpr"],timezones:["Europe/Monaco"]},ME:{name:"Montenegro",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Montenegro (GDPR-aligned)",locales:["sr-Latn-ME"],compliance:["gdpr"],timezones:["Europe/Podgorica"]},MK:{name:"North Macedonia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"North Macedonia (GDPR-aligned)",locales:["mk-MK"],compliance:["gdpr"],timezones:["Europe/Skopje"]},RS:{name:"Serbia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Serbia (GDPR-aligned)",locales:["sr-RS"],compliance:["gdpr"],timezones:["Europe/Belgrade"]},SM:{name:"San Marino",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"San Marino (GDPR-aligned)",locales:["it-SM"],compliance:["gdpr"],timezones:["Europe/San_Marino"]},TR:{name:"T\xFCrkiye",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"T\xFCrkiye (KVKK)",locales:["tr-TR"],compliance:["kvkk"],timezones:["Europe/Istanbul"]},CA:{name:"Canada",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Canada (PIPEDA / Law 25)",locales:["en","fr-CA"],compliance:["pipeda","law25"],timezones:["America/St_Johns","America/Halifax","America/Toronto","America/Winnipeg","America/Edmonton","America/Vancouver"],overriddenRegions:{QC:{name:"Quebec",type:"region",complianceGroup:"opt-in",description:"Quebec \u2014 Law 25 (GDPR-style opt-in)"}}},US:{name:"United States",type:"country",complianceGroup:"opt-out",default:"opt-out-strict",description:"United States \u2014 opt-out-strict (CPRA) used when state cannot be detected",locales:["en","es-US"],compliance:["ccpa","cpra","vcdpa","cpa-co","ctdpa","ucpa","icdpa-ia","icdpa-in","tipa","mcdpa-mt","mcdpa-mn","ocpa","tdpsa","dpdpa-de","njdpa","nhpa","ndpa-ne","modpa","kcdpa","ridtpa"],timezones:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","America/Anchorage","Pacific/Honolulu"],overriddenRegions:{CA:{name:"California",type:"region",complianceGroup:"opt-out-strict",description:"California \u2014 CPRA/CCPA"},VA:{name:"Virginia",type:"region",complianceGroup:"opt-out",description:"Virginia \u2014 VCDPA"},CO:{name:"Colorado",type:"region",complianceGroup:"opt-out",description:"Colorado \u2014 CPA",requiresSensitiveOptIn:!0},CT:{name:"Connecticut",type:"region",complianceGroup:"opt-out",description:"Connecticut \u2014 CTDPA"},UT:{name:"Utah",type:"region",complianceGroup:"opt-out",description:"Utah \u2014 UCPA"},TX:{name:"Texas",type:"region",complianceGroup:"opt-out",description:"Texas \u2014 TDPSA"},DE:{name:"Delaware",type:"region",complianceGroup:"opt-out",description:"Delaware \u2014 DPDPA"},NJ:{name:"New Jersey",type:"region",complianceGroup:"opt-out",description:"New Jersey \u2014 NJDPA"},OR:{name:"Oregon",type:"region",complianceGroup:"opt-out",description:"Oregon \u2014 OCPA"},MN:{name:"Minnesota",type:"region",complianceGroup:"opt-out",description:"Minnesota \u2014 MCDPA"},MD:{name:"Maryland",type:"region",complianceGroup:"opt-out",description:"Maryland \u2014 MODPA"},KY:{name:"Kentucky",type:"region",complianceGroup:"opt-out",description:"Kentucky \u2014 KCDPA"},TN:{name:"Tennessee",type:"region",complianceGroup:"opt-out",description:"Tennessee \u2014 TIPA"},NE:{name:"Nebraska",type:"region",complianceGroup:"opt-out",description:"Nebraska \u2014 NDPA"},IA:{name:"Iowa",type:"region",complianceGroup:"opt-out",description:"Iowa \u2014 ICDPA"},IN:{name:"Indiana",type:"region",complianceGroup:"opt-out",description:"Indiana \u2014 ICDPA"},MT:{name:"Montana",type:"region",complianceGroup:"opt-out",description:"Montana \u2014 MCDPA"},NH:{name:"New Hampshire",type:"region",complianceGroup:"opt-out",description:"New Hampshire \u2014 NHPA"},RI:{name:"Rhode Island",type:"region",complianceGroup:"opt-out",description:"Rhode Island \u2014 RIDTPA"}}},AR:{name:"Argentina",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Argentina (LPDP)",locales:["es-AR"],compliance:["lpdp-ar"],timezones:["America/Argentina/Buenos_Aires"]},BO:{name:"Bolivia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Bolivia",locales:["es-BO"],compliance:[],timezones:["America/La_Paz"]},BR:{name:"Brazil",type:"country",complianceGroup:"opt-in-brazil",default:"opt-in-brazil",description:"Brazil (LGPD)",locales:["pt-BR"],compliance:["lgpd"],timezones:["America/Noronha","America/Sao_Paulo","America/Manaus","America/Rio_Branco"]},CL:{name:"Chile",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Chile (Law 19.628)",locales:["es-CL"],compliance:["law19628-cl"],timezones:["America/Santiago","Pacific/Easter"]},CO:{name:"Colombia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Colombia (Law 1581)",locales:["es-CO"],compliance:["law1581-co"],timezones:["America/Bogota"]},CR:{name:"Costa Rica",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Costa Rica (LPDP)",locales:["es-CR"],compliance:["lpdp-cr"],timezones:["America/Costa_Rica"]},DO:{name:"Dominican Republic",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Dominican Republic",locales:["es-DO"],compliance:["data-protection-do"],timezones:["America/Santo_Domingo"]},EC:{name:"Ecuador",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Ecuador (LOPDP)",locales:["es-EC"],compliance:["lopdp-ec"],timezones:["America/Guayaquil","Pacific/Galapagos"]},GF:{name:"French Guiana",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"French Guiana",locales:["fr-GF"],compliance:[],timezones:["America/Cayenne"]},GT:{name:"Guatemala",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guatemala",locales:["es-GT"],compliance:[],timezones:["America/Guatemala"]},GY:{name:"Guyana",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guyana",locales:["en"],compliance:[],timezones:["America/Guyana"]},HN:{name:"Honduras",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Honduras",locales:["es-HN"],compliance:[],timezones:["America/Tegucigalpa"]},HT:{name:"Haiti",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Haiti",locales:["fr-HT"],compliance:[],timezones:["America/Port-au-Prince"]},JM:{name:"Jamaica",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Jamaica",locales:["en"],compliance:[],timezones:["America/Jamaica"]},MX:{name:"Mexico",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Mexico (LFPDPPP)",locales:["es-MX"],compliance:["lfpdppp"],timezones:["America/Mexico_City","America/Cancun","America/Chihuahua","America/Hermosillo","America/Tijuana"]},NI:{name:"Nicaragua",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Nicaragua",locales:["es-NI"],compliance:[],timezones:["America/Managua"]},PA:{name:"Panama",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Panama",locales:["es-PA"],compliance:["data-protection-pa"],timezones:["America/Panama"]},PE:{name:"Peru",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Peru (LPDP)",locales:["es-PE"],compliance:["lpdp-pe"],timezones:["America/Lima"]},PY:{name:"Paraguay",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Paraguay",locales:["es-PY"],compliance:[],timezones:["America/Asuncion"]},SR:{name:"Suriname",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Suriname",locales:["nl-SR"],compliance:[],timezones:["America/Paramaribo"]},SV:{name:"El Salvador",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"El Salvador",locales:["es-SV"],compliance:[],timezones:["America/El_Salvador"]},TT:{name:"Trinidad and Tobago",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Trinidad and Tobago",locales:["en"],compliance:[],timezones:["America/Port_of_Spain"]},UY:{name:"Uruguay",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Uruguay (Law 18.331)",locales:["es-UY"],compliance:["law18331-uy"],timezones:["America/Montevideo"]},VE:{name:"Venezuela",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Venezuela",locales:["es-VE"],compliance:[],timezones:["America/Caracas"]},AG:{name:"Antigua and Barbuda",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Antigua and Barbuda",locales:["en"],compliance:[],timezones:["America/Antigua"]},BB:{name:"Barbados",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Barbados",locales:["en"],compliance:[],timezones:["America/Barbados"]},BL:{name:"Saint Barth\xE9lemy",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Barth\xE9lemy",locales:["fr-BL"],compliance:[],timezones:["America/St_Barthelemy"]},BM:{name:"Bermuda",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Bermuda",locales:["en"],compliance:[],timezones:["Atlantic/Bermuda"]},BS:{name:"Bahamas",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Bahamas",locales:["en"],compliance:[],timezones:["America/Nassau"]},CU:{name:"Cuba",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cuba",locales:["es-CU"],compliance:[],timezones:["America/Havana"]},DM:{name:"Dominica",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Dominica",locales:["en"],compliance:[],timezones:["America/Dominica"]},GD:{name:"Grenada",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Grenada",locales:["en"],compliance:[],timezones:["America/Grenada"]},KN:{name:"Saint Kitts and Nevis",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Kitts and Nevis",locales:["en"],compliance:[],timezones:["America/St_Kitts"]},LC:{name:"Saint Lucia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Lucia",locales:["en"],compliance:[],timezones:["America/St_Lucia"]},PM:{name:"Saint Pierre and Miquelon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Pierre and Miquelon",locales:["fr-PM"],compliance:[],timezones:["America/Miquelon"]},PR:{name:"Puerto Rico",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Puerto Rico",locales:["es-PR","en"],compliance:[],timezones:["America/Puerto_Rico"]},VC:{name:"Saint Vincent and the Grenadines",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Vincent and the Grenadines",locales:["en"],compliance:[],timezones:["America/St_Vincent"]},IN:{name:"India",type:"country",complianceGroup:"opt-in-dpdpa",default:"opt-in-dpdpa",description:"India (DPDPA)",locales:["hi-IN","en","bn-IN","ta-IN"],compliance:["dpdpa"],timezones:["Asia/Kolkata","Asia/Calcutta"]},CN:{name:"China",type:"country",complianceGroup:"opt-in-china",default:"opt-in-china",description:"China (PIPL + DSL + CSL)",locales:["zh-CN"],compliance:["pipl","dsl-cn","csl-cn"],timezones:["Asia/Shanghai"]},BN:{name:"Brunei",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Brunei (Personal Data Protection Order)",locales:["ms-BN","en"],compliance:["privacy-bn"],timezones:["Asia/Brunei"]},ID:{name:"Indonesia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Indonesia (PDP Law)",locales:["id-ID"],compliance:["pdp-id"],timezones:["Asia/Jakarta","Asia/Makassar","Asia/Jayapura"]},KH:{name:"Cambodia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cambodia",locales:["km-KH"],compliance:[],timezones:["Asia/Phnom_Penh"]},LA:{name:"Laos",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Laos",locales:["lo-LA"],compliance:[],timezones:["Asia/Vientiane"]},MM:{name:"Myanmar",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Myanmar",locales:["my-MM"],compliance:[],timezones:["Asia/Yangon"]},MY:{name:"Malaysia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Malaysia (PDPA)",locales:["ms-MY","zh-MY","en"],compliance:["pdpa-my"],timezones:["Asia/Kuala_Lumpur","Asia/Kuching"]},PH:{name:"Philippines",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Philippines (DPA)",locales:["fil-PH","en"],compliance:["dpa-ph"],timezones:["Asia/Manila"]},SG:{name:"Singapore",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Singapore (PDPA)",locales:["zh-SG","ms-SG","ta-SG","en"],compliance:["pdpa-sg"],timezones:["Asia/Singapore"]},TH:{name:"Thailand",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Thailand (PDPA \u2014 GDPR-style opt-in)",locales:["th-TH"],compliance:["pdpa-th"],timezones:["Asia/Bangkok"]},TL:{name:"Timor-Leste",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Timor-Leste",locales:["pt-TL"],compliance:[],timezones:["Asia/Dili"]},VN:{name:"Vietnam",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Vietnam (PDPD)",locales:["vi-VN"],compliance:["pdpd-vn"],timezones:["Asia/Ho_Chi_Minh"]},HK:{name:"Hong Kong",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Hong Kong SAR (PDPO)",locales:["zh-HK"],compliance:["pdpl-hk"],timezones:["Asia/Hong_Kong"]},JP:{name:"Japan",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Japan (APPI)",locales:["ja-JP"],compliance:["appi"],timezones:["Asia/Tokyo"]},KP:{name:"North Korea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"North Korea",locales:["ko-KP"],compliance:[],timezones:["Asia/Pyongyang"]},KR:{name:"South Korea",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"South Korea (PIPA)",locales:["ko-KR"],compliance:["pipa-kr"],timezones:["Asia/Seoul"]},MN:{name:"Mongolia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mongolia",locales:["mn-MN"],compliance:[],timezones:["Asia/Ulaanbaatar","Asia/Hovd"]},MO:{name:"Macau",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Macau SAR (PDPA)",locales:["zh-MO","pt-MO"],compliance:["pdpa-mo"],timezones:["Asia/Macau"]},TW:{name:"Taiwan",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Taiwan (PDPL)",locales:["zh-TW"],compliance:["pdpl-tw"],timezones:["Asia/Taipei"]},AF:{name:"Afghanistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Afghanistan",locales:["fa-AF"],compliance:[],timezones:["Asia/Kabul"]},BD:{name:"Bangladesh",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Bangladesh",locales:["bn-BD"],compliance:[],timezones:["Asia/Dhaka"]},BT:{name:"Bhutan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Bhutan",locales:["dz-BT"],compliance:[],timezones:["Asia/Thimphu"]},IO:{name:"British Indian Ocean Territory",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"British Indian Ocean Territory",locales:["en"],compliance:[],timezones:["Indian/Chagos"]},LK:{name:"Sri Lanka",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Sri Lanka",locales:["si-LK","ta-LK"],compliance:["privacy-lk"],timezones:["Asia/Colombo"]},MV:{name:"Maldives",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Maldives",locales:["dv-MV"],compliance:[],timezones:["Indian/Maldives"]},NP:{name:"Nepal",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Nepal",locales:["ne-NP"],compliance:["privacy-np"],timezones:["Asia/Kathmandu"]},PK:{name:"Pakistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Pakistan",locales:["ur-PK","en"],compliance:[],timezones:["Asia/Karachi"]},AM:{name:"Armenia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Armenia",locales:["hy-AM"],compliance:[],timezones:["Asia/Yerevan"]},AZ:{name:"Azerbaijan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Azerbaijan",locales:["az-AZ"],compliance:[],timezones:["Asia/Baku"]},GE:{name:"Georgia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Georgia",locales:["ka-GE"],compliance:[],timezones:["Asia/Tbilisi"]},KG:{name:"Kyrgyzstan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Kyrgyzstan",locales:["ky-KG","ru-KG"],compliance:[],timezones:["Asia/Bishkek"]},KZ:{name:"Kazakhstan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Kazakhstan",locales:["kk-KZ","ru-KZ"],compliance:[],timezones:["Asia/Almaty","Asia/Aqtobe"]},TJ:{name:"Tajikistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Tajikistan",locales:["tg-TJ"],compliance:[],timezones:["Asia/Dushanbe"]},TM:{name:"Turkmenistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Turkmenistan",locales:["tk-TM"],compliance:[],timezones:["Asia/Ashgabat"]},UZ:{name:"Uzbekistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Uzbekistan",locales:["uz-UZ"],compliance:[],timezones:["Asia/Tashkent","Asia/Samarkand"]},AE:{name:"United Arab Emirates",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"United Arab Emirates (UAE PDPL / DIFC DPL / ADGM DPR)",locales:["ar-AE"],compliance:["uae-pdpl","difc-dpl","adgm-dpr"],timezones:["Asia/Dubai"]},BH:{name:"Bahrain",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Bahrain (PDPL)",locales:["ar-BH"],compliance:["pdpl-bh"],timezones:["Asia/Bahrain"]},IL:{name:"Israel",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Israel (Privacy Protection Law)",locales:["he-IL","ar-IL"],compliance:["privacy-il"],timezones:["Asia/Jerusalem"]},IQ:{name:"Iraq",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Iraq",locales:["ar-IQ"],compliance:[],timezones:["Asia/Baghdad"]},IR:{name:"Iran",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Iran",locales:["fa-IR"],compliance:[],timezones:["Asia/Tehran"]},JO:{name:"Jordan",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Jordan",locales:["ar-JO"],compliance:[],timezones:["Asia/Amman"]},KW:{name:"Kuwait",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Kuwait",locales:["ar-KW"],compliance:["privacy-kw"],timezones:["Asia/Kuwait"]},LB:{name:"Lebanon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Lebanon",locales:["ar-LB"],compliance:[],timezones:["Asia/Beirut"]},OM:{name:"Oman",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Oman (PDPL)",locales:["ar-OM"],compliance:["pdpl-om"],timezones:["Asia/Muscat"]},PS:{name:"Palestine",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Palestine",locales:["ar-PS"],compliance:[],timezones:["Asia/Gaza","Asia/Hebron"]},QA:{name:"Qatar",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Qatar (PDPL)",locales:["ar-QA"],compliance:["qpdl-qa"],timezones:["Asia/Qatar"]},SA:{name:"Saudi Arabia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Saudi Arabia (PDPL)",locales:["ar-SA"],compliance:["pdpl-sa"],timezones:["Asia/Riyadh"]},SY:{name:"Syria",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Syria",locales:["ar-SY"],compliance:[],timezones:["Asia/Damascus"]},YE:{name:"Yemen",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Yemen",locales:["ar-YE"],compliance:[],timezones:["Asia/Aden"]},BF:{name:"Burkina Faso",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Burkina Faso",locales:["fr-BF"],compliance:[],timezones:["Africa/Ouagadougou"]},BJ:{name:"Benin",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Benin",locales:["fr-BJ"],compliance:[],timezones:["Africa/Porto-Novo"]},CI:{name:"C\xF4te d'Ivoire",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"C\xF4te d'Ivoire",locales:["fr-CI"],compliance:[],timezones:["Africa/Abidjan"]},CM:{name:"Cameroon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cameroon",locales:["fr-CM","en"],compliance:[],timezones:["Africa/Douala"]},CV:{name:"Cabo Verde",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cabo Verde",locales:["pt-CV"],compliance:[],timezones:["Atlantic/Cape_Verde"]},GA:{name:"Gabon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Gabon",locales:["fr-GA"],compliance:[],timezones:["Africa/Libreville"]},GH:{name:"Ghana",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Ghana (DPA)",locales:["en"],compliance:["dpa-gh"],timezones:["Africa/Accra"]},GM:{name:"Gambia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Gambia",locales:["en"],compliance:[],timezones:["Africa/Banjul"]},GN:{name:"Guinea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guinea",locales:["fr-GN"],compliance:[],timezones:["Africa/Conakry"]},GQ:{name:"Equatorial Guinea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Equatorial Guinea",locales:["es-GQ","fr-GQ"],compliance:[],timezones:["Africa/Malabo"]},GW:{name:"Guinea-Bissau",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guinea-Bissau",locales:["pt-GW"],compliance:[],timezones:["Africa/Bissau"]},LR:{name:"Liberia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Liberia",locales:["en"],compliance:[],timezones:["Africa/Monrovia"]},ML:{name:"Mali",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mali",locales:["fr-ML"],compliance:[],timezones:["Africa/Bamako"]},MR:{name:"Mauritania",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mauritania",locales:["ar-MR"],compliance:[],timezones:["Africa/Nouakchott"]},NE:{name:"Niger",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Niger",locales:["fr-NE"],compliance:[],timezones:["Africa/Niamey"]},NG:{name:"Nigeria",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Nigeria (NDPA)",locales:["en"],compliance:["ndpa-ng"],timezones:["Africa/Lagos"]},SL:{name:"Sierra Leone",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Sierra Leone",locales:["en"],compliance:[],timezones:["Africa/Freetown"]},SN:{name:"Senegal",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Senegal",locales:["fr-SN"],compliance:[],timezones:["Africa/Dakar"]},TG:{name:"Togo",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Togo",locales:["fr-TG"],compliance:[],timezones:["Africa/Lome"]},BI:{name:"Burundi",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Burundi",locales:["fr-BI"],compliance:[],timezones:["Africa/Bujumbura"]},DJ:{name:"Djibouti",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Djibouti",locales:["fr-DJ","ar-DJ"],compliance:[],timezones:["Africa/Djibouti"]},ER:{name:"Eritrea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Eritrea",locales:["ti-ER"],compliance:[],timezones:["Africa/Asmara"]},ET:{name:"Ethiopia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Ethiopia",locales:["am-ET"],compliance:[],timezones:["Africa/Addis_Ababa"]},KE:{name:"Kenya",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Kenya (DPA)",locales:["sw-KE","en"],compliance:["dpa-ke"],timezones:["Africa/Nairobi"]},KM:{name:"Comoros",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Comoros",locales:["ar-KM","fr-KM"],compliance:[],timezones:["Indian/Comoro"]},MG:{name:"Madagascar",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Madagascar",locales:["fr-MG"],compliance:[],timezones:["Indian/Antananarivo"]},MU:{name:"Mauritius",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Mauritius (DPA)",locales:["en","fr-MU"],compliance:["dpa-mu"],timezones:["Indian/Mauritius"]},MW:{name:"Malawi",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Malawi",locales:["en"],compliance:[],timezones:["Africa/Blantyre"]},MZ:{name:"Mozambique",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mozambique",locales:["pt-MZ"],compliance:[],timezones:["Africa/Maputo"]},RW:{name:"Rwanda",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Rwanda (DPA)",locales:["rw-RW","en"],compliance:["dpa-rw"],timezones:["Africa/Kigali"]},SC:{name:"Seychelles",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Seychelles",locales:["fr-SC","en"],compliance:[],timezones:["Indian/Mahe"]},SO:{name:"Somalia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Somalia",locales:["so-SO"],compliance:[],timezones:["Africa/Mogadishu"]},SS:{name:"South Sudan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"South Sudan",locales:["en"],compliance:[],timezones:["Africa/Juba"]},ST:{name:"S\xE3o Tom\xE9 and Pr\xEDncipe",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"S\xE3o Tom\xE9 and Pr\xEDncipe",locales:["pt-ST"],compliance:[],timezones:["Africa/Sao_Tome"]},TZ:{name:"Tanzania",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Tanzania",locales:["sw-TZ","en"],compliance:[],timezones:["Africa/Dar_es_Salaam"]},UG:{name:"Uganda",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Uganda (DPA)",locales:["en"],compliance:["dpa-ug"],timezones:["Africa/Kampala"]},AO:{name:"Angola",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Angola",locales:["pt-AO"],compliance:[],timezones:["Africa/Luanda"]},BW:{name:"Botswana",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Botswana (DPA)",locales:["en"],compliance:["dpa-bw"],timezones:["Africa/Gaborone"]},LS:{name:"Lesotho",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Lesotho",locales:["en"],compliance:[],timezones:["Africa/Maseru"]},NA:{name:"Namibia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Namibia",locales:["en"],compliance:[],timezones:["Africa/Windhoek"]},SZ:{name:"Eswatini",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Eswatini",locales:["en"],compliance:[],timezones:["Africa/Mbabane"]},ZA:{name:"South Africa",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"South Africa (POPIA)",locales:["en","af-ZA"],compliance:["popia"],timezones:["Africa/Johannesburg"]},ZM:{name:"Zambia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Zambia (DPA)",locales:["en"],compliance:["dpa-zm"],timezones:["Africa/Lusaka"]},ZW:{name:"Zimbabwe",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Zimbabwe (DPA)",locales:["en"],compliance:["dpa-zw"],timezones:["Africa/Harare"]},DZ:{name:"Algeria",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Algeria",locales:["ar-DZ","fr-DZ"],compliance:["dpa-dz"],timezones:["Africa/Algiers"]},EG:{name:"Egypt",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Egypt (DPA)",locales:["ar-EG"],compliance:["dpa-eg"],timezones:["Africa/Cairo"]},LY:{name:"Libya",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Libya",locales:["ar-LY"],compliance:[],timezones:["Africa/Tripoli"]},MA:{name:"Morocco",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Morocco",locales:["ar-MA","fr-MA"],compliance:["dpa-ma"],timezones:["Africa/Casablanca"]},SD:{name:"Sudan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Sudan",locales:["ar-SD"],compliance:[],timezones:["Africa/Khartoum"]},TN:{name:"Tunisia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Tunisia (DPA)",locales:["ar-TN","fr-TN"],compliance:["dpa-tn"],timezones:["Africa/Tunis"]},CD:{name:"DR Congo",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"DR Congo",locales:["fr-CD"],compliance:[],timezones:["Africa/Kinshasa","Africa/Lubumbashi"]},CF:{name:"Central African Republic",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Central African Republic",locales:["fr-CF"],compliance:[],timezones:["Africa/Bangui"]},CG:{name:"Republic of Congo",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Republic of Congo",locales:["fr-CG"],compliance:[],timezones:["Africa/Brazzaville"]},TD:{name:"Chad",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Chad",locales:["fr-TD","ar-TD"],compliance:[],timezones:["Africa/Ndjamena"]},BY:{name:"Belarus",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Belarus",locales:["be-BY","ru-BY"],compliance:[],timezones:["Europe/Minsk"]},MD:{name:"Moldova",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Moldova",locales:["ro-MD"],compliance:[],timezones:["Europe/Chisinau"]},RU:{name:"Russia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Russia",locales:["ru-RU"],compliance:[],timezones:["Europe/Kaliningrad","Europe/Moscow","Europe/Samara","Asia/Yekaterinburg","Asia/Omsk","Asia/Krasnoyarsk","Asia/Irkutsk","Asia/Yakutsk","Asia/Vladivostok","Asia/Magadan","Asia/Kamchatka"]},UA:{name:"Ukraine",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Ukraine",locales:["uk-UA"],compliance:[],timezones:["Europe/Kyiv"]},VA:{name:"Holy See",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Holy See",locales:["it-VA"],compliance:[],timezones:["Europe/Vatican"]},AU:{name:"Australia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Australia (Privacy Act)",locales:["en"],compliance:["privacy-au"],timezones:["Australia/Sydney","Australia/Brisbane","Australia/Adelaide","Australia/Darwin","Australia/Perth","Australia/Hobart"]},FJ:{name:"Fiji",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Fiji",locales:["en"],compliance:["privacy-fj"],timezones:["Pacific/Fiji"]},FM:{name:"Micronesia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Micronesia",locales:["en"],compliance:[],timezones:["Pacific/Chuuk","Pacific/Pohnpei","Pacific/Kosrae"]},KI:{name:"Kiribati",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Kiribati",locales:["en"],compliance:[],timezones:["Pacific/Tarawa","Pacific/Enderbury","Pacific/Kiritimati"]},MH:{name:"Marshall Islands",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Marshall Islands",locales:["en"],compliance:[],timezones:["Pacific/Majuro","Pacific/Kwajalein"]},MP:{name:"Northern Mariana Islands",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Northern Mariana Islands",locales:["en"],compliance:[],timezones:["Pacific/Saipan"]},NC:{name:"New Caledonia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"New Caledonia",locales:["fr-NC"],compliance:[],timezones:["Pacific/Noumea"]},NF:{name:"Norfolk Island",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Norfolk Island",locales:["en"],compliance:[],timezones:["Pacific/Norfolk"]},NR:{name:"Nauru",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Nauru",locales:["en"],compliance:[],timezones:["Pacific/Nauru"]},NU:{name:"Niue",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Niue",locales:["en"],compliance:[],timezones:["Pacific/Niue"]},NZ:{name:"New Zealand",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"New Zealand (Privacy Act)",locales:["en"],compliance:["privacy-nz"],timezones:["Pacific/Auckland","Pacific/Chatham"]},PF:{name:"French Polynesia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"French Polynesia",locales:["fr-PF"],compliance:[],timezones:["Pacific/Tahiti","Pacific/Marquesas","Pacific/Gambier"]},PG:{name:"Papua New Guinea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Papua New Guinea",locales:["en"],compliance:["privacy-pg"],timezones:["Pacific/Port_Moresby","Pacific/Bougainville"]},PW:{name:"Palau",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Palau",locales:["en"],compliance:[],timezones:["Pacific/Palau"]},SB:{name:"Solomon Islands",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Solomon Islands",locales:["en"],compliance:[],timezones:["Pacific/Guadalcanal"]},TO:{name:"Tonga",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Tonga",locales:["en"],compliance:[],timezones:["Pacific/Tongatapu"]},TV:{name:"Tuvalu",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Tuvalu",locales:["en"],compliance:[],timezones:["Pacific/Funafuti"]},VU:{name:"Vanuatu",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Vanuatu",locales:["fr-VU","en"],compliance:[],timezones:["Pacific/Efate"]},WS:{name:"Samoa",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Samoa",locales:["en"],compliance:[],timezones:["Pacific/Apia"]},UK:{name:"United Kingdom",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"United Kingdom (UK GDPR + PECR)",locales:["en"],compliance:["uk-gdpr","pecr"],timezones:["Europe/London"]},CH:{name:"Switzerland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Switzerland (revFADP)",locales:["de-CH","fr-CH","it-CH"],compliance:["revfadp"],timezones:["Europe/Zurich"]}}},kl=[...Object.values(Ie.countries).reduce((i,e)=>(e.compliance.forEach(t=>{i.add(t)}),i),new Set)],Ll=Object.entries(Ie.countries).reduce(function(i,[e,t]){return i[e]=t.name,i},{}),Nl=Object.values(Ie.countries).reduce(function(i,e){return e.locales.forEach(t=>{i[t]=e.name}),i},{})});function Ml(i){let e=i.trim();if(!e)return;let t=ii.find(o=>!o.pattern.endsWith("*")&&o.pattern===e);if(t)return t;let n=ii.filter(o=>o.pattern.endsWith("*")&&e.startsWith(o.pattern.slice(0,-1)));if(n.length!==0)return n.reduce((o,r)=>r.pattern.length>o.pattern.length?r:o)}var ii,Qr=T(()=>{"use strict";p();ii=[{pattern:"security_storage",vendor:"Google Consent Mode v2",category:"necessary"},{pattern:"functionality_storage",vendor:"Google Consent Mode v2",category:"functional"},{pattern:"personalization_storage",vendor:"Google Consent Mode v2",category:"preferences"},{pattern:"analytics_storage",vendor:"Google Consent Mode v2",category:"analytics"},{pattern:"ad_storage",vendor:"Google Consent Mode v2",category:"marketing"},{pattern:"ad_user_data",vendor:"Google Consent Mode v2",category:"marketing"},{pattern:"ad_personalization",vendor:"Google Consent Mode v2",category:"marketing"},{pattern:"_ga",vendor:"Google Analytics",category:"analytics"},{pattern:"_ga_*",vendor:"Google Analytics 4",category:"analytics"},{pattern:"_gid",vendor:"Google Analytics",category:"analytics"},{pattern:"_gat",vendor:"Google Analytics",category:"analytics"},{pattern:"_gat_*",vendor:"Google Analytics",category:"analytics"},{pattern:"_gcl_au",vendor:"Google Ads",category:"marketing"},{pattern:"_gac_*",vendor:"Google Ads",category:"marketing"},{pattern:"_gcl_aw",vendor:"Google Ads",category:"marketing"},{pattern:"_fbp",vendor:"Meta Pixel",category:"marketing"},{pattern:"_fbc",vendor:"Meta Pixel",category:"marketing"},{pattern:"fr",vendor:"Meta Pixel",category:"marketing"},{pattern:"_hjSessionUser_*",vendor:"Hotjar",category:"analytics"},{pattern:"_hjSession_*",vendor:"Hotjar",category:"analytics"},{pattern:"_hjid",vendor:"Hotjar",category:"analytics"},{pattern:"hjViewportId",vendor:"Hotjar",category:"analytics"},{pattern:"ajs_user_id",vendor:"Segment",category:"analytics"},{pattern:"ajs_anonymous_id",vendor:"Segment",category:"analytics"},{pattern:"ajs_group_id",vendor:"Segment",category:"analytics"},{pattern:"intercom-id-*",vendor:"Intercom",category:"functional"},{pattern:"intercom-session-*",vendor:"Intercom",category:"functional"},{pattern:"intercom-device-id-*",vendor:"Intercom",category:"functional"},{pattern:"__hstc",vendor:"HubSpot",category:"marketing"},{pattern:"hubspotutk",vendor:"HubSpot",category:"marketing"},{pattern:"__hssc",vendor:"HubSpot",category:"marketing"},{pattern:"__hssrc",vendor:"HubSpot",category:"marketing"},{pattern:"mp_*",vendor:"Mixpanel",category:"analytics"},{pattern:"li_sugr",vendor:"LinkedIn Insight",category:"marketing"},{pattern:"bcookie",vendor:"LinkedIn Insight",category:"marketing"},{pattern:"lidc",vendor:"LinkedIn Insight",category:"marketing"},{pattern:"UserMatchHistory",vendor:"LinkedIn Insight",category:"marketing"},{pattern:"_ttp",vendor:"TikTok Pixel",category:"marketing"},{pattern:"_clck",vendor:"Microsoft Clarity",category:"analytics"},{pattern:"_clsk",vendor:"Microsoft Clarity",category:"analytics"},{pattern:"_pinterest_ct*",vendor:"Pinterest Tag",category:"marketing"},{pattern:"_pin_unauth",vendor:"Pinterest Tag",category:"marketing"},{pattern:"personalization_id",vendor:"X (Twitter) Pixel",category:"marketing"},{pattern:"amplitude_id_*",vendor:"Amplitude",category:"analytics"},{pattern:"__stripe_mid",vendor:"Stripe",category:"necessary"},{pattern:"__stripe_sid",vendor:"Stripe",category:"necessary"},{pattern:"__cf_bm",vendor:"Cloudflare",category:"necessary"},{pattern:"cf_clearance",vendor:"Cloudflare",category:"necessary"},{pattern:"_zendesk_*",vendor:"Zendesk",category:"functional"},{pattern:"drift_aid",vendor:"Drift",category:"functional"},{pattern:"driftt_aid",vendor:"Drift",category:"functional"},{pattern:"crisp-client*",vendor:"Crisp",category:"functional"},{pattern:"AMCV_*",vendor:"Adobe Experience Cloud",category:"analytics"},{pattern:"AMCVS_*",vendor:"Adobe Experience Cloud",category:"analytics"},{pattern:"s_cc",vendor:"Adobe Analytics",category:"analytics"},{pattern:"s_sq",vendor:"Adobe Analytics",category:"analytics"},{pattern:"s_vi",vendor:"Adobe Analytics",category:"analytics"},{pattern:"mbox",vendor:"Adobe Target",category:"preferences"},{pattern:"_mkto_trk",vendor:"Marketo",category:"marketing"},{pattern:"cto_bundle",vendor:"Criteo",category:"marketing"},{pattern:"cto_id_out",vendor:"Criteo",category:"marketing"},{pattern:"TTD_DEVICE_ID",vendor:"The Trade Desk",category:"marketing"},{pattern:"ttd_*",vendor:"The Trade Desk",category:"marketing"},{pattern:"id",vendor:"Google DoubleClick",category:"marketing"},{pattern:"IDE",vendor:"Google DoubleClick",category:"marketing"},{pattern:"DSID",vendor:"Google DoubleClick",category:"marketing"},{pattern:"KADUSERCOOKIE",vendor:"PubMatic",category:"marketing"},{pattern:"rubicon_user_*",vendor:"Rubicon Project",category:"marketing"},{pattern:"Anonymon_id",vendor:"OpenX",category:"marketing"},{pattern:"pdomid",vendor:"OpenX",category:"marketing"},{pattern:"uuid2",vendor:"AppNexus",category:"marketing"},{pattern:"icu",vendor:"AppNexus",category:"marketing"},{pattern:"_scid",vendor:"Snap Pixel",category:"marketing"},{pattern:"_sc_cspv",vendor:"Snap Pixel",category:"marketing"},{pattern:"_rdt_uuid",vendor:"Reddit Pixel",category:"marketing"},{pattern:"obuid",vendor:"Outbrain",category:"marketing"},{pattern:"t_gid",vendor:"Taboola",category:"marketing"},{pattern:"__kla_id",vendor:"Klaviyo",category:"marketing"},{pattern:"sc_anonymous_id",vendor:"Salesforce Marketing Cloud",category:"marketing"},{pattern:"vst",vendor:"Salesforce Marketing Cloud",category:"marketing"},{pattern:"visitor_id*",vendor:"Salesforce Pardot",category:"marketing"},{pattern:"piAId",vendor:"Salesforce Pardot",category:"marketing"},{pattern:"exp_last_visit",vendor:"ActiveCampaign",category:"marketing"},{pattern:"exp_tracker",vendor:"ActiveCampaign",category:"marketing"},{pattern:"_ce.s*",vendor:"Crazy Egg",category:"analytics"},{pattern:"lr_*",vendor:"LogRocket",category:"analytics"},{pattern:"_hp2_id.*",vendor:"Heap Analytics",category:"analytics"},{pattern:"_hp2_ses.*",vendor:"Heap Analytics",category:"analytics"},{pattern:"_lo_*",vendor:"Lucky Orange",category:"analytics"},{pattern:"fs_uid",vendor:"FullStory",category:"analytics"},{pattern:"_fs_*",vendor:"FullStory",category:"analytics"},{pattern:"ln_or",vendor:"LiveSession",category:"analytics"},{pattern:"_vwo_uuid*",vendor:"Visual Website Optimizer (VWO)",category:"analytics"},{pattern:"_vis_opt_*",vendor:"Visual Website Optimizer (VWO)",category:"analytics"},{pattern:"OptimizelyBuckets",vendor:"Optimizely",category:"analytics"},{pattern:"optimizelyEndUserId",vendor:"Optimizely",category:"analytics"},{pattern:"OptanonConsent",vendor:"OneTrust",category:"necessary"},{pattern:"OptanonAlertBoxClosed",vendor:"OneTrust",category:"necessary"},{pattern:"SyrenisCookieConsentDate_*",vendor:"Syrenis Cassie",category:"necessary"},{pattern:"SyrenisCookieFormConsent_*",vendor:"Syrenis Cassie",category:"necessary"},{pattern:"SyrenisCookiePrivacyLink_*",vendor:"Syrenis Cassie",category:"necessary"},{pattern:"SyrenisGtmConsent_*",vendor:"Syrenis Cassie",category:"necessary"},{pattern:"SyrenisGuid_*",vendor:"Syrenis Cassie",category:"necessary"},{pattern:"CookieConsent",vendor:"Cookiebot",category:"necessary"},{pattern:"uc_settings",vendor:"Usercentrics",category:"necessary"},{pattern:"uc_user_interaction",vendor:"Usercentrics",category:"necessary"},{pattern:"didomi_token",vendor:"Didomi",category:"necessary"},{pattern:"euconsent-v2",vendor:"IAB TCF Global Vendor List",category:"necessary"},{pattern:"cconsent",vendor:"Cookie Consent Studio",category:"necessary"},{pattern:"JSESSIONID",vendor:"New Relic",category:"necessary"},{pattern:"NRAGENT",vendor:"New Relic",category:"necessary"},{pattern:"_dd_s",vendor:"Datadog",category:"necessary"},{pattern:"dtCookie",vendor:"Dynatrace",category:"necessary"},{pattern:"dtPC",vendor:"Dynatrace",category:"necessary"},{pattern:"rxVisitor",vendor:"Dynatrace",category:"necessary"},{pattern:"ak_bmsc",vendor:"Akamai",category:"necessary"},{pattern:"_abck",vendor:"Akamai",category:"necessary"},{pattern:"vuid",vendor:"Vimeo",category:"analytics"},{pattern:"__cf_vuid",vendor:"Vimeo",category:"analytics"},{pattern:"VISITOR_INFO1_LIVE",vendor:"YouTube",category:"marketing"},{pattern:"YSC",vendor:"YouTube",category:"necessary"},{pattern:"GPS",vendor:"YouTube",category:"marketing"},{pattern:"_wistia_*",vendor:"Wistia",category:"analytics"},{pattern:"_elvr_*",vendor:"Elevar",category:"analytics"},{pattern:"stkn",vendor:"Shopify Core Analytics",category:"analytics"},{pattern:"rmStore*",vendor:"Rakuten Advertising",category:"marketing"},{pattern:"_ir_*",vendor:"Impact Radius",category:"marketing"},{pattern:"aw*",vendor:"Awin",category:"marketing"},{pattern:"bctc",vendor:"Awin",category:"marketing"},{pattern:"mcookie",vendor:"CJ Affiliate",category:"marketing"},{pattern:"_shopify_y",vendor:"Shopify",category:"analytics"},{pattern:"_shopify_s",vendor:"Shopify",category:"analytics"},{pattern:"_shopify_sa_p",vendor:"Shopify",category:"marketing"},{pattern:"shopify_sa_t",vendor:"Shopify",category:"marketing"},{pattern:"cart_sig",vendor:"Shopify",category:"necessary"},{pattern:"secure_customer_sig",vendor:"Shopify",category:"necessary"},{pattern:"wp_woocommerce_session*",vendor:"WooCommerce",category:"necessary"},{pattern:"woocommerce_items_in_cart",vendor:"WooCommerce",category:"necessary"},{pattern:"woocommerce_cart_hash",vendor:"WooCommerce",category:"necessary"},{pattern:"QSI_",vendor:"Qualtrics",category:"functional"},{pattern:"feedback_id",vendor:"SurveyMonkey",category:"functional"},{pattern:"usbl.",vendor:"Usabilla",category:"functional"}]});function Zr(i){return i.map(oi).join("")}function oi(i){return i.t==="text"?Ul(i.v):i.t==="br"?"<br>":i.t==="a"?`<a href="${Gl(i.href)}">${i.c.map(oi).join("")}</a>`:`<${i.t}>${i.c.map(oi).join("")}</${i.t}>`}function Ul(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Gl(i){return i.replace(/"/g,"&quot;").replace(/</g,"&lt;")}function jl(i){if(!i)return"";let e=i.trim();if(e.startsWith("["))try{return Zr(JSON.parse(e))}catch{}return i}function Xr(i){return i.t==="text"?i.v.trim().length>0:i.t==="br"?!1:i.c.some(Xr)}function Bl(i){return i.replace(/<[^>]*>/g,"").trim().length>0}function tn(i){if(!i)return!1;let e=i.trim();if(!e)return!1;if(e.startsWith("["))try{return JSON.parse(e).some(Xr)}catch{}return Bl(e)}var es=T(()=>{"use strict";p()});function Fl(i){return new TextEncoder().encode(i)}function $l(i){return new TextDecoder().decode(i)}function Hl(i){let e="";for(let t=0;t<i.length;t+=3){let n=i[t]??0,o=t+1<i.length?i[t+1]??0:0,r=t+2<i.length?i[t+2]??0:0;e+=et[n>>2],e+=et[(n&3)<<4|o>>4],t+1<i.length&&(e+=et[(o&15)<<2|r>>6]),t+2<i.length&&(e+=et[r&63])}return e}function Vl(i){let e=new Map(et.split("").map((o,r)=>[o,r])),t=i.replace(/[^A-Za-z0-9\-_]/g,""),n=[];for(let o=0;o<t.length;o+=4){let r=e.get(t[o]??"")??0,s=e.get(t[o+1]??"")??0,a=t[o+2]!==void 0?e.get(t[o+2]):void 0,c=t[o+3]!==void 0?e.get(t[o+3]):void 0;n.push(r<<2|s>>4),a!==void 0&&n.push((s&15)<<4|a>>2),c!==void 0&&n.push(((a??0)&3)<<6|c)}return new Uint8Array(n)}function ri(i){let e={v:2,ts:Math.floor(Date.now()/100),cmpId:i.cmpId,cmpV:i.cmpVersion,cs:i.consentScreen,lang:i.consentLanguage.toUpperCase().slice(0,2),vlV:i.vendorListVersion,pc:i.purposeConsents,vc:i.vendorConsents};return Hl(Fl(JSON.stringify(e)))}function Wl(i){try{let e=JSON.parse($l(Vl(i)));return{version:e.v,cmpId:e.cmpId,consentLanguage:e.lang,purposeConsents:Array.isArray(e.pc)?e.pc:[],vendorConsents:Array.isArray(e.vc)?e.vc:[],created:e.ts*100}}catch{return null}}var et,ts=T(()=>{"use strict";p();et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"});function ql(i){return new TextEncoder().encode(i)}function Jl(i){return new TextDecoder().decode(i)}function zl(i){let e="";for(let t=0;t<i.length;t+=3){let n=i[t]??0,o=t+1<i.length?i[t+1]??0:0,r=t+2<i.length?i[t+2]??0:0;e+=tt[n>>2],e+=tt[(n&3)<<4|o>>4],t+1<i.length&&(e+=tt[(o&15)<<2|r>>6]),t+2<i.length&&(e+=tt[r&63])}return e}function Kl(i){let e=new Map(tt.split("").map((o,r)=>[o,r])),t=i.replace(/[^A-Za-z0-9\-_]/g,""),n=[];for(let o=0;o<t.length;o+=4){let r=e.get(t[o]??"")??0,s=e.get(t[o+1]??"")??0,a=t[o+2]!==void 0?e.get(t[o+2]):void 0,c=t[o+3]!==void 0?e.get(t[o+3]):void 0;n.push(r<<2|s>>4),a!==void 0&&n.push((s&15)<<4|a>>2),c!==void 0&&n.push(((a??0)&3)<<6|c)}return new Uint8Array(n)}function si(i,e){return i?e?Ql:Zl:Yl}function ai(i){let e={v:1,ts:Math.floor(Date.now()/100),cmpId:i.cmpId,cmpV:i.cmpVersion,sect:"usnat",saleOO:si(i.saleApplicable,i.saleOptOut),shareOO:si(i.sharingApplicable,i.sharingOptOut),taOO:si(i.sharingApplicable,i.sharingOptOut),mspaCT:i.mspaCoveredTransaction?1:2,mspaOOM:i.mspaOptOutOptionMode,mspaSPM:i.mspaServiceProviderMode,...i.gpcDetected!==void 0?{gpc:i.gpcDetected}:{}};return zl(ql(JSON.stringify(e)))}function Xl(i){try{let e=JSON.parse(Jl(Kl(i)));return{version:e.v,cmpId:e.cmpId,cmpVersion:e.cmpV,saleOptOut:e.saleOO,sharingOptOut:e.shareOO,targetedAdvertisingOptOut:e.taOO,...e.gpc!==void 0?{gpc:e.gpc}:{},created:e.ts*100}}catch{return null}}var tt,Yl,Ql,Zl,ns=T(()=>{"use strict";p();tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";Yl=0,Ql=1,Zl=2});function td(i,e){if(e==="ltr"||e==="rtl")return e;try{let n=new Intl.Locale(i).getTextInfo?.().direction;if(n==="ltr"||n==="rtl")return n}catch{}let t=i.slice(0,2).toLowerCase();return ed.includes(t)?"rtl":"ltr"}var ed,is=T(()=>{"use strict";p();ed=["ar","he","fa","ur","ps","sd","ug","yi"]});var os={};Pn(os,{COMPLIANCE_GROUPS:()=>Xe,COMPLIANCE_GROUP_IDS:()=>Xt,COMPLIANCE_REGULATION_IDS:()=>kl,COMPLIANCE_VALIDATION_RULES:()=>ti,COOKIE_PURPOSES:()=>Pl,COOKIE_PURPOSE_DEFAULTS:()=>Tl,COOKIE_PURPOSE_IDS:()=>en,COUNTRY_CODES:()=>Ll,CPRA_CATEGORIES:()=>Al,DEFAULT_PROFILES:()=>Zt,EMBEDDED_COMPLIANCE_MAP:()=>Ie,GPC_OPTIONS:()=>vl,KNOWN_COOKIE_PURPOSES:()=>Kr,LEGAL_BASIS_OPTIONS:()=>Cl,LOCALES:()=>Nl,TCF_PURPOSES:()=>bl,TCF_SPECIAL_FEATURES:()=>Ol,TRACKER_KNOWLEDGE_BASE:()=>ii,buildCookieCategoryIndex:()=>xe,color:()=>Y,debounce:()=>hl,decodeGppString:()=>Xl,decodeTcString:()=>Wl,encodeGppString:()=>ai,encodeTcString:()=>ri,findCategoryForCookie:()=>Dl,formatLog:()=>Sl,getCookieLegalBasis:()=>Me,hasVisibleText:()=>tn,inferCookiePurpose:()=>Il,isMandatoryCookie:()=>ei,jsonToHtml:()=>Zr,matchTrackerKnowledge:()=>Ml,renderContentText:()=>jl,resolveComplianceMapOverride:()=>ni,resolveTextDirection:()=>td,statusLabel:()=>El,throttle:()=>yl});var re=T(()=>{"use strict";p();qr();Jr();zr();Yr();Qr();es();ts();ns();is();Xn()});var Kd={};Pn(Kd,{CategoryAction:()=>Rn,ConsentAction:()=>En,MongoDBAdapter:()=>ke,MySQLAdapter:()=>Le,PostgreSQLAdapter:()=>Ne,SQLiteAdapter:()=>Te,createConsenti:()=>zd,dashboardDir:()=>Fd});module.exports=sc(Kd);p();var Va=require("node:events"),Wa=require("node:crypto"),Be=require("node:fs/promises"),V=require("node:path"),Si=require("node:url");p();var ft=class{plugins=[];register(e){this.plugins=e}async initialize(e){for(let t of this.plugins)try{await t.initialize?.(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" initialize failed:`,n)}}async destroy(){for(let e of this.plugins)try{await e.destroy?.()}catch(t){console.warn(`[Consenti] Plugin "${e.name}" destroy failed:`,t)}}async runBeforeConsentSave(e){let t=e;for(let n of this.plugins)if(n.beforeConsentSave)try{t=await n.beforeConsentSave(t)}catch(o){console.warn(`[Consenti] Plugin "${n.name}" beforeConsentSave failed:`,o)}return t}async runAfterConsentSave(e){for(let t of this.plugins)if(t.afterConsentSave)try{await t.afterConsentSave(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" afterConsentSave failed:`,n)}}async runBeforeConsentUpdate(e){let t=e;for(let n of this.plugins)if(n.beforeConsentUpdate)try{t=await n.beforeConsentUpdate(t)}catch(o){console.warn(`[Consenti] Plugin "${n.name}" beforeConsentUpdate failed:`,o)}return t}async runAfterConsentUpdate(e){for(let t of this.plugins)if(t.afterConsentUpdate)try{await t.afterConsentUpdate(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" afterConsentUpdate failed:`,n)}}async runAfterProfileFetch(e){let t=e;for(let n of this.plugins)if(n.afterProfileFetch)try{t=await n.afterProfileFetch(t)}catch(o){console.warn(`[Consenti] Plugin "${n.name}" afterProfileFetch failed:`,o)}return t}async runBeforeUserCreate(e){let t=e;for(let n of this.plugins)if(n.beforeUserCreate)try{t=await n.beforeUserCreate(t)}catch(o){console.warn(`[Consenti] Plugin "${n.name}" beforeUserCreate failed:`,o)}return t}async runAfterUserCreate(e){for(let t of this.plugins)if(t.afterUserCreate)try{await t.afterUserCreate(e)}catch(n){console.warn(`[Consenti] Plugin "${t.name}" afterUserCreate failed:`,n)}}};p();var Tn=require("node:fs"),Ni=require("node:path");function xi(i,e,t={},n={},o="local"){let r={};return n.type!==void 0&&(r.type=n.type),n.gpc!==void 0&&(r.gpc=n.gpc),{appName:t.appName??"Consenti",appLogoPath:t?.appLogoPath??"/logo-dark.svg",hidePoweredBy:t.hidePoweredBy??!1,basePath:e,compliance:r,authMode:o}}function Mi(i){return`<script>(function(){function d(o){if(o&&typeof o==='object')Object.keys(o).forEach(function(k){d(o[k])});return Object.freeze(o)}Object.defineProperty(window,'__CONSENTI_CONFIG__',{value:d(${JSON.stringify(i).replace(/<\/script>/gi,"<\\/script>")}),writable:false,configurable:false,enumerable:true})})()</script>`}function $e(i,e){let t=Buffer.from(i).toString("utf-8");return t.includes("</head>")?t.replace("</head>",`${e}</head>`):t.replace("</body>",`${e}</body>`)}p();var cc="https://vendor-list.consensu.org/v3/vendor-list.json";var Ce=null,Ui=0,He=null;function lc(i){return typeof i=="object"&&i!==null&&"vendors"in i&&"purposes"in i&&typeof i.vendors=="object"&&typeof i.purposes=="object"}async function Ae(){if(Ce&&Date.now()-Ui<6048e5)return Ce;try{let i=await fetch(cc,{signal:AbortSignal.timeout(15e3)});if(!i.ok)return Ce;let e=await i.json();if(!lc(e))return Ce;let t=e;return Ce={gvlSpecificationVersion:t.gvlSpecificationVersion,vendorListVersion:t.vendorListVersion,tcfPolicyVersion:t.tcfPolicyVersion,vendors:t.vendors,purposes:t.purposes,raw:t},Ui=Date.now(),Ce}catch{return Ce}}function Gi(){He||(Ae(),He=setInterval(()=>{Ae()},6048e5))}function ji(){He&&(clearInterval(He),He=null)}p();var dc="https://vendor-list.consensu.org/v3/cmp-list.json";var Pe=null,Bi=0,Ve=null;function uc(i){return typeof i=="object"&&i!==null&&"cmps"in i&&typeof i.cmps=="object"}async function We(i=!1){if(!i&&Pe&&Date.now()-Bi<6048e5)return Pe;try{let e=await fetch(dc,{signal:AbortSignal.timeout(15e3)});if(!e.ok)return Pe;let t=await e.json();if(!uc(t))return Pe;let n=t;return Pe={cmpListVersion:n.cmpListVersion,lastUpdated:n.lastUpdated,cmps:n.cmps},Bi=Date.now(),Pe}catch{return Pe}}function Fi(){Ve||(We(),Ve=setInterval(()=>{We()},6048e5))}function $i(){Ve&&(clearInterval(Ve),Ve=null)}p();var Hi={ConsentRecord:{type:"object",properties:{id:{type:"string"},visitorId:{type:"string"},profileId:{type:"string"},locale:{type:"string"},consentJson:{type:"object",additionalProperties:{type:"string",enum:["granted","denied","objected"]}},gpcDetected:{type:"boolean"},source:{type:"string",enum:["banner","api","import"]},ageVerified:{type:"boolean"},tcfString:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}}},CreateConsentInput:{type:"object",required:["visitorId","profileId","consentJson"],properties:{visitorId:{type:"string"},profileId:{type:"string"},consentJson:{type:"object",additionalProperties:{type:"string"}},gpcDetected:{type:"boolean",default:!1},source:{type:"string",enum:["banner","api","import"],default:"banner"},ageVerified:{type:"boolean"},parentalConsentToken:{type:"string"},tcfString:{type:"string"}}}},In={openapi:"3.1.0",info:{title:"Consenti Public API",version:"0.1.0",description:"Visitor-facing endpoints for reading consent profiles and submitting/verifying consent. Rate-limited; no authentication required.",license:{name:"Apache 2.0",url:"https://www.apache.org/licenses/LICENSE-2.0"}},servers:[{url:"/consenti/api",description:"Consenti Public API"}],paths:{"/v1/profiles/{id}":{get:{tags:["Profile"],summary:"Get profile in its default locale",description:"Returns the resolved profile with banner and modal content for the profile's default locale. Includes `currentLocale`, `locales`, `cookies`, `mainBanner`, `preferenceModal`, and optionally `gpcBanner`.",parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Resolved profile for the default locale"},404:{description:"Profile not found"}}}},"/v1/profiles/{id}/{locale}":{get:{tags:["Profile"],summary:"Get profile resolved for a specific locale",description:"Same response shape as `GET /v1/profiles/{id}` but resolved for the requested locale, falling back to the default locale for any missing translations.",parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}},{name:"locale",in:"path",required:!0,schema:{type:"string",example:"fr"}}],responses:{200:{description:"Resolved profile for the requested locale"},404:{description:"Profile not found"}}}},"/v1/consent":{post:{tags:["Consent"],summary:"Submit consent",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/CreateConsentInput"}}}},responses:{200:{description:"Consent created or updated",content:{"application/json":{schema:{$ref:"#/components/schemas/ConsentRecord"}}}},400:{description:"Validation error"}}}},"/v1/consent/{visitorId}":{get:{tags:["Consent"],summary:"Get consent for visitor",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Consent record",content:{"application/json":{schema:{$ref:"#/components/schemas/ConsentRecord"}}}},404:{description:"Not found"}}},put:{tags:["Consent"],summary:"Update consent",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Updated consent"}}},delete:{tags:["Consent"],summary:"GDPR erasure \u2014 delete all consent data for visitor",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Erased successfully"}}}},"/v1/consent/{visitorId}/verify":{get:{tags:["Consent"],summary:"Verify consent validity",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Verification result"}}}},"/v1/consent/{visitorId}/parental-consent-request":{post:{tags:["Consent"],summary:"Request a parental-consent token (stateless hook)",description:"Issues a token \u2014 signed with `compliance.dataSigningHash` when configured, otherwise unsigned \u2014 for a host's own out-of-band parental-verification flow. Emits `consent.parentalConsentRequired`. Not by itself sufficient verifiable parental consent (COPPA-style VPC is left to the host).",parameters:[{name:"visitorId",in:"path",required:!0,schema:{type:"string"}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["profileId"],properties:{profileId:{type:"string"}}}}}},responses:{200:{description:"Token issued",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}},400:{description:"Validation error"},403:{description:"Visitor ownership check failed"},404:{description:"Profile not found"}}}},"/v1/consent/parental-consent-resolve":{post:{tags:["Consent"],summary:"Resolve a parental-consent token",description:"Recovers `visitorId`/`profileId` from a token issued by the request route above and emits `consent.parentalConsentGranted` \u2014 the host's own backend listener decides what \"granted\" means for stored consent. No visitor-ownership cookie required, since this is typically called from the parent's own device. Token replay is not prevented (stateless by design).",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["token"],properties:{token:{type:"string"}}}}}},responses:{200:{description:"Token resolved",content:{"application/json":{schema:{type:"object",properties:{visitorId:{type:"string"},profileId:{type:"string"}}}}}},400:{description:"Validation error"},403:{description:"Invalid, tampered, or expired token"}}}},"/v1/notice-shown":{post:{tags:["Consent"],summary:"Record proof that the consent banner was shown",description:"Lightweight, fire-and-forget ping recording that the banner was rendered to a visitor, independent of whether they ever interact with it. Called automatically by `@consenti/ui` on banner mount when `api.enabled` is configured.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["visitorId","profileId","locale"],properties:{visitorId:{type:"string"},profileId:{type:"string"},locale:{type:"string"}}}}}},responses:{201:{description:"Recorded"},400:{description:"Validation error"}}}}},components:{schemas:Hi}},bn={openapi:"3.1.0",info:{title:"Consenti Admin API",version:"0.1.0",description:"Authenticated endpoints for managing profiles, consent records, users, analytics, and exports. All routes (except `/auth/login`) require `Authorization: Bearer <JWT>`. Obtain a token via `POST /auth/login`.",license:{name:"Apache 2.0",url:"https://www.apache.org/licenses/LICENSE-2.0"}},servers:[{url:"/consenti/admin/v1",description:"Consenti Admin API"}],paths:{"/auth/login":{post:{tags:["Auth"],summary:"Login with email + password",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{email:{type:"string"},password:{type:"string"}}}}}},responses:{200:{description:"JWT token"}}}},"/auth/me":{get:{tags:["Auth"],summary:"Get current user",security:[{BearerAuth:[]}],responses:{200:{description:"Current admin user info"}}}},"/auth/logout":{post:{tags:["Auth"],summary:"Invalidate session",security:[{BearerAuth:[]}],responses:{200:{description:"Logged out"}}}},"/auth/refresh":{post:{tags:["Auth"],summary:"Reissue a fresh token from the current one, extending the session",description:"Used by the dashboard on user activity to implement a sliding inactivity timeout instead of a flat expiry from login.",security:[{BearerAuth:[]}],responses:{200:{description:"New JWT token"},401:{description:"Current token is missing, invalid, or already expired"}}}},"/auth/oidc/authorize":{get:{tags:["Auth"],summary:"Start OIDC authorization (PKCE)",responses:{302:{description:"Redirect to OIDC provider"}}}},"/auth/oidc/callback":{get:{tags:["Auth"],summary:"OIDC callback \u2014 exchange code for token",responses:{200:{description:"JWT token"}}}},"/auth/saml/metadata":{get:{tags:["Auth"],summary:"SAML SP metadata XML",responses:{200:{description:"SAML metadata XML",content:{"application/xml":{}}}}}},"/auth/saml/acs":{post:{tags:["Auth"],summary:"SAML Assertion Consumer Service",responses:{200:{description:"JWT token"}}}},"/auth/totp/setup":{post:{tags:["Auth"],summary:"Setup TOTP MFA",security:[{BearerAuth:[]}],responses:{200:{description:"TOTP secret and QR URL"}}}},"/auth/totp/verify":{post:{tags:["Auth"],summary:"Verify and enable TOTP",security:[{BearerAuth:[]}],responses:{200:{description:"TOTP enabled"}}}},"/profiles":{get:{tags:["Profiles"],summary:"List profiles",security:[{BearerAuth:[]}],responses:{200:{description:"Array of profiles"}}},post:{tags:["Profiles"],summary:"Create profile",security:[{BearerAuth:[]}],responses:{201:{description:"Created profile"}}}},"/consent-templates":{get:{tags:["Consent Templates"],summary:"List consent templates",description:"A Consent Template groups parameters (`cookies`, keyed by id) with the categories that own their legal basis (`categories`, keyed by id).",security:[{BearerAuth:[]}],responses:{200:{description:"Array of consent templates"}}},post:{tags:["Consent Templates"],summary:"Create consent template",security:[{BearerAuth:[]}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["name","cookies","categories"],properties:{name:{type:"string"},cookies:{type:"object",description:"Keyed by parameter id."},categories:{type:"object",description:"Keyed by category id. Every parameter id must appear in exactly one category."}}}}}},responses:{201:{description:"Created consent template"},400:{description:"Validation error"}}}},"/consent-templates/{id}":{get:{tags:["Consent Templates"],summary:"Get consent template",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Consent template"},404:{description:"Not found"}}},put:{tags:["Consent Templates"],summary:"Update consent template",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Updated consent template"},422:{description:"Change would break compliance for profiles using this template"}}},delete:{tags:["Consent Templates"],summary:"Delete consent template",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Deleted"},422:{description:"Template is still used by profiles"}}}},"/consent-templates/{id}/copy":{post:{tags:["Consent Templates"],summary:"Duplicate a consent template",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{201:{description:"Copied consent template"}}}},"/consent-templates/{id}/profile-usage":{get:{tags:["Consent Templates"],summary:"List profiles using this consent template",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Array of profile summaries"}}}},"/consents":{get:{tags:["Consents"],summary:"List consent records",security:[{BearerAuth:[]}],parameters:[{name:"page",in:"query",schema:{type:"integer"}},{name:"profileId",in:"query",schema:{type:"string"}},{name:"from",in:"query",schema:{type:"string",format:"date"}},{name:"to",in:"query",schema:{type:"string",format:"date"}},{name:"q",in:"query",schema:{type:"string"},description:"Free-text search across visitorId, profileId, locale, source"}],responses:{200:{description:"Paginated consent records"}}}},"/stats/overview":{get:{tags:["Stats"],summary:"Overview statistics",security:[{BearerAuth:[]}],responses:{200:{description:"Totals and acceptance rates"}}}},"/stats/timeline":{get:{tags:["Stats"],summary:"Daily consent timeline",security:[{BearerAuth:[]}],parameters:[{name:"days",in:"query",schema:{type:"integer",default:30}}],responses:{200:{description:"Array of date+count"}}}},"/stats/countries":{get:{tags:["Stats"],summary:"Consent by country",security:[{BearerAuth:[]}],responses:{200:{description:"Country counts"}}}},"/stats/gpc":{get:{tags:["Stats"],summary:"GPC detection stats",security:[{BearerAuth:[]}],responses:{200:{description:"GPC rate and counts"}}}},"/export/consents":{get:{tags:["Export"],summary:"Export consent records",security:[{BearerAuth:[]}],parameters:[{name:"format",in:"query",schema:{type:"string",enum:["csv","json"]}},{name:"from",in:"query",schema:{type:"string",format:"date"}},{name:"to",in:"query",schema:{type:"string",format:"date"}}],responses:{200:{description:"CSV or JSON download"}}}},"/tenants":{get:{tags:["Sites"],summary:"List all sites/tenants",security:[{BearerAuth:[]}],responses:{200:{description:"Array of tenants"}}},post:{tags:["Sites"],summary:"Create a site/tenant",security:[{BearerAuth:[]}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{name:{type:"string"},slug:{type:"string"}},required:["name","slug"]}}}},responses:{201:{description:"Created tenant"}}}},"/tenants/{id}":{put:{tags:["Sites"],summary:"Update a site/tenant",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Updated tenant"}}},delete:{tags:["Sites"],summary:"Delete a site/tenant",security:[{BearerAuth:[]}],parameters:[{name:"id",in:"path",required:!0,schema:{type:"string"}}],responses:{200:{description:"Deleted"}}}},"/setup/status":{get:{tags:["Setup"],summary:"Whether the first-run setup wizard has been completed for this tenant",security:[{BearerAuth:[]}],responses:{200:{description:"{ completed: boolean }"}}}},"/setup/config":{get:{tags:["Setup"],summary:"Resolved server config (secrets redacted) plus production-readiness flags",description:"The same merged `DEFAULT_CONFIG` + user config `createConsenti` computes at boot. `auth.adminPassword`, `auth.masterSecret`, `compliance.dataSigningHash`, `compliance.dataSigningHash`, storage credentials, and OIDC/SAML secrets are replaced with a redaction marker.",security:[{BearerAuth:[]}],responses:{200:{description:"{ config: object, usingJsonStorage: boolean, usingDefaultCredentials: boolean }"}}}},"/setup/compliance-groups":{get:{tags:["Setup"],summary:"The 8 built-in compliance groups with label/description/regulation metadata",security:[{BearerAuth:[]}],responses:{200:{description:"Array of compliance group descriptors"}}}},"/setup/seed-profiles":{post:{tags:["Setup"],summary:"Seed default profiles for the selected compliance groups",description:"Idempotent \u2014 skips any group that already has an active profile. `groups` must be a subset of the 8 built-in compliance group ids.",security:[{BearerAuth:[]}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{groups:{type:"array",items:{type:"string"}}},required:["groups"]}}}},responses:{200:{description:"{ seeded: string[] }"},400:{description:"groups is missing, not an array of strings, or contains an unknown compliance group id"},409:{description:"Setup has already been completed for this tenant"}}}},"/setup/complete":{post:{tags:["Setup"],summary:"Mark the first-run setup wizard as complete for this tenant",description:"Called on both wizard finish and skip. Never reset from the dashboard once true.",security:[{BearerAuth:[]}],responses:{200:{description:"Updated tenant settings"},409:{description:"Setup has already been completed for this tenant"}}}}},components:{securitySchemes:{BearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}},schemas:Hi}};p();p();var C=require("node:crypto");var Vi="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pc=16;function mc(i){let e=(0,C.randomBytes)(i),t="";for(let n=0;n<i;n++)t+=Vi[e[n]%Vi.length];return t}function qe(i){return`${i}_${mc(pc)}`}function z(){return qe("prof")}function q(){return qe("visi")}function K(){return qe("cons")}function _e(){return qe("ctem")}function we(){return qe("utem")}function gc(i){if(i.includes(":")){let t=i.split(":");for(;t.length<8;)t.push("0");return t.slice(0,3).concat(["0","0","0","0","0"]).join(":")}let e=i.split(".");return e.length===4?(e[3]="0",e.join(".")):i}function Wi(i,e=""){return(0,C.createHash)("sha256").update(e+gc(i)).digest("hex")}function qi(i){return(0,C.createHash)("sha256").update(i).digest("hex")}function ae(i,e){return(0,C.createHmac)("sha256",e).update(i).digest("hex")}function ht(i,e,t){let n=Buffer.from(ae(i,t),"hex"),o=Buffer.from(e,"hex");return n.length!==o.length?!1:(0,C.timingSafeEqual)(n,o)}function Je(i){let e=(0,C.randomBytes)(16).toString("hex"),t=(0,C.scryptSync)(i,e,64).toString("hex");return`${e}:${t}`}function Ji(i,e){let[t,n]=e.split(":");if(!t||!n)return!1;let o=(0,C.scryptSync)(i,t,64).toString("hex");return(0,C.timingSafeEqual)(Buffer.from(n,"hex"),Buffer.from(o,"hex"))}function On(i,e,t=3600){let n=Math.floor(Date.now()/1e3),o=btoa(JSON.stringify({alg:"HS256",typ:"JWT"})).replace(/=/g,""),r=btoa(JSON.stringify({...i,iat:n,exp:n+t})).replace(/=/g,""),s=ae(`${o}.${r}`,e).match(/.{2}/g).map(c=>String.fromCharCode(parseInt(c,16))).join(""),a=btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return`${o}.${r}.${a}`}function yt(i,e){let t=i.split(".");if(t.length!==3)return null;let[n,o,r]=t;if(!n||!o||!r)return null;let s=ae(`${n}.${o}`,e),a=atob(r.replace(/-/g,"+").replace(/_/g,"/")),c=Array.from(a).map(u=>u.charCodeAt(0).toString(16).padStart(2,"0")).join(""),l=Buffer.from(s,"hex"),d=Buffer.from(c,"hex");if(l.length!==d.length||!(0,C.timingSafeEqual)(l,d))return null;try{let u=JSON.parse(atob(o)),m=u.exp;return typeof m=="number"&&Date.now()/1e3>m?null:u}catch{return null}}p();var ce=require("node:fs"),X=require("node:path"),zi=require("node:url"),fc={"node:sqlite":"consenti.db","better-sqlite3":"consenti.db","node-sqlite3-wasm":"consenti.db",sqlite:"consenti.db",json:"consenti-data.json",mongodb:"",mysql:"",postgresql:""},hc=(0,X.dirname)((0,zi.fileURLToPath)(f));function yc(i){let e=i.includes("node_modules"),t=i.startsWith((0,X.resolve)(hc,"..",".."));return e||t}function ue(i,e){let t=(0,X.resolve)(i),n=(0,X.extname)(t);if(n&&(console.warn(`[consenti] storage.path "${i}" looks like a file path (has extension "${n}"). Treating parent directory as storage root. Update your config to pass a directory path.`),t=(0,X.dirname)(t)),yc(t))throw new Error(`[consenti] storage.path "${t}" is inside the package installation directory. Choose a writable directory outside node_modules.`);(0,ce.existsSync)(t)||(0,ce.mkdirSync)(t,{recursive:!0});try{(0,ce.accessSync)(t,ce.constants.W_OK)}catch{throw new Error(`[consenti] storage.path "${t}" is not writable.`)}let o=(0,X.join)(t,"db"),r=(0,X.join)(t,"profiles"),s=(0,X.join)(t,"logs");(0,ce.mkdirSync)(o,{recursive:!0}),(0,ce.mkdirSync)(r,{recursive:!0}),(0,ce.mkdirSync)(s,{recursive:!0});let a=fc[e]??"consenti.db",c=a?(0,X.join)(o,a):"";return{basePath:t,dbPath:c,profilesDir:r,logsDir:s}}p();var Zi={name:"tenants",cols:[{n:"id",t:"pk"},{n:"name",t:"text"},{n:"slug",t:"text",unique:!0},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},Xi={name:"profiles",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"name",t:"text"},{n:"default_locale",t:"text_sm",def:"en"},{n:"version",t:"int",def:1},{n:"profile_json",t:"json_ordered"},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}],idx:[{cols:["tenant_id"]}]},eo={name:"consent_records",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"visitor_id",t:"text"},{n:"profile_id",t:"text",ref:"profiles"},{n:"locale",t:"text_sm"},{n:"consent_json",t:"json"},{n:"gpc_detected",t:"bool",def:!1},{n:"source",t:"text_sm"},{n:"age_verified",t:"bool",def:!1},{n:"parental_consent_token",t:"longtext",null:!0},{n:"tcf_string",t:"longtext",null:!0},{n:"gpp_string",t:"longtext",null:!0},{n:"signature",t:"longtext",null:!0},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}],uq:[{cols:["visitor_id","profile_id"]}],idx:[{cols:["tenant_id","created_at"]},{cols:["tenant_id","profile_id","created_at"]},{cols:["locale"]},{cols:["source"]}]},to={name:"consent_history",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"consent_record_id",t:"text",ref:"consent_records"},{n:"visitor_id",t:"text"},{n:"old_json",t:"json",null:!0},{n:"new_json",t:"json"},{n:"action",t:"text_sm"},{n:"created_at",t:"ts",def:"$now"}],idx:[{cols:["visitor_id"]}]},no={name:"visitors",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"visitor_id",t:"text",unique:!0},{n:"country",t:"text_geo",null:!0},{n:"region",t:"text_md",null:!0},{n:"city",t:"text_md",null:!0},{n:"ip_hash",t:"text_hash",null:!0},{n:"user_agent_hash",t:"text_hash",null:!0},{n:"first_seen",t:"ts",def:"$now"},{n:"last_seen",t:"ts",def:"$now",mysqlUpd:!0}],idx:[{cols:["tenant_id","first_seen"]},{cols:["country"]}]},io={name:"notice_shown",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"visitor_id",t:"text"},{n:"profile_id",t:"text",ref:"profiles"},{n:"locale",t:"text_sm"},{n:"created_at",t:"ts",def:"$now"}],idx:[{cols:["visitor_id"]}]},Dn={name:"users",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"name",t:"text"},{n:"email",t:"text",unique:!0},{n:"password_hash",t:"text"},{n:"is_active",t:"bool",def:!0},{n:"totp_secret",t:"longtext",null:!0},{n:"totp_enabled",t:"bool",def:!1},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},_c={...Dn,cols:[...Dn.cols,{n:"allowed_tenants",t:"json",null:!0}]},oo={name:"roles",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"name",t:"text_md"},{n:"description",t:"text",null:!0}]},ro={name:"permissions",cols:[{n:"id",t:"pk"},{n:"name",t:"text_md",unique:!0},{n:"description",t:"text",null:!0}]},so={name:"user_roles",cols:[{n:"user_id",t:"text",ref:"users"},{n:"role_id",t:"text",ref:"roles"},{n:"tenant_id",t:"text",def:"default"}],pk:["user_id","role_id","tenant_id"],idx:[{cols:["user_id"]}]},ao={name:"role_permissions",cols:[{n:"role_id",t:"text",ref:"roles"},{n:"permission_id",t:"text",ref:"permissions"}],pk:["role_id","permission_id"],idx:[{cols:["role_id"]}]},co={name:"audit_logs",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants"},{n:"user_id",t:"text",null:!0},{n:"action",t:"text_md"},{n:"resource_type",t:"text_md"},{n:"resource_id",t:"text",null:!0},{n:"old_data",t:"json",null:!0},{n:"new_data",t:"json",null:!0},{n:"created_at",t:"ts",def:"$now"}],idx:[{cols:["tenant_id","created_at"]},{cols:["action"]},{cols:["resource_type"]},{cols:["resource_id"]},{cols:["user_id"]}]},lo={name:"api_keys",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants",onDel:"CASCADE"},{n:"key_hash",t:"text_hash",unique:!0},{n:"name",t:"text"},{n:"is_active",t:"bool",def:!0},{n:"created_by",t:"text",null:!0},{n:"expire_by",t:"ts",null:!0},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},uo={name:"tenant_settings",cols:[{n:"tenant_id",t:"text",ref:"tenants",onDel:"CASCADE"},{n:"allowed_origins_json",t:"json",def:"$arr"},{n:"admin_allowed_origins_json",t:"json",def:"$arr"},{n:"setup_completed",t:"bool",def:!1},{n:"profiles_seeded",t:"bool",def:!1},{n:"tcf_confirmation_json",t:"json",null:!0},{n:"gpp_confirmation_json",t:"json",null:!0},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}],pk:["tenant_id"]},po={name:"consent_templates",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants",onDel:"CASCADE"},{n:"name",t:"text"},{n:"cookies_json",t:"json_ordered",def:"$obj"},{n:"categories_json",t:"json_ordered",def:"$obj"},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},mo={name:"ui_templates",cols:[{n:"id",t:"pk"},{n:"tenant_id",t:"text",ref:"tenants",onDel:"CASCADE"},{n:"name",t:"text"},{n:"settings_json",t:"json_ordered",def:"$obj"},{n:"created_at",t:"ts",def:"$now"},{n:"updated_at",t:"ts",def:"$now",mysqlUpd:!0}]},wc=[Zi,Xi,eo,to,no,_c,oo,ro,so,ao,co,lo,po,mo,uo,io],kn=[Zi,Xi,eo,to,no,Dn,oo,ro,so,ao,co,lo,po,mo,uo,io];function Ec(i){return i==="$now"?"DEFAULT (datetime('now'))":i==="$arr"?"DEFAULT '[]'":i==="$obj"?"DEFAULT '{}'":i===!0?"DEFAULT 1":i===!1?"DEFAULT 0":typeof i=="string"?`DEFAULT '${i}'`:`DEFAULT ${i}`}function Rc(i){if(i.t==="pk")return`${i.n} TEXT PRIMARY KEY`;let e=i.t==="int"||i.t==="bool"?"INTEGER":"TEXT",t=[`${i.n} ${e}`];return i.null||t.push("NOT NULL"),i.def!==void 0&&t.push(Ec(i.def)),i.unique&&t.push("UNIQUE"),i.ref&&(t.push(`REFERENCES ${i.ref}(id)`),i.onDel&&t.push(`ON DELETE ${i.onDel}`)),t.join(" ")}function Ki(i){let e=i.cols.map(t=>` ${Rc(t)}`);if(i.pk&&e.push(` PRIMARY KEY (${i.pk.join(", ")})`),i.uq)for(let t of i.uq)e.push(` UNIQUE(${t.cols.join(", ")})`);return`CREATE TABLE IF NOT EXISTS ${i.name} (
2
2
  ${e.join(`,
3
3
  `)}
4
- );`}function Ys(s){return s==="$now"?"DEFAULT NOW()":s==="$arr"?"DEFAULT '[]'":s==="$obj"?"DEFAULT '{}'":s===!0?"DEFAULT TRUE":s===!1?"DEFAULT FALSE":typeof s=="string"?`DEFAULT '${s}'`:`DEFAULT ${s}`}function zs(s){if(s.t==="pk")return`${s.n} TEXT PRIMARY KEY`;let e=s.t==="json"?"JSONB":s.t==="int"?"INTEGER":s.t==="bool"?"BOOLEAN":s.t==="ts"?"TIMESTAMPTZ":"TEXT",t=[`${s.n} ${e}`];return s.null||t.push("NOT NULL"),s.def!==void 0&&t.push(Ys(s.def)),s.unique&&t.push("UNIQUE"),s.ref&&(t.push(`REFERENCES ${s.ref}(id)`),s.onDel&&t.push(`ON DELETE ${s.onDel}`)),t.join(" ")}function Qs(s){let e=s.cols.map(t=>` ${zs(t)}`);if(s.pk&&e.push(` PRIMARY KEY (${s.pk.join(", ")})`),s.uq)for(let t of s.uq)e.push(` UNIQUE (${t.cols.join(", ")})`);return`CREATE TABLE IF NOT EXISTS ${s.name} (
4
+ );`}function Ln(i,e){return`idx_${i.name}_${e.join("_")}`}function Sc(i){return(i.idx??[]).map(e=>`CREATE INDEX IF NOT EXISTS ${Ln(i,e.cols)} ON ${i.name} (${e.cols.join(", ")});`).join(`
5
+ `)}function vc(i){return i==="$now"?"DEFAULT NOW()":i==="$arr"?"DEFAULT '[]'":i==="$obj"?"DEFAULT '{}'":i===!0?"DEFAULT TRUE":i===!1?"DEFAULT FALSE":typeof i=="string"?`DEFAULT '${i}'`:`DEFAULT ${i}`}function Cc(i){if(i.t==="pk")return`${i.n} TEXT PRIMARY KEY`;let e=i.t==="json"?"JSONB":i.t==="json_ordered"?"JSON":i.t==="int"?"INTEGER":i.t==="bool"?"BOOLEAN":i.t==="ts"?"TIMESTAMPTZ":"TEXT",t=[`${i.n} ${e}`];return i.null||t.push("NOT NULL"),i.def!==void 0&&t.push(vc(i.def)),i.unique&&t.push("UNIQUE"),i.ref&&(t.push(`REFERENCES ${i.ref}(id)`),i.onDel&&t.push(`ON DELETE ${i.onDel}`)),t.join(" ")}function Yi(i){let e=i.cols.map(t=>` ${Cc(t)}`);if(i.pk&&e.push(` PRIMARY KEY (${i.pk.join(", ")})`),i.uq)for(let t of i.uq)e.push(` UNIQUE (${t.cols.join(", ")})`);return`CREATE TABLE IF NOT EXISTS ${i.name} (
5
6
  ${e.join(`,
6
7
  `)}
7
- );`}var Xs={text:"VARCHAR(255)",text_sm:"VARCHAR(20)",text_md:"VARCHAR(100)",text_geo:"VARCHAR(10)",text_hash:"VARCHAR(64)",longtext:"LONGTEXT",json:"LONGTEXT"};function Zs(s){return s==="$now"?"DEFAULT CURRENT_TIMESTAMP":s==="$arr"?"DEFAULT '[]'":s==="$obj"?"DEFAULT '{}'":s===!0?"DEFAULT 1":s===!1?"DEFAULT 0":typeof s=="string"?`DEFAULT '${s}'`:`DEFAULT ${s}`}function eo(s){if(s.t==="pk")return`${s.n} VARCHAR(36) PRIMARY KEY`;let e=s.t==="int"?"INT":s.t==="bool"?"TINYINT(1)":s.t==="ts"?"DATETIME":Xs[s.t]??"TEXT",t=[`${s.n} ${e}`];return s.null||t.push("NOT NULL"),s.def!==void 0&&t.push(Zs(s.def)),s.mysqlUpd&&t.push("ON UPDATE CURRENT_TIMESTAMP"),s.unique&&t.push("UNIQUE"),s.ref&&(t.push(`REFERENCES ${s.ref}(id)`),s.onDel&&t.push(`ON DELETE ${s.onDel}`)),t.join(" ")}function to(s){let e=s.cols.map(t=>` ${eo(t)}`);if(s.pk&&e.push(` PRIMARY KEY (${s.pk.join(", ")})`),s.uq)for(let t of s.uq)e.push(` UNIQUE KEY uq_${t.cols.join("_")} (${t.cols.join(", ")})`);return`CREATE TABLE IF NOT EXISTS ${s.name} (
8
+ );`}function Ac(i){return(i.idx??[]).map(e=>`CREATE INDEX IF NOT EXISTS ${Ln(i,e.cols)} ON ${i.name} (${e.cols.join(", ")});`).join(`
9
+ `)}var Pc={text:"VARCHAR(255)",text_sm:"VARCHAR(20)",text_md:"VARCHAR(100)",text_geo:"VARCHAR(10)",text_hash:"VARCHAR(64)",longtext:"LONGTEXT",json:"LONGTEXT",json_ordered:"LONGTEXT"};function Tc(i){return i==="$now"?"DEFAULT CURRENT_TIMESTAMP":i==="$arr"?"DEFAULT '[]'":i==="$obj"?"DEFAULT '{}'":i===!0?"DEFAULT 1":i===!1?"DEFAULT 0":typeof i=="string"?`DEFAULT '${i}'`:`DEFAULT ${i}`}function Ic(i){if(i.t==="pk")return`${i.n} VARCHAR(64) PRIMARY KEY`;let e=i.t==="int"?"INT":i.t==="bool"?"TINYINT(1)":i.t==="ts"?"DATETIME":Pc[i.t]??"TEXT",t=[`${i.n} ${e}`];return i.null||t.push("NOT NULL"),i.def!==void 0&&t.push(Tc(i.def)),i.mysqlUpd&&t.push("ON UPDATE CURRENT_TIMESTAMP"),i.unique&&t.push("UNIQUE"),i.ref&&(t.push(`REFERENCES ${i.ref}(id)`),i.onDel&&t.push(`ON DELETE ${i.onDel}`)),t.join(" ")}function Qi(i){let e=i.cols.map(t=>` ${Ic(t)}`);if(i.pk&&e.push(` PRIMARY KEY (${i.pk.join(", ")})`),i.uq)for(let t of i.uq)e.push(` UNIQUE KEY uq_${t.cols.join("_")} (${t.cols.join(", ")})`);return`CREATE TABLE IF NOT EXISTS ${i.name} (
8
10
  ${e.join(`,
9
11
  `)}
10
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`}function Ut(s){return s.map(Ks).join(`
11
- `)}function no(s){return s.map(Qs).join(`
12
- `)}function io(s){return s.map(to).join(`
13
- `)}var ue=Ut(Vs),pe=Ut(vn),me=`
14
- ALTER TABLE consent_records ADD COLUMN age_verified INTEGER NOT NULL DEFAULT 0;
15
- ALTER TABLE consent_records ADD COLUMN parental_consent_token TEXT;
16
- ALTER TABLE consent_records ADD COLUMN tcf_string TEXT;
17
- ALTER TABLE users ADD COLUMN totp_secret TEXT;
18
- ALTER TABLE users ADD COLUMN totp_enabled INTEGER NOT NULL DEFAULT 0;
19
- `,ge=Ut(In),Pn=[...Ws,...vn,...In],bn=no(Pn)+`
12
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`}function bc(i){return(i.idx??[]).map(e=>`CREATE INDEX ${Ln(i,e.cols)} ON ${i.name} (${e.cols.join(", ")});`).join(`
13
+ `)}function Oc(i){let e=i.map(Sc).filter(Boolean).join(`
14
+ `);return e?`${i.map(Ki).join(`
15
+ `)}
16
+ ${e}`:i.map(Ki).join(`
17
+ `)}function Dc(i){let e=i.map(Ac).filter(Boolean).join(`
18
+ `);return e?`${i.map(Yi).join(`
19
+ `)}
20
+ ${e}`:i.map(Yi).join(`
21
+ `)}function kc(i){let e=i.map(bc).filter(Boolean).join(`
22
+ `);return e?`${i.map(Qi).join(`
23
+ `)}
24
+ ${e}`:i.map(Qi).join(`
25
+ `)}function Lc(i){let e=[];for(let t of i){for(let n of t.uq??[])e.push({table:t.name,cols:n.cols,unique:!0});for(let n of t.cols)n.unique&&e.push({table:t.name,cols:[n.n],unique:!0});for(let n of t.idx??[])e.push({table:t.name,cols:n.cols})}return e}var go=Lc(kn),Oe=Oc(wc),fo=Dc(kn)+`
20
26
  CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
21
- `,On=io(Pn)+`
27
+ `,ho=kc(kn)+`
22
28
  CREATE TABLE IF NOT EXISTS schema_version (
23
29
  version INT NOT NULL PRIMARY KEY
24
30
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
25
- `,$={id:"default",name:"Default",slug:"default"},j=[{id:"perm_profile_create",name:"profile:create",description:"Create profiles"},{id:"perm_profile_update",name:"profile:update",description:"Update profiles"},{id:"perm_profile_delete",name:"profile:delete",description:"Delete profiles"},{id:"perm_profile_view",name:"profile:view",description:"View profiles"},{id:"perm_consent_view",name:"consent:view",description:"View consent records"},{id:"perm_visitor_view",name:"visitor:view",description:"View visitor records"},{id:"perm_user_create",name:"user:create",description:"Create users"},{id:"perm_user_update",name:"user:update",description:"Update users"},{id:"perm_user_delete",name:"user:delete",description:"Delete users"},{id:"perm_user_view",name:"user:view",description:"View users"},{id:"perm_role_create",name:"role:create",description:"Create roles"},{id:"perm_role_update",name:"role:update",description:"Update roles"},{id:"perm_role_delete",name:"role:delete",description:"Delete roles"},{id:"perm_role_view",name:"role:view",description:"View roles"},{id:"perm_audit_view",name:"audit:view",description:"View audit logs"},{id:"perm_settings_update",name:"settings:update",description:"Update settings"},{id:"perm_export_run",name:"export:run",description:"Run data exports"}],Z=[{id:"role_super_admin",tenantId:"default",name:"super_admin",description:"Full system access"},{id:"role_admin",tenantId:"default",name:"admin",description:"Administrative access"},{id:"role_compliance_officer",tenantId:"default",name:"compliance_officer",description:"Compliance read access"},{id:"role_viewer",tenantId:"default",name:"viewer",description:"Read-only access"}],so=new Set(["role:delete","user:delete"]),oo=new Set(["consent:view","visitor:view","audit:view","profile:view","export:run"]),ro=new Set(["consent:view","visitor:view","profile:view"]),ee=[...j.map(s=>({roleId:"role_super_admin",permissionId:s.id})),...j.filter(s=>!so.has(s.name)).map(s=>({roleId:"role_admin",permissionId:s.id})),...j.filter(s=>oo.has(s.name)).map(s=>({roleId:"role_compliance_officer",permissionId:s.id})),...j.filter(s=>ro.has(s.name)).map(s=>({roleId:"role_viewer",permissionId:s.id}))];function V(s){return`'${s.replace(/'/g,"''")}'`}function ao(){let{id:s,name:e,slug:t}=$,n=`INSERT OR IGNORE INTO tenants (id, name, slug) VALUES (${V(s)},${V(e)},${V(t)});`,i=`INSERT OR IGNORE INTO permissions (id, name, description) VALUES
26
- ${j.map(c=>` (${V(c.id)},${V(c.name)},${V(c.description)})`).join(`,
27
- `)};`,o=`INSERT OR IGNORE INTO roles (id, tenant_id, name, description) VALUES
28
- ${Z.map(c=>` (${V(c.id)},${V(c.tenantId)},${V(c.name)},${V(c.description)})`).join(`,
29
- `)};`,r=new Map;for(let c of ee)r.has(c.roleId)||r.set(c.roleId,[]),r.get(c.roleId).push(c.permissionId);let a=[...r.entries()].map(([c,l])=>`INSERT OR IGNORE INTO role_permissions (role_id, permission_id) VALUES
30
- ${l.map(u=>` (${V(c)},${V(u)})`).join(`,
31
+ `,te={id:"default",name:"Default",slug:"default"},ee=[{id:"perm_profile_create",name:"profile:create",description:"Create profiles"},{id:"perm_profile_update",name:"profile:update",description:"Update profiles"},{id:"perm_profile_delete",name:"profile:delete",description:"Delete profiles"},{id:"perm_profile_view",name:"profile:view",description:"View profiles"},{id:"perm_consent_view",name:"consent:view",description:"View consent records"},{id:"perm_visitor_view",name:"visitor:view",description:"View visitor records"},{id:"perm_user_create",name:"user:create",description:"Create users"},{id:"perm_user_update",name:"user:update",description:"Update users"},{id:"perm_user_delete",name:"user:delete",description:"Delete users"},{id:"perm_user_view",name:"user:view",description:"View users"},{id:"perm_role_create",name:"role:create",description:"Create roles"},{id:"perm_role_update",name:"role:update",description:"Update roles"},{id:"perm_role_delete",name:"role:delete",description:"Delete roles"},{id:"perm_role_view",name:"role:view",description:"View roles"},{id:"perm_audit_view",name:"audit:view",description:"View audit logs"},{id:"perm_settings_update",name:"settings:update",description:"Update settings"},{id:"perm_export_run",name:"export:run",description:"Run data exports"},{id:"perm_stats_view",name:"stats:view",description:"View reporting and analytics"}],pe=[{id:"role_super_admin",tenantId:"default",name:"super_admin",description:"Full system access"},{id:"role_admin",tenantId:"default",name:"admin",description:"Administrative access"},{id:"role_compliance_officer",tenantId:"default",name:"compliance_officer",description:"Compliance read access"},{id:"role_viewer",tenantId:"default",name:"viewer",description:"Read-only access"}],Nc=new Set(["role:delete","user:delete"]),xc=new Set(["consent:view","visitor:view","audit:view","profile:view","export:run","stats:view"]),Mc=new Set(["consent:view","visitor:view","profile:view","stats:view"]),me=[...ee.map(i=>({roleId:"role_super_admin",permissionId:i.id})),...ee.filter(i=>!Nc.has(i.name)).map(i=>({roleId:"role_admin",permissionId:i.id})),...ee.filter(i=>xc.has(i.name)).map(i=>({roleId:"role_compliance_officer",permissionId:i.id})),...ee.filter(i=>Mc.has(i.name)).map(i=>({roleId:"role_viewer",permissionId:i.id}))];function ie(i){return`'${i.replace(/'/g,"''")}'`}function Uc(){let{id:i,name:e,slug:t}=te,n=`INSERT OR IGNORE INTO tenants (id, name, slug) VALUES (${ie(i)},${ie(e)},${ie(t)});`,o=`INSERT OR IGNORE INTO permissions (id, name, description) VALUES
32
+ ${ee.map(c=>` (${ie(c.id)},${ie(c.name)},${ie(c.description)})`).join(`,
33
+ `)};`,r=`INSERT OR IGNORE INTO roles (id, tenant_id, name, description) VALUES
34
+ ${pe.map(c=>` (${ie(c.id)},${ie(c.tenantId)},${ie(c.name)},${ie(c.description)})`).join(`,
35
+ `)};`,s=new Map;for(let c of me)s.has(c.roleId)||s.set(c.roleId,[]),s.get(c.roleId).push(c.permissionId);let a=[...s.entries()].map(([c,l])=>`INSERT OR IGNORE INTO role_permissions (role_id, permission_id) VALUES
36
+ ${l.map(d=>` (${ie(c)},${ie(d)})`).join(`,
31
37
  `)};`).join(`
32
- `);return[n,i,o,a].join(`
33
- `)}var fe=ao();var kt=500,ce=class{constructor(e){this.config=e}config;db;cache=new Map;stmt(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}async connect(){let e=await import("better-sqlite3").catch(()=>{throw new Error("driver 'better-sqlite3' requires: npm install better-sqlite3")}),{dbPath:t}=Q(this.config.path??"./consenti-data","better-sqlite3");this.db=new e.default(t),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA foreign_keys=ON"),this.db.exec("PRAGMA synchronous=NORMAL"),await this.migrate()}async disconnect(){this.cache.clear(),this.db.close()}async migrate(){let e=this.db.prepare("PRAGMA user_version").get();e.user_version<1&&(this.db.exec(ue),this.db.exec(fe),this.db.exec("PRAGMA user_version = 1")),e.user_version<2&&(this.db.exec(pe),this.db.exec("PRAGMA user_version = 2")),e.user_version<3&&(this.db.exec(me),this.db.exec("PRAGMA user_version = 3")),e.user_version<4&&(this.db.exec("ALTER TABLE user_roles ADD COLUMN tenant_id TEXT NOT NULL DEFAULT 'default'"),this.db.exec("PRAGMA user_version = 4")),e.user_version<5&&(this.db.exec(ge),this.db.exec("PRAGMA user_version = 5")),e.user_version<6&&(this.db.exec("ALTER TABLE users ADD COLUMN allowed_tenants TEXT"),this.db.exec("PRAGMA user_version = 6")),this.db.exec(`
38
+ `);return[n,o,r,a].join(`
39
+ `)}var De=Uc();p();function j(i){return`${i.replace(/[\\%_]/g,e=>`\\${e}`)}%`}var Nn=500,Te=class i{constructor(e){this.config=e}config;db;cache=new Map;stmt(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}async connect(){let e=await import("better-sqlite3").catch(()=>{throw new Error("driver 'better-sqlite3' requires: npm install better-sqlite3")}),{dbPath:t}=ue(this.config.path??"./consenti-data","better-sqlite3");this.db=new e.default(t),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA foreign_keys=ON"),this.db.exec("PRAGMA synchronous=NORMAL"),await this.migrate()}async disconnect(){this.cache.clear(),this.db.close()}async migrate(){this.db.prepare("PRAGMA user_version").get().user_version<1&&(this.db.exec(Oe),this.db.exec(De),this.db.exec("PRAGMA user_version = 1")),this.db.exec(`
34
40
  CREATE INDEX IF NOT EXISTS idx_profiles_tenant_compliance_active
35
41
  ON profiles (tenant_id, json_extract(profile_json,'$.complianceGroup'), json_extract(profile_json,'$.isActive'));
36
- CREATE INDEX IF NOT EXISTS idx_profiles_tenant
37
- ON profiles (tenant_id);
38
- CREATE INDEX IF NOT EXISTS idx_consents_tenant_profile_date
39
- ON consent_records (tenant_id, profile_id, created_at);
40
- CREATE INDEX IF NOT EXISTS idx_consents_visitor
41
- ON consent_records (visitor_id);
42
- CREATE INDEX IF NOT EXISTS idx_visitors_tenant
43
- ON visitors (tenant_id);
44
- CREATE INDEX IF NOT EXISTS idx_audit_tenant_date
45
- ON audit_logs (tenant_id, created_at);
46
- `)}mapProfile(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,defaultLocale:e.default_locale,version:e.version,profileJson:JSON.parse(e.profile_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createProfile(e){let t=de(),n=new Date().toISOString();this.stmt("INSERT INTO profiles (id,tenant_id,name,default_locale,profile_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.defaultLocale,JSON.stringify(e.profileJson),n,n);let i=await this.getProfile(t);if(!i)throw new Error("Failed to create profile");return i}async updateProfile(e,t){if(!await this.getProfile(e))throw new Error(`Profile ${e} not found`);let i=new Date().toISOString(),o=["updated_at = ?","version = version + 1"],r=[i];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.defaultLocale!=null&&(o.push("default_locale = ?"),r.push(t.defaultLocale)),t.profileJson!=null&&(o.push("profile_json = ?"),r.push(JSON.stringify(t.profileJson))),r.push(e),this.stmt(`UPDATE profiles SET ${o.join(", ")} WHERE id = ?`).run(...r);let a=await this.getProfile(e);if(!a)throw new Error("Failed to update profile");return a}async deleteProfile(e){this.stmt("DELETE FROM profiles WHERE id = ?").run(e)}async getProfile(e){let t=this.stmt("SELECT * FROM profiles WHERE id = ?").get(e);return t?this.mapProfile(t):null}async getProfiles(e){return this.stmt("SELECT * FROM profiles WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapProfile(n))}async findActiveProfileByComplianceGroup(e,t){let n=this.stmt("SELECT * FROM profiles WHERE tenant_id = ? AND json_extract(profile_json, '$.complianceGroup') = ? AND json_extract(profile_json, '$.isActive') = 1 LIMIT 1").get(e,t);return n?this.mapProfile(n):null}mapConsent(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,profileVersion:e.profile_version,locale:e.locale,consentJson:JSON.parse(e.consent_json),gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},...e.parental_consent_token!=null?{parentalConsentToken:e.parental_consent_token}:{},...e.tcf_string!=null?{tcfString:e.tcf_string}:{},createdAt:e.created_at,updatedAt:e.updated_at}}async createConsent(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO consent_records (id,tenant_id,visitor_id,profile_id,profile_version,locale,consent_json,gpc_detected,source,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.profileId,e.profileVersion,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source,n,n);let i=(0,w.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(i,e.tenantId,t,e.visitorId,null,JSON.stringify(e.consentJson),"created",n);let o=await this.getConsent(e.visitorId);if(!o)throw new Error("Failed to create consent");return o}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let i=new Date().toISOString(),o=["updated_at = ?","consent_json = ?"],r=[i,JSON.stringify(t.consentJson)];t.locale!=null&&(o.push("locale = ?"),r.push(t.locale)),t.gpcDetected!=null&&(o.push("gpc_detected = ?"),r.push(t.gpcDetected?1:0)),r.push(e),this.stmt(`UPDATE consent_records SET ${o.join(", ")} WHERE visitor_id = ?`).run(...r);let a=(0,w.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(a,n.tenantId,n.id,e,JSON.stringify(n.consentJson),JSON.stringify(t.consentJson),"updated",i);let c=await this.getConsent(e);if(!c)throw new Error("Failed to update consent");return c}async deleteConsent(e){this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(e),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(e)}async getConsent(e){let t=this.stmt("SELECT * FROM consent_records WHERE visitor_id = ?").get(e);return t?this.mapConsent(t):null}async getConsents(e){let t=["tenant_id = ?"],n=[e.tenantId];e.profileId&&(t.push("profile_id = ?"),n.push(e.profileId)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=Math.min(e.limit??50,kt),o=((e.page??1)-1)*i;return n.push(i,o),this.stmt(`SELECT * FROM consent_records WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n).map(a=>this.mapConsent(a))}async*streamConsents(e){let n=0;for(;;){let i=this.stmt("SELECT * FROM consent_records WHERE tenant_id = ? LIMIT ? OFFSET ?").all(e.tenantId,500,n);if(i.length===0)break;for(let o of i)yield this.mapConsent(o);n+=500}}async getConsentHistory(e){return this.stmt("SELECT * FROM consent_history WHERE visitor_id = ? ORDER BY created_at ASC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,consentRecordId:n.consent_record_id,visitorId:n.visitor_id,oldJson:n.old_json!=null?JSON.parse(n.old_json):null,newJson:JSON.parse(n.new_json),action:n.action,createdAt:n.created_at}))}mapVisitor(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,firstSeen:e.first_seen,lastSeen:e.last_seen,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip_hash!=null?{ipHash:e.ip_hash}:{},...e.user_agent_hash!=null?{userAgentHash:e.user_agent_hash}:{}}}async createVisitor(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO visitors (id,tenant_id,visitor_id,country,region,city,ip_hash,user_agent_hash,first_seen,last_seen) VALUES (?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null,n,n);let i=await this.getVisitor(e.visitorId);if(!i)throw new Error("Failed to create visitor");return i}async updateVisitor(e,t){let n=new Date().toISOString(),i=["last_seen = ?"],o=[t.lastSeen??n];t.country!=null&&(i.push("country = ?"),o.push(t.country)),t.region!=null&&(i.push("region = ?"),o.push(t.region)),t.city!=null&&(i.push("city = ?"),o.push(t.city)),o.push(e),this.stmt(`UPDATE visitors SET ${i.join(", ")} WHERE visitor_id = ?`).run(...o);let r=await this.getVisitor(e);if(!r)throw new Error(`Visitor ${e} not found`);return r}async deleteVisitor(e){this.stmt("DELETE FROM visitors WHERE visitor_id = ?").run(e)}async getVisitor(e){let t=this.stmt("SELECT * FROM visitors WHERE visitor_id = ?").get(e);return t?this.mapVisitor(t):null}async getVisitors(e){let t=["tenant_id = ?"],n=[e.tenantId];e.from&&(t.push("first_seen >= ?"),n.push(e.from)),e.to&&(t.push("first_seen <= ?"),n.push(e.to));let i=Math.min(e.limit??50,kt),o=((e.page??1)-1)*i;return n.push(i,o),this.stmt(`SELECT * FROM visitors WHERE ${t.join(" AND ")} ORDER BY last_seen DESC LIMIT ? OFFSET ?`).all(...n).map(a=>this.mapVisitor(a))}mapUser(e){let t=e.allowed_tenants?JSON.parse(e.allowed_tenants):[];return{id:e.id,tenantId:e.tenant_id,name:e.name,email:e.email,passwordHash:e.password_hash,isActive:e.is_active===1,totpEnabled:e.totp_enabled===1,...e.totp_secret!=null?{totpSecret:e.totp_secret}:{},allowedTenants:t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUser(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),i=e.allowedTenants?.length?JSON.stringify(e.allowedTenants):null;this.stmt("INSERT INTO users (id,tenant_id,name,email,password_hash,allowed_tenants,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.email,e.passwordHash,i,n,n);let o=await this.getUserByEmail(e.email);if(!o)throw new Error("Failed to create user");return o}async updateUser(e,t){let n=new Date().toISOString(),i=["updated_at = ?"],o=[n];t.name!=null&&(i.push("name = ?"),o.push(t.name)),t.email!=null&&(i.push("email = ?"),o.push(t.email)),t.passwordHash!=null&&(i.push("password_hash = ?"),o.push(t.passwordHash)),t.isActive!=null&&(i.push("is_active = ?"),o.push(t.isActive?1:0)),"totpSecret"in t&&(i.push("totp_secret = ?"),o.push(t.totpSecret??null)),t.totpEnabled!=null&&(i.push("totp_enabled = ?"),o.push(t.totpEnabled?1:0)),"allowedTenants"in t&&(i.push("allowed_tenants = ?"),o.push(t.allowedTenants?.length?JSON.stringify(t.allowedTenants):null)),o.push(e),this.stmt(`UPDATE users SET ${i.join(", ")} WHERE id = ?`).run(...o);let r=this.stmt("SELECT * FROM users WHERE id = ?").get(e);if(!r)throw new Error(`User ${e} not found`);return this.mapUser(r)}async deleteUser(e){this.stmt("DELETE FROM user_roles WHERE user_id = ?").run(e),this.stmt("DELETE FROM users WHERE id = ?").run(e)}async getUserById(e){let t=this.stmt("SELECT * FROM users WHERE id = ?").get(e);return t?this.mapUser(t):null}async getUserByEmail(e){let t=this.stmt("SELECT * FROM users WHERE email = ?").get(e);return t?this.mapUser(t):null}async getUsers(e){return this.stmt("SELECT * FROM users WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapUser(n))}async countUsers(e){return(e?this.stmt("SELECT COUNT(*) as n FROM users WHERE tenant_id = ?").get(e):this.stmt("SELECT COUNT(*) as n FROM users").get())?.n??0}async getRoles(e){return this.stmt("SELECT * FROM roles WHERE tenant_id = ?").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async createRole(e){let t=(0,w.randomUUID)();this.stmt("INSERT INTO roles (id,tenant_id,name,description) VALUES (?,?,?,?)").run(t,e.tenantId,e.name,e.description??null);let n=this.stmt("SELECT * FROM roles WHERE id = ?").get(t);if(!n)throw new Error("Failed to create role");return{id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}}async updateRole(e,t){let n=[],i=[];t.name!=null&&(n.push("name = ?"),i.push(t.name)),t.description!=null&&(n.push("description = ?"),i.push(t.description)),n.length>0&&(i.push(e),this.stmt(`UPDATE roles SET ${n.join(", ")} WHERE id = ?`).run(...i));let o=this.stmt("SELECT * FROM roles WHERE id = ?").get(e);if(!o)throw new Error(`Role ${e} not found`);return{id:o.id,tenantId:o.tenant_id,name:o.name,...o.description!=null?{description:o.description}:{}}}async deleteRole(e){this.stmt("DELETE FROM role_permissions WHERE role_id = ?").run(e),this.stmt("DELETE FROM user_roles WHERE role_id = ?").run(e),this.stmt("DELETE FROM roles WHERE id = ?").run(e)}async getAllPermissions(){return this.stmt("SELECT * FROM permissions ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,...t.description!=null?{description:t.description}:{}}))}async assignPermissionToRole(e,t){this.stmt("INSERT OR IGNORE INTO role_permissions (role_id,permission_id) VALUES (?,?)").run(e,t)}async revokePermissionFromRole(e,t){this.stmt("DELETE FROM role_permissions WHERE role_id = ? AND permission_id = ?").run(e,t)}async getPermissionsForRole(e){return this.stmt("SELECT p.* FROM permissions p JOIN role_permissions rp ON rp.permission_id = p.id WHERE rp.role_id = ?").all(e).map(n=>({id:n.id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async getUserRoles(e,t){return(t?this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.tenant_id = ?").all(e,t):this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?").all(e)).map(i=>({id:i.id,tenantId:i.tenant_id,name:i.name,...i.description!=null?{description:i.description}:{}}))}async assignRole(e,t,n="default"){this.stmt("INSERT OR IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)").run(e,t,n)}async revokeRole(e,t,n){n?this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ? AND tenant_id = ?").run(e,t,n):this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?").run(e,t)}async createLog(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO audit_logs (id,tenant_id,user_id,action,resource_type,resource_id,old_data,new_data,created_at) VALUES (?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null,n)}async getLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.resourceType&&(t.push("resource_type = ?"),n.push(e.resourceType)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=Math.min(e.limit??50,kt),o=((e.page??1)-1)*i;return n.push(i,o),this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n).map(a=>this.mapAuditLog(a))}mapAuditLog(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,createdAt:e.created_at,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},...e.old_data!=null?{oldData:JSON.parse(e.old_data)}:{},...e.new_data!=null?{newData:JSON.parse(e.new_data)}:{}}}async*streamAuditLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=500,o=0;for(;;){let r=this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,i,o);if(r.length===0)break;for(let a of r)yield this.mapAuditLog(a);o+=i}}async getOverviewStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),i=this.stmt("SELECT COUNT(*) as n FROM visitors WHERE tenant_id = ?").get(e),o=t?.n??0,r=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 500").all(e),a=0,c=0;for(let u of r){let d=Object.values(JSON.parse(u.consent_json)),p=d.length>0?d.filter(E=>E==="granted").length/d.length:0;p>=.8?a++:p<=.2&&c++}let l=r.length||1;return{totalConsents:o,gpcDetectedCount:n?.n??0,totalVisitors:i?.n??0,acceptedPct:Math.round(a/l*100),rejectedPct:Math.round(c/l*100)}}async getCategoryStats(e){let t=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? LIMIT 5000").all(e),n={};for(let i of t){let o=JSON.parse(i.consent_json);for(let[r,a]of Object.entries(o))n[r]||(n[r]={granted:0,denied:0,objected:0}),a==="granted"?n[r].granted++:a==="denied"?n[r].denied++:a==="objected"&&n[r].objected++}return n}async getTimeline(e,t=30){return this.stmt("SELECT date(created_at) as date, COUNT(*) as count FROM consent_records WHERE tenant_id = ? AND created_at >= date('now', ?) GROUP BY date(created_at) ORDER BY date ASC").all(e,`-${t} days`).map(i=>({date:i.date,count:i.count}))}async getCountries(e){return this.stmt("SELECT v.country, COUNT(*) as count FROM consent_records cr JOIN visitors v ON v.visitor_id = cr.visitor_id WHERE cr.tenant_id = ? AND v.country IS NOT NULL GROUP BY v.country ORDER BY count DESC LIMIT 50").all(e).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),i=t?.n??0,o=n?.n??0;return{detected:o,total:i,rate:i>0?Math.round(o/i*100):0}}async getTenants(){return this.stmt("SELECT * FROM tenants ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createTenant(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO tenants (id,name,slug,created_at,updated_at) VALUES (?,?,?,?,?)").run(t,e.name,e.slug,n,n);let i=this.stmt("SELECT * FROM tenants WHERE id = ?").get(t);if(!i)throw new Error("Failed to create tenant");return{id:i.id,name:i.name,slug:i.slug,createdAt:i.created_at,updatedAt:i.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),i=["updated_at = ?"],o=[n];t.name!=null&&(i.push("name = ?"),o.push(t.name)),t.slug!=null&&(i.push("slug = ?"),o.push(t.slug)),o.push(e),this.stmt(`UPDATE tenants SET ${i.join(", ")} WHERE id = ?`).run(...o);let r=this.stmt("SELECT * FROM tenants WHERE id = ?").get(e);if(!r)throw new Error(`Tenant ${e} not found`);return{id:r.id,name:r.name,slug:r.slug,createdAt:r.created_at,updatedAt:r.updated_at}}async deleteTenant(e){this.stmt("DELETE FROM tenants WHERE id = ?").run(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=this.stmt("SELECT visitor_id FROM consent_records WHERE created_at < ?").all(t);for(let{visitor_id:i}of n)this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(i),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(i);return n.length}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active===1,createdAt:e.created_at}}async createApiKey(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO api_keys (id,tenant_id,key_hash,name,created_at) VALUES (?,?,?,?,?)").run(t,e.tenantId,e.keyHash,e.name,n);let i=this.stmt("SELECT * FROM api_keys WHERE id = ?").get(t);if(!i)throw new Error("Failed to create API key");return this.mapApiKey(i)}async getApiKeyByHash(e){let t=this.stmt("SELECT * FROM api_keys WHERE key_hash = ? AND is_active = 1").get(e);return t?this.mapApiKey(t):null}async revokeApiKey(e){this.stmt("UPDATE api_keys SET is_active = 0 WHERE id = ?").run(e)}async getApiKeys(e){return this.stmt("SELECT * FROM api_keys WHERE tenant_id = ? ORDER BY created_at DESC").all(e).map(n=>this.mapApiKey(n))}mapCookieTemplate(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,cookies:JSON.parse(e.cookies_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createCookieTemplate(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();return this.stmt("INSERT INTO cookie_templates (id,tenant_id,name,cookies_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run(t,e.tenantId,e.name,JSON.stringify(e.cookies),n,n),this.mapCookieTemplate(this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(t))}async updateCookieTemplate(e,t){let n=new Date().toISOString();t.name!==void 0&&this.stmt("UPDATE cookie_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e),t.cookies!==void 0&&this.stmt("UPDATE cookie_templates SET cookies_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t.cookies),n,e);let i=this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(e);if(!i)throw new Error("Cookie template not found");return this.mapCookieTemplate(i)}async deleteCookieTemplate(e){this.stmt("DELETE FROM cookie_templates WHERE id = ?").run(e)}async getCookieTemplate(e){let t=this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(e);return t?this.mapCookieTemplate(t):null}async getCookieTemplates(e){return this.stmt("SELECT * FROM cookie_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapCookieTemplate(n))}async copyCookieTemplate(e,t){let n=await this.getCookieTemplate(e);if(!n)throw new Error("Cookie template not found");return this.createCookieTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies})}mapUITemplate(e){let t=JSON.parse(e.settings_json);return{id:e.id,tenantId:e.tenant_id,name:e.name,...t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUITemplate(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),{tenantId:i,name:o,...r}=e;return this.stmt("INSERT INTO ui_templates (id,tenant_id,name,settings_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run(t,i,o,JSON.stringify(r),n,n),this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(t))}async updateUITemplate(e,t){let n=new Date().toISOString(),i=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);if(!i)throw new Error("UI template not found");t.name!==void 0&&this.stmt("UPDATE ui_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e);let{name:o,...r}=t;if(Object.keys(r).length>0){let c={...JSON.parse(i.settings_json),...r};this.stmt("UPDATE ui_templates SET settings_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(c),n,e)}return this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e))}async deleteUITemplate(e){this.stmt("DELETE FROM ui_templates WHERE id = ?").run(e)}async getUITemplate(e){let t=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);return t?this.mapUITemplate(t):null}async getUITemplates(e){return this.stmt("SELECT * FROM ui_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapUITemplate(n))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:i,mainBanner:o,gpcBanner:r,preferenceModal:a}=n;return this.createUITemplate({tenantId:i,name:t,mainBanner:o,gpcBanner:r,preferenceModal:a})}mapProfileSummary(e){return{id:e.id,name:e.name,defaultLocale:e.default_locale,complianceGroup:e.compliance_group??null,version:e.version,isActive:e.is_active===1,cookieTemplateName:e.cookie_template_name,uiTemplateName:e.ui_template_name,createdAt:e.created_at,updatedAt:e.updated_at}}PROFILE_SUMMARY_SQL=`
42
+ `)}mapProfile(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,defaultLocale:e.default_locale,version:e.version,profileJson:JSON.parse(e.profile_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createProfile(e){let t=z(),n=new Date().toISOString();this.stmt("INSERT INTO profiles (id,tenant_id,name,default_locale,version,profile_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.defaultLocale,1,JSON.stringify(e.profileJson),n,n);let o=await this.getProfile(t);if(!o)throw new Error("Failed to create profile");return o}async updateProfile(e,t){if(!await this.getProfile(e))throw new Error(`Profile ${e} not found`);let o=new Date().toISOString(),r=["updated_at = ?"],s=[o];t.name!=null&&(r.push("name = ?"),s.push(t.name)),t.defaultLocale!=null&&(r.push("default_locale = ?"),s.push(t.defaultLocale)),t.profileJson!=null&&(r.push("profile_json = ?"),s.push(JSON.stringify(t.profileJson))),t.version!=null&&(r.push("version = ?"),s.push(t.version)),s.push(e),this.stmt(`UPDATE profiles SET ${r.join(", ")} WHERE id = ?`).run(...s);let a=await this.getProfile(e);if(!a)throw new Error("Failed to update profile");return a}async deleteProfile(e){this.stmt("DELETE FROM profiles WHERE id = ?").run(e)}async getProfile(e){let t=this.stmt("SELECT * FROM profiles WHERE id = ?").get(e);return t?this.mapProfile(t):null}async getProfiles(e){return this.stmt("SELECT * FROM profiles WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapProfile(n))}async findActiveProfileByComplianceGroup(e,t){let n=this.stmt(`SELECT * FROM profiles WHERE tenant_id = ?
43
+ AND (json_extract(profile_json, '$.complianceGroup') = ? OR json_extract(profile_json, '$.customComplianceGroup') = ?)
44
+ AND json_extract(profile_json, '$.isActive') = 1 LIMIT 1`).get(e,t,t);return n?this.mapProfile(n):null}mapConsent(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,locale:e.locale,consentJson:JSON.parse(e.consent_json),gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},...e.parental_consent_token!=null?{parentalConsentToken:e.parental_consent_token}:{},...e.tcf_string!=null?{tcfString:e.tcf_string}:{},...e.gpp_string!=null?{gppString:e.gpp_string}:{},...e.signature!=null?{signature:e.signature}:{},createdAt:e.created_at,updatedAt:e.updated_at}}static CONSENT_SUMMARY_COLS="id, tenant_id, visitor_id, profile_id, locale, gpc_detected, source, age_verified, created_at, updated_at";mapConsentSummary(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,locale:e.locale,gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},createdAt:e.created_at,updatedAt:e.updated_at}}async createConsent(e){let t=K(),n=new Date().toISOString();this.stmt("INSERT INTO consent_records (id,tenant_id,visitor_id,profile_id,locale,consent_json,gpc_detected,source,age_verified,parental_consent_token,tcf_string,gpp_string,signature,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.profileId,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source,e.ageVerified?1:0,e.parentalConsentToken??null,e.tcfString??null,e.gppString??null,e.signature??null,n,n);let o=(0,C.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(o,e.tenantId,t,e.visitorId,null,JSON.stringify(e.consentJson),"created",n);let r=await this.getConsent(e.visitorId);if(!r)throw new Error("Failed to create consent");return r}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let o=new Date().toISOString(),r=["updated_at = ?","consent_json = ?"],s=[o,JSON.stringify(t.consentJson)];t.locale!=null&&(r.push("locale = ?"),s.push(t.locale)),t.gpcDetected!=null&&(r.push("gpc_detected = ?"),s.push(t.gpcDetected?1:0)),t.signature!=null&&(r.push("signature = ?"),s.push(t.signature)),s.push(e),this.stmt(`UPDATE consent_records SET ${r.join(", ")} WHERE visitor_id = ?`).run(...s);let a=(0,C.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(a,n.tenantId,n.id,e,JSON.stringify(n.consentJson),JSON.stringify(t.consentJson),"updated",o);let c=await this.getConsent(e);if(!c)throw new Error("Failed to update consent");return c}async deleteConsent(e){this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(e),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(e)}async getConsent(e){let t=this.stmt("SELECT * FROM consent_records WHERE visitor_id = ?").get(e);return t?this.mapConsent(t):null}async getConsents(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.profileId&&(t.push("profile_id = ?"),n.push(e.profileId)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to)),e.q){t.push("(visitor_id LIKE ? OR profile_id LIKE ? OR locale LIKE ? OR source LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d,d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,Nn),a=(r-1)*s,c=this.stmt(`SELECT ${i.CONSENT_SUMMARY_COLS} FROM consent_records WHERE ${o} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,s,a),l=this.stmt(`SELECT COUNT(*) AS total FROM consent_records WHERE ${o}`).get(...n);return{items:c.map(d=>this.mapConsentSummary(d)),total:l.total,page:r,limit:s}}async*streamConsents(e){let n=0;for(;;){let o=this.stmt("SELECT * FROM consent_records WHERE tenant_id = ? LIMIT ? OFFSET ?").all(e.tenantId,500,n);if(o.length===0)break;for(let r of o)yield this.mapConsent(r);n+=500}}async getConsentHistory(e){return this.stmt("SELECT * FROM consent_history WHERE visitor_id = ? ORDER BY created_at ASC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,consentRecordId:n.consent_record_id,visitorId:n.visitor_id,oldJson:n.old_json!=null?JSON.parse(n.old_json):null,newJson:JSON.parse(n.new_json),action:n.action,createdAt:n.created_at}))}async createNoticeShown(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();return this.stmt("INSERT INTO notice_shown (id,tenant_id,visitor_id,profile_id,locale,created_at) VALUES (?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.profileId,e.locale,n),{id:t,tenantId:e.tenantId,visitorId:e.visitorId,profileId:e.profileId,locale:e.locale,createdAt:n}}async getNoticeShownForVisitor(e){return this.stmt("SELECT * FROM notice_shown WHERE visitor_id = ? ORDER BY created_at DESC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,visitorId:n.visitor_id,profileId:n.profile_id,locale:n.locale,createdAt:n.created_at}))}mapVisitor(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,firstSeen:e.first_seen,lastSeen:e.last_seen,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip_hash!=null?{ipHash:e.ip_hash}:{},...e.user_agent_hash!=null?{userAgentHash:e.user_agent_hash}:{}}}async createVisitor(e){let t=q(),n=new Date().toISOString();this.stmt("INSERT INTO visitors (id,tenant_id,visitor_id,country,region,city,ip_hash,user_agent_hash,first_seen,last_seen) VALUES (?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null,n,n);let o=await this.getVisitor(e.visitorId);if(!o)throw new Error("Failed to create visitor");return o}async updateVisitor(e,t){let n=new Date().toISOString(),o=["last_seen = ?"],r=[t.lastSeen??n];t.country!=null&&(o.push("country = ?"),r.push(t.country)),t.region!=null&&(o.push("region = ?"),r.push(t.region)),t.city!=null&&(o.push("city = ?"),r.push(t.city)),r.push(e),this.stmt(`UPDATE visitors SET ${o.join(", ")} WHERE visitor_id = ?`).run(...r);let s=await this.getVisitor(e);if(!s)throw new Error(`Visitor ${e} not found`);return s}async deleteVisitor(e){this.stmt("DELETE FROM visitors WHERE visitor_id = ?").run(e)}async getVisitor(e){let t=this.stmt("SELECT * FROM visitors WHERE visitor_id = ?").get(e);return t?this.mapVisitor(t):null}async getVisitors(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.from&&(t.push("first_seen >= ?"),n.push(e.from)),e.to&&(t.push("first_seen <= ?"),n.push(e.to)),e.q){t.push("(visitor_id LIKE ? OR country LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,Nn),a=(r-1)*s,c=this.stmt(`SELECT * FROM visitors WHERE ${o} ORDER BY last_seen DESC LIMIT ? OFFSET ?`).all(...n,s,a),l=this.stmt(`SELECT COUNT(*) AS total FROM visitors WHERE ${o}`).get(...n);return{items:c.map(d=>this.mapVisitor(d)),total:l.total,page:r,limit:s}}mapUser(e){let t=e.allowed_tenants?JSON.parse(e.allowed_tenants):[];return{id:e.id,tenantId:e.tenant_id,name:e.name,email:e.email,passwordHash:e.password_hash,isActive:e.is_active===1,totpEnabled:e.totp_enabled===1,...e.totp_secret!=null?{totpSecret:e.totp_secret}:{},allowedTenants:t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUser(e){let t=(0,C.randomUUID)(),n=new Date().toISOString(),o=e.allowedTenants?.length?JSON.stringify(e.allowedTenants):null;this.stmt("INSERT INTO users (id,tenant_id,name,email,password_hash,allowed_tenants,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.email,e.passwordHash,o,n,n);let r=await this.getUserByEmail(e.email);if(!r)throw new Error("Failed to create user");return r}async updateUser(e,t){let n=new Date().toISOString(),o=["updated_at = ?"],r=[n];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.email!=null&&(o.push("email = ?"),r.push(t.email)),t.passwordHash!=null&&(o.push("password_hash = ?"),r.push(t.passwordHash)),t.isActive!=null&&(o.push("is_active = ?"),r.push(t.isActive?1:0)),"totpSecret"in t&&(o.push("totp_secret = ?"),r.push(t.totpSecret??null)),t.totpEnabled!=null&&(o.push("totp_enabled = ?"),r.push(t.totpEnabled?1:0)),"allowedTenants"in t&&(o.push("allowed_tenants = ?"),r.push(t.allowedTenants?.length?JSON.stringify(t.allowedTenants):null)),r.push(e),this.stmt(`UPDATE users SET ${o.join(", ")} WHERE id = ?`).run(...r);let s=this.stmt("SELECT * FROM users WHERE id = ?").get(e);if(!s)throw new Error(`User ${e} not found`);return this.mapUser(s)}async deleteUser(e){this.stmt("DELETE FROM user_roles WHERE user_id = ?").run(e),this.stmt("DELETE FROM users WHERE id = ?").run(e)}async getUserById(e){let t=this.stmt("SELECT * FROM users WHERE id = ?").get(e);return t?this.mapUser(t):null}async getUserByEmail(e){let t=this.stmt("SELECT * FROM users WHERE email = ?").get(e);return t?this.mapUser(t):null}async getUsers(e){return this.stmt("SELECT * FROM users WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapUser(n))}async countUsers(e){return(e?this.stmt("SELECT COUNT(*) as n FROM users WHERE tenant_id = ?").get(e):this.stmt("SELECT COUNT(*) as n FROM users").get())?.n??0}async getRoles(e){return this.stmt("SELECT * FROM roles WHERE tenant_id = ?").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async createRole(e){let t=(0,C.randomUUID)();this.stmt("INSERT INTO roles (id,tenant_id,name,description) VALUES (?,?,?,?)").run(t,e.tenantId,e.name,e.description??null);let n=this.stmt("SELECT * FROM roles WHERE id = ?").get(t);if(!n)throw new Error("Failed to create role");return{id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}}async updateRole(e,t){let n=[],o=[];t.name!=null&&(n.push("name = ?"),o.push(t.name)),t.description!=null&&(n.push("description = ?"),o.push(t.description)),n.length>0&&(o.push(e),this.stmt(`UPDATE roles SET ${n.join(", ")} WHERE id = ?`).run(...o));let r=this.stmt("SELECT * FROM roles WHERE id = ?").get(e);if(!r)throw new Error(`Role ${e} not found`);return{id:r.id,tenantId:r.tenant_id,name:r.name,...r.description!=null?{description:r.description}:{}}}async deleteRole(e){this.stmt("DELETE FROM role_permissions WHERE role_id = ?").run(e),this.stmt("DELETE FROM user_roles WHERE role_id = ?").run(e),this.stmt("DELETE FROM roles WHERE id = ?").run(e)}async getAllPermissions(){return this.stmt("SELECT * FROM permissions ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,...t.description!=null?{description:t.description}:{}}))}async assignPermissionToRole(e,t){this.stmt("INSERT OR IGNORE INTO role_permissions (role_id,permission_id) VALUES (?,?)").run(e,t)}async revokePermissionFromRole(e,t){this.stmt("DELETE FROM role_permissions WHERE role_id = ? AND permission_id = ?").run(e,t)}async getPermissionsForRole(e){return this.stmt("SELECT p.* FROM permissions p JOIN role_permissions rp ON rp.permission_id = p.id WHERE rp.role_id = ?").all(e).map(n=>({id:n.id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async getUserRoles(e,t){return(t?this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.tenant_id = ?").all(e,t):this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?").all(e)).map(o=>({id:o.id,tenantId:o.tenant_id,name:o.name,...o.description!=null?{description:o.description}:{}}))}async assignRole(e,t,n="default"){this.stmt("INSERT OR IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)").run(e,t,n)}async revokeRole(e,t,n){n?this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ? AND tenant_id = ?").run(e,t,n):this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?").run(e,t)}async createLog(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO audit_logs (id,tenant_id,user_id,action,resource_type,resource_id,old_data,new_data,created_at) VALUES (?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null,n)}async getLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.action&&(t.push("action = ?"),n.push(e.action)),e.resourceType&&(t.push("resource_type = ?"),n.push(e.resourceType)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to)),e.q){t.push("(action LIKE ? OR resource_type LIKE ? OR resource_id LIKE ? OR user_id LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d,d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,Nn),a=(r-1)*s,c=this.stmt(`SELECT ${i.AUDIT_SUMMARY_COLS} FROM audit_logs WHERE ${o} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,s,a),l=this.stmt(`SELECT COUNT(*) AS total FROM audit_logs WHERE ${o}`).get(...n);return{items:c.map(d=>this.mapAuditSummary(d)),total:l.total,page:r,limit:s}}async getAuditLogById(e){let t=this.stmt("SELECT * FROM audit_logs WHERE id = ?").get(e);return t?this.mapAuditLog(t):null}static AUDIT_SUMMARY_COLS="id, tenant_id, user_id, action, resource_type, resource_id, created_at";mapAuditSummary(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},createdAt:e.created_at}}mapAuditLog(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,createdAt:e.created_at,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},...e.old_data!=null?{oldData:JSON.parse(e.old_data)}:{},...e.new_data!=null?{newData:JSON.parse(e.new_data)}:{}}}async*streamAuditLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let o=500,r=0;for(;;){let s=this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,o,r);if(s.length===0)break;for(let a of s)yield this.mapAuditLog(a);r+=o}}async getOverviewStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),o=this.stmt("SELECT COUNT(*) as n FROM visitors WHERE tenant_id = ?").get(e),r=t?.n??0,s=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 500").all(e),a=0,c=0;for(let d of s){let u=Object.values(JSON.parse(d.consent_json)),m=u.length>0?u.filter(h=>h==="granted").length/u.length:0;m>=.8?a++:m<=.2&&c++}let l=s.length||1;return{totalConsents:r,gpcDetectedCount:n?.n??0,totalVisitors:o?.n??0,acceptedPct:Math.round(a/l*100),rejectedPct:Math.round(c/l*100)}}async getCategoryStats(e){let t=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? LIMIT 5000").all(e),n={};for(let o of t){let r=JSON.parse(o.consent_json);for(let[s,a]of Object.entries(r))n[s]||(n[s]={granted:0,denied:0,objected:0}),a==="granted"?n[s].granted++:a==="denied"?n[s].denied++:a==="objected"&&n[s].objected++}return n}async getTimeline(e,t=30){return this.stmt("SELECT date(created_at) as date, COUNT(*) as count FROM consent_records WHERE tenant_id = ? AND created_at >= date('now', ?) GROUP BY date(created_at) ORDER BY date ASC").all(e,`-${t} days`).map(o=>({date:o.date,count:o.count}))}async getCountries(e){return this.stmt("SELECT v.country, COUNT(*) as count FROM consent_records cr JOIN visitors v ON v.visitor_id = cr.visitor_id WHERE cr.tenant_id = ? AND v.country IS NOT NULL GROUP BY v.country ORDER BY count DESC LIMIT 50").all(e).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),o=t?.n??0,r=n?.n??0;return{detected:r,total:o,rate:o>0?Math.round(r/o*100):0}}async getTenants(){return this.stmt("SELECT * FROM tenants ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createTenant(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO tenants (id,name,slug,created_at,updated_at) VALUES (?,?,?,?,?)").run(t,e.name,e.slug,n,n);let o=this.stmt("SELECT * FROM tenants WHERE id = ?").get(t);if(!o)throw new Error("Failed to create tenant");return{id:o.id,name:o.name,slug:o.slug,createdAt:o.created_at,updatedAt:o.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),o=["updated_at = ?"],r=[n];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.slug!=null&&(o.push("slug = ?"),r.push(t.slug)),r.push(e),this.stmt(`UPDATE tenants SET ${o.join(", ")} WHERE id = ?`).run(...r);let s=this.stmt("SELECT * FROM tenants WHERE id = ?").get(e);if(!s)throw new Error(`Tenant ${e} not found`);return{id:s.id,name:s.name,slug:s.slug,createdAt:s.created_at,updatedAt:s.updated_at}}async deleteTenant(e){this.stmt("DELETE FROM tenants WHERE id = ?").run(e)}async getSettings(e){let t=this.stmt("SELECT allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json FROM tenant_settings WHERE tenant_id = ?").get(e);return t?{allowedOrigins:JSON.parse(t.allowed_origins_json),adminAllowedOrigins:JSON.parse(t.admin_allowed_origins_json),setupCompleted:!!t.setup_completed,profilesSeeded:!!t.profiles_seeded,tcfConfirmation:t.tcf_confirmation_json?JSON.parse(t.tcf_confirmation_json):void 0,gppConfirmation:t.gpp_confirmation_json?JSON.parse(t.gpp_confirmation_json):void 0}:{}}async updateSettings(e,t){let o={...await this.getSettings(e),...t};return this.stmt(`INSERT INTO tenant_settings (tenant_id, allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json, updated_at) VALUES (?,?,?,?,?,?,?,?)
45
+ ON CONFLICT(tenant_id) DO UPDATE SET allowed_origins_json = excluded.allowed_origins_json, admin_allowed_origins_json = excluded.admin_allowed_origins_json, setup_completed = excluded.setup_completed, profiles_seeded = excluded.profiles_seeded, tcf_confirmation_json = excluded.tcf_confirmation_json, gpp_confirmation_json = excluded.gpp_confirmation_json, updated_at = excluded.updated_at`).run(e,JSON.stringify(o.allowedOrigins??[]),JSON.stringify(o.adminAllowedOrigins??[]),o.setupCompleted?1:0,o.profilesSeeded?1:0,o.tcfConfirmation?JSON.stringify(o.tcfConfirmation):null,o.gppConfirmation?JSON.stringify(o.gppConfirmation):null,new Date().toISOString()),this.getSettings(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=this.stmt("SELECT visitor_id FROM consent_records WHERE created_at < ?").all(t);for(let{visitor_id:o}of n)this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(o),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(o);return n.length}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active===1,...e.created_by!==null?{createdBy:e.created_by}:{},...e.expire_by!==null?{expireBy:e.expire_by}:{},createdAt:e.created_at,...e.updated_at!==null?{updatedAt:e.updated_at}:{}}}async createApiKey(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO api_keys (id,tenant_id,key_hash,name,created_by,expire_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.keyHash,e.name,e.createdBy??null,e.expireBy??null,n,n);let o=this.stmt("SELECT * FROM api_keys WHERE id = ?").get(t);if(!o)throw new Error("Failed to create API key");return this.mapApiKey(o)}async getApiKeyByHash(e){let t=this.stmt("SELECT * FROM api_keys WHERE key_hash = ? AND is_active = 1").get(e);return t?this.mapApiKey(t):null}async revokeApiKey(e){this.stmt("UPDATE api_keys SET is_active = 0, updated_at = ? WHERE id = ?").run(new Date().toISOString(),e)}async reactivateApiKey(e){let t=new Date().toISOString();this.stmt("UPDATE api_keys SET is_active = 1, updated_at = ?, expire_by = CASE WHEN expire_by <= ? THEN NULL ELSE expire_by END WHERE id = ?").run(t,t,e)}async deleteApiKey(e){this.stmt("DELETE FROM api_keys WHERE id = ?").run(e)}async getApiKeys(e){return this.stmt("SELECT * FROM api_keys WHERE tenant_id = ? ORDER BY created_at DESC").all(e).map(n=>this.mapApiKey(n))}mapConsentTemplate(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,cookies:JSON.parse(e.cookies_json),categories:JSON.parse(e.categories_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createConsentTemplate(e){let t=_e(),n=new Date().toISOString();return this.stmt("INSERT INTO consent_templates (id,tenant_id,name,cookies_json,categories_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,JSON.stringify(e.cookies),JSON.stringify(e.categories),n,n),this.mapConsentTemplate(this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(t))}async updateConsentTemplate(e,t){let n=new Date().toISOString();t.name!==void 0&&this.stmt("UPDATE consent_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e),t.cookies!==void 0&&this.stmt("UPDATE consent_templates SET cookies_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t.cookies),n,e),t.categories!==void 0&&this.stmt("UPDATE consent_templates SET categories_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t.categories),n,e);let o=this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(e);if(!o)throw new Error("Consent template not found");return this.mapConsentTemplate(o)}async deleteConsentTemplate(e){this.stmt("DELETE FROM consent_templates WHERE id = ?").run(e)}async getConsentTemplate(e){let t=this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(e);return t?this.mapConsentTemplate(t):null}async getConsentTemplates(e){return this.stmt("SELECT * FROM consent_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapConsentTemplate(n))}async copyConsentTemplate(e,t){let n=await this.getConsentTemplate(e);if(!n)throw new Error("Consent template not found");return this.createConsentTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies,categories:n.categories})}mapUITemplate(e){let t=JSON.parse(e.settings_json);return{id:e.id,tenantId:e.tenant_id,name:e.name,...t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUITemplate(e){let t=we(),n=new Date().toISOString(),{tenantId:o,name:r,...s}=e;return this.stmt("INSERT INTO ui_templates (id,tenant_id,name,settings_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run(t,o,r,JSON.stringify(s),n,n),this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(t))}async updateUITemplate(e,t){let n=new Date().toISOString(),o=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);if(!o)throw new Error("UI template not found");t.name!==void 0&&this.stmt("UPDATE ui_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e);let{name:r,...s}=t;if(Object.keys(s).length>0){let c={...JSON.parse(o.settings_json),...s};this.stmt("UPDATE ui_templates SET settings_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(c),n,e)}return this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e))}async deleteUITemplate(e){this.stmt("DELETE FROM ui_templates WHERE id = ?").run(e)}async getUITemplate(e){let t=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);return t?this.mapUITemplate(t):null}async getUITemplates(e){return this.stmt("SELECT * FROM ui_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapUITemplate(n))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:o,mainBanner:r,gpcBanner:s,preferenceModal:a}=n;return this.createUITemplate({tenantId:o,name:t,mainBanner:r,gpcBanner:s,preferenceModal:a})}mapProfileSummary(e){return{id:e.id,name:e.name,defaultLocale:e.default_locale,complianceGroup:e.compliance_group??null,customComplianceGroup:e.custom_compliance_group??null,isActive:e.is_active===1,consentTemplateName:e.consent_template_name,uiTemplateName:e.ui_template_name,createdAt:e.created_at,updatedAt:e.updated_at}}PROFILE_SUMMARY_SQL=`
47
46
  SELECT
48
- p.id, p.name, p.default_locale, p.version, p.created_at, p.updated_at,
47
+ p.id, p.name, p.default_locale, p.created_at, p.updated_at,
49
48
  json_extract(p.profile_json, '$.complianceGroup') AS compliance_group,
49
+ json_extract(p.profile_json, '$.customComplianceGroup') AS custom_compliance_group,
50
50
  json_extract(p.profile_json, '$.isActive') AS is_active,
51
- json_extract(p.profile_json, '$.cookieTemplateId') AS cookie_template_id,
51
+ json_extract(p.profile_json, '$.consentTemplateId') AS consent_template_id,
52
52
  json_extract(p.profile_json, '$.uiTemplateId') AS ui_template_id,
53
- ct.name AS cookie_template_name,
53
+ ct.name AS consent_template_name,
54
54
  ut.name AS ui_template_name
55
55
  FROM profiles p
56
- LEFT JOIN cookie_templates ct ON ct.id = json_extract(p.profile_json, '$.cookieTemplateId')
56
+ LEFT JOIN consent_templates ct ON ct.id = json_extract(p.profile_json, '$.consentTemplateId')
57
57
  LEFT JOIN ui_templates ut ON ut.id = json_extract(p.profile_json, '$.uiTemplateId')
58
- `;async listProfilesSummary(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE p.tenant_id = ? ORDER BY p.created_at ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingCookieTemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.cookieTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingUITemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.uiTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async getOptInStats(e,t){let n=["cr.tenant_id = ?"],i=[e];t.profileId&&(n.push("cr.profile_id = ?"),i.push(t.profileId)),t.from&&(n.push("cr.created_at >= ?"),i.push(t.from)),t.to&&(n.push("cr.created_at <= ?"),i.push(t.to)),t.locale&&(n.push("cr.locale = ?"),i.push(t.locale));let o=n.join(" AND "),r=this.stmt(`SELECT cr.locale, cr.consent_json FROM consent_records cr WHERE ${o}`).all(...i),a=0,c=0,l=0,u=0,d={};for(let f of r){let _=Object.values(JSON.parse(f.consent_json)),h=_.length>0?_.filter(I=>I==="granted").length/_.length:0,A=_.length>0?_.filter(I=>I==="denied").length/_.length:0;a++;let T=f.locale;d[T]||(d[T]={total:0,granted:0,denied:0,managed:0}),d[T].total++,h>=.9?(c++,d[T].granted++):A>=.9?(l++,d[T].denied++):(u++,d[T].managed++)}let p=this.stmt(`SELECT date(cr.created_at) as d, cr.consent_json FROM consent_records cr WHERE ${o} ORDER BY d ASC`).all(...i),E=new Map;for(let f of p){let _=E.get(f.d)??{total:0,granted:0,denied:0,managed:0},h=Object.values(JSON.parse(f.consent_json)),A=h.length>0?h.filter(I=>I==="granted").length/h.length:0,T=h.length>0?h.filter(I=>I==="denied").length/h.length:0;_.total++,A>=.9?_.granted++:T>=.9?_.denied++:_.managed++,E.set(f.d,_)}let S=Array.from(E.entries()).map(([f,_])=>({date:f,..._}));return{total:a,granted:c,denied:l,managed:u,grantedPct:a>0?Math.round(c/a*1e3)/10:0,deniedPct:a>0?Math.round(l/a*1e3)/10:0,managedPct:a>0?Math.round(u/a*1e3)/10:0,byLocale:d,byDate:S}}};var Nt=500,qe=class{constructor(e){this.config=e}config;db;cache=new Map;stmt(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}async connect(){let e=await import("node-sqlite3-wasm").catch(()=>{throw new Error("driver 'node-sqlite3-wasm' requires: npm install node-sqlite3-wasm")}),{dbPath:t}=Q(this.config.path??"./consenti-data","node-sqlite3-wasm");this.db=new e.default.Database(t),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA foreign_keys=ON"),this.db.exec("PRAGMA synchronous=NORMAL"),await this.migrate()}async disconnect(){for(let e of this.cache.values())e.finalize();this.cache.clear(),this.db.close()}async migrate(){let t=this.stmt("PRAGMA user_version").get()?.user_version??0;t<1&&(this.db.exec(ue),this.db.exec(fe),this.db.exec("PRAGMA user_version = 1")),t<2&&(this.db.exec(pe),this.db.exec("PRAGMA user_version = 2")),t<3&&(this.db.exec(me),this.db.exec("PRAGMA user_version = 3")),t<4&&(this.db.exec("ALTER TABLE user_roles ADD COLUMN tenant_id TEXT NOT NULL DEFAULT 'default'"),this.db.exec("PRAGMA user_version = 4")),t<5&&(this.db.exec(ge),this.db.exec("PRAGMA user_version = 5")),t<6&&(this.db.exec("ALTER TABLE users ADD COLUMN allowed_tenants TEXT"),this.db.exec("PRAGMA user_version = 6")),this.db.exec(`
58
+ `;async listProfilesSummary(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE p.tenant_id = ? ORDER BY p.created_at ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingConsentTemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.consentTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingUITemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.uiTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async getOptInStats(e,t){let n=["cr.tenant_id = ?"],o=[e];t.profileId&&(n.push("cr.profile_id = ?"),o.push(t.profileId)),t.from&&(n.push("cr.created_at >= ?"),o.push(t.from)),t.to&&(n.push("cr.created_at <= ?"),o.push(t.to)),t.locale&&(n.push("cr.locale = ?"),o.push(t.locale));let r=n.join(" AND "),s=this.stmt(`SELECT cr.locale, cr.consent_json FROM consent_records cr WHERE ${r}`).all(...o),a=0,c=0,l=0,d=0,u={};for(let _ of s){let w=Object.values(JSON.parse(_.consent_json)),R=w.length>0?w.filter(P=>P==="granted").length/w.length:0,v=w.length>0?w.filter(P=>P==="denied").length/w.length:0;a++;let A=_.locale;u[A]||(u[A]={total:0,granted:0,denied:0,managed:0}),u[A].total++,R>=.9?(c++,u[A].granted++):v>=.9?(l++,u[A].denied++):(d++,u[A].managed++)}let m=this.stmt(`SELECT date(cr.created_at) as d, cr.consent_json FROM consent_records cr WHERE ${r} ORDER BY d ASC`).all(...o),h=new Map;for(let _ of m){let w=h.get(_.d)??{total:0,granted:0,denied:0,managed:0},R=Object.values(JSON.parse(_.consent_json)),v=R.length>0?R.filter(P=>P==="granted").length/R.length:0,A=R.length>0?R.filter(P=>P==="denied").length/R.length:0;w.total++,v>=.9?w.granted++:A>=.9?w.denied++:w.managed++,h.set(_.d,w)}let S=Array.from(h.entries()).map(([_,w])=>({date:_,...w}));return{total:a,granted:c,denied:l,managed:d,grantedPct:a>0?Math.round(c/a*1e3)/10:0,deniedPct:a>0?Math.round(l/a*1e3)/10:0,managedPct:a>0?Math.round(d/a*1e3)/10:0,byLocale:u,byDate:S}}};p();var xn=500,_t=class i{constructor(e){this.config=e}config;db;cache=new Map;stmt(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}async connect(){let e=await import("node-sqlite3-wasm").catch(()=>{throw new Error("driver 'node-sqlite3-wasm' requires: npm install node-sqlite3-wasm")}),{dbPath:t}=ue(this.config.path??"./consenti-data","node-sqlite3-wasm");this.db=new e.default.Database(t),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA foreign_keys=ON"),this.db.exec("PRAGMA synchronous=NORMAL"),await this.migrate()}async disconnect(){for(let e of this.cache.values())e.finalize();this.cache.clear(),this.db.close()}async migrate(){(this.stmt("PRAGMA user_version").get()?.user_version??0)<1&&(this.db.exec(Oe),this.db.exec(De),this.db.exec("PRAGMA user_version = 1")),this.db.exec(`
59
59
  CREATE INDEX IF NOT EXISTS idx_profiles_tenant_compliance_active
60
60
  ON profiles (tenant_id, json_extract(profile_json,'$.complianceGroup'), json_extract(profile_json,'$.isActive'));
61
- CREATE INDEX IF NOT EXISTS idx_profiles_tenant
62
- ON profiles (tenant_id);
63
- CREATE INDEX IF NOT EXISTS idx_consents_tenant_profile_date
64
- ON consent_records (tenant_id, profile_id, created_at);
65
- CREATE INDEX IF NOT EXISTS idx_consents_visitor
66
- ON consent_records (visitor_id);
67
- CREATE INDEX IF NOT EXISTS idx_visitors_tenant
68
- ON visitors (tenant_id);
69
- CREATE INDEX IF NOT EXISTS idx_audit_tenant_date
70
- ON audit_logs (tenant_id, created_at);
71
- `)}mapProfile(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,defaultLocale:e.default_locale,version:e.version,profileJson:JSON.parse(e.profile_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createProfile(e){let t=de(),n=new Date().toISOString();this.stmt("INSERT INTO profiles (id,tenant_id,name,default_locale,profile_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?)").run([t,e.tenantId,e.name,e.defaultLocale,JSON.stringify(e.profileJson),n,n]);let i=await this.getProfile(t);if(!i)throw new Error("Failed to create profile");return i}async updateProfile(e,t){if(!await this.getProfile(e))throw new Error(`Profile ${e} not found`);let i=new Date().toISOString(),o=["updated_at = ?","version = version + 1"],r=[i];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.defaultLocale!=null&&(o.push("default_locale = ?"),r.push(t.defaultLocale)),t.profileJson!=null&&(o.push("profile_json = ?"),r.push(JSON.stringify(t.profileJson))),r.push(e),this.stmt(`UPDATE profiles SET ${o.join(", ")} WHERE id = ?`).run(r);let a=await this.getProfile(e);if(!a)throw new Error("Failed to update profile");return a}async deleteProfile(e){this.stmt("DELETE FROM profiles WHERE id = ?").run(e)}async getProfile(e){let t=this.stmt("SELECT * FROM profiles WHERE id = ?").get(e);return t?this.mapProfile(t):null}async getProfiles(e){return this.stmt("SELECT * FROM profiles WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapProfile(n))}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(i=>i.profileJson.complianceGroup===t&&i.profileJson.isActive)??null}mapConsent(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,profileVersion:e.profile_version,locale:e.locale,consentJson:JSON.parse(e.consent_json),gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},...e.parental_consent_token!=null?{parentalConsentToken:e.parental_consent_token}:{},...e.tcf_string!=null?{tcfString:e.tcf_string}:{},createdAt:e.created_at,updatedAt:e.updated_at}}async createConsent(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO consent_records (id,tenant_id,visitor_id,profile_id,profile_version,locale,consent_json,gpc_detected,source,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.visitorId,e.profileId,e.profileVersion,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source,n,n]);let i=(0,w.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run([i,e.tenantId,t,e.visitorId,null,JSON.stringify(e.consentJson),"created",n]);let o=await this.getConsent(e.visitorId);if(!o)throw new Error("Failed to create consent");return o}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let i=new Date().toISOString(),o=["updated_at = ?","consent_json = ?"],r=[i,JSON.stringify(t.consentJson)];t.locale!=null&&(o.push("locale = ?"),r.push(t.locale)),t.gpcDetected!=null&&(o.push("gpc_detected = ?"),r.push(t.gpcDetected?1:0)),r.push(e),this.stmt(`UPDATE consent_records SET ${o.join(", ")} WHERE visitor_id = ?`).run(r);let a=(0,w.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run([a,n.tenantId,n.id,e,JSON.stringify(n.consentJson),JSON.stringify(t.consentJson),"updated",i]);let c=await this.getConsent(e);if(!c)throw new Error("Failed to update consent");return c}async deleteConsent(e){this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(e),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(e)}async getConsent(e){let t=this.stmt("SELECT * FROM consent_records WHERE visitor_id = ?").get(e);return t?this.mapConsent(t):null}async getConsents(e){let t=["tenant_id = ?"],n=[e.tenantId];e.profileId&&(t.push("profile_id = ?"),n.push(e.profileId)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=Math.min(e.limit??50,Nt),o=((e.page??1)-1)*i;return this.stmt(`SELECT * FROM consent_records WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all([...n,i,o]).map(a=>this.mapConsent(a))}async*streamConsents(e){let n=0;for(;;){let i=this.stmt("SELECT * FROM consent_records WHERE tenant_id = ? LIMIT ? OFFSET ?").all([e.tenantId,500,n]);if(i.length===0)break;for(let o of i)yield this.mapConsent(o);n+=500}}async getConsentHistory(e){return this.stmt("SELECT * FROM consent_history WHERE visitor_id = ? ORDER BY created_at ASC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,consentRecordId:n.consent_record_id,visitorId:n.visitor_id,oldJson:n.old_json!=null?JSON.parse(n.old_json):null,newJson:JSON.parse(n.new_json),action:n.action,createdAt:n.created_at}))}mapVisitor(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,firstSeen:e.first_seen,lastSeen:e.last_seen,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip_hash!=null?{ipHash:e.ip_hash}:{},...e.user_agent_hash!=null?{userAgentHash:e.user_agent_hash}:{}}}async createVisitor(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO visitors (id,tenant_id,visitor_id,country,region,city,ip_hash,user_agent_hash,first_seen,last_seen) VALUES (?,?,?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null,n,n]);let i=await this.getVisitor(e.visitorId);if(!i)throw new Error("Failed to create visitor");return i}async updateVisitor(e,t){let n=new Date().toISOString(),i=["last_seen = ?"],o=[t.lastSeen??n];t.country!=null&&(i.push("country = ?"),o.push(t.country)),t.region!=null&&(i.push("region = ?"),o.push(t.region)),t.city!=null&&(i.push("city = ?"),o.push(t.city)),o.push(e),this.stmt(`UPDATE visitors SET ${i.join(", ")} WHERE visitor_id = ?`).run(o);let r=await this.getVisitor(e);if(!r)throw new Error(`Visitor ${e} not found`);return r}async deleteVisitor(e){this.stmt("DELETE FROM visitors WHERE visitor_id = ?").run(e)}async getVisitor(e){let t=this.stmt("SELECT * FROM visitors WHERE visitor_id = ?").get(e);return t?this.mapVisitor(t):null}async getVisitors(e){let t=["tenant_id = ?"],n=[e.tenantId];e.from&&(t.push("first_seen >= ?"),n.push(e.from)),e.to&&(t.push("first_seen <= ?"),n.push(e.to));let i=Math.min(e.limit??50,Nt),o=((e.page??1)-1)*i;return this.stmt(`SELECT * FROM visitors WHERE ${t.join(" AND ")} ORDER BY last_seen DESC LIMIT ? OFFSET ?`).all([...n,i,o]).map(a=>this.mapVisitor(a))}mapUser(e){let t=e.allowed_tenants?JSON.parse(e.allowed_tenants):[];return{id:e.id,tenantId:e.tenant_id,name:e.name,email:e.email,passwordHash:e.password_hash,isActive:e.is_active===1,totpEnabled:e.totp_enabled===1,...e.totp_secret!=null?{totpSecret:e.totp_secret}:{},allowedTenants:t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUser(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),i=e.allowedTenants?.length?JSON.stringify(e.allowedTenants):null;this.stmt("INSERT INTO users (id,tenant_id,name,email,password_hash,allowed_tenants,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.name,e.email,e.passwordHash,i,n,n]);let o=await this.getUserByEmail(e.email);if(!o)throw new Error("Failed to create user");return o}async updateUser(e,t){let n=new Date().toISOString(),i=["updated_at = ?"],o=[n];t.name!=null&&(i.push("name = ?"),o.push(t.name)),t.email!=null&&(i.push("email = ?"),o.push(t.email)),t.passwordHash!=null&&(i.push("password_hash = ?"),o.push(t.passwordHash)),t.isActive!=null&&(i.push("is_active = ?"),o.push(t.isActive?1:0)),"totpSecret"in t&&(i.push("totp_secret = ?"),o.push(t.totpSecret??null)),t.totpEnabled!=null&&(i.push("totp_enabled = ?"),o.push(t.totpEnabled?1:0)),"allowedTenants"in t&&(i.push("allowed_tenants = ?"),o.push(t.allowedTenants?.length?JSON.stringify(t.allowedTenants):null)),o.push(e),this.stmt(`UPDATE users SET ${i.join(", ")} WHERE id = ?`).run(o);let r=this.stmt("SELECT * FROM users WHERE id = ?").get(e);if(!r)throw new Error(`User ${e} not found`);return this.mapUser(r)}async deleteUser(e){this.stmt("DELETE FROM user_roles WHERE user_id = ?").run(e),this.stmt("DELETE FROM users WHERE id = ?").run(e)}async getUserById(e){let t=this.stmt("SELECT * FROM users WHERE id = ?").get(e);return t?this.mapUser(t):null}async getUserByEmail(e){let t=this.stmt("SELECT * FROM users WHERE email = ?").get(e);return t?this.mapUser(t):null}async getUsers(e){return this.stmt("SELECT * FROM users WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapUser(n))}async countUsers(e){return(e?this.stmt("SELECT COUNT(*) as n FROM users WHERE tenant_id = ?").get(e):this.stmt("SELECT COUNT(*) as n FROM users").get())?.n??0}async getRoles(e){return this.stmt("SELECT * FROM roles WHERE tenant_id = ?").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async createRole(e){let t=(0,w.randomUUID)();this.stmt("INSERT INTO roles (id,tenant_id,name,description) VALUES (?,?,?,?)").run([t,e.tenantId,e.name,e.description??null]);let n=this.stmt("SELECT * FROM roles WHERE id = ?").get(t);if(!n)throw new Error("Failed to create role");return{id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}}async updateRole(e,t){let n=[],i=[];t.name!=null&&(n.push("name = ?"),i.push(t.name)),t.description!=null&&(n.push("description = ?"),i.push(t.description)),n.length>0&&(i.push(e),this.stmt(`UPDATE roles SET ${n.join(", ")} WHERE id = ?`).run(i));let o=this.stmt("SELECT * FROM roles WHERE id = ?").get(e);if(!o)throw new Error(`Role ${e} not found`);return{id:o.id,tenantId:o.tenant_id,name:o.name,...o.description!=null?{description:o.description}:{}}}async deleteRole(e){this.stmt("DELETE FROM role_permissions WHERE role_id = ?").run(e),this.stmt("DELETE FROM user_roles WHERE role_id = ?").run(e),this.stmt("DELETE FROM roles WHERE id = ?").run(e)}async getAllPermissions(){return this.stmt("SELECT * FROM permissions ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,...t.description!=null?{description:t.description}:{}}))}async assignPermissionToRole(e,t){this.stmt("INSERT OR IGNORE INTO role_permissions (role_id,permission_id) VALUES (?,?)").run([e,t])}async revokePermissionFromRole(e,t){this.stmt("DELETE FROM role_permissions WHERE role_id = ? AND permission_id = ?").run([e,t])}async getPermissionsForRole(e){return this.stmt("SELECT p.* FROM permissions p JOIN role_permissions rp ON rp.permission_id = p.id WHERE rp.role_id = ?").all(e).map(n=>({id:n.id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async getUserRoles(e,t){return(t?this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.tenant_id = ?").all([e,t]):this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?").all(e)).map(i=>({id:i.id,tenantId:i.tenant_id,name:i.name,...i.description!=null?{description:i.description}:{}}))}async assignRole(e,t,n="default"){this.stmt("INSERT OR IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)").run([e,t,n])}async revokeRole(e,t,n){n?this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ? AND tenant_id = ?").run([e,t,n]):this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?").run([e,t])}async createLog(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO audit_logs (id,tenant_id,user_id,action,resource_type,resource_id,old_data,new_data,created_at) VALUES (?,?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null,n])}async getLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.resourceType&&(t.push("resource_type = ?"),n.push(e.resourceType)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=Math.min(e.limit??50,Nt),o=((e.page??1)-1)*i;return this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all([...n,i,o]).map(a=>this.mapAuditLog(a))}mapAuditLog(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,createdAt:e.created_at,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},...e.old_data!=null?{oldData:JSON.parse(e.old_data)}:{},...e.new_data!=null?{newData:JSON.parse(e.new_data)}:{}}}async*streamAuditLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=500,o=0;for(;;){let r=this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all([...n,i,o]);if(r.length===0)break;for(let a of r)yield this.mapAuditLog(a);o+=i}}async getOverviewStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),i=this.stmt("SELECT COUNT(*) as n FROM visitors WHERE tenant_id = ?").get(e),o=t?.n??0,r=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 500").all(e),a=0,c=0;for(let u of r){let d=Object.values(JSON.parse(u.consent_json)),p=d.length>0?d.filter(E=>E==="granted").length/d.length:0;p>=.8?a++:p<=.2&&c++}let l=r.length||1;return{totalConsents:o,gpcDetectedCount:n?.n??0,totalVisitors:i?.n??0,acceptedPct:Math.round(a/l*100),rejectedPct:Math.round(c/l*100)}}async getCategoryStats(e){let t=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? LIMIT 5000").all(e),n={};for(let i of t){let o=JSON.parse(i.consent_json);for(let[r,a]of Object.entries(o))n[r]||(n[r]={granted:0,denied:0,objected:0}),a==="granted"?n[r].granted++:a==="denied"?n[r].denied++:a==="objected"&&n[r].objected++}return n}async getTimeline(e,t=30){return this.stmt("SELECT date(created_at) as date, COUNT(*) as count FROM consent_records WHERE tenant_id = ? AND created_at >= date('now', ?) GROUP BY date(created_at) ORDER BY date ASC").all([e,`-${t} days`]).map(i=>({date:i.date,count:i.count}))}async getCountries(e){return this.stmt("SELECT v.country, COUNT(*) as count FROM consent_records cr JOIN visitors v ON v.visitor_id = cr.visitor_id WHERE cr.tenant_id = ? AND v.country IS NOT NULL GROUP BY v.country ORDER BY count DESC LIMIT 50").all(e).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),i=t?.n??0,o=n?.n??0;return{detected:o,total:i,rate:i>0?Math.round(o/i*100):0}}async getTenants(){return this.stmt("SELECT * FROM tenants ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createTenant(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO tenants (id,name,slug,created_at,updated_at) VALUES (?,?,?,?,?)").run([t,e.name,e.slug,n,n]);let i=this.stmt("SELECT * FROM tenants WHERE id = ?").get(t);if(!i)throw new Error("Failed to create tenant");return{id:i.id,name:i.name,slug:i.slug,createdAt:i.created_at,updatedAt:i.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),i=["updated_at = ?"],o=[n];t.name!=null&&(i.push("name = ?"),o.push(t.name)),t.slug!=null&&(i.push("slug = ?"),o.push(t.slug)),o.push(e),this.stmt(`UPDATE tenants SET ${i.join(", ")} WHERE id = ?`).run(o);let r=this.stmt("SELECT * FROM tenants WHERE id = ?").get(e);if(!r)throw new Error(`Tenant ${e} not found`);return{id:r.id,name:r.name,slug:r.slug,createdAt:r.created_at,updatedAt:r.updated_at}}async deleteTenant(e){this.stmt("DELETE FROM tenants WHERE id = ?").run(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=this.stmt("SELECT visitor_id FROM consent_records WHERE created_at < ?").all(t);for(let{visitor_id:i}of n)this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(i),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(i);return n.length}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active===1,createdAt:e.created_at}}async createApiKey(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO api_keys (id,tenant_id,key_hash,name,created_at) VALUES (?,?,?,?,?)").run([t,e.tenantId,e.keyHash,e.name,n]);let i=this.stmt("SELECT * FROM api_keys WHERE id = ?").get(t);if(!i)throw new Error("Failed to create API key");return this.mapApiKey(i)}async getApiKeyByHash(e){let t=this.stmt("SELECT * FROM api_keys WHERE key_hash = ? AND is_active = 1").get(e);return t?this.mapApiKey(t):null}async revokeApiKey(e){this.stmt("UPDATE api_keys SET is_active = 0 WHERE id = ?").run(e)}async getApiKeys(e){return this.stmt("SELECT * FROM api_keys WHERE tenant_id = ? ORDER BY created_at DESC").all(e).map(n=>this.mapApiKey(n))}mapCookieTemplate(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,cookies:JSON.parse(e.cookies_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createCookieTemplate(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();return this.stmt("INSERT INTO cookie_templates (id,tenant_id,name,cookies_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run([t,e.tenantId,e.name,JSON.stringify(e.cookies),n,n]),this.mapCookieTemplate(this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(t))}async updateCookieTemplate(e,t){let n=new Date().toISOString();t.name!==void 0&&this.stmt("UPDATE cookie_templates SET name = ?, updated_at = ? WHERE id = ?").run([t.name,n,e]),t.cookies!==void 0&&this.stmt("UPDATE cookie_templates SET cookies_json = ?, updated_at = ? WHERE id = ?").run([JSON.stringify(t.cookies),n,e]);let i=this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(e);if(!i)throw new Error("Cookie template not found");return this.mapCookieTemplate(i)}async deleteCookieTemplate(e){this.stmt("DELETE FROM cookie_templates WHERE id = ?").run(e)}async getCookieTemplate(e){let t=this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(e);return t?this.mapCookieTemplate(t):null}async getCookieTemplates(e){return this.stmt("SELECT * FROM cookie_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapCookieTemplate(n))}async copyCookieTemplate(e,t){let n=await this.getCookieTemplate(e);if(!n)throw new Error("Cookie template not found");return this.createCookieTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies})}mapUITemplate(e){let t=JSON.parse(e.settings_json);return{id:e.id,tenantId:e.tenant_id,name:e.name,...t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUITemplate(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),{tenantId:i,name:o,...r}=e;return this.stmt("INSERT INTO ui_templates (id,tenant_id,name,settings_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run([t,i,o,JSON.stringify(r),n,n]),this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(t))}async updateUITemplate(e,t){let n=new Date().toISOString(),i=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);if(!i)throw new Error("UI template not found");t.name!==void 0&&this.stmt("UPDATE ui_templates SET name = ?, updated_at = ? WHERE id = ?").run([t.name,n,e]);let{name:o,...r}=t;if(Object.keys(r).length>0){let c={...JSON.parse(i.settings_json),...r};this.stmt("UPDATE ui_templates SET settings_json = ?, updated_at = ? WHERE id = ?").run([JSON.stringify(c),n,e])}return this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e))}async deleteUITemplate(e){this.stmt("DELETE FROM ui_templates WHERE id = ?").run(e)}async getUITemplate(e){let t=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);return t?this.mapUITemplate(t):null}async getUITemplates(e){return this.stmt("SELECT * FROM ui_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapUITemplate(n))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:i,mainBanner:o,gpcBanner:r,preferenceModal:a}=n;return this.createUITemplate({tenantId:i,name:t,mainBanner:o,gpcBanner:r,preferenceModal:a})}mapProfileSummary(e){return{id:e.id,name:e.name,defaultLocale:e.default_locale,complianceGroup:e.compliance_group??null,version:e.version,isActive:e.is_active===1,cookieTemplateName:e.cookie_template_name,uiTemplateName:e.ui_template_name,createdAt:e.created_at,updatedAt:e.updated_at}}PROFILE_SUMMARY_SQL=`
61
+ `)}mapProfile(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,defaultLocale:e.default_locale,version:e.version,profileJson:JSON.parse(e.profile_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createProfile(e){let t=z(),n=new Date().toISOString();this.stmt("INSERT INTO profiles (id,tenant_id,name,default_locale,version,profile_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.name,e.defaultLocale,1,JSON.stringify(e.profileJson),n,n]);let o=await this.getProfile(t);if(!o)throw new Error("Failed to create profile");return o}async updateProfile(e,t){if(!await this.getProfile(e))throw new Error(`Profile ${e} not found`);let o=new Date().toISOString(),r=["updated_at = ?"],s=[o];t.name!=null&&(r.push("name = ?"),s.push(t.name)),t.defaultLocale!=null&&(r.push("default_locale = ?"),s.push(t.defaultLocale)),t.profileJson!=null&&(r.push("profile_json = ?"),s.push(JSON.stringify(t.profileJson))),t.version!=null&&(r.push("version = ?"),s.push(t.version)),s.push(e),this.stmt(`UPDATE profiles SET ${r.join(", ")} WHERE id = ?`).run(s);let a=await this.getProfile(e);if(!a)throw new Error("Failed to update profile");return a}async deleteProfile(e){this.stmt("DELETE FROM profiles WHERE id = ?").run(e)}async getProfile(e){let t=this.stmt("SELECT * FROM profiles WHERE id = ?").get(e);return t?this.mapProfile(t):null}async getProfiles(e){return this.stmt("SELECT * FROM profiles WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapProfile(n))}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(o=>(o.profileJson.complianceGroup===t||o.profileJson.customComplianceGroup===t)&&o.profileJson.isActive)??null}mapConsent(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,locale:e.locale,consentJson:JSON.parse(e.consent_json),gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},...e.parental_consent_token!=null?{parentalConsentToken:e.parental_consent_token}:{},...e.tcf_string!=null?{tcfString:e.tcf_string}:{},...e.gpp_string!=null?{gppString:e.gpp_string}:{},...e.signature!=null?{signature:e.signature}:{},createdAt:e.created_at,updatedAt:e.updated_at}}static CONSENT_SUMMARY_COLS="id, tenant_id, visitor_id, profile_id, locale, gpc_detected, source, age_verified, created_at, updated_at";mapConsentSummary(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,locale:e.locale,gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},createdAt:e.created_at,updatedAt:e.updated_at}}async createConsent(e){let t=K(),n=new Date().toISOString();this.stmt("INSERT INTO consent_records (id,tenant_id,visitor_id,profile_id,locale,consent_json,gpc_detected,source,age_verified,parental_consent_token,tcf_string,gpp_string,signature,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.visitorId,e.profileId,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source,e.ageVerified?1:0,e.parentalConsentToken??null,e.tcfString??null,e.gppString??null,e.signature??null,n,n]);let o=(0,C.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run([o,e.tenantId,t,e.visitorId,null,JSON.stringify(e.consentJson),"created",n]);let r=await this.getConsent(e.visitorId);if(!r)throw new Error("Failed to create consent");return r}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let o=new Date().toISOString(),r=["updated_at = ?","consent_json = ?"],s=[o,JSON.stringify(t.consentJson)];t.locale!=null&&(r.push("locale = ?"),s.push(t.locale)),t.gpcDetected!=null&&(r.push("gpc_detected = ?"),s.push(t.gpcDetected?1:0)),t.signature!=null&&(r.push("signature = ?"),s.push(t.signature)),s.push(e),this.stmt(`UPDATE consent_records SET ${r.join(", ")} WHERE visitor_id = ?`).run(s);let a=(0,C.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run([a,n.tenantId,n.id,e,JSON.stringify(n.consentJson),JSON.stringify(t.consentJson),"updated",o]);let c=await this.getConsent(e);if(!c)throw new Error("Failed to update consent");return c}async deleteConsent(e){this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(e),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(e)}async getConsent(e){let t=this.stmt("SELECT * FROM consent_records WHERE visitor_id = ?").get(e);return t?this.mapConsent(t):null}async getConsents(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.profileId&&(t.push("profile_id = ?"),n.push(e.profileId)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to)),e.q){t.push("(visitor_id LIKE ? OR profile_id LIKE ? OR locale LIKE ? OR source LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d,d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,xn),a=(r-1)*s,c=this.stmt(`SELECT ${i.CONSENT_SUMMARY_COLS} FROM consent_records WHERE ${o} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all([...n,s,a]),l=this.stmt(`SELECT COUNT(*) AS total FROM consent_records WHERE ${o}`).get(n);return{items:c.map(d=>this.mapConsentSummary(d)),total:l?.total??0,page:r,limit:s}}async*streamConsents(e){let n=0;for(;;){let o=this.stmt("SELECT * FROM consent_records WHERE tenant_id = ? LIMIT ? OFFSET ?").all([e.tenantId,500,n]);if(o.length===0)break;for(let r of o)yield this.mapConsent(r);n+=500}}async getConsentHistory(e){return this.stmt("SELECT * FROM consent_history WHERE visitor_id = ? ORDER BY created_at ASC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,consentRecordId:n.consent_record_id,visitorId:n.visitor_id,oldJson:n.old_json!=null?JSON.parse(n.old_json):null,newJson:JSON.parse(n.new_json),action:n.action,createdAt:n.created_at}))}async createNoticeShown(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();return this.stmt("INSERT INTO notice_shown (id,tenant_id,visitor_id,profile_id,locale,created_at) VALUES (?,?,?,?,?,?)").run([t,e.tenantId,e.visitorId,e.profileId,e.locale,n]),{id:t,tenantId:e.tenantId,visitorId:e.visitorId,profileId:e.profileId,locale:e.locale,createdAt:n}}async getNoticeShownForVisitor(e){return this.stmt("SELECT * FROM notice_shown WHERE visitor_id = ? ORDER BY created_at DESC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,visitorId:n.visitor_id,profileId:n.profile_id,locale:n.locale,createdAt:n.created_at}))}mapVisitor(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,firstSeen:e.first_seen,lastSeen:e.last_seen,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip_hash!=null?{ipHash:e.ip_hash}:{},...e.user_agent_hash!=null?{userAgentHash:e.user_agent_hash}:{}}}async createVisitor(e){let t=q(),n=new Date().toISOString();this.stmt("INSERT INTO visitors (id,tenant_id,visitor_id,country,region,city,ip_hash,user_agent_hash,first_seen,last_seen) VALUES (?,?,?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null,n,n]);let o=await this.getVisitor(e.visitorId);if(!o)throw new Error("Failed to create visitor");return o}async updateVisitor(e,t){let n=new Date().toISOString(),o=["last_seen = ?"],r=[t.lastSeen??n];t.country!=null&&(o.push("country = ?"),r.push(t.country)),t.region!=null&&(o.push("region = ?"),r.push(t.region)),t.city!=null&&(o.push("city = ?"),r.push(t.city)),r.push(e),this.stmt(`UPDATE visitors SET ${o.join(", ")} WHERE visitor_id = ?`).run(r);let s=await this.getVisitor(e);if(!s)throw new Error(`Visitor ${e} not found`);return s}async deleteVisitor(e){this.stmt("DELETE FROM visitors WHERE visitor_id = ?").run(e)}async getVisitor(e){let t=this.stmt("SELECT * FROM visitors WHERE visitor_id = ?").get(e);return t?this.mapVisitor(t):null}async getVisitors(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.from&&(t.push("first_seen >= ?"),n.push(e.from)),e.to&&(t.push("first_seen <= ?"),n.push(e.to)),e.q){t.push("(visitor_id LIKE ? OR country LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,xn),a=(r-1)*s,c=this.stmt(`SELECT * FROM visitors WHERE ${o} ORDER BY last_seen DESC LIMIT ? OFFSET ?`).all([...n,s,a]),l=this.stmt(`SELECT COUNT(*) AS total FROM visitors WHERE ${o}`).get(n);return{items:c.map(d=>this.mapVisitor(d)),total:l?.total??0,page:r,limit:s}}mapUser(e){let t=e.allowed_tenants?JSON.parse(e.allowed_tenants):[];return{id:e.id,tenantId:e.tenant_id,name:e.name,email:e.email,passwordHash:e.password_hash,isActive:e.is_active===1,totpEnabled:e.totp_enabled===1,...e.totp_secret!=null?{totpSecret:e.totp_secret}:{},allowedTenants:t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUser(e){let t=(0,C.randomUUID)(),n=new Date().toISOString(),o=e.allowedTenants?.length?JSON.stringify(e.allowedTenants):null;this.stmt("INSERT INTO users (id,tenant_id,name,email,password_hash,allowed_tenants,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.name,e.email,e.passwordHash,o,n,n]);let r=await this.getUserByEmail(e.email);if(!r)throw new Error("Failed to create user");return r}async updateUser(e,t){let n=new Date().toISOString(),o=["updated_at = ?"],r=[n];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.email!=null&&(o.push("email = ?"),r.push(t.email)),t.passwordHash!=null&&(o.push("password_hash = ?"),r.push(t.passwordHash)),t.isActive!=null&&(o.push("is_active = ?"),r.push(t.isActive?1:0)),"totpSecret"in t&&(o.push("totp_secret = ?"),r.push(t.totpSecret??null)),t.totpEnabled!=null&&(o.push("totp_enabled = ?"),r.push(t.totpEnabled?1:0)),"allowedTenants"in t&&(o.push("allowed_tenants = ?"),r.push(t.allowedTenants?.length?JSON.stringify(t.allowedTenants):null)),r.push(e),this.stmt(`UPDATE users SET ${o.join(", ")} WHERE id = ?`).run(r);let s=this.stmt("SELECT * FROM users WHERE id = ?").get(e);if(!s)throw new Error(`User ${e} not found`);return this.mapUser(s)}async deleteUser(e){this.stmt("DELETE FROM user_roles WHERE user_id = ?").run(e),this.stmt("DELETE FROM users WHERE id = ?").run(e)}async getUserById(e){let t=this.stmt("SELECT * FROM users WHERE id = ?").get(e);return t?this.mapUser(t):null}async getUserByEmail(e){let t=this.stmt("SELECT * FROM users WHERE email = ?").get(e);return t?this.mapUser(t):null}async getUsers(e){return this.stmt("SELECT * FROM users WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapUser(n))}async countUsers(e){return(e?this.stmt("SELECT COUNT(*) as n FROM users WHERE tenant_id = ?").get(e):this.stmt("SELECT COUNT(*) as n FROM users").get())?.n??0}async getRoles(e){return this.stmt("SELECT * FROM roles WHERE tenant_id = ?").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async createRole(e){let t=(0,C.randomUUID)();this.stmt("INSERT INTO roles (id,tenant_id,name,description) VALUES (?,?,?,?)").run([t,e.tenantId,e.name,e.description??null]);let n=this.stmt("SELECT * FROM roles WHERE id = ?").get(t);if(!n)throw new Error("Failed to create role");return{id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}}async updateRole(e,t){let n=[],o=[];t.name!=null&&(n.push("name = ?"),o.push(t.name)),t.description!=null&&(n.push("description = ?"),o.push(t.description)),n.length>0&&(o.push(e),this.stmt(`UPDATE roles SET ${n.join(", ")} WHERE id = ?`).run(o));let r=this.stmt("SELECT * FROM roles WHERE id = ?").get(e);if(!r)throw new Error(`Role ${e} not found`);return{id:r.id,tenantId:r.tenant_id,name:r.name,...r.description!=null?{description:r.description}:{}}}async deleteRole(e){this.stmt("DELETE FROM role_permissions WHERE role_id = ?").run(e),this.stmt("DELETE FROM user_roles WHERE role_id = ?").run(e),this.stmt("DELETE FROM roles WHERE id = ?").run(e)}async getAllPermissions(){return this.stmt("SELECT * FROM permissions ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,...t.description!=null?{description:t.description}:{}}))}async assignPermissionToRole(e,t){this.stmt("INSERT OR IGNORE INTO role_permissions (role_id,permission_id) VALUES (?,?)").run([e,t])}async revokePermissionFromRole(e,t){this.stmt("DELETE FROM role_permissions WHERE role_id = ? AND permission_id = ?").run([e,t])}async getPermissionsForRole(e){return this.stmt("SELECT p.* FROM permissions p JOIN role_permissions rp ON rp.permission_id = p.id WHERE rp.role_id = ?").all(e).map(n=>({id:n.id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async getUserRoles(e,t){return(t?this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.tenant_id = ?").all([e,t]):this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?").all(e)).map(o=>({id:o.id,tenantId:o.tenant_id,name:o.name,...o.description!=null?{description:o.description}:{}}))}async assignRole(e,t,n="default"){this.stmt("INSERT OR IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)").run([e,t,n])}async revokeRole(e,t,n){n?this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ? AND tenant_id = ?").run([e,t,n]):this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?").run([e,t])}async createLog(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO audit_logs (id,tenant_id,user_id,action,resource_type,resource_id,old_data,new_data,created_at) VALUES (?,?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null,n])}async getLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.action&&(t.push("action = ?"),n.push(e.action)),e.resourceType&&(t.push("resource_type = ?"),n.push(e.resourceType)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to)),e.q){t.push("(action LIKE ? OR resource_type LIKE ? OR resource_id LIKE ? OR user_id LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d,d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,xn),a=(r-1)*s,c=this.stmt(`SELECT ${i.AUDIT_SUMMARY_COLS} FROM audit_logs WHERE ${o} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all([...n,s,a]),l=this.stmt(`SELECT COUNT(*) AS total FROM audit_logs WHERE ${o}`).get(n);return{items:c.map(d=>this.mapAuditSummary(d)),total:l?.total??0,page:r,limit:s}}async getAuditLogById(e){let t=this.stmt("SELECT * FROM audit_logs WHERE id = ?").get(e);return t?this.mapAuditLog(t):null}static AUDIT_SUMMARY_COLS="id, tenant_id, user_id, action, resource_type, resource_id, created_at";mapAuditSummary(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},createdAt:e.created_at}}mapAuditLog(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,createdAt:e.created_at,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},...e.old_data!=null?{oldData:JSON.parse(e.old_data)}:{},...e.new_data!=null?{newData:JSON.parse(e.new_data)}:{}}}async*streamAuditLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let o=500,r=0;for(;;){let s=this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all([...n,o,r]);if(s.length===0)break;for(let a of s)yield this.mapAuditLog(a);r+=o}}async getOverviewStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),o=this.stmt("SELECT COUNT(*) as n FROM visitors WHERE tenant_id = ?").get(e),r=t?.n??0,s=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 500").all(e),a=0,c=0;for(let d of s){let u=Object.values(JSON.parse(d.consent_json)),m=u.length>0?u.filter(h=>h==="granted").length/u.length:0;m>=.8?a++:m<=.2&&c++}let l=s.length||1;return{totalConsents:r,gpcDetectedCount:n?.n??0,totalVisitors:o?.n??0,acceptedPct:Math.round(a/l*100),rejectedPct:Math.round(c/l*100)}}async getCategoryStats(e){let t=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? LIMIT 5000").all(e),n={};for(let o of t){let r=JSON.parse(o.consent_json);for(let[s,a]of Object.entries(r))n[s]||(n[s]={granted:0,denied:0,objected:0}),a==="granted"?n[s].granted++:a==="denied"?n[s].denied++:a==="objected"&&n[s].objected++}return n}async getTimeline(e,t=30){return this.stmt("SELECT date(created_at) as date, COUNT(*) as count FROM consent_records WHERE tenant_id = ? AND created_at >= date('now', ?) GROUP BY date(created_at) ORDER BY date ASC").all([e,`-${t} days`]).map(o=>({date:o.date,count:o.count}))}async getCountries(e){return this.stmt("SELECT v.country, COUNT(*) as count FROM consent_records cr JOIN visitors v ON v.visitor_id = cr.visitor_id WHERE cr.tenant_id = ? AND v.country IS NOT NULL GROUP BY v.country ORDER BY count DESC LIMIT 50").all(e).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),o=t?.n??0,r=n?.n??0;return{detected:r,total:o,rate:o>0?Math.round(r/o*100):0}}async getTenants(){return this.stmt("SELECT * FROM tenants ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createTenant(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO tenants (id,name,slug,created_at,updated_at) VALUES (?,?,?,?,?)").run([t,e.name,e.slug,n,n]);let o=this.stmt("SELECT * FROM tenants WHERE id = ?").get(t);if(!o)throw new Error("Failed to create tenant");return{id:o.id,name:o.name,slug:o.slug,createdAt:o.created_at,updatedAt:o.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),o=["updated_at = ?"],r=[n];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.slug!=null&&(o.push("slug = ?"),r.push(t.slug)),r.push(e),this.stmt(`UPDATE tenants SET ${o.join(", ")} WHERE id = ?`).run(r);let s=this.stmt("SELECT * FROM tenants WHERE id = ?").get(e);if(!s)throw new Error(`Tenant ${e} not found`);return{id:s.id,name:s.name,slug:s.slug,createdAt:s.created_at,updatedAt:s.updated_at}}async deleteTenant(e){this.stmt("DELETE FROM tenants WHERE id = ?").run(e)}async getSettings(e){let t=this.stmt("SELECT allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json FROM tenant_settings WHERE tenant_id = ?").get(e);return t?{allowedOrigins:JSON.parse(t.allowed_origins_json),adminAllowedOrigins:JSON.parse(t.admin_allowed_origins_json),setupCompleted:!!t.setup_completed,profilesSeeded:!!t.profiles_seeded,tcfConfirmation:t.tcf_confirmation_json?JSON.parse(t.tcf_confirmation_json):void 0,gppConfirmation:t.gpp_confirmation_json?JSON.parse(t.gpp_confirmation_json):void 0}:{}}async updateSettings(e,t){let o={...await this.getSettings(e),...t};return this.stmt(`INSERT INTO tenant_settings (tenant_id, allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json, updated_at) VALUES (?,?,?,?,?,?,?,?)
62
+ ON CONFLICT(tenant_id) DO UPDATE SET allowed_origins_json = excluded.allowed_origins_json, admin_allowed_origins_json = excluded.admin_allowed_origins_json, setup_completed = excluded.setup_completed, profiles_seeded = excluded.profiles_seeded, tcf_confirmation_json = excluded.tcf_confirmation_json, gpp_confirmation_json = excluded.gpp_confirmation_json, updated_at = excluded.updated_at`).run([e,JSON.stringify(o.allowedOrigins??[]),JSON.stringify(o.adminAllowedOrigins??[]),o.setupCompleted?1:0,o.profilesSeeded?1:0,o.tcfConfirmation?JSON.stringify(o.tcfConfirmation):null,o.gppConfirmation?JSON.stringify(o.gppConfirmation):null,new Date().toISOString()]),this.getSettings(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=this.stmt("SELECT visitor_id FROM consent_records WHERE created_at < ?").all(t);for(let{visitor_id:o}of n)this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(o),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(o);return n.length}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active===1,...e.created_by!==null?{createdBy:e.created_by}:{},...e.expire_by!==null?{expireBy:e.expire_by}:{},createdAt:e.created_at,...e.updated_at!==null?{updatedAt:e.updated_at}:{}}}async createApiKey(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO api_keys (id,tenant_id,key_hash,name,created_by,expire_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run([t,e.tenantId,e.keyHash,e.name,e.createdBy??null,e.expireBy??null,n,n]);let o=this.stmt("SELECT * FROM api_keys WHERE id = ?").get(t);if(!o)throw new Error("Failed to create API key");return this.mapApiKey(o)}async getApiKeyByHash(e){let t=this.stmt("SELECT * FROM api_keys WHERE key_hash = ? AND is_active = 1").get(e);return t?this.mapApiKey(t):null}async revokeApiKey(e){this.stmt("UPDATE api_keys SET is_active = 0, updated_at = ? WHERE id = ?").run([new Date().toISOString(),e])}async reactivateApiKey(e){let t=new Date().toISOString();this.stmt("UPDATE api_keys SET is_active = 1, updated_at = ?, expire_by = CASE WHEN expire_by <= ? THEN NULL ELSE expire_by END WHERE id = ?").run([t,t,e])}async deleteApiKey(e){this.stmt("DELETE FROM api_keys WHERE id = ?").run([e])}async getApiKeys(e){return this.stmt("SELECT * FROM api_keys WHERE tenant_id = ? ORDER BY created_at DESC").all(e).map(n=>this.mapApiKey(n))}mapConsentTemplate(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,cookies:JSON.parse(e.cookies_json),categories:JSON.parse(e.categories_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createConsentTemplate(e){let t=_e(),n=new Date().toISOString();return this.stmt("INSERT INTO consent_templates (id,tenant_id,name,cookies_json,categories_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?)").run([t,e.tenantId,e.name,JSON.stringify(e.cookies),JSON.stringify(e.categories),n,n]),this.mapConsentTemplate(this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(t))}async updateConsentTemplate(e,t){let n=new Date().toISOString();t.name!==void 0&&this.stmt("UPDATE consent_templates SET name = ?, updated_at = ? WHERE id = ?").run([t.name,n,e]),t.cookies!==void 0&&this.stmt("UPDATE consent_templates SET cookies_json = ?, updated_at = ? WHERE id = ?").run([JSON.stringify(t.cookies),n,e]),t.categories!==void 0&&this.stmt("UPDATE consent_templates SET categories_json = ?, updated_at = ? WHERE id = ?").run([JSON.stringify(t.categories),n,e]);let o=this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(e);if(!o)throw new Error("Consent template not found");return this.mapConsentTemplate(o)}async deleteConsentTemplate(e){this.stmt("DELETE FROM consent_templates WHERE id = ?").run(e)}async getConsentTemplate(e){let t=this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(e);return t?this.mapConsentTemplate(t):null}async getConsentTemplates(e){return this.stmt("SELECT * FROM consent_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapConsentTemplate(n))}async copyConsentTemplate(e,t){let n=await this.getConsentTemplate(e);if(!n)throw new Error("Consent template not found");return this.createConsentTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies,categories:n.categories})}mapUITemplate(e){let t=JSON.parse(e.settings_json);return{id:e.id,tenantId:e.tenant_id,name:e.name,...t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUITemplate(e){let t=we(),n=new Date().toISOString(),{tenantId:o,name:r,...s}=e;return this.stmt("INSERT INTO ui_templates (id,tenant_id,name,settings_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run([t,o,r,JSON.stringify(s),n,n]),this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(t))}async updateUITemplate(e,t){let n=new Date().toISOString(),o=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);if(!o)throw new Error("UI template not found");t.name!==void 0&&this.stmt("UPDATE ui_templates SET name = ?, updated_at = ? WHERE id = ?").run([t.name,n,e]);let{name:r,...s}=t;if(Object.keys(s).length>0){let c={...JSON.parse(o.settings_json),...s};this.stmt("UPDATE ui_templates SET settings_json = ?, updated_at = ? WHERE id = ?").run([JSON.stringify(c),n,e])}return this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e))}async deleteUITemplate(e){this.stmt("DELETE FROM ui_templates WHERE id = ?").run(e)}async getUITemplate(e){let t=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);return t?this.mapUITemplate(t):null}async getUITemplates(e){return this.stmt("SELECT * FROM ui_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapUITemplate(n))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:o,mainBanner:r,gpcBanner:s,preferenceModal:a}=n;return this.createUITemplate({tenantId:o,name:t,mainBanner:r,gpcBanner:s,preferenceModal:a})}mapProfileSummary(e){return{id:e.id,name:e.name,defaultLocale:e.default_locale,complianceGroup:e.compliance_group??null,customComplianceGroup:e.custom_compliance_group??null,isActive:e.is_active===1,consentTemplateName:e.consent_template_name,uiTemplateName:e.ui_template_name,createdAt:e.created_at,updatedAt:e.updated_at}}PROFILE_SUMMARY_SQL=`
72
63
  SELECT
73
- p.id, p.name, p.default_locale, p.version, p.created_at, p.updated_at,
64
+ p.id, p.name, p.default_locale, p.created_at, p.updated_at,
74
65
  json_extract(p.profile_json, '$.complianceGroup') AS compliance_group,
66
+ json_extract(p.profile_json, '$.customComplianceGroup') AS custom_compliance_group,
75
67
  json_extract(p.profile_json, '$.isActive') AS is_active,
76
- json_extract(p.profile_json, '$.cookieTemplateId') AS cookie_template_id,
68
+ json_extract(p.profile_json, '$.consentTemplateId') AS consent_template_id,
77
69
  json_extract(p.profile_json, '$.uiTemplateId') AS ui_template_id,
78
- ct.name AS cookie_template_name,
70
+ ct.name AS consent_template_name,
79
71
  ut.name AS ui_template_name
80
72
  FROM profiles p
81
- LEFT JOIN cookie_templates ct ON ct.id = json_extract(p.profile_json, '$.cookieTemplateId')
73
+ LEFT JOIN consent_templates ct ON ct.id = json_extract(p.profile_json, '$.consentTemplateId')
82
74
  LEFT JOIN ui_templates ut ON ut.id = json_extract(p.profile_json, '$.uiTemplateId')
83
- `;async listProfilesSummary(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE p.tenant_id = ? ORDER BY p.created_at ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingCookieTemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.cookieTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingUITemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.uiTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async getOptInStats(e,t){let n=["cr.tenant_id = ?"],i=[e];t.profileId&&(n.push("cr.profile_id = ?"),i.push(t.profileId)),t.from&&(n.push("cr.created_at >= ?"),i.push(t.from)),t.to&&(n.push("cr.created_at <= ?"),i.push(t.to)),t.locale&&(n.push("cr.locale = ?"),i.push(t.locale));let o=n.join(" AND "),r=this.stmt(`SELECT cr.locale, cr.consent_json FROM consent_records cr WHERE ${o}`).all(i),a=0,c=0,l=0,u=0,d={};for(let f of r){let _=Object.values(JSON.parse(f.consent_json)),h=_.length>0?_.filter(I=>I==="granted").length/_.length:0,A=_.length>0?_.filter(I=>I==="denied").length/_.length:0;a++;let T=f.locale;d[T]||(d[T]={total:0,granted:0,denied:0,managed:0}),d[T].total++,h>=.9?(c++,d[T].granted++):A>=.9?(l++,d[T].denied++):(u++,d[T].managed++)}let p=this.stmt(`SELECT date(cr.created_at) as d, cr.consent_json FROM consent_records cr WHERE ${o} ORDER BY d ASC`).all(i),E=new Map;for(let f of p){let _=E.get(f.d)??{total:0,granted:0,denied:0,managed:0},h=Object.values(JSON.parse(f.consent_json)),A=h.length>0?h.filter(I=>I==="granted").length/h.length:0,T=h.length>0?h.filter(I=>I==="denied").length/h.length:0;_.total++,A>=.9?_.granted++:T>=.9?_.denied++:_.managed++,E.set(f.d,_)}let S=Array.from(E.entries()).map(([f,_])=>({date:f,..._}));return{total:a,granted:c,denied:l,managed:u,grantedPct:a>0?Math.round(c/a*1e3)/10:0,deniedPct:a>0?Math.round(l/a*1e3)/10:0,managedPct:a>0?Math.round(u/a*1e3)/10:0,byLocale:d,byDate:S}}};var Mt=500,Ke=class{constructor(e){this.config=e}config;db;cache=new Map;stmt(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}async connect(){let{DatabaseSync:e}=await import("sqlite").catch(()=>{throw new Error(`driver 'node:sqlite' requires Node.js >= 22.5.0 (current: ${process.version})`)}),{dbPath:t}=Q(this.config.path??"./consenti-data","node:sqlite");this.db=new e(t),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA foreign_keys=ON"),this.db.exec("PRAGMA synchronous=NORMAL"),await this.migrate()}async disconnect(){this.cache.clear(),this.db.close()}async migrate(){let e=this.db.prepare("PRAGMA user_version").get();e.user_version<1&&(this.db.exec(ue),this.db.exec(fe),this.db.exec("PRAGMA user_version = 1")),e.user_version<2&&(this.db.exec(pe),this.db.exec("PRAGMA user_version = 2")),e.user_version<3&&(this.db.exec(me),this.db.exec("PRAGMA user_version = 3")),e.user_version<4&&(this.db.exec("ALTER TABLE user_roles ADD COLUMN tenant_id TEXT NOT NULL DEFAULT 'default'"),this.db.exec("PRAGMA user_version = 4")),e.user_version<5&&(this.db.exec(ge),this.db.exec("PRAGMA user_version = 5")),e.user_version<6&&(this.db.exec("ALTER TABLE users ADD COLUMN allowed_tenants TEXT"),this.db.exec("PRAGMA user_version = 6")),this.db.exec(`
75
+ `;async listProfilesSummary(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE p.tenant_id = ? ORDER BY p.created_at ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingConsentTemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.consentTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingUITemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.uiTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async getOptInStats(e,t){let n=["cr.tenant_id = ?"],o=[e];t.profileId&&(n.push("cr.profile_id = ?"),o.push(t.profileId)),t.from&&(n.push("cr.created_at >= ?"),o.push(t.from)),t.to&&(n.push("cr.created_at <= ?"),o.push(t.to)),t.locale&&(n.push("cr.locale = ?"),o.push(t.locale));let r=n.join(" AND "),s=this.stmt(`SELECT cr.locale, cr.consent_json FROM consent_records cr WHERE ${r}`).all(o),a=0,c=0,l=0,d=0,u={};for(let _ of s){let w=Object.values(JSON.parse(_.consent_json)),R=w.length>0?w.filter(P=>P==="granted").length/w.length:0,v=w.length>0?w.filter(P=>P==="denied").length/w.length:0;a++;let A=_.locale;u[A]||(u[A]={total:0,granted:0,denied:0,managed:0}),u[A].total++,R>=.9?(c++,u[A].granted++):v>=.9?(l++,u[A].denied++):(d++,u[A].managed++)}let m=this.stmt(`SELECT date(cr.created_at) as d, cr.consent_json FROM consent_records cr WHERE ${r} ORDER BY d ASC`).all(o),h=new Map;for(let _ of m){let w=h.get(_.d)??{total:0,granted:0,denied:0,managed:0},R=Object.values(JSON.parse(_.consent_json)),v=R.length>0?R.filter(P=>P==="granted").length/R.length:0,A=R.length>0?R.filter(P=>P==="denied").length/R.length:0;w.total++,v>=.9?w.granted++:A>=.9?w.denied++:w.managed++,h.set(_.d,w)}let S=Array.from(h.entries()).map(([_,w])=>({date:_,...w}));return{total:a,granted:c,denied:l,managed:d,grantedPct:a>0?Math.round(c/a*1e3)/10:0,deniedPct:a>0?Math.round(l/a*1e3)/10:0,managedPct:a>0?Math.round(d/a*1e3)/10:0,byLocale:u,byDate:S}}};p();var Mn=500,wt=class i{constructor(e){this.config=e}config;db;cache=new Map;stmt(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}async connect(){let{DatabaseSync:e}=await import("node:sqlite").catch(()=>{throw new Error(`driver 'node:sqlite' requires Node.js >= 22.5.0 (current: ${process.version})`)}),{dbPath:t}=ue(this.config.path??"./consenti-data","node:sqlite");this.db=new e(t),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA foreign_keys=ON"),this.db.exec("PRAGMA synchronous=NORMAL"),await this.migrate()}async disconnect(){this.cache.clear(),this.db.close()}async migrate(){this.db.prepare("PRAGMA user_version").get().user_version<1&&(this.db.exec(Oe),this.db.exec(De),this.db.exec("PRAGMA user_version = 1")),this.db.exec(`
84
76
  CREATE INDEX IF NOT EXISTS idx_profiles_tenant_compliance_active
85
77
  ON profiles (tenant_id, json_extract(profile_json,'$.complianceGroup'), json_extract(profile_json,'$.isActive'));
86
- CREATE INDEX IF NOT EXISTS idx_profiles_tenant
87
- ON profiles (tenant_id);
88
- CREATE INDEX IF NOT EXISTS idx_consents_tenant_profile_date
89
- ON consent_records (tenant_id, profile_id, created_at);
90
- CREATE INDEX IF NOT EXISTS idx_consents_visitor
91
- ON consent_records (visitor_id);
92
- CREATE INDEX IF NOT EXISTS idx_visitors_tenant
93
- ON visitors (tenant_id);
94
- CREATE INDEX IF NOT EXISTS idx_audit_tenant_date
95
- ON audit_logs (tenant_id, created_at);
96
- `)}mapProfile(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,defaultLocale:e.default_locale,version:e.version,profileJson:JSON.parse(e.profile_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createProfile(e){let t=de(),n=new Date().toISOString();this.stmt("INSERT INTO profiles (id,tenant_id,name,default_locale,profile_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.defaultLocale,JSON.stringify(e.profileJson),n,n);let i=await this.getProfile(t);if(!i)throw new Error("Failed to create profile");return i}async updateProfile(e,t){if(!await this.getProfile(e))throw new Error(`Profile ${e} not found`);let i=new Date().toISOString(),o=["updated_at = ?","version = version + 1"],r=[i];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.defaultLocale!=null&&(o.push("default_locale = ?"),r.push(t.defaultLocale)),t.profileJson!=null&&(o.push("profile_json = ?"),r.push(JSON.stringify(t.profileJson))),r.push(e),this.stmt(`UPDATE profiles SET ${o.join(", ")} WHERE id = ?`).run(...r);let a=await this.getProfile(e);if(!a)throw new Error("Failed to update profile");return a}async deleteProfile(e){this.stmt("DELETE FROM profiles WHERE id = ?").run(e)}async getProfile(e){let t=this.stmt("SELECT * FROM profiles WHERE id = ?").get(e);return t?this.mapProfile(t):null}async getProfiles(e){return this.stmt("SELECT * FROM profiles WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapProfile(n))}async findActiveProfileByComplianceGroup(e,t){let n=this.stmt("SELECT * FROM profiles WHERE tenant_id = ? AND json_extract(profile_json, '$.complianceGroup') = ? AND json_extract(profile_json, '$.isActive') = 1 LIMIT 1").get(e,t);return n?this.mapProfile(n):null}mapConsent(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,profileVersion:e.profile_version,locale:e.locale,consentJson:JSON.parse(e.consent_json),gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},...e.parental_consent_token!=null?{parentalConsentToken:e.parental_consent_token}:{},...e.tcf_string!=null?{tcfString:e.tcf_string}:{},createdAt:e.created_at,updatedAt:e.updated_at}}async createConsent(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO consent_records (id,tenant_id,visitor_id,profile_id,profile_version,locale,consent_json,gpc_detected,source,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.profileId,e.profileVersion,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source,n,n);let i=(0,w.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(i,e.tenantId,t,e.visitorId,null,JSON.stringify(e.consentJson),"created",n);let o=await this.getConsent(e.visitorId);if(!o)throw new Error("Failed to create consent");return o}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let i=new Date().toISOString(),o=["updated_at = ?","consent_json = ?"],r=[i,JSON.stringify(t.consentJson)];t.locale!=null&&(o.push("locale = ?"),r.push(t.locale)),t.gpcDetected!=null&&(o.push("gpc_detected = ?"),r.push(t.gpcDetected?1:0)),r.push(e),this.stmt(`UPDATE consent_records SET ${o.join(", ")} WHERE visitor_id = ?`).run(...r);let a=(0,w.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(a,n.tenantId,n.id,e,JSON.stringify(n.consentJson),JSON.stringify(t.consentJson),"updated",i);let c=await this.getConsent(e);if(!c)throw new Error("Failed to update consent");return c}async deleteConsent(e){this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(e),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(e)}async getConsent(e){let t=this.stmt("SELECT * FROM consent_records WHERE visitor_id = ?").get(e);return t?this.mapConsent(t):null}async getConsents(e){let t=["tenant_id = ?"],n=[e.tenantId];e.profileId&&(t.push("profile_id = ?"),n.push(e.profileId)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=Math.min(e.limit??50,Mt),o=((e.page??1)-1)*i;return n.push(i,o),this.stmt(`SELECT * FROM consent_records WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n).map(a=>this.mapConsent(a))}async*streamConsents(e){let n=0;for(;;){let i=this.stmt("SELECT * FROM consent_records WHERE tenant_id = ? LIMIT ? OFFSET ?").all(e.tenantId,500,n);if(i.length===0)break;for(let o of i)yield this.mapConsent(o);n+=500}}async getConsentHistory(e){return this.stmt("SELECT * FROM consent_history WHERE visitor_id = ? ORDER BY created_at ASC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,consentRecordId:n.consent_record_id,visitorId:n.visitor_id,oldJson:n.old_json!=null?JSON.parse(n.old_json):null,newJson:JSON.parse(n.new_json),action:n.action,createdAt:n.created_at}))}mapVisitor(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,firstSeen:e.first_seen,lastSeen:e.last_seen,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip_hash!=null?{ipHash:e.ip_hash}:{},...e.user_agent_hash!=null?{userAgentHash:e.user_agent_hash}:{}}}async createVisitor(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO visitors (id,tenant_id,visitor_id,country,region,city,ip_hash,user_agent_hash,first_seen,last_seen) VALUES (?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null,n,n);let i=await this.getVisitor(e.visitorId);if(!i)throw new Error("Failed to create visitor");return i}async updateVisitor(e,t){let n=new Date().toISOString(),i=["last_seen = ?"],o=[t.lastSeen??n];t.country!=null&&(i.push("country = ?"),o.push(t.country)),t.region!=null&&(i.push("region = ?"),o.push(t.region)),t.city!=null&&(i.push("city = ?"),o.push(t.city)),o.push(e),this.stmt(`UPDATE visitors SET ${i.join(", ")} WHERE visitor_id = ?`).run(...o);let r=await this.getVisitor(e);if(!r)throw new Error(`Visitor ${e} not found`);return r}async deleteVisitor(e){this.stmt("DELETE FROM visitors WHERE visitor_id = ?").run(e)}async getVisitor(e){let t=this.stmt("SELECT * FROM visitors WHERE visitor_id = ?").get(e);return t?this.mapVisitor(t):null}async getVisitors(e){let t=["tenant_id = ?"],n=[e.tenantId];e.from&&(t.push("first_seen >= ?"),n.push(e.from)),e.to&&(t.push("first_seen <= ?"),n.push(e.to));let i=Math.min(e.limit??50,Mt),o=((e.page??1)-1)*i;return n.push(i,o),this.stmt(`SELECT * FROM visitors WHERE ${t.join(" AND ")} ORDER BY last_seen DESC LIMIT ? OFFSET ?`).all(...n).map(a=>this.mapVisitor(a))}mapUser(e){let t=e.allowed_tenants?JSON.parse(e.allowed_tenants):[];return{id:e.id,tenantId:e.tenant_id,name:e.name,email:e.email,passwordHash:e.password_hash,isActive:e.is_active===1,totpEnabled:e.totp_enabled===1,...e.totp_secret!=null?{totpSecret:e.totp_secret}:{},allowedTenants:t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUser(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),i=e.allowedTenants?.length?JSON.stringify(e.allowedTenants):null;this.stmt("INSERT INTO users (id,tenant_id,name,email,password_hash,allowed_tenants,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.email,e.passwordHash,i,n,n);let o=await this.getUserByEmail(e.email);if(!o)throw new Error("Failed to create user");return o}async updateUser(e,t){let n=new Date().toISOString(),i=["updated_at = ?"],o=[n];t.name!=null&&(i.push("name = ?"),o.push(t.name)),t.email!=null&&(i.push("email = ?"),o.push(t.email)),t.passwordHash!=null&&(i.push("password_hash = ?"),o.push(t.passwordHash)),t.isActive!=null&&(i.push("is_active = ?"),o.push(t.isActive?1:0)),"totpSecret"in t&&(i.push("totp_secret = ?"),o.push(t.totpSecret??null)),t.totpEnabled!=null&&(i.push("totp_enabled = ?"),o.push(t.totpEnabled?1:0)),"allowedTenants"in t&&(i.push("allowed_tenants = ?"),o.push(t.allowedTenants?.length?JSON.stringify(t.allowedTenants):null)),o.push(e),this.stmt(`UPDATE users SET ${i.join(", ")} WHERE id = ?`).run(...o);let r=this.stmt("SELECT * FROM users WHERE id = ?").get(e);if(!r)throw new Error(`User ${e} not found`);return this.mapUser(r)}async deleteUser(e){this.stmt("DELETE FROM user_roles WHERE user_id = ?").run(e),this.stmt("DELETE FROM users WHERE id = ?").run(e)}async getUserById(e){let t=this.stmt("SELECT * FROM users WHERE id = ?").get(e);return t?this.mapUser(t):null}async getUserByEmail(e){let t=this.stmt("SELECT * FROM users WHERE email = ?").get(e);return t?this.mapUser(t):null}async getUsers(e){return this.stmt("SELECT * FROM users WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapUser(n))}async countUsers(e){return(e?this.stmt("SELECT COUNT(*) as n FROM users WHERE tenant_id = ?").get(e):this.stmt("SELECT COUNT(*) as n FROM users").get())?.n??0}async getRoles(e){return this.stmt("SELECT * FROM roles WHERE tenant_id = ?").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async createRole(e){let t=(0,w.randomUUID)();this.stmt("INSERT INTO roles (id,tenant_id,name,description) VALUES (?,?,?,?)").run(t,e.tenantId,e.name,e.description??null);let n=this.stmt("SELECT * FROM roles WHERE id = ?").get(t);if(!n)throw new Error("Failed to create role");return{id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}}async updateRole(e,t){let n=[],i=[];t.name!=null&&(n.push("name = ?"),i.push(t.name)),t.description!=null&&(n.push("description = ?"),i.push(t.description)),n.length>0&&(i.push(e),this.stmt(`UPDATE roles SET ${n.join(", ")} WHERE id = ?`).run(...i));let o=this.stmt("SELECT * FROM roles WHERE id = ?").get(e);if(!o)throw new Error(`Role ${e} not found`);return{id:o.id,tenantId:o.tenant_id,name:o.name,...o.description!=null?{description:o.description}:{}}}async deleteRole(e){this.stmt("DELETE FROM role_permissions WHERE role_id = ?").run(e),this.stmt("DELETE FROM user_roles WHERE role_id = ?").run(e),this.stmt("DELETE FROM roles WHERE id = ?").run(e)}async getAllPermissions(){return this.stmt("SELECT * FROM permissions ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,...t.description!=null?{description:t.description}:{}}))}async assignPermissionToRole(e,t){this.stmt("INSERT OR IGNORE INTO role_permissions (role_id,permission_id) VALUES (?,?)").run(e,t)}async revokePermissionFromRole(e,t){this.stmt("DELETE FROM role_permissions WHERE role_id = ? AND permission_id = ?").run(e,t)}async getPermissionsForRole(e){return this.stmt("SELECT p.* FROM permissions p JOIN role_permissions rp ON rp.permission_id = p.id WHERE rp.role_id = ?").all(e).map(n=>({id:n.id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async getUserRoles(e,t){return(t?this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.tenant_id = ?").all(e,t):this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?").all(e)).map(i=>({id:i.id,tenantId:i.tenant_id,name:i.name,...i.description!=null?{description:i.description}:{}}))}async assignRole(e,t,n="default"){this.stmt("INSERT OR IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)").run(e,t,n)}async revokeRole(e,t,n){n?this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ? AND tenant_id = ?").run(e,t,n):this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?").run(e,t)}async createLog(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO audit_logs (id,tenant_id,user_id,action,resource_type,resource_id,old_data,new_data,created_at) VALUES (?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null,n)}async getLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.resourceType&&(t.push("resource_type = ?"),n.push(e.resourceType)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=Math.min(e.limit??50,Mt),o=((e.page??1)-1)*i;return n.push(i,o),this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n).map(a=>this.mapAuditLog(a))}mapAuditLog(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,createdAt:e.created_at,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},...e.old_data!=null?{oldData:JSON.parse(e.old_data)}:{},...e.new_data!=null?{newData:JSON.parse(e.new_data)}:{}}}async*streamAuditLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let i=500,o=0;for(;;){let r=this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,i,o);if(r.length===0)break;for(let a of r)yield this.mapAuditLog(a);o+=i}}async getOverviewStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),i=this.stmt("SELECT COUNT(*) as n FROM visitors WHERE tenant_id = ?").get(e),o=t?.n??0,r=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 500").all(e),a=0,c=0;for(let u of r){let d=Object.values(JSON.parse(u.consent_json)),p=d.length>0?d.filter(E=>E==="granted").length/d.length:0;p>=.8?a++:p<=.2&&c++}let l=r.length||1;return{totalConsents:o,gpcDetectedCount:n?.n??0,totalVisitors:i?.n??0,acceptedPct:Math.round(a/l*100),rejectedPct:Math.round(c/l*100)}}async getCategoryStats(e){let t=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? LIMIT 5000").all(e),n={};for(let i of t){let o=JSON.parse(i.consent_json);for(let[r,a]of Object.entries(o))n[r]||(n[r]={granted:0,denied:0,objected:0}),a==="granted"?n[r].granted++:a==="denied"?n[r].denied++:a==="objected"&&n[r].objected++}return n}async getTimeline(e,t=30){return this.stmt("SELECT date(created_at) as date, COUNT(*) as count FROM consent_records WHERE tenant_id = ? AND created_at >= date('now', ?) GROUP BY date(created_at) ORDER BY date ASC").all(e,`-${t} days`).map(i=>({date:i.date,count:i.count}))}async getCountries(e){return this.stmt("SELECT v.country, COUNT(*) as count FROM consent_records cr JOIN visitors v ON v.visitor_id = cr.visitor_id WHERE cr.tenant_id = ? AND v.country IS NOT NULL GROUP BY v.country ORDER BY count DESC LIMIT 50").all(e).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),i=t?.n??0,o=n?.n??0;return{detected:o,total:i,rate:i>0?Math.round(o/i*100):0}}async getTenants(){return this.stmt("SELECT * FROM tenants ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createTenant(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO tenants (id,name,slug,created_at,updated_at) VALUES (?,?,?,?,?)").run(t,e.name,e.slug,n,n);let i=this.stmt("SELECT * FROM tenants WHERE id = ?").get(t);if(!i)throw new Error("Failed to create tenant");return{id:i.id,name:i.name,slug:i.slug,createdAt:i.created_at,updatedAt:i.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),i=["updated_at = ?"],o=[n];t.name!=null&&(i.push("name = ?"),o.push(t.name)),t.slug!=null&&(i.push("slug = ?"),o.push(t.slug)),o.push(e),this.stmt(`UPDATE tenants SET ${i.join(", ")} WHERE id = ?`).run(...o);let r=this.stmt("SELECT * FROM tenants WHERE id = ?").get(e);if(!r)throw new Error(`Tenant ${e} not found`);return{id:r.id,name:r.name,slug:r.slug,createdAt:r.created_at,updatedAt:r.updated_at}}async deleteTenant(e){this.stmt("DELETE FROM tenants WHERE id = ?").run(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=this.stmt("SELECT visitor_id FROM consent_records WHERE created_at < ?").all(t);for(let{visitor_id:i}of n)this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(i),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(i);return n.length}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active===1,createdAt:e.created_at}}async createApiKey(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO api_keys (id,tenant_id,key_hash,name,created_at) VALUES (?,?,?,?,?)").run(t,e.tenantId,e.keyHash,e.name,n);let i=this.stmt("SELECT * FROM api_keys WHERE id = ?").get(t);if(!i)throw new Error("Failed to create API key");return this.mapApiKey(i)}async getApiKeyByHash(e){let t=this.stmt("SELECT * FROM api_keys WHERE key_hash = ? AND is_active = 1").get(e);return t?this.mapApiKey(t):null}async revokeApiKey(e){this.stmt("UPDATE api_keys SET is_active = 0 WHERE id = ?").run(e)}async getApiKeys(e){return this.stmt("SELECT * FROM api_keys WHERE tenant_id = ? ORDER BY created_at DESC").all(e).map(n=>this.mapApiKey(n))}mapCookieTemplate(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,cookies:JSON.parse(e.cookies_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createCookieTemplate(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();return this.stmt("INSERT INTO cookie_templates (id,tenant_id,name,cookies_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run(t,e.tenantId,e.name,JSON.stringify(e.cookies),n,n),this.mapCookieTemplate(this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(t))}async updateCookieTemplate(e,t){let n=new Date().toISOString();t.name!==void 0&&this.stmt("UPDATE cookie_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e),t.cookies!==void 0&&this.stmt("UPDATE cookie_templates SET cookies_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t.cookies),n,e);let i=this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(e);if(!i)throw new Error("Cookie template not found");return this.mapCookieTemplate(i)}async deleteCookieTemplate(e){this.stmt("DELETE FROM cookie_templates WHERE id = ?").run(e)}async getCookieTemplate(e){let t=this.stmt("SELECT * FROM cookie_templates WHERE id = ?").get(e);return t?this.mapCookieTemplate(t):null}async getCookieTemplates(e){return this.stmt("SELECT * FROM cookie_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapCookieTemplate(n))}async copyCookieTemplate(e,t){let n=await this.getCookieTemplate(e);if(!n)throw new Error("Cookie template not found");return this.createCookieTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies})}mapUITemplate(e){let t=JSON.parse(e.settings_json);return{id:e.id,tenantId:e.tenant_id,name:e.name,...t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUITemplate(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),{tenantId:i,name:o,...r}=e;return this.stmt("INSERT INTO ui_templates (id,tenant_id,name,settings_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run(t,i,o,JSON.stringify(r),n,n),this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(t))}async updateUITemplate(e,t){let n=new Date().toISOString(),i=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);if(!i)throw new Error("UI template not found");t.name!==void 0&&this.stmt("UPDATE ui_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e);let{name:o,...r}=t;if(Object.keys(r).length>0){let c={...JSON.parse(i.settings_json),...r};this.stmt("UPDATE ui_templates SET settings_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(c),n,e)}return this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e))}async deleteUITemplate(e){this.stmt("DELETE FROM ui_templates WHERE id = ?").run(e)}async getUITemplate(e){let t=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);return t?this.mapUITemplate(t):null}async getUITemplates(e){return this.stmt("SELECT * FROM ui_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapUITemplate(n))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:i,mainBanner:o,gpcBanner:r,preferenceModal:a}=n;return this.createUITemplate({tenantId:i,name:t,mainBanner:o,gpcBanner:r,preferenceModal:a})}mapProfileSummary(e){return{id:e.id,name:e.name,defaultLocale:e.default_locale,complianceGroup:e.compliance_group??null,version:e.version,isActive:e.is_active===1,cookieTemplateName:e.cookie_template_name,uiTemplateName:e.ui_template_name,createdAt:e.created_at,updatedAt:e.updated_at}}PROFILE_SUMMARY_SQL=`
78
+ `)}mapProfile(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,defaultLocale:e.default_locale,version:e.version,profileJson:JSON.parse(e.profile_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createProfile(e){let t=z(),n=new Date().toISOString();this.stmt("INSERT INTO profiles (id,tenant_id,name,default_locale,version,profile_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.defaultLocale,1,JSON.stringify(e.profileJson),n,n);let o=await this.getProfile(t);if(!o)throw new Error("Failed to create profile");return o}async updateProfile(e,t){if(!await this.getProfile(e))throw new Error(`Profile ${e} not found`);let o=new Date().toISOString(),r=["updated_at = ?"],s=[o];t.name!=null&&(r.push("name = ?"),s.push(t.name)),t.defaultLocale!=null&&(r.push("default_locale = ?"),s.push(t.defaultLocale)),t.profileJson!=null&&(r.push("profile_json = ?"),s.push(JSON.stringify(t.profileJson))),t.version!=null&&(r.push("version = ?"),s.push(t.version)),s.push(e),this.stmt(`UPDATE profiles SET ${r.join(", ")} WHERE id = ?`).run(...s);let a=await this.getProfile(e);if(!a)throw new Error("Failed to update profile");return a}async deleteProfile(e){this.stmt("DELETE FROM profiles WHERE id = ?").run(e)}async getProfile(e){let t=this.stmt("SELECT * FROM profiles WHERE id = ?").get(e);return t?this.mapProfile(t):null}async getProfiles(e){return this.stmt("SELECT * FROM profiles WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapProfile(n))}async findActiveProfileByComplianceGroup(e,t){let n=this.stmt(`SELECT * FROM profiles WHERE tenant_id = ?
79
+ AND (json_extract(profile_json, '$.complianceGroup') = ? OR json_extract(profile_json, '$.customComplianceGroup') = ?)
80
+ AND json_extract(profile_json, '$.isActive') = 1 LIMIT 1`).get(e,t,t);return n?this.mapProfile(n):null}mapConsent(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,locale:e.locale,consentJson:JSON.parse(e.consent_json),gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},...e.parental_consent_token!=null?{parentalConsentToken:e.parental_consent_token}:{},...e.tcf_string!=null?{tcfString:e.tcf_string}:{},...e.gpp_string!=null?{gppString:e.gpp_string}:{},...e.signature!=null?{signature:e.signature}:{},createdAt:e.created_at,updatedAt:e.updated_at}}static CONSENT_SUMMARY_COLS="id, tenant_id, visitor_id, profile_id, locale, gpc_detected, source, age_verified, created_at, updated_at";mapConsentSummary(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,profileId:e.profile_id,locale:e.locale,gpcDetected:e.gpc_detected===1,source:e.source,...e.age_verified!=null&&e.age_verified!==0?{ageVerified:!0}:{},createdAt:e.created_at,updatedAt:e.updated_at}}async createConsent(e){let t=K(),n=new Date().toISOString();this.stmt("INSERT INTO consent_records (id,tenant_id,visitor_id,profile_id,locale,consent_json,gpc_detected,source,age_verified,parental_consent_token,tcf_string,gpp_string,signature,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.profileId,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source,e.ageVerified?1:0,e.parentalConsentToken??null,e.tcfString??null,e.gppString??null,e.signature??null,n,n);let o=(0,C.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(o,e.tenantId,t,e.visitorId,null,JSON.stringify(e.consentJson),"created",n);let r=await this.getConsent(e.visitorId);if(!r)throw new Error("Failed to create consent");return r}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let o=new Date().toISOString(),r=["updated_at = ?","consent_json = ?"],s=[o,JSON.stringify(t.consentJson)];t.locale!=null&&(r.push("locale = ?"),s.push(t.locale)),t.gpcDetected!=null&&(r.push("gpc_detected = ?"),s.push(t.gpcDetected?1:0)),t.signature!=null&&(r.push("signature = ?"),s.push(t.signature)),s.push(e),this.stmt(`UPDATE consent_records SET ${r.join(", ")} WHERE visitor_id = ?`).run(...s);let a=(0,C.randomUUID)();this.stmt("INSERT INTO consent_history (id,tenant_id,consent_record_id,visitor_id,old_json,new_json,action,created_at) VALUES (?,?,?,?,?,?,?,?)").run(a,n.tenantId,n.id,e,JSON.stringify(n.consentJson),JSON.stringify(t.consentJson),"updated",o);let c=await this.getConsent(e);if(!c)throw new Error("Failed to update consent");return c}async deleteConsent(e){this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(e),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(e)}async getConsent(e){let t=this.stmt("SELECT * FROM consent_records WHERE visitor_id = ?").get(e);return t?this.mapConsent(t):null}async getConsents(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.profileId&&(t.push("profile_id = ?"),n.push(e.profileId)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to)),e.q){t.push("(visitor_id LIKE ? OR profile_id LIKE ? OR locale LIKE ? OR source LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d,d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,Mn),a=(r-1)*s,c=this.stmt(`SELECT ${i.CONSENT_SUMMARY_COLS} FROM consent_records WHERE ${o} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,s,a),l=this.stmt(`SELECT COUNT(*) AS total FROM consent_records WHERE ${o}`).get(...n);return{items:c.map(d=>this.mapConsentSummary(d)),total:l.total,page:r,limit:s}}async*streamConsents(e){let n=0;for(;;){let o=this.stmt("SELECT * FROM consent_records WHERE tenant_id = ? LIMIT ? OFFSET ?").all(e.tenantId,500,n);if(o.length===0)break;for(let r of o)yield this.mapConsent(r);n+=500}}async getConsentHistory(e){return this.stmt("SELECT * FROM consent_history WHERE visitor_id = ? ORDER BY created_at ASC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,consentRecordId:n.consent_record_id,visitorId:n.visitor_id,oldJson:n.old_json!=null?JSON.parse(n.old_json):null,newJson:JSON.parse(n.new_json),action:n.action,createdAt:n.created_at}))}async createNoticeShown(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();return this.stmt("INSERT INTO notice_shown (id,tenant_id,visitor_id,profile_id,locale,created_at) VALUES (?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.profileId,e.locale,n),{id:t,tenantId:e.tenantId,visitorId:e.visitorId,profileId:e.profileId,locale:e.locale,createdAt:n}}async getNoticeShownForVisitor(e){return this.stmt("SELECT * FROM notice_shown WHERE visitor_id = ? ORDER BY created_at DESC").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,visitorId:n.visitor_id,profileId:n.profile_id,locale:n.locale,createdAt:n.created_at}))}mapVisitor(e){return{id:e.id,tenantId:e.tenant_id,visitorId:e.visitor_id,firstSeen:e.first_seen,lastSeen:e.last_seen,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip_hash!=null?{ipHash:e.ip_hash}:{},...e.user_agent_hash!=null?{userAgentHash:e.user_agent_hash}:{}}}async createVisitor(e){let t=q(),n=new Date().toISOString();this.stmt("INSERT INTO visitors (id,tenant_id,visitor_id,country,region,city,ip_hash,user_agent_hash,first_seen,last_seen) VALUES (?,?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null,n,n);let o=await this.getVisitor(e.visitorId);if(!o)throw new Error("Failed to create visitor");return o}async updateVisitor(e,t){let n=new Date().toISOString(),o=["last_seen = ?"],r=[t.lastSeen??n];t.country!=null&&(o.push("country = ?"),r.push(t.country)),t.region!=null&&(o.push("region = ?"),r.push(t.region)),t.city!=null&&(o.push("city = ?"),r.push(t.city)),r.push(e),this.stmt(`UPDATE visitors SET ${o.join(", ")} WHERE visitor_id = ?`).run(...r);let s=await this.getVisitor(e);if(!s)throw new Error(`Visitor ${e} not found`);return s}async deleteVisitor(e){this.stmt("DELETE FROM visitors WHERE visitor_id = ?").run(e)}async getVisitor(e){let t=this.stmt("SELECT * FROM visitors WHERE visitor_id = ?").get(e);return t?this.mapVisitor(t):null}async getVisitors(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.from&&(t.push("first_seen >= ?"),n.push(e.from)),e.to&&(t.push("first_seen <= ?"),n.push(e.to)),e.q){t.push("(visitor_id LIKE ? OR country LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,Mn),a=(r-1)*s,c=this.stmt(`SELECT * FROM visitors WHERE ${o} ORDER BY last_seen DESC LIMIT ? OFFSET ?`).all(...n,s,a),l=this.stmt(`SELECT COUNT(*) AS total FROM visitors WHERE ${o}`).get(...n);return{items:c.map(d=>this.mapVisitor(d)),total:l.total,page:r,limit:s}}mapUser(e){let t=e.allowed_tenants?JSON.parse(e.allowed_tenants):[];return{id:e.id,tenantId:e.tenant_id,name:e.name,email:e.email,passwordHash:e.password_hash,isActive:e.is_active===1,totpEnabled:e.totp_enabled===1,...e.totp_secret!=null?{totpSecret:e.totp_secret}:{},allowedTenants:t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUser(e){let t=(0,C.randomUUID)(),n=new Date().toISOString(),o=e.allowedTenants?.length?JSON.stringify(e.allowedTenants):null;this.stmt("INSERT INTO users (id,tenant_id,name,email,password_hash,allowed_tenants,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,e.email,e.passwordHash,o,n,n);let r=await this.getUserByEmail(e.email);if(!r)throw new Error("Failed to create user");return r}async updateUser(e,t){let n=new Date().toISOString(),o=["updated_at = ?"],r=[n];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.email!=null&&(o.push("email = ?"),r.push(t.email)),t.passwordHash!=null&&(o.push("password_hash = ?"),r.push(t.passwordHash)),t.isActive!=null&&(o.push("is_active = ?"),r.push(t.isActive?1:0)),"totpSecret"in t&&(o.push("totp_secret = ?"),r.push(t.totpSecret??null)),t.totpEnabled!=null&&(o.push("totp_enabled = ?"),r.push(t.totpEnabled?1:0)),"allowedTenants"in t&&(o.push("allowed_tenants = ?"),r.push(t.allowedTenants?.length?JSON.stringify(t.allowedTenants):null)),r.push(e),this.stmt(`UPDATE users SET ${o.join(", ")} WHERE id = ?`).run(...r);let s=this.stmt("SELECT * FROM users WHERE id = ?").get(e);if(!s)throw new Error(`User ${e} not found`);return this.mapUser(s)}async deleteUser(e){this.stmt("DELETE FROM user_roles WHERE user_id = ?").run(e),this.stmt("DELETE FROM users WHERE id = ?").run(e)}async getUserById(e){let t=this.stmt("SELECT * FROM users WHERE id = ?").get(e);return t?this.mapUser(t):null}async getUserByEmail(e){let t=this.stmt("SELECT * FROM users WHERE email = ?").get(e);return t?this.mapUser(t):null}async getUsers(e){return this.stmt("SELECT * FROM users WHERE tenant_id = ? ORDER BY created_at ASC").all(e).map(n=>this.mapUser(n))}async countUsers(e){return(e?this.stmt("SELECT COUNT(*) as n FROM users WHERE tenant_id = ?").get(e):this.stmt("SELECT COUNT(*) as n FROM users").get())?.n??0}async getRoles(e){return this.stmt("SELECT * FROM roles WHERE tenant_id = ?").all(e).map(n=>({id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async createRole(e){let t=(0,C.randomUUID)();this.stmt("INSERT INTO roles (id,tenant_id,name,description) VALUES (?,?,?,?)").run(t,e.tenantId,e.name,e.description??null);let n=this.stmt("SELECT * FROM roles WHERE id = ?").get(t);if(!n)throw new Error("Failed to create role");return{id:n.id,tenantId:n.tenant_id,name:n.name,...n.description!=null?{description:n.description}:{}}}async updateRole(e,t){let n=[],o=[];t.name!=null&&(n.push("name = ?"),o.push(t.name)),t.description!=null&&(n.push("description = ?"),o.push(t.description)),n.length>0&&(o.push(e),this.stmt(`UPDATE roles SET ${n.join(", ")} WHERE id = ?`).run(...o));let r=this.stmt("SELECT * FROM roles WHERE id = ?").get(e);if(!r)throw new Error(`Role ${e} not found`);return{id:r.id,tenantId:r.tenant_id,name:r.name,...r.description!=null?{description:r.description}:{}}}async deleteRole(e){this.stmt("DELETE FROM role_permissions WHERE role_id = ?").run(e),this.stmt("DELETE FROM user_roles WHERE role_id = ?").run(e),this.stmt("DELETE FROM roles WHERE id = ?").run(e)}async getAllPermissions(){return this.stmt("SELECT * FROM permissions ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,...t.description!=null?{description:t.description}:{}}))}async assignPermissionToRole(e,t){this.stmt("INSERT OR IGNORE INTO role_permissions (role_id,permission_id) VALUES (?,?)").run(e,t)}async revokePermissionFromRole(e,t){this.stmt("DELETE FROM role_permissions WHERE role_id = ? AND permission_id = ?").run(e,t)}async getPermissionsForRole(e){return this.stmt("SELECT p.* FROM permissions p JOIN role_permissions rp ON rp.permission_id = p.id WHERE rp.role_id = ?").all(e).map(n=>({id:n.id,name:n.name,...n.description!=null?{description:n.description}:{}}))}async getUserRoles(e,t){return(t?this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ? AND ur.tenant_id = ?").all(e,t):this.stmt("SELECT r.* FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?").all(e)).map(o=>({id:o.id,tenantId:o.tenant_id,name:o.name,...o.description!=null?{description:o.description}:{}}))}async assignRole(e,t,n="default"){this.stmt("INSERT OR IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)").run(e,t,n)}async revokeRole(e,t,n){n?this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ? AND tenant_id = ?").run(e,t,n):this.stmt("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?").run(e,t)}async createLog(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO audit_logs (id,tenant_id,user_id,action,resource_type,resource_id,old_data,new_data,created_at) VALUES (?,?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null,n)}async getLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];if(e.action&&(t.push("action = ?"),n.push(e.action)),e.resourceType&&(t.push("resource_type = ?"),n.push(e.resourceType)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to)),e.q){t.push("(action LIKE ? OR resource_type LIKE ? OR resource_id LIKE ? OR user_id LIKE ?) ESCAPE '\\'");let d=j(e.q);n.push(d,d,d,d)}let o=t.join(" AND "),r=e.page??1,s=Math.min(e.limit??50,Mn),a=(r-1)*s,c=this.stmt(`SELECT ${i.AUDIT_SUMMARY_COLS} FROM audit_logs WHERE ${o} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,s,a),l=this.stmt(`SELECT COUNT(*) AS total FROM audit_logs WHERE ${o}`).get(...n);return{items:c.map(d=>this.mapAuditSummary(d)),total:l.total,page:r,limit:s}}async getAuditLogById(e){let t=this.stmt("SELECT * FROM audit_logs WHERE id = ?").get(e);return t?this.mapAuditLog(t):null}static AUDIT_SUMMARY_COLS="id, tenant_id, user_id, action, resource_type, resource_id, created_at";mapAuditSummary(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},createdAt:e.created_at}}mapAuditLog(e){return{id:e.id,tenantId:e.tenant_id,action:e.action,resourceType:e.resource_type,createdAt:e.created_at,...e.user_id!=null?{userId:e.user_id}:{},...e.resource_id!=null?{resourceId:e.resource_id}:{},...e.old_data!=null?{oldData:JSON.parse(e.old_data)}:{},...e.new_data!=null?{newData:JSON.parse(e.new_data)}:{}}}async*streamAuditLogs(e){let t=["tenant_id = ?"],n=[e.tenantId];e.action&&(t.push("action = ?"),n.push(e.action)),e.from&&(t.push("created_at >= ?"),n.push(e.from)),e.to&&(t.push("created_at <= ?"),n.push(e.to));let o=500,r=0;for(;;){let s=this.stmt(`SELECT * FROM audit_logs WHERE ${t.join(" AND ")} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...n,o,r);if(s.length===0)break;for(let a of s)yield this.mapAuditLog(a);r+=o}}async getOverviewStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),o=this.stmt("SELECT COUNT(*) as n FROM visitors WHERE tenant_id = ?").get(e),r=t?.n??0,s=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 500").all(e),a=0,c=0;for(let d of s){let u=Object.values(JSON.parse(d.consent_json)),m=u.length>0?u.filter(h=>h==="granted").length/u.length:0;m>=.8?a++:m<=.2&&c++}let l=s.length||1;return{totalConsents:r,gpcDetectedCount:n?.n??0,totalVisitors:o?.n??0,acceptedPct:Math.round(a/l*100),rejectedPct:Math.round(c/l*100)}}async getCategoryStats(e){let t=this.stmt("SELECT consent_json FROM consent_records WHERE tenant_id = ? LIMIT 5000").all(e),n={};for(let o of t){let r=JSON.parse(o.consent_json);for(let[s,a]of Object.entries(r))n[s]||(n[s]={granted:0,denied:0,objected:0}),a==="granted"?n[s].granted++:a==="denied"?n[s].denied++:a==="objected"&&n[s].objected++}return n}async getTimeline(e,t=30){return this.stmt("SELECT date(created_at) as date, COUNT(*) as count FROM consent_records WHERE tenant_id = ? AND created_at >= date('now', ?) GROUP BY date(created_at) ORDER BY date ASC").all(e,`-${t} days`).map(o=>({date:o.date,count:o.count}))}async getCountries(e){return this.stmt("SELECT v.country, COUNT(*) as count FROM consent_records cr JOIN visitors v ON v.visitor_id = cr.visitor_id WHERE cr.tenant_id = ? AND v.country IS NOT NULL GROUP BY v.country ORDER BY count DESC LIMIT 50").all(e).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let t=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ?").get(e),n=this.stmt("SELECT COUNT(*) as n FROM consent_records WHERE tenant_id = ? AND gpc_detected = 1").get(e),o=t?.n??0,r=n?.n??0;return{detected:r,total:o,rate:o>0?Math.round(r/o*100):0}}async getTenants(){return this.stmt("SELECT * FROM tenants ORDER BY name ASC").all().map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createTenant(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO tenants (id,name,slug,created_at,updated_at) VALUES (?,?,?,?,?)").run(t,e.name,e.slug,n,n);let o=this.stmt("SELECT * FROM tenants WHERE id = ?").get(t);if(!o)throw new Error("Failed to create tenant");return{id:o.id,name:o.name,slug:o.slug,createdAt:o.created_at,updatedAt:o.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),o=["updated_at = ?"],r=[n];t.name!=null&&(o.push("name = ?"),r.push(t.name)),t.slug!=null&&(o.push("slug = ?"),r.push(t.slug)),r.push(e),this.stmt(`UPDATE tenants SET ${o.join(", ")} WHERE id = ?`).run(...r);let s=this.stmt("SELECT * FROM tenants WHERE id = ?").get(e);if(!s)throw new Error(`Tenant ${e} not found`);return{id:s.id,name:s.name,slug:s.slug,createdAt:s.created_at,updatedAt:s.updated_at}}async deleteTenant(e){this.stmt("DELETE FROM tenants WHERE id = ?").run(e)}async getSettings(e){let t=this.stmt("SELECT allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json FROM tenant_settings WHERE tenant_id = ?").get(e);return t?{allowedOrigins:JSON.parse(t.allowed_origins_json),adminAllowedOrigins:JSON.parse(t.admin_allowed_origins_json),setupCompleted:!!t.setup_completed,profilesSeeded:!!t.profiles_seeded,tcfConfirmation:t.tcf_confirmation_json?JSON.parse(t.tcf_confirmation_json):void 0,gppConfirmation:t.gpp_confirmation_json?JSON.parse(t.gpp_confirmation_json):void 0}:{}}async updateSettings(e,t){let o={...await this.getSettings(e),...t};return this.stmt(`INSERT INTO tenant_settings (tenant_id, allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json, updated_at) VALUES (?,?,?,?,?,?,?,?)
81
+ ON CONFLICT(tenant_id) DO UPDATE SET allowed_origins_json = excluded.allowed_origins_json, admin_allowed_origins_json = excluded.admin_allowed_origins_json, setup_completed = excluded.setup_completed, profiles_seeded = excluded.profiles_seeded, tcf_confirmation_json = excluded.tcf_confirmation_json, gpp_confirmation_json = excluded.gpp_confirmation_json, updated_at = excluded.updated_at`).run(e,JSON.stringify(o.allowedOrigins??[]),JSON.stringify(o.adminAllowedOrigins??[]),o.setupCompleted?1:0,o.profilesSeeded?1:0,o.tcfConfirmation?JSON.stringify(o.tcfConfirmation):null,o.gppConfirmation?JSON.stringify(o.gppConfirmation):null,new Date().toISOString()),this.getSettings(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=this.stmt("SELECT visitor_id FROM consent_records WHERE created_at < ?").all(t);for(let{visitor_id:o}of n)this.stmt("DELETE FROM consent_history WHERE visitor_id = ?").run(o),this.stmt("DELETE FROM consent_records WHERE visitor_id = ?").run(o);return n.length}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active===1,...e.created_by!==null?{createdBy:e.created_by}:{},...e.expire_by!==null?{expireBy:e.expire_by}:{},createdAt:e.created_at,...e.updated_at!==null?{updatedAt:e.updated_at}:{}}}async createApiKey(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();this.stmt("INSERT INTO api_keys (id,tenant_id,key_hash,name,created_by,expire_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)").run(t,e.tenantId,e.keyHash,e.name,e.createdBy??null,e.expireBy??null,n,n);let o=this.stmt("SELECT * FROM api_keys WHERE id = ?").get(t);if(!o)throw new Error("Failed to create API key");return this.mapApiKey(o)}async getApiKeyByHash(e){let t=this.stmt("SELECT * FROM api_keys WHERE key_hash = ? AND is_active = 1").get(e);return t?this.mapApiKey(t):null}async revokeApiKey(e){this.stmt("UPDATE api_keys SET is_active = 0, updated_at = ? WHERE id = ?").run(new Date().toISOString(),e)}async reactivateApiKey(e){let t=new Date().toISOString();this.stmt("UPDATE api_keys SET is_active = 1, updated_at = ?, expire_by = CASE WHEN expire_by <= ? THEN NULL ELSE expire_by END WHERE id = ?").run(t,t,e)}async deleteApiKey(e){this.stmt("DELETE FROM api_keys WHERE id = ?").run(e)}async getApiKeys(e){return this.stmt("SELECT * FROM api_keys WHERE tenant_id = ? ORDER BY created_at DESC").all(e).map(n=>this.mapApiKey(n))}mapConsentTemplate(e){return{id:e.id,tenantId:e.tenant_id,name:e.name,cookies:JSON.parse(e.cookies_json),categories:JSON.parse(e.categories_json),createdAt:e.created_at,updatedAt:e.updated_at}}async createConsentTemplate(e){let t=_e(),n=new Date().toISOString();return this.stmt("INSERT INTO consent_templates (id,tenant_id,name,cookies_json,categories_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?)").run(t,e.tenantId,e.name,JSON.stringify(e.cookies),JSON.stringify(e.categories),n,n),this.mapConsentTemplate(this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(t))}async updateConsentTemplate(e,t){let n=new Date().toISOString();t.name!==void 0&&this.stmt("UPDATE consent_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e),t.cookies!==void 0&&this.stmt("UPDATE consent_templates SET cookies_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t.cookies),n,e),t.categories!==void 0&&this.stmt("UPDATE consent_templates SET categories_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t.categories),n,e);let o=this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(e);if(!o)throw new Error("Consent template not found");return this.mapConsentTemplate(o)}async deleteConsentTemplate(e){this.stmt("DELETE FROM consent_templates WHERE id = ?").run(e)}async getConsentTemplate(e){let t=this.stmt("SELECT * FROM consent_templates WHERE id = ?").get(e);return t?this.mapConsentTemplate(t):null}async getConsentTemplates(e){return this.stmt("SELECT * FROM consent_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapConsentTemplate(n))}async copyConsentTemplate(e,t){let n=await this.getConsentTemplate(e);if(!n)throw new Error("Consent template not found");return this.createConsentTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies,categories:n.categories})}mapUITemplate(e){let t=JSON.parse(e.settings_json);return{id:e.id,tenantId:e.tenant_id,name:e.name,...t,createdAt:e.created_at,updatedAt:e.updated_at}}async createUITemplate(e){let t=we(),n=new Date().toISOString(),{tenantId:o,name:r,...s}=e;return this.stmt("INSERT INTO ui_templates (id,tenant_id,name,settings_json,created_at,updated_at) VALUES (?,?,?,?,?,?)").run(t,o,r,JSON.stringify(s),n,n),this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(t))}async updateUITemplate(e,t){let n=new Date().toISOString(),o=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);if(!o)throw new Error("UI template not found");t.name!==void 0&&this.stmt("UPDATE ui_templates SET name = ?, updated_at = ? WHERE id = ?").run(t.name,n,e);let{name:r,...s}=t;if(Object.keys(s).length>0){let c={...JSON.parse(o.settings_json),...s};this.stmt("UPDATE ui_templates SET settings_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(c),n,e)}return this.mapUITemplate(this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e))}async deleteUITemplate(e){this.stmt("DELETE FROM ui_templates WHERE id = ?").run(e)}async getUITemplate(e){let t=this.stmt("SELECT * FROM ui_templates WHERE id = ?").get(e);return t?this.mapUITemplate(t):null}async getUITemplates(e){return this.stmt("SELECT * FROM ui_templates WHERE tenant_id = ? ORDER BY name ASC").all(e).map(n=>this.mapUITemplate(n))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:o,mainBanner:r,gpcBanner:s,preferenceModal:a}=n;return this.createUITemplate({tenantId:o,name:t,mainBanner:r,gpcBanner:s,preferenceModal:a})}mapProfileSummary(e){return{id:e.id,name:e.name,defaultLocale:e.default_locale,complianceGroup:e.compliance_group??null,customComplianceGroup:e.custom_compliance_group??null,isActive:e.is_active===1,consentTemplateName:e.consent_template_name,uiTemplateName:e.ui_template_name,createdAt:e.created_at,updatedAt:e.updated_at}}PROFILE_SUMMARY_SQL=`
97
82
  SELECT
98
- p.id, p.name, p.default_locale, p.version, p.created_at, p.updated_at,
83
+ p.id, p.name, p.default_locale, p.created_at, p.updated_at,
99
84
  json_extract(p.profile_json, '$.complianceGroup') AS compliance_group,
85
+ json_extract(p.profile_json, '$.customComplianceGroup') AS custom_compliance_group,
100
86
  json_extract(p.profile_json, '$.isActive') AS is_active,
101
- json_extract(p.profile_json, '$.cookieTemplateId') AS cookie_template_id,
87
+ json_extract(p.profile_json, '$.consentTemplateId') AS consent_template_id,
102
88
  json_extract(p.profile_json, '$.uiTemplateId') AS ui_template_id,
103
- ct.name AS cookie_template_name,
89
+ ct.name AS consent_template_name,
104
90
  ut.name AS ui_template_name
105
91
  FROM profiles p
106
- LEFT JOIN cookie_templates ct ON ct.id = json_extract(p.profile_json, '$.cookieTemplateId')
92
+ LEFT JOIN consent_templates ct ON ct.id = json_extract(p.profile_json, '$.consentTemplateId')
107
93
  LEFT JOIN ui_templates ut ON ut.id = json_extract(p.profile_json, '$.uiTemplateId')
108
- `;async listProfilesSummary(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE p.tenant_id = ? ORDER BY p.created_at ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingCookieTemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.cookieTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingUITemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.uiTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async getOptInStats(e,t){let n=["cr.tenant_id = ?"],i=[e];t.profileId&&(n.push("cr.profile_id = ?"),i.push(t.profileId)),t.from&&(n.push("cr.created_at >= ?"),i.push(t.from)),t.to&&(n.push("cr.created_at <= ?"),i.push(t.to)),t.locale&&(n.push("cr.locale = ?"),i.push(t.locale));let o=n.join(" AND "),r=this.stmt(`SELECT cr.locale, cr.consent_json FROM consent_records cr WHERE ${o}`).all(...i),a=0,c=0,l=0,u=0,d={};for(let f of r){let _=JSON.parse(f.consent_json),h=Object.values(_),A=h.filter(z=>z==="granted").length,T=h.filter(z=>z==="denied").length,I=h.length>0?A/h.length:0;a++;let O=f.locale;d[O]||(d[O]={total:0,granted:0,denied:0,managed:0}),d[O].total++,I>=.9?(c++,d[O].granted++):T/(h.length||1)>=.9?(l++,d[O].denied++):(u++,d[O].managed++)}let p=this.stmt(`SELECT date(cr.created_at) as d, cr.consent_json FROM consent_records cr WHERE ${o} ORDER BY d ASC`).all(...i),E=new Map;for(let f of p){let _=E.get(f.d)??{total:0,granted:0,denied:0,managed:0},h=JSON.parse(f.consent_json),A=Object.values(h),T=A.length>0?A.filter(O=>O==="granted").length/A.length:0,I=A.length>0?A.filter(O=>O==="denied").length/A.length:0;_.total++,T>=.9?_.granted++:I>=.9?_.denied++:_.managed++,E.set(f.d,_)}let S=Array.from(E.entries()).map(([f,_])=>({date:f,..._}));return{total:a,granted:c,denied:l,managed:u,grantedPct:a>0?Math.round(c/a*1e3)/10:0,deniedPct:a>0?Math.round(l/a*1e3)/10:0,managedPct:a>0?Math.round(u/a*1e3)/10:0,byLocale:d,byDate:S}}};function Ye(s){return{id:s._id,tenantId:s.tenant_id,name:s.name,defaultLocale:s.default_locale,version:s.version,profileJson:s.profile_json,createdAt:s.created_at,updatedAt:s.updated_at}}function Ie(s){return{id:s._id,tenantId:s.tenant_id,visitorId:s.visitor_id,profileId:s.profile_id,profileVersion:s.profile_version,locale:s.locale,consentJson:s.consent_json,gpcDetected:s.gpc_detected,source:s.source,createdAt:s.created_at,updatedAt:s.updated_at}}function co(s){return{id:s._id,tenantId:s.tenant_id,consentRecordId:s.consent_record_id,visitorId:s.visitor_id,oldJson:s.old_json,newJson:s.new_json,action:s.action,createdAt:s.created_at}}function ze(s){return{id:s._id,tenantId:s.tenant_id,visitorId:s.visitor_id,...s.country!=null?{country:s.country}:{},...s.region!=null?{region:s.region}:{},...s.city!=null?{city:s.city}:{},...s.ip_hash!=null?{ipHash:s.ip_hash}:{},...s.user_agent_hash!=null?{userAgentHash:s.user_agent_hash}:{},firstSeen:s.first_seen,lastSeen:s.last_seen}}function Pe(s){return{id:s._id,tenantId:s.tenant_id,name:s.name,email:s.email,passwordHash:s.password_hash,isActive:s.is_active,createdAt:s.created_at,updatedAt:s.updated_at}}function Qe(s){return{id:s._id,tenantId:s.tenant_id,name:s.name,...s.description!=null?{description:s.description}:{}}}function Dn(s){return{id:s._id,name:s.name,...s.description!=null?{description:s.description}:{}}}function Ln(s){return{id:s._id,tenantId:s.tenant_id,action:s.action,resourceType:s.resource_type,...s.user_id!=null?{userId:s.user_id}:{},...s.resource_id!=null?{resourceId:s.resource_id}:{},...s.old_data!=null?{oldData:s.old_data}:{},...s.new_data!=null?{newData:s.new_data}:{},createdAt:s.created_at}}var ye=class{constructor(e){this.config=e}config;client;db;col(e){return this.db.collection(e)}async connect(){let{MongoClient:e}=await import("mongodb"),t=this.config.uri??"mongodb://localhost:27017";this.client=new e(t),await this.client.connect(),this.db=this.client.db(this.config.database??"consenti"),await this.migrate()}async disconnect(){await this.client.close()}async migrate(){await this.createIndexes(),await this.seed()}async createIndexes(){await this.col("consent_records").createIndex({visitor_id:1,profile_id:1},{unique:!0}),await this.col("consent_records").createIndex({tenant_id:1}),await this.col("consent_records").createIndex({created_at:1}),await this.col("visitors").createIndex({visitor_id:1},{unique:!0}),await this.col("visitors").createIndex({tenant_id:1}),await this.col("users").createIndex({email:1},{unique:!0}),await this.col("audit_logs").createIndex({tenant_id:1,created_at:1}),await this.col("user_roles").createIndex({user_id:1}),await this.col("role_permissions").createIndex({role_id:1})}async seed(){let{id:e,name:t,slug:n}=$;await this.col("tenants").findOne({_id:e})||await this.col("tenants").insertOne({_id:e,name:t,slug:n});for(let o of j){let r={_id:o.id,name:o.name,description:o.description};await this.col("permissions").updateOne({_id:o.id},{$setOnInsert:r},{upsert:!0})}for(let o of Z){let r={_id:o.id,tenant_id:o.tenantId,name:o.name,description:o.description};await this.col("roles").updateOne({_id:o.id},{$setOnInsert:r},{upsert:!0})}let i=this.col("role_permissions");for(let{roleId:o,permissionId:r}of ee)await i.updateOne({role_id:o,permission_id:r},{$setOnInsert:{role_id:o,permission_id:r}},{upsert:!0})}async createProfile(e){let t=new Date().toISOString(),n={_id:(0,w.randomUUID)(),tenant_id:e.tenantId,name:e.name,default_locale:e.defaultLocale,version:1,profile_json:e.profileJson,created_at:t,updated_at:t};return await this.col("profiles").insertOne(n),Ye(n)}async updateProfile(e,t){let i={updated_at:new Date().toISOString()};t.name!=null&&(i.name=t.name),t.defaultLocale!=null&&(i.default_locale=t.defaultLocale),t.profileJson!=null&&(i.profile_json=t.profileJson);let o=await this.col("profiles").findOneAndUpdate({_id:e},{$set:i,$inc:{version:1}},{returnDocument:"after"});if(!o)throw new Error(`Profile ${e} not found`);return Ye(o)}async deleteProfile(e){await this.col("profiles").deleteOne({_id:e})}async getProfile(e){let t=await this.col("profiles").findOne({_id:e});return t?Ye(t):null}async getProfiles(e){return(await this.col("profiles").find({tenant_id:e}).toArray()).map(Ye)}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(i=>i.profileJson.complianceGroup===t&&i.profileJson.isActive)??null}async createConsent(e){let t=new Date().toISOString(),n={_id:(0,w.randomUUID)(),tenant_id:e.tenantId,visitor_id:e.visitorId,profile_id:e.profileId,profile_version:e.profileVersion,locale:e.locale,consent_json:e.consentJson,gpc_detected:e.gpcDetected,source:e.source,created_at:t,updated_at:t};return await this.col("consent_records").insertOne(n),await this.writeHistory(n._id,e.tenantId,e.visitorId,null,e.consentJson,"created"),Ie(n)}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let o={updated_at:new Date().toISOString(),consent_json:t.consentJson};t.locale!=null&&(o.locale=t.locale),t.gpcDetected!=null&&(o.gpc_detected=t.gpcDetected);let r=await this.col("consent_records").findOneAndUpdate({visitor_id:e},{$set:o},{returnDocument:"after"});if(!r)throw new Error(`Consent for visitor ${e} not found`);return await this.writeHistory(r._id,r.tenant_id,e,n.consentJson,t.consentJson,"updated"),Ie(r)}async deleteConsent(e){await this.col("consent_history").deleteMany({visitor_id:e}),await this.col("consent_records").deleteOne({visitor_id:e})}async getConsent(e){let t=await this.col("consent_records").findOne({visitor_id:e});return t?Ie(t):null}async getConsents(e){let t=this.buildConsentFilter(e),n=e.page??1,i=e.limit??50;return(await this.col("consent_records").find(t).sort({created_at:-1}).skip((n-1)*i).limit(i).toArray()).map(Ie)}async*streamConsents(e){let t=this.buildConsentFilter(e),n=this.col("consent_records").find(t).sort({created_at:1});for await(let i of n)yield Ie(i)}buildConsentFilter(e){let t={tenant_id:e.tenantId};if(e.profileId!=null&&(t.profile_id=e.profileId),e.from!=null||e.to!=null){let n={};e.from!=null&&(n.$gte=e.from),e.to!=null&&(n.$lte=e.to),t.created_at=n}return t}async writeHistory(e,t,n,i,o,r){let a={_id:(0,w.randomUUID)(),tenant_id:t,consent_record_id:e,visitor_id:n,old_json:i,new_json:o,action:r,created_at:new Date().toISOString()};await this.col("consent_history").insertOne(a)}async getConsentHistory(e){return(await this.col("consent_history").find({visitor_id:e}).sort({created_at:1}).toArray()).map(co)}async createVisitor(e){let t=new Date().toISOString(),n={_id:(0,w.randomUUID)(),tenant_id:e.tenantId,visitor_id:e.visitorId,first_seen:t,last_seen:t,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ipHash!=null?{ip_hash:e.ipHash}:{},...e.userAgentHash!=null?{user_agent_hash:e.userAgentHash}:{}};return await this.col("visitors").insertOne(n),ze(n)}async updateVisitor(e,t){let n={last_seen:t.lastSeen??new Date().toISOString()};t.country!=null&&(n.country=t.country),t.region!=null&&(n.region=t.region),t.city!=null&&(n.city=t.city);let i=await this.col("visitors").findOneAndUpdate({visitor_id:e},{$set:n},{returnDocument:"after"});if(!i)throw new Error(`Visitor ${e} not found`);return ze(i)}async deleteVisitor(e){await this.col("visitors").deleteOne({visitor_id:e})}async getVisitor(e){let t=await this.col("visitors").findOne({visitor_id:e});return t?ze(t):null}async getVisitors(e){let t={tenant_id:e.tenantId};if(e.from!=null||e.to!=null){let r={};e.from!=null&&(r.$gte=e.from),e.to!=null&&(r.$lte=e.to),t.first_seen=r}let n=e.page??1,i=e.limit??50;return(await this.col("visitors").find(t).sort({first_seen:-1}).skip((n-1)*i).limit(i).toArray()).map(ze)}async getOverviewStats(e){let[t,n,i]=await Promise.all([this.col("consent_records").countDocuments({tenant_id:e}),this.col("consent_records").countDocuments({tenant_id:e,gpc_detected:!0}),this.col("visitors").countDocuments({tenant_id:e})]),o=[{$match:{tenant_id:e}},{$addFields:{values:{$objectToArray:"$consent_json"}}},{$unwind:"$values"},{$group:{_id:"$values.v",count:{$sum:1}}}],r=await this.col("consent_records").aggregate(o).toArray(),a=0,c=0,l=0;for(let u of r)l+=u.count,u._id==="granted"&&(a=u.count),u._id==="denied"&&(c=u.count);return{totalConsents:t,acceptedPct:l>0?Math.round(a/l*100):0,rejectedPct:l>0?Math.round(c/l*100):0,totalVisitors:i,gpcDetectedCount:n}}async getCategoryStats(e){let t=[{$match:{tenant_id:e}},{$addFields:{pairs:{$objectToArray:"$consent_json"}}},{$unwind:"$pairs"},{$group:{_id:{cookie:"$pairs.k",status:"$pairs.v"},count:{$sum:1}}}],n=await this.col("consent_records").aggregate(t).toArray(),i={};for(let o of n){let r=o._id.cookie;i[r]||(i[r]={granted:0,denied:0,objected:0});let a=i[r];a&&(o._id.status==="granted"&&(a.granted+=o.count),o._id.status==="denied"&&(a.denied+=o.count),o._id.status==="objected"&&(a.objected+=o.count))}return i}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString(),i=[{$match:{tenant_id:e,created_at:{$gte:n}}},{$group:{_id:{$substr:["$created_at",0,10]},count:{$sum:1}}},{$sort:{_id:1}}];return(await this.col("consent_records").aggregate(i).toArray()).map(r=>({date:r._id,count:r.count}))}async createUser(e){let t=new Date().toISOString(),n={_id:(0,w.randomUUID)(),tenant_id:e.tenantId,name:e.name,email:e.email,password_hash:e.passwordHash,is_active:!0,created_at:t,updated_at:t};return await this.col("users").insertOne(n),Pe(n)}async updateUser(e,t){let n={updated_at:new Date().toISOString()};t.name!=null&&(n.name=t.name),t.email!=null&&(n.email=t.email),t.passwordHash!=null&&(n.password_hash=t.passwordHash),t.isActive!=null&&(n.is_active=t.isActive);let i=await this.col("users").findOneAndUpdate({_id:e},{$set:n},{returnDocument:"after"});if(!i)throw new Error(`User ${e} not found`);return Pe(i)}async deleteUser(e){await this.col("user_roles").deleteMany({user_id:e}),await this.col("users").deleteOne({_id:e})}async getUserById(e){let t=await this.col("users").findOne({_id:e});return t?Pe(t):null}async getUserByEmail(e){let t=await this.col("users").findOne({email:e});return t?Pe(t):null}async getUsers(e){return(await this.col("users").find({tenant_id:e}).toArray()).map(Pe)}async countUsers(e){return this.col("users").countDocuments(e?{tenant_id:e}:{})}async getRoles(e){return(await this.col("roles").find({tenant_id:e}).toArray()).map(Qe)}async createRole(e){let t={_id:(0,w.randomUUID)(),tenant_id:e.tenantId,name:e.name,...e.description!=null?{description:e.description}:{}};return await this.col("roles").insertOne(t),Qe(t)}async updateRole(e,t){let n={};t.name!=null&&(n.name=t.name),t.description!=null&&(n.description=t.description);let i=await this.col("roles").findOneAndUpdate({_id:e},{$set:n},{returnDocument:"after"});if(!i)throw new Error(`Role ${e} not found`);return Qe(i)}async deleteRole(e){await this.col("role_permissions").deleteMany({role_id:e}),await this.col("user_roles").deleteMany({role_id:e}),await this.col("roles").deleteOne({_id:e})}async getAllPermissions(){return(await this.col("permissions").find({}).toArray()).map(Dn)}async getPermissionsForRole(e){let n=(await this.col("role_permissions").find({role_id:e}).toArray()).map(o=>o.permission_id);return n.length===0?[]:(await this.col("permissions").find({_id:{$in:n}}).toArray()).map(Dn)}async getUserRoles(e,t){let n=t?{user_id:e,tenant_id:t}:{user_id:e},o=(await this.col("user_roles").find(n).toArray()).map(a=>a.role_id);return o.length===0?[]:(await this.col("roles").find({_id:{$in:o}}).toArray()).map(Qe)}async assignRole(e,t,n="default"){await this.col("user_roles").updateOne({user_id:e,role_id:t,tenant_id:n},{$setOnInsert:{user_id:e,role_id:t,tenant_id:n}},{upsert:!0})}async revokeRole(e,t,n){n?await this.col("user_roles").deleteOne({user_id:e,role_id:t,tenant_id:n}):await this.col("user_roles").deleteMany({user_id:e,role_id:t})}async assignPermissionToRole(e,t){await this.col("role_permissions").updateOne({role_id:e,permission_id:t},{$setOnInsert:{role_id:e,permission_id:t}},{upsert:!0})}async revokePermissionFromRole(e,t){await this.col("role_permissions").deleteOne({role_id:e,permission_id:t})}async createLog(e){let t={_id:(0,w.randomUUID)(),tenant_id:e.tenantId,action:e.action,resource_type:e.resourceType,...e.userId!=null?{user_id:e.userId}:{},...e.resourceId!=null?{resource_id:e.resourceId}:{},...e.oldData!=null?{old_data:e.oldData}:{},...e.newData!=null?{new_data:e.newData}:{},created_at:new Date().toISOString()};await this.col("audit_logs").insertOne(t)}async getLogs(e){let t=this.buildAuditFilter(e),n=e.page??1,i=e.limit??50;return(await this.col("audit_logs").find(t).sort({created_at:-1}).skip((n-1)*i).limit(i).toArray()).map(Ln)}async*streamAuditLogs(e){let t=this.buildAuditFilter(e),n=this.col("audit_logs").find(t).sort({created_at:1});for await(let i of n)yield Ln(i)}buildAuditFilter(e){let t={tenant_id:e.tenantId};if(e.action!=null&&(t.action=e.action),e.resourceType!=null&&(t.resource_type=e.resourceType),e.from!=null||e.to!=null){let n={};e.from!=null&&(n.$gte=e.from),e.to!=null&&(n.$lte=e.to),t.created_at=n}return t}async getCountries(e){let t=[{$match:{tenant_id:e}},{$lookup:{from:"visitors",localField:"visitor_id",foreignField:"visitor_id",as:"v"}},{$unwind:"$v"},{$match:{"v.country":{$ne:null}}},{$group:{_id:"$v.country",count:{$sum:1}}},{$sort:{count:-1}},{$limit:50}];return(await this.col("consent_records").aggregate(t).toArray()).map(i=>({country:i._id,count:i.count}))}async getGpcStats(e){let t=await this.col("consent_records").countDocuments({tenant_id:e}),n=await this.col("consent_records").countDocuments({tenant_id:e,gpc_detected:!0});return{detected:n,total:t,rate:t>0?Math.round(n/t*100):0}}async getTenants(){return(await this.col("tenants").find({}).toArray()).map(t=>({id:t._id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createApiKey(e){let t={_id:(0,w.randomUUID)(),tenant_id:e.tenantId,key_hash:e.keyHash,name:e.name,is_active:!0,created_at:new Date().toISOString()};return await this.col("api_keys").insertOne(t),{id:t._id,tenantId:t.tenant_id,keyHash:t.key_hash,name:t.name,isActive:t.is_active,createdAt:t.created_at}}async getApiKeyByHash(e){let t=await this.col("api_keys").findOne({key_hash:e,is_active:!0});return t?{id:t._id,tenantId:t.tenant_id,keyHash:t.key_hash,name:t.name,isActive:t.is_active,createdAt:t.created_at}:null}async revokeApiKey(e){await this.col("api_keys").updateOne({_id:e},{$set:{is_active:!1}})}async getApiKeys(e){return(await this.col("api_keys").find({tenant_id:e}).sort({created_at:-1}).toArray()).map(n=>({id:n._id,tenantId:n.tenant_id,keyHash:n.key_hash,name:n.name,isActive:n.is_active,createdAt:n.created_at}))}async createTenant(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),i={_id:t,name:e.name,slug:e.slug,created_at:n,updated_at:n};return await this.col("tenants").insertOne(i),{id:t,name:e.name,slug:e.slug,createdAt:n,updatedAt:n}}async updateTenant(e,t){let i={updated_at:new Date().toISOString()};t.name!=null&&(i.name=t.name),t.slug!=null&&(i.slug=t.slug),await this.col("tenants").updateOne({_id:e},{$set:i});let o=await this.col("tenants").findOne({_id:e});if(!o)throw new Error(`Tenant ${e} not found`);return{id:o._id,name:o.name,slug:o.slug,createdAt:o.created_at,updatedAt:o.updated_at}}async deleteTenant(e){await this.col("tenants").deleteOne({_id:e})}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=await this.col("consent_records").find({created_at:{$lt:t}}).toArray();if(n.length===0)return 0;let i=n.map(o=>o.visitor_id);return await this.col("consent_history").deleteMany({visitor_id:{$in:i}}),await this.col("consent_records").deleteMany({visitor_id:{$in:i}}),n.length}async createCookieTemplate(){throw new Error("Not implemented")}async updateCookieTemplate(){throw new Error("Not implemented")}async deleteCookieTemplate(){throw new Error("Not implemented")}async getCookieTemplate(){throw new Error("Not implemented")}async getCookieTemplates(){throw new Error("Not implemented")}async copyCookieTemplate(){throw new Error("Not implemented")}async createUITemplate(){throw new Error("Not implemented")}async updateUITemplate(){throw new Error("Not implemented")}async deleteUITemplate(){throw new Error("Not implemented")}async getUITemplate(){throw new Error("Not implemented")}async getUITemplates(){throw new Error("Not implemented")}async copyUITemplate(){throw new Error("Not implemented")}async listProfilesSummary(){return[]}async findProfilesUsingCookieTemplate(){return[]}async findProfilesUsingUITemplate(){return[]}async getOptInStats(){throw new Error("Not implemented")}};function Xe(s){return{id:s.id,tenantId:s.tenant_id,name:s.name,defaultLocale:s.default_locale,version:s.version,profileJson:JSON.parse(s.profile_json),createdAt:s.created_at,updatedAt:s.updated_at}}function be(s){return{id:s.id,tenantId:s.tenant_id,visitorId:s.visitor_id,profileId:s.profile_id,profileVersion:s.profile_version,locale:s.locale,consentJson:JSON.parse(s.consent_json),gpcDetected:s.gpc_detected===1,source:s.source,createdAt:s.created_at,updatedAt:s.updated_at,...s.age_verified!=null?{ageVerified:s.age_verified===1}:{},...s.parental_consent_token!=null?{parentalConsentToken:s.parental_consent_token}:{},...s.tcf_string!=null?{tcfString:s.tcf_string}:{}}}function lo(s){return{id:s.id,tenantId:s.tenant_id,consentRecordId:s.consent_record_id,visitorId:s.visitor_id,oldJson:s.old_json?JSON.parse(s.old_json):null,newJson:JSON.parse(s.new_json),action:s.action,createdAt:s.created_at}}function Ze(s){return{id:s.id,tenantId:s.tenant_id,visitorId:s.visitor_id,...s.country!=null?{country:s.country}:{},...s.region!=null?{region:s.region}:{},...s.city!=null?{city:s.city}:{},...s.ip_hash!=null?{ipHash:s.ip_hash}:{},...s.user_agent_hash!=null?{userAgentHash:s.user_agent_hash}:{},firstSeen:s.first_seen,lastSeen:s.last_seen}}function Oe(s){return{id:s.id,tenantId:s.tenant_id,name:s.name,email:s.email,passwordHash:s.password_hash,isActive:s.is_active===1,createdAt:s.created_at,updatedAt:s.updated_at,totpEnabled:s.totp_enabled===1,...s.totp_secret!=null?{totpSecret:s.totp_secret}:{}}}function et(s){return{id:s.id,tenantId:s.tenant_id,name:s.name,...s.description!=null?{description:s.description}:{}}}function Un(s){return{id:s.id,name:s.name,...s.description!=null?{description:s.description}:{}}}function kn(s){return{id:s.id,tenantId:s.tenant_id,action:s.action,resourceType:s.resource_type,...s.user_id!=null?{userId:s.user_id}:{},...s.resource_id!=null?{resourceId:s.resource_id}:{},...s.old_data!=null?{oldData:JSON.parse(s.old_data)}:{},...s.new_data!=null?{newData:JSON.parse(s.new_data)}:{},createdAt:s.created_at}}var he=class{constructor(e){this.config=e}config;pool;async q(e,t=[]){let[n]=await this.pool.query(e,t);return n}async exec(e,t=[]){let[n]=await this.pool.query(e,t);return n}async connect(){let e=await import("mysql2/promise"),t=this.config;t.uri?this.pool=e.createPool(t.uri):this.pool=e.createPool({host:t.host??"localhost",port:t.port??3306,user:t.user??"root",password:t.password??"",database:t.database??"consenti"}),await this.migrate()}async disconnect(){await this.pool.end()}async migrate(){let e=await this.pool.getConnection();try{let[t]=await e.query("SHOW TABLES LIKE ?",["schema_version"]);if(t.length===0){for(let o of On.split(";").map(r=>r.trim()).filter(Boolean))await e.query(o);await this.seed(e),await e.query("INSERT IGNORE INTO schema_version (version) VALUES (2)");return}let[n]=await e.query("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1"),i=n[0]?.version??0;if(i<2){let o=["ALTER TABLE consent_records ADD COLUMN IF NOT EXISTS age_verified TINYINT(1) NOT NULL DEFAULT 0","ALTER TABLE consent_records ADD COLUMN IF NOT EXISTS parental_consent_token TEXT","ALTER TABLE consent_records ADD COLUMN IF NOT EXISTS tcf_string TEXT","ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret TEXT","ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_enabled TINYINT(1) NOT NULL DEFAULT 0"];for(let r of o)await e.query(r);await e.query("INSERT IGNORE INTO schema_version (version) VALUES (2)")}i<3&&(await e.query("ALTER TABLE user_roles ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(36) NOT NULL DEFAULT 'default'"),await e.query("INSERT IGNORE INTO schema_version (version) VALUES (3)"))}finally{e.release()}}async seed(e){await e.query("INSERT IGNORE INTO tenants (id, name, slug) VALUES (?,?,?)",[$.id,$.name,$.slug]);for(let t of j)await e.query("INSERT IGNORE INTO permissions (id, name, description) VALUES (?,?,?)",[t.id,t.name,t.description]);for(let t of Z)await e.query("INSERT IGNORE INTO roles (id, tenant_id, name, description) VALUES (?,?,?,?)",[t.id,t.tenantId,t.name,t.description]);for(let{roleId:t,permissionId:n}of ee)await e.query("INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?,?)",[t,n])}async createProfile(e){let t=(0,w.randomUUID)();await this.exec("INSERT INTO profiles (id, tenant_id, name, default_locale, profile_json) VALUES (?,?,?,?,?)",[t,e.tenantId,e.name,e.defaultLocale,JSON.stringify(e.profileJson)]);let i=(await this.q("SELECT * FROM profiles WHERE id=?",[t]))[0];if(!i)throw new Error("Profile creation failed");return Xe(i)}async updateProfile(e,t){let n=["version = version + 1"],i=[];t.name!=null&&(n.push("name=?"),i.push(t.name)),t.defaultLocale!=null&&(n.push("default_locale=?"),i.push(t.defaultLocale)),t.profileJson!=null&&(n.push("profile_json=?"),i.push(JSON.stringify(t.profileJson))),i.push(e),await this.exec(`UPDATE profiles SET ${n.join(",")} WHERE id=?`,i);let r=(await this.q("SELECT * FROM profiles WHERE id=?",[e]))[0];if(!r)throw new Error(`Profile ${e} not found`);return Xe(r)}async deleteProfile(e){await this.exec("DELETE FROM profiles WHERE id=?",[e])}async getProfile(e){let t=await this.q("SELECT * FROM profiles WHERE id=?",[e]);return t[0]?Xe(t[0]):null}async getProfiles(e){return(await this.q("SELECT * FROM profiles WHERE tenant_id=? ORDER BY created_at DESC",[e])).map(Xe)}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(i=>i.profileJson.complianceGroup===t&&i.profileJson.isActive)??null}async createConsent(e){let t=(0,w.randomUUID)();await this.exec("INSERT INTO consent_records (id, tenant_id, visitor_id, profile_id, profile_version, locale, consent_json, gpc_detected, source) VALUES (?,?,?,?,?,?,?,?,?)",[t,e.tenantId,e.visitorId,e.profileId,e.profileVersion,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source]);let i=(await this.q("SELECT * FROM consent_records WHERE id=?",[t]))[0];if(!i)throw new Error("Consent creation failed");return await this.writeHistory(t,e.tenantId,e.visitorId,null,e.consentJson,"created"),be(i)}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let i=["consent_json=?"],o=[JSON.stringify(t.consentJson)];t.locale!=null&&(i.push("locale=?"),o.push(t.locale)),t.gpcDetected!=null&&(i.push("gpc_detected=?"),o.push(t.gpcDetected?1:0)),o.push(e),await this.exec(`UPDATE consent_records SET ${i.join(",")} WHERE visitor_id=?`,o);let a=(await this.q("SELECT * FROM consent_records WHERE visitor_id=?",[e]))[0];if(!a)throw new Error(`Consent for visitor ${e} not found`);return await this.writeHistory(a.id,a.tenant_id,e,n.consentJson,t.consentJson,"updated"),be(a)}async deleteConsent(e){await this.exec("DELETE FROM consent_history WHERE visitor_id=?",[e]),await this.exec("DELETE FROM consent_records WHERE visitor_id=?",[e])}async getConsent(e){let t=await this.q("SELECT * FROM consent_records WHERE visitor_id=?",[e]);return t[0]?be(t[0]):null}async getConsents(e){let{sql:t,params:n}=this.buildConsentQuery(e),i=e.page??1,o=e.limit??50;return(await this.q(`${t} ORDER BY created_at DESC LIMIT ? OFFSET ?`,[...n,o,(i-1)*o])).map(be)}async*streamConsents(e){let{sql:t,params:n}=this.buildConsentQuery(e),i=await this.q(`${t} ORDER BY created_at ASC`,n);for(let o of i)yield be(o)}buildConsentQuery(e){let t="SELECT * FROM consent_records WHERE tenant_id=?",n=[e.tenantId];return e.profileId!=null&&(t+=" AND profile_id=?",n.push(e.profileId)),e.from!=null&&(t+=" AND created_at>=?",n.push(e.from)),e.to!=null&&(t+=" AND created_at<=?",n.push(e.to)),{sql:t,params:n}}async writeHistory(e,t,n,i,o,r){await this.exec("INSERT INTO consent_history (id, tenant_id, consent_record_id, visitor_id, old_json, new_json, action) VALUES (?,?,?,?,?,?,?)",[(0,w.randomUUID)(),t,e,n,i?JSON.stringify(i):null,JSON.stringify(o),r])}async getConsentHistory(e){return(await this.q("SELECT * FROM consent_history WHERE visitor_id=? ORDER BY created_at ASC",[e])).map(lo)}async createVisitor(e){let t=(0,w.randomUUID)();await this.exec("INSERT INTO visitors (id, tenant_id, visitor_id, country, region, city, ip_hash, user_agent_hash) VALUES (?,?,?,?,?,?,?,?)",[t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null]);let i=(await this.q("SELECT * FROM visitors WHERE id=?",[t]))[0];if(!i)throw new Error("Visitor creation failed");return Ze(i)}async updateVisitor(e,t){let n=["last_seen=NOW()"],i=[];t.country!=null&&(n.push("country=?"),i.push(t.country)),t.region!=null&&(n.push("region=?"),i.push(t.region)),t.city!=null&&(n.push("city=?"),i.push(t.city)),i.push(e),await this.exec(`UPDATE visitors SET ${n.join(",")} WHERE visitor_id=?`,i);let r=(await this.q("SELECT * FROM visitors WHERE visitor_id=?",[e]))[0];if(!r)throw new Error(`Visitor ${e} not found`);return Ze(r)}async deleteVisitor(e){await this.exec("DELETE FROM visitors WHERE visitor_id=?",[e])}async getVisitor(e){let t=await this.q("SELECT * FROM visitors WHERE visitor_id=?",[e]);return t[0]?Ze(t[0]):null}async getVisitors(e){let t="SELECT * FROM visitors WHERE tenant_id=?",n=[e.tenantId];e.from!=null&&(t+=" AND first_seen>=?",n.push(e.from)),e.to!=null&&(t+=" AND first_seen<=?",n.push(e.to));let i=e.page??1,o=e.limit??50;return(await this.q(`${t} ORDER BY first_seen DESC LIMIT ? OFFSET ?`,[...n,o,(i-1)*o])).map(Ze)}async getOverviewStats(e){let[[t],[n],[i]]=await Promise.all([this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=?",[e]),this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=? AND gpc_detected=1",[e]),this.q("SELECT COUNT(*) AS total FROM visitors WHERE tenant_id=?",[e])]),o=t?.total??0,r=n?.total??0,a=i?.total??0,c=await this.q(`SELECT jt.status, COUNT(*) AS count
94
+ `;async listProfilesSummary(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE p.tenant_id = ? ORDER BY p.created_at ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingConsentTemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.consentTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async findProfilesUsingUITemplate(e){return this.stmt(`${this.PROFILE_SUMMARY_SQL} WHERE json_extract(p.profile_json, '$.uiTemplateId') = ? ORDER BY p.name ASC`).all(e).map(n=>this.mapProfileSummary(n))}async getOptInStats(e,t){let n=["cr.tenant_id = ?"],o=[e];t.profileId&&(n.push("cr.profile_id = ?"),o.push(t.profileId)),t.from&&(n.push("cr.created_at >= ?"),o.push(t.from)),t.to&&(n.push("cr.created_at <= ?"),o.push(t.to)),t.locale&&(n.push("cr.locale = ?"),o.push(t.locale));let r=n.join(" AND "),s=this.stmt(`SELECT cr.locale, cr.consent_json FROM consent_records cr WHERE ${r}`).all(...o),a=0,c=0,l=0,d=0,u={};for(let _ of s){let w=JSON.parse(_.consent_json),R=Object.values(w),v=R.filter(D=>D==="granted").length,A=R.filter(D=>D==="denied").length,P=R.length>0?v/R.length:0;a++;let O=_.locale;u[O]||(u[O]={total:0,granted:0,denied:0,managed:0}),u[O].total++,P>=.9?(c++,u[O].granted++):A/(R.length||1)>=.9?(l++,u[O].denied++):(d++,u[O].managed++)}let m=this.stmt(`SELECT date(cr.created_at) as d, cr.consent_json FROM consent_records cr WHERE ${r} ORDER BY d ASC`).all(...o),h=new Map;for(let _ of m){let w=h.get(_.d)??{total:0,granted:0,denied:0,managed:0},R=JSON.parse(_.consent_json),v=Object.values(R),A=v.length>0?v.filter(O=>O==="granted").length/v.length:0,P=v.length>0?v.filter(O=>O==="denied").length/v.length:0;w.total++,A>=.9?w.granted++:P>=.9?w.denied++:w.managed++,h.set(_.d,w)}let S=Array.from(h.entries()).map(([_,w])=>({date:_,...w}));return{total:a,granted:c,denied:l,managed:d,grantedPct:a>0?Math.round(c/a*1e3)/10:0,deniedPct:a>0?Math.round(l/a*1e3)/10:0,managedPct:a>0?Math.round(d/a*1e3)/10:0,byLocale:u,byDate:S}}};p();function Un(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Et(i){return{id:i._id,tenantId:i.tenant_id,name:i.name,defaultLocale:i.default_locale,version:i.version,profileJson:i.profile_json,createdAt:i.created_at,updatedAt:i.updated_at}}function Rt(i){return{id:i._id,tenantId:i.tenant_id,visitorId:i.visitor_id,profileId:i.profile_id,locale:i.locale,consentJson:i.consent_json,gpcDetected:i.gpc_detected,source:i.source,createdAt:i.created_at,updatedAt:i.updated_at,...i.age_verified!=null?{ageVerified:i.age_verified}:{},...i.parental_consent_token!=null?{parentalConsentToken:i.parental_consent_token}:{},...i.tcf_string!=null?{tcfString:i.tcf_string}:{},...i.gpp_string!=null?{gppString:i.gpp_string}:{},...i.signature!=null?{signature:i.signature}:{}}}var Gc={tenant_id:1,visitor_id:1,profile_id:1,locale:1,gpc_detected:1,source:1,age_verified:1,created_at:1,updated_at:1};function jc(i){return{id:i._id,tenantId:i.tenant_id,visitorId:i.visitor_id,profileId:i.profile_id,locale:i.locale,gpcDetected:i.gpc_detected,source:i.source,createdAt:i.created_at,updatedAt:i.updated_at,...i.age_verified!=null?{ageVerified:i.age_verified}:{}}}function Bc(i){return{id:i._id,tenantId:i.tenant_id,consentRecordId:i.consent_record_id,visitorId:i.visitor_id,oldJson:i.old_json,newJson:i.new_json,action:i.action,createdAt:i.created_at}}function St(i){return{id:i._id,tenantId:i.tenant_id,visitorId:i.visitor_id,...i.country!=null?{country:i.country}:{},...i.region!=null?{region:i.region}:{},...i.city!=null?{city:i.city}:{},...i.ip_hash!=null?{ipHash:i.ip_hash}:{},...i.user_agent_hash!=null?{userAgentHash:i.user_agent_hash}:{},firstSeen:i.first_seen,lastSeen:i.last_seen}}function ze(i){return{id:i._id,tenantId:i.tenant_id,name:i.name,email:i.email,passwordHash:i.password_hash,isActive:i.is_active,createdAt:i.created_at,updatedAt:i.updated_at}}function vt(i){return{id:i._id,tenantId:i.tenant_id,name:i.name,...i.description!=null?{description:i.description}:{}}}function yo(i){return{id:i._id,name:i.name,...i.description!=null?{description:i.description}:{}}}function _o(i){return{id:i._id,tenantId:i.tenant_id,action:i.action,resourceType:i.resource_type,...i.user_id!=null?{userId:i.user_id}:{},...i.resource_id!=null?{resourceId:i.resource_id}:{},...i.old_data!=null?{oldData:i.old_data}:{},...i.new_data!=null?{newData:i.new_data}:{},createdAt:i.created_at}}var Fc={tenant_id:1,user_id:1,action:1,resource_type:1,resource_id:1,created_at:1};function $c(i){return{id:i._id,tenantId:i.tenant_id,action:i.action,resourceType:i.resource_type,...i.user_id!=null?{userId:i.user_id}:{},...i.resource_id!=null?{resourceId:i.resource_id}:{},createdAt:i.created_at}}var ke=class{constructor(e){this.config=e}config;client;db;col(e){return this.db.collection(e)}async connect(){let{MongoClient:e}=await import("mongodb"),t=this.config.uri??"mongodb://localhost:27017";this.client=new e(t),await this.client.connect(),this.db=this.client.db(this.config.database??"consenti"),await this.migrate()}async disconnect(){await this.client.close()}async migrate(){await this.createIndexes(),await this.seed()}async createIndexes(){for(let{table:e,cols:t,unique:n}of go){let o=Object.fromEntries(t.map(r=>[r,1]));await this.col(e).createIndex(o,n?{unique:!0}:void 0)}}async seed(){let{id:e,name:t,slug:n}=te;await this.col("tenants").findOne({_id:e})||await this.col("tenants").insertOne({_id:e,name:t,slug:n});for(let r of ee){let s={_id:r.id,name:r.name,description:r.description};await this.col("permissions").updateOne({_id:r.id},{$setOnInsert:s},{upsert:!0})}for(let r of pe){let s={_id:r.id,tenant_id:r.tenantId,name:r.name,description:r.description};await this.col("roles").updateOne({_id:r.id},{$setOnInsert:s},{upsert:!0})}let o=this.col("role_permissions");for(let{roleId:r,permissionId:s}of me)await o.updateOne({role_id:r,permission_id:s},{$setOnInsert:{role_id:r,permission_id:s}},{upsert:!0})}async createProfile(e){let t=new Date().toISOString(),o={_id:z(),tenant_id:e.tenantId,name:e.name,default_locale:e.defaultLocale,version:1,profile_json:e.profileJson,created_at:t,updated_at:t};return await this.col("profiles").insertOne(o),Et(o)}async updateProfile(e,t){let o={updated_at:new Date().toISOString()};t.name!=null&&(o.name=t.name),t.defaultLocale!=null&&(o.default_locale=t.defaultLocale),t.profileJson!=null&&(o.profile_json=t.profileJson),t.version!=null&&(o.version=t.version);let r=await this.col("profiles").findOneAndUpdate({_id:e},{$set:o},{returnDocument:"after"});if(!r)throw new Error(`Profile ${e} not found`);return Et(r)}async deleteProfile(e){await this.col("profiles").deleteOne({_id:e})}async getProfile(e){let t=await this.col("profiles").findOne({_id:e});return t?Et(t):null}async getProfiles(e){return(await this.col("profiles").find({tenant_id:e}).toArray()).map(Et)}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(o=>(o.profileJson.complianceGroup===t||o.profileJson.customComplianceGroup===t)&&o.profileJson.isActive)??null}async createConsent(e){let t=new Date().toISOString(),n={_id:K(),tenant_id:e.tenantId,visitor_id:e.visitorId,profile_id:e.profileId,locale:e.locale,consent_json:e.consentJson,gpc_detected:e.gpcDetected,source:e.source,created_at:t,updated_at:t,...e.ageVerified!=null?{age_verified:e.ageVerified}:{},...e.parentalConsentToken!=null?{parental_consent_token:e.parentalConsentToken}:{},...e.tcfString!=null?{tcf_string:e.tcfString}:{},...e.gppString!=null?{gpp_string:e.gppString}:{},...e.signature!=null?{signature:e.signature}:{}};return await this.col("consent_records").insertOne(n),await this.writeHistory(n._id,e.tenantId,e.visitorId,null,e.consentJson,"created"),Rt(n)}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let r={updated_at:new Date().toISOString(),consent_json:t.consentJson};t.locale!=null&&(r.locale=t.locale),t.gpcDetected!=null&&(r.gpc_detected=t.gpcDetected),t.signature!=null&&(r.signature=t.signature);let s=await this.col("consent_records").findOneAndUpdate({visitor_id:e},{$set:r},{returnDocument:"after"});if(!s)throw new Error(`Consent for visitor ${e} not found`);return await this.writeHistory(s._id,s.tenant_id,e,n.consentJson,t.consentJson,"updated"),Rt(s)}async deleteConsent(e){await this.col("consent_history").deleteMany({visitor_id:e}),await this.col("consent_records").deleteOne({visitor_id:e})}async getConsent(e){let t=await this.col("consent_records").findOne({visitor_id:e});return t?Rt(t):null}async getConsents(e){let t=this.buildConsentFilter(e),n=e.page??1,o=e.limit??50,[r,s]=await Promise.all([this.col("consent_records").find(t,{projection:Gc}).sort({created_at:-1}).skip((n-1)*o).limit(o).toArray(),this.col("consent_records").countDocuments(t)]);return{items:r.map(jc),total:s,page:n,limit:o}}async*streamConsents(e){let t=this.buildConsentFilter(e),n=this.col("consent_records").find(t).sort({created_at:1});for await(let o of n)yield Rt(o)}buildConsentFilter(e){let t={tenant_id:e.tenantId};if(e.profileId!=null&&(t.profile_id=e.profileId),e.from!=null||e.to!=null){let n={};e.from!=null&&(n.$gte=e.from),e.to!=null&&(n.$lte=e.to),t.created_at=n}if(e.q){let n={$regex:"^"+Un(e.q),$options:"i"};t.$or=[{visitor_id:n},{profile_id:n},{locale:n},{source:n}]}return t}async writeHistory(e,t,n,o,r,s){let a={_id:(0,C.randomUUID)(),tenant_id:t,consent_record_id:e,visitor_id:n,old_json:o,new_json:r,action:s,created_at:new Date().toISOString()};await this.col("consent_history").insertOne(a)}async getConsentHistory(e){return(await this.col("consent_history").find({visitor_id:e}).sort({created_at:1}).toArray()).map(Bc)}async createNoticeShown(e){let t={_id:(0,C.randomUUID)(),tenant_id:e.tenantId,visitor_id:e.visitorId,profile_id:e.profileId,locale:e.locale,created_at:new Date().toISOString()};return await this.col("notice_shown").insertOne(t),{id:t._id,tenantId:t.tenant_id,visitorId:t.visitor_id,profileId:t.profile_id,locale:t.locale,createdAt:t.created_at}}async getNoticeShownForVisitor(e){return(await this.col("notice_shown").find({visitor_id:e}).sort({created_at:-1}).toArray()).map(n=>({id:n._id,tenantId:n.tenant_id,visitorId:n.visitor_id,profileId:n.profile_id,locale:n.locale,createdAt:n.created_at}))}async createVisitor(e){let t=new Date().toISOString(),n={_id:q(),tenant_id:e.tenantId,visitor_id:e.visitorId,first_seen:t,last_seen:t,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ipHash!=null?{ip_hash:e.ipHash}:{},...e.userAgentHash!=null?{user_agent_hash:e.userAgentHash}:{}};return await this.col("visitors").insertOne(n),St(n)}async updateVisitor(e,t){let n={last_seen:t.lastSeen??new Date().toISOString()};t.country!=null&&(n.country=t.country),t.region!=null&&(n.region=t.region),t.city!=null&&(n.city=t.city);let o=await this.col("visitors").findOneAndUpdate({visitor_id:e},{$set:n},{returnDocument:"after"});if(!o)throw new Error(`Visitor ${e} not found`);return St(o)}async deleteVisitor(e){await this.col("visitors").deleteOne({visitor_id:e})}async getVisitor(e){let t=await this.col("visitors").findOne({visitor_id:e});return t?St(t):null}async getVisitors(e){let t={tenant_id:e.tenantId};if(e.from!=null||e.to!=null){let a={};e.from!=null&&(a.$gte=e.from),e.to!=null&&(a.$lte=e.to),t.first_seen=a}if(e.q){let a={$regex:"^"+Un(e.q),$options:"i"};t.$or=[{visitor_id:a},{country:a}]}let n=e.page??1,o=e.limit??50,[r,s]=await Promise.all([this.col("visitors").find(t).sort({first_seen:-1}).skip((n-1)*o).limit(o).toArray(),this.col("visitors").countDocuments(t)]);return{items:r.map(St),total:s,page:n,limit:o}}async getOverviewStats(e){let[t,n,o]=await Promise.all([this.col("consent_records").countDocuments({tenant_id:e}),this.col("consent_records").countDocuments({tenant_id:e,gpc_detected:!0}),this.col("visitors").countDocuments({tenant_id:e})]),r=[{$match:{tenant_id:e}},{$addFields:{values:{$objectToArray:"$consent_json"}}},{$unwind:"$values"},{$group:{_id:"$values.v",count:{$sum:1}}}],s=await this.col("consent_records").aggregate(r).toArray(),a=0,c=0,l=0;for(let d of s)l+=d.count,d._id==="granted"&&(a=d.count),d._id==="denied"&&(c=d.count);return{totalConsents:t,acceptedPct:l>0?Math.round(a/l*100):0,rejectedPct:l>0?Math.round(c/l*100):0,totalVisitors:o,gpcDetectedCount:n}}async getCategoryStats(e){let t=[{$match:{tenant_id:e}},{$addFields:{pairs:{$objectToArray:"$consent_json"}}},{$unwind:"$pairs"},{$group:{_id:{cookie:"$pairs.k",status:"$pairs.v"},count:{$sum:1}}}],n=await this.col("consent_records").aggregate(t).toArray(),o={};for(let r of n){let s=r._id.cookie;o[s]||(o[s]={granted:0,denied:0,objected:0});let a=o[s];a&&(r._id.status==="granted"&&(a.granted+=r.count),r._id.status==="denied"&&(a.denied+=r.count),r._id.status==="objected"&&(a.objected+=r.count))}return o}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString(),o=[{$match:{tenant_id:e,created_at:{$gte:n}}},{$group:{_id:{$substr:["$created_at",0,10]},count:{$sum:1}}},{$sort:{_id:1}}];return(await this.col("consent_records").aggregate(o).toArray()).map(s=>({date:s._id,count:s.count}))}async createUser(e){let t=new Date().toISOString(),n={_id:(0,C.randomUUID)(),tenant_id:e.tenantId,name:e.name,email:e.email,password_hash:e.passwordHash,is_active:!0,created_at:t,updated_at:t};return await this.col("users").insertOne(n),ze(n)}async updateUser(e,t){let n={updated_at:new Date().toISOString()};t.name!=null&&(n.name=t.name),t.email!=null&&(n.email=t.email),t.passwordHash!=null&&(n.password_hash=t.passwordHash),t.isActive!=null&&(n.is_active=t.isActive);let o=await this.col("users").findOneAndUpdate({_id:e},{$set:n},{returnDocument:"after"});if(!o)throw new Error(`User ${e} not found`);return ze(o)}async deleteUser(e){await this.col("user_roles").deleteMany({user_id:e}),await this.col("users").deleteOne({_id:e})}async getUserById(e){let t=await this.col("users").findOne({_id:e});return t?ze(t):null}async getUserByEmail(e){let t=await this.col("users").findOne({email:e});return t?ze(t):null}async getUsers(e){return(await this.col("users").find({tenant_id:e}).toArray()).map(ze)}async countUsers(e){return this.col("users").countDocuments(e?{tenant_id:e}:{})}async getRoles(e){return(await this.col("roles").find({tenant_id:e}).toArray()).map(vt)}async createRole(e){let t={_id:(0,C.randomUUID)(),tenant_id:e.tenantId,name:e.name,...e.description!=null?{description:e.description}:{}};return await this.col("roles").insertOne(t),vt(t)}async updateRole(e,t){let n={};t.name!=null&&(n.name=t.name),t.description!=null&&(n.description=t.description);let o=await this.col("roles").findOneAndUpdate({_id:e},{$set:n},{returnDocument:"after"});if(!o)throw new Error(`Role ${e} not found`);return vt(o)}async deleteRole(e){await this.col("role_permissions").deleteMany({role_id:e}),await this.col("user_roles").deleteMany({role_id:e}),await this.col("roles").deleteOne({_id:e})}async getAllPermissions(){return(await this.col("permissions").find({}).toArray()).map(yo)}async getPermissionsForRole(e){let n=(await this.col("role_permissions").find({role_id:e}).toArray()).map(r=>r.permission_id);return n.length===0?[]:(await this.col("permissions").find({_id:{$in:n}}).toArray()).map(yo)}async getUserRoles(e,t){let n=t?{user_id:e,tenant_id:t}:{user_id:e},r=(await this.col("user_roles").find(n).toArray()).map(a=>a.role_id);return r.length===0?[]:(await this.col("roles").find({_id:{$in:r}}).toArray()).map(vt)}async assignRole(e,t,n="default"){await this.col("user_roles").updateOne({user_id:e,role_id:t,tenant_id:n},{$setOnInsert:{user_id:e,role_id:t,tenant_id:n}},{upsert:!0})}async revokeRole(e,t,n){n?await this.col("user_roles").deleteOne({user_id:e,role_id:t,tenant_id:n}):await this.col("user_roles").deleteMany({user_id:e,role_id:t})}async assignPermissionToRole(e,t){await this.col("role_permissions").updateOne({role_id:e,permission_id:t},{$setOnInsert:{role_id:e,permission_id:t}},{upsert:!0})}async revokePermissionFromRole(e,t){await this.col("role_permissions").deleteOne({role_id:e,permission_id:t})}async createLog(e){let t={_id:(0,C.randomUUID)(),tenant_id:e.tenantId,action:e.action,resource_type:e.resourceType,...e.userId!=null?{user_id:e.userId}:{},...e.resourceId!=null?{resource_id:e.resourceId}:{},...e.oldData!=null?{old_data:e.oldData}:{},...e.newData!=null?{new_data:e.newData}:{},created_at:new Date().toISOString()};await this.col("audit_logs").insertOne(t)}async getLogs(e){let t=this.buildAuditFilter(e),n=e.page??1,o=e.limit??50,[r,s]=await Promise.all([this.col("audit_logs").find(t,{projection:Fc}).sort({created_at:-1}).skip((n-1)*o).limit(o).toArray(),this.col("audit_logs").countDocuments(t)]);return{items:r.map($c),total:s,page:n,limit:o}}async getAuditLogById(e){let t=await this.col("audit_logs").findOne({_id:e});return t?_o(t):null}async*streamAuditLogs(e){let t=this.buildAuditFilter(e),n=this.col("audit_logs").find(t).sort({created_at:1});for await(let o of n)yield _o(o)}buildAuditFilter(e){let t={tenant_id:e.tenantId};if(e.action!=null&&(t.action=e.action),e.resourceType!=null&&(t.resource_type=e.resourceType),e.from!=null||e.to!=null){let n={};e.from!=null&&(n.$gte=e.from),e.to!=null&&(n.$lte=e.to),t.created_at=n}if(e.q){let n={$regex:"^"+Un(e.q),$options:"i"};t.$or=[{action:n},{resource_type:n},{resource_id:n},{user_id:n}]}return t}async getCountries(e){let t=[{$match:{tenant_id:e}},{$lookup:{from:"visitors",localField:"visitor_id",foreignField:"visitor_id",as:"v"}},{$unwind:"$v"},{$match:{"v.country":{$ne:null}}},{$group:{_id:"$v.country",count:{$sum:1}}},{$sort:{count:-1}},{$limit:50}];return(await this.col("consent_records").aggregate(t).toArray()).map(o=>({country:o._id,count:o.count}))}async getGpcStats(e){let t=await this.col("consent_records").countDocuments({tenant_id:e}),n=await this.col("consent_records").countDocuments({tenant_id:e,gpc_detected:!0});return{detected:n,total:t,rate:t>0?Math.round(n/t*100):0}}async getTenants(){return(await this.col("tenants").find({}).toArray()).map(t=>({id:t._id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}mapApiKey(e){return{id:e._id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active,...e.created_by!==void 0?{createdBy:e.created_by}:{},...e.expire_by!==void 0?{expireBy:e.expire_by}:{},createdAt:e.created_at,...e.updated_at!==void 0?{updatedAt:e.updated_at}:{}}}async createApiKey(e){let t=new Date().toISOString(),n={_id:(0,C.randomUUID)(),tenant_id:e.tenantId,key_hash:e.keyHash,name:e.name,is_active:!0,...e.createdBy!==void 0?{created_by:e.createdBy}:{},...e.expireBy!==void 0?{expire_by:e.expireBy}:{},created_at:t,updated_at:t};return await this.col("api_keys").insertOne(n),this.mapApiKey(n)}async getApiKeyByHash(e){let t=await this.col("api_keys").findOne({key_hash:e,is_active:!0});return t?this.mapApiKey(t):null}async revokeApiKey(e){await this.col("api_keys").updateOne({_id:e},{$set:{is_active:!1,updated_at:new Date().toISOString()}})}async reactivateApiKey(e){let t=await this.col("api_keys").findOne({_id:e});if(!t)return;let n=t.expire_by&&new Date(t.expire_by)<=new Date;await this.col("api_keys").updateOne({_id:e},{$set:{is_active:!0,updated_at:new Date().toISOString()},...n?{$unset:{expire_by:""}}:{}})}async deleteApiKey(e){await this.col("api_keys").deleteOne({_id:e})}async getApiKeys(e){return(await this.col("api_keys").find({tenant_id:e}).sort({created_at:-1}).toArray()).map(n=>this.mapApiKey(n))}async createTenant(e){let t=(0,C.randomUUID)(),n=new Date().toISOString(),o={_id:t,name:e.name,slug:e.slug,created_at:n,updated_at:n};return await this.col("tenants").insertOne(o),{id:t,name:e.name,slug:e.slug,createdAt:n,updatedAt:n}}async updateTenant(e,t){let o={updated_at:new Date().toISOString()};t.name!=null&&(o.name=t.name),t.slug!=null&&(o.slug=t.slug),await this.col("tenants").updateOne({_id:e},{$set:o});let r=await this.col("tenants").findOne({_id:e});if(!r)throw new Error(`Tenant ${e} not found`);return{id:r._id,name:r.name,slug:r.slug,createdAt:r.created_at,updatedAt:r.updated_at}}async deleteTenant(e){await this.col("tenants").deleteOne({_id:e})}async getSettings(e){let t=await this.col("tenant_settings").findOne({_id:e});return{...t?.allowed_origins!==void 0?{allowedOrigins:t.allowed_origins}:{},...t?.admin_allowed_origins!==void 0?{adminAllowedOrigins:t.admin_allowed_origins}:{},...t?.setup_completed!==void 0?{setupCompleted:t.setup_completed}:{},...t?.profiles_seeded!==void 0?{profilesSeeded:t.profiles_seeded}:{},...t?.tcf_confirmation!==void 0?{tcfConfirmation:t.tcf_confirmation}:{},...t?.gpp_confirmation!==void 0?{gppConfirmation:t.gpp_confirmation}:{}}}async updateSettings(e,t){let n={updated_at:new Date().toISOString()};return t.allowedOrigins!==void 0&&(n.allowed_origins=t.allowedOrigins),t.adminAllowedOrigins!==void 0&&(n.admin_allowed_origins=t.adminAllowedOrigins),t.setupCompleted!==void 0&&(n.setup_completed=t.setupCompleted),t.profilesSeeded!==void 0&&(n.profiles_seeded=t.profilesSeeded),t.tcfConfirmation!==void 0&&(n.tcf_confirmation=t.tcfConfirmation),t.gppConfirmation!==void 0&&(n.gpp_confirmation=t.gppConfirmation),await this.col("tenant_settings").updateOne({_id:e},{$set:n},{upsert:!0}),this.getSettings(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=await this.col("consent_records").find({created_at:{$lt:t}}).toArray();if(n.length===0)return 0;let o=n.map(r=>r.visitor_id);return await this.col("consent_history").deleteMany({visitor_id:{$in:o}}),await this.col("consent_records").deleteMany({visitor_id:{$in:o}}),n.length}async createConsentTemplate(){throw new Error("Not implemented")}async updateConsentTemplate(){throw new Error("Not implemented")}async deleteConsentTemplate(){throw new Error("Not implemented")}async getConsentTemplate(){throw new Error("Not implemented")}async getConsentTemplates(){throw new Error("Not implemented")}async copyConsentTemplate(){throw new Error("Not implemented")}async createUITemplate(){throw new Error("Not implemented")}async updateUITemplate(){throw new Error("Not implemented")}async deleteUITemplate(){throw new Error("Not implemented")}async getUITemplate(){throw new Error("Not implemented")}async getUITemplates(){throw new Error("Not implemented")}async copyUITemplate(){throw new Error("Not implemented")}async listProfilesSummary(){return[]}async findProfilesUsingConsentTemplate(){return[]}async findProfilesUsingUITemplate(){return[]}async getOptInStats(){throw new Error("Not implemented")}};p();function Ct(i){return{id:i.id,tenantId:i.tenant_id,name:i.name,defaultLocale:i.default_locale,version:i.version,profileJson:JSON.parse(i.profile_json),createdAt:i.created_at,updatedAt:i.updated_at}}function At(i){return{id:i.id,tenantId:i.tenant_id,visitorId:i.visitor_id,profileId:i.profile_id,locale:i.locale,consentJson:JSON.parse(i.consent_json),gpcDetected:i.gpc_detected===1,source:i.source,createdAt:i.created_at,updatedAt:i.updated_at,...i.age_verified!=null?{ageVerified:i.age_verified===1}:{},...i.parental_consent_token!=null?{parentalConsentToken:i.parental_consent_token}:{},...i.tcf_string!=null?{tcfString:i.tcf_string}:{},...i.gpp_string!=null?{gppString:i.gpp_string}:{},...i.signature!=null?{signature:i.signature}:{}}}var Hc="id, tenant_id, visitor_id, profile_id, locale, gpc_detected, source, age_verified, created_at, updated_at";function Vc(i){return{id:i.id,tenantId:i.tenant_id,visitorId:i.visitor_id,profileId:i.profile_id,locale:i.locale,gpcDetected:i.gpc_detected===1,source:i.source,createdAt:i.created_at,updatedAt:i.updated_at,...i.age_verified!=null?{ageVerified:i.age_verified===1}:{}}}function Wc(i){return{id:i.id,tenantId:i.tenant_id,consentRecordId:i.consent_record_id,visitorId:i.visitor_id,oldJson:i.old_json?JSON.parse(i.old_json):null,newJson:JSON.parse(i.new_json),action:i.action,createdAt:i.created_at}}function Pt(i){return{id:i.id,tenantId:i.tenant_id,visitorId:i.visitor_id,...i.country!=null?{country:i.country}:{},...i.region!=null?{region:i.region}:{},...i.city!=null?{city:i.city}:{},...i.ip_hash!=null?{ipHash:i.ip_hash}:{},...i.user_agent_hash!=null?{userAgentHash:i.user_agent_hash}:{},firstSeen:i.first_seen,lastSeen:i.last_seen}}function Ke(i){return{id:i.id,tenantId:i.tenant_id,name:i.name,email:i.email,passwordHash:i.password_hash,isActive:i.is_active===1,createdAt:i.created_at,updatedAt:i.updated_at,totpEnabled:i.totp_enabled===1,...i.totp_secret!=null?{totpSecret:i.totp_secret}:{}}}function Tt(i){return{id:i.id,tenantId:i.tenant_id,name:i.name,...i.description!=null?{description:i.description}:{}}}function wo(i){return{id:i.id,name:i.name,...i.description!=null?{description:i.description}:{}}}function Eo(i){return{id:i.id,tenantId:i.tenant_id,action:i.action,resourceType:i.resource_type,...i.user_id!=null?{userId:i.user_id}:{},...i.resource_id!=null?{resourceId:i.resource_id}:{},...i.old_data!=null?{oldData:JSON.parse(i.old_data)}:{},...i.new_data!=null?{newData:JSON.parse(i.new_data)}:{},createdAt:i.created_at}}var qc="id, tenant_id, user_id, action, resource_type, resource_id, created_at";function Jc(i){return{id:i.id,tenantId:i.tenant_id,action:i.action,resourceType:i.resource_type,...i.user_id!=null?{userId:i.user_id}:{},...i.resource_id!=null?{resourceId:i.resource_id}:{},createdAt:i.created_at}}var Le=class{constructor(e){this.config=e}config;pool;async q(e,t=[]){let n=this.config.statementTimeoutMs,[o]=n?await this.pool.query({sql:e,timeout:n},t):await this.pool.query(e,t);return o}async exec(e,t=[]){let n=this.config.statementTimeoutMs,[o]=n?await this.pool.query({sql:e,timeout:n},t):await this.pool.query(e,t);return o}async connect(){let e=await import("mysql2/promise"),t=this.config;this.pool=e.createPool({...t.uri?{uri:t.uri}:{host:t.host??"localhost",port:t.port??3306,user:t.user??"root",password:t.password??"",database:t.database??"consenti"},connectionLimit:t.poolMax??10}),await this.migrate()}async disconnect(){await this.pool.end()}async migrate(){let e=await this.pool.getConnection();try{let[t]=await e.query("SHOW TABLES LIKE ?",["schema_version"]);if(t.length===0){for(let n of ho.split(";").map(o=>o.trim()).filter(Boolean))await e.query(n);await this.seed(e),await e.query("INSERT IGNORE INTO schema_version (version) VALUES (1)")}}finally{e.release()}}async seed(e){await e.query("INSERT IGNORE INTO tenants (id, name, slug) VALUES (?,?,?)",[te.id,te.name,te.slug]);for(let t of ee)await e.query("INSERT IGNORE INTO permissions (id, name, description) VALUES (?,?,?)",[t.id,t.name,t.description]);for(let t of pe)await e.query("INSERT IGNORE INTO roles (id, tenant_id, name, description) VALUES (?,?,?,?)",[t.id,t.tenantId,t.name,t.description]);for(let{roleId:t,permissionId:n}of me)await e.query("INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?,?)",[t,n])}async createProfile(e){let t=z();await this.exec("INSERT INTO profiles (id, tenant_id, name, default_locale, version, profile_json) VALUES (?,?,?,?,?,?)",[t,e.tenantId,e.name,e.defaultLocale,1,JSON.stringify(e.profileJson)]);let o=(await this.q("SELECT * FROM profiles WHERE id=?",[t]))[0];if(!o)throw new Error("Profile creation failed");return Ct(o)}async updateProfile(e,t){let n=[],o=[];t.name!=null&&(n.push("name=?"),o.push(t.name)),t.defaultLocale!=null&&(n.push("default_locale=?"),o.push(t.defaultLocale)),t.profileJson!=null&&(n.push("profile_json=?"),o.push(JSON.stringify(t.profileJson))),t.version!=null&&(n.push("version=?"),o.push(t.version)),n.length>0&&(o.push(e),await this.exec(`UPDATE profiles SET ${n.join(",")} WHERE id=?`,o));let s=(await this.q("SELECT * FROM profiles WHERE id=?",[e]))[0];if(!s)throw new Error(`Profile ${e} not found`);return Ct(s)}async deleteProfile(e){await this.exec("DELETE FROM profiles WHERE id=?",[e])}async getProfile(e){let t=await this.q("SELECT * FROM profiles WHERE id=?",[e]);return t[0]?Ct(t[0]):null}async getProfiles(e){return(await this.q("SELECT * FROM profiles WHERE tenant_id=? ORDER BY created_at DESC",[e])).map(Ct)}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(o=>(o.profileJson.complianceGroup===t||o.profileJson.customComplianceGroup===t)&&o.profileJson.isActive)??null}async createConsent(e){let t=K();await this.exec("INSERT INTO consent_records (id, tenant_id, visitor_id, profile_id, locale, consent_json, gpc_detected, source, age_verified, parental_consent_token, tcf_string, gpp_string, signature) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.tenantId,e.visitorId,e.profileId,e.locale,JSON.stringify(e.consentJson),e.gpcDetected?1:0,e.source,e.ageVerified?1:0,e.parentalConsentToken??null,e.tcfString??null,e.gppString??null,e.signature??null]);let o=(await this.q("SELECT * FROM consent_records WHERE id=?",[t]))[0];if(!o)throw new Error("Consent creation failed");return await this.writeHistory(t,e.tenantId,e.visitorId,null,e.consentJson,"created"),At(o)}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let o=["consent_json=?"],r=[JSON.stringify(t.consentJson)];t.locale!=null&&(o.push("locale=?"),r.push(t.locale)),t.gpcDetected!=null&&(o.push("gpc_detected=?"),r.push(t.gpcDetected?1:0)),t.signature!=null&&(o.push("signature=?"),r.push(t.signature)),r.push(e),await this.exec(`UPDATE consent_records SET ${o.join(",")} WHERE visitor_id=?`,r);let a=(await this.q("SELECT * FROM consent_records WHERE visitor_id=?",[e]))[0];if(!a)throw new Error(`Consent for visitor ${e} not found`);return await this.writeHistory(a.id,a.tenant_id,e,n.consentJson,t.consentJson,"updated"),At(a)}async deleteConsent(e){await this.exec("DELETE FROM consent_history WHERE visitor_id=?",[e]),await this.exec("DELETE FROM consent_records WHERE visitor_id=?",[e])}async getConsent(e){let t=await this.q("SELECT * FROM consent_records WHERE visitor_id=?",[e]);return t[0]?At(t[0]):null}async getConsents(e){let{where:t,params:n}=this.buildConsentWhere(e),o=e.page??1,r=e.limit??50,[s,a]=await Promise.all([this.q(`SELECT ${Hc} ${t} ORDER BY created_at DESC LIMIT ? OFFSET ?`,[...n,r,(o-1)*r]),this.q(`SELECT COUNT(*) AS total ${t}`,n)]);return{items:s.map(Vc),total:a[0]?.total??0,page:o,limit:r}}async*streamConsents(e){let{where:t,params:n}=this.buildConsentWhere(e),o=await this.q(`SELECT * ${t} ORDER BY created_at ASC`,n);for(let r of o)yield At(r)}buildConsentWhere(e){let t="FROM consent_records WHERE tenant_id=?",n=[e.tenantId];if(e.profileId!=null&&(t+=" AND profile_id=?",n.push(e.profileId)),e.from!=null&&(t+=" AND created_at>=?",n.push(e.from)),e.to!=null&&(t+=" AND created_at<=?",n.push(e.to)),e.q){t+=" AND (visitor_id LIKE ? OR profile_id LIKE ? OR locale LIKE ? OR source LIKE ?) ESCAPE '\\\\'";let o=j(e.q);n.push(o,o,o,o)}return{where:t,params:n}}async writeHistory(e,t,n,o,r,s){await this.exec("INSERT INTO consent_history (id, tenant_id, consent_record_id, visitor_id, old_json, new_json, action) VALUES (?,?,?,?,?,?,?)",[(0,C.randomUUID)(),t,e,n,o?JSON.stringify(o):null,JSON.stringify(r),s])}async getConsentHistory(e){return(await this.q("SELECT * FROM consent_history WHERE visitor_id=? ORDER BY created_at ASC",[e])).map(Wc)}async createNoticeShown(e){let t=(0,C.randomUUID)();await this.exec("INSERT INTO notice_shown (id, tenant_id, visitor_id, profile_id, locale) VALUES (?,?,?,?,?)",[t,e.tenantId,e.visitorId,e.profileId,e.locale]);let o=(await this.q("SELECT * FROM notice_shown WHERE id=?",[t]))[0];return{id:o.id,tenantId:o.tenant_id,visitorId:o.visitor_id,profileId:o.profile_id,locale:o.locale,createdAt:o.created_at}}async getNoticeShownForVisitor(e){return(await this.q("SELECT * FROM notice_shown WHERE visitor_id=? ORDER BY created_at DESC",[e])).map(n=>({id:n.id,tenantId:n.tenant_id,visitorId:n.visitor_id,profileId:n.profile_id,locale:n.locale,createdAt:n.created_at}))}async createVisitor(e){let t=q();await this.exec("INSERT INTO visitors (id, tenant_id, visitor_id, country, region, city, ip_hash, user_agent_hash) VALUES (?,?,?,?,?,?,?,?)",[t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null]);let o=(await this.q("SELECT * FROM visitors WHERE id=?",[t]))[0];if(!o)throw new Error("Visitor creation failed");return Pt(o)}async updateVisitor(e,t){let n=["last_seen=NOW()"],o=[];t.country!=null&&(n.push("country=?"),o.push(t.country)),t.region!=null&&(n.push("region=?"),o.push(t.region)),t.city!=null&&(n.push("city=?"),o.push(t.city)),o.push(e),await this.exec(`UPDATE visitors SET ${n.join(",")} WHERE visitor_id=?`,o);let s=(await this.q("SELECT * FROM visitors WHERE visitor_id=?",[e]))[0];if(!s)throw new Error(`Visitor ${e} not found`);return Pt(s)}async deleteVisitor(e){await this.exec("DELETE FROM visitors WHERE visitor_id=?",[e])}async getVisitor(e){let t=await this.q("SELECT * FROM visitors WHERE visitor_id=?",[e]);return t[0]?Pt(t[0]):null}async getVisitors(e){let t="FROM visitors WHERE tenant_id=?",n=[e.tenantId];if(e.from!=null&&(t+=" AND first_seen>=?",n.push(e.from)),e.to!=null&&(t+=" AND first_seen<=?",n.push(e.to)),e.q){t+=" AND (visitor_id LIKE ? OR country LIKE ?) ESCAPE '\\\\'";let c=j(e.q);n.push(c,c)}let o=e.page??1,r=e.limit??50,[s,a]=await Promise.all([this.q(`SELECT * ${t} ORDER BY first_seen DESC LIMIT ? OFFSET ?`,[...n,r,(o-1)*r]),this.q(`SELECT COUNT(*) AS total ${t}`,n)]);return{items:s.map(Pt),total:a[0]?.total??0,page:o,limit:r}}async getOverviewStats(e){let[[t],[n],[o]]=await Promise.all([this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=?",[e]),this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=? AND gpc_detected=1",[e]),this.q("SELECT COUNT(*) AS total FROM visitors WHERE tenant_id=?",[e])]),r=t?.total??0,s=n?.total??0,a=o?.total??0,c=await this.q(`SELECT jt.status, COUNT(*) AS count
109
95
  FROM consent_records cr
110
96
  JOIN JSON_TABLE(cr.consent_json, '$.*' COLUMNS (status VARCHAR(20) PATH '$')) AS jt
111
97
  WHERE cr.tenant_id=?
112
- GROUP BY jt.status`,[e]),l=0,u=0,d=0;for(let p of c)d+=p.count,p.status==="granted"&&(l=p.count),p.status==="denied"&&(u=p.count);return{totalConsents:o,acceptedPct:d>0?Math.round(l/d*100):0,rejectedPct:d>0?Math.round(u/d*100):0,totalVisitors:a,gpcDetectedCount:r}}async getCategoryStats(e){let t=await this.q(`SELECT jt.cookie_id, jt.status, COUNT(*) AS count
98
+ GROUP BY jt.status`,[e]),l=0,d=0,u=0;for(let m of c)u+=m.count,m.status==="granted"&&(l=m.count),m.status==="denied"&&(d=m.count);return{totalConsents:r,acceptedPct:u>0?Math.round(l/u*100):0,rejectedPct:u>0?Math.round(d/u*100):0,totalVisitors:a,gpcDetectedCount:s}}async getCategoryStats(e){let t=await this.q(`SELECT jt.cookie_id, jt.status, COUNT(*) AS count
113
99
  FROM consent_records cr
114
100
  JOIN JSON_TABLE(cr.consent_json, '$.*' COLUMNS (NESTED PATH '$' COLUMNS (
115
101
  cookie_id VARCHAR(100) PATH '$.k',
116
102
  status VARCHAR(20) PATH '$.v'
117
103
  ))) AS jt
118
104
  WHERE cr.tenant_id=?
119
- GROUP BY jt.cookie_id, jt.status`,[e]),n={};for(let i of t){n[i.cookie_id]||(n[i.cookie_id]={granted:0,denied:0,objected:0});let o=n[i.cookie_id];o&&(i.status==="granted"&&(o.granted+=i.count),i.status==="denied"&&(o.denied+=i.count),i.status==="objected"&&(o.objected+=i.count))}return n}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString().slice(0,10);return(await this.q(`SELECT DATE(created_at) AS date, COUNT(*) AS count
105
+ GROUP BY jt.cookie_id, jt.status`,[e]),n={};for(let o of t){n[o.cookie_id]||(n[o.cookie_id]={granted:0,denied:0,objected:0});let r=n[o.cookie_id];r&&(o.status==="granted"&&(r.granted+=o.count),o.status==="denied"&&(r.denied+=o.count),o.status==="objected"&&(r.objected+=o.count))}return n}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString().slice(0,10);return(await this.q(`SELECT DATE(created_at) AS date, COUNT(*) AS count
120
106
  FROM consent_records WHERE tenant_id=? AND created_at>=?
121
- GROUP BY DATE(created_at) ORDER BY date ASC`,[e,n])).map(o=>({date:String(o.date),count:o.count}))}async createUser(e){let t=(0,w.randomUUID)();await this.exec("INSERT INTO users (id, tenant_id, name, email, password_hash) VALUES (?,?,?,?,?)",[t,e.tenantId,e.name,e.email,e.passwordHash]);let i=(await this.q("SELECT * FROM users WHERE id=?",[t]))[0];if(!i)throw new Error("User creation failed");return Oe(i)}async updateUser(e,t){let n=[],i=[];t.name!=null&&(n.push("name=?"),i.push(t.name)),t.email!=null&&(n.push("email=?"),i.push(t.email)),t.passwordHash!=null&&(n.push("password_hash=?"),i.push(t.passwordHash)),t.isActive!=null&&(n.push("is_active=?"),i.push(t.isActive?1:0)),n.length>0&&(i.push(e),await this.exec(`UPDATE users SET ${n.join(",")} WHERE id=?`,i));let r=(await this.q("SELECT * FROM users WHERE id=?",[e]))[0];if(!r)throw new Error(`User ${e} not found`);return Oe(r)}async deleteUser(e){await this.exec("DELETE FROM user_roles WHERE user_id=?",[e]),await this.exec("DELETE FROM users WHERE id=?",[e])}async getUserById(e){let t=await this.q("SELECT * FROM users WHERE id=?",[e]);return t[0]?Oe(t[0]):null}async getUserByEmail(e){let t=await this.q("SELECT * FROM users WHERE email=?",[e]);return t[0]?Oe(t[0]):null}async getUsers(e){return(await this.q("SELECT * FROM users WHERE tenant_id=? ORDER BY created_at DESC",[e])).map(Oe)}async countUsers(e){return(e?await this.q("SELECT COUNT(*) AS total FROM users WHERE tenant_id=?",[e]):await this.q("SELECT COUNT(*) AS total FROM users"))[0]?.total??0}async getRoles(e){return(await this.q("SELECT * FROM roles WHERE tenant_id=?",[e])).map(et)}async createRole(e){let t=(0,w.randomUUID)();await this.exec("INSERT INTO roles (id, tenant_id, name, description) VALUES (?,?,?,?)",[t,e.tenantId,e.name,e.description??null]);let i=(await this.q("SELECT * FROM roles WHERE id=?",[t]))[0];if(!i)throw new Error("Role creation failed");return et(i)}async updateRole(e,t){let n=[],i=[];t.name!=null&&(n.push("name=?"),i.push(t.name)),t.description!=null&&(n.push("description=?"),i.push(t.description)),n.length>0&&(i.push(e),await this.exec(`UPDATE roles SET ${n.join(",")} WHERE id=?`,i));let r=(await this.q("SELECT * FROM roles WHERE id=?",[e]))[0];if(!r)throw new Error(`Role ${e} not found`);return et(r)}async deleteRole(e){await this.exec("DELETE FROM role_permissions WHERE role_id=?",[e]),await this.exec("DELETE FROM user_roles WHERE role_id=?",[e]),await this.exec("DELETE FROM roles WHERE id=?",[e])}async getAllPermissions(){return(await this.q("SELECT * FROM permissions ORDER BY name")).map(Un)}async getPermissionsForRole(e){return(await this.q("SELECT p.* FROM permissions p JOIN role_permissions rp ON p.id=rp.permission_id WHERE rp.role_id=?",[e])).map(Un)}async getUserRoles(e,t){return(t?await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=? AND ur.tenant_id=?",[e,t]):await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=?",[e])).map(et)}async assignRole(e,t,n="default"){await this.exec("INSERT IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)",[e,t,n])}async revokeRole(e,t,n){n?await this.exec("DELETE FROM user_roles WHERE user_id=? AND role_id=? AND tenant_id=?",[e,t,n]):await this.exec("DELETE FROM user_roles WHERE user_id=? AND role_id=?",[e,t])}async assignPermissionToRole(e,t){await this.exec("INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?,?)",[e,t])}async revokePermissionFromRole(e,t){await this.exec("DELETE FROM role_permissions WHERE role_id=? AND permission_id=?",[e,t])}async createLog(e){await this.exec("INSERT INTO audit_logs (id, tenant_id, user_id, action, resource_type, resource_id, old_data, new_data) VALUES (?,?,?,?,?,?,?,?)",[(0,w.randomUUID)(),e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null])}async getLogs(e){let{sql:t,params:n}=this.buildAuditQuery(e),i=e.page??1,o=e.limit??50;return(await this.q(`${t} ORDER BY created_at DESC LIMIT ? OFFSET ?`,[...n,o,(i-1)*o])).map(kn)}async*streamAuditLogs(e){let{sql:t,params:n}=this.buildAuditQuery(e),i=await this.q(`${t} ORDER BY created_at ASC`,n);for(let o of i)yield kn(o)}buildAuditQuery(e){let t="SELECT * FROM audit_logs WHERE tenant_id=?",n=[e.tenantId];return e.action!=null&&(t+=" AND action=?",n.push(e.action)),e.resourceType!=null&&(t+=" AND resource_type=?",n.push(e.resourceType)),e.from!=null&&(t+=" AND created_at>=?",n.push(e.from)),e.to!=null&&(t+=" AND created_at<=?",n.push(e.to)),{sql:t,params:n}}async getCountries(e){return(await this.q(`SELECT v.country, COUNT(*) AS count FROM consent_records cr
107
+ GROUP BY DATE(created_at) ORDER BY date ASC`,[e,n])).map(r=>({date:String(r.date),count:r.count}))}async createUser(e){let t=(0,C.randomUUID)();await this.exec("INSERT INTO users (id, tenant_id, name, email, password_hash) VALUES (?,?,?,?,?)",[t,e.tenantId,e.name,e.email,e.passwordHash]);let o=(await this.q("SELECT * FROM users WHERE id=?",[t]))[0];if(!o)throw new Error("User creation failed");return Ke(o)}async updateUser(e,t){let n=[],o=[];t.name!=null&&(n.push("name=?"),o.push(t.name)),t.email!=null&&(n.push("email=?"),o.push(t.email)),t.passwordHash!=null&&(n.push("password_hash=?"),o.push(t.passwordHash)),t.isActive!=null&&(n.push("is_active=?"),o.push(t.isActive?1:0)),n.length>0&&(o.push(e),await this.exec(`UPDATE users SET ${n.join(",")} WHERE id=?`,o));let s=(await this.q("SELECT * FROM users WHERE id=?",[e]))[0];if(!s)throw new Error(`User ${e} not found`);return Ke(s)}async deleteUser(e){await this.exec("DELETE FROM user_roles WHERE user_id=?",[e]),await this.exec("DELETE FROM users WHERE id=?",[e])}async getUserById(e){let t=await this.q("SELECT * FROM users WHERE id=?",[e]);return t[0]?Ke(t[0]):null}async getUserByEmail(e){let t=await this.q("SELECT * FROM users WHERE email=?",[e]);return t[0]?Ke(t[0]):null}async getUsers(e){return(await this.q("SELECT * FROM users WHERE tenant_id=? ORDER BY created_at DESC",[e])).map(Ke)}async countUsers(e){return(e?await this.q("SELECT COUNT(*) AS total FROM users WHERE tenant_id=?",[e]):await this.q("SELECT COUNT(*) AS total FROM users"))[0]?.total??0}async getRoles(e){return(await this.q("SELECT * FROM roles WHERE tenant_id=?",[e])).map(Tt)}async createRole(e){let t=(0,C.randomUUID)();await this.exec("INSERT INTO roles (id, tenant_id, name, description) VALUES (?,?,?,?)",[t,e.tenantId,e.name,e.description??null]);let o=(await this.q("SELECT * FROM roles WHERE id=?",[t]))[0];if(!o)throw new Error("Role creation failed");return Tt(o)}async updateRole(e,t){let n=[],o=[];t.name!=null&&(n.push("name=?"),o.push(t.name)),t.description!=null&&(n.push("description=?"),o.push(t.description)),n.length>0&&(o.push(e),await this.exec(`UPDATE roles SET ${n.join(",")} WHERE id=?`,o));let s=(await this.q("SELECT * FROM roles WHERE id=?",[e]))[0];if(!s)throw new Error(`Role ${e} not found`);return Tt(s)}async deleteRole(e){await this.exec("DELETE FROM role_permissions WHERE role_id=?",[e]),await this.exec("DELETE FROM user_roles WHERE role_id=?",[e]),await this.exec("DELETE FROM roles WHERE id=?",[e])}async getAllPermissions(){return(await this.q("SELECT * FROM permissions ORDER BY name")).map(wo)}async getPermissionsForRole(e){return(await this.q("SELECT p.* FROM permissions p JOIN role_permissions rp ON p.id=rp.permission_id WHERE rp.role_id=?",[e])).map(wo)}async getUserRoles(e,t){return(t?await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=? AND ur.tenant_id=?",[e,t]):await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=?",[e])).map(Tt)}async assignRole(e,t,n="default"){await this.exec("INSERT IGNORE INTO user_roles (user_id, role_id, tenant_id) VALUES (?,?,?)",[e,t,n])}async revokeRole(e,t,n){n?await this.exec("DELETE FROM user_roles WHERE user_id=? AND role_id=? AND tenant_id=?",[e,t,n]):await this.exec("DELETE FROM user_roles WHERE user_id=? AND role_id=?",[e,t])}async assignPermissionToRole(e,t){await this.exec("INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?,?)",[e,t])}async revokePermissionFromRole(e,t){await this.exec("DELETE FROM role_permissions WHERE role_id=? AND permission_id=?",[e,t])}async createLog(e){await this.exec("INSERT INTO audit_logs (id, tenant_id, user_id, action, resource_type, resource_id, old_data, new_data) VALUES (?,?,?,?,?,?,?,?)",[(0,C.randomUUID)(),e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null])}async getLogs(e){let{where:t,params:n}=this.buildAuditWhere(e),o=e.page??1,r=e.limit??50,[s,a]=await Promise.all([this.q(`SELECT ${qc} ${t} ORDER BY created_at DESC LIMIT ? OFFSET ?`,[...n,r,(o-1)*r]),this.q(`SELECT COUNT(*) AS total ${t}`,n)]);return{items:s.map(Jc),total:a[0]?.total??0,page:o,limit:r}}async getAuditLogById(e){let t=await this.q("SELECT * FROM audit_logs WHERE id=?",[e]);return t[0]?Eo(t[0]):null}async*streamAuditLogs(e){let{where:t,params:n}=this.buildAuditWhere(e),o=await this.q(`SELECT * ${t} ORDER BY created_at ASC`,n);for(let r of o)yield Eo(r)}buildAuditWhere(e){let t="FROM audit_logs WHERE tenant_id=?",n=[e.tenantId];if(e.action!=null&&(t+=" AND action=?",n.push(e.action)),e.resourceType!=null&&(t+=" AND resource_type=?",n.push(e.resourceType)),e.from!=null&&(t+=" AND created_at>=?",n.push(e.from)),e.to!=null&&(t+=" AND created_at<=?",n.push(e.to)),e.q){t+=" AND (action LIKE ? OR resource_type LIKE ? OR resource_id LIKE ? OR user_id LIKE ?) ESCAPE '\\\\'";let o=j(e.q);n.push(o,o,o,o)}return{where:t,params:n}}async getCountries(e){return(await this.q(`SELECT v.country, COUNT(*) AS count FROM consent_records cr
122
108
  JOIN visitors v ON v.visitor_id=cr.visitor_id
123
109
  WHERE cr.tenant_id=? AND v.country IS NOT NULL
124
- GROUP BY v.country ORDER BY count DESC LIMIT 50`,[e])).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let[t]=await this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=?",[e]),[n]=await this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=? AND gpc_detected=1",[e]),i=t?.total??0,o=n?.total??0;return{detected:o,total:i,rate:i>0?Math.round(o/i*100):0}}async getTenants(){return(await this.q("SELECT * FROM tenants ORDER BY name ASC",[])).map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createApiKey(e){let t=(0,w.randomUUID)();await this.exec("INSERT INTO api_keys (id, tenant_id, key_hash, name) VALUES (?,?,?,?)",[t,e.tenantId,e.keyHash,e.name]);let i=(await this.q("SELECT * FROM api_keys WHERE id=?",[t]))[0];if(!i)throw new Error("Failed to create API key");return{id:i.id,tenantId:i.tenant_id,keyHash:i.key_hash,name:i.name,isActive:i.is_active===1,createdAt:i.created_at}}async getApiKeyByHash(e){let n=(await this.q("SELECT * FROM api_keys WHERE key_hash=? AND is_active=1",[e]))[0];return n?{id:n.id,tenantId:n.tenant_id,keyHash:n.key_hash,name:n.name,isActive:n.is_active===1,createdAt:n.created_at}:null}async revokeApiKey(e){await this.exec("UPDATE api_keys SET is_active=0 WHERE id=?",[e])}async getApiKeys(e){return(await this.q("SELECT * FROM api_keys WHERE tenant_id=? ORDER BY created_at DESC",[e])).map(n=>({id:n.id,tenantId:n.tenant_id,keyHash:n.key_hash,name:n.name,isActive:n.is_active===1,createdAt:n.created_at}))}async createTenant(e){let t=(0,w.randomUUID)(),n=new Date().toISOString();await this.exec("INSERT INTO tenants (id, name, slug, created_at, updated_at) VALUES (?,?,?,?,?)",[t,e.name,e.slug,n,n]);let o=(await this.q("SELECT * FROM tenants WHERE id=?",[t]))[0];if(!o)throw new Error("Failed to create tenant");return{id:o.id,name:o.name,slug:o.slug,createdAt:o.created_at,updatedAt:o.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),i=["updated_at=?"],o=[n];t.name!=null&&(i.push("name=?"),o.push(t.name)),t.slug!=null&&(i.push("slug=?"),o.push(t.slug)),o.push(e),await this.exec(`UPDATE tenants SET ${i.join(",")} WHERE id=?`,o);let a=(await this.q("SELECT * FROM tenants WHERE id=?",[e]))[0];if(!a)throw new Error(`Tenant ${e} not found`);return{id:a.id,name:a.name,slug:a.slug,createdAt:a.created_at,updatedAt:a.updated_at}}async deleteTenant(e){await this.exec("DELETE FROM tenants WHERE id=?",[e])}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=await this.q("SELECT visitor_id FROM consent_records WHERE created_at < ?",[t]);if(n.length===0)return 0;let i=n.map(r=>r.visitor_id),o=i.map(()=>"?").join(",");return await this.exec(`DELETE FROM consent_history WHERE visitor_id IN (${o})`,i),await this.exec(`DELETE FROM consent_records WHERE visitor_id IN (${o})`,i),i.length}async createCookieTemplate(){throw new Error("Not implemented")}async updateCookieTemplate(){throw new Error("Not implemented")}async deleteCookieTemplate(){throw new Error("Not implemented")}async getCookieTemplate(){throw new Error("Not implemented")}async getCookieTemplates(){throw new Error("Not implemented")}async copyCookieTemplate(){throw new Error("Not implemented")}async createUITemplate(){throw new Error("Not implemented")}async updateUITemplate(){throw new Error("Not implemented")}async deleteUITemplate(){throw new Error("Not implemented")}async getUITemplate(){throw new Error("Not implemented")}async getUITemplates(){throw new Error("Not implemented")}async copyUITemplate(){throw new Error("Not implemented")}async listProfilesSummary(){return[]}async findProfilesUsingCookieTemplate(){return[]}async findProfilesUsingUITemplate(){return[]}async getOptInStats(){throw new Error("Not implemented")}};function tt(s){return{id:s.id,tenantId:s.tenant_id,name:s.name,defaultLocale:s.default_locale,version:s.version,profileJson:JSON.parse(s.profile_json),createdAt:s.created_at,updatedAt:s.updated_at}}function De(s){return{id:s.id,tenantId:s.tenant_id,visitorId:s.visitor_id,profileId:s.profile_id,profileVersion:s.profile_version,locale:s.locale,consentJson:JSON.parse(s.consent_json),gpcDetected:s.gpc_detected,source:s.source,createdAt:s.created_at,updatedAt:s.updated_at,...s.age_verified!=null?{ageVerified:s.age_verified}:{},...s.parental_consent_token!=null?{parentalConsentToken:s.parental_consent_token}:{},...s.tcf_string!=null?{tcfString:s.tcf_string}:{}}}function uo(s){return{id:s.id,tenantId:s.tenant_id,consentRecordId:s.consent_record_id,visitorId:s.visitor_id,oldJson:s.old_json?JSON.parse(s.old_json):null,newJson:JSON.parse(s.new_json),action:s.action,createdAt:s.created_at}}function nt(s){return{id:s.id,tenantId:s.tenant_id,visitorId:s.visitor_id,...s.country!=null?{country:s.country}:{},...s.region!=null?{region:s.region}:{},...s.city!=null?{city:s.city}:{},...s.ip_hash!=null?{ipHash:s.ip_hash}:{},...s.user_agent_hash!=null?{userAgentHash:s.user_agent_hash}:{},firstSeen:s.first_seen,lastSeen:s.last_seen}}function Le(s){return{id:s.id,tenantId:s.tenant_id,name:s.name,email:s.email,passwordHash:s.password_hash,isActive:s.is_active,createdAt:s.created_at,updatedAt:s.updated_at,totpEnabled:s.totp_enabled??!1,...s.totp_secret!=null?{totpSecret:s.totp_secret}:{}}}function Ue(s){return{id:s.id,tenantId:s.tenant_id,name:s.name,...s.description!=null?{description:s.description}:{}}}function Nn(s){return{id:s.id,name:s.name,...s.description!=null?{description:s.description}:{}}}function Mn(s){return{id:s.id,tenantId:s.tenant_id,action:s.action,resourceType:s.resource_type,...s.user_id!=null?{userId:s.user_id}:{},...s.resource_id!=null?{resourceId:s.resource_id}:{},...s.old_data!=null?{oldData:JSON.parse(s.old_data)}:{},...s.new_data!=null?{newData:JSON.parse(s.new_data)}:{},createdAt:s.created_at}}var _e=class{constructor(e){this.config=e}config;pool;async q(e,t=[]){return(await this.pool.query(e,t)).rows}async connect(){let t=(await import("pg")).default.Pool,n=this.config,i=n.uri?{connectionString:n.uri}:{host:n.host??"localhost",port:n.port??5432,user:n.user??"postgres",password:n.password??"",database:n.database??"consenti"};this.pool=new t(i),await this.migrate()}async disconnect(){await this.pool.end()}async migrate(){let e=await this.pool.connect();try{let t=0;try{t=(await e.query("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1")).rows[0]?.version??0}catch{}if(t===0){await e.query("BEGIN");try{for(let n of bn.split(";").map(i=>i.trim()).filter(Boolean))await e.query(n);await this.seedTx(e),await e.query("INSERT INTO schema_version (version) VALUES (2) ON CONFLICT DO NOTHING"),await e.query("COMMIT")}catch(n){throw await e.query("ROLLBACK"),n}return}if(t<2){await e.query("BEGIN");try{let n=["ALTER TABLE consent_records ADD COLUMN IF NOT EXISTS age_verified BOOLEAN NOT NULL DEFAULT FALSE","ALTER TABLE consent_records ADD COLUMN IF NOT EXISTS parental_consent_token TEXT","ALTER TABLE consent_records ADD COLUMN IF NOT EXISTS tcf_string TEXT","ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret TEXT","ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE"];for(let i of n)await e.query(i);await e.query("INSERT INTO schema_version (version) VALUES (2) ON CONFLICT DO NOTHING"),await e.query("COMMIT")}catch(n){throw await e.query("ROLLBACK"),n}}if(t<3){await e.query("BEGIN");try{await e.query("ALTER TABLE user_roles ADD COLUMN IF NOT EXISTS tenant_id TEXT NOT NULL DEFAULT 'default'"),await e.query("INSERT INTO schema_version (version) VALUES (3) ON CONFLICT DO NOTHING"),await e.query("COMMIT")}catch(n){throw await e.query("ROLLBACK"),n}}}finally{e.release()}}async seedTx(e){await e.query("INSERT INTO tenants (id, name, slug) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",[$.id,$.name,$.slug]);for(let t of j)await e.query("INSERT INTO permissions (id, name, description) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",[t.id,t.name,t.description]);for(let t of Z)await e.query("INSERT INTO roles (id, tenant_id, name, description) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING",[t.id,t.tenantId,t.name,t.description]);for(let{roleId:t,permissionId:n}of ee)await e.query("INSERT INTO role_permissions VALUES ($1,$2) ON CONFLICT DO NOTHING",[t,n])}async createProfile(e){let t=(0,w.randomUUID)(),i=(await this.q(`INSERT INTO profiles (id, tenant_id, name, default_locale, profile_json)
125
- VALUES ($1,$2,$3,$4,$5::jsonb) RETURNING *`,[t,e.tenantId,e.name,e.defaultLocale,JSON.stringify(e.profileJson)]))[0];if(!i)throw new Error("Profile creation failed");return tt(i)}async updateProfile(e,t){let n=["version = version + 1","updated_at = NOW()"],i=[],o=1;t.name!=null&&(n.push(`name=$${o++}`),i.push(t.name)),t.defaultLocale!=null&&(n.push(`default_locale=$${o++}`),i.push(t.defaultLocale)),t.profileJson!=null&&(n.push(`profile_json=$${o++}::jsonb`),i.push(JSON.stringify(t.profileJson))),i.push(e);let a=(await this.q(`UPDATE profiles SET ${n.join(",")} WHERE id=$${o} RETURNING *`,i))[0];if(!a)throw new Error(`Profile ${e} not found`);return tt(a)}async deleteProfile(e){await this.q("DELETE FROM profiles WHERE id=$1",[e])}async getProfile(e){let t=await this.q("SELECT * FROM profiles WHERE id=$1",[e]);return t[0]?tt(t[0]):null}async getProfiles(e){return(await this.q("SELECT * FROM profiles WHERE tenant_id=$1 ORDER BY created_at DESC",[e])).map(tt)}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(i=>i.profileJson.complianceGroup===t&&i.profileJson.isActive)??null}async createConsent(e){let t=(0,w.randomUUID)(),i=(await this.q(`INSERT INTO consent_records (id, tenant_id, visitor_id, profile_id, profile_version, locale, consent_json, gpc_detected, source)
126
- VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9) RETURNING *`,[t,e.tenantId,e.visitorId,e.profileId,e.profileVersion,e.locale,JSON.stringify(e.consentJson),e.gpcDetected,e.source]))[0];if(!i)throw new Error("Consent creation failed");return await this.writeHistory(t,e.tenantId,e.visitorId,null,e.consentJson,"created"),De(i)}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let i=["consent_json=$1::jsonb","updated_at=NOW()"],o=[JSON.stringify(t.consentJson)],r=2;t.locale!=null&&(i.push(`locale=$${r++}`),o.push(t.locale)),t.gpcDetected!=null&&(i.push(`gpc_detected=$${r++}`),o.push(t.gpcDetected)),o.push(e);let c=(await this.q(`UPDATE consent_records SET ${i.join(",")} WHERE visitor_id=$${r} RETURNING *`,o))[0];if(!c)throw new Error(`Consent for visitor ${e} not found`);return await this.writeHistory(c.id,c.tenant_id,e,n.consentJson,t.consentJson,"updated"),De(c)}async deleteConsent(e){await this.q("DELETE FROM consent_history WHERE visitor_id=$1",[e]),await this.q("DELETE FROM consent_records WHERE visitor_id=$1",[e])}async getConsent(e){let t=await this.q("SELECT * FROM consent_records WHERE visitor_id=$1",[e]);return t[0]?De(t[0]):null}async getConsents(e){let{sql:t,params:n,nextIdx:i}=this.buildConsentQuery(e),o=e.page??1,r=e.limit??50;return(await this.q(`${t} ORDER BY created_at DESC LIMIT $${i} OFFSET $${i+1}`,[...n,r,(o-1)*r])).map(De)}async*streamConsents(e){let{sql:t,params:n}=this.buildConsentQuery(e),i=await this.q(`${t} ORDER BY created_at ASC`,n);for(let o of i)yield De(o)}buildConsentQuery(e){let t="SELECT * FROM consent_records WHERE tenant_id=$1",n=[e.tenantId],i=2;return e.profileId!=null&&(t+=` AND profile_id=$${i++}`,n.push(e.profileId)),e.from!=null&&(t+=` AND created_at>=$${i++}`,n.push(e.from)),e.to!=null&&(t+=` AND created_at<=$${i++}`,n.push(e.to)),{sql:t,params:n,nextIdx:i}}async writeHistory(e,t,n,i,o,r){await this.q(`INSERT INTO consent_history (id, tenant_id, consent_record_id, visitor_id, old_json, new_json, action)
127
- VALUES ($1,$2,$3,$4,$5::jsonb,$6::jsonb,$7)`,[(0,w.randomUUID)(),t,e,n,i?JSON.stringify(i):null,JSON.stringify(o),r])}async getConsentHistory(e){return(await this.q("SELECT * FROM consent_history WHERE visitor_id=$1 ORDER BY created_at ASC",[e])).map(uo)}async createVisitor(e){let t=(0,w.randomUUID)(),i=(await this.q(`INSERT INTO visitors (id, tenant_id, visitor_id, country, region, city, ip_hash, user_agent_hash)
128
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`,[t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null]))[0];if(!i)throw new Error("Visitor creation failed");return nt(i)}async updateVisitor(e,t){let n=["last_seen=NOW()"],i=[],o=1;t.country!=null&&(n.push(`country=$${o++}`),i.push(t.country)),t.region!=null&&(n.push(`region=$${o++}`),i.push(t.region)),t.city!=null&&(n.push(`city=$${o++}`),i.push(t.city)),i.push(e);let a=(await this.q(`UPDATE visitors SET ${n.join(",")} WHERE visitor_id=$${o} RETURNING *`,i))[0];if(!a)throw new Error(`Visitor ${e} not found`);return nt(a)}async deleteVisitor(e){await this.q("DELETE FROM visitors WHERE visitor_id=$1",[e])}async getVisitor(e){let t=await this.q("SELECT * FROM visitors WHERE visitor_id=$1",[e]);return t[0]?nt(t[0]):null}async getVisitors(e){let t="SELECT * FROM visitors WHERE tenant_id=$1",n=[e.tenantId],i=2;e.from!=null&&(t+=` AND first_seen>=$${i++}`,n.push(e.from)),e.to!=null&&(t+=` AND first_seen<=$${i++}`,n.push(e.to));let o=e.page??1,r=e.limit??50;return(await this.q(`${t} ORDER BY first_seen DESC LIMIT $${i} OFFSET $${i+1}`,[...n,r,(o-1)*r])).map(nt)}async getOverviewStats(e){let[[t],[n],[i]]=await Promise.all([this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1",[e]),this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1 AND gpc_detected=true",[e]),this.q("SELECT COUNT(*)::int AS total FROM visitors WHERE tenant_id=$1",[e])]),o=Number(t?.total??0),r=Number(n?.total??0),a=Number(i?.total??0),c=await this.q(`SELECT val AS status, COUNT(*)::int AS count
110
+ GROUP BY v.country ORDER BY count DESC LIMIT 50`,[e])).map(n=>({country:n.country,count:n.count}))}async getGpcStats(e){let[t]=await this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=?",[e]),[n]=await this.q("SELECT COUNT(*) AS total FROM consent_records WHERE tenant_id=? AND gpc_detected=1",[e]),o=t?.total??0,r=n?.total??0;return{detected:r,total:o,rate:o>0?Math.round(r/o*100):0}}async getTenants(){return(await this.q("SELECT * FROM tenants ORDER BY name ASC",[])).map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active===1,...e.created_by!==null?{createdBy:e.created_by}:{},...e.expire_by!==null?{expireBy:e.expire_by}:{},createdAt:e.created_at,...e.updated_at!==null?{updatedAt:e.updated_at}:{}}}async createApiKey(e){let t=(0,C.randomUUID)();await this.exec("INSERT INTO api_keys (id, tenant_id, key_hash, name, created_by, expire_by) VALUES (?,?,?,?,?,?)",[t,e.tenantId,e.keyHash,e.name,e.createdBy??null,e.expireBy??null]);let o=(await this.q("SELECT * FROM api_keys WHERE id=?",[t]))[0];if(!o)throw new Error("Failed to create API key");return this.mapApiKey(o)}async getApiKeyByHash(e){let n=(await this.q("SELECT * FROM api_keys WHERE key_hash=? AND is_active=1",[e]))[0];return n?this.mapApiKey(n):null}async revokeApiKey(e){await this.exec("UPDATE api_keys SET is_active=0, updated_at=NOW() WHERE id=?",[e])}async reactivateApiKey(e){await this.exec("UPDATE api_keys SET is_active=1, updated_at=NOW(), expire_by=CASE WHEN expire_by <= NOW() THEN NULL ELSE expire_by END WHERE id=?",[e])}async deleteApiKey(e){await this.exec("DELETE FROM api_keys WHERE id=?",[e])}async getApiKeys(e){return(await this.q("SELECT * FROM api_keys WHERE tenant_id=? ORDER BY created_at DESC",[e])).map(n=>this.mapApiKey(n))}async createTenant(e){let t=(0,C.randomUUID)(),n=new Date().toISOString();await this.exec("INSERT INTO tenants (id, name, slug, created_at, updated_at) VALUES (?,?,?,?,?)",[t,e.name,e.slug,n,n]);let r=(await this.q("SELECT * FROM tenants WHERE id=?",[t]))[0];if(!r)throw new Error("Failed to create tenant");return{id:r.id,name:r.name,slug:r.slug,createdAt:r.created_at,updatedAt:r.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),o=["updated_at=?"],r=[n];t.name!=null&&(o.push("name=?"),r.push(t.name)),t.slug!=null&&(o.push("slug=?"),r.push(t.slug)),r.push(e),await this.exec(`UPDATE tenants SET ${o.join(",")} WHERE id=?`,r);let a=(await this.q("SELECT * FROM tenants WHERE id=?",[e]))[0];if(!a)throw new Error(`Tenant ${e} not found`);return{id:a.id,name:a.name,slug:a.slug,createdAt:a.created_at,updatedAt:a.updated_at}}async getSettings(e){let n=(await this.q("SELECT allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json FROM tenant_settings WHERE tenant_id=?",[e]))[0];return n?{allowedOrigins:JSON.parse(n.allowed_origins_json),adminAllowedOrigins:JSON.parse(n.admin_allowed_origins_json),setupCompleted:!!n.setup_completed,profilesSeeded:!!n.profiles_seeded,tcfConfirmation:n.tcf_confirmation_json?JSON.parse(n.tcf_confirmation_json):void 0,gppConfirmation:n.gpp_confirmation_json?JSON.parse(n.gpp_confirmation_json):void 0}:{}}async updateSettings(e,t){let o={...await this.getSettings(e),...t};return await this.exec(`INSERT INTO tenant_settings (tenant_id, allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json, updated_at) VALUES (?,?,?,?,?,?,?,NOW())
111
+ ON DUPLICATE KEY UPDATE allowed_origins_json=VALUES(allowed_origins_json), admin_allowed_origins_json=VALUES(admin_allowed_origins_json), setup_completed=VALUES(setup_completed), profiles_seeded=VALUES(profiles_seeded), tcf_confirmation_json=VALUES(tcf_confirmation_json), gpp_confirmation_json=VALUES(gpp_confirmation_json), updated_at=NOW()`,[e,JSON.stringify(o.allowedOrigins??[]),JSON.stringify(o.adminAllowedOrigins??[]),o.setupCompleted?1:0,o.profilesSeeded?1:0,o.tcfConfirmation?JSON.stringify(o.tcfConfirmation):null,o.gppConfirmation?JSON.stringify(o.gppConfirmation):null]),this.getSettings(e)}async deleteTenant(e){await this.exec("DELETE FROM tenants WHERE id=?",[e])}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=await this.q("SELECT visitor_id FROM consent_records WHERE created_at < ?",[t]);if(n.length===0)return 0;let o=n.map(s=>s.visitor_id),r=o.map(()=>"?").join(",");return await this.exec(`DELETE FROM consent_history WHERE visitor_id IN (${r})`,o),await this.exec(`DELETE FROM consent_records WHERE visitor_id IN (${r})`,o),o.length}async createConsentTemplate(){throw new Error("Not implemented")}async updateConsentTemplate(){throw new Error("Not implemented")}async deleteConsentTemplate(){throw new Error("Not implemented")}async getConsentTemplate(){throw new Error("Not implemented")}async getConsentTemplates(){throw new Error("Not implemented")}async copyConsentTemplate(){throw new Error("Not implemented")}async createUITemplate(){throw new Error("Not implemented")}async updateUITemplate(){throw new Error("Not implemented")}async deleteUITemplate(){throw new Error("Not implemented")}async getUITemplate(){throw new Error("Not implemented")}async getUITemplates(){throw new Error("Not implemented")}async copyUITemplate(){throw new Error("Not implemented")}async listProfilesSummary(){return[]}async findProfilesUsingConsentTemplate(){return[]}async findProfilesUsingUITemplate(){return[]}async getOptInStats(){throw new Error("Not implemented")}};p();function It(i){return{id:i.id,tenantId:i.tenant_id,name:i.name,defaultLocale:i.default_locale,version:i.version,profileJson:i.profile_json,createdAt:i.created_at,updatedAt:i.updated_at}}function bt(i){return{id:i.id,tenantId:i.tenant_id,visitorId:i.visitor_id,profileId:i.profile_id,locale:i.locale,consentJson:i.consent_json,gpcDetected:i.gpc_detected,source:i.source,createdAt:i.created_at,updatedAt:i.updated_at,...i.age_verified!=null?{ageVerified:i.age_verified}:{},...i.parental_consent_token!=null?{parentalConsentToken:i.parental_consent_token}:{},...i.tcf_string!=null?{tcfString:i.tcf_string}:{},...i.gpp_string!=null?{gppString:i.gpp_string}:{},...i.signature!=null?{signature:i.signature}:{}}}var zc="id, tenant_id, visitor_id, profile_id, locale, gpc_detected, source, age_verified, created_at, updated_at";function Kc(i){return{id:i.id,tenantId:i.tenant_id,visitorId:i.visitor_id,profileId:i.profile_id,locale:i.locale,gpcDetected:i.gpc_detected,source:i.source,createdAt:i.created_at,updatedAt:i.updated_at,...i.age_verified!=null?{ageVerified:i.age_verified}:{}}}function Yc(i){return{id:i.id,tenantId:i.tenant_id,consentRecordId:i.consent_record_id,visitorId:i.visitor_id,oldJson:i.old_json,newJson:i.new_json,action:i.action,createdAt:i.created_at}}function Ot(i){return{id:i.id,tenantId:i.tenant_id,visitorId:i.visitor_id,...i.country!=null?{country:i.country}:{},...i.region!=null?{region:i.region}:{},...i.city!=null?{city:i.city}:{},...i.ip_hash!=null?{ipHash:i.ip_hash}:{},...i.user_agent_hash!=null?{userAgentHash:i.user_agent_hash}:{},firstSeen:i.first_seen,lastSeen:i.last_seen}}function Ye(i){return{id:i.id,tenantId:i.tenant_id,name:i.name,email:i.email,passwordHash:i.password_hash,isActive:i.is_active,createdAt:i.created_at,updatedAt:i.updated_at,totpEnabled:i.totp_enabled??!1,...i.totp_secret!=null?{totpSecret:i.totp_secret}:{}}}function Qe(i){return{id:i.id,tenantId:i.tenant_id,name:i.name,...i.description!=null?{description:i.description}:{}}}function Ro(i){return{id:i.id,name:i.name,...i.description!=null?{description:i.description}:{}}}function So(i){return{id:i.id,tenantId:i.tenant_id,action:i.action,resourceType:i.resource_type,...i.user_id!=null?{userId:i.user_id}:{},...i.resource_id!=null?{resourceId:i.resource_id}:{},...i.old_data!=null?{oldData:i.old_data}:{},...i.new_data!=null?{newData:i.new_data}:{},createdAt:i.created_at}}var Qc="id, tenant_id, user_id, action, resource_type, resource_id, created_at";function Zc(i){return{id:i.id,tenantId:i.tenant_id,action:i.action,resourceType:i.resource_type,...i.user_id!=null?{userId:i.user_id}:{},...i.resource_id!=null?{resourceId:i.resource_id}:{},createdAt:i.created_at}}var Ne=class{constructor(e){this.config=e}config;pool;async q(e,t=[]){return(await this.pool.query(e,t)).rows}async connect(){let t=(await import("pg")).default.Pool,n=this.config,o=n.uri?{connectionString:n.uri}:{host:n.host??"localhost",port:n.port??5432,user:n.user??"postgres",password:n.password??"",database:n.database??"consenti"};o.max=n.poolMax??10,n.statementTimeoutMs!=null&&(o.statement_timeout=n.statementTimeoutMs),n.idleInTransactionTimeoutMs!=null&&(o.idle_in_transaction_session_timeout=n.idleInTransactionTimeoutMs),this.pool=new t(o),await this.migrate()}async disconnect(){await this.pool.end()}async migrate(){let e=await this.pool.connect();try{let t=0;try{t=(await e.query("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1")).rows[0]?.version??0}catch{}if(t===0){await e.query("BEGIN");try{for(let n of fo.split(";").map(o=>o.trim()).filter(Boolean))await e.query(n);await this.seedTx(e),await e.query("INSERT INTO schema_version (version) VALUES (1) ON CONFLICT DO NOTHING"),await e.query("COMMIT")}catch(n){throw await e.query("ROLLBACK"),n}}}finally{e.release()}}async seedTx(e){await e.query("INSERT INTO tenants (id, name, slug) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",[te.id,te.name,te.slug]);for(let t of ee)await e.query("INSERT INTO permissions (id, name, description) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",[t.id,t.name,t.description]);for(let t of pe)await e.query("INSERT INTO roles (id, tenant_id, name, description) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING",[t.id,t.tenantId,t.name,t.description]);for(let{roleId:t,permissionId:n}of me)await e.query("INSERT INTO role_permissions VALUES ($1,$2) ON CONFLICT DO NOTHING",[t,n])}async createProfile(e){let t=z(),o=(await this.q(`INSERT INTO profiles (id, tenant_id, name, default_locale, version, profile_json)
112
+ VALUES ($1,$2,$3,$4,$5,$6::json) RETURNING *`,[t,e.tenantId,e.name,e.defaultLocale,1,JSON.stringify(e.profileJson)]))[0];if(!o)throw new Error("Profile creation failed");return It(o)}async updateProfile(e,t){let n=["updated_at = NOW()"],o=[],r=1;t.name!=null&&(n.push(`name=$${r++}`),o.push(t.name)),t.defaultLocale!=null&&(n.push(`default_locale=$${r++}`),o.push(t.defaultLocale)),t.profileJson!=null&&(n.push(`profile_json=$${r++}::json`),o.push(JSON.stringify(t.profileJson))),t.version!=null&&(n.push(`version=$${r++}`),o.push(t.version)),o.push(e);let a=(await this.q(`UPDATE profiles SET ${n.join(",")} WHERE id=$${r} RETURNING *`,o))[0];if(!a)throw new Error(`Profile ${e} not found`);return It(a)}async deleteProfile(e){await this.q("DELETE FROM profiles WHERE id=$1",[e])}async getProfile(e){let t=await this.q("SELECT * FROM profiles WHERE id=$1",[e]);return t[0]?It(t[0]):null}async getProfiles(e){return(await this.q("SELECT * FROM profiles WHERE tenant_id=$1 ORDER BY created_at DESC",[e])).map(It)}async findActiveProfileByComplianceGroup(e,t){return(await this.getProfiles(e)).find(o=>(o.profileJson.complianceGroup===t||o.profileJson.customComplianceGroup===t)&&o.profileJson.isActive)??null}async createConsent(e){let t=K(),o=(await this.q(`INSERT INTO consent_records (id, tenant_id, visitor_id, profile_id, locale, consent_json, gpc_detected, source, age_verified, parental_consent_token, tcf_string, gpp_string, signature)
113
+ VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9,$10,$11,$12,$13) RETURNING *`,[t,e.tenantId,e.visitorId,e.profileId,e.locale,JSON.stringify(e.consentJson),e.gpcDetected,e.source,e.ageVerified??!1,e.parentalConsentToken??null,e.tcfString??null,e.gppString??null,e.signature??null]))[0];if(!o)throw new Error("Consent creation failed");return await this.writeHistory(t,e.tenantId,e.visitorId,null,e.consentJson,"created"),bt(o)}async updateConsent(e,t){let n=await this.getConsent(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let o=["consent_json=$1::jsonb","updated_at=NOW()"],r=[JSON.stringify(t.consentJson)],s=2;t.locale!=null&&(o.push(`locale=$${s++}`),r.push(t.locale)),t.gpcDetected!=null&&(o.push(`gpc_detected=$${s++}`),r.push(t.gpcDetected)),t.signature!=null&&(o.push(`signature=$${s++}`),r.push(t.signature)),r.push(e);let c=(await this.q(`UPDATE consent_records SET ${o.join(",")} WHERE visitor_id=$${s} RETURNING *`,r))[0];if(!c)throw new Error(`Consent for visitor ${e} not found`);return await this.writeHistory(c.id,c.tenant_id,e,n.consentJson,t.consentJson,"updated"),bt(c)}async deleteConsent(e){await this.q("DELETE FROM consent_history WHERE visitor_id=$1",[e]),await this.q("DELETE FROM consent_records WHERE visitor_id=$1",[e])}async getConsent(e){let t=await this.q("SELECT * FROM consent_records WHERE visitor_id=$1",[e]);return t[0]?bt(t[0]):null}async getConsents(e){let{where:t,params:n,nextIdx:o}=this.buildConsentWhere(e),r=e.page??1,s=e.limit??50,[a,c]=await Promise.all([this.q(`SELECT ${zc} ${t} ORDER BY created_at DESC LIMIT $${o} OFFSET $${o+1}`,[...n,s,(r-1)*s]),this.q(`SELECT COUNT(*)::int AS total ${t}`,n)]);return{items:a.map(Kc),total:Number(c[0]?.total??0),page:r,limit:s}}async*streamConsents(e){let{where:t,params:n}=this.buildConsentWhere(e),o=await this.q(`SELECT * ${t} ORDER BY created_at ASC`,n);for(let r of o)yield bt(r)}buildConsentWhere(e){let t="FROM consent_records WHERE tenant_id=$1",n=[e.tenantId],o=2;return e.profileId!=null&&(t+=` AND profile_id=$${o++}`,n.push(e.profileId)),e.from!=null&&(t+=` AND created_at>=$${o++}`,n.push(e.from)),e.to!=null&&(t+=` AND created_at<=$${o++}`,n.push(e.to)),e.q&&(t+=` AND (visitor_id ILIKE $${o} OR profile_id ILIKE $${o} OR locale ILIKE $${o} OR source ILIKE $${o}) ESCAPE '\\'`,n.push(j(e.q)),o++),{where:t,params:n,nextIdx:o}}async writeHistory(e,t,n,o,r,s){await this.q(`INSERT INTO consent_history (id, tenant_id, consent_record_id, visitor_id, old_json, new_json, action)
114
+ VALUES ($1,$2,$3,$4,$5::jsonb,$6::jsonb,$7)`,[(0,C.randomUUID)(),t,e,n,o?JSON.stringify(o):null,JSON.stringify(r),s])}async getConsentHistory(e){return(await this.q("SELECT * FROM consent_history WHERE visitor_id=$1 ORDER BY created_at ASC",[e])).map(Yc)}async createNoticeShown(e){let t=(0,C.randomUUID)(),o=(await this.q(`INSERT INTO notice_shown (id, tenant_id, visitor_id, profile_id, locale)
115
+ VALUES ($1,$2,$3,$4,$5) RETURNING *`,[t,e.tenantId,e.visitorId,e.profileId,e.locale]))[0];return{id:o.id,tenantId:o.tenant_id,visitorId:o.visitor_id,profileId:o.profile_id,locale:o.locale,createdAt:o.created_at}}async getNoticeShownForVisitor(e){return(await this.q("SELECT * FROM notice_shown WHERE visitor_id=$1 ORDER BY created_at DESC",[e])).map(n=>({id:n.id,tenantId:n.tenant_id,visitorId:n.visitor_id,profileId:n.profile_id,locale:n.locale,createdAt:n.created_at}))}async createVisitor(e){let t=q(),o=(await this.q(`INSERT INTO visitors (id, tenant_id, visitor_id, country, region, city, ip_hash, user_agent_hash)
116
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`,[t,e.tenantId,e.visitorId,e.country??null,e.region??null,e.city??null,e.ipHash??null,e.userAgentHash??null]))[0];if(!o)throw new Error("Visitor creation failed");return Ot(o)}async updateVisitor(e,t){let n=["last_seen=NOW()"],o=[],r=1;t.country!=null&&(n.push(`country=$${r++}`),o.push(t.country)),t.region!=null&&(n.push(`region=$${r++}`),o.push(t.region)),t.city!=null&&(n.push(`city=$${r++}`),o.push(t.city)),o.push(e);let a=(await this.q(`UPDATE visitors SET ${n.join(",")} WHERE visitor_id=$${r} RETURNING *`,o))[0];if(!a)throw new Error(`Visitor ${e} not found`);return Ot(a)}async deleteVisitor(e){await this.q("DELETE FROM visitors WHERE visitor_id=$1",[e])}async getVisitor(e){let t=await this.q("SELECT * FROM visitors WHERE visitor_id=$1",[e]);return t[0]?Ot(t[0]):null}async getVisitors(e){let t="FROM visitors WHERE tenant_id=$1",n=[e.tenantId],o=2;e.from!=null&&(t+=` AND first_seen>=$${o++}`,n.push(e.from)),e.to!=null&&(t+=` AND first_seen<=$${o++}`,n.push(e.to)),e.q&&(t+=` AND (visitor_id ILIKE $${o} OR country ILIKE $${o}) ESCAPE '\\'`,n.push(j(e.q)),o++);let r=e.page??1,s=e.limit??50,[a,c]=await Promise.all([this.q(`SELECT * ${t} ORDER BY first_seen DESC LIMIT $${o} OFFSET $${o+1}`,[...n,s,(r-1)*s]),this.q(`SELECT COUNT(*)::int AS total ${t}`,n)]);return{items:a.map(Ot),total:Number(c[0]?.total??0),page:r,limit:s}}async getOverviewStats(e){let[[t],[n],[o]]=await Promise.all([this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1",[e]),this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1 AND gpc_detected=true",[e]),this.q("SELECT COUNT(*)::int AS total FROM visitors WHERE tenant_id=$1",[e])]),r=Number(t?.total??0),s=Number(n?.total??0),a=Number(o?.total??0),c=await this.q(`SELECT val AS status, COUNT(*)::int AS count
129
117
  FROM consent_records cr,
130
118
  jsonb_each_text(cr.consent_json) AS kv(key, val)
131
119
  WHERE cr.tenant_id=$1
132
- GROUP BY val`,[e]),l=0,u=0,d=0;for(let p of c)d+=Number(p.count),p.status==="granted"&&(l=Number(p.count)),p.status==="denied"&&(u=Number(p.count));return{totalConsents:o,acceptedPct:d>0?Math.round(l/d*100):0,rejectedPct:d>0?Math.round(u/d*100):0,totalVisitors:a,gpcDetectedCount:r}}async getCategoryStats(e){let t=await this.q(`SELECT kv.key AS cookie_id, kv.val AS status, COUNT(*)::int AS count
120
+ GROUP BY val`,[e]),l=0,d=0,u=0;for(let m of c)u+=Number(m.count),m.status==="granted"&&(l=Number(m.count)),m.status==="denied"&&(d=Number(m.count));return{totalConsents:r,acceptedPct:u>0?Math.round(l/u*100):0,rejectedPct:u>0?Math.round(d/u*100):0,totalVisitors:a,gpcDetectedCount:s}}async getCategoryStats(e){let t=await this.q(`SELECT kv.key AS cookie_id, kv.val AS status, COUNT(*)::int AS count
133
121
  FROM consent_records cr,
134
122
  jsonb_each_text(cr.consent_json) AS kv(key, val)
135
123
  WHERE cr.tenant_id=$1
136
- GROUP BY kv.key, kv.val`,[e]),n={};for(let i of t){n[i.cookie_id]||(n[i.cookie_id]={granted:0,denied:0,objected:0});let o=n[i.cookie_id];o&&(i.status==="granted"&&(o.granted+=Number(i.count)),i.status==="denied"&&(o.denied+=Number(i.count)),i.status==="objected"&&(o.objected+=Number(i.count)))}return n}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString();return(await this.q(`SELECT to_char(created_at, 'YYYY-MM-DD') AS date, COUNT(*)::int AS count
124
+ GROUP BY kv.key, kv.val`,[e]),n={};for(let o of t){n[o.cookie_id]||(n[o.cookie_id]={granted:0,denied:0,objected:0});let r=n[o.cookie_id];r&&(o.status==="granted"&&(r.granted+=Number(o.count)),o.status==="denied"&&(r.denied+=Number(o.count)),o.status==="objected"&&(r.objected+=Number(o.count)))}return n}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString();return(await this.q(`SELECT to_char(created_at, 'YYYY-MM-DD') AS date, COUNT(*)::int AS count
137
125
  FROM consent_records
138
126
  WHERE tenant_id=$1 AND created_at>=$2
139
127
  GROUP BY to_char(created_at, 'YYYY-MM-DD')
140
- ORDER BY date ASC`,[e,n])).map(o=>({date:o.date,count:Number(o.count)}))}async createUser(e){let t=(0,w.randomUUID)(),i=(await this.q("INSERT INTO users (id, tenant_id, name, email, password_hash) VALUES ($1,$2,$3,$4,$5) RETURNING *",[t,e.tenantId,e.name,e.email,e.passwordHash]))[0];if(!i)throw new Error("User creation failed");return Le(i)}async updateUser(e,t){let n=["updated_at=NOW()"],i=[],o=1;t.name!=null&&(n.push(`name=$${o++}`),i.push(t.name)),t.email!=null&&(n.push(`email=$${o++}`),i.push(t.email)),t.passwordHash!=null&&(n.push(`password_hash=$${o++}`),i.push(t.passwordHash)),t.isActive!=null&&(n.push(`is_active=$${o++}`),i.push(t.isActive)),i.push(e);let a=(await this.q(`UPDATE users SET ${n.join(",")} WHERE id=$${o} RETURNING *`,i))[0];if(!a)throw new Error(`User ${e} not found`);return Le(a)}async deleteUser(e){await this.q("DELETE FROM user_roles WHERE user_id=$1",[e]),await this.q("DELETE FROM users WHERE id=$1",[e])}async getUserById(e){let t=await this.q("SELECT * FROM users WHERE id=$1",[e]);return t[0]?Le(t[0]):null}async getUserByEmail(e){let t=await this.q("SELECT * FROM users WHERE email=$1",[e]);return t[0]?Le(t[0]):null}async getUsers(e){return(await this.q("SELECT * FROM users WHERE tenant_id=$1 ORDER BY created_at DESC",[e])).map(Le)}async countUsers(e){let t=e?await this.q("SELECT COUNT(*)::int AS total FROM users WHERE tenant_id=$1",[e]):await this.q("SELECT COUNT(*)::int AS total FROM users");return Number(t[0]?.total??0)}async getRoles(e){return(await this.q("SELECT * FROM roles WHERE tenant_id=$1",[e])).map(Ue)}async createRole(e){let t=(0,w.randomUUID)(),i=(await this.q("INSERT INTO roles (id, tenant_id, name, description) VALUES ($1,$2,$3,$4) RETURNING *",[t,e.tenantId,e.name,e.description??null]))[0];if(!i)throw new Error("Role creation failed");return Ue(i)}async updateRole(e,t){let n=[],i=[],o=1;if(t.name!=null&&(n.push(`name=$${o++}`),i.push(t.name)),t.description!=null&&(n.push(`description=$${o++}`),i.push(t.description)),n.length===0){let l=(await this.q("SELECT * FROM roles WHERE id=$1",[e]))[0];if(!l)throw new Error(`Role ${e} not found`);return Ue(l)}i.push(e);let a=(await this.q(`UPDATE roles SET ${n.join(",")} WHERE id=$${o} RETURNING *`,i))[0];if(!a)throw new Error(`Role ${e} not found`);return Ue(a)}async deleteRole(e){await this.q("DELETE FROM role_permissions WHERE role_id=$1",[e]),await this.q("DELETE FROM user_roles WHERE role_id=$1",[e]),await this.q("DELETE FROM roles WHERE id=$1",[e])}async getAllPermissions(){return(await this.q("SELECT * FROM permissions ORDER BY name")).map(Nn)}async getPermissionsForRole(e){return(await this.q("SELECT p.* FROM permissions p JOIN role_permissions rp ON p.id=rp.permission_id WHERE rp.role_id=$1",[e])).map(Nn)}async getUserRoles(e,t){return(t?await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=$1 AND ur.tenant_id=$2",[e,t]):await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=$1",[e])).map(Ue)}async assignRole(e,t,n="default"){await this.q("INSERT INTO user_roles (user_id, role_id, tenant_id) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",[e,t,n])}async revokeRole(e,t,n){n?await this.q("DELETE FROM user_roles WHERE user_id=$1 AND role_id=$2 AND tenant_id=$3",[e,t,n]):await this.q("DELETE FROM user_roles WHERE user_id=$1 AND role_id=$2",[e,t])}async assignPermissionToRole(e,t){await this.q("INSERT INTO role_permissions (role_id, permission_id) VALUES ($1,$2) ON CONFLICT DO NOTHING",[e,t])}async revokePermissionFromRole(e,t){await this.q("DELETE FROM role_permissions WHERE role_id=$1 AND permission_id=$2",[e,t])}async createLog(e){await this.q(`INSERT INTO audit_logs (id, tenant_id, user_id, action, resource_type, resource_id, old_data, new_data)
141
- VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb)`,[(0,w.randomUUID)(),e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null])}async getLogs(e){let{sql:t,params:n,nextIdx:i}=this.buildAuditQuery(e),o=e.page??1,r=e.limit??50;return(await this.q(`${t} ORDER BY created_at DESC LIMIT $${i} OFFSET $${i+1}`,[...n,r,(o-1)*r])).map(Mn)}async*streamAuditLogs(e){let{sql:t,params:n}=this.buildAuditQuery(e),i=await this.q(`${t} ORDER BY created_at ASC`,n);for(let o of i)yield Mn(o)}buildAuditQuery(e){let t="SELECT * FROM audit_logs WHERE tenant_id=$1",n=[e.tenantId],i=2;return e.action!=null&&(t+=` AND action=$${i++}`,n.push(e.action)),e.resourceType!=null&&(t+=` AND resource_type=$${i++}`,n.push(e.resourceType)),e.from!=null&&(t+=` AND created_at>=$${i++}`,n.push(e.from)),e.to!=null&&(t+=` AND created_at<=$${i++}`,n.push(e.to)),{sql:t,params:n,nextIdx:i}}async getCountries(e){return(await this.q(`SELECT v.country, COUNT(*)::int AS count FROM consent_records cr
128
+ ORDER BY date ASC`,[e,n])).map(r=>({date:r.date,count:Number(r.count)}))}async createUser(e){let t=(0,C.randomUUID)(),o=(await this.q("INSERT INTO users (id, tenant_id, name, email, password_hash) VALUES ($1,$2,$3,$4,$5) RETURNING *",[t,e.tenantId,e.name,e.email,e.passwordHash]))[0];if(!o)throw new Error("User creation failed");return Ye(o)}async updateUser(e,t){let n=["updated_at=NOW()"],o=[],r=1;t.name!=null&&(n.push(`name=$${r++}`),o.push(t.name)),t.email!=null&&(n.push(`email=$${r++}`),o.push(t.email)),t.passwordHash!=null&&(n.push(`password_hash=$${r++}`),o.push(t.passwordHash)),t.isActive!=null&&(n.push(`is_active=$${r++}`),o.push(t.isActive)),o.push(e);let a=(await this.q(`UPDATE users SET ${n.join(",")} WHERE id=$${r} RETURNING *`,o))[0];if(!a)throw new Error(`User ${e} not found`);return Ye(a)}async deleteUser(e){await this.q("DELETE FROM user_roles WHERE user_id=$1",[e]),await this.q("DELETE FROM users WHERE id=$1",[e])}async getUserById(e){let t=await this.q("SELECT * FROM users WHERE id=$1",[e]);return t[0]?Ye(t[0]):null}async getUserByEmail(e){let t=await this.q("SELECT * FROM users WHERE email=$1",[e]);return t[0]?Ye(t[0]):null}async getUsers(e){return(await this.q("SELECT * FROM users WHERE tenant_id=$1 ORDER BY created_at DESC",[e])).map(Ye)}async countUsers(e){let t=e?await this.q("SELECT COUNT(*)::int AS total FROM users WHERE tenant_id=$1",[e]):await this.q("SELECT COUNT(*)::int AS total FROM users");return Number(t[0]?.total??0)}async getRoles(e){return(await this.q("SELECT * FROM roles WHERE tenant_id=$1",[e])).map(Qe)}async createRole(e){let t=(0,C.randomUUID)(),o=(await this.q("INSERT INTO roles (id, tenant_id, name, description) VALUES ($1,$2,$3,$4) RETURNING *",[t,e.tenantId,e.name,e.description??null]))[0];if(!o)throw new Error("Role creation failed");return Qe(o)}async updateRole(e,t){let n=[],o=[],r=1;if(t.name!=null&&(n.push(`name=$${r++}`),o.push(t.name)),t.description!=null&&(n.push(`description=$${r++}`),o.push(t.description)),n.length===0){let l=(await this.q("SELECT * FROM roles WHERE id=$1",[e]))[0];if(!l)throw new Error(`Role ${e} not found`);return Qe(l)}o.push(e);let a=(await this.q(`UPDATE roles SET ${n.join(",")} WHERE id=$${r} RETURNING *`,o))[0];if(!a)throw new Error(`Role ${e} not found`);return Qe(a)}async deleteRole(e){await this.q("DELETE FROM role_permissions WHERE role_id=$1",[e]),await this.q("DELETE FROM user_roles WHERE role_id=$1",[e]),await this.q("DELETE FROM roles WHERE id=$1",[e])}async getAllPermissions(){return(await this.q("SELECT * FROM permissions ORDER BY name")).map(Ro)}async getPermissionsForRole(e){return(await this.q("SELECT p.* FROM permissions p JOIN role_permissions rp ON p.id=rp.permission_id WHERE rp.role_id=$1",[e])).map(Ro)}async getUserRoles(e,t){return(t?await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=$1 AND ur.tenant_id=$2",[e,t]):await this.q("SELECT r.* FROM roles r JOIN user_roles ur ON r.id=ur.role_id WHERE ur.user_id=$1",[e])).map(Qe)}async assignRole(e,t,n="default"){await this.q("INSERT INTO user_roles (user_id, role_id, tenant_id) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",[e,t,n])}async revokeRole(e,t,n){n?await this.q("DELETE FROM user_roles WHERE user_id=$1 AND role_id=$2 AND tenant_id=$3",[e,t,n]):await this.q("DELETE FROM user_roles WHERE user_id=$1 AND role_id=$2",[e,t])}async assignPermissionToRole(e,t){await this.q("INSERT INTO role_permissions (role_id, permission_id) VALUES ($1,$2) ON CONFLICT DO NOTHING",[e,t])}async revokePermissionFromRole(e,t){await this.q("DELETE FROM role_permissions WHERE role_id=$1 AND permission_id=$2",[e,t])}async createLog(e){await this.q(`INSERT INTO audit_logs (id, tenant_id, user_id, action, resource_type, resource_id, old_data, new_data)
129
+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb)`,[(0,C.randomUUID)(),e.tenantId,e.userId??null,e.action,e.resourceType,e.resourceId??null,e.oldData!=null?JSON.stringify(e.oldData):null,e.newData!=null?JSON.stringify(e.newData):null])}async getLogs(e){let{where:t,params:n,nextIdx:o}=this.buildAuditWhere(e),r=e.page??1,s=e.limit??50,[a,c]=await Promise.all([this.q(`SELECT ${Qc} ${t} ORDER BY created_at DESC LIMIT $${o} OFFSET $${o+1}`,[...n,s,(r-1)*s]),this.q(`SELECT COUNT(*)::int AS total ${t}`,n)]);return{items:a.map(Zc),total:Number(c[0]?.total??0),page:r,limit:s}}async getAuditLogById(e){let t=await this.q("SELECT * FROM audit_logs WHERE id=$1",[e]);return t[0]?So(t[0]):null}async*streamAuditLogs(e){let{where:t,params:n}=this.buildAuditWhere(e),o=await this.q(`SELECT * ${t} ORDER BY created_at ASC`,n);for(let r of o)yield So(r)}buildAuditWhere(e){let t="FROM audit_logs WHERE tenant_id=$1",n=[e.tenantId],o=2;return e.action!=null&&(t+=` AND action=$${o++}`,n.push(e.action)),e.resourceType!=null&&(t+=` AND resource_type=$${o++}`,n.push(e.resourceType)),e.from!=null&&(t+=` AND created_at>=$${o++}`,n.push(e.from)),e.to!=null&&(t+=` AND created_at<=$${o++}`,n.push(e.to)),e.q&&(t+=` AND (action ILIKE $${o} OR resource_type ILIKE $${o} OR resource_id ILIKE $${o} OR user_id ILIKE $${o}) ESCAPE '\\'`,n.push(j(e.q)),o++),{where:t,params:n,nextIdx:o}}async getCountries(e){return(await this.q(`SELECT v.country, COUNT(*)::int AS count FROM consent_records cr
142
130
  JOIN visitors v ON v.visitor_id=cr.visitor_id
143
131
  WHERE cr.tenant_id=$1 AND v.country IS NOT NULL
144
- GROUP BY v.country ORDER BY count DESC LIMIT 50`,[e])).map(n=>({country:n.country,count:Number(n.count)}))}async getGpcStats(e){let[t]=await this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1",[e]),[n]=await this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1 AND gpc_detected=TRUE",[e]),i=Number(t?.total??0),o=Number(n?.total??0);return{detected:o,total:i,rate:i>0?Math.round(o/i*100):0}}async getTenants(){return(await this.q("SELECT * FROM tenants ORDER BY name ASC",[])).map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}async createApiKey(e){let t=(0,w.randomUUID)(),i=(await this.q("INSERT INTO api_keys (id, tenant_id, key_hash, name) VALUES ($1,$2,$3,$4) RETURNING *",[t,e.tenantId,e.keyHash,e.name]))[0];if(!i)throw new Error("Failed to create API key");return{id:i.id,tenantId:i.tenant_id,keyHash:i.key_hash,name:i.name,isActive:i.is_active,createdAt:i.created_at}}async getApiKeyByHash(e){let n=(await this.q("SELECT * FROM api_keys WHERE key_hash=$1 AND is_active=TRUE",[e]))[0];return n?{id:n.id,tenantId:n.tenant_id,keyHash:n.key_hash,name:n.name,isActive:n.is_active,createdAt:n.created_at}:null}async revokeApiKey(e){await this.q("UPDATE api_keys SET is_active=FALSE WHERE id=$1",[e])}async getApiKeys(e){return(await this.q("SELECT * FROM api_keys WHERE tenant_id=$1 ORDER BY created_at DESC",[e])).map(n=>({id:n.id,tenantId:n.tenant_id,keyHash:n.key_hash,name:n.name,isActive:n.is_active,createdAt:n.created_at}))}async createTenant(e){let t=(0,w.randomUUID)(),n=new Date().toISOString(),o=(await this.q("INSERT INTO tenants (id, name, slug, created_at, updated_at) VALUES ($1,$2,$3,$4,$5) RETURNING *",[t,e.name,e.slug,n,n]))[0];if(!o)throw new Error("Failed to create tenant");return{id:o.id,name:o.name,slug:o.slug,createdAt:o.created_at,updatedAt:o.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),i=["updated_at=$1"],o=[n],r=2;t.name!=null&&(i.push(`name=$${r++}`),o.push(t.name)),t.slug!=null&&(i.push(`slug=$${r++}`),o.push(t.slug)),o.push(e);let c=(await this.q(`UPDATE tenants SET ${i.join(",")} WHERE id=$${r} RETURNING *`,o))[0];if(!c)throw new Error(`Tenant ${e} not found`);return{id:c.id,name:c.name,slug:c.slug,createdAt:c.created_at,updatedAt:c.updated_at}}async deleteTenant(e){await this.q("DELETE FROM tenants WHERE id=$1",[e])}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=await this.q("SELECT visitor_id FROM consent_records WHERE created_at < $1",[t]);if(n.length===0)return 0;let i=n.map(r=>r.visitor_id),o=i.map((r,a)=>`$${a+1}`).join(",");return await this.q(`DELETE FROM consent_history WHERE visitor_id IN (${o})`,i),await this.q(`DELETE FROM consent_records WHERE visitor_id IN (${o})`,i),i.length}async createCookieTemplate(){throw new Error("Not implemented")}async updateCookieTemplate(){throw new Error("Not implemented")}async deleteCookieTemplate(){throw new Error("Not implemented")}async getCookieTemplate(){throw new Error("Not implemented")}async getCookieTemplates(){throw new Error("Not implemented")}async copyCookieTemplate(){throw new Error("Not implemented")}async createUITemplate(){throw new Error("Not implemented")}async updateUITemplate(){throw new Error("Not implemented")}async deleteUITemplate(){throw new Error("Not implemented")}async getUITemplate(){throw new Error("Not implemented")}async getUITemplates(){throw new Error("Not implemented")}async copyUITemplate(){throw new Error("Not implemented")}async listProfilesSummary(){return[]}async findProfilesUsingCookieTemplate(){return[]}async findProfilesUsingUITemplate(){return[]}async getOptInStats(){throw new Error("Not implemented")}};var ie=require("node:fs/promises"),B=require("node:crypto");var po=500;function Gn(){return{_version:1,tenants:[],profiles:[],consents:[],consent_history:[],visitors:[],users:[],roles:[],permissions:[],user_roles:[],role_permissions:[],audit_logs:[],cookie_templates:[],ui_templates:[],api_keys:[]}}function mo(){return`prof_${(0,B.randomUUID)().replace(/-/g,"")}`}function Gt(s,e,t){let n=Math.min(t,po),i=(e-1)*n;return s.slice(i,i+n)}var it=class{constructor(e){this.config=e}config;db=Gn();filePath="";writeQueue=Promise.resolve();scheduleWrite(){this.writeQueue=this.writeQueue.then(async()=>{await(0,ie.mkdir)(this.filePath.replace(/\/[^/]+$/,""),{recursive:!0});let e=`${this.filePath}.tmp`;await(0,ie.writeFile)(e,JSON.stringify(this.db),"utf8"),await(0,ie.rename)(e,this.filePath)}).catch(e=>{console.warn("[Consenti] JSON store write failed:",e)})}async connect(){let{dbPath:e}=Q(this.config.path??"./consenti-data","json");this.filePath=e;try{let t=await(0,ie.readFile)(this.filePath,"utf8");this.db=JSON.parse(t)}catch{this.db=Gn()}await this.migrate()}async disconnect(){await this.writeQueue}async migrate(){this.seed()}seed(){let e=new Date().toISOString(),{id:t,name:n,slug:i}=$;this.db.tenants.find(o=>o.id===t)||this.db.tenants.push({id:t,name:n,slug:i,createdAt:e,updatedAt:e});for(let o of j)this.db.permissions.find(r=>r.id===o.id)||this.db.permissions.push({id:o.id,name:o.name,description:o.description});for(let o of Z)this.db.roles.find(r=>r.id===o.id)||this.db.roles.push({id:o.id,tenantId:o.tenantId,name:o.name,description:o.description});for(let o of ee)this.db.role_permissions.find(r=>r.roleId===o.roleId&&r.permissionId===o.permissionId)||this.db.role_permissions.push(o);this.scheduleWrite()}async createProfile(e){let t=new Date().toISOString(),n={id:mo(),tenantId:e.tenantId,name:e.name,defaultLocale:e.defaultLocale,version:1,profileJson:e.profileJson,createdAt:t,updatedAt:t};return this.db.profiles.push(n),this.scheduleWrite(),n}async updateProfile(e,t){let n=this.db.profiles.findIndex(r=>r.id===e);if(n===-1)throw new Error(`Profile ${e} not found`);let i=this.db.profiles[n],o={...i,...t.name!=null&&{name:t.name},...t.defaultLocale!=null&&{defaultLocale:t.defaultLocale},...t.profileJson!=null&&{profileJson:t.profileJson},version:i.version+1,updatedAt:new Date().toISOString()};return this.db.profiles[n]=o,this.scheduleWrite(),o}async deleteProfile(e){this.db.profiles=this.db.profiles.filter(t=>t.id!==e),this.scheduleWrite()}async getProfile(e){return this.db.profiles.find(t=>t.id===e)??null}async getProfiles(e){return this.db.profiles.filter(t=>t.tenantId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}async findActiveProfileByComplianceGroup(e,t){return this.db.profiles.find(n=>n.tenantId===e&&n.profileJson.complianceGroup===t&&n.profileJson.isActive)??null}async createConsent(e){let t=new Date().toISOString(),n=(0,B.randomUUID)(),i={id:n,tenantId:e.tenantId,visitorId:e.visitorId,profileId:e.profileId,profileVersion:e.profileVersion,locale:e.locale,consentJson:e.consentJson,gpcDetected:e.gpcDetected??!1,source:e.source,createdAt:t,updatedAt:t};return this.db.consents.push(i),this.db.consent_history.push({id:(0,B.randomUUID)(),tenantId:e.tenantId,consentRecordId:n,visitorId:e.visitorId,oldJson:null,newJson:e.consentJson,action:"created",createdAt:t}),this.scheduleWrite(),i}async updateConsent(e,t){let n=this.db.consents.findIndex(a=>a.visitorId===e);if(n===-1)throw new Error(`Consent for visitor ${e} not found`);let i=this.db.consents[n],o=new Date().toISOString(),r={...i,consentJson:t.consentJson,...t.locale!=null&&{locale:t.locale},...t.gpcDetected!=null&&{gpcDetected:t.gpcDetected},updatedAt:o};return this.db.consents[n]=r,this.db.consent_history.push({id:(0,B.randomUUID)(),tenantId:i.tenantId,consentRecordId:i.id,visitorId:e,oldJson:i.consentJson,newJson:t.consentJson,action:"updated",createdAt:o}),this.scheduleWrite(),r}async deleteConsent(e){this.db.consent_history=this.db.consent_history.filter(t=>t.visitorId!==e),this.db.consents=this.db.consents.filter(t=>t.visitorId!==e),this.scheduleWrite()}async getConsent(e){return this.db.consents.find(t=>t.visitorId===e)??null}async getConsents(e){let t=this.db.consents.filter(n=>n.tenantId===e.tenantId);return e.profileId&&(t=t.filter(n=>n.profileId===e.profileId)),e.from&&(t=t.filter(n=>n.createdAt>=e.from)),e.to&&(t=t.filter(n=>n.createdAt<=e.to)),t.sort((n,i)=>i.createdAt.localeCompare(n.createdAt)),Gt(t,e.page??1,e.limit??50)}async*streamConsents(e){for(let t of this.db.consents.filter(n=>n.tenantId===e.tenantId))yield t}async getConsentHistory(e){return this.db.consent_history.filter(t=>t.visitorId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}async createVisitor(e){let t=new Date().toISOString(),n={id:(0,B.randomUUID)(),tenantId:e.tenantId,visitorId:e.visitorId,firstSeen:t,lastSeen:t,...e.country!=null&&{country:e.country},...e.region!=null&&{region:e.region},...e.city!=null&&{city:e.city},...e.ipHash!=null&&{ipHash:e.ipHash},...e.userAgentHash!=null&&{userAgentHash:e.userAgentHash}};return this.db.visitors.push(n),this.scheduleWrite(),n}async updateVisitor(e,t){let n=this.db.visitors.findIndex(r=>r.visitorId===e);if(n===-1)throw new Error(`Visitor ${e} not found`);let o={...this.db.visitors[n],lastSeen:t.lastSeen??new Date().toISOString(),...t.country!=null&&{country:t.country},...t.region!=null&&{region:t.region},...t.city!=null&&{city:t.city}};return this.db.visitors[n]=o,this.scheduleWrite(),o}async deleteVisitor(e){this.db.visitors=this.db.visitors.filter(t=>t.visitorId!==e),this.scheduleWrite()}async getVisitor(e){return this.db.visitors.find(t=>t.visitorId===e)??null}async getVisitors(e){let t=this.db.visitors.filter(n=>n.tenantId===e.tenantId);return e.from&&(t=t.filter(n=>n.firstSeen>=e.from)),e.to&&(t=t.filter(n=>n.firstSeen<=e.to)),t.sort((n,i)=>i.lastSeen.localeCompare(n.lastSeen)),Gt(t,e.page??1,e.limit??50)}async createUser(e){let t=new Date().toISOString(),n={id:(0,B.randomUUID)(),tenantId:e.tenantId,name:e.name,email:e.email,passwordHash:e.passwordHash,isActive:!0,allowedTenants:e.allowedTenants??[],createdAt:t,updatedAt:t};return this.db.users.push(n),this.scheduleWrite(),n}async updateUser(e,t){let n=this.db.users.findIndex(r=>r.id===e);if(n===-1)throw new Error(`User ${e} not found`);let o={...this.db.users[n],...t.name!=null&&{name:t.name},...t.email!=null&&{email:t.email},...t.passwordHash!=null&&{passwordHash:t.passwordHash},...t.isActive!=null&&{isActive:t.isActive},..."totpSecret"in t&&t.totpSecret!=null&&{totpSecret:t.totpSecret},...t.totpEnabled!=null&&{totpEnabled:t.totpEnabled},..."allowedTenants"in t&&{allowedTenants:t.allowedTenants??[]},updatedAt:new Date().toISOString()};return this.db.users[n]=o,this.scheduleWrite(),o}async deleteUser(e){this.db.user_roles=this.db.user_roles.filter(t=>t.userId!==e),this.db.users=this.db.users.filter(t=>t.id!==e),this.scheduleWrite()}async getUserById(e){return this.db.users.find(t=>t.id===e)??null}async getUserByEmail(e){return this.db.users.find(t=>t.email===e)??null}async getUsers(e){return this.db.users.filter(t=>t.tenantId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}async countUsers(e){return e?this.db.users.filter(t=>t.tenantId===e).length:this.db.users.length}async getRoles(e){return this.db.roles.filter(t=>t.tenantId===e)}async createRole(e){let t={id:(0,B.randomUUID)(),tenantId:e.tenantId,name:e.name,...e.description!=null&&{description:e.description}};return this.db.roles.push(t),this.scheduleWrite(),t}async updateRole(e,t){let n=this.db.roles.findIndex(o=>o.id===e);if(n===-1)throw new Error(`Role ${e} not found`);let i={...this.db.roles[n],...t.name!=null&&{name:t.name},...t.description!=null&&{description:t.description}};return this.db.roles[n]=i,this.scheduleWrite(),i}async deleteRole(e){this.db.role_permissions=this.db.role_permissions.filter(t=>t.roleId!==e),this.db.user_roles=this.db.user_roles.filter(t=>t.roleId!==e),this.db.roles=this.db.roles.filter(t=>t.id!==e),this.scheduleWrite()}async getAllPermissions(){return[...this.db.permissions].sort((e,t)=>e.name.localeCompare(t.name))}async getPermissionsForRole(e){let t=new Set(this.db.role_permissions.filter(n=>n.roleId===e).map(n=>n.permissionId));return this.db.permissions.filter(n=>t.has(n.id))}async getUserRoles(e,t){let n=this.db.user_roles.filter(o=>o.userId===e);t&&(n=n.filter(o=>o.tenantId===t));let i=new Set(n.map(o=>o.roleId));return this.db.roles.filter(o=>i.has(o.id))}async assignRole(e,t,n="default"){this.db.user_roles.find(i=>i.userId===e&&i.roleId===t&&i.tenantId===n)||(this.db.user_roles.push({userId:e,roleId:t,tenantId:n}),this.scheduleWrite())}async revokeRole(e,t,n){this.db.user_roles=this.db.user_roles.filter(i=>!(i.userId===e&&i.roleId===t&&(n==null||i.tenantId===n))),this.scheduleWrite()}async assignPermissionToRole(e,t){this.db.role_permissions.find(n=>n.roleId===e&&n.permissionId===t)||(this.db.role_permissions.push({roleId:e,permissionId:t}),this.scheduleWrite())}async revokePermissionFromRole(e,t){this.db.role_permissions=this.db.role_permissions.filter(n=>!(n.roleId===e&&n.permissionId===t)),this.scheduleWrite()}async createLog(e){let t={id:(0,B.randomUUID)(),tenantId:e.tenantId,action:e.action,resourceType:e.resourceType,createdAt:new Date().toISOString(),...e.userId!=null&&{userId:e.userId},...e.resourceId!=null&&{resourceId:e.resourceId},...e.oldData!=null&&{oldData:e.oldData},...e.newData!=null&&{newData:e.newData}};this.db.audit_logs.push(t),this.scheduleWrite()}async getLogs(e){let t=this.db.audit_logs.filter(n=>n.tenantId===e.tenantId);return e.action&&(t=t.filter(n=>n.action===e.action)),e.resourceType&&(t=t.filter(n=>n.resourceType===e.resourceType)),e.from&&(t=t.filter(n=>n.createdAt>=e.from)),e.to&&(t=t.filter(n=>n.createdAt<=e.to)),t.sort((n,i)=>i.createdAt.localeCompare(n.createdAt)),Gt(t,e.page??1,e.limit??50)}async*streamAuditLogs(e){let t=this.db.audit_logs.filter(n=>n.tenantId===e.tenantId);e.action&&(t=t.filter(n=>n.action===e.action)),e.from&&(t=t.filter(n=>n.createdAt>=e.from)),e.to&&(t=t.filter(n=>n.createdAt<=e.to)),t.sort((n,i)=>i.createdAt.localeCompare(n.createdAt));for(let n of t)yield n}async getOverviewStats(e){let t=this.db.consents.filter(a=>a.tenantId===e),n=t.slice(-500),i=0,o=0;for(let a of n){let c=Object.values(a.consentJson),l=c.length>0?c.filter(u=>u==="granted").length/c.length:0;l>=.8?i++:l<=.2&&o++}let r=n.length||1;return{totalConsents:t.length,gpcDetectedCount:t.filter(a=>a.gpcDetected).length,totalVisitors:this.db.visitors.filter(a=>a.tenantId===e).length,acceptedPct:Math.round(i/r*100),rejectedPct:Math.round(o/r*100)}}async getCategoryStats(e){let t={};for(let n of this.db.consents.filter(i=>i.tenantId===e).slice(0,5e3))for(let[i,o]of Object.entries(n.consentJson))t[i]||(t[i]={granted:0,denied:0,objected:0}),o==="granted"?t[i].granted++:o==="denied"?t[i].denied++:o==="objected"&&t[i].objected++;return t}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString().slice(0,10),i=new Map;for(let o of this.db.consents.filter(r=>r.tenantId===e&&r.createdAt.slice(0,10)>=n)){let r=o.createdAt.slice(0,10);i.set(r,(i.get(r)??0)+1)}return[...i.entries()].sort(([o],[r])=>o.localeCompare(r)).map(([o,r])=>({date:o,count:r}))}async getCountries(e){let t=new Set(this.db.consents.filter(i=>i.tenantId===e).map(i=>i.visitorId)),n=new Map;for(let i of this.db.visitors.filter(o=>t.has(o.visitorId)&&o.country)){let o=i.country;n.set(o,(n.get(o)??0)+1)}return[...n.entries()].sort(([,i],[,o])=>o-i).slice(0,50).map(([i,o])=>({country:i,count:o}))}async getGpcStats(e){let t=this.db.consents.filter(o=>o.tenantId===e),n=t.filter(o=>o.gpcDetected).length,i=t.length;return{detected:n,total:i,rate:i>0?Math.round(n/i*100):0}}async getTenants(){return[...this.db.tenants].sort((e,t)=>e.name.localeCompare(t.name))}async createTenant(e){let t=new Date().toISOString(),n={id:(0,B.randomUUID)(),name:e.name,slug:e.slug,createdAt:t,updatedAt:t};return this.db.tenants.push(n),this.scheduleWrite(),n}async updateTenant(e,t){let n=this.db.tenants.findIndex(r=>r.id===e);if(n===-1)throw new Error(`Tenant ${e} not found`);let i=new Date().toISOString(),o={...this.db.tenants[n],...t.name!=null&&{name:t.name},...t.slug!=null&&{slug:t.slug},updatedAt:i};return this.db.tenants[n]=o,this.scheduleWrite(),o}async deleteTenant(e){this.db.tenants=this.db.tenants.filter(t=>t.id!==e),this.scheduleWrite()}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=new Set(this.db.consents.filter(i=>i.createdAt<t).map(i=>i.visitorId));return n.size===0?0:(this.db.consent_history=this.db.consent_history.filter(i=>!n.has(i.visitorId)),this.db.consents=this.db.consents.filter(i=>!n.has(i.visitorId)),this.scheduleWrite(),n.size)}async createApiKey(e){let t={id:(0,B.randomUUID)(),tenantId:e.tenantId,keyHash:e.keyHash,name:e.name,isActive:!0,createdAt:new Date().toISOString()};return this.db.api_keys.push(t),this.scheduleWrite(),t}async getApiKeyByHash(e){return this.db.api_keys.find(t=>t.keyHash===e&&t.isActive)??null}async revokeApiKey(e){let t=this.db.api_keys.find(n=>n.id===e);t&&(t.isActive=!1,this.scheduleWrite())}async getApiKeys(e){return this.db.api_keys.filter(t=>t.tenantId===e).sort((t,n)=>n.createdAt.localeCompare(t.createdAt))}async createCookieTemplate(e){let t=new Date().toISOString(),n={id:(0,B.randomUUID)(),tenantId:e.tenantId,name:e.name,cookies:e.cookies,createdAt:t,updatedAt:t};return this.db.cookie_templates.push(n),this.scheduleWrite(),n}async updateCookieTemplate(e,t){let n=this.db.cookie_templates.findIndex(r=>r.id===e);if(n===-1)throw new Error("Cookie template not found");let i=new Date().toISOString(),o={...this.db.cookie_templates[n],...t.name!==void 0&&{name:t.name},...t.cookies!==void 0&&{cookies:t.cookies},updatedAt:i};return this.db.cookie_templates[n]=o,this.scheduleWrite(),o}async deleteCookieTemplate(e){this.db.cookie_templates=this.db.cookie_templates.filter(t=>t.id!==e),this.scheduleWrite()}async getCookieTemplate(e){return this.db.cookie_templates.find(t=>t.id===e)??null}async getCookieTemplates(e){return this.db.cookie_templates.filter(t=>t.tenantId===e).sort((t,n)=>t.name.localeCompare(n.name))}async copyCookieTemplate(e,t){let n=await this.getCookieTemplate(e);if(!n)throw new Error("Cookie template not found");return this.createCookieTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies})}async createUITemplate(e){let t=new Date().toISOString(),{tenantId:n,name:i,...o}=e,r={id:(0,B.randomUUID)(),tenantId:n,name:i,...o,createdAt:t,updatedAt:t};return this.db.ui_templates.push(r),this.scheduleWrite(),r}async updateUITemplate(e,t){let n=this.db.ui_templates.findIndex(c=>c.id===e);if(n===-1)throw new Error("UI template not found");let{name:i,...o}=t,r=new Date().toISOString(),a={...this.db.ui_templates[n],...t.name!==void 0&&{name:t.name},...o,updatedAt:r};return this.db.ui_templates[n]=a,this.scheduleWrite(),a}async deleteUITemplate(e){this.db.ui_templates=this.db.ui_templates.filter(t=>t.id!==e),this.scheduleWrite()}async getUITemplate(e){return this.db.ui_templates.find(t=>t.id===e)??null}async getUITemplates(e){return this.db.ui_templates.filter(t=>t.tenantId===e).sort((t,n)=>t.name.localeCompare(n.name))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:i,mainBanner:o,gpcBanner:r,preferenceModal:a}=n;return this.createUITemplate({tenantId:i,name:t,...o!==void 0&&{mainBanner:o},...r!==void 0&&{gpcBanner:r},...a!==void 0&&{preferenceModal:a}})}profileToSummary(e){let t=e.profileJson,n=t.cookieTemplateId?this.db.cookie_templates.find(o=>o.id===t.cookieTemplateId):null,i=t.uiTemplateId?this.db.ui_templates.find(o=>o.id===t.uiTemplateId):null;return{id:e.id,name:e.name,defaultLocale:e.defaultLocale,complianceGroup:t.complianceGroup??null,version:e.version,isActive:t.isActive??!1,cookieTemplateName:n?.name??null,uiTemplateName:i?.name??null,createdAt:e.createdAt,updatedAt:e.updatedAt}}async listProfilesSummary(e){return this.db.profiles.filter(t=>t.tenantId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt)).map(t=>this.profileToSummary(t))}async findProfilesUsingCookieTemplate(e){return this.db.profiles.filter(t=>t.profileJson.cookieTemplateId===e).sort((t,n)=>t.name.localeCompare(n.name)).map(t=>this.profileToSummary(t))}async findProfilesUsingUITemplate(e){return this.db.profiles.filter(t=>t.profileJson.uiTemplateId===e).sort((t,n)=>t.name.localeCompare(n.name)).map(t=>this.profileToSummary(t))}async getOptInStats(e,t){let n=this.db.consents.filter(d=>d.tenantId===e);t.profileId&&(n=n.filter(d=>d.profileId===t.profileId)),t.from&&(n=n.filter(d=>d.createdAt>=t.from)),t.to&&(n=n.filter(d=>d.createdAt<=t.to)),t.locale&&(n=n.filter(d=>d.locale===t.locale));let i=0,o=0,r=0,a=0,c={},l=new Map;for(let d of n){let p=Object.values(d.consentJson),E=p.length>0?p.filter(A=>A==="granted").length/p.length:0,S=p.length>0?p.filter(A=>A==="denied").length/p.length:0;i++;let f=d.locale;c[f]||(c[f]={total:0,granted:0,denied:0,managed:0}),c[f].total++;let _=d.createdAt.slice(0,10),h=l.get(_)??{total:0,granted:0,denied:0,managed:0};h.total++,E>=.9?(o++,c[f].granted++,h.granted++):S>=.9?(r++,c[f].denied++,h.denied++):(a++,c[f].managed++,h.managed++),l.set(_,h)}let u=Array.from(l.entries()).sort(([d],[p])=>d.localeCompare(p)).map(([d,p])=>({date:d,...p}));return{total:i,granted:o,denied:r,managed:a,grantedPct:i>0?Math.round(o/i*1e3)/10:0,deniedPct:i>0?Math.round(r/i*1e3)/10:0,managedPct:i>0?Math.round(a/i*1e3)/10:0,byLocale:c,byDate:u}}};var st=class{constructor(e){this.adapter=e}adapter;create(e){return this.adapter.createProfile(e)}update(e,t){return this.adapter.updateProfile(e,t)}delete(e){return this.adapter.deleteProfile(e)}get(e){return this.adapter.getProfile(e)}list(e){return this.adapter.getProfiles(e)}findActiveByComplianceGroup(e,t){return this.adapter.findActiveProfileByComplianceGroup(e,t)}};var ot=class{constructor(e){this.adapter=e}adapter;create(e){return this.adapter.createConsent(e)}update(e,t){return this.adapter.updateConsent(e,t)}delete(e){return this.adapter.deleteConsent(e)}get(e){return this.adapter.getConsent(e)}list(e){return this.adapter.getConsents(e)}};var rt=class{constructor(e){this.adapter=e}adapter;create(e){return this.adapter.createVisitor(e)}update(e,t){return this.adapter.updateVisitor(e,t)}delete(e){return this.adapter.deleteVisitor(e)}get(e){return this.adapter.getVisitor(e)}};var at=class{constructor(e){this.adapter=e}adapter;log(e){return this.adapter.createLog(e)}list(e){return this.adapter.getLogs(e)}};var ct=class{constructor(e){this.adapter=e}adapter;getById(e){return this.adapter.getUserById(e)}getByEmail(e){return this.adapter.getUserByEmail(e)}list(e){return this.adapter.getUsers(e)}create(e){return this.adapter.createUser(e)}update(e,t){return this.adapter.updateUser(e,t)}delete(e){return this.adapter.deleteUser(e)}getRoles(e,t){return this.adapter.getUserRoles(e,t)}assignRole(e,t,n){return this.adapter.assignRole(e,t,n)}revokeRole(e,t,n){return this.adapter.revokeRole(e,t,n)}};function xn(s,e){return{mainBanner:{...s.mainBanner,...e.mainBanner},preferenceModal:{...s.preferenceModal,...e.preferenceModal,buttons:e.preferenceModal?.buttons??s.preferenceModal.buttons,categories:e.preferenceModal?.categories??s.preferenceModal.categories},...e.gpcBanner!=null||s.gpcBanner!=null?{gpcBanner:{...s.gpcBanner??s.mainBanner,...e.gpcBanner}}:{}}}function xt(s,e,t){let n=s[t];if(!n)throw new Error(`Default locale '${t}' not found in translations`);if(e===t)return n;let i=s[e];if(i)return xn(n,i);let o=e.split("-")[0]??"",r=o?s[o]:void 0;return r?xn(n,r):n}var J=require("node:fs"),te=require("node:path");var qn=require("node:worker_threads"),Kn=require("node:url"),ut=require("node:path"),Yn=require("node:fs");var U=require("node:fs"),W=require("node:path");var ke=require("node:crypto");function Ft(s){return(0,ke.createHash)("sha256").update(s).digest("hex")}function lt(s,e){return(0,ke.createHmac)("sha256",s).update(e).digest()}function go(s){let e=s.toISOString().replace(/[-:]/g,"").slice(0,15)+"Z";return{amzDate:e,dateStamp:e.slice(0,8)}}function fo(s,e,t,n){let i=lt(`AWS4${s}`,e),o=lt(i,t),r=lt(o,n);return lt(r,"aws4_request")}function Fn(s){let{method:e,key:t,body:n,contentType:i,config:o}=s,r=new Date,{amzDate:a,dateStamp:c}=go(r),l=`${o.bucketName}.s3.${o.region}.amazonaws.com`,u=Ft(n?Buffer.isBuffer(n)?n:Buffer.from(n,"utf8"):""),d={host:l,"x-amz-date":a,"x-amz-content-sha256":u};o.sessionToken&&(d["x-amz-security-token"]=o.sessionToken),i&&e==="PUT"&&(d["content-type"]=i);let p=Object.keys(d).sort(),E=p.map(O=>`${O}:${d[O]}
145
- `).join(""),S=p.join(";"),f=[e,`/${encodeURIComponent(t).replace(/%2F/g,"/")}`,"",E,S,u].join(`
146
- `),_=`${c}/${o.region}/s3/aws4_request`,h=["AWS4-HMAC-SHA256",a,_,Ft(f)].join(`
147
- `),A=fo(o.secretAccessKey,c,o.region,"s3"),T=(0,ke.createHmac)("sha256",A).update(h).digest("hex"),I=[`AWS4-HMAC-SHA256 Credential=${o.accessKeyId}/${_}`,`SignedHeaders=${S}`,`Signature=${T}`].join(", ");return{...d,authorization:I}}function Hn(s,e){let t=encodeURIComponent(s).replace(/%2F/g,"/");return`https://${e.bucketName}.s3.${e.region}.amazonaws.com/${t}`}async function dt(s,e,t,n="application/json"){let i=Fn({method:"PUT",key:s,body:e,contentType:n,config:t}),o=typeof e=="string"?e:e.toString("utf8"),r=await fetch(Hn(s,t),{method:"PUT",headers:{...i,"content-length":String(Buffer.byteLength(o,"utf8"))},body:o});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`S3 PUT ${s} failed: ${r.status} ${a}`)}}async function Ht(s,e){let t=Fn({method:"DELETE",key:s,config:e}),n=await fetch(Hn(s,e),{method:"DELETE",headers:t});if(!n.ok&&n.status!==404){let i=await n.text().catch(()=>"");throw new Error(`S3 DELETE ${s} failed: ${n.status} ${i}`)}}function Bn(s,e){return(0,W.join)(s,"profiles",e)}function Vn(s,e,t,n){return(0,W.join)(Bn(s,e),t,String(n))}function Wn(s,e,t){return(0,W.join)(Bn(s,e),t)}function Ne(s,e,t){return`profiles/${s}/${e}/${t}.json`}function jn(s,e){let t=s+".tmp";(0,U.writeFileSync)(t,e,"utf8"),JSON.parse(e),(0,U.renameSync)(t,s)}async function $n(s){let{storagePath:e,tenantId:t,profileId:n,version:i,profile:o,s3Config:r}=s,a=Vn(e,t,n,i);(0,U.mkdirSync)(a,{recursive:!0});let c=o.locales??[],l=o.defaultLocale,u=o.translations??{};for(let d of c){let p=d===o.currentLocale?JSON.stringify(o,null,2):JSON.stringify({...o,currentLocale:d,...u[d]??{}},null,2),E=(0,W.join)(a,`${d}.json`);jn(E,p),d===l&&jn((0,W.join)(a,"default.json"),p),r?.enabled&&(await dt(Ne(t,`${n}/${i}`,d),p,r),d===l&&await dt(Ne(t,`${n}/${i}`,"default"),p,r))}if(!(0,U.existsSync)((0,W.join)(a,"default.json"))){let d=c.includes(l)?l:c[0]??"";if(d){let p=(0,W.join)(a,`${d}.json`);(0,U.existsSync)(p)&&(0,U.copyFileSync)(p,(0,W.join)(a,"default.json"))}}}async function yo(s){let{storagePath:e,tenantId:t,profileId:n,version:i,complianceGroup:o,s3Config:r}=s,a=Vn(e,t,n,i),c=Wn(e,t,o);(0,U.mkdirSync)(c,{recursive:!0});let l=(0,U.readdirSync)(a).filter(u=>u.endsWith(".json"));for(let u of l)if((0,U.copyFileSync)((0,W.join)(a,u),(0,W.join)(c,u)),r?.enabled){let d=(0,U.readFileSync)((0,W.join)(c,u),"utf8");await dt(Ne(t,o,u.replace(".json","")),d,r)}}async function ho(s){let{storagePath:e,tenantId:t,complianceGroup:n,s3Config:i,profile:o}=s,r=Wn(e,t,n);if((0,U.existsSync)(r)){if(i?.enabled){let a=o.locales??[];for(let c of a)await Ht(Ne(t,n,c),i);await Ht(Ne(t,n,"default"),i)}(0,U.rmSync)(r,{recursive:!0,force:!0})}}async function Jn(s){s.action==="write"?await $n(s):s.action==="activate"?(await $n(s),await yo(s)):s.action==="deactivate"&&await ho(s)}var _o=(0,ut.dirname)((0,Kn.fileURLToPath)(R)),zn=(0,ut.join)(_o,"profile-json.worker.js"),Eo=!(0,Yn.existsSync)(zn);async function Qn(s){if(Eo){await Jn(s);return}return new Promise((e,t)=>{let n=new qn.Worker(zn);n.postMessage(s),n.once("message",i=>{n.terminate(),i.ok?e():t(new Error(`[profile-worker] ${i.action} failed: ${i.error}`))}),n.once("error",i=>{n.terminate(),t(i)})})}function wo(s,e){let t={};for(let[n,i]of Object.entries(e))t[n]={mainBanner:{position:s.mainBanner.position,...s.mainBanner.overlayOpacity!==void 0?{overlayOpacity:s.mainBanner.overlayOpacity}:{},...s.mainBanner.showClose!==void 0?{showClose:s.mainBanner.showClose}:{},...s.mainBanner.showLocaleSwitcher!==void 0?{showLocaleSwitcher:s.mainBanner.showLocaleSwitcher}:{},...s.mainBanner.headingTag!==void 0?{headingTag:s.mainBanner.headingTag}:{},...i.mainBanner.heading!==void 0?{heading:i.mainBanner.heading}:{},htmlText:i.mainBanner.htmlText,buttons:s.mainBanner.buttons.map((o,r)=>({text:i.mainBanner.buttonLabels?.[r]??o.text,style:o.style,action:o.action,...o.url!==void 0?{url:o.url}:{},...o.type!==void 0?{type:o.type}:{},...o.cookies!==void 0?{cookies:o.cookies}:{}}))},gpcBanner:{position:s.gpcBanner.position,...s.gpcBanner.overlayOpacity!==void 0?{overlayOpacity:s.gpcBanner.overlayOpacity}:{},...s.gpcBanner.showClose!==void 0?{showClose:s.gpcBanner.showClose}:{},...s.gpcBanner.showLocaleSwitcher!==void 0?{showLocaleSwitcher:s.gpcBanner.showLocaleSwitcher}:{},...s.gpcBanner.headingTag!==void 0?{headingTag:s.gpcBanner.headingTag}:{},...i.gpcBanner.heading!==void 0?{heading:i.gpcBanner.heading}:{},htmlText:i.gpcBanner.htmlText,buttons:s.gpcBanner.buttons.map((o,r)=>({text:i.gpcBanner.buttonLabels?.[r]??o.text,style:o.style,action:o.action,...o.url!==void 0?{url:o.url}:{},...o.type!==void 0?{type:o.type}:{},...o.cookies!==void 0?{cookies:o.cookies}:{}}))},preferenceModal:{...s.preferenceModal.position!==void 0?{position:s.preferenceModal.position}:{},...s.preferenceModal.overlayOpacity!==void 0?{overlayOpacity:s.preferenceModal.overlayOpacity}:{},...s.preferenceModal.showClose!==void 0?{showClose:s.preferenceModal.showClose}:{},...s.preferenceModal.showLocaleSwitcher!==void 0?{showLocaleSwitcher:s.preferenceModal.showLocaleSwitcher}:{},...s.preferenceModal.persistent!==void 0?{persistent:s.preferenceModal.persistent}:{},...s.preferenceModal.headingTag!==void 0?{headingTag:s.preferenceModal.headingTag}:{},...s.preferenceModal.mobileFullScreenBreakpoint!==void 0?{mobileFullScreenBreakpoint:s.preferenceModal.mobileFullScreenBreakpoint}:{},heading:i.preferenceModal.heading??"",...i.preferenceModal.subheading!==void 0?{subheading:i.preferenceModal.subheading}:{},htmlText:i.preferenceModal.htmlText??"",buttons:s.preferenceModal.buttons.map((o,r)=>({text:i.preferenceModal.buttonLabels?.[r]??o.text,style:o.style,action:o.action,...o.url!==void 0?{url:o.url}:{},...o.type!==void 0?{type:o.type}:{},...o.cookies!==void 0?{cookies:o.cookies}:{}})),categories:s.preferenceModal.categories.map(o=>{let r=i.preferenceModal.categories.find(a=>a.id===o.id);return{id:o.id,heading:r?.heading??o.id,...o.headingTag!==void 0?{headingTag:o.headingTag}:{},htmlText:r?.htmlText??"",...o.mandatory!==void 0?{mandatory:o.mandatory}:{},...o.type!==void 0?{type:o.type}:{},...o.legitimateInterest?.enabled?{legitimateInterest:{enabled:!0}}:{},cookies:o.cookies}})}};return t}function Ro(s){return s.legalBasis?s:s.mandatory?{...s,legalBasis:"mandatory"}:s.type?{...s,legalBasis:s.type}:s}var pt=class{constructor(e,t,n="default",i,o,r,a,c,l){this.profiles=e;this.audit=t;this.tenantId=n;this.storage=i;this.eventBus=o;this.localeCache=r;this.profilesDir=a;this.handleCache=c;this.s3Config=l}profiles;audit;tenantId;storage;eventBus;localeCache;profilesDir;handleCache;s3Config;profileDir(e){return(0,te.join)(this.profilesDir??"",this.tenantId,e)}complianceGroupDir(e){return(0,te.join)(this.profilesDir??"",this.tenantId,e)}profileFilePaths(e,t){let n=this.complianceGroupDir(e);return t.map(i=>(0,te.join)(n,`${i}.json`)).concat((0,te.join)(n,"default.json"))}async create(e){let t=await this.profiles.create({...e,tenantId:this.tenantId});if(await this.audit.log({tenantId:this.tenantId,action:"profile.created",resourceType:"profile",resourceId:t.id,newData:t}),this.eventBus?.emit("profile.created",t),this.profilesDir){let n=await this.getResolved(t.id);if(n){let i=t.profileJson.complianceGroup??"";await this.runWrite({action:"write",profile:n,profileId:t.id,version:t.version,complianceGroup:i});let o=this.profileFilePaths(i,n.locales);this.handleCache?.(o,t.version,!1),this.eventBus?.emit("cache:warm",{paths:o,version:t.version})}}return t}async update(e,t){let n=await this.profiles.get(e),i=await this.profiles.update(e,t);if(this.localeCache?.invalidate(e),await this.audit.log({tenantId:this.tenantId,action:"profile.updated",resourceType:"profile",resourceId:e,...n!=null?{oldData:n}:{},newData:i}),this.eventBus?.emit("profile.updated",{previous:n,current:i}),this.profilesDir){let o=await this.getResolved(i.id);if(o){let r=i.profileJson.complianceGroup??"",a=i.profileJson.isActive??!1,c=a?"activate":"write";if(await this.runWrite({action:c,profile:o,profileId:e,version:i.version,complianceGroup:r}),a){let l=this.profileFilePaths(r,o.locales);this.handleCache?.(l,i.version,!0),this.eventBus?.emit("cache:purge",{paths:l,version:i.version})}}}return i}async delete(e){let t=await this.profiles.get(e);if(await this.profiles.delete(e),this.localeCache?.invalidate(e),await this.audit.log({tenantId:this.tenantId,action:"profile.deleted",resourceType:"profile",resourceId:e,...t!=null?{oldData:t}:{}}),this.eventBus?.emit("profile.deleted",{id:e,previous:t}),this.profilesDir&&t){let n=t.profileJson.complianceGroup??"";if((t.profileJson.isActive??!1)&&n){let o=await this.getResolved(e).catch(()=>null),r=o?.locales??[];await this.runWrite({action:"deactivate",profile:o??{},profileId:e,version:t.version,complianceGroup:n});let a=this.profileFilePaths(n,r);this.handleCache?.(a,t.version,!0),this.eventBus?.emit("cache:purge",{paths:a,version:t.version})}}}async activate(e){let t=await this.profiles.get(e);if(!t)throw new Error(`Profile ${e} not found`);let n=t.profileJson,i=await this.profiles.update(e,{profileJson:{...t.profileJson,isActive:!0}});if(this.localeCache?.invalidate(e),this.profilesDir&&n.complianceGroup){let o=await this.getResolved(e);if(o){await this.runWrite({action:"activate",profile:o,profileId:e,version:i.version,complianceGroup:n.complianceGroup});let r=this.profileFilePaths(n.complianceGroup,o.locales);this.handleCache?.(r,i.version,!1),this.eventBus?.emit("cache:warm",{paths:r,version:i.version})}}return await this.audit.log({tenantId:this.tenantId,action:"profile.activated",resourceType:"profile",resourceId:e}),this.eventBus?.emit("profile.activated",i),i}async deactivate(e){let t=await this.profiles.get(e);if(!t)throw new Error(`Profile ${e} not found`);let n=t.profileJson,i=await this.profiles.update(e,{profileJson:{...t.profileJson,isActive:!1}});if(this.localeCache?.invalidate(e),this.profilesDir&&n.complianceGroup){let o=await this.getResolved(e),r=o?.locales??[];await this.runWrite({action:"deactivate",profile:o??{},profileId:e,version:t.version,complianceGroup:n.complianceGroup});let a=this.profileFilePaths(n.complianceGroup,r);this.handleCache?.(a,t.version,!0),this.eventBus?.emit("cache:purge",{paths:a,version:t.version})}return await this.audit.log({tenantId:this.tenantId,action:"profile.deactivated",resourceType:"profile",resourceId:e}),this.eventBus?.emit("profile.deactivated",i),i}async runWrite(e){if(!this.profilesDir)return;let t={action:e.action,profile:e.profile,storagePath:(0,te.join)(this.profilesDir,".."),tenantId:this.tenantId,profileId:e.profileId,version:e.version,complianceGroup:e.complianceGroup,...this.s3Config?.enabled?{s3Config:this.s3Config}:{}};await Qn(t)}async get(e,t){let n=await this.profiles.get(e);if(!n)return null;if(!t)return n;let i=xt(n.profileJson.translations??{},t,n.defaultLocale);return{...n,profileJson:{...n.profileJson,translations:{[t]:i}}}}async getResolved(e,t){let n=await this.profiles.get(e);if(!n)return null;let i=t??n.defaultLocale;if(this.localeCache){let d=this.localeCache.read(e,i);if(d)return d}let o=n.profileJson,r=o.cookies??[],a=o.translations??{};if(o.cookieTemplateId&&this.storage){let d=await this.storage.getCookieTemplate(o.cookieTemplateId);d&&(r=d.cookies)}if(o.uiTemplateId&&o.localeContents&&this.storage){let d=await this.storage.getUITemplate(o.uiTemplateId);d&&(a=wo(d,o.localeContents))}let c=o.localeContents?Object.keys(o.localeContents):Object.keys(a),l=xt(a,i,n.defaultLocale),u={id:n.id,version:n.version,defaultLocale:n.defaultLocale,currentLocale:i,locales:c,cookies:r.map(Ro),mainBanner:l.mainBanner,preferenceModal:l.preferenceModal,...l.gpcBanner!=null?{gpcBanner:l.gpcBanner}:{}};if(this.localeCache)try{this.localeCache.write(e,i,u)}catch{}return u}findActiveByComplianceGroup(e){return this.profiles.findActiveByComplianceGroup(this.tenantId,e)}list(){return this.profiles.list(this.tenantId)}listSummary(){return this.storage?this.storage.listProfilesSummary(this.tenantId):Promise.resolve([])}listVersions(e){if(!this.profilesDir)return[];let t=this.profileDir(e);if(!(0,J.existsSync)(t))return[];let n=[];try{let i=(0,J.readdirSync)(t,{withFileTypes:!0});for(let o of i){if(!o.isDirectory())continue;let r=parseInt(o.name,10);if(isNaN(r))continue;let a=(0,te.join)(t,o.name),c=(0,J.readdirSync)(a).filter(u=>u.endsWith(".json")&&u!=="default.json").map(u=>u.replace(".json","")),l;try{l=(0,J.statSync)(a).mtime.toISOString()}catch{l=new Date().toISOString()}n.push({version:r,createdAt:l,locales:c})}}catch{return[]}return n.sort((i,o)=>o.version-i.version)}getVersionFile(e,t,n){if(!this.profilesDir)return null;let i=(0,te.join)(this.profileDir(e),String(t),`${n}.json`);if(!(0,J.existsSync)(i)){let o=(0,te.join)(this.profileDir(e),String(t),"default.json");return(0,J.existsSync)(o)?(0,J.readFileSync)(o,"utf8"):null}return(0,J.readFileSync)(i,"utf8")}};var Xn={"Europe/Amsterdam":"NL","Europe/Andorra":"AD","Europe/Athens":"GR","Europe/Belgrade":"RS","Europe/Berlin":"DE","Europe/Bratislava":"SK","Europe/Brussels":"BE","Europe/Bucharest":"RO","Europe/Budapest":"HU","Europe/Busingen":"DE","Europe/Chisinau":"MD","Europe/Copenhagen":"DK","Europe/Dublin":"IE","Europe/Gibraltar":"GI","Europe/Guernsey":"GG","Europe/Helsinki":"FI","Europe/Isle_of_Man":"IM","Europe/Istanbul":"TR","Europe/Jersey":"JE","Europe/Kaliningrad":"RU","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Lisbon":"PT","Europe/Ljubljana":"SI","Europe/London":"GB","Europe/Luxembourg":"LU","Europe/Madrid":"ES","Europe/Malta":"MT","Europe/Mariehamn":"FI","Europe/Minsk":"BY","Europe/Monaco":"MC","Europe/Moscow":"RU","Europe/Nicosia":"CY","Europe/Oslo":"NO","Europe/Paris":"FR","Europe/Podgorica":"ME","Europe/Prague":"CZ","Europe/Riga":"LV","Europe/Rome":"IT","Europe/Samara":"RU","Europe/San_Marino":"SM","Europe/Sarajevo":"BA","Europe/Saratov":"RU","Europe/Simferopol":"UA","Europe/Skopje":"MK","Europe/Sofia":"BG","Europe/Stockholm":"SE","Europe/Tallinn":"EE","Europe/Tirane":"AL","Europe/Ulyanovsk":"RU","Europe/Uzhgorod":"UA","Europe/Vaduz":"LI","Europe/Vatican":"VA","Europe/Vienna":"AT","Europe/Vilnius":"LT","Europe/Volgograd":"RU","Europe/Warsaw":"PL","Europe/Zagreb":"HR","Europe/Zaporozhye":"UA","Europe/Zurich":"CH","Atlantic/Reykjavik":"IS","Atlantic/Faroe":"FO","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Anchorage":"US","America/Adak":"US","America/Honolulu":"US","America/Phoenix":"US","America/Detroit":"US","America/Indiana/Indianapolis":"US","America/Indiana/Knox":"US","America/Indiana/Marengo":"US","America/Indiana/Petersburg":"US","America/Indiana/Tell_City":"US","America/Indiana/Vevay":"US","America/Indiana/Vincennes":"US","America/Indiana/Winamac":"US","America/Kentucky/Louisville":"US","America/Kentucky/Monticello":"US","America/North_Dakota/Beulah":"US","America/North_Dakota/Center":"US","America/North_Dakota/New_Salem":"US","America/Boise":"US","America/Menominee":"US","America/Nome":"US","America/Sitka":"US","America/Yakutat":"US","America/Juneau":"US","America/Metlakatla":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Winnipeg":"CA","America/Halifax":"CA","America/St_Johns":"CA","America/Edmonton":"CA","America/Regina":"CA","America/Whitehorse":"CA","America/Yellowknife":"CA","America/Iqaluit":"CA","America/Moncton":"CA","America/Glace_Bay":"CA","America/Goose_Bay":"CA","America/Swift_Current":"CA","America/Dawson":"CA","America/Cambridge_Bay":"CA","America/Dawson_Creek":"CA","America/Fort_Nelson":"CA","America/Creston":"CA","America/Rankin_Inlet":"CA","America/Resolute":"CA","America/Pangnirtung":"CA","America/Nipigon":"CA","America/Mexico_City":"MX","America/Cancun":"MX","America/Monterrey":"MX","America/Merida":"MX","America/Chihuahua":"MX","America/Hermosillo":"MX","America/Mazatlan":"MX","America/Ojinaga":"MX","America/Bahia_Banderas":"MX","America/Matamoros":"MX","America/Tijuana":"MX","America/Sao_Paulo":"BR","America/Manaus":"BR","America/Belem":"BR","America/Fortaleza":"BR","America/Recife":"BR","America/Maceio":"BR","America/Bahia":"BR","America/Porto_Velho":"BR","America/Boa_Vista":"BR","America/Campo_Grande":"BR","America/Cuiaba":"BR","America/Santarem":"BR","America/Rio_Branco":"BR","America/Eirunepe":"BR","America/Noronha":"BR","America/Argentina/Buenos_Aires":"AR","America/Argentina/Cordoba":"AR","America/Argentina/Salta":"AR","America/Argentina/Jujuy":"AR","America/Argentina/Tucuman":"AR","America/Argentina/Catamarca":"AR","America/Argentina/La_Rioja":"AR","America/Argentina/San_Juan":"AR","America/Argentina/Mendoza":"AR","America/Argentina/San_Luis":"AR","America/Argentina/Rio_Gallegos":"AR","America/Argentina/Ushuaia":"AR","America/Bogota":"CO","America/Lima":"PE","America/Santiago":"CL","America/Caracas":"VE","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Guayaquil":"EC","America/Guyana":"GY","America/Paramaribo":"SR","America/Cayenne":"GF","America/Panama":"PA","America/Costa_Rica":"CR","America/Guatemala":"GT","America/El_Salvador":"SV","America/Tegucigalpa":"HN","America/Managua":"NI","America/Belize":"BZ","America/Havana":"CU","America/Jamaica":"JM","America/Nassau":"BS","America/Port_of_Spain":"TT","America/Santo_Domingo":"DO","America/Port-au-Prince":"HT","America/Barbados":"BB","America/Martinique":"MQ","America/Guadeloupe":"GP","America/Puerto_Rico":"PR","America/St_Kitts":"KN","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Colombo":"LK","Asia/Kathmandu":"NP","Asia/Kabul":"AF","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Shanghai":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Ulaanbaatar":"MN","Asia/Choibalsan":"MN","Asia/Hovd":"MN","Asia/Singapore":"SG","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Kuala_Lumpur":"MY","Asia/Manila":"PH","Asia/Ho_Chi_Minh":"VN","Asia/Saigon":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Rangoon":"MM","Asia/Yangon":"MM","Asia/Pontianak":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Kuching":"MY","Asia/Brunei":"BN","Asia/Dili":"TL","Asia/Tashkent":"UZ","Asia/Almaty":"KZ","Asia/Qyzylorda":"KZ","Asia/Aqtau":"KZ","Asia/Aqtobe":"KZ","Asia/Atyrau":"KZ","Asia/Oral":"KZ","Asia/Ashgabat":"TM","Asia/Dushanbe":"TJ","Asia/Bishkek":"KG","Asia/Yekaterinburg":"RU","Asia/Tehran":"IR","Asia/Baghdad":"IQ","Asia/Riyadh":"SA","Asia/Dubai":"AE","Asia/Kuwait":"KW","Asia/Qatar":"QA","Asia/Bahrain":"BH","Asia/Muscat":"OM","Asia/Beirut":"LB","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Amman":"JO","Asia/Damascus":"SY","Asia/Nicosia":"CY","Asia/Famagusta":"CY","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Tbilisi":"GE","Asia/Samarkand":"UZ","Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Lagos":"NG","Africa/Nairobi":"KE","Africa/Johannesburg":"ZA","Africa/Addis_Ababa":"ET","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Tripoli":"LY","Africa/Khartoum":"SD","Africa/Accra":"GH","Africa/Dar_es_Salaam":"TZ","Africa/Abidjan":"CI","Africa/Bamako":"ML","Africa/Banjul":"GM","Africa/Conakry":"GN","Africa/Dakar":"SN","Africa/Freetown":"SL","Africa/Lome":"TG","Africa/Monrovia":"LR","Africa/Nouakchott":"MR","Africa/Ouagadougou":"BF","Africa/Sao_Tome":"ST","Africa/Bissau":"GW","Africa/Bangui":"CF","Africa/Brazzaville":"CG","Africa/Douala":"CM","Africa/Kinshasa":"CD","Africa/Libreville":"GA","Africa/Luanda":"AO","Africa/Malabo":"GQ","Africa/Ndjamena":"TD","Africa/Niamey":"NE","Africa/Porto-Novo":"BJ","Africa/Blantyre":"MW","Africa/Bujumbura":"BI","Africa/Gaborone":"BW","Africa/Harare":"ZW","Africa/Kampala":"UG","Africa/Kigali":"RW","Africa/Lubumbashi":"CD","Africa/Lusaka":"ZM","Africa/Maputo":"MZ","Africa/Maseru":"LS","Africa/Mbabane":"SZ","Africa/Mogadishu":"SO","Africa/Windhoek":"NA","Africa/Asmara":"ER","Africa/Djibouti":"DJ","Africa/El_Aaiun":"EH","Africa/Juba":"SS","Africa/Ceuta":"ES","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Darwin":"AU","Australia/Hobart":"AU","Australia/Canberra":"AU","Australia/Broken_Hill":"AU","Australia/Lord_Howe":"AU","Australia/Lindeman":"AU","Australia/Eucla":"AU","Pacific/Auckland":"NZ","Pacific/Chatham":"NZ","Pacific/Fiji":"FJ","Pacific/Port_Moresby":"PG","Pacific/Bougainville":"PG","Pacific/Guam":"GU","Pacific/Saipan":"MP","Pacific/Pago_Pago":"AS","Pacific/Apia":"WS","Pacific/Tongatapu":"TO","Pacific/Fakaofo":"TK","Pacific/Niue":"NU","Pacific/Rarotonga":"CK","Pacific/Tahiti":"PF","Pacific/Marquesas":"PF","Pacific/Gambier":"PF","Pacific/Honolulu":"US","Pacific/Johnston":"US","Pacific/Midway":"UM","Pacific/Wake":"UM","Pacific/Tarawa":"KI","Pacific/Enderbury":"KI","Pacific/Kiritimati":"KI","Pacific/Efate":"VU","Pacific/Guadalcanal":"SB","Pacific/Noumea":"NC","Pacific/Nauru":"NR","Pacific/Palau":"PW","Pacific/Chuuk":"FM","Pacific/Pohnpei":"FM","Pacific/Kosrae":"FM","Pacific/Majuro":"MH","Pacific/Kwajalein":"MH","Pacific/Funafuti":"TV","Pacific/Wallis":"WF","Asia/Novosibirsk":"RU","Asia/Omsk":"RU","Asia/Krasnoyarsk":"RU","Asia/Irkutsk":"RU","Asia/Chita":"RU","Asia/Yakutsk":"RU","Asia/Khandyga":"RU","Asia/Vladivostok":"RU","Asia/Ust-Nera":"RU","Asia/Magadan":"RU","Asia/Sakhalin":"RU","Asia/Srednekolymsk":"RU","Asia/Kamchatka":"RU","Asia/Anadyr":"RU"};var So={ar:"SA",cs:"CZ",da:"DK",de:"DE",el:"GR",fi:"FI",fr:"FR",he:"IL",hi:"IN",hu:"HU",id:"ID",it:"IT",ja:"JP",ko:"KR",nl:"NL",no:"NO",pl:"PL",pt:"BR",ro:"RO",ru:"RU",sv:"SE",th:"TH",tr:"TR",uk:"UA",vi:"VN",zh:"CN"},mt=class{constructor(e,t){this.map=t;this.provider=e??"default"}map;provider;async resolve(e){let t="",n,i,o=null;if(typeof this.provider=="function"){let a=await this.provider(e);t=a.country??"",n=a.region??void 0,o=a.locale}else switch(this.provider){case"default":case"timezone":({country:t}=Ao(e.timezone)),t||({country:t,region:n}=Zn(e.language));break;case"language":({country:t,region:n}=Zn(e.language));break;case"geoip":({country:t,region:n}=await To(e.ip));break;case"hosted-geoip-lite":({country:t,region:n}=await vo(e.ip));break;case"maxmind":({country:t,region:n}=await Co(e.ip));break}let r={country:t,complianceGroup:this.resolveGroup(t,n)};return n!==void 0&&(r.region=n),i!==void 0&&(r.regulation=i),o!==null&&(r.locale=o),r}resolveGroup(e,t){if(!e)return"";let i=this.map.countries[e];return i?t!==void 0?i.overriddenRegions?.[t]?.complianceGroup??i.complianceGroup:i.default:""}};function Zn(s){let t=(s.split(",")[0]?.trim().split(";")[0]?.trim()??"").split("-");if(t.length>=2){let i=(t[t.length-1]??"").toUpperCase();if(/^[A-Z]{2}$/.test(i))return{country:i}}return{country:So[(t[0]??"").toLowerCase()]??""}}function Ao(s){return{country:Xn[s]??""}}async function To(s){if(!s)return{country:""};try{let t=(await import("geoip-lite")).lookup(s),n={country:t?.country??""},i=t?.region;return i&&(n.region=i),n}catch{return console.warn("[Consenti] geoip-lite not installed \u2014 country detection skipped. Run: npm install geoip-lite"),{country:""}}}async function Co(s){if(!s)return{country:""};try{let e=await import("maxmind"),t=process.env.MAXMIND_DB_PATH??"./GeoLite2-City.mmdb",i=(await e.open(t)).get(s),o=i?.country?.iso_code??"",r=i?.subdivisions?.[0]?.iso_code,a={country:o};return r&&(a.region=r),a}catch{return console.warn("[Consenti] maxmind not available \u2014 country detection skipped. See HOW_TO_MAXMIND.md"),{country:""}}}async function vo(s){return s?new Promise(e=>{import("https").then(({default:t})=>{let n=`https://ipinfo.io/${encodeURIComponent(s)}/json`,i=t.get(n,{timeout:3e3},o=>{let r=[];o.on("data",a=>r.push(a)),o.on("end",()=>{try{let a=JSON.parse(Buffer.concat(r).toString()),c={country:a.country??""};a.region&&(c.region=a.region),e(c)}catch{e({country:""})}})});i.on("error",()=>e({country:""})),i.on("timeout",()=>{i.destroy(),e({country:""})})}).catch(()=>e({country:""}))}):{country:""}}var se=require("node:fs"),jt=require("node:path");var N=require("node:fs"),ei=require("node:path");function ti(s,e,t){let n=s+".bak",i=s+".tmp";(0,N.mkdirSync)((0,ei.dirname)(s),{recursive:!0});let o=(0,N.existsSync)(s);o&&(0,N.copyFileSync)(s,n);try{(0,N.writeFileSync)(i,JSON.stringify(e,null,2),"utf8");let r=JSON.parse((0,N.readFileSync)(i,"utf8"));if(!t(r))throw new Error("Schema validation failed for "+s);if((0,N.renameSync)(i,s),o)try{(0,N.unlinkSync)(n)}catch{}}catch(r){if(o)try{(0,N.copyFileSync)(n,s),(0,N.unlinkSync)(n)}catch{}try{(0,N.unlinkSync)(i)}catch{}throw r}}function ni(s){return typeof s=="object"&&s!==null&&typeof s.id=="string"&&typeof s.version=="number"}var gt=class{constructor(e){this.dir=e}dir;read(e,t){let n=this.path(e,t);if(!(0,se.existsSync)(n))return null;try{let i=JSON.parse((0,se.readFileSync)(n,"utf8"));return ni(i)?i:null}catch{return null}}write(e,t,n){ti(this.path(e,t),n,ni)}rebuild(e,t){for(let[n,i]of t)try{this.write(e,n,i)}catch(o){console.warn(`[Consenti] locale cache rebuild failed for ${e}/${n}:`,o)}}invalidate(e){try{let t=`${e}_`;for(let n of(0,se.readdirSync)(this.dir))if(n.startsWith(t)&&n.endsWith(".json"))try{(0,se.unlinkSync)((0,jt.join)(this.dir,n))}catch{}}catch{}}path(e,t){return(0,jt.join)(this.dir,`${e}_${t}.json`)}};function ii(s,e){let t=[];for(let[n,i]of Object.entries(s.consentJson)){let o=(e.profileJson.cookies??[]).find(r=>r.id===n);o&&(o.mandatory&&i!=="granted"&&t.push(`Cookie "${n}" is mandatory and cannot be "${i}"`),i==="objected"&&o.type!=="legitimate_interest"&&t.push(`Cookie "${n}" is type "${o.type??"consent"}" \u2014 'objected' is only valid for 'legitimate_interest'`))}return{valid:t.length===0,errors:t}}function $t(s,e,t,n){let i={};for(let o of s??[]){let r=o.id;if(o.mandatory){i[r]="granted";continue}if(n==="cpra"){if(o.cpraCategory==="sensitive"){let c=e[r];i[r]=c==="granted"||c==="denied"||c==="objected"?c:"denied";continue}if(t&&(o.cpraCategory==="sale"||o.cpraCategory==="sharing")){i[r]="denied";continue}}if(t&&o.listenGpc&&n!=="dpdpa"){i[r]="denied";continue}let a=e[r];a==="granted"||a==="denied"||a==="objected"?i[r]=a:i[r]="denied"}return i}function si(s,e){let t=[];return s.profileVersion<e.version&&t.push("profile_version_mismatch"),Io(s,e)&&t.push("consent_expired"),{valid:t.length===0,reasons:t,currentProfileVersion:e.version,consentProfileVersion:s.profileVersion}}function oi(s,e){let t=new Set,n=new Set;for(let i of s)if(e[i.id]==="granted"){i.tcfVendorId&&t.add(i.tcfVendorId);for(let o of i.tcfPurposes??[])n.add(o)}return{vendorConsents:[...t].sort((i,o)=>i-o),purposeConsents:[...n].sort((i,o)=>i-o)}}function Io(s,e){let t=e.profileJson.cookies??[],n=new Date(s.createdAt).getTime(),i=Date.now();for(let o of t){if(!o.expiry)continue;let r=n+o.expiry*24*60*60*1e3;if(i>r)return!0}return!1}function ri(s){let e={v:2,ts:Math.floor(Date.now()/100),cmpId:s.cmpId,cmpV:s.cmpVersion,cs:s.consentScreen,lang:s.consentLanguage.toUpperCase().slice(0,2),vlV:s.vendorListVersion,pc:s.purposeConsents,vc:s.vendorConsents};return Buffer.from(JSON.stringify(e)).toString("base64url")}var ft=class{constructor(e,t,n,i,o="default",r,a,c,l){this.consents=e;this.visitors=t;this.profiles=n;this.audit=i;this.tenantId=o;this.compliance=r;this.pluginEngine=a;this.eventBus=c;this.tcfConfig=l}consents;visitors;profiles;audit;tenantId;compliance;pluginEngine;eventBus;tcfConfig;async create(e){let t=await this.profiles.get(e.profileId);if(!t)throw new Error(`Profile ${e.profileId} not found`);let n=t.profileJson.regulation,i=t.profileJson.cookies??[],o=e.consentJson;if(e.gpcDetected&&this.compliance?.gpc!==!1&&n!=="dpdpa"){o={...o};for(let p of i)n==="cpra"?(p.cpraCategory==="sale"||p.cpraCategory==="sharing")&&(o[p.id]="denied"):p.listenGpc&&(o[p.id]="denied")}let r=ii({...e,consentJson:o},t);if(!r.valid)throw new Error(r.errors.join("; "));let a=$t(i,o,e.gpcDetected,n),c;if(this.tcfConfig?.enabled&&i.some(p=>p.tcfVendorId)){let p=await ae(),{vendorConsents:E,purposeConsents:S}=oi(i,a);c=ri({cmpId:this.tcfConfig.cmpId,cmpVersion:this.tcfConfig.cmpVersion,consentScreen:1,consentLanguage:e.locale?.slice(0,2)??"en",vendorListVersion:p?.vendorListVersion??0,purposeConsents:S,vendorConsents:E})}let l={...e,tenantId:this.tenantId,consentJson:a,profileVersion:t.version,...c?{tcfString:c}:{}};this.pluginEngine&&(l=await this.pluginEngine.runBeforeConsentSave(l));let u=await this.consents.get(e.visitorId),d;if(u){let p=await(this.pluginEngine?this.pluginEngine.runBeforeConsentUpdate({consentJson:a,locale:e.locale,gpcDetected:e.gpcDetected}):Promise.resolve({consentJson:a,locale:e.locale,gpcDetected:e.gpcDetected}));d=await this.consents.update(e.visitorId,p)}else d=await this.consents.create(l);return await this.audit.log({tenantId:this.tenantId,action:u?"consent.updated":"consent.created",resourceType:"consent",resourceId:d.id,...u!=null?{oldData:u}:{},newData:d}),u?(this.eventBus?.emit("consent.updated",{previous:u,current:d}),await this.pluginEngine?.runAfterConsentUpdate(d)):(this.eventBus?.emit("consent.created",d),await this.pluginEngine?.runAfterConsentSave(d)),d}async update(e,t){let n=await this.consents.get(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let i=await this.profiles.get(n.profileId);if(!i)throw new Error(`Profile ${n.profileId} not found`);let o=i.profileJson.regulation,r=i.profileJson.cookies??[],a=t.gpcDetected??n.gpcDetected,c=t.consentJson;if(a&&this.compliance?.gpc!==!1&&o!=="dpdpa"){c={...c};for(let d of r)o==="cpra"?(d.cpraCategory==="sale"||d.cpraCategory==="sharing")&&(c[d.id]="denied"):d.listenGpc&&(c[d.id]="denied")}let l=$t(r,c,a,o),u=await this.consents.update(e,{...t,consentJson:l});return await this.audit.log({tenantId:this.tenantId,action:"consent.updated",resourceType:"consent",resourceId:u.id,oldData:n,newData:u}),u}get(e){return this.consents.get(e)}async verify(e){let t=await this.consents.get(e);if(!t)return{valid:!1,reasons:["profile_version_mismatch"]};let n=await this.profiles.get(t.profileId);return n?si(t,n):{valid:!1,reasons:["profile_version_mismatch"]}}async erase(e){let t=await this.consents.get(e);await this.consents.delete(e),await this.visitors.delete(e),await this.audit.log({tenantId:this.tenantId,action:"consent.erased",resourceType:"consent",resourceId:e,...t!=null?{oldData:t}:{}}),this.eventBus?.emit("consent.erased",{visitorId:e})}};var yt=class{constructor(e,t="default",n){this.visitors=e;this.tenantId=t;this.eventBus=n}visitors;tenantId;eventBus;async upsert(e){if(await this.visitors.get(e.visitorId))return this.visitors.update(e.visitorId,{...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{}});let n={tenantId:this.tenantId,visitorId:e.visitorId,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip?{ipHash:mn(e.ip)}:{},...e.userAgent?{userAgentHash:gn(e.userAgent)}:{}},i=await this.visitors.create(n);return this.eventBus?.emit("visitor.created",i),i}};var ht=class{constructor(e,t,n="default"){this.users=e;this.audit=t;this.tenantId=n}users;audit;tenantId;safe(e){let{passwordHash:t,...n}=e;return n}async create(e,t){let n=await this.users.create({tenantId:this.tenantId,name:e.name,email:e.email,passwordHash:ve(e.password),...e.allowedTenants?{allowedTenants:e.allowedTenants}:{}});return e.roleId&&await this.users.assignRole(n.id,e.roleId),await this.audit.log({tenantId:this.tenantId,...t!=null?{userId:t}:{},action:"user.created",resourceType:"user",resourceId:n.id,newData:this.safe(n)}),this.safe(n)}async update(e,t,n){let i=await this.users.getById(e);if(!i)throw new Error(`User ${e} not found`);let o={};t.name!=null&&(o.name=t.name),t.email!=null&&(o.email=t.email),t.isActive!=null&&(o.isActive=t.isActive),t.password&&(o.passwordHash=ve(t.password)),t.allowedTenants!=null&&(o.allowedTenants=t.allowedTenants);let r=await this.users.update(e,o);return await this.audit.log({tenantId:this.tenantId,...n!=null?{userId:n}:{},action:"user.updated",resourceType:"user",resourceId:e,oldData:this.safe(i),newData:this.safe(r)}),this.safe(r)}async delete(e,t){let n=await this.users.getById(e);await this.users.delete(e),await this.audit.log({tenantId:this.tenantId,...t!=null?{userId:t}:{},action:"user.deleted",resourceType:"user",resourceId:e,...n!=null?{oldData:this.safe(n)}:{}})}async get(e){let t=await this.users.getById(e);return t?this.safe(t):null}async list(){return(await this.users.list(this.tenantId)).map(t=>this.safe(t))}getRoles(e,t){return this.users.getRoles(e,t)}assignRole(e,t,n){return this.users.assignRole(e,t,n)}revokeRole(e,t,n){return this.users.revokeRole(e,t,n)}};var ai=15*6e4,Po=5,_t=class{constructor(e,t){this.storage=e;this.secret=t;setInterval(()=>{let n=Date.now();for(let[i,o]of this.loginAttempts)n>=o.resetAt&&this.loginAttempts.delete(i)},ai).unref()}storage;secret;loginAttempts=new Map;async bootstrap(e,t){if(await this.storage.countUsers("default")>0)return null;if(t.length<12)throw new Error("[Consenti] bootstrap: admin password must be at least 12 characters");t.length<16&&console.warn("[Consenti] bootstrap: admin password is shorter than 16 characters \u2014 consider using a longer password");let i=ve(t),o=await this.storage.createUser({tenantId:"default",name:"Admin",email:e,passwordHash:i});return await this.storage.assignRole(o.id,"role_super_admin"),o}async login(e,t){let n=Date.now(),i=this.loginAttempts.get(e);if(i&&n<i.resetAt&&i.count>=Po)return null;let o=await this.storage.getUserByEmail(e);if(!o||!o.isActive||!yn(t,o.passwordHash)){let l=this.loginAttempts.get(e);return!l||n>=l.resetAt?this.loginAttempts.set(e,{count:1,resetAt:n+ai}):l.count+=1,null}this.loginAttempts.delete(e);let r=await this.storage.getUserRoles(o.id),a=await Promise.all(r.map(l=>this.storage.getPermissionsForRole(l.id))),c=[...new Set(a.flat().map(l=>l.name))];return Lt({sub:o.id,email:o.email,roles:r.map(l=>l.name),permissions:c,allowedTenants:o.allowedTenants??[]},this.secret)}signToken(e){return Lt(e,this.secret)}verify(e){return Je(e,this.secret)}async getUser(e){let t=this.verify(e);if(!t)return null;let n=t.sub;return typeof n!="string"?null:this.storage.getUserById(n)}};var Me=class extends Error{constructor(){super("Payload Too Large")}};function bo(s,e){let t=s.socket?.remoteAddress??"";if(!e?.length||!e.includes(t))return t;let n=s.headers["x-forwarded-for"];return typeof n=="string"?n.split(",")[0]?.trim()??t:Array.isArray(n)?n[0]?.trim()??t:t}function y(s,e){return new Response(JSON.stringify(e),{status:s,headers:{"Content-Type":"application/json"}})}async function v(s){if(!(s.headers.get("content-type")??"").includes("application/json"))return null;try{return await s.json()}catch{return null}}function k(s,e){return s.searchParams.get(e)??void 0}function Y(s,e,t){let n=s.searchParams.get(e);if(!n)return t;let i=parseInt(n,10);return isNaN(i)?t:i}async function ci(s,e=1048576,t){let i=s.headers["x-forwarded-proto"]==="https"?"https":"http",o=s.headers.host??"localhost",r=new URL(s.url??"/",`${i}://${o}`),a=new Headers;for(let[u,d]of Object.entries(s.headers))if(d)if(Array.isArray(d))for(let p of d)a.append(u,p);else a.set(u,d);a.set("x-real-ip",bo(s,t));let c=null,l=(s.method??"GET").toUpperCase();if(l!=="GET"&&l!=="HEAD"){let u=[],d=0;for await(let p of s){if(d+=p.length,d>e)throw new Me;u.push(p)}u.length>0&&(c=Buffer.concat(u))}return new Request(r.toString(),{method:l,headers:a,body:c})}async function li(s,e){e.statusCode=s.status;let t=typeof s.headers.getSetCookie=="function"?s.headers.getSetCookie():s.headers.get("set-cookie")?[s.headers.get("set-cookie")]:[];s.headers.forEach((n,i)=>{i.toLowerCase()!=="set-cookie"&&e.setHeader(i,n)});for(let n of t)e.appendHeader("set-cookie",n);if(s.body){let n=s.body.getReader();try{for(;;){let{done:i,value:o}=await n.read();if(i)break;e.write(Buffer.from(o))}}finally{n.releaseLock()}e.end()}else e.end()}function m(s,e,t){let n={error:e};return t!=null&&process.env.NODE_ENV!=="production"&&(n.details=t),new Response(JSON.stringify(n),{status:s,headers:{"Content-Type":"application/json"}})}async function g(s){try{return await s()}catch(e){let t=e instanceof Error?e.message:"Internal Server Error";return m(500,"Internal Server Error",process.env.NODE_ENV!=="production"?t:void 0)}}var ne=require("node:fs"),le=require("node:path"),Oo="public, max-age=3600, stale-while-revalidate=60",di={"Content-Type":"application/json","Cache-Control":Oo};function Bt(s){let e=(0,ne.readFileSync)(s,"utf8");return new Response(e,{headers:di})}function Do(s,e,t){return new Response(null,{status:303,headers:{Location:`${s}/profiles/${e}/${t}/default`}})}function ui(s,e,t,n=""){return{"GET /profiles/:tenantId/:complianceGroupOrProfileId/:locale":async(i,o)=>g(async()=>{let{tenantId:r,complianceGroupOrProfileId:a,locale:c}=o;if(!r||!a||!c)return m(400,"Missing path parameters");if(t){let u=(0,le.join)(t,r,a,`${c}.json`);if((0,ne.existsSync)(u))return Bt(u);let d=(0,le.join)(t,r,a,"default.json");if((0,ne.existsSync)(d))return Do(n,r,a)}let l=await s.getResolved(a,c);return l?y(200,l):m(404,"Profile not found")}),"GET /profiles/:tenantId/:profileId/:version/:locale":async(i,o)=>g(async()=>{let{tenantId:r,profileId:a,version:c,locale:l}=o;if(!r||!a||!c||!l)return m(400,"Missing path parameters");let u=parseInt(c,10);if(isNaN(u)||u<1)return m(400,"Invalid version");if(t){let p=(0,le.join)(t,r,a,c,`${l}.json`);if((0,ne.existsSync)(p))return Bt(p);let E=(0,le.join)(t,r,a,c,"default.json");if((0,ne.existsSync)(E))return Bt(E)}let d=s.getVersionFile(a,u,l);return d?new Response(d,{headers:di}):m(404,"Version not found")}),"GET /resolve-profile":async(i,o)=>g(async()=>{if(!e)return m(501,"Geo compliance routing not configured");let r=new URL(i.url),a=i.headers.get("x-forwarded-for")?.split(",")[0]?.trim()??i.headers.get("x-real-ip")??"",c=r.searchParams.get("tz")??"",l=r.searchParams.get("lang")??i.headers.get("accept-language")??"",u=r.searchParams.get("locale")??"",d=await e.resolve({ip:a,language:l,timezone:c});if(!d.complianceGroup)return m(404,"Could not resolve compliance group for this location");let p=await s.findActiveByComplianceGroup(d.complianceGroup);if(!p)return m(404,`No active profile found for compliance group: ${d.complianceGroup}`);let E=p.profileJson,S=E.localeContents?Object.keys(E.localeContents):[],f=p.defaultLocale;u&&S.includes(u)?f=u:d.locale&&S.includes(d.locale)&&(f=d.locale);let _=d.complianceGroup,h=p.tenantId,A,T=t?(0,le.join)(t,h,_,`${f}.json`):"";if(t&&!(0,ne.existsSync)(T)){let O=(0,le.join)(t,h,_,"default.json");(0,ne.existsSync)(O)&&(f=p.defaultLocale,A="locale_not_found",T=O)}let I=`${n}/profiles/${h}/${_}/${f}`;return y(200,{path:I,resolvedLocale:f,resolvedComplianceGroup:_,profileId:p.id,version:p.version,...A?{warning:A}:{}})}),"GET /profiles/:id":async(i,o)=>g(async()=>{let r=o.id;if(!r)return m(400,"Missing profile id");let a=await s.getResolved(r);return a?y(200,a):m(404,"Profile not found")}),"GET /profiles/:id/:locale":async(i,o)=>g(async()=>{let{id:r,locale:a}=o;if(!r)return m(400,"Missing profile id");let c=await s.getResolved(r,a);return c?y(200,c):m(404,"Profile not found")}),"GET /profiles/auto/:locale":async(i,o)=>g(async()=>{if(!e)return m(501,"Geo compliance routing not configured");let r=o.locale??"en",a=new URL(i.url),c=i.headers.get("x-forwarded-for")?.split(",")[0]?.trim()??i.headers.get("x-real-ip")??"",l=a.searchParams.get("tz")??"",u=i.headers.get("accept-language")??a.searchParams.get("lang")??"",d=await e.resolve({ip:c,language:u,timezone:l});if(!d.complianceGroup)return m(404,"Could not resolve compliance group for this location");let p=await s.findActiveByComplianceGroup(d.complianceGroup);if(!p)return m(404,`No active profile found for compliance group: ${d.complianceGroup}`);let E=await s.getResolved(p.id,r);return E?y(200,{...E,resolvedComplianceGroup:d.complianceGroup}):m(404,"Profile not found")})}}function Lo(s,e){let t=Object.entries(s).map(([n,i])=>`${n}:${i}`).join("|");return`ConsentTimestamp:${e}::${t}`}function Vt(s){let e=`consenti_${s.visitorId}_${s.profileId}`,t=Lo(s.consentJson,s.createdAt),n=process.env.NODE_ENV==="production"?"; Secure":"";return`${e}=${t}; SameSite=Lax${n}; Path=/; Max-Age=31536000`}function pi(s,e){let t=`consenti_${s}_${e}`,n=process.env.NODE_ENV==="production"?"; Secure":"";return`${t}=; SameSite=Lax${n}; Path=/; Max-Age=0`}function mi(s,e){let t;try{t=new URL(s).hostname}catch{return!1}return e.some(n=>{if(n.startsWith("*.")){let i=n.slice(1);return t===n.slice(2)||t.endsWith(i)}return t===n})}function gi(s,e){let t=s??"*";return e&&e.length>0&&s&&(t=mi(s,e)?s:"null"),{"Access-Control-Allow-Origin":t,"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"}}function fi(s){if(s.method==="OPTIONS"){let e=s.headers.get("origin");return new Response(null,{status:204,headers:gi(e)})}return null}function Et(s,e){let t=e.headers.get("origin"),n=gi(t),i=new Headers(s.headers);for(let[o,r]of Object.entries(n))i.set(o,r);return new Response(s.body,{status:s.status,statusText:s.statusText,headers:i})}function yi(s,e){if(e.length===0)return!0;let t=s.headers.get("origin");return t?mi(t,e):!0}var Uo=["default-src 'self'","script-src 'self' https://unpkg.com","style-src 'self' https://unpkg.com 'unsafe-inline'","img-src 'self' data:","font-src 'self'","connect-src 'self'","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");function Wt(s){let e=new Headers(s.headers);return e.set("X-Content-Type-Options","nosniff"),e.set("X-Frame-Options","DENY"),e.set("Referrer-Policy","no-referrer"),e.set("Permissions-Policy","interest-cohort=()"),e.set("Content-Security-Policy",Uo),e.set("Strict-Transport-Security","max-age=63072000; includeSubDomains; preload"),new Response(s.body,{status:s.status,statusText:s.statusText,headers:e})}var ko=new Set(["granted","denied","objected"]);function hi(s){let e=Object.entries(s);for(let[t,n]of e){if(!t)return{valid:!1,error:"consentJson keys must be non-empty strings"};if(!ko.has(n))return{valid:!1,error:`consentJson value "${String(n)}" is invalid; must be granted, denied, or objected`}}return{valid:!0}}function _i(s){if(!s||typeof s!="object")return{valid:!1,error:"Request body must be a JSON object"};let e=s;return typeof e.profileId!="string"||!e.profileId?{valid:!1,error:"profileId is required"}:!e.consentJson||typeof e.consentJson!="object"||Array.isArray(e.consentJson)?{valid:!1,error:"consentJson must be an object"}:hi(e.consentJson)}function Ei(s){if(!s||typeof s!="object")return{valid:!1,error:"Request body must be a JSON object"};let e=s;return!e.consentJson||typeof e.consentJson!="object"||Array.isArray(e.consentJson)?{valid:!1,error:"consentJson must be an object"}:hi(e.consentJson)}function wi(s,e,t){return{tenantId:t,visitorId:e,profileId:s.profileId,profileVersion:typeof s.profileVersion=="number"?s.profileVersion:1,locale:typeof s.locale=="string"?s.locale:"en",consentJson:s.consentJson,gpcDetected:!!s.gpcDetected,source:s.source??"banner"}}function Ri(s){let e={consentJson:s.consentJson};return typeof s.locale=="string"&&(e.locale=s.locale),s.gpcDetected!=null&&(e.gpcDetected=!!s.gpcDetected),e}function wt(s,e){let t=s.headers.get("cookie")??"",n=`consenti_${e}_`;return t.split(";").some(o=>{let r=o.trim();return r.startsWith(n)?r.slice(r.indexOf("=")+1).startsWith("ConsentTimestamp:"):!1})?null:m(403,"Forbidden")}function Si(s,e,t,n=async()=>"default"){return{"POST /consent":async(i,o)=>g(async()=>{let r=await v(i),a=_i(r);if(!a.valid)return m(400,a.error??"Invalid request");let c=r,l=typeof c.profileId=="string"?c.profileId:null;if(!l)return m(400,"profileId is required");let u=await t.get(l);if(!u)return m(404,"Profile not found");let p=u.profileJson.allowedOrigins??[];if(!yi(i,p))return m(403,"Origin not allowed for this profile");let E=typeof c.visitorId=="string"?c.visitorId:(0,w.randomUUID)(),S=i.headers.get("x-real-ip")??"",f=i.headers.get("user-agent")??"",_=await n(i);await e.upsert({visitorId:E,ip:S,userAgent:f});let h=wi(c,E,_),A=await s.create(h),T=Vt(A);return new Response(JSON.stringify(A),{status:201,headers:{"Content-Type":"application/json","Set-Cookie":T}})}),"PUT /consent/:visitorId":async(i,o)=>g(async()=>{let r=o.visitorId;if(!r)return m(400,"Missing visitorId");let a=wt(i,r);if(a)return a;let c=await v(i),l=Ei(c);if(!l.valid)return m(400,l.error??"Invalid request");let u=Ri(c),d=await s.update(r,u),p=Vt(d);return new Response(JSON.stringify(d),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":p}})}),"GET /consent/:visitorId":async(i,o)=>g(async()=>{let r=o.visitorId;if(!r)return m(400,"Missing visitorId");let a=wt(i,r);if(a)return a;let c=await s.get(r);return c?new Response(JSON.stringify(c),{status:200,headers:{"Content-Type":"application/json"}}):m(404,"Consent not found")}),"GET /consent/:visitorId/verify":async(i,o)=>g(async()=>{let r=o.visitorId;if(!r)return m(400,"Missing visitorId");let a=wt(i,r);if(a)return a;let c=await s.verify(r);return new Response(JSON.stringify(c),{status:200,headers:{"Content-Type":"application/json"}})}),"DELETE /consent/:visitorId":async(i,o)=>g(async()=>{let r=o.visitorId;if(!r)return m(400,"Missing visitorId");let a=wt(i,r);if(a)return a;let c=await s.get(r);await s.erase(r);let l={"Content-Type":"application/json"};return c&&(l["Set-Cookie"]=pi(r,c.profileId)),new Response(JSON.stringify({success:!0}),{status:200,headers:l})})}}var Kt=require("node:crypto");async function C(s,e,t,n){let i=s.headers.get("authorization"),o=i?.startsWith("Bearer ")?i.slice(7):null;if(!o)return null;if(t.mode==="local"||t.mode==="jwt"){let r=Je(o,n);if(!r)return null;let a=r.sub,c=r.email,l=r.roles,u=r.permissions,d=r.allowedTenants;return typeof a!="string"||typeof c!="string"?null:{sub:a,email:c,roles:Array.isArray(l)?l:[],permissions:Array.isArray(u)?u:[],allowedTenants:Array.isArray(d)?d:[]}}if(t.mode==="custom"&&t.validateUser){let r=await t.validateUser(s);if(!r)return null;let a=await e.getUserRoles(r.id),c=await Promise.all(a.map(u=>e.getPermissionsForRole(u.id))),l=[...new Set(c.flat().map(u=>u.name))];return{sub:r.id,email:r.email,roles:a.map(u=>u.name),permissions:l,allowedTenants:[]}}return null}function P(s,e){return s?e&&!s.permissions.includes(e)?m(403,"Forbidden"):null:m(401,"Unauthorized")}var Rt=require("node:crypto");function Ai(s){return s.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ti(s){return Buffer.from(s.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8")}function Ci(){let s=Ai((0,Rt.randomBytes)(32)),e=Ai((0,Rt.createHash)("sha256").update(s).digest());return{verifier:s,challenge:e}}async function Jt(s){let e=await fetch(`${s}/.well-known/openid-configuration`,{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`OIDC discovery failed for ${s}: ${e.status}`);return e.json()}function vi(s,e,t,n,i){let o=new URLSearchParams({response_type:"code",client_id:s.clientId,redirect_uri:s.redirectUri,scope:"openid email profile",state:t,nonce:n,code_challenge:i,code_challenge_method:"S256"});return`${e}?${o.toString()}`}async function Ii(s,e,t,n){let i=new URLSearchParams({grant_type:"authorization_code",client_id:s.clientId,client_secret:s.clientSecret,redirect_uri:s.redirectUri,code:t,code_verifier:n}),o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString(),signal:AbortSignal.timeout(1e4)});if(!o.ok){let r=await o.text();throw new Error(`OIDC token exchange failed: ${r}`)}return o.json()}async function Pi(s,e){let t=s.split(".");if(t.length!==3)throw new Error("Invalid ID token format");let n=JSON.parse(Ti(t[0])),i=n.alg??"RS256",o=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error(`Failed to fetch JWKS: ${o.status}`);let r=await o.json(),a=n.kid?r.keys.find(h=>h.kid===n.kid):r.keys.find(h=>h.use==="sig")??r.keys[0];if(!a)throw new Error("No matching key in JWKS");let c;if(i==="RS256"||i==="RS384"||i==="RS512"){let h=i==="RS256"?"SHA-256":i==="RS384"?"SHA-384":"SHA-512";c=await globalThis.crypto.subtle.importKey("jwk",a,{name:"RSASSA-PKCS1-v1_5",hash:{name:h}},!1,["verify"])}else if(i==="ES256"||i==="ES384"||i==="ES512"){let h=i==="ES256"?"P-256":i==="ES384"?"P-384":"P-521";c=await globalThis.crypto.subtle.importKey("jwk",a,{name:"ECDSA",namedCurve:h},!1,["verify"])}else throw new Error(`Unsupported OIDC token algorithm: ${i}`);let l=new TextEncoder().encode(`${t[0]}.${t[1]}`),u=(4-t[2].length%4)%4,d=t[2].replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(u),p=Uint8Array.from(atob(d),h=>h.charCodeAt(0)),E=i.startsWith("ES")?{name:"ECDSA",hash:{name:`SHA-${i.slice(2)}`}}:{name:"RSASSA-PKCS1-v1_5"};if(!await globalThis.crypto.subtle.verify(E,c,p,l))throw new Error("ID token signature verification failed");let f=JSON.parse(Ti(t[1])),_=Math.floor(Date.now()/1e3);if(typeof f.exp=="number"&&f.exp<_)throw new Error("ID token has expired");return f}function bi(s,e){let t=e?.email??"email",n=s[t];if(typeof n!="string")throw new Error("OIDC token missing email claim");return n}function Oi(s,e){let t=e?.roles??"consenti_roles",n=s[t];return Array.isArray(n)?n.filter(i=>typeof i=="string"):[]}var Ge=new Map;setInterval(()=>{let s=Date.now();for(let[e,t]of Ge)t.expiresAt<s&&Ge.delete(e)},5*6e4).unref();function Di(s,e,t){Ge.set(s,{verifier:e,nonce:t,expiresAt:Date.now()+10*6e4})}function Li(s){let e=Ge.get(s);return Ge.delete(s),!e||e.expiresAt<Date.now()?null:{verifier:e.verifier,nonce:e.nonce}}function No(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ui(s){return`<?xml version="1.0" encoding="UTF-8"?>
132
+ GROUP BY v.country ORDER BY count DESC LIMIT 50`,[e])).map(n=>({country:n.country,count:Number(n.count)}))}async getGpcStats(e){let[t]=await this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1",[e]),[n]=await this.q("SELECT COUNT(*)::int AS total FROM consent_records WHERE tenant_id=$1 AND gpc_detected=TRUE",[e]),o=Number(t?.total??0),r=Number(n?.total??0);return{detected:r,total:o,rate:o>0?Math.round(r/o*100):0}}async getTenants(){return(await this.q("SELECT * FROM tenants ORDER BY name ASC",[])).map(t=>({id:t.id,name:t.name,slug:t.slug,createdAt:t.created_at,updatedAt:t.updated_at}))}mapApiKey(e){return{id:e.id,tenantId:e.tenant_id,keyHash:e.key_hash,name:e.name,isActive:e.is_active,...e.created_by!==null?{createdBy:e.created_by}:{},...e.expire_by!==null?{expireBy:e.expire_by}:{},createdAt:e.created_at,...e.updated_at!==null?{updatedAt:e.updated_at}:{}}}async createApiKey(e){let t=(0,C.randomUUID)(),o=(await this.q("INSERT INTO api_keys (id, tenant_id, key_hash, name, created_by, expire_by) VALUES ($1,$2,$3,$4,$5,$6) RETURNING *",[t,e.tenantId,e.keyHash,e.name,e.createdBy??null,e.expireBy??null]))[0];if(!o)throw new Error("Failed to create API key");return this.mapApiKey(o)}async getApiKeyByHash(e){let n=(await this.q("SELECT * FROM api_keys WHERE key_hash=$1 AND is_active=TRUE",[e]))[0];return n?this.mapApiKey(n):null}async revokeApiKey(e){await this.q("UPDATE api_keys SET is_active=FALSE, updated_at=NOW() WHERE id=$1",[e])}async reactivateApiKey(e){await this.q("UPDATE api_keys SET is_active=TRUE, updated_at=NOW(), expire_by=CASE WHEN expire_by <= NOW() THEN NULL ELSE expire_by END WHERE id=$1",[e])}async deleteApiKey(e){await this.q("DELETE FROM api_keys WHERE id=$1",[e])}async getApiKeys(e){return(await this.q("SELECT * FROM api_keys WHERE tenant_id=$1 ORDER BY created_at DESC",[e])).map(n=>this.mapApiKey(n))}async createTenant(e){let t=(0,C.randomUUID)(),n=new Date().toISOString(),r=(await this.q("INSERT INTO tenants (id, name, slug, created_at, updated_at) VALUES ($1,$2,$3,$4,$5) RETURNING *",[t,e.name,e.slug,n,n]))[0];if(!r)throw new Error("Failed to create tenant");return{id:r.id,name:r.name,slug:r.slug,createdAt:r.created_at,updatedAt:r.updated_at}}async updateTenant(e,t){let n=new Date().toISOString(),o=["updated_at=$1"],r=[n],s=2;t.name!=null&&(o.push(`name=$${s++}`),r.push(t.name)),t.slug!=null&&(o.push(`slug=$${s++}`),r.push(t.slug)),r.push(e);let c=(await this.q(`UPDATE tenants SET ${o.join(",")} WHERE id=$${s} RETURNING *`,r))[0];if(!c)throw new Error(`Tenant ${e} not found`);return{id:c.id,name:c.name,slug:c.slug,createdAt:c.created_at,updatedAt:c.updated_at}}async deleteTenant(e){await this.q("DELETE FROM tenants WHERE id=$1",[e])}async getSettings(e){let n=(await this.q("SELECT allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json FROM tenant_settings WHERE tenant_id=$1",[e]))[0];return n?{allowedOrigins:n.allowed_origins_json,adminAllowedOrigins:n.admin_allowed_origins_json,setupCompleted:n.setup_completed,profilesSeeded:n.profiles_seeded,...n.tcf_confirmation_json?{tcfConfirmation:n.tcf_confirmation_json}:{},...n.gpp_confirmation_json?{gppConfirmation:n.gpp_confirmation_json}:{}}:{}}async updateSettings(e,t){let o={...await this.getSettings(e),...t};return await this.q(`INSERT INTO tenant_settings (tenant_id, allowed_origins_json, admin_allowed_origins_json, setup_completed, profiles_seeded, tcf_confirmation_json, gpp_confirmation_json, updated_at) VALUES ($1,$2::jsonb,$3::jsonb,$4,$5,$6::jsonb,$7::jsonb,NOW())
133
+ ON CONFLICT (tenant_id) DO UPDATE SET allowed_origins_json=$2::jsonb, admin_allowed_origins_json=$3::jsonb, setup_completed=$4, profiles_seeded=$5, tcf_confirmation_json=$6::jsonb, gpp_confirmation_json=$7::jsonb, updated_at=NOW()`,[e,JSON.stringify(o.allowedOrigins??[]),JSON.stringify(o.adminAllowedOrigins??[]),o.setupCompleted??!1,o.profilesSeeded??!1,o.tcfConfirmation?JSON.stringify(o.tcfConfirmation):null,o.gppConfirmation?JSON.stringify(o.gppConfirmation):null]),this.getSettings(e)}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=await this.q("SELECT visitor_id FROM consent_records WHERE created_at < $1",[t]);if(n.length===0)return 0;let o=n.map(s=>s.visitor_id),r=o.map((s,a)=>`$${a+1}`).join(",");return await this.q(`DELETE FROM consent_history WHERE visitor_id IN (${r})`,o),await this.q(`DELETE FROM consent_records WHERE visitor_id IN (${r})`,o),o.length}async createConsentTemplate(){throw new Error("Not implemented")}async updateConsentTemplate(){throw new Error("Not implemented")}async deleteConsentTemplate(){throw new Error("Not implemented")}async getConsentTemplate(){throw new Error("Not implemented")}async getConsentTemplates(){throw new Error("Not implemented")}async copyConsentTemplate(){throw new Error("Not implemented")}async createUITemplate(){throw new Error("Not implemented")}async updateUITemplate(){throw new Error("Not implemented")}async deleteUITemplate(){throw new Error("Not implemented")}async getUITemplate(){throw new Error("Not implemented")}async getUITemplates(){throw new Error("Not implemented")}async copyUITemplate(){throw new Error("Not implemented")}async listProfilesSummary(){return[]}async findProfilesUsingConsentTemplate(){return[]}async findProfilesUsingUITemplate(){return[]}async getOptInStats(){throw new Error("Not implemented")}};p();var Ee=require("node:fs/promises"),ge=require("node:crypto");var Xc=500;function Gn(){return{_version:1,tenants:[],profiles:[],consents:[],consent_history:[],visitors:[],users:[],roles:[],permissions:[],user_roles:[],role_permissions:[],audit_logs:[],consent_templates:[],ui_templates:[],api_keys:[],settings:{},notice_shown:[]}}function jn(i,e,t){let n=Math.min(t,Xc),o=(e-1)*n;return i.slice(o,o+n)}function el(i){let{id:e,tenantId:t,visitorId:n,profileId:o,locale:r,gpcDetected:s,source:a,ageVerified:c,createdAt:l,updatedAt:d}=i;return{id:e,tenantId:t,visitorId:n,profileId:o,locale:r,gpcDetected:s,source:a,...c!=null?{ageVerified:c}:{},createdAt:l,updatedAt:d}}function tl(i){let{id:e,tenantId:t,userId:n,action:o,resourceType:r,resourceId:s,createdAt:a}=i;return{id:e,tenantId:t,action:o,resourceType:r,createdAt:a,...n!=null?{userId:n}:{},...s!=null?{resourceId:s}:{}}}var Dt=class{constructor(e){this.config=e}config;db=Gn();filePath="";writeQueue=Promise.resolve();scheduleWrite(){this.writeQueue=this.writeQueue.then(async()=>{await(0,Ee.mkdir)(this.filePath.replace(/\/[^/]+$/,""),{recursive:!0});let e=`${this.filePath}.tmp`;await(0,Ee.writeFile)(e,JSON.stringify(this.db),"utf8"),await(0,Ee.rename)(e,this.filePath)}).catch(e=>{console.warn("[Consenti] JSON store write failed:",e)})}async connect(){let{dbPath:e}=ue(this.config.path??"./consenti-data","json");this.filePath=e;try{let t=await(0,Ee.readFile)(this.filePath,"utf8");this.db={...Gn(),...JSON.parse(t)}}catch{this.db=Gn()}await this.migrate()}async disconnect(){await this.writeQueue}async migrate(){this.seed()}seed(){let e=new Date().toISOString(),{id:t,name:n,slug:o}=te;this.db.tenants.find(r=>r.id===t)||this.db.tenants.push({id:t,name:n,slug:o,createdAt:e,updatedAt:e});for(let r of ee)this.db.permissions.find(s=>s.id===r.id)||this.db.permissions.push({id:r.id,name:r.name,description:r.description});for(let r of pe)this.db.roles.find(s=>s.id===r.id)||this.db.roles.push({id:r.id,tenantId:r.tenantId,name:r.name,description:r.description});for(let r of me)this.db.role_permissions.find(s=>s.roleId===r.roleId&&s.permissionId===r.permissionId)||this.db.role_permissions.push(r);this.scheduleWrite()}async createProfile(e){let t=new Date().toISOString(),o={id:z(),tenantId:e.tenantId,name:e.name,defaultLocale:e.defaultLocale,version:1,profileJson:e.profileJson,createdAt:t,updatedAt:t};return this.db.profiles.push(o),this.scheduleWrite(),o}async updateProfile(e,t){let n=this.db.profiles.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Profile ${e} not found`);let r={...this.db.profiles[n],...t.name!=null&&{name:t.name},...t.defaultLocale!=null&&{defaultLocale:t.defaultLocale},...t.profileJson!=null&&{profileJson:t.profileJson},...t.version!=null&&{version:t.version},updatedAt:new Date().toISOString()};return this.db.profiles[n]=r,this.scheduleWrite(),r}async deleteProfile(e){this.db.profiles=this.db.profiles.filter(t=>t.id!==e),this.scheduleWrite()}async getProfile(e){return this.db.profiles.find(t=>t.id===e)??null}async getProfiles(e){return this.db.profiles.filter(t=>t.tenantId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}async findActiveProfileByComplianceGroup(e,t){return this.db.profiles.find(n=>n.tenantId===e&&(n.profileJson.complianceGroup===t||n.profileJson.customComplianceGroup===t)&&n.profileJson.isActive)??null}async createConsent(e){let t=new Date().toISOString(),n=K(),o={id:n,tenantId:e.tenantId,visitorId:e.visitorId,profileId:e.profileId,locale:e.locale,consentJson:e.consentJson,gpcDetected:e.gpcDetected??!1,source:e.source,...e.ageVerified!=null&&{ageVerified:e.ageVerified},...e.parentalConsentToken!=null&&{parentalConsentToken:e.parentalConsentToken},...e.tcfString!=null&&{tcfString:e.tcfString},...e.gppString!=null&&{gppString:e.gppString},...e.signature!=null&&{signature:e.signature},createdAt:t,updatedAt:t};return this.db.consents.push(o),this.db.consent_history.push({id:(0,ge.randomUUID)(),tenantId:e.tenantId,consentRecordId:n,visitorId:e.visitorId,oldJson:null,newJson:e.consentJson,action:"created",createdAt:t}),this.scheduleWrite(),o}async updateConsent(e,t){let n=this.db.consents.findIndex(a=>a.visitorId===e);if(n===-1)throw new Error(`Consent for visitor ${e} not found`);let o=this.db.consents[n],r=new Date().toISOString(),s={...o,consentJson:t.consentJson,...t.locale!=null&&{locale:t.locale},...t.gpcDetected!=null&&{gpcDetected:t.gpcDetected},...t.signature!=null&&{signature:t.signature},updatedAt:r};return this.db.consents[n]=s,this.db.consent_history.push({id:(0,ge.randomUUID)(),tenantId:o.tenantId,consentRecordId:o.id,visitorId:e,oldJson:o.consentJson,newJson:t.consentJson,action:"updated",createdAt:r}),this.scheduleWrite(),s}async deleteConsent(e){this.db.consent_history=this.db.consent_history.filter(t=>t.visitorId!==e),this.db.consents=this.db.consents.filter(t=>t.visitorId!==e),this.scheduleWrite()}async getConsent(e){return this.db.consents.find(t=>t.visitorId===e)??null}async getConsents(e){let t=this.db.consents.filter(r=>r.tenantId===e.tenantId);if(e.profileId&&(t=t.filter(r=>r.profileId===e.profileId)),e.from&&(t=t.filter(r=>r.createdAt>=e.from)),e.to&&(t=t.filter(r=>r.createdAt<=e.to)),e.q){let r=e.q.toLowerCase();t=t.filter(s=>s.visitorId.toLowerCase().startsWith(r)||s.profileId.toLowerCase().startsWith(r)||s.locale.toLowerCase().startsWith(r)||s.source.toLowerCase().startsWith(r))}t.sort((r,s)=>s.createdAt.localeCompare(r.createdAt));let n=e.page??1,o=e.limit??50;return{items:jn(t,n,o).map(el),total:t.length,page:n,limit:o}}async*streamConsents(e){for(let t of this.db.consents.filter(n=>n.tenantId===e.tenantId))yield t}async getConsentHistory(e){return this.db.consent_history.filter(t=>t.visitorId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}async createNoticeShown(e){let t={id:(0,ge.randomUUID)(),tenantId:e.tenantId,visitorId:e.visitorId,profileId:e.profileId,locale:e.locale,createdAt:new Date().toISOString()};return this.db.notice_shown.push(t),this.scheduleWrite(),t}async getNoticeShownForVisitor(e){return this.db.notice_shown.filter(t=>t.visitorId===e).sort((t,n)=>n.createdAt.localeCompare(t.createdAt))}async createVisitor(e){let t=new Date().toISOString(),n={id:q(),tenantId:e.tenantId,visitorId:e.visitorId,firstSeen:t,lastSeen:t,...e.country!=null&&{country:e.country},...e.region!=null&&{region:e.region},...e.city!=null&&{city:e.city},...e.ipHash!=null&&{ipHash:e.ipHash},...e.userAgentHash!=null&&{userAgentHash:e.userAgentHash}};return this.db.visitors.push(n),this.scheduleWrite(),n}async updateVisitor(e,t){let n=this.db.visitors.findIndex(s=>s.visitorId===e);if(n===-1)throw new Error(`Visitor ${e} not found`);let r={...this.db.visitors[n],lastSeen:t.lastSeen??new Date().toISOString(),...t.country!=null&&{country:t.country},...t.region!=null&&{region:t.region},...t.city!=null&&{city:t.city}};return this.db.visitors[n]=r,this.scheduleWrite(),r}async deleteVisitor(e){this.db.visitors=this.db.visitors.filter(t=>t.visitorId!==e),this.scheduleWrite()}async getVisitor(e){return this.db.visitors.find(t=>t.visitorId===e)??null}async getVisitors(e){let t=this.db.visitors.filter(r=>r.tenantId===e.tenantId);if(e.from&&(t=t.filter(r=>r.firstSeen>=e.from)),e.to&&(t=t.filter(r=>r.firstSeen<=e.to)),e.q){let r=e.q.toLowerCase();t=t.filter(s=>s.visitorId.toLowerCase().startsWith(r)||(s.country?.toLowerCase().startsWith(r)??!1))}t.sort((r,s)=>s.lastSeen.localeCompare(r.lastSeen));let n=e.page??1,o=e.limit??50;return{items:jn(t,n,o),total:t.length,page:n,limit:o}}async createUser(e){let t=new Date().toISOString(),n={id:(0,ge.randomUUID)(),tenantId:e.tenantId,name:e.name,email:e.email,passwordHash:e.passwordHash,isActive:!0,allowedTenants:e.allowedTenants??[],createdAt:t,updatedAt:t};return this.db.users.push(n),this.scheduleWrite(),n}async updateUser(e,t){let n=this.db.users.findIndex(s=>s.id===e);if(n===-1)throw new Error(`User ${e} not found`);let r={...this.db.users[n],...t.name!=null&&{name:t.name},...t.email!=null&&{email:t.email},...t.passwordHash!=null&&{passwordHash:t.passwordHash},...t.isActive!=null&&{isActive:t.isActive},..."totpSecret"in t&&t.totpSecret!=null&&{totpSecret:t.totpSecret},...t.totpEnabled!=null&&{totpEnabled:t.totpEnabled},..."allowedTenants"in t&&{allowedTenants:t.allowedTenants??[]},updatedAt:new Date().toISOString()};return this.db.users[n]=r,this.scheduleWrite(),r}async deleteUser(e){this.db.user_roles=this.db.user_roles.filter(t=>t.userId!==e),this.db.users=this.db.users.filter(t=>t.id!==e),this.scheduleWrite()}async getUserById(e){return this.db.users.find(t=>t.id===e)??null}async getUserByEmail(e){return this.db.users.find(t=>t.email===e)??null}async getUsers(e){return this.db.users.filter(t=>t.tenantId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}async countUsers(e){return e?this.db.users.filter(t=>t.tenantId===e).length:this.db.users.length}async getRoles(e){return this.db.roles.filter(t=>t.tenantId===e)}async createRole(e){let t={id:(0,ge.randomUUID)(),tenantId:e.tenantId,name:e.name,...e.description!=null&&{description:e.description}};return this.db.roles.push(t),this.scheduleWrite(),t}async updateRole(e,t){let n=this.db.roles.findIndex(r=>r.id===e);if(n===-1)throw new Error(`Role ${e} not found`);let o={...this.db.roles[n],...t.name!=null&&{name:t.name},...t.description!=null&&{description:t.description}};return this.db.roles[n]=o,this.scheduleWrite(),o}async deleteRole(e){this.db.role_permissions=this.db.role_permissions.filter(t=>t.roleId!==e),this.db.user_roles=this.db.user_roles.filter(t=>t.roleId!==e),this.db.roles=this.db.roles.filter(t=>t.id!==e),this.scheduleWrite()}async getAllPermissions(){return[...this.db.permissions].sort((e,t)=>e.name.localeCompare(t.name))}async getPermissionsForRole(e){let t=new Set(this.db.role_permissions.filter(n=>n.roleId===e).map(n=>n.permissionId));return this.db.permissions.filter(n=>t.has(n.id))}async getUserRoles(e,t){let n=this.db.user_roles.filter(r=>r.userId===e);t&&(n=n.filter(r=>r.tenantId===t));let o=new Set(n.map(r=>r.roleId));return this.db.roles.filter(r=>o.has(r.id))}async assignRole(e,t,n="default"){this.db.user_roles.find(o=>o.userId===e&&o.roleId===t&&o.tenantId===n)||(this.db.user_roles.push({userId:e,roleId:t,tenantId:n}),this.scheduleWrite())}async revokeRole(e,t,n){this.db.user_roles=this.db.user_roles.filter(o=>!(o.userId===e&&o.roleId===t&&(n==null||o.tenantId===n))),this.scheduleWrite()}async assignPermissionToRole(e,t){this.db.role_permissions.find(n=>n.roleId===e&&n.permissionId===t)||(this.db.role_permissions.push({roleId:e,permissionId:t}),this.scheduleWrite())}async revokePermissionFromRole(e,t){this.db.role_permissions=this.db.role_permissions.filter(n=>!(n.roleId===e&&n.permissionId===t)),this.scheduleWrite()}async createLog(e){let t={id:(0,ge.randomUUID)(),tenantId:e.tenantId,action:e.action,resourceType:e.resourceType,createdAt:new Date().toISOString(),...e.userId!=null&&{userId:e.userId},...e.resourceId!=null&&{resourceId:e.resourceId},...e.oldData!=null&&{oldData:e.oldData},...e.newData!=null&&{newData:e.newData}};this.db.audit_logs.push(t),this.scheduleWrite()}async getLogs(e){let t=this.db.audit_logs.filter(r=>r.tenantId===e.tenantId);if(e.action&&(t=t.filter(r=>r.action===e.action)),e.resourceType&&(t=t.filter(r=>r.resourceType===e.resourceType)),e.from&&(t=t.filter(r=>r.createdAt>=e.from)),e.to&&(t=t.filter(r=>r.createdAt<=e.to)),e.q){let r=e.q.toLowerCase();t=t.filter(s=>s.action.toLowerCase().startsWith(r)||s.resourceType.toLowerCase().startsWith(r)||(s.resourceId?.toLowerCase().startsWith(r)??!1)||(s.userId?.toLowerCase().startsWith(r)??!1))}t.sort((r,s)=>s.createdAt.localeCompare(r.createdAt));let n=e.page??1,o=e.limit??50;return{items:jn(t,n,o).map(tl),total:t.length,page:n,limit:o}}async getAuditLogById(e){return this.db.audit_logs.find(t=>t.id===e)??null}async*streamAuditLogs(e){let t=this.db.audit_logs.filter(n=>n.tenantId===e.tenantId);e.action&&(t=t.filter(n=>n.action===e.action)),e.from&&(t=t.filter(n=>n.createdAt>=e.from)),e.to&&(t=t.filter(n=>n.createdAt<=e.to)),t.sort((n,o)=>o.createdAt.localeCompare(n.createdAt));for(let n of t)yield n}async getOverviewStats(e){let t=this.db.consents.filter(a=>a.tenantId===e),n=t.slice(-500),o=0,r=0;for(let a of n){let c=Object.values(a.consentJson),l=c.length>0?c.filter(d=>d==="granted").length/c.length:0;l>=.8?o++:l<=.2&&r++}let s=n.length||1;return{totalConsents:t.length,gpcDetectedCount:t.filter(a=>a.gpcDetected).length,totalVisitors:this.db.visitors.filter(a=>a.tenantId===e).length,acceptedPct:Math.round(o/s*100),rejectedPct:Math.round(r/s*100)}}async getCategoryStats(e){let t={};for(let n of this.db.consents.filter(o=>o.tenantId===e).slice(0,5e3))for(let[o,r]of Object.entries(n.consentJson))t[o]||(t[o]={granted:0,denied:0,objected:0}),r==="granted"?t[o].granted++:r==="denied"?t[o].denied++:r==="objected"&&t[o].objected++;return t}async getTimeline(e,t=30){let n=new Date(Date.now()-t*864e5).toISOString().slice(0,10),o=new Map;for(let r of this.db.consents.filter(s=>s.tenantId===e&&s.createdAt.slice(0,10)>=n)){let s=r.createdAt.slice(0,10);o.set(s,(o.get(s)??0)+1)}return[...o.entries()].sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>({date:r,count:s}))}async getCountries(e){let t=new Set(this.db.consents.filter(o=>o.tenantId===e).map(o=>o.visitorId)),n=new Map;for(let o of this.db.visitors.filter(r=>t.has(r.visitorId)&&r.country)){let r=o.country;n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort(([,o],[,r])=>r-o).slice(0,50).map(([o,r])=>({country:o,count:r}))}async getGpcStats(e){let t=this.db.consents.filter(r=>r.tenantId===e),n=t.filter(r=>r.gpcDetected).length,o=t.length;return{detected:n,total:o,rate:o>0?Math.round(n/o*100):0}}async getTenants(){return[...this.db.tenants].sort((e,t)=>e.name.localeCompare(t.name))}async createTenant(e){let t=new Date().toISOString(),n={id:(0,ge.randomUUID)(),name:e.name,slug:e.slug,createdAt:t,updatedAt:t};return this.db.tenants.push(n),this.scheduleWrite(),n}async updateTenant(e,t){let n=this.db.tenants.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Tenant ${e} not found`);let o=new Date().toISOString(),r={...this.db.tenants[n],...t.name!=null&&{name:t.name},...t.slug!=null&&{slug:t.slug},updatedAt:o};return this.db.tenants[n]=r,this.scheduleWrite(),r}async deleteTenant(e){this.db.tenants=this.db.tenants.filter(t=>t.id!==e),this.scheduleWrite()}async getSettings(e){return this.db.settings[e]??{}}async updateSettings(e,t){let n={...this.db.settings[e]??{},...t};return this.db.settings[e]=n,this.scheduleWrite(),n}async purgeExpiredConsents(e){let t=new Date(Date.now()-e*864e5).toISOString(),n=new Set(this.db.consents.filter(o=>o.createdAt<t).map(o=>o.visitorId));return n.size===0?0:(this.db.consent_history=this.db.consent_history.filter(o=>!n.has(o.visitorId)),this.db.consents=this.db.consents.filter(o=>!n.has(o.visitorId)),this.scheduleWrite(),n.size)}async createApiKey(e){let t=new Date().toISOString(),n={id:(0,ge.randomUUID)(),tenantId:e.tenantId,keyHash:e.keyHash,name:e.name,isActive:!0,...e.createdBy!==void 0?{createdBy:e.createdBy}:{},...e.expireBy!==void 0?{expireBy:e.expireBy}:{},createdAt:t,updatedAt:t};return this.db.api_keys.push(n),this.scheduleWrite(),n}async getApiKeyByHash(e){return this.db.api_keys.find(t=>t.keyHash===e&&t.isActive)??null}async revokeApiKey(e){let t=this.db.api_keys.find(n=>n.id===e);t&&(t.isActive=!1,t.updatedAt=new Date().toISOString(),this.scheduleWrite())}async reactivateApiKey(e){let t=this.db.api_keys.find(n=>n.id===e);t&&(t.isActive=!0,t.expireBy&&new Date(t.expireBy)<=new Date&&delete t.expireBy,t.updatedAt=new Date().toISOString(),this.scheduleWrite())}async deleteApiKey(e){let t=this.db.api_keys.findIndex(n=>n.id===e);t!==-1&&(this.db.api_keys.splice(t,1),this.scheduleWrite())}async getApiKeys(e){return this.db.api_keys.filter(t=>t.tenantId===e).sort((t,n)=>n.createdAt.localeCompare(t.createdAt))}async createConsentTemplate(e){let t=new Date().toISOString(),n={id:_e(),tenantId:e.tenantId,name:e.name,cookies:e.cookies,categories:e.categories,createdAt:t,updatedAt:t};return this.db.consent_templates.push(n),this.scheduleWrite(),n}async updateConsentTemplate(e,t){let n=this.db.consent_templates.findIndex(s=>s.id===e);if(n===-1)throw new Error("Consent template not found");let o=new Date().toISOString(),r={...this.db.consent_templates[n],...t.name!==void 0&&{name:t.name},...t.cookies!==void 0&&{cookies:t.cookies},...t.categories!==void 0&&{categories:t.categories},updatedAt:o};return this.db.consent_templates[n]=r,this.scheduleWrite(),r}async deleteConsentTemplate(e){this.db.consent_templates=this.db.consent_templates.filter(t=>t.id!==e),this.scheduleWrite()}async getConsentTemplate(e){return this.db.consent_templates.find(t=>t.id===e)??null}async getConsentTemplates(e){return this.db.consent_templates.filter(t=>t.tenantId===e).sort((t,n)=>t.name.localeCompare(n.name))}async copyConsentTemplate(e,t){let n=await this.getConsentTemplate(e);if(!n)throw new Error("Consent template not found");return this.createConsentTemplate({tenantId:n.tenantId,name:t,cookies:n.cookies,categories:n.categories})}async createUITemplate(e){let t=new Date().toISOString(),{tenantId:n,name:o,...r}=e,s={id:we(),tenantId:n,name:o,...r,createdAt:t,updatedAt:t};return this.db.ui_templates.push(s),this.scheduleWrite(),s}async updateUITemplate(e,t){let n=this.db.ui_templates.findIndex(c=>c.id===e);if(n===-1)throw new Error("UI template not found");let{name:o,...r}=t,s=new Date().toISOString(),a={...this.db.ui_templates[n],...t.name!==void 0&&{name:t.name},...r,updatedAt:s};return this.db.ui_templates[n]=a,this.scheduleWrite(),a}async deleteUITemplate(e){this.db.ui_templates=this.db.ui_templates.filter(t=>t.id!==e),this.scheduleWrite()}async getUITemplate(e){return this.db.ui_templates.find(t=>t.id===e)??null}async getUITemplates(e){return this.db.ui_templates.filter(t=>t.tenantId===e).sort((t,n)=>t.name.localeCompare(n.name))}async copyUITemplate(e,t){let n=await this.getUITemplate(e);if(!n)throw new Error("UI template not found");let{tenantId:o,mainBanner:r,gpcBanner:s,preferenceModal:a}=n;return this.createUITemplate({tenantId:o,name:t,...r!==void 0&&{mainBanner:r},...s!==void 0&&{gpcBanner:s},...a!==void 0&&{preferenceModal:a}})}profileToSummary(e){let t=e.profileJson,n=t.consentTemplateId?this.db.consent_templates.find(r=>r.id===t.consentTemplateId):null,o=t.uiTemplateId?this.db.ui_templates.find(r=>r.id===t.uiTemplateId):null;return{id:e.id,name:e.name,defaultLocale:e.defaultLocale,complianceGroup:t.complianceGroup??null,customComplianceGroup:t.customComplianceGroup??null,isActive:t.isActive??!1,consentTemplateName:n?.name??null,uiTemplateName:o?.name??null,createdAt:e.createdAt,updatedAt:e.updatedAt}}async listProfilesSummary(e){return this.db.profiles.filter(t=>t.tenantId===e).sort((t,n)=>t.createdAt.localeCompare(n.createdAt)).map(t=>this.profileToSummary(t))}async findProfilesUsingConsentTemplate(e){return this.db.profiles.filter(t=>t.profileJson.consentTemplateId===e).sort((t,n)=>t.name.localeCompare(n.name)).map(t=>this.profileToSummary(t))}async findProfilesUsingUITemplate(e){return this.db.profiles.filter(t=>t.profileJson.uiTemplateId===e).sort((t,n)=>t.name.localeCompare(n.name)).map(t=>this.profileToSummary(t))}async getOptInStats(e,t){let n=this.db.consents.filter(u=>u.tenantId===e);t.profileId&&(n=n.filter(u=>u.profileId===t.profileId)),t.from&&(n=n.filter(u=>u.createdAt>=t.from)),t.to&&(n=n.filter(u=>u.createdAt<=t.to)),t.locale&&(n=n.filter(u=>u.locale===t.locale));let o=0,r=0,s=0,a=0,c={},l=new Map;for(let u of n){let m=Object.values(u.consentJson),h=m.length>0?m.filter(v=>v==="granted").length/m.length:0,S=m.length>0?m.filter(v=>v==="denied").length/m.length:0;o++;let _=u.locale;c[_]||(c[_]={total:0,granted:0,denied:0,managed:0}),c[_].total++;let w=u.createdAt.slice(0,10),R=l.get(w)??{total:0,granted:0,denied:0,managed:0};R.total++,h>=.9?(r++,c[_].granted++,R.granted++):S>=.9?(s++,c[_].denied++,R.denied++):(a++,c[_].managed++,R.managed++),l.set(w,R)}let d=Array.from(l.entries()).sort(([u],[m])=>u.localeCompare(m)).map(([u,m])=>({date:u,...m}));return{total:o,granted:r,denied:s,managed:a,grantedPct:o>0?Math.round(r/o*1e3)/10:0,deniedPct:o>0?Math.round(s/o*1e3)/10:0,managedPct:o>0?Math.round(a/o*1e3)/10:0,byLocale:c,byDate:d}}};p();var kt=class{constructor(e){this.adapter=e}adapter;create(e){return this.adapter.createProfile(e)}update(e,t){return this.adapter.updateProfile(e,t)}delete(e){return this.adapter.deleteProfile(e)}get(e){return this.adapter.getProfile(e)}list(e){return this.adapter.getProfiles(e)}findActiveByComplianceGroup(e,t){return this.adapter.findActiveProfileByComplianceGroup(e,t)}};p();var Lt=class{constructor(e){this.adapter=e}adapter;create(e){return this.adapter.createConsent(e)}update(e,t){return this.adapter.updateConsent(e,t)}delete(e){return this.adapter.deleteConsent(e)}get(e){return this.adapter.getConsent(e)}list(e){return this.adapter.getConsents(e)}};p();var Nt=class{constructor(e){this.adapter=e}adapter;create(e){return this.adapter.createVisitor(e)}update(e,t){return this.adapter.updateVisitor(e,t)}delete(e){return this.adapter.deleteVisitor(e)}get(e){return this.adapter.getVisitor(e)}};p();var xt=class{constructor(e){this.adapter=e}adapter;create(e){return this.adapter.createNoticeShown(e)}getForVisitor(e){return this.adapter.getNoticeShownForVisitor(e)}};p();var Mt=class{constructor(e){this.adapter=e}adapter;log(e){return this.adapter.createLog(e)}list(e){return this.adapter.getLogs(e)}get(e){return this.adapter.getAuditLogById(e)}};p();p();var Ut=class{constructor(e,t=500,n=6e4){this.ttlMs=e;this.maxEntries=t;this.sweepTimer=setInterval(()=>this.sweep(),n),this.sweepTimer.unref?.()}ttlMs;maxEntries;store=new Map;sweepTimer=null;get(e){let t=this.store.get(e);if(t){if(Date.now()>t.expiresAt){this.store.delete(e);return}return t.value}}set(e,t){if(this.store.size>=this.maxEntries&&!this.store.has(e)){let n=this.store.keys().next().value;n!==void 0&&this.store.delete(n)}this.store.set(e,{value:t,expiresAt:Date.now()+this.ttlMs})}sweep(){let e=Date.now();for(let[t,n]of this.store)e>n.expiresAt&&this.store.delete(t)}dispose(){this.sweepTimer&&clearInterval(this.sweepTimer),this.sweepTimer=null}};var nl=3e4,Gt=class{constructor(e){this.storage=e}storage;cache=new Ut(nl);async getOverview(e){return this.cached(`overview:${e}`,()=>this.storage.getOverviewStats(e))}async getCategories(e){return this.cached(`categories:${e}`,()=>this.storage.getCategoryStats(e))}async getTimeline(e,t){return this.cached(`timeline:${e}:${t}`,()=>this.storage.getTimeline(e,t))}async getCountries(e){return this.cached(`countries:${e}`,()=>this.storage.getCountries(e))}async getGpc(e){return this.cached(`gpc:${e}`,()=>this.storage.getGpcStats(e))}async getTenants(){return this.storage.getTenants()}dispose(){this.cache.dispose()}async cached(e,t){let n=this.cache.get(e);if(n!==void 0)return n;let o=await t();return this.cache.set(e,o),o}};p();var jt=class{constructor(e){this.adapter=e}adapter;getById(e){return this.adapter.getUserById(e)}getByEmail(e){return this.adapter.getUserByEmail(e)}list(e){return this.adapter.getUsers(e)}create(e){return this.adapter.createUser(e)}update(e,t){return this.adapter.updateUser(e,t)}delete(e){return this.adapter.deleteUser(e)}getRoles(e,t){return this.adapter.getUserRoles(e,t)}assignRole(e,t,n){return this.adapter.assignRole(e,t,n)}revokeRole(e,t,n){return this.adapter.revokeRole(e,t,n)}};p();var F=require("node:fs"),Q=require("node:path");p();var Do=require("node:worker_threads"),ko=require("node:url"),Ht=require("node:path"),Lo=require("node:fs");p();var x=require("node:fs"),oe=require("node:path"),Io=require("node:crypto");p();var Ze=require("node:crypto");function Bn(i){return(0,Ze.createHash)("sha256").update(i).digest("hex")}function Bt(i,e){return(0,Ze.createHmac)("sha256",i).update(e).digest()}function il(i){let e=i.toISOString().replace(/[-:]/g,"").slice(0,15)+"Z";return{amzDate:e,dateStamp:e.slice(0,8)}}function ol(i,e,t,n){let o=Bt(`AWS4${i}`,e),r=Bt(o,t),s=Bt(r,n);return Bt(s,"aws4_request")}function vo(i){let{method:e,key:t,body:n,contentType:o,config:r}=i,s=new Date,{amzDate:a,dateStamp:c}=il(s),l=`${r.bucketName}.s3.${r.region}.amazonaws.com`,d=Bn(n?Buffer.isBuffer(n)?n:Buffer.from(n,"utf8"):""),u={host:l,"x-amz-date":a,"x-amz-content-sha256":d};r.sessionToken&&(u["x-amz-security-token"]=r.sessionToken),o&&e==="PUT"&&(u["content-type"]=o);let m=Object.keys(u).sort(),h=m.map(O=>`${O}:${u[O]}
134
+ `).join(""),S=m.join(";"),_=[e,`/${encodeURIComponent(t).replace(/%2F/g,"/")}`,"",h,S,d].join(`
135
+ `),w=`${c}/${r.region}/s3/aws4_request`,R=["AWS4-HMAC-SHA256",a,w,Bn(_)].join(`
136
+ `),v=ol(r.secretAccessKey,c,r.region,"s3"),A=(0,Ze.createHmac)("sha256",v).update(R).digest("hex"),P=[`AWS4-HMAC-SHA256 Credential=${r.accessKeyId}/${w}`,`SignedHeaders=${S}`,`Signature=${A}`].join(", ");return{...u,authorization:P}}function Co(i,e){let t=encodeURIComponent(i).replace(/%2F/g,"/");return`https://${e.bucketName}.s3.${e.region}.amazonaws.com/${t}`}async function Ft(i,e,t,n="application/json"){let o=vo({method:"PUT",key:i,body:e,contentType:n,config:t}),r=typeof e=="string"?e:e.toString("utf8"),s=await fetch(Co(i,t),{method:"PUT",headers:{...o,"content-length":String(Buffer.byteLength(r,"utf8"))},body:r});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`S3 PUT ${i} failed: ${s.status} ${a}`)}}async function Ao(i,e){let t=vo({method:"DELETE",key:i,config:e}),n=await fetch(Co(i,e),{method:"DELETE",headers:t});if(!n.ok&&n.status!==404){let o=await n.text().catch(()=>"");throw new Error(`S3 DELETE ${i} failed: ${n.status} ${o}`)}}function $n(i,e){return(0,oe.join)(i,"profiles",e)}function Fn(i,e,t,n){return(0,oe.join)($n(i,e),t,String(n))}function bo(i,e,t){return(0,oe.join)($n(i,e),t)}function $t(i,e,t){return`profiles/${i}/${e}/${t}.json`}function Po(i,e){let t=i+".tmp";(0,x.writeFileSync)(t,e,"utf8"),JSON.parse(e),(0,x.renameSync)(t,i)}var rl=["gpcMode","complianceGroup","darkMode","allowReceipt","enhanceAccessibility","showFooterMetadata","allowedOrigins","complianceConfig","dpdpa","ageGate","hidePoweredBy"];function sl(i){let e={};for(let t of rl){let n=i[t];n!==void 0&&(e[t]=n)}return e}async function To(i){let{storagePath:e,tenantId:t,profileId:n,version:o,profile:r,localeContent:s,previousVersion:a,s3Config:c}=i,l=Fn(e,t,n,o);(0,x.mkdirSync)(l,{recursive:!0});let{locales:d,defaultLocale:u,cookies:m,expiryDays:h}=r;for(let S of d){let _,w=s[S];if(w){let v={id:r.id,version:o,defaultLocale:u,currentLocale:S,locales:d,cookies:m,...h!==void 0?{expiryDays:h}:{},...sl(r),mainBanner:w.mainBanner,...w.gpcBanner?{gpcBanner:w.gpcBanner}:{},preferenceModal:w.preferenceModal,...w.ageGateModal?{ageGateModal:w.ageGateModal}:{}};_=JSON.stringify(v,null,2)}else if(a!==void 0){let v=(0,oe.join)(Fn(e,t,n,a),`${S}.json`);if(!(0,x.existsSync)(v))continue;_=(0,x.readFileSync)(v,"utf8")}else continue;let R=(0,oe.join)(l,`${S}.json`);Po(R,_),S===u&&Po((0,oe.join)(l,"default.json"),_),c?.enabled&&(await Ft($t(t,`${n}/${o}`,S),_,c),S===u&&await Ft($t(t,`${n}/${o}`,"default"),_,c))}if(!(0,x.existsSync)((0,oe.join)(l,"default.json"))){let S=d.includes(u)?u:d[0]??"";if(S){let _=(0,oe.join)(l,`${S}.json`);(0,x.existsSync)(_)&&(0,x.copyFileSync)(_,(0,oe.join)(l,"default.json"))}}}function al(i){(0,x.existsSync)(i)&&((0,x.lstatSync)(i).isSymbolicLink()||(0,x.rmSync)(i,{recursive:!0,force:!0}))}async function cl(i){let{storagePath:e,tenantId:t,profileId:n,version:o,complianceGroup:r,s3Config:s}=i,a=(0,oe.resolve)(Fn(e,t,n,o)),c=bo(e,t,r);(0,x.mkdirSync)($n(e,t),{recursive:!0}),al(c);let l=`${c}.new-${(0,Io.randomUUID)().slice(0,8)}`;if((0,x.symlinkSync)(a,l,"junction"),(0,x.renameSync)(l,c),s?.enabled){let d=JSON.stringify({profileId:n,version:o});await Ft($t(t,r,"pointer"),d,s)}}async function ll(i){let{storagePath:e,tenantId:t,complianceGroup:n,s3Config:o}=i,r=bo(e,t,n);(0,x.existsSync)(r)&&((0,x.lstatSync)(r).isSymbolicLink()?(0,x.unlinkSync)(r):(0,x.rmSync)(r,{recursive:!0,force:!0})),o?.enabled&&await Ao($t(t,n,"pointer"),o)}async function Oo(i){i.action==="write"?await To(i):i.action==="activate"?(await To(i),await cl(i)):i.action==="deactivate"&&await ll(i)}var dl=(0,Ht.dirname)((0,ko.fileURLToPath)(f)),No=(0,Ht.join)(dl,"profile-json.worker.js"),ul=!(0,Lo.existsSync)(No);async function Hn(i){if(ul){await Oo(i);return}return new Promise((e,t)=>{let n=new Do.Worker(No);n.postMessage(i),n.once("message",o=>{n.terminate(),o.ok?e():t(new Error(`[profile-worker] ${o.action} failed: ${o.error}`))}),n.once("error",o=>{n.terminate(),t(o)})})}function ci(i,e){if(!e)return i;let t={...i};for(let[n,o]of Object.entries(e))t[n]&&(t[n]={...t[n],...o});return t}function rs(i){return{...i.gpcMode!==void 0?{gpcMode:i.gpcMode}:{},...i.complianceGroup!==void 0?{complianceGroup:i.complianceGroup}:{},...i.darkMode!==void 0?{darkMode:i.darkMode}:{},...i.allowReceipt!==void 0?{allowReceipt:i.allowReceipt}:{},...i.enhanceAccessibility!==void 0?{enhanceAccessibility:i.enhanceAccessibility}:{},...i.showFooterMetadata!==void 0?{showFooterMetadata:i.showFooterMetadata}:{},...i.allowedOrigins!==void 0?{allowedOrigins:i.allowedOrigins}:{},...i.complianceConfig!==void 0?{complianceConfig:i.complianceConfig}:{},...i.dpdpa!==void 0?{dpdpa:i.dpdpa}:{},...i.ageGate!==void 0?{ageGate:i.ageGate}:{},...i.hidePoweredBy!==void 0?{hidePoweredBy:i.hidePoweredBy}:{}}}var nn=class{constructor(e,t,n="default",o,r,s,a,c,l){this.profiles=e;this.audit=t;this.tenantId=n;this.storage=o;this.eventBus=r;this.localeCache=s;this.profilesDir=a;this.handleCache=c;this.s3Config=l}profiles;audit;tenantId;storage;eventBus;localeCache;profilesDir;handleCache;s3Config;versionsRootDir(e){return(0,Q.join)(this.profilesDir??"",this.tenantId,e)}complianceGroupDir(e){return(0,Q.join)(this.profilesDir??"",this.tenantId,e)}groupKey(e){return e.complianceGroup||e.customComplianceGroup||""}profileFilePaths(e,t){let n=this.complianceGroupDir(e);return t.map(o=>(0,Q.join)(n,`${o}.json`)).concat((0,Q.join)(n,"default.json"))}async resolveCookies(e){let t=e.cookies??{};if(e.consentTemplateId&&this.storage){let n=await this.storage.getConsentTemplate(e.consentTemplateId);n&&(t=n.cookies)}return ci(t,e.cookiesOverride)}async writeLocaleFiles(e,t,n,o){if(!this.profilesDir)return;let r=e.profileJson,s=await this.resolveCookies(r),a=r.locales?.length?r.locales:[e.defaultLocale],c={[e.defaultLocale]:{mainBanner:r.mainBanner,...r.gpcBanner?{gpcBanner:r.gpcBanner}:{},preferenceModal:r.preferenceModal,...r.ageGateModal?{ageGateModal:r.ageGateModal}:{}},...t??{}},l=r.isActive??!1,u={action:l?"activate":"write",storagePath:(0,Q.join)(this.profilesDir,".."),tenantId:this.tenantId,profileId:e.id,version:e.version,complianceGroup:n,profile:{id:e.id,defaultLocale:e.defaultLocale,locales:a,cookies:s,...r.expiryDays!==void 0?{expiryDays:r.expiryDays}:{},...rs(r)},localeContent:c,...o!==void 0?{previousVersion:o}:{},...this.s3Config?.enabled?{s3Config:this.s3Config}:{}};if(await Hn(u),l){let m=this.profileFilePaths(n,a);this.handleCache?.(m,e.id,!0),this.eventBus?.emit("cache:purge",{paths:m,profileId:e.id})}}async create(e){let{localeContent:t,...n}=e,o=await this.profiles.create({...n,tenantId:this.tenantId});if(await this.audit.log({tenantId:this.tenantId,action:"profile:created",resourceType:"profile",resourceId:o.id,newData:{profileId:o.id,version:o.version,complianceGroup:this.groupKey(o.profileJson)}}),this.eventBus?.emit("profile:created",o),this.profilesDir){let r=this.groupKey(o.profileJson);await this.writeLocaleFiles(o,t,r,void 0);let s=o.profileJson.locales?.length?o.profileJson.locales:[o.defaultLocale],a=this.profileFilePaths(r,s);this.handleCache?.(a,o.id,!1),this.eventBus?.emit("cache:warm",{paths:a,profileId:o.id})}return o}async copy(e,t){let n=await this.profiles.get(e);if(!n)throw new Error(`Profile ${e} not found`);let o=n.profileJson.locales?.length?n.profileJson.locales:[n.defaultLocale],r={};for(let s of o){if(s===n.defaultLocale)continue;let a=await this.getVersionFile(e,String(n.version),s);if(a)try{let c=JSON.parse(a);r[s]={mainBanner:c.mainBanner,...c.gpcBanner?{gpcBanner:c.gpcBanner}:{},preferenceModal:c.preferenceModal}}catch{}}return this.create({name:t??`Copy of ${n.name}`,defaultLocale:n.defaultLocale,profileJson:{...n.profileJson,isActive:!1},...Object.keys(r).length>0?{localeContent:r}:{}})}async update(e,t){let n=await this.profiles.get(e);if(!n)throw new Error(`Profile ${e} not found`);let{localeContent:o,...r}=t,s=r.profileJson?.isActive??n.profileJson.isActive,a=r.profileJson?{...r.profileJson,...s!==void 0?{isActive:s}:{}}:n.profileJson,c=await this.profiles.update(e,{name:r.name??n.name,defaultLocale:r.defaultLocale??n.defaultLocale,profileJson:a,version:n.version+1});if(this.localeCache?.invalidate(e),await this.audit.log({tenantId:this.tenantId,action:"profile:updated",resourceType:"profile",resourceId:c.id,oldData:{profileId:n.id,version:n.version},newData:{profileId:c.id,version:c.version,complianceGroup:this.groupKey(c.profileJson)}}),this.eventBus?.emit("profile:updated",{previous:n,current:c}),this.profilesDir){let l=this.groupKey(c.profileJson);await this.writeLocaleFiles(c,o,l,n.version)}return c}async delete(e){let t=await this.profiles.get(e);if(await this.profiles.delete(e),this.localeCache?.invalidate(e),await this.audit.log({tenantId:this.tenantId,action:"profile:deleted",resourceType:"profile",resourceId:e,...t!=null?{oldData:{profileId:t.id,version:t.version}}:{}}),this.eventBus?.emit("profile:deleted",{id:e,previous:t}),this.profilesDir&&t){let n=this.groupKey(t.profileJson);if((t.profileJson.isActive??!1)&&n){let r=t.profileJson.locales?.length?t.profileJson.locales:[t.defaultLocale];await this.runDeactivate(n);let s=this.profileFilePaths(n,r);this.handleCache?.(s,e,!0),this.eventBus?.emit("cache:purge",{paths:s,profileId:e})}}}async activate(e){let t=await this.profiles.get(e);if(!t)throw new Error(`Profile ${e} not found`);let n=this.groupKey(t.profileJson),o=await this.profiles.update(e,{profileJson:{...t.profileJson,isActive:!0}});return this.localeCache?.invalidate(e),this.profilesDir&&n&&await this.writeLocaleFiles(o,void 0,n,t.version),await this.audit.log({tenantId:this.tenantId,action:"profile.activated",resourceType:"profile",resourceId:e}),this.eventBus?.emit("profile.activated",o),o}async deactivate(e){let t=await this.profiles.get(e);if(!t)throw new Error(`Profile ${e} not found`);let n=this.groupKey(t.profileJson),o=await this.profiles.update(e,{profileJson:{...t.profileJson,isActive:!1}});if(this.localeCache?.invalidate(e),this.profilesDir&&n){let r=t.profileJson.locales?.length?t.profileJson.locales:[t.defaultLocale];await this.runDeactivate(n);let s=this.profileFilePaths(n,r);this.handleCache?.(s,e,!0),this.eventBus?.emit("cache:purge",{paths:s,profileId:e})}return await this.audit.log({tenantId:this.tenantId,action:"profile.deactivated",resourceType:"profile",resourceId:e}),this.eventBus?.emit("profile.deactivated",o),o}async runDeactivate(e){if(!this.profilesDir)return;let t={action:"deactivate",storagePath:(0,Q.join)(this.profilesDir,".."),tenantId:this.tenantId,profileId:"",version:0,complianceGroup:e,profile:{id:"",defaultLocale:"",locales:[],cookies:{}},localeContent:{},...this.s3Config?.enabled?{s3Config:this.s3Config}:{}};await Hn(t)}async get(e){return this.profiles.get(e)}async getResolved(e,t){let n=await this.profiles.get(e);if(!n)return null;let o=t??n.defaultLocale;if(this.localeCache){let u=this.localeCache.read(e,o);if(u)return u}let r=n.profileJson,s=await this.resolveCookies(r),a=r.locales?.length?r.locales:[n.defaultLocale],l={mainBanner:r.mainBanner,...r.gpcBanner?{gpcBanner:r.gpcBanner}:{},preferenceModal:r.preferenceModal,...r.ageGateModal?{ageGateModal:r.ageGateModal}:{}};if(o!==n.defaultLocale){let u=await this.getVersionFile(e,String(n.version),o);if(u)try{let m=JSON.parse(u);l={mainBanner:m.mainBanner,...m.gpcBanner?{gpcBanner:m.gpcBanner}:{},preferenceModal:m.preferenceModal,...m.ageGateModal?{ageGateModal:m.ageGateModal}:{}}}catch{}}let d={id:n.id,version:n.version,defaultLocale:n.defaultLocale,currentLocale:o,locales:a,cookies:s,...r.expiryDays!==void 0?{expiryDays:r.expiryDays}:{},...rs(r),...l};if(this.localeCache)try{this.localeCache.write(e,o,d)}catch(u){console.warn(`[Consenti] locale cache write failed for ${e}/${o}:`,u)}return d}findActiveByComplianceGroup(e){return this.profiles.findActiveByComplianceGroup(this.tenantId,e)}list(){return this.profiles.list(this.tenantId)}listSummary(){return this.storage?this.storage.listProfilesSummary(this.tenantId):Promise.resolve([])}async listVersions(e){if(!this.profilesDir)return[];let t=this.versionsRootDir(e);if(!(0,F.existsSync)(t))return[];let n=[];try{let o=(0,F.readdirSync)(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=Number(r.name);if(!Number.isInteger(s))continue;let a=(0,Q.join)(t,r.name),c=(0,F.readdirSync)(a).filter(d=>d.endsWith(".json")&&d!=="default.json").map(d=>d.replace(".json","")),l;try{l=(0,F.statSync)(a).mtime.toISOString()}catch{l=new Date().toISOString()}n.push({version:s,createdAt:l,locales:c})}}catch{return[]}return n.sort((o,r)=>r.version-o.version)}async getVersionFile(e,t,n){if(!this.profilesDir)return null;let o=(0,Q.join)(this.versionsRootDir(e),t),r=(0,Q.join)(o,`${n}.json`);if(!(0,F.existsSync)(r)){let s=(0,Q.join)(o,"default.json");return(0,F.existsSync)(s)?(0,F.readFileSync)(s,"utf8"):null}return(0,F.readFileSync)(r,"utf8")}async listArchivedProfiles(){if(!this.profilesDir)return[];let e=(0,Q.join)(this.profilesDir,this.tenantId);if(!(0,F.existsSync)(e))return[];let t=new Set((await this.profiles.list(this.tenantId)).map(r=>r.id)),n=[],o;try{o=(0,F.readdirSync)(e,{withFileTypes:!0})}catch{return[]}for(let r of o){if(!r.isDirectory()||t.has(r.name))continue;let s=(0,Q.join)(e,r.name);if((0,F.lstatSync)(s).isSymbolicLink())continue;let a;try{a=(0,F.readdirSync)(s,{withFileTypes:!0})}catch{continue}let c=a.filter(d=>d.isDirectory()&&Number.isInteger(Number(d.name)));if(c.length===0)continue;let l=new Date(0).toISOString();for(let d of c)try{let u=(0,F.statSync)((0,Q.join)(s,d.name)).mtime.toISOString();u>l&&(l=u)}catch{}n.push({id:r.name,versionCount:c.length,lastModified:l})}return n.sort((r,s)=>s.lastModified.localeCompare(r.lastModified))}toTemplateButtonMap(e){let t={};for(let[n,o]of Object.entries(e))t[n]={type:o.style,action:o.action,...o.cookies!==void 0?{cookies:o.cookies}:{}};return t}buildSeedUiTemplatePayload(e){let t={position:e.mainBanner.position,buttons:this.toTemplateButtonMap(e.mainBanner.buttons),...e.mainBanner.showClose!==void 0?{showClose:e.mainBanner.showClose}:{},...e.mainBanner.showLocaleSwitcher!==void 0?{showLocaleSwitcher:e.mainBanner.showLocaleSwitcher}:{}},n=e.gpcBanner?{position:e.gpcBanner.position,buttons:this.toTemplateButtonMap(e.gpcBanner.buttons),...e.gpcBanner.showClose!==void 0?{showClose:e.gpcBanner.showClose}:{},...e.gpcBanner.showLocaleSwitcher!==void 0?{showLocaleSwitcher:e.gpcBanner.showLocaleSwitcher}:{}}:t,o={buttons:this.toTemplateButtonMap(e.preferenceModal.buttons),...e.preferenceModal.position!==void 0?{position:e.preferenceModal.position}:{},...e.preferenceModal.persistent!==void 0?{persistent:e.preferenceModal.persistent}:{}};return{mainBanner:t,gpcBanner:n,preferenceModal:o}}async getOrCreateSeedTemplates(e,t,n){if(!this.storage)throw new Error("Storage adapter required to seed templates");let o=`Default \u2014 ${e}`,s=(await this.storage.getConsentTemplates(this.tenantId)).find(l=>l.name===o)??await this.storage.createConsentTemplate({tenantId:this.tenantId,name:o,cookies:t.cookies,categories:n.preferenceModal.categories}),c=(await this.storage.getUITemplates(this.tenantId)).find(l=>l.name===o)??await this.storage.createUITemplate({tenantId:this.tenantId,name:o,...this.buildSeedUiTemplatePayload(n)});return{consentTemplateId:s.id,uiTemplateId:c.id}}async seedDefaultProfile(e){if(await this.profiles.findActiveByComplianceGroup(this.tenantId,e))return;let{DEFAULT_PROFILES:n,resolveLocaleTranslation:o}=await Promise.resolve().then(()=>(Xn(),Wr)),r=n[e];if(!r)return;let s=r.translations.en;if(!s)return;let a=["de","es","fr","ja"],c=["en",...a.filter(m=>o(e,m)!==void 0)],l={};for(let m of a){let h=o(e,m);h&&(l[m]={mainBanner:h.mainBanner,...h.gpcBanner?{gpcBanner:h.gpcBanner}:{},preferenceModal:h.preferenceModal})}let{consentTemplateId:d,uiTemplateId:u}=await this.getOrCreateSeedTemplates(e,{cookies:r.cookies},s);await this.create({name:`Default \u2014 ${e}`,defaultLocale:r.defaultLocale,profileJson:{id:(0,C.randomUUID)(),defaultLocale:r.defaultLocale,complianceGroup:r.complianceGroup,gpcMode:r.gpcMode,cookies:r.cookies,consentTemplateId:d,uiTemplateId:u,...r.expiryDays!==void 0?{expiryDays:r.expiryDays}:{},locales:c,mainBanner:s.mainBanner,...s.gpcBanner?{gpcBanner:s.gpcBanner}:{},preferenceModal:s.preferenceModal,isActive:!0},...Object.keys(l).length>0?{localeContent:l}:{}})}async seedAllDefaults(){let{COMPLIANCE_GROUP_IDS:e}=await Promise.resolve().then(()=>(re(),os));await Promise.all(e.map(t=>this.seedDefaultProfile(t)))}};p();p();var ss={"Europe/Amsterdam":"NL","Europe/Andorra":"AD","Europe/Athens":"GR","Europe/Belgrade":"RS","Europe/Berlin":"DE","Europe/Bratislava":"SK","Europe/Brussels":"BE","Europe/Bucharest":"RO","Europe/Budapest":"HU","Europe/Busingen":"DE","Europe/Chisinau":"MD","Europe/Copenhagen":"DK","Europe/Dublin":"IE","Europe/Gibraltar":"GI","Europe/Guernsey":"GG","Europe/Helsinki":"FI","Europe/Isle_of_Man":"IM","Europe/Istanbul":"TR","Europe/Jersey":"JE","Europe/Kaliningrad":"RU","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Lisbon":"PT","Europe/Ljubljana":"SI","Europe/London":"GB","Europe/Luxembourg":"LU","Europe/Madrid":"ES","Europe/Malta":"MT","Europe/Mariehamn":"FI","Europe/Minsk":"BY","Europe/Monaco":"MC","Europe/Moscow":"RU","Europe/Nicosia":"CY","Europe/Oslo":"NO","Europe/Paris":"FR","Europe/Podgorica":"ME","Europe/Prague":"CZ","Europe/Riga":"LV","Europe/Rome":"IT","Europe/Samara":"RU","Europe/San_Marino":"SM","Europe/Sarajevo":"BA","Europe/Saratov":"RU","Europe/Simferopol":"UA","Europe/Skopje":"MK","Europe/Sofia":"BG","Europe/Stockholm":"SE","Europe/Tallinn":"EE","Europe/Tirane":"AL","Europe/Ulyanovsk":"RU","Europe/Uzhgorod":"UA","Europe/Vaduz":"LI","Europe/Vatican":"VA","Europe/Vienna":"AT","Europe/Vilnius":"LT","Europe/Volgograd":"RU","Europe/Warsaw":"PL","Europe/Zagreb":"HR","Europe/Zaporozhye":"UA","Europe/Zurich":"CH","Atlantic/Reykjavik":"IS","Atlantic/Faroe":"FO","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Anchorage":"US","America/Adak":"US","America/Honolulu":"US","America/Phoenix":"US","America/Detroit":"US","America/Indiana/Indianapolis":"US","America/Indiana/Knox":"US","America/Indiana/Marengo":"US","America/Indiana/Petersburg":"US","America/Indiana/Tell_City":"US","America/Indiana/Vevay":"US","America/Indiana/Vincennes":"US","America/Indiana/Winamac":"US","America/Kentucky/Louisville":"US","America/Kentucky/Monticello":"US","America/North_Dakota/Beulah":"US","America/North_Dakota/Center":"US","America/North_Dakota/New_Salem":"US","America/Boise":"US","America/Menominee":"US","America/Nome":"US","America/Sitka":"US","America/Yakutat":"US","America/Juneau":"US","America/Metlakatla":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Winnipeg":"CA","America/Halifax":"CA","America/St_Johns":"CA","America/Edmonton":"CA","America/Regina":"CA","America/Whitehorse":"CA","America/Yellowknife":"CA","America/Iqaluit":"CA","America/Moncton":"CA","America/Glace_Bay":"CA","America/Goose_Bay":"CA","America/Swift_Current":"CA","America/Dawson":"CA","America/Cambridge_Bay":"CA","America/Dawson_Creek":"CA","America/Fort_Nelson":"CA","America/Creston":"CA","America/Rankin_Inlet":"CA","America/Resolute":"CA","America/Pangnirtung":"CA","America/Nipigon":"CA","America/Mexico_City":"MX","America/Cancun":"MX","America/Monterrey":"MX","America/Merida":"MX","America/Chihuahua":"MX","America/Hermosillo":"MX","America/Mazatlan":"MX","America/Ojinaga":"MX","America/Bahia_Banderas":"MX","America/Matamoros":"MX","America/Tijuana":"MX","America/Sao_Paulo":"BR","America/Manaus":"BR","America/Belem":"BR","America/Fortaleza":"BR","America/Recife":"BR","America/Maceio":"BR","America/Bahia":"BR","America/Porto_Velho":"BR","America/Boa_Vista":"BR","America/Campo_Grande":"BR","America/Cuiaba":"BR","America/Santarem":"BR","America/Rio_Branco":"BR","America/Eirunepe":"BR","America/Noronha":"BR","America/Argentina/Buenos_Aires":"AR","America/Argentina/Cordoba":"AR","America/Argentina/Salta":"AR","America/Argentina/Jujuy":"AR","America/Argentina/Tucuman":"AR","America/Argentina/Catamarca":"AR","America/Argentina/La_Rioja":"AR","America/Argentina/San_Juan":"AR","America/Argentina/Mendoza":"AR","America/Argentina/San_Luis":"AR","America/Argentina/Rio_Gallegos":"AR","America/Argentina/Ushuaia":"AR","America/Bogota":"CO","America/Lima":"PE","America/Santiago":"CL","America/Caracas":"VE","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Guayaquil":"EC","America/Guyana":"GY","America/Paramaribo":"SR","America/Cayenne":"GF","America/Panama":"PA","America/Costa_Rica":"CR","America/Guatemala":"GT","America/El_Salvador":"SV","America/Tegucigalpa":"HN","America/Managua":"NI","America/Belize":"BZ","America/Havana":"CU","America/Jamaica":"JM","America/Nassau":"BS","America/Port_of_Spain":"TT","America/Santo_Domingo":"DO","America/Port-au-Prince":"HT","America/Barbados":"BB","America/Martinique":"MQ","America/Guadeloupe":"GP","America/Puerto_Rico":"PR","America/St_Kitts":"KN","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Colombo":"LK","Asia/Kathmandu":"NP","Asia/Kabul":"AF","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Shanghai":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Ulaanbaatar":"MN","Asia/Choibalsan":"MN","Asia/Hovd":"MN","Asia/Singapore":"SG","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Kuala_Lumpur":"MY","Asia/Manila":"PH","Asia/Ho_Chi_Minh":"VN","Asia/Saigon":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Rangoon":"MM","Asia/Yangon":"MM","Asia/Pontianak":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Kuching":"MY","Asia/Brunei":"BN","Asia/Dili":"TL","Asia/Tashkent":"UZ","Asia/Almaty":"KZ","Asia/Qyzylorda":"KZ","Asia/Aqtau":"KZ","Asia/Aqtobe":"KZ","Asia/Atyrau":"KZ","Asia/Oral":"KZ","Asia/Ashgabat":"TM","Asia/Dushanbe":"TJ","Asia/Bishkek":"KG","Asia/Yekaterinburg":"RU","Asia/Tehran":"IR","Asia/Baghdad":"IQ","Asia/Riyadh":"SA","Asia/Dubai":"AE","Asia/Kuwait":"KW","Asia/Qatar":"QA","Asia/Bahrain":"BH","Asia/Muscat":"OM","Asia/Beirut":"LB","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Amman":"JO","Asia/Damascus":"SY","Asia/Nicosia":"CY","Asia/Famagusta":"CY","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Tbilisi":"GE","Asia/Samarkand":"UZ","Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Lagos":"NG","Africa/Nairobi":"KE","Africa/Johannesburg":"ZA","Africa/Addis_Ababa":"ET","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Tripoli":"LY","Africa/Khartoum":"SD","Africa/Accra":"GH","Africa/Dar_es_Salaam":"TZ","Africa/Abidjan":"CI","Africa/Bamako":"ML","Africa/Banjul":"GM","Africa/Conakry":"GN","Africa/Dakar":"SN","Africa/Freetown":"SL","Africa/Lome":"TG","Africa/Monrovia":"LR","Africa/Nouakchott":"MR","Africa/Ouagadougou":"BF","Africa/Sao_Tome":"ST","Africa/Bissau":"GW","Africa/Bangui":"CF","Africa/Brazzaville":"CG","Africa/Douala":"CM","Africa/Kinshasa":"CD","Africa/Libreville":"GA","Africa/Luanda":"AO","Africa/Malabo":"GQ","Africa/Ndjamena":"TD","Africa/Niamey":"NE","Africa/Porto-Novo":"BJ","Africa/Blantyre":"MW","Africa/Bujumbura":"BI","Africa/Gaborone":"BW","Africa/Harare":"ZW","Africa/Kampala":"UG","Africa/Kigali":"RW","Africa/Lubumbashi":"CD","Africa/Lusaka":"ZM","Africa/Maputo":"MZ","Africa/Maseru":"LS","Africa/Mbabane":"SZ","Africa/Mogadishu":"SO","Africa/Windhoek":"NA","Africa/Asmara":"ER","Africa/Djibouti":"DJ","Africa/El_Aaiun":"EH","Africa/Juba":"SS","Africa/Ceuta":"ES","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Darwin":"AU","Australia/Hobart":"AU","Australia/Canberra":"AU","Australia/Broken_Hill":"AU","Australia/Lord_Howe":"AU","Australia/Lindeman":"AU","Australia/Eucla":"AU","Pacific/Auckland":"NZ","Pacific/Chatham":"NZ","Pacific/Fiji":"FJ","Pacific/Port_Moresby":"PG","Pacific/Bougainville":"PG","Pacific/Guam":"GU","Pacific/Saipan":"MP","Pacific/Pago_Pago":"AS","Pacific/Apia":"WS","Pacific/Tongatapu":"TO","Pacific/Fakaofo":"TK","Pacific/Niue":"NU","Pacific/Rarotonga":"CK","Pacific/Tahiti":"PF","Pacific/Marquesas":"PF","Pacific/Gambier":"PF","Pacific/Honolulu":"US","Pacific/Johnston":"US","Pacific/Midway":"UM","Pacific/Wake":"UM","Pacific/Tarawa":"KI","Pacific/Enderbury":"KI","Pacific/Kiritimati":"KI","Pacific/Efate":"VU","Pacific/Guadalcanal":"SB","Pacific/Noumea":"NC","Pacific/Nauru":"NR","Pacific/Palau":"PW","Pacific/Chuuk":"FM","Pacific/Pohnpei":"FM","Pacific/Kosrae":"FM","Pacific/Majuro":"MH","Pacific/Kwajalein":"MH","Pacific/Funafuti":"TV","Pacific/Wallis":"WF","Asia/Novosibirsk":"RU","Asia/Omsk":"RU","Asia/Krasnoyarsk":"RU","Asia/Irkutsk":"RU","Asia/Chita":"RU","Asia/Yakutsk":"RU","Asia/Khandyga":"RU","Asia/Vladivostok":"RU","Asia/Ust-Nera":"RU","Asia/Magadan":"RU","Asia/Sakhalin":"RU","Asia/Srednekolymsk":"RU","Asia/Kamchatka":"RU","Asia/Anadyr":"RU"};var nd={ar:"SA",cs:"CZ",da:"DK",de:"DE",el:"GR",fi:"FI",fr:"FR",he:"IL",hi:"IN",hu:"HU",id:"ID",it:"IT",ja:"JP",ko:"KR",nl:"NL",no:"NO",pl:"PL",pt:"BR",ro:"RO",ru:"RU",sv:"SE",th:"TH",tr:"TR",uk:"UA",vi:"VN",zh:"CN"},on=class{constructor(e,t){this.map=t;this.provider=e??"default",this.provider==="default"&&console.warn("[Consenti] geoDataProvider is unset (using the timezone/language heuristic) \u2014 this cannot resolve US state-level regions (California, Colorado, etc.), so US visitors always fall back to the country-level default (the strictest group, opt-out-strict) rather than their actual state law. Configure a geoip-capable provider (geoip, hosted-geoip-lite, or maxmind) for accurate US state routing in production.")}map;provider;setMap(e){this.map=e}async resolve(e){let t="",n,o,r=null,s;if(typeof this.provider=="function"){let l=await this.provider(e);t=l.country??"",n=l.region??void 0,r=l.locale,s=l.complianceGroup??void 0}else switch(this.provider){case"default":({country:t}=od(e.timezone)),t||({country:t,region:n}=id(e.language));break;case"geoip":({country:t,region:n}=await rd(e.ip));break;case"hosted-geoip-lite":({country:t,region:n}=await ad(e.ip));break;case"maxmind":({country:t,region:n}=await sd(e.ip));break}let a={country:t,complianceGroup:s??this.resolveGroup(t,n)};return n!==void 0&&(a.region=n),o!==void 0&&(a.regulation=o),r!==null&&(a.locale=r),this.resolveRequiresSensitiveOptIn(t,n)&&(a.requiresSensitiveOptIn=!0),a}countryEntry(e){return this.map.countries[e]}resolveGroup(e,t){if(!e)return"";let n=this.countryEntry(e);return n?t!==void 0?n.overriddenRegions?.[t]?.complianceGroup??n.complianceGroup:n.default??n.complianceGroup:""}resolveRequiresSensitiveOptIn(e,t){return!e||t===void 0?!1:this.countryEntry(e)?.overriddenRegions?.[t]?.requiresSensitiveOptIn===!0}};function id(i){let t=(i.split(",")[0]?.trim().split(";")[0]?.trim()??"").split("-");if(t.length>=2){let o=(t[t.length-1]??"").toUpperCase();if(/^[A-Z]{2}$/.test(o))return{country:o}}return{country:nd[(t[0]??"").toLowerCase()]??""}}function od(i){return{country:ss[i]??""}}async function rd(i){if(!i)return{country:""};try{let t=(await import("geoip-lite")).lookup(i),n={country:t?.country??""},o=t?.region;return o&&(n.region=o),n}catch{return console.warn("[Consenti] geoip-lite not installed \u2014 country detection skipped. Run: npm install geoip-lite"),{country:""}}}async function sd(i){if(!i)return{country:""};try{let e=await import("maxmind"),t=process.env.MAXMIND_DB_PATH??"./GeoLite2-City.mmdb",o=(await e.open(t)).get(i),r=o?.country?.iso_code??"",s=o?.subdivisions?.[0]?.iso_code,a={country:r};return s&&(a.region=s),a}catch{return console.warn("[Consenti] maxmind not available \u2014 country detection skipped. See HOW_TO_MAXMIND.md"),{country:""}}}async function ad(i){return i?new Promise(e=>{import("node:https").then(({default:t})=>{let n=`https://ipinfo.io/${encodeURIComponent(i)}/json`,o=t.get(n,{timeout:3e3},r=>{let s=[];r.on("data",a=>s.push(a)),r.on("end",()=>{try{let a=JSON.parse(Buffer.concat(s).toString()),c={country:a.country??""};a.region&&(c.region=a.region),e(c)}catch{e({country:""})}})});o.on("error",()=>e({country:""})),o.on("timeout",()=>{o.destroy(),e({country:""})})}).catch(()=>e({country:""}))}):{country:""}}p();re();var cd=1440*60*1e3;function ld(i){let e=i?.headers.get("cache-control")?.match(/max-age=(\d+)/)?.[1];if(e){let n=parseInt(e,10)*1e3;if(!isNaN(n)&&n>0)return n}let t=i?.headers.get("expires");if(t){let n=Date.parse(t)-Date.now();if(!isNaN(n)&&n>0)return n}return cd}function as(i,e){let t,n=async()=>{let{map:o,response:r}=await ni(i,s=>console.error("[Consenti]",s));e.setMap(o),typeof i=="string"&&(t=setTimeout(()=>{n()},ld(r)),t.unref())};return n(),{stop:()=>{t&&clearTimeout(t)}}}p();var Re=require("node:fs"),li=require("node:path");p();var H=require("node:fs"),cs=require("node:path");function ls(i,e,t){let n=i+".bak",o=i+".tmp";(0,H.mkdirSync)((0,cs.dirname)(i),{recursive:!0});let r=(0,H.existsSync)(i);r&&(0,H.copyFileSync)(i,n);try{(0,H.writeFileSync)(o,JSON.stringify(e,null,2),"utf8");let s=JSON.parse((0,H.readFileSync)(o,"utf8"));if(!t(s))throw new Error("Schema validation failed for "+i);if((0,H.renameSync)(o,i),r)try{(0,H.unlinkSync)(n)}catch{}}catch(s){if(r)try{(0,H.copyFileSync)(n,i),(0,H.unlinkSync)(n)}catch{}try{(0,H.unlinkSync)(o)}catch{}throw s}}function ds(i){return typeof i=="object"&&i!==null&&typeof i.id=="string"&&typeof i.version=="number"}var rn=class{constructor(e){this.dir=e}dir;read(e,t){let n=this.path(e,t);if(!(0,Re.existsSync)(n))return null;try{let o=JSON.parse((0,Re.readFileSync)(n,"utf8"));return ds(o)?o:null}catch{return null}}write(e,t,n){ls(this.path(e,t),n,ds)}rebuild(e,t){for(let[n,o]of t)try{this.write(e,n,o)}catch(r){console.warn(`[Consenti] locale cache rebuild failed for ${e}/${n}:`,r)}}invalidate(e){try{let t=`${e}_`;for(let n of(0,Re.readdirSync)(this.dir))if(n.startsWith(t)&&n.endsWith(".json"))try{(0,Re.unlinkSync)((0,li.join)(this.dir,n))}catch{}}catch{}}path(e,t){return(0,li.join)(this.dir,`${e}_${t}.json`)}};p();p();re();function us(i,e,t){let n=[];for(let[o,r]of Object.entries(i.consentJson)){if(!e[o])continue;let s=Me(o,t);s==="mandatory"&&r!=="granted"&&n.push(`Cookie "${o}" is mandatory and cannot be "${r}"`),r==="objected"&&s!=="legitimate_interest"&&n.push(`Cookie "${o}" has legal basis "${s}" \u2014 'objected' is only valid for 'legitimate_interest'`)}return{valid:n.length===0,errors:n}}function di(i,e,t,n,o){let r={};for(let[s,a]of Object.entries(i)){if(ei(s,e)){r[s]="granted";continue}if(o==="cpra"){if(a.cpraCategory==="sensitive"){let l=t[s];r[s]=l==="granted"||l==="denied"||l==="objected"?l:"denied";continue}if(n&&(a.cpraCategory==="sale"||a.cpraCategory==="sharing")){r[s]="denied";continue}}if(n&&a.listenGpc&&o!=="dpdpa"){r[s]="denied";continue}let c=t[s];c==="granted"||c==="denied"||c==="objected"?r[s]=c:r[s]="denied"}return r}function ui(i){let e=Object.keys(i.consentJson).sort().map(t=>`${t}=${i.consentJson[t]}`).join(",");return`${i.tenantId}|${i.visitorId}|${i.profileId}|${i.locale}|${e}`}function ps(i,e,t,n){let o=[];return(!t||t.id!==e.id)&&o.push("profile_changed"),dd(i,e)&&o.push("consent_expired"),n&&i.signature&&ae(ui(i),n)!==i.signature&&o.push("hmac_invalid"),{valid:o.length===0,reasons:o,...t?{currentProfileId:t.id}:{},consentProfileId:e.id}}function ms(i,e){let t=new Set,n=new Set;for(let[o,r]of Object.entries(i))if(e[o]==="granted"){r.tcfVendorId&&t.add(r.tcfVendorId);for(let s of r.tcfPurposes??[])n.add(s)}return{vendorConsents:[...t].sort((o,r)=>o-r),purposeConsents:[...n].sort((o,r)=>o-r)}}function dd(i,e){let t=e.profileJson.expiryDays;if(!t)return!1;let o=new Date(i.createdAt).getTime()+t*24*60*60*1e3;return Date.now()>o}re();p();var gs=!1,sn=null,fs=!1;async function ud(){if(gs)return sn;gs=!0;try{sn=await import("@iabtechlabtcf/core")}catch{sn=null}return sn}function pd(i,e){let t=new Set,n=new Set;for(let o of i){let r=e.vendors[String(o)];if(r?.legIntPurposes?.length){t.add(o);for(let s of r.legIntPurposes)n.add(s)}}return{vendorLegitimateInterests:[...t].sort((o,r)=>o-r),purposeLegitimateInterests:[...n].sort((o,r)=>o-r)}}async function hs(i){let e=await ud();if(!e)return fs||(fs=!0,console.warn('[consenti] TCF is enabled but the optional "@iabtechlabtcf/core" dependency is not installed. Falling back to a simplified, non-spec-compliant TC string. Run `npm install @iabtechlabtcf/core` to produce real IAB-spec binary TC strings.')),null;let{TCModel:t,TCString:n,GVL:o}=e,r=new o(i.gvl.raw),s=new t(r);s.cmpId=i.cmpId,s.cmpVersion=i.cmpVersion,s.consentScreen=i.consentScreen,s.consentLanguage=i.consentLanguage,s.publisherCountryCode=i.publisherCC,s.isServiceSpecific=i.isServiceSpecific,s.purposeConsents.set(i.purposeConsents),s.vendorConsents.set(i.vendorConsents);let{vendorLegitimateInterests:a,purposeLegitimateInterests:c}=pd(i.vendorConsents,i.gvl);return s.purposeLegitimateInterests.set(c),s.vendorLegitimateInterests.set(a),s.vendorsDisclosed.set(i.vendorConsents),n.encode(s)}p();var ys=require("node:crypto");function nt(i){let e=Object.keys(i).sort().map(t=>`${t}=${i[t]??""}`).join("&");return(0,ys.createHash)("sha256").update(e).digest("hex")}function le(i,e,t){return i?t?t.configHash===nt(e):!1:!0}p();re();var _s=!1,an=null,ws=!1;async function md(){if(_s)return an;_s=!0;try{an=await import("@iabgpp/cmpapi")}catch{an=null}return an}var Es=0,Rs=1,gd=2;function cn(i){return i?Rs:Es}function pi(i,e){return i?e?Rs:gd:Es}async function fd(i){let e=await md();if(!e)return null;let{GppModel:t}=e,n=new t;return n.setFieldValue("usnat","SharingNotice",cn(i.sharingApplicable)),n.setFieldValue("usnat","SaleOptOutNotice",cn(i.saleApplicable)),n.setFieldValue("usnat","SharingOptOutNotice",cn(i.sharingApplicable)),n.setFieldValue("usnat","TargetedAdvertisingOptOutNotice",cn(i.sharingApplicable)),n.setFieldValue("usnat","SaleOptOut",pi(i.saleApplicable,i.saleOptOut)),n.setFieldValue("usnat","SharingOptOut",pi(i.sharingApplicable,i.sharingOptOut)),n.setFieldValue("usnat","TargetedAdvertisingOptOut",pi(i.sharingApplicable,i.sharingOptOut)),n.setFieldValue("usnat","MspaCoveredTransaction",i.mspaCoveredTransaction?1:2),n.setFieldValue("usnat","MspaOptOutOptionMode",i.mspaOptOutOptionMode),n.setFieldValue("usnat","MspaServiceProviderMode",i.mspaServiceProviderMode),i.gpcDetected!==void 0&&(n.setFieldValue("usnat","GpcSegmentIncluded",!0),n.setFieldValue("usnat","Gpc",i.gpcDetected)),n.encode()}async function Ss(i){let e=await fd(i);return e||(ws||(ws=!0,console.warn('[consenti] GPP is enabled but the optional "@iabgpp/cmpapi" dependency is not installed. Falling back to a simplified, non-spec-compliant GPP string. Run `npm install @iabgpp/cmpapi` to produce real IAB-spec binary GPP strings.')),ai(i))}var ln=class{constructor(e,t,n,o,r="default",s,a,c,l,d,u,m){this.consents=e;this.visitors=t;this.profiles=n;this.audit=o;this.tenantId=r;this.compliance=s;this.pluginEngine=a;this.eventBus=c;this.tcfConfig=l;this.storage=d;this.dataSigningHash=u;this.gppConfig=m}consents;visitors;profiles;audit;tenantId;compliance;pluginEngine;eventBus;tcfConfig;storage;dataSigningHash;gppConfig;sign(e){if(this.dataSigningHash)return ae(ui(e),this.dataSigningHash)}async isTcfConfirmed(){if(!this.tcfConfig?.enabled)return!0;if(!this.storage)return!1;let e=await this.storage.getSettings(this.tenantId);return le(!0,{cmpId:this.tcfConfig.cmpId,cmpVersion:this.tcfConfig.cmpVersion,publisherCC:this.tcfConfig.publisherCC},e.tcfConfirmation)}async isGppConfirmed(){if(!this.gppConfig?.enabled)return!0;if(!this.storage)return!1;let e=await this.storage.getSettings(this.tenantId);return le(!0,{cmpId:this.gppConfig.cmpId,cmpVersion:this.gppConfig.cmpVersion},e.gppConfirmation)}async resolveTemplateData(e){let t=!e.cookies,n=!e.preferenceModal?.categories,o=(t||n)&&e.consentTemplateId&&this.storage?await this.storage.getConsentTemplate(e.consentTemplateId):null;return{cookies:e.cookies??(o?ci(o.cookies,e.cookiesOverride):{}),categories:e.preferenceModal?.categories??o?.categories??{}}}async create(e){let t=await this.profiles.get(e.profileId);if(!t)throw new Error(`Profile ${e.profileId} not found`);let n=t.profileJson.regulation,{cookies:o,categories:r}=await this.resolveTemplateData(t.profileJson),s=xe(r),a=e.consentJson;if(e.gpcDetected&&this.compliance?.gpc!==!1&&n!=="dpdpa"){a={...a};for(let[N,se]of Object.entries(o))n==="cpra"?(se.cpraCategory==="sale"||se.cpraCategory==="sharing")&&(a[N]="denied"):se.listenGpc&&(a[N]="denied")}let c=us({...e,consentJson:a},o,s);if(!c.valid)throw new Error(c.errors.join("; "));let l=di(o,s,a,e.gpcDetected,n),d,u=this.tcfConfig,m=u?.enabled&&Object.values(o).some(N=>N.tcfVendorId),h=m?await this.isTcfConfirmed():!0;if(u&&m&&!h)console.error(`[Consenti] TCF is enabled (cmpId=${u.cmpId}, cmpVersion=${u.cmpVersion}) but this registration is unconfirmed \u2014 treating TCF as disabled for this consent write (no tcfString generated). Confirm the current cmpId/cmpVersion in the dashboard's TCF Registration panel to re-enable.`);else if(u&&m){let N=await Ae(),{vendorConsents:se,purposeConsents:ne}=ms(o,l),Fe=e.locale?.slice(0,2)??"en";d=u.publisherCC&&N?await hs({cmpId:u.cmpId,cmpVersion:u.cmpVersion,consentScreen:1,consentLanguage:Fe,publisherCC:u.publisherCC,isServiceSpecific:!0,purposeConsents:ne,vendorConsents:se,gvl:N})??void 0:void 0,d||(d=ri({cmpId:u.cmpId,cmpVersion:u.cmpVersion,consentScreen:1,consentLanguage:Fe,vendorListVersion:N?.vendorListVersion??0,purposeConsents:ne,vendorConsents:se}))}let S,_=this.gppConfig,w=Object.values(o).some(N=>N.cpraCategory==="sale"),R=Object.values(o).some(N=>N.cpraCategory==="sharing"),v=_?.enabled&&(w||R),A=v?await this.isGppConfirmed():!0;if(_&&v&&!A)console.error(`[Consenti] GPP is enabled (cmpId=${_.cmpId}, cmpVersion=${_.cmpVersion}) but this registration is unconfirmed \u2014 treating GPP as disabled for this consent write (no gppString generated). Confirm the current cmpId/cmpVersion in the dashboard's GPP Registration panel to re-enable.`);else if(_&&v){let N=!w||Object.entries(o).filter(([,ne])=>ne.cpraCategory==="sale").every(([ne])=>l[ne]!=="granted"),se=!R||Object.entries(o).filter(([,ne])=>ne.cpraCategory==="sharing").every(([ne])=>l[ne]!=="granted");S=await Ss({cmpId:_.cmpId,cmpVersion:_.cmpVersion,mspaCoveredTransaction:_.mspaCoveredTransaction,mspaOptOutOptionMode:_.mspaOptOutOptionMode,mspaServiceProviderMode:_.mspaServiceProviderMode,saleOptOut:N,saleApplicable:w,sharingOptOut:se,sharingApplicable:R,gpcDetected:e.gpcDetected})}let P=this.sign({tenantId:this.tenantId,visitorId:e.visitorId,profileId:e.profileId,locale:e.locale,consentJson:l}),O={...e,tenantId:this.tenantId,consentJson:l,...d?{tcfString:d}:{},...S?{gppString:S}:{},...P?{signature:P}:{}};this.pluginEngine&&(O=await this.pluginEngine.runBeforeConsentSave(O));let D=await this.consents.get(e.visitorId),G;if(D){let N=await(this.pluginEngine?this.pluginEngine.runBeforeConsentUpdate({consentJson:l,locale:e.locale,gpcDetected:e.gpcDetected,...P?{signature:P}:{}}):Promise.resolve({consentJson:l,locale:e.locale,gpcDetected:e.gpcDetected,...P?{signature:P}:{}}));G=await this.consents.update(e.visitorId,N)}else G=await this.consents.create(O);return await this.audit.log({tenantId:this.tenantId,action:D?"consent:updated":"consent:created",resourceType:"consent",resourceId:G.id,...D!=null?{oldData:D}:{},newData:G}),D?(this.eventBus?.emit("consent:updated",{previous:D,current:G}),await this.pluginEngine?.runAfterConsentUpdate(G)):(this.eventBus?.emit("consent:created",G),await this.pluginEngine?.runAfterConsentSave(G)),G}async update(e,t){let n=await this.consents.get(e);if(!n)throw new Error(`Consent for visitor ${e} not found`);let o=await this.profiles.get(n.profileId);if(!o)throw new Error(`Profile ${n.profileId} not found`);let r=o.profileJson.regulation,{cookies:s,categories:a}=await this.resolveTemplateData(o.profileJson),c=xe(a),l=t.gpcDetected??n.gpcDetected,d=t.consentJson;if(l&&this.compliance?.gpc!==!1&&r!=="dpdpa"){d={...d};for(let[w,R]of Object.entries(s))r==="cpra"?(R.cpraCategory==="sale"||R.cpraCategory==="sharing")&&(d[w]="denied"):R.listenGpc&&(d[w]="denied")}let u=di(s,c,d,l,r),m=this.sign({tenantId:this.tenantId,visitorId:e,profileId:n.profileId,locale:t.locale??n.locale,consentJson:u}),h={consentJson:u,...t.locale!==void 0?{locale:t.locale}:{},...t.gpcDetected!==void 0?{gpcDetected:t.gpcDetected}:{},...m?{signature:m}:{}},S=await(this.pluginEngine?this.pluginEngine.runBeforeConsentUpdate(h):Promise.resolve(h)),_=await this.consents.update(e,S);return await this.audit.log({tenantId:this.tenantId,action:"consent:updated",resourceType:"consent",resourceId:_.id,oldData:n,newData:_}),this.eventBus?.emit("consent:updated",{previous:n,current:_}),await this.pluginEngine?.runAfterConsentUpdate(_),_}get(e){return this.consents.get(e)}async verify(e){let t=await this.consents.get(e);if(!t)return{valid:!1,reasons:["profile_changed"]};let n=await this.profiles.get(t.profileId);if(!n)return{valid:!1,reasons:["profile_changed"]};let o=n.profileJson.complianceGroup,r=o?await this.profiles.findActiveByComplianceGroup(this.tenantId,o):null;return ps(t,n,r,this.dataSigningHash)}async erase(e){let t=await this.consents.get(e);await this.consents.delete(e),await this.visitors.delete(e),await this.audit.log({tenantId:this.tenantId,action:"consent:erased",resourceType:"consent",resourceId:e,...t!=null?{oldData:t}:{}}),this.eventBus?.emit("consent:erased",{visitorId:e})}};p();var dn=class{constructor(e,t="default",n,o=""){this.visitors=e;this.tenantId=t;this.eventBus=n;this.dataSigningHash=o}visitors;tenantId;eventBus;dataSigningHash;async upsert(e){if(await this.visitors.get(e.visitorId))return this.visitors.update(e.visitorId,{...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{}});let n={tenantId:this.tenantId,visitorId:e.visitorId,...e.country!=null?{country:e.country}:{},...e.region!=null?{region:e.region}:{},...e.city!=null?{city:e.city}:{},...e.ip?{ipHash:Wi(e.ip,this.dataSigningHash)}:{},...e.userAgent?{userAgentHash:qi(e.userAgent)}:{}},o=await this.visitors.create(n);return this.eventBus?.emit("visitor:created",o),o}};p();var un=class{constructor(e,t="default"){this.notices=e;this.tenantId=t}notices;tenantId;recordShown(e){return this.notices.create({tenantId:this.tenantId,...e})}getForVisitor(e){return this.notices.getForVisitor(e)}};p();var pn=class{constructor(e,t,n="default"){this.users=e;this.audit=t;this.tenantId=n}users;audit;tenantId;safe(e){let{passwordHash:t,...n}=e;return n}async create(e,t){let n=await this.users.create({tenantId:this.tenantId,name:e.name,email:e.email,passwordHash:Je(e.password),...e.allowedTenants?{allowedTenants:e.allowedTenants}:{}});return e.roleId&&await this.users.assignRole(n.id,e.roleId),await this.audit.log({tenantId:this.tenantId,...t!=null?{userId:t}:{},action:"user.created",resourceType:"user",resourceId:n.id,newData:this.safe(n)}),this.safe(n)}async update(e,t,n){let o=await this.users.getById(e);if(!o)throw new Error(`User ${e} not found`);let r={};t.name!=null&&(r.name=t.name),t.email!=null&&(r.email=t.email),t.isActive!=null&&(r.isActive=t.isActive),t.password&&(r.passwordHash=Je(t.password)),t.allowedTenants!=null&&(r.allowedTenants=t.allowedTenants);let s=await this.users.update(e,r);return await this.audit.log({tenantId:this.tenantId,...n!=null?{userId:n}:{},action:"user.updated",resourceType:"user",resourceId:e,oldData:this.safe(o),newData:this.safe(s)}),this.safe(s)}async delete(e,t){let n=await this.users.getById(e);await this.users.delete(e),await this.audit.log({tenantId:this.tenantId,...t!=null?{userId:t}:{},action:"user.deleted",resourceType:"user",resourceId:e,...n!=null?{oldData:this.safe(n)}:{}})}async get(e){let t=await this.users.getById(e);return t?this.safe(t):null}async list(){return(await this.users.list(this.tenantId)).map(t=>this.safe(t))}getRoles(e,t){return this.users.getRoles(e,t)}assignRole(e,t,n){return this.users.assignRole(e,t,n)}revokeRole(e,t,n){return this.users.revokeRole(e,t,n)}};p();var vs=15*6e4,hd=5,Cs=1800,mn=class{constructor(e,t){this.storage=e;this.secret=t;setInterval(()=>{let n=Date.now();for(let[o,r]of this.loginAttempts)n>=r.resetAt&&this.loginAttempts.delete(o)},vs).unref()}storage;secret;loginAttempts=new Map;async bootstrap(e,t){if(await this.storage.countUsers("default")>0)return null;if(t.length<12)throw new Error("[Consenti] bootstrap: admin password must be at least 12 characters");t.length<16&&console.warn("[Consenti] bootstrap: admin password is shorter than 16 characters \u2014 consider using a longer password");let o=Je(t),r=await this.storage.createUser({tenantId:"default",name:"Admin",email:e,passwordHash:o});return await this.storage.assignRole(r.id,"role_super_admin"),r}async login(e,t){let n=Date.now(),o=this.loginAttempts.get(e);if(o&&n<o.resetAt&&o.count>=hd)return null;let r=await this.storage.getUserByEmail(e);if(!r||!r.isActive||!Ji(t,r.passwordHash)){let l=this.loginAttempts.get(e);return!l||n>=l.resetAt?this.loginAttempts.set(e,{count:1,resetAt:n+vs}):l.count+=1,null}this.loginAttempts.delete(e);let s=await this.storage.getUserRoles(r.id),a=await Promise.all(s.map(l=>this.storage.getPermissionsForRole(l.id))),c=[...new Set(a.flat().map(l=>l.name))];return On({sub:r.id,email:r.email,roles:s.map(l=>l.name),permissions:c,allowedTenants:r.allowedTenants??[]},this.secret,Cs)}signToken(e){return On(e,this.secret,Cs)}verify(e){return yt(e,this.secret)}async getUser(e){let t=this.verify(e);if(!t)return null;let n=t.sub;return typeof n!="string"?null:this.storage.getUserById(n)}};p();p();var it=class extends Error{constructor(){super("Payload Too Large")}};function yd(i,e){let t=i.socket?.remoteAddress??"";if(!e?.length||!e.includes(t))return t;let n=i.headers["x-forwarded-for"];return typeof n=="string"?n.split(",")[0]?.trim()??t:Array.isArray(n)?n[0]?.trim()??t:t}function y(i,e){return new Response(JSON.stringify(e),{status:i,headers:{"Content-Type":"application/json"}})}async function I(i){if(!(i.headers.get("content-type")??"").includes("application/json"))return null;try{return await i.json()}catch{return null}}function U(i,e){return i.searchParams.get(e)??void 0}function gn(i,e,t){let n=i.searchParams.get(e);if(!n)return t;let o=parseInt(n,10);return isNaN(o)?t:o}var As=500;function Ue(i,e=50){let t=gn(i,"limit",e);return t<1||t>As?{error:`limit must be between 1 and ${As}`}:{page:Math.max(1,gn(i,"page",1)),limit:t}}async function Ps(i,e=1048576,t){let o=i.headers["x-forwarded-proto"]==="https"?"https":"http",r=i.headers.host??"localhost",s=new URL(i.url??"/",`${o}://${r}`),a=new Headers;for(let[d,u]of Object.entries(i.headers))if(u)if(Array.isArray(u))for(let m of u)a.append(d,m);else a.set(d,u);a.set("x-real-ip",yd(i,t));let c=null,l=(i.method??"GET").toUpperCase();if(l!=="GET"&&l!=="HEAD"){let d=[],u=0;for await(let m of i){if(u+=m.length,u>e)throw new it;d.push(m)}d.length>0&&(c=Buffer.concat(d))}return new Request(s.toString(),{method:l,headers:a,body:c})}async function Ts(i,e){e.statusCode=i.status;let t=typeof i.headers.getSetCookie=="function"?i.headers.getSetCookie():i.headers.get("set-cookie")?[i.headers.get("set-cookie")]:[];i.headers.forEach((n,o)=>{o.toLowerCase()!=="set-cookie"&&e.setHeader(o,n)});for(let n of t)e.appendHeader("set-cookie",n);if(i.body){let n=i.body.getReader();try{for(;;){let{done:o,value:r}=await n.read();if(o)break;e.write(Buffer.from(r))}}finally{n.releaseLock()}e.end()}else e.end()}p();function g(i,e,t){let n={error:e};return t!=null&&(n.details=t),new Response(JSON.stringify(n),{status:i,headers:{"Content-Type":"application/json"}})}async function E(i){try{return await i()}catch(e){let t=e instanceof Error?e.message:"Internal Server Error";return g(500,"Internal Server Error",process.env.NODE_ENV!=="production"?t:void 0)}}var be=require("node:fs"),ot=require("node:path"),_d="public, max-age=3600, stale-while-revalidate=60",Is={"Content-Type":"application/json","Cache-Control":_d};function wd(i){let e=(0,be.readFileSync)(i,"utf8");return new Response(e,{headers:Is})}function Ed(i,e,t){return new Response(null,{status:303,headers:{Location:`${i}/profiles/${e}/${t}/default`}})}function bs(i,e,t,n=""){return{"GET /profiles/:tenantId/:complianceGroupOrProfileId/:locale":async(o,r)=>E(async()=>{let{tenantId:s,complianceGroupOrProfileId:a,locale:c}=r;if(!s||!a||!c)return g(400,"Missing path parameters");if(t){let d=(0,ot.join)(t,s,a,`${c}.json`);if((0,be.existsSync)(d))return wd(d);let u=(0,ot.join)(t,s,a,"default.json");if((0,be.existsSync)(u))return Ed(n,s,a)}let l=await i.getResolved(a,c);return l?y(200,l):g(404,"Profile not found")}),"GET /profiles/:tenantId/:profileId/:entryId/:locale":async(o,r)=>E(async()=>{let{profileId:s,entryId:a,locale:c}=r;if(!s||!a||!c)return g(400,"Missing path parameters");let l=await i.getVersionFile(s,a,c);return l?new Response(l,{headers:Is}):g(404,"Version not found")}),"GET /resolve-profile":async(o,r)=>E(async()=>{if(!e)return g(501,"Geo compliance routing not configured");let s=new URL(o.url),a=o.headers.get("x-forwarded-for")?.split(",")[0]?.trim()??o.headers.get("x-real-ip")??"",c=s.searchParams.get("tz")??"",l=s.searchParams.get("lang")??o.headers.get("accept-language")??"",d=s.searchParams.get("locale")??"",u=s.searchParams.get("data");if(u)try{let D=JSON.parse(Buffer.from(u,"base64").toString("utf8"));D.timezone&&(c=D.timezone),D.language&&(l=D.language),D.locale&&(d=D.locale)}catch{}let m=await e.resolve({ip:a,language:l,timezone:c}),h=m.requiresSensitiveOptIn?{requiresSensitiveOptIn:!0}:{};if(!m.complianceGroup)return y(200,{path:null,complianceGroup:"opt-in",locale:d||"en",found:!1,...h});let S=await i.findActiveByComplianceGroup(m.complianceGroup);if(!S)return y(200,{path:null,complianceGroup:m.complianceGroup,locale:d||"en",found:!1,...h});let _=S.profileJson.locales??[],w=S.defaultLocale;if(d&&_.includes(d))w=d;else if(_.length>0){let D=(d||l).split("-")[0]??"",G=_.find(N=>N===D||N.startsWith(`${D}-`));G&&(w=G)}let R=m.complianceGroup,v=S.tenantId,A=!1,P=t?(0,ot.join)(t,v,R,`${w}.json`):"";if(t&&(0,be.existsSync)(P))A=!0;else if(t){let D=(0,ot.join)(t,v,R,`${S.defaultLocale}.json`);(0,be.existsSync)(D)&&(w=S.defaultLocale,P=D,A=!0)}let O=A?`${n}/profiles/${v}/${R}/${w}`:null;return y(200,{path:O,complianceGroup:R,locale:w,found:A,...h})}),"GET /profiles/:id":async(o,r)=>E(async()=>{let s=r.id;if(!s)return g(400,"Missing profile id");let a=await i.getResolved(s);return a?y(200,a):g(404,"Profile not found")}),"GET /profiles/:id/:locale":async(o,r)=>E(async()=>{let{id:s,locale:a}=r;if(!s)return g(400,"Missing profile id");let c=await i.getResolved(s,a);return c?y(200,c):g(404,"Profile not found")}),"GET /profiles/auto/:locale":async(o,r)=>E(async()=>{if(!e)return g(501,"Geo compliance routing not configured");let s=r.locale??"en",a=new URL(o.url),c=o.headers.get("x-forwarded-for")?.split(",")[0]?.trim()??o.headers.get("x-real-ip")??"",l=a.searchParams.get("tz")??"",d=o.headers.get("accept-language")??a.searchParams.get("lang")??"",u=await e.resolve({ip:c,language:d,timezone:l});if(!u.complianceGroup)return g(404,"Could not resolve compliance group for this location");let m=await i.findActiveByComplianceGroup(u.complianceGroup);if(!m)return g(404,`No active profile found for compliance group: ${u.complianceGroup}`);let h=await i.getResolved(m.id,s);return h?y(200,{...h,resolvedComplianceGroup:u.complianceGroup,...u.requiresSensitiveOptIn?{requiresSensitiveOptIn:!0}:{}}):g(404,"Profile not found")})}}p();p();function Os(){return process.env.NODE_ENV==="production"?"SameSite=None; Secure":"SameSite=Lax"}function Rd(i,e,t){let n=ae(`${i}.${e}`,t);return`${e}.${n}`}function mi(i,e,t){let n=`consenti_${i}`,o=Rd(i,e,t);return`${n}=${o}; ${Os()}; Path=/; Max-Age=31536000`}function Ds(i){return`${`consenti_${i}`}=; ${Os()}; Path=/; Max-Age=0`}function ks(i,e,t){let n=i.split(".");if(n.length!==2)return!1;let[o,r]=n;return!o||!r?!1:ht(`${e}.${o}`,r,t)}p();var fn="pcon_";function Sd(i){return Buffer.from(JSON.stringify(i),"utf8").toString("base64url")}function vd(i){try{let e=JSON.parse(Buffer.from(i,"base64url").toString("utf8"));return typeof e.visitorId!="string"||typeof e.profileId!="string"||typeof e.issuedAt!="number"?null:{visitorId:e.visitorId,profileId:e.profileId,issuedAt:e.issuedAt}}catch{return null}}function Ls(i,e,t){let n={visitorId:i,profileId:e,issuedAt:Math.round(Date.now()/1e3)},o=Sd(n);if(!t)return`${fn}${o}`;let r=ae(o,t);return`${fn}${o}.${r}`}function Ns(i,e,t){if(!i.startsWith(fn))return{valid:!1,reason:"malformed"};let n=i.slice(fn.length),o=n.indexOf("."),r=o===-1?n:n.slice(0,o),s=o===-1?void 0:n.slice(o+1);if(e&&(!s||!ht(r,s,e)))return{valid:!1,reason:"invalid_signature"};let a=vd(r);return a?t>0&&Math.round(Date.now()/1e3)-a.issuedAt>t*24*60*60?{valid:!1,reason:"expired"}:{valid:!0,visitorId:a.visitorId,profileId:a.profileId}:{valid:!1,reason:"malformed"}}p();function Cd(i){if(!i.includes("://"))return i;try{return new URL(i).hostname}catch{return i}}function xs(i,e){let t;try{t=new URL(i).hostname}catch{return!1}return e.some(n=>{if(n.startsWith("*.")){let o=n.slice(1);return t===n.slice(2)||t.endsWith(o)}return t===Cd(n)})}function Ms(i,e){let t=i??"*";return e&&e.length>0&&i&&(t=xs(i,e)?i:"null"),{"Access-Control-Allow-Origin":t,"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Credentials":"true"}}function Us(i){if(i.method==="OPTIONS"){let e=i.headers.get("origin");return new Response(null,{status:204,headers:Ms(e)})}return null}function rt(i,e){let t=e.headers.get("origin"),n=Ms(t),o=new Headers(i.headers);for(let[r,s]of Object.entries(n))o.set(r,s);return new Response(i.body,{status:i.status,statusText:i.statusText,headers:o})}function hn(i,e){if(e.length===0)return!0;let t=i.headers.get("origin");return t?xs(t,e):!0}var Ad=["default-src 'self'","script-src 'self' https://unpkg.com","style-src 'self' https://unpkg.com 'unsafe-inline'","img-src 'self' data:","font-src 'self'","connect-src 'self'","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");function gi(i){let e=new Headers(i.headers);return e.set("X-Content-Type-Options","nosniff"),e.set("X-Frame-Options","DENY"),e.set("Referrer-Policy","no-referrer"),e.set("Permissions-Policy","interest-cohort=()"),e.set("Content-Security-Policy",Ad),e.set("Strict-Transport-Security","max-age=63072000; includeSubDomains; preload"),new Response(i.body,{status:i.status,statusText:i.statusText,headers:e})}p();var Pd=new Set(["granted","denied","objected"]);function Gs(i){let e=Object.entries(i);for(let[t,n]of e){if(!t)return{valid:!1,error:"consentJson keys must be non-empty strings"};if(!Pd.has(n))return{valid:!1,error:`consentJson value "${String(n)}" is invalid; must be granted, denied, or objected`}}return{valid:!0}}function js(i){if(!i||typeof i!="object")return{valid:!1,error:"Request body must be a JSON object"};let e=i;return typeof e.profileId!="string"||!e.profileId?{valid:!1,error:"profileId is required"}:!e.consentJson||typeof e.consentJson!="object"||Array.isArray(e.consentJson)?{valid:!1,error:"consentJson must be an object"}:Gs(e.consentJson)}function Bs(i){if(!i||typeof i!="object")return{valid:!1,error:"Request body must be a JSON object"};let e=i;return!e.consentJson||typeof e.consentJson!="object"||Array.isArray(e.consentJson)?{valid:!1,error:"consentJson must be an object"}:Gs(e.consentJson)}function Fs(i,e,t){return{tenantId:t,visitorId:e,profileId:i.profileId,locale:typeof i.locale=="string"?i.locale:"en",consentJson:i.consentJson,gpcDetected:!!i.gpcDetected,source:i.source??"banner",...typeof i.ageVerified=="boolean"?{ageVerified:i.ageVerified}:{},...typeof i.parentalConsentToken=="string"?{parentalConsentToken:i.parentalConsentToken}:{}}}function $s(i){let e={consentJson:i.consentJson};return typeof i.locale=="string"&&(e.locale=i.locale),i.gpcDetected!=null&&(e.gpcDetected=!!i.gpcDetected),e}function st(i,e,t){let n=i.headers.get("cookie")??"",o=`consenti_${e}`;return n.split(";").some(s=>{let a=s.trim(),c=a.indexOf("=");return c===-1||a.slice(0,c)!==o?!1:ks(a.slice(c+1),e,t)})?null:g(403,"Forbidden")}function Hs(i,e,t,n=async()=>"default",o,r="",s,a=7){return{"POST /consent":async(c,l)=>E(async()=>{let d=await I(c),u=js(d);if(!u.valid)return g(400,u.error??"Invalid request");let m=d,h=typeof m.profileId=="string"?m.profileId:null;if(!h)return g(400,"profileId is required");let S=await t.get(h);if(!S)return g(404,"Profile not found");let _=await n(c),R=S.profileJson.allowedOrigins??[];if(R.length===0&&o&&(R=(await o.getSettings(_)).allowedOrigins??[]),!hn(c,R))return g(403,"Origin not allowed for this profile");let v=typeof m.visitorId=="string"?m.visitorId:q(),A=c.headers.get("x-real-ip")??"",P=c.headers.get("user-agent")??"";await e.upsert({visitorId:v,ip:A,userAgent:P});let O=Fs(m,v,_),D=await i.create(O),G=mi(v,D.id,r);return new Response(JSON.stringify(D),{status:201,headers:{"Content-Type":"application/json","Set-Cookie":G}})}),"PUT /consent/:visitorId":async(c,l)=>E(async()=>{let d=l.visitorId;if(!d)return g(400,"Missing visitorId");let u=st(c,d,r);if(u)return u;let m=await I(c),h=Bs(m);if(!h.valid)return g(400,h.error??"Invalid request");let S=$s(m),_=await i.update(d,S),w=mi(d,_.id,r);return new Response(JSON.stringify(_),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":w}})}),"GET /consent/:visitorId":async(c,l)=>E(async()=>{let d=l.visitorId;if(!d)return g(400,"Missing visitorId");let u=st(c,d,r);if(u)return u;let m=await i.get(d);return m?new Response(JSON.stringify(m),{status:200,headers:{"Content-Type":"application/json"}}):g(404,"Consent not found")}),"GET /consent/:visitorId/verify":async(c,l)=>E(async()=>{let d=l.visitorId;if(!d)return g(400,"Missing visitorId");let u=st(c,d,r);if(u)return u;let m=await i.verify(d);return new Response(JSON.stringify(m),{status:200,headers:{"Content-Type":"application/json"}})}),"DELETE /consent/:visitorId":async(c,l)=>E(async()=>{let d=l.visitorId;if(!d)return g(400,"Missing visitorId");let u=st(c,d,r);if(u)return u;let m=await i.get(d);await i.erase(d);let h={"Content-Type":"application/json"};return m&&(h["Set-Cookie"]=Ds(d)),new Response(JSON.stringify({success:!0}),{status:200,headers:h})}),"POST /consent/:visitorId/parental-consent-request":async(c,l)=>E(async()=>{let d=l.visitorId;if(!d)return g(400,"Missing visitorId");let u=st(c,d,r);if(u)return u;let m=await I(c),h=typeof m.profileId=="string"?m.profileId:null;if(!h)return g(400,"profileId is required");if(!await t.get(h))return g(404,"Profile not found");let S=Ls(d,h,r),_=Math.round(Date.now()/1e3);return s?.emit("consent.parentalConsentRequired",{visitorId:d,profileId:h,token:S,issuedAt:_}),y(200,{token:S})}),"POST /consent/parental-consent-resolve":async c=>E(async()=>{let l=await I(c),d=typeof l.token=="string"?l.token:null;if(!d)return g(400,"token is required");let u=Ns(d,r,a);return u.valid?(s?.emit("consent.parentalConsentGranted",{visitorId:u.visitorId,profileId:u.profileId}),y(200,{visitorId:u.visitorId,profileId:u.profileId})):g(403,`Invalid or expired token (${u.reason})`)})}}p();var Td=!1;function Vs(i){return{"POST /notice-shown":async(e,t)=>E(async()=>{if(!Td)return g(404,"Not found");let n=await I(e);if(!n||typeof n!="object")return g(400,"Request body must be a JSON object");let o=n,r=typeof o.visitorId=="string"?o.visitorId:"",s=typeof o.profileId=="string"?o.profileId:"",a=typeof o.locale=="string"?o.locale:"";if(!r)return g(400,"visitorId is required");if(!s)return g(400,"profileId is required");if(!a)return g(400,"locale is required");let c=await i.recordShown({visitorId:r,profileId:s,locale:a});return new Response(JSON.stringify({success:!0,id:c.id}),{status:201,headers:{"Content-Type":"application/json"}})})}}p();function Ws(i,e){return{"GET /tcf/status":async(t,n)=>E(async()=>{if(!e?.enabled)return y(200,{blocked:!1});let o=await i.getSettings("default"),r=le(!0,{cmpId:e.cmpId,cmpVersion:e.cmpVersion,publisherCC:e.publisherCC},o.tcfConfirmation);return y(200,{blocked:!r})})}}p();function qs(i,e){return{"GET /gpp/status":async(t,n)=>E(async()=>{if(!e?.enabled)return y(200,{blocked:!1});let o=await i.getSettings("default"),r=le(!0,{cmpId:e.cmpId,cmpVersion:e.cmpVersion},o.gppConfirmation);return y(200,{blocked:!r})})}}p();var yi=require("node:crypto");p();var Js=require("node:crypto");async function b(i,e,t,n){let o=i.headers.get("authorization"),r=o?.startsWith("Bearer ")?o.slice(7):null;if(!r)return null;if(r.startsWith("ck_")){let s=(0,Js.createHash)("sha256").update(r).digest("hex"),a=await e.getApiKeyByHash(s);if(!a||!a.isActive)return null;if(a.expireBy&&new Date(a.expireBy)<=new Date)return await e.revokeApiKey(a.id).catch(()=>{}),null;let c=(await e.getAllPermissions()).map(l=>l.name);return{sub:`apikey:${a.id}`,email:a.name,roles:["api_key"],permissions:c,allowedTenants:[a.tenantId]}}if(t.mode==="local"||t.mode==="jwt"){let s=yt(r,n);if(!s)return null;let a=s.sub,c=s.email,l=s.roles,d=s.permissions,u=s.allowedTenants;return typeof a!="string"||typeof c!="string"?null:{sub:a,email:c,roles:Array.isArray(l)?l:[],permissions:Array.isArray(d)?d:[],allowedTenants:Array.isArray(u)?u:[]}}if(t.mode==="custom"&&t.validateUser){let s=await t.validateUser(i);if(!s)return null;let a=await e.getUserRoles(s.id),c=await Promise.all(a.map(d=>e.getPermissionsForRole(d.id))),l=[...new Set(c.flat().map(d=>d.name))];return{sub:s.id,email:s.email,roles:a.map(d=>d.name),permissions:l,allowedTenants:[]}}return null}function k(i,e){return i?e&&!i.permissions.includes(e)?g(403,"Forbidden"):null:g(401,"Unauthorized")}p();var yn=require("node:crypto");function zs(i){return i.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ks(i){return Buffer.from(i.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8")}function Ys(){let i=zs((0,yn.randomBytes)(32)),e=zs((0,yn.createHash)("sha256").update(i).digest());return{verifier:i,challenge:e}}async function fi(i){let e=await fetch(`${i}/.well-known/openid-configuration`,{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`OIDC discovery failed for ${i}: ${e.status}`);return e.json()}function Qs(i,e,t,n,o){let r=new URLSearchParams({response_type:"code",client_id:i.clientId,redirect_uri:i.redirectUri,scope:"openid email profile",state:t,nonce:n,code_challenge:o,code_challenge_method:"S256"});return`${e}?${r.toString()}`}async function Zs(i,e,t,n){let o=new URLSearchParams({grant_type:"authorization_code",client_id:i.clientId,client_secret:i.clientSecret,redirect_uri:i.redirectUri,code:t,code_verifier:n}),r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:AbortSignal.timeout(1e4)});if(!r.ok){let s=await r.text();throw new Error(`OIDC token exchange failed: ${s}`)}return r.json()}async function Xs(i,e){let t=i.split(".");if(t.length!==3)throw new Error("Invalid ID token format");let n=JSON.parse(Ks(t[0])),o=n.alg??"RS256",r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch JWKS: ${r.status}`);let s=await r.json(),a=n.kid?s.keys.find(R=>R.kid===n.kid):s.keys.find(R=>R.use==="sig")??s.keys[0];if(!a)throw new Error("No matching key in JWKS");let c;if(o==="RS256"||o==="RS384"||o==="RS512"){let R=o==="RS256"?"SHA-256":o==="RS384"?"SHA-384":"SHA-512";c=await globalThis.crypto.subtle.importKey("jwk",a,{name:"RSASSA-PKCS1-v1_5",hash:{name:R}},!1,["verify"])}else if(o==="ES256"||o==="ES384"||o==="ES512"){let R=o==="ES256"?"P-256":o==="ES384"?"P-384":"P-521";c=await globalThis.crypto.subtle.importKey("jwk",a,{name:"ECDSA",namedCurve:R},!1,["verify"])}else throw new Error(`Unsupported OIDC token algorithm: ${o}`);let l=new TextEncoder().encode(`${t[0]}.${t[1]}`),d=(4-t[2].length%4)%4,u=t[2].replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(d),m=Uint8Array.from(atob(u),R=>R.charCodeAt(0)),h=o.startsWith("ES")?{name:"ECDSA",hash:{name:`SHA-${o.slice(2)}`}}:{name:"RSASSA-PKCS1-v1_5"};if(!await globalThis.crypto.subtle.verify(h,c,m,l))throw new Error("ID token signature verification failed");let _=JSON.parse(Ks(t[1])),w=Math.floor(Date.now()/1e3);if(typeof _.exp=="number"&&_.exp<w)throw new Error("ID token has expired");return _}function ea(i,e){let t=e?.email??"email",n=i[t];if(typeof n!="string")throw new Error("OIDC token missing email claim");return n}function ta(i,e){let t=e?.roles??"consenti_roles",n=i[t];return Array.isArray(n)?n.filter(o=>typeof o=="string"):[]}var at=new Map;setInterval(()=>{let i=Date.now();for(let[e,t]of at)t.expiresAt<i&&at.delete(e)},5*6e4).unref();function na(i,e,t){at.set(i,{verifier:e,nonce:t,expiresAt:Date.now()+10*6e4})}function ia(i){let e=at.get(i);return at.delete(i),!e||e.expiresAt<Date.now()?null:{verifier:e.verifier,nonce:e.nonce}}p();function Id(i){return i.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function oa(i){return`<?xml version="1.0" encoding="UTF-8"?>
148
137
  <EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
149
138
  entityID="saml:sp:consenti">
150
139
  <SPSSODescriptor
@@ -154,19 +143,19 @@ ${l.map(u=>` (${V(c)},${V(u)})`).join(`,
154
143
  <NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</NameIDFormat>
155
144
  <AssertionConsumerService
156
145
  Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
157
- Location="${No(s.callbackUrl)}"
146
+ Location="${Id(i.callbackUrl)}"
158
147
  index="0"
159
148
  isDefault="true"/>
160
149
  </SPSSODescriptor>
161
- </EntityDescriptor>`}async function ki(s,e){let t;try{t=await import("samlify")}catch{return console.warn("[Consenti] samlify is not installed. Install it to use SAML auth mode."),null}try{let n=t.ServiceProvider({entityID:"saml:sp:consenti",assertionConsumerService:[{Binding:"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",Location:e.callbackUrl}]}),i=t.IdentityProvider({entityID:e.issuer,singleSignOnService:[{Binding:"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",Location:e.entryPoint}],signingCert:e.cert}),o=await n.parseLoginResponse(i,"post",{body:{SAMLResponse:s}}),r=o.extract.nameID,a=o.extract.attributes.roles,c=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];return{email:r,roles:c}}catch(n){return console.warn("[Consenti] SAML response validation failed:",n),null}}var Ee=require("node:crypto"),qt="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Mo(s){let e="",t=0,n=0;for(let i of s)for(n=n<<8|i,t+=8;t>=5;)e+=qt[n>>>t-5&31],t-=5;return t>0&&(e+=qt[n<<5-t&31]),e}function Go(s){let e=s.toUpperCase().replace(/[^A-Z2-7]/g,""),t=[],n=0,i=0;for(let o of e){let r=qt.indexOf(o);r<0||(i=i<<5|r,n+=5,n>=8&&(t.push(i>>>n-8&255),n-=8))}return Buffer.from(t)}function xo(s,e){let t=Buffer.alloc(8),n=e;for(let a=7;a>=0;a--)t[a]=n&255,n=Math.floor(n/256);let i=(0,Ee.createHmac)("sha1",s).update(t).digest(),o=i[i.length-1]&15,r=(i[o]&127)<<24|(i[o+1]&255)<<16|(i[o+2]&255)<<8|i[o+3]&255;return String(r%1e6).padStart(6,"0")}function Ni(){return Mo((0,Ee.randomBytes)(20))}var St=new Map;setInterval(()=>{let s=Date.now();for(let[e,t]of St)s>=t&&St.delete(e)},9e4).unref();function Mi(s,e,t=1){if(St.has(e))return!1;let n=Math.floor(Date.now()/3e4),i=Go(s),o=Buffer.from(e);for(let r=-t;r<=t;r++){let a=Buffer.from(xo(i,n+r));if(a.length===o.length&&(0,Ee.timingSafeEqual)(a,o))return St.set(e,Date.now()+9e4),!0}return!1}function Gi(s,e,t="Consenti"){let n=encodeURIComponent(`${t}:${e}`),i=new URLSearchParams({secret:s,issuer:t,algorithm:"SHA1",digits:"6",period:"30"});return`otpauth://totp/${n}?${i.toString()}`}function xi(s){return s.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Fi(s,e,t,n,i){function o(r){if(!i)return null;let a=r.headers.get("x-real-ip")??"";return i.checkRequest(a)?null:m(429,"Too Many Requests")}return{"POST /auth/login":async(r,a)=>g(async()=>{let c=o(r);if(c)return c;if(t.mode!=="local")return m(400,"Login not available in this auth mode");let l=await v(r);if(!l||typeof l!="object")return m(400,"Invalid body");let u=l;if(typeof u.email!="string"||typeof u.password!="string")return m(400,"email and password are required");let d=await s.login(u.email,u.password);return d?y(200,{token:d}):m(401,"Invalid credentials")}),"GET /auth/me":async(r,a)=>g(async()=>{let c=await C(r,e,t,n);if(!c)return m(401,"Unauthorized");let l=await e.getUserById(c.sub);if(!l)return m(401,"User not found");let u=await e.getUserRoles(l.id);return y(200,{id:l.id,email:l.email,name:l.name,isActive:l.isActive,totpEnabled:l.totpEnabled??!1,roles:u.map(d=>d.name),permissions:c.permissions})}),"POST /auth/logout":async(r,a)=>g(async()=>y(200,{success:!0})),"GET /auth/oidc/authorize":async(r,a)=>g(async()=>{if(t.mode!=="oidc"||!t.oidc)return m(400,"OIDC not configured");let c=await Jt(t.oidc.issuer),l=xi((0,Kt.randomBytes)(16)),u=xi((0,Kt.randomBytes)(16)),{verifier:d,challenge:p}=Ci();Di(l,d,u);let E=vi(t.oidc,c.authorization_endpoint,l,u,p);return new Response(null,{status:302,headers:{Location:E}})}),"GET /auth/oidc/callback":async(r,a)=>g(async()=>{if(t.mode!=="oidc"||!t.oidc)return m(400,"OIDC not configured");let c=new URL(r.url),l=c.searchParams.get("code"),u=c.searchParams.get("state");if(!l||!u)return m(400,"Missing code or state");let d=Li(u);if(!d)return m(400,"Invalid or expired state");let p=await Jt(t.oidc.issuer),E=await Ii(t.oidc,p.token_endpoint,l,d.verifier),S=await Pi(E.id_token,p.jwks_uri),f=bi(S,t.oidc.claimsMapping),_=Oi(S,t.oidc.claimsMapping),h=await e.getUserByEmail(f);if(h||(h=await e.createUser({tenantId:"default",name:f,email:f,passwordHash:""})),_.length>0){let O=await e.getRoles("default");for(let z of _){let L=O.find(Fe=>Fe.name===z);L&&await e.assignRole(h.id,L.id).catch(()=>{})}}let A=await e.getUserRoles(h.id),T=[];for(let O of A){let z=await e.getPermissionsForRole(O.id);T.push(...z.map(L=>L.name))}let I=s.signToken({sub:h.id,email:h.email,roles:A.map(O=>O.name),permissions:[...new Set(T)]});return y(200,{token:I})}),"GET /auth/saml/metadata":async(r,a)=>g(async()=>{if(t.mode!=="saml"||!t.saml)return m(400,"SAML not configured");let c=Ui(t.saml);return new Response(c,{status:200,headers:{"Content-Type":"application/xml"}})}),"POST /auth/saml/acs":async(r,a)=>g(async()=>{let c=o(r);if(c)return c;if(t.mode!=="saml"||!t.saml)return m(400,"SAML not configured");let u=new URLSearchParams(await r.text()).get("SAMLResponse");if(typeof u!="string")return m(400,"Missing SAMLResponse");let d=await ki(u,t.saml);if(!d)return m(401,"SAML validation failed");let p=await e.getUserByEmail(d.email);p||(p=await e.createUser({tenantId:"default",name:d.email,email:d.email,passwordHash:""}));let E=await e.getUserRoles(p.id),S=[];for(let _ of E){let h=await e.getPermissionsForRole(_.id);S.push(...h.map(A=>A.name))}let f=s.signToken({sub:p.id,email:p.email,roles:E.map(_=>_.name),permissions:[...new Set(S)]});return y(200,{token:f})}),"POST /auth/totp/setup":async(r,a)=>g(async()=>{let c=await C(r,e,t,n);if(!c)return m(401,"Unauthorized");let l=await e.getUserById(c.sub);if(!l)return m(401,"User not found");let u=Ni(),d=Gi(u,l.email);return await e.updateUser(l.id,{totpSecret:u,totpEnabled:!1}),y(200,{qrUrl:d,message:"Scan QR code, then verify with POST /auth/totp/verify"})}),"POST /auth/totp/verify":async(r,a)=>g(async()=>{let c=o(r);if(c)return c;let l=await C(r,e,t,n);if(!l)return m(401,"Unauthorized");let u=await e.getUserById(l.sub);if(!u)return m(401,"User not found");if(!u.totpSecret)return m(400,"TOTP not set up \u2014 call POST /auth/totp/setup first");let d=await v(r);if(!d||typeof d!="object")return m(400,"Invalid body");let p=d;return typeof p.token!="string"?m(400,"token is required"):Mi(u.totpSecret,p.token)?(await e.updateUser(u.id,{totpEnabled:!0}),y(200,{success:!0,message:"TOTP enabled successfully"})):m(400,"Invalid TOTP token")}),"POST /auth/totp/disable":async(r,a)=>g(async()=>{let c=await C(r,e,t,n);if(!c)return m(401,"Unauthorized");let l=await e.getUserById(c.sub);return l?(await e.updateUser(l.id,{totpSecret:null,totpEnabled:!1}),y(200,{success:!0,message:"TOTP disabled"})):m(401,"User not found")})}}var Hi={"opt-out-strict":{label:"Opt-out Strict (CPRA / California)",description:"California CPRA: opt-out with sale/sharing/sensitive categories required. GPC must be honored. Stricter than general US state laws.",compliances:["cpra"],defaultGpc:"honor",gpcAutoHonor:!0,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!0,requiresDpdpaDisclosure:!1},"opt-out":{label:"Opt-out (US State Laws)",description:"US state privacy laws. Collect first, allow opt-out of sale/share. Covers CCPA and all state-level equivalents.",compliances:["ccpa","vcdpa","cpa-co","ctdpa","ucpa","icdpa-ia","icdpa-in","tipa","mcdpa-mt","mcdpa-mn","ocpa","tdpsa","dpdpa-de","njdpa","nhpa","ndpa-ne","modpa","kcdpa","ridtpa"],defaultGpc:"honor",gpcAutoHonor:!0,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"notice-only":{label:"Notice Only",description:"A privacy notice is generally sufficient. No dedicated cookie banner law is encoded for this jurisdiction.",compliances:["privacy-fj","privacy-pg"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"opt-in":{label:"Standard Opt-in (GDPR)",description:"GDPR / ePrivacy style: prior consent required before non-essential cookies. Granular consent, easy reject, easy withdrawal.",compliances:["gdpr","eprivacy","uk-gdpr","pecr","revfadp","kvkk","pdpa-th","pdpl-sa","uae-pdpl","difc-dpl","adgm-dpr","qpdl-qa","pdpl-bh","pdpl-om","law25"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!0,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"opt-in-dpdpa":{label:"Opt-in (India DPDPA)",description:"India's Digital Personal Data Protection Act. Opt-in consent with data fiduciary disclosure. No legitimate interest basis.",compliances:["dpdpa"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!0},"opt-in-china":{label:"Opt-in (China PIPL / DSL)",description:"China PIPL + DSL + CSL: strict opt-in with purpose specification, data minimisation, and cross-border transfer controls.",compliances:["pipl","dsl-cn","csl-cn"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!1,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"opt-in-brazil":{label:"Opt-in (Brazil LGPD)",description:"Brazil LGPD: opt-in consent required. Legitimate interest is a valid basis. Analytics and advertising may differ in treatment.",compliances:["lgpd"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1},"general-privacy-consent":{label:"General Privacy Consent",description:"Privacy notice or consent rules exist but the jurisdiction does not have a GDPR/PECR-style strict cookie banner law. Documenting legal basis is best practice.",compliances:["pipeda","popia","appi","pipa-kr","pdpa-sg","pdpa-my","dpa-ph","pdp-id","pdpd-vn","privacy-au","privacy-nz","pdpl-hk","pdpa-mo","pdpl-tw","privacy-bn","privacy-lk","privacy-np","privacy-kw","privacy-il","ndpa-ng","dpa-ke","dpa-gh","dpa-ug","dpa-rw","dpa-mu","dpa-bw","dpa-zm","dpa-zw","dpa-eg","dpa-ma","dpa-tn","dpa-dz","lfpdppp","lpdp-ar","lpdp-pe","law1581-co","law18331-uy","law19628-cl","lopdp-ec","lpdp-cr","data-protection-pa","data-protection-do"],defaultGpc:"ignore",gpcAutoHonor:!1,allowsLegitimateInterest:!0,allowsTcf:!1,requiresCpraCategory:!1,requiresDpdpaDisclosure:!1}};var ji={"opt-in":{errors:[{rule:"legal-basis-required",field:"legalBasis",check:s=>!s.legalBasis,message:s=>`Cookie "${s}" must have a legal basis set (Consent, Legitimate Interest, or Strictly Necessary) for GDPR compliance.`},{rule:"li-description-required",field:"legitimateInterest.description",check:s=>s.legalBasis==="legitimate_interest"&&!s.legitimateInterest?.description,message:s=>`Cookie "${s}" uses Legitimate Interest but has no balancing test description. GDPR requires documenting your LI assessment.`}],warnings:[{rule:"li-description-recommended",field:"legitimateInterest.description",check:s=>s.legalBasis==="legitimate_interest"&&!s.legitimateInterest?.description,message:s=>`Cookie "${s}": adding a Legitimate Interest description improves transparency and is a GDPR best practice.`,suggestion:"Add a brief description of your legitimate interest balancing test."}]},"opt-out":{errors:[],warnings:[{rule:"gpc-recommended",field:"listenGpc",check:s=>s.legalBasis!=="mandatory"&&!s.listenGpc,message:s=>`Cookie "${s}" does not listen for the GPC signal. US state privacy laws require honoring GPC for opt-out of sale/sharing.`,suggestion:'Enable "Listen for GPC signal" on this cookie.'}]},"opt-out-strict":{errors:[{rule:"cpra-category-required",field:"cpraCategory",check:s=>s.legalBasis!=="mandatory"&&!s.cpraCategory,message:s=>`Cookie "${s}" must have a CPRA category (Sale, Sharing, or Sensitive) assigned. Required under CPRA for all non-necessary cookies.`}],warnings:[{rule:"gpc-strict-required",field:"listenGpc",check:s=>s.legalBasis!=="mandatory"&&!s.listenGpc,message:s=>`Cookie "${s}" does not listen for the GPC signal. Under CPRA, non-mandatory cookies must honor GPC as a Do Not Sell/Share signal.`,suggestion:'Enable "Listen for GPC signal" on this cookie.'}]},"opt-in-dpdpa":{errors:[{rule:"no-li-allowed",field:"legalBasis",check:s=>s.legalBasis==="legitimate_interest",message:s=>`Cookie "${s}" uses Legitimate Interest, which is not a valid legal basis under India's DPDPA. Use Consent or Strictly Necessary.`},{rule:"legal-basis-required",field:"legalBasis",check:s=>!s.legalBasis,message:s=>`Cookie "${s}" must have a legal basis set (Consent or Strictly Necessary) for DPDPA compliance.`}],warnings:[]},"opt-in-china":{errors:[{rule:"legal-basis-required",field:"legalBasis",check:s=>!s.legalBasis,message:s=>`Cookie "${s}" must have a legal basis set for China PIPL compliance. Consent is the primary valid basis.`}],warnings:[{rule:"li-limited-under-pipl",field:"legalBasis",check:s=>s.legalBasis==="legitimate_interest",message:s=>`Cookie "${s}" uses Legitimate Interest. Under China's PIPL, LI is narrowly scoped and data processing purposes must be strictly documented.`,suggestion:"Consider using Consent for this cookie to ensure PIPL compliance. Document the specific legitimate interest basis if retaining LI."}]},"opt-in-brazil":{errors:[{rule:"legal-basis-required",field:"legalBasis",check:s=>!s.legalBasis,message:s=>`Cookie "${s}" must have a legal basis set. Brazil's LGPD requires one of ten legal bases; Consent or Legitimate Interest are most common for cookies.`}],warnings:[{rule:"li-description-recommended",field:"legitimateInterest.description",check:s=>s.legalBasis==="legitimate_interest"&&!s.legitimateInterest?.description,message:s=>`Cookie "${s}" uses Legitimate Interest. LGPD requires documenting the basis and conducting an impact assessment.`,suggestion:"Add a Legitimate Interest description to document the LGPD basis and your impact assessment."}]},"general-privacy-consent":{errors:[],warnings:[{rule:"legal-basis-recommended",field:"legalBasis",check:s=>!s.legalBasis,message:s=>`Cookie "${s}" has no legal basis documented. While a strict cookie banner may not be legally required in this jurisdiction, documenting legal basis is a privacy best practice.`,suggestion:"Set a legal basis to improve compliance documentation and future-proof against stricter enforcement."}]},"notice-only":{errors:[],warnings:[]}},At={version:"2026-07",countries:{AT:{name:"Austria",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Austria (GDPR)",locales:["de-AT"]},BE:{name:"Belgium",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Belgium (GDPR)",locales:["nl-BE","fr-BE"]},BG:{name:"Bulgaria",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Bulgaria (GDPR)",locales:["bg-BG"]},HR:{name:"Croatia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Croatia (GDPR)",locales:["hr-HR"]},CY:{name:"Cyprus",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Cyprus (GDPR)",locales:["el-CY"]},CZ:{name:"Czechia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Czechia (GDPR)",locales:["cs-CZ"]},DK:{name:"Denmark",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Denmark (GDPR)",locales:["da-DK"]},EE:{name:"Estonia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Estonia (GDPR)",locales:["et-EE"]},FI:{name:"Finland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Finland (GDPR)",locales:["fi-FI"]},FR:{name:"France",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"France (GDPR)",locales:["fr-FR"]},DE:{name:"Germany",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Germany (GDPR)",locales:["de-DE"]},GR:{name:"Greece",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Greece (GDPR)",locales:["el-GR"]},HU:{name:"Hungary",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Hungary (GDPR)",locales:["hu-HU"]},IE:{name:"Ireland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Ireland (GDPR)",locales:["en"]},IT:{name:"Italy",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Italy (GDPR)",locales:["it-IT"]},LV:{name:"Latvia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Latvia (GDPR)",locales:["lv-LV"]},LT:{name:"Lithuania",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Lithuania (GDPR)",locales:["lt-LT"]},LU:{name:"Luxembourg",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Luxembourg (GDPR)",locales:["fr-LU","de-LU"]},MT:{name:"Malta",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Malta (GDPR)",locales:["mt-MT","en"]},NL:{name:"Netherlands",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Netherlands (GDPR)",locales:["nl-NL"]},PL:{name:"Poland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Poland (GDPR)",locales:["pl-PL"]},PT:{name:"Portugal",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Portugal (GDPR)",locales:["pt-PT"]},RO:{name:"Romania",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Romania (GDPR)",locales:["ro-RO"]},SK:{name:"Slovakia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Slovakia (GDPR)",locales:["sk-SK"]},SI:{name:"Slovenia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Slovenia (GDPR)",locales:["sl-SI"]},ES:{name:"Spain",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Spain (GDPR)",locales:["es-ES"]},SE:{name:"Sweden",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Sweden (GDPR)",locales:["sv-SE"]},IS:{name:"Iceland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Iceland (GDPR via EEA)",locales:["is-IS"]},LI:{name:"Liechtenstein",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Liechtenstein (GDPR via EEA)",locales:["de-LI"]},NO:{name:"Norway",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Norway (GDPR via EEA)",locales:["nb-NO"]},AD:{name:"Andorra",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Andorra (GDPR-aligned)",locales:["ca-AD"]},AL:{name:"Albania",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Albania (GDPR-aligned)",locales:["sq-AL"]},BA:{name:"Bosnia and Herzegovina",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Bosnia and Herzegovina (GDPR-aligned)",locales:["bs-BA","sr-Latn-BA"]},GG:{name:"Guernsey",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Guernsey (DPA based on GDPR)",locales:["en"]},GI:{name:"Gibraltar",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Gibraltar (DPA based on UK GDPR)",locales:["en"]},GL:{name:"Greenland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Greenland (Danish GDPR implementation)",locales:["da-GL"]},MC:{name:"Monaco",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Monaco (GDPR-aligned)",locales:["fr-MC"]},ME:{name:"Montenegro",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Montenegro (GDPR-aligned)",locales:["sr-Latn-ME"]},MK:{name:"North Macedonia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"North Macedonia (GDPR-aligned)",locales:["mk-MK"]},RS:{name:"Serbia",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Serbia (GDPR-aligned)",locales:["sr-RS"]},SM:{name:"San Marino",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"San Marino (GDPR-aligned)",locales:["it-SM"]},TR:{name:"T\xFCrkiye",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"T\xFCrkiye (KVKK)",locales:["tr-TR"]},CA:{name:"Canada",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Canada (PIPEDA / Law 25)",locales:["en","fr-CA"],overriddenRegions:{QC:{name:"Quebec",type:"region",complianceGroup:"opt-in",description:"Quebec \u2014 Law 25 (GDPR-style opt-in)"}}},US:{name:"United States",type:"country",complianceGroup:"opt-out",default:"opt-out-strict",description:"United States \u2014 opt-out-strict (CPRA) used when state cannot be detected",locales:["en","es-US"],overriddenRegions:{CA:{name:"California",type:"region",complianceGroup:"opt-out-strict",description:"California \u2014 CPRA/CCPA"},VA:{name:"Virginia",type:"region",complianceGroup:"opt-out",description:"Virginia \u2014 VCDPA"},CO:{name:"Colorado",type:"region",complianceGroup:"opt-out",description:"Colorado \u2014 CPA"},CT:{name:"Connecticut",type:"region",complianceGroup:"opt-out",description:"Connecticut \u2014 CTDPA"},UT:{name:"Utah",type:"region",complianceGroup:"opt-out",description:"Utah \u2014 UCPA"},TX:{name:"Texas",type:"region",complianceGroup:"opt-out",description:"Texas \u2014 TDPSA"},DE:{name:"Delaware",type:"region",complianceGroup:"opt-out",description:"Delaware \u2014 DPDPA"},NJ:{name:"New Jersey",type:"region",complianceGroup:"opt-out",description:"New Jersey \u2014 NJDPA"},OR:{name:"Oregon",type:"region",complianceGroup:"opt-out",description:"Oregon \u2014 OCPA"},MN:{name:"Minnesota",type:"region",complianceGroup:"opt-out",description:"Minnesota \u2014 MCDPA"},MD:{name:"Maryland",type:"region",complianceGroup:"opt-out",description:"Maryland \u2014 MODPA"},KY:{name:"Kentucky",type:"region",complianceGroup:"opt-out",description:"Kentucky \u2014 KCDPA"},TN:{name:"Tennessee",type:"region",complianceGroup:"opt-out",description:"Tennessee \u2014 TIPA"},NE:{name:"Nebraska",type:"region",complianceGroup:"opt-out",description:"Nebraska \u2014 NDPA"},IA:{name:"Iowa",type:"region",complianceGroup:"opt-out",description:"Iowa \u2014 ICDPA"},IN:{name:"Indiana",type:"region",complianceGroup:"opt-out",description:"Indiana \u2014 ICDPA"},MT:{name:"Montana",type:"region",complianceGroup:"opt-out",description:"Montana \u2014 MCDPA"},NH:{name:"New Hampshire",type:"region",complianceGroup:"opt-out",description:"New Hampshire \u2014 NHPA"},RI:{name:"Rhode Island",type:"region",complianceGroup:"opt-out",description:"Rhode Island \u2014 RIDTPA"}}},AR:{name:"Argentina",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Argentina (LPDP)",locales:["es-AR"]},BO:{name:"Bolivia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Bolivia",locales:["es-BO"]},BR:{name:"Brazil",type:"country",complianceGroup:"opt-in-brazil",default:"opt-in-brazil",description:"Brazil (LGPD)",locales:["pt-BR"]},CL:{name:"Chile",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Chile (Law 19.628)",locales:["es-CL"]},CO:{name:"Colombia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Colombia (Law 1581)",locales:["es-CO"]},CR:{name:"Costa Rica",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Costa Rica (LPDP)",locales:["es-CR"]},DO:{name:"Dominican Republic",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Dominican Republic",locales:["es-DO"]},EC:{name:"Ecuador",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Ecuador (LOPDP)",locales:["es-EC"]},GF:{name:"French Guiana",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"French Guiana",locales:["fr-GF"]},GT:{name:"Guatemala",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guatemala",locales:["es-GT"]},GY:{name:"Guyana",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guyana",locales:["en"]},HN:{name:"Honduras",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Honduras",locales:["es-HN"]},HT:{name:"Haiti",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Haiti",locales:["fr-HT"]},JM:{name:"Jamaica",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Jamaica",locales:["en"]},MX:{name:"Mexico",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Mexico (LFPDPPP)",locales:["es-MX"]},NI:{name:"Nicaragua",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Nicaragua",locales:["es-NI"]},PA:{name:"Panama",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Panama",locales:["es-PA"]},PE:{name:"Peru",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Peru (LPDP)",locales:["es-PE"]},PY:{name:"Paraguay",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Paraguay",locales:["es-PY"]},SR:{name:"Suriname",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Suriname",locales:["nl-SR"]},SV:{name:"El Salvador",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"El Salvador",locales:["es-SV"]},TT:{name:"Trinidad and Tobago",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Trinidad and Tobago",locales:["en"]},UY:{name:"Uruguay",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Uruguay (Law 18.331)",locales:["es-UY"]},VE:{name:"Venezuela",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Venezuela",locales:["es-VE"]},AG:{name:"Antigua and Barbuda",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Antigua and Barbuda",locales:["en"]},BB:{name:"Barbados",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Barbados",locales:["en"]},BL:{name:"Saint Barth\xE9lemy",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Barth\xE9lemy",locales:["fr-BL"]},BM:{name:"Bermuda",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Bermuda",locales:["en"]},BS:{name:"Bahamas",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Bahamas",locales:["en"]},CU:{name:"Cuba",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cuba",locales:["es-CU"]},DM:{name:"Dominica",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Dominica",locales:["en"]},GD:{name:"Grenada",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Grenada",locales:["en"]},KN:{name:"Saint Kitts and Nevis",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Kitts and Nevis",locales:["en"]},LC:{name:"Saint Lucia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Lucia",locales:["en"]},PM:{name:"Saint Pierre and Miquelon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Pierre and Miquelon",locales:["fr-PM"]},PR:{name:"Puerto Rico",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Puerto Rico",locales:["es-PR","en"]},VC:{name:"Saint Vincent and the Grenadines",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Saint Vincent and the Grenadines",locales:["en"]},IN:{name:"India",type:"country",complianceGroup:"opt-in-dpdpa",default:"opt-in-dpdpa",description:"India (DPDPA)",locales:["hi-IN","en","bn-IN","ta-IN"]},CN:{name:"China",type:"country",complianceGroup:"opt-in-china",default:"opt-in-china",description:"China (PIPL + DSL + CSL)",locales:["zh-CN"]},BN:{name:"Brunei",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Brunei (Personal Data Protection Order)",locales:["ms-BN","en"]},ID:{name:"Indonesia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Indonesia (PDP Law)",locales:["id-ID"]},KH:{name:"Cambodia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cambodia",locales:["km-KH"]},LA:{name:"Laos",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Laos",locales:["lo-LA"]},MM:{name:"Myanmar",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Myanmar",locales:["my-MM"]},MY:{name:"Malaysia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Malaysia (PDPA)",locales:["ms-MY","zh-MY","en"]},PH:{name:"Philippines",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Philippines (DPA)",locales:["fil-PH","en"]},SG:{name:"Singapore",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Singapore (PDPA)",locales:["zh-SG","ms-SG","ta-SG","en"]},TH:{name:"Thailand",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Thailand (PDPA \u2014 GDPR-style opt-in)",locales:["th-TH"]},TL:{name:"Timor-Leste",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Timor-Leste",locales:["pt-TL"]},VN:{name:"Vietnam",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Vietnam (PDPD)",locales:["vi-VN"]},HK:{name:"Hong Kong",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Hong Kong SAR (PDPO)",locales:["zh-HK"]},JP:{name:"Japan",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Japan (APPI)",locales:["ja-JP"]},KP:{name:"North Korea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"North Korea",locales:["ko-KP"]},KR:{name:"South Korea",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"South Korea (PIPA)",locales:["ko-KR"]},MN:{name:"Mongolia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mongolia",locales:["mn-MN"]},MO:{name:"Macau",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Macau SAR (PDPA)",locales:["zh-MO","pt-MO"]},TW:{name:"Taiwan",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Taiwan (PDPL)",locales:["zh-TW"]},AF:{name:"Afghanistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Afghanistan",locales:["fa-AF"]},BD:{name:"Bangladesh",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Bangladesh",locales:["bn-BD"]},BT:{name:"Bhutan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Bhutan",locales:["dz-BT"]},IO:{name:"British Indian Ocean Territory",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"British Indian Ocean Territory",locales:["en"]},LK:{name:"Sri Lanka",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Sri Lanka",locales:["si-LK","ta-LK"]},MV:{name:"Maldives",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Maldives",locales:["dv-MV"]},NP:{name:"Nepal",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Nepal",locales:["ne-NP"]},PK:{name:"Pakistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Pakistan",locales:["ur-PK","en"]},AM:{name:"Armenia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Armenia",locales:["hy-AM"]},AZ:{name:"Azerbaijan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Azerbaijan",locales:["az-AZ"]},GE:{name:"Georgia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Georgia",locales:["ka-GE"]},KG:{name:"Kyrgyzstan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Kyrgyzstan",locales:["ky-KG","ru-KG"]},KZ:{name:"Kazakhstan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Kazakhstan",locales:["kk-KZ","ru-KZ"]},TJ:{name:"Tajikistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Tajikistan",locales:["tg-TJ"]},TM:{name:"Turkmenistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Turkmenistan",locales:["tk-TM"]},UZ:{name:"Uzbekistan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Uzbekistan",locales:["uz-UZ"]},AE:{name:"United Arab Emirates",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"United Arab Emirates (UAE PDPL / DIFC DPL / ADGM DPR)",locales:["ar-AE"]},BH:{name:"Bahrain",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Bahrain (PDPL)",locales:["ar-BH"]},IL:{name:"Israel",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Israel (Privacy Protection Law)",locales:["he-IL","ar-IL"]},IQ:{name:"Iraq",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Iraq",locales:["ar-IQ"]},IR:{name:"Iran",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Iran",locales:["fa-IR"]},JO:{name:"Jordan",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Jordan",locales:["ar-JO"]},KW:{name:"Kuwait",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Kuwait",locales:["ar-KW"]},LB:{name:"Lebanon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Lebanon",locales:["ar-LB"]},OM:{name:"Oman",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Oman (PDPL)",locales:["ar-OM"]},PS:{name:"Palestine",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Palestine",locales:["ar-PS"]},QA:{name:"Qatar",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Qatar (PDPL)",locales:["ar-QA"]},SA:{name:"Saudi Arabia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Saudi Arabia (PDPL)",locales:["ar-SA"]},SY:{name:"Syria",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Syria",locales:["ar-SY"]},YE:{name:"Yemen",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Yemen",locales:["ar-YE"]},BF:{name:"Burkina Faso",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Burkina Faso",locales:["fr-BF"]},BJ:{name:"Benin",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Benin",locales:["fr-BJ"]},CI:{name:"C\xF4te d'Ivoire",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"C\xF4te d'Ivoire",locales:["fr-CI"]},CM:{name:"Cameroon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cameroon",locales:["fr-CM","en"]},CV:{name:"Cabo Verde",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Cabo Verde",locales:["pt-CV"]},GA:{name:"Gabon",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Gabon",locales:["fr-GA"]},GH:{name:"Ghana",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Ghana (DPA)",locales:["en"]},GM:{name:"Gambia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Gambia",locales:["en"]},GN:{name:"Guinea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guinea",locales:["fr-GN"]},GQ:{name:"Equatorial Guinea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Equatorial Guinea",locales:["es-GQ","fr-GQ"]},GW:{name:"Guinea-Bissau",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Guinea-Bissau",locales:["pt-GW"]},LR:{name:"Liberia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Liberia",locales:["en"]},ML:{name:"Mali",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mali",locales:["fr-ML"]},MR:{name:"Mauritania",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mauritania",locales:["ar-MR"]},NE:{name:"Niger",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Niger",locales:["fr-NE"]},NG:{name:"Nigeria",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Nigeria (NDPA)",locales:["en"]},SL:{name:"Sierra Leone",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Sierra Leone",locales:["en"]},SN:{name:"Senegal",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Senegal",locales:["fr-SN"]},TG:{name:"Togo",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Togo",locales:["fr-TG"]},BI:{name:"Burundi",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Burundi",locales:["fr-BI"]},DJ:{name:"Djibouti",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Djibouti",locales:["fr-DJ","ar-DJ"]},ER:{name:"Eritrea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Eritrea",locales:["ti-ER"]},ET:{name:"Ethiopia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Ethiopia",locales:["am-ET"]},KE:{name:"Kenya",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Kenya (DPA)",locales:["sw-KE","en"]},KM:{name:"Comoros",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Comoros",locales:["ar-KM","fr-KM"]},MG:{name:"Madagascar",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Madagascar",locales:["fr-MG"]},MU:{name:"Mauritius",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Mauritius (DPA)",locales:["en","fr-MU"]},MW:{name:"Malawi",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Malawi",locales:["en"]},MZ:{name:"Mozambique",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Mozambique",locales:["pt-MZ"]},RW:{name:"Rwanda",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Rwanda (DPA)",locales:["rw-RW","en"]},SC:{name:"Seychelles",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Seychelles",locales:["fr-SC","en"]},SO:{name:"Somalia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Somalia",locales:["so-SO"]},SS:{name:"South Sudan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"South Sudan",locales:["en"]},ST:{name:"S\xE3o Tom\xE9 and Pr\xEDncipe",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"S\xE3o Tom\xE9 and Pr\xEDncipe",locales:["pt-ST"]},TZ:{name:"Tanzania",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Tanzania",locales:["sw-TZ","en"]},UG:{name:"Uganda",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Uganda (DPA)",locales:["en"]},AO:{name:"Angola",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Angola",locales:["pt-AO"]},BW:{name:"Botswana",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Botswana (DPA)",locales:["en"]},LS:{name:"Lesotho",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Lesotho",locales:["en"]},NA:{name:"Namibia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Namibia",locales:["en"]},SZ:{name:"Eswatini",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Eswatini",locales:["en"]},ZA:{name:"South Africa",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"South Africa (POPIA)",locales:["en","af-ZA"]},ZM:{name:"Zambia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Zambia (DPA)",locales:["en"]},ZW:{name:"Zimbabwe",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Zimbabwe (DPA)",locales:["en"]},DZ:{name:"Algeria",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Algeria",locales:["ar-DZ","fr-DZ"]},EG:{name:"Egypt",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Egypt (DPA)",locales:["ar-EG"]},LY:{name:"Libya",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Libya",locales:["ar-LY"]},MA:{name:"Morocco",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Morocco",locales:["ar-MA","fr-MA"]},SD:{name:"Sudan",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Sudan",locales:["ar-SD"]},TN:{name:"Tunisia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Tunisia (DPA)",locales:["ar-TN","fr-TN"]},CD:{name:"DR Congo",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"DR Congo",locales:["fr-CD"]},CF:{name:"Central African Republic",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Central African Republic",locales:["fr-CF"]},CG:{name:"Republic of Congo",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Republic of Congo",locales:["fr-CG"]},TD:{name:"Chad",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Chad",locales:["fr-TD","ar-TD"]},BY:{name:"Belarus",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Belarus",locales:["be-BY","ru-BY"]},MD:{name:"Moldova",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Moldova",locales:["ro-MD"]},RU:{name:"Russia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Russia",locales:["ru-RU"]},UA:{name:"Ukraine",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Ukraine",locales:["uk-UA"]},VA:{name:"Holy See",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Holy See",locales:["it-VA"]},AU:{name:"Australia",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"Australia (Privacy Act)",locales:["en"]},FJ:{name:"Fiji",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Fiji",locales:["en"]},FM:{name:"Micronesia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Micronesia",locales:["en"]},KI:{name:"Kiribati",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Kiribati",locales:["en"]},MH:{name:"Marshall Islands",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Marshall Islands",locales:["en"]},MP:{name:"Northern Mariana Islands",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Northern Mariana Islands",locales:["en"]},NC:{name:"New Caledonia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"New Caledonia",locales:["fr-NC"]},NF:{name:"Norfolk Island",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Norfolk Island",locales:["en"]},NR:{name:"Nauru",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Nauru",locales:["en"]},NU:{name:"Niue",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Niue",locales:["en"]},NZ:{name:"New Zealand",type:"country",complianceGroup:"general-privacy-consent",default:"general-privacy-consent",description:"New Zealand (Privacy Act)",locales:["en"]},PF:{name:"French Polynesia",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"French Polynesia",locales:["fr-PF"]},PG:{name:"Papua New Guinea",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Papua New Guinea",locales:["en"]},PW:{name:"Palau",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Palau",locales:["en"]},SB:{name:"Solomon Islands",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Solomon Islands",locales:["en"]},TO:{name:"Tonga",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Tonga",locales:["en"]},TV:{name:"Tuvalu",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Tuvalu",locales:["en"]},VU:{name:"Vanuatu",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Vanuatu",locales:["fr-VU","en"]},WS:{name:"Samoa",type:"country",complianceGroup:"notice-only",default:"notice-only",description:"Samoa",locales:["en"]},UK:{name:"United Kingdom",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"United Kingdom (UK GDPR + PECR)",locales:["en"]},CH:{name:"Switzerland",type:"country",complianceGroup:"opt-in",default:"opt-in",description:"Switzerland (revFADP)",locales:["de-CH","fr-CH","it-CH"]}}},Mc=Object.entries(At.countries).reduce(function(s,[e,t]){return s[e]=t.name,s},{}),Gc=Object.values(At.countries).reduce(function(s,e){return e.locales.forEach(t=>{s[t]=e.name}),s},{});function $i(s){if(!s||typeof s!="object")return{valid:!1,error:"Request body must be a JSON object"};let e=s;if(typeof e.name!="string"||!e.name)return{valid:!1,error:"name is required"};if(typeof e.defaultLocale!="string"||!e.defaultLocale)return{valid:!1,error:"defaultLocale is required"};if(!e.profileJson||typeof e.profileJson!="object")return{valid:!1,error:"profileJson is required"};let t=e.profileJson;return typeof t.cookieTemplateId!="string"||!t.cookieTemplateId?{valid:!1,error:"profileJson.cookieTemplateId is required"}:typeof t.uiTemplateId!="string"||!t.uiTemplateId?{valid:!1,error:"profileJson.uiTemplateId is required"}:{valid:!0}}function Bi(s){return!s||typeof s!="object"?{valid:!1,error:"Request body must be a JSON object"}:{valid:!0}}function Vi(s,e){return{tenantId:e,name:s.name,defaultLocale:s.defaultLocale,profileJson:s.profileJson}}function Wi(s){let e={};return typeof s.name=="string"&&(e.name=s.name),typeof s.defaultLocale=="string"&&(e.defaultLocale=s.defaultLocale),s.profileJson!=null&&(e.profileJson=s.profileJson),e}function we(s,e){let t=ji[e];if(!t)return{valid:!0,errors:[],warnings:[]};let n=[],i=[];for(let o of s){let r=o;for(let a of t.errors)a.check(r)&&n.push({cookieId:o.id,field:a.field,message:a.message(o.id),rule:a.rule});for(let a of t.warnings)a.check(r)&&i.push({cookieId:o.id,field:a.field,message:a.message(o.id),suggestion:a.suggestion})}return{valid:n.length===0,errors:n,warnings:i}}function Ji(s,e,t,n){async function i(r,a){let c=await C(r,e,t,n);return{user:c,denied:P(c,a)}}function o(r,a){return r?r.allowedTenants.length===0||r.allowedTenants.includes(a):!1}return{"GET /profiles":async(r,a)=>g(async()=>{let{user:c,denied:l}=await i(r,"profile:view");return l||(o(c,"default")?new URL(r.url).searchParams.get("summary")==="1"?y(200,await s.listSummary()):y(200,await s.list()):y(200,[]))}),"GET /profiles/:id":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:view");if(c)return c;let l=await s.get(a.id??"");return l?y(200,l):m(404,"Profile not found")}),"POST /profiles/validate":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:view");if(c)return c;let l=await v(r);return!l.complianceGroup||!Array.isArray(l.cookies)?m(400,"complianceGroup and cookies are required"):y(200,we(l.cookies,l.complianceGroup))}),"GET /compliance-coverage":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:view");if(c)return c;let l={};for(let[u,d]of Object.entries(Hi)){let p=await s.findActiveByComplianceGroup(u);l[u]={label:d.label,compliances:d.compliances,activeProfile:p?{id:p.id,name:p.name}:null}}return y(200,{groups:l})}),"POST /profiles":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:create");if(c)return c;let l=await v(r),u=$i(l);if(!u.valid)return m(400,u.error??"Invalid body");let d=Vi(l,"default"),p=d.profileJson.complianceGroup,E=typeof l.choice=="string"?l.choice:void 0;if(p){let f=d.profileJson.cookies??[],_=we(f,p);if(!_.valid)return m(422,"Profile does not meet compliance requirements",{errors:_.errors,warnings:_.warnings});let h=await s.findActiveByComplianceGroup(p);if(h){if(!E)return y(200,{conflict:{id:h.id,name:h.name},requiresChoice:!0});E==="deactivate"&&await s.deactivate(h.id)}let A=await s.create(d);return y(201,{profile:A,warnings:_.warnings})}let S=await s.create(d);return y(201,S)}),"PUT /profiles/:id":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:update");if(c)return c;let l=a.id??"",u=await v(r),d=Bi(u);if(!d.valid)return m(400,d.error??"Invalid body");let p=Wi(u),E=p.profileJson?.complianceGroup,S=typeof u.choice=="string"?u.choice:void 0;if(E){let _=p.profileJson?.cookies??[],h=we(_,E);if(!h.valid)return m(422,"Profile does not meet compliance requirements",{errors:h.errors,warnings:h.warnings});let A=await s.findActiveByComplianceGroup(E);if(A&&A.id!==l){if(!S)return y(200,{conflict:{id:A.id,name:A.name},requiresChoice:!0});S==="deactivate"&&await s.deactivate(A.id)}let T=await s.update(l,p);return y(200,{profile:T,warnings:h.warnings})}let f=await s.update(l,p);return y(200,f)}),"DELETE /profiles/:id":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:delete");return c||(await s.delete(a.id??""),y(200,{success:!0}))}),"POST /profiles/:id/activate":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:update");if(c)return c;let l=a.id??"",u=await v(r),d=typeof u?.choice=="string"?u.choice:void 0,p=await s.get(l);if(!p)return m(404,"Profile not found");let E=p.profileJson.complianceGroup;if(E){let f=await s.findActiveByComplianceGroup(E);if(f&&f.id!==l){if(!d)return y(200,{conflict:{id:f.id,name:f.name},requiresChoice:!0});d==="deactivate"&&await s.deactivate(f.id)}}let S=await s.activate(l);return y(200,S)}),"POST /profiles/:id/deactivate":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:update");if(c)return c;let l=await s.deactivate(a.id??"");return y(200,l)}),"GET /profiles/:id/versions":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:view");return c||y(200,s.listVersions(a.id??""))}),"GET /profiles/:id/versions/:version":async(r,a)=>g(async()=>{let{denied:c}=await i(r,"profile:view");if(c)return c;let u=new URL(r.url).searchParams.get("locale")??"default",d=parseInt(a.version??"0",10);if(isNaN(d)||d<1)return m(400,"Invalid version number");let p=s.getVersionFile(a.id??"",d,u);return p?new Response(p,{headers:{"Content-Type":"application/json"}}):m(404,"Version file not found")})}}function qi(s,e,t){async function n(i,o){let r=await C(i,s,e,t);return{user:r,denied:P(r,o)}}return{"GET /consents":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"consent:view");if(a)return a;if(r?.allowedTenants.length&&!r.allowedTenants.includes("default"))return y(200,{items:[],total:0,page:1,limit:50});let c=new URL(i.url),l=k(c,"profileId"),u=k(c,"from"),d=k(c,"to"),p=Y(c,"limit",50);if(p>500)return m(400,"limit must not exceed 500");let E={tenantId:"default",page:Y(c,"page",1),limit:p,...l!==void 0?{profileId:l}:{},...u!==void 0?{from:u}:{},...d!==void 0?{to:d}:{}},S=await s.getConsents(E);return y(200,S)}),"GET /consents/:visitorId":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"consent:view");if(a)return a;if(r?.allowedTenants.length&&!r.allowedTenants.includes("default"))return m(403,"Forbidden");let c=await s.getConsent(o.visitorId??"");return c?y(200,c):m(404,"Consent not found")}),"GET /consents/:visitorId/history":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"consent:view");if(a)return a;if(r?.allowedTenants.length&&!r.allowedTenants.includes("default"))return m(403,"Forbidden");let c=await s.getConsentHistory(o.visitorId??"");return y(200,c)})}}function Ki(s,e,t){async function n(i,o){let r=await C(i,s,e,t);return{user:r,denied:P(r,o)}}return{"GET /visitors":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"visitor:view");if(a)return a;if(r?.allowedTenants.length&&!r.allowedTenants.includes("default"))return y(200,{items:[],total:0,page:1,limit:50});let c=new URL(i.url),l=k(c,"from"),u=k(c,"to"),d=Y(c,"limit",50);if(d>500)return m(400,"limit must not exceed 500");let p={tenantId:"default",page:Y(c,"page",1),limit:d,...l!==void 0?{from:l}:{},...u!==void 0?{to:u}:{}},E=await s.getVisitors(p);return y(200,E)})}}function Yi(s,e,t,n){async function i(o,r){let a=await C(o,e,t,n);return{user:a,denied:P(a,r)}}return{"GET /users":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"user:view");if(a)return a;let c=await s.list();return y(200,c)}),"GET /users/:id":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"user:view");if(a)return a;let c=await s.get(r.id??"");if(!c)return m(404,"User not found");let l=await s.getRoles(c.id);return y(200,{...c,roles:l.map(u=>({id:u.id,name:u.name}))})}),"POST /users":async(o,r)=>g(async()=>{let{user:a,denied:c}=await i(o,"user:create");if(c)return c;let l=await v(o);if(!l||typeof l!="object")return m(400,"Invalid body");let u=l;if(typeof u.name!="string"||!u.name)return m(400,"name is required");if(typeof u.email!="string"||!u.email)return m(400,"email is required");if(typeof u.password!="string"||!u.password)return m(400,"password is required");if(u.password.length<12)return m(400,"password must be at least 12 characters");let d=await s.create({name:u.name,email:u.email,password:u.password,...typeof u.roleId=="string"?{roleId:u.roleId}:{},...Array.isArray(u.allowedTenants)?{allowedTenants:u.allowedTenants}:{}},a.sub);return y(201,d)}),"PUT /users/:id":async(o,r)=>g(async()=>{let{user:a,denied:c}=await i(o,"user:update");if(c)return c;let l=r.id??"",u=await v(o);if(!u||typeof u!="object")return m(400,"Invalid body");let d=u;if(typeof d.password=="string"&&d.password.length<12)return m(400,"password must be at least 12 characters");let p=await s.update(l,{...typeof d.name=="string"?{name:d.name}:{},...typeof d.email=="string"?{email:d.email}:{},...d.isActive!=null?{isActive:!!d.isActive}:{},...typeof d.password=="string"?{password:d.password}:{},...Array.isArray(d.allowedTenants)?{allowedTenants:d.allowedTenants}:{}},a.sub);return y(200,p)}),"DELETE /users/:id":async(o,r)=>g(async()=>{let{user:a,denied:c}=await i(o,"user:delete");if(c)return c;let l=r.id??"";return l===a.sub?m(400,"Cannot delete your own account"):(await s.delete(l,a.sub),y(200,{success:!0}))}),"POST /users/:id/roles":async(o,r)=>g(async()=>{let{user:a,denied:c}=await i(o,"role:update");if(c)return c;let l=await v(o);if(!l||typeof l!="object")return m(400,"Invalid body");let u=l;if(typeof u.roleId!="string")return m(400,"roleId is required");let d=typeof u.tenantId=="string"?u.tenantId:void 0;return await s.assignRole(r.id??"",u.roleId,d),await e.createLog({tenantId:"default",userId:a.sub,action:"user.role_assigned",resourceType:"user",...r.id!=null?{resourceId:r.id}:{},newData:{roleId:u.roleId}}),y(200,{success:!0})}),"DELETE /users/:id/roles/:roleId":async(o,r)=>g(async()=>{let{user:a,denied:c}=await i(o,"role:update");if(c)return c;let u=new URL(o.url).searchParams.get("tenantId")??void 0;return await s.revokeRole(r.id??"",r.roleId??"",u),await e.createLog({tenantId:"default",userId:a.sub,action:"user.role_revoked",resourceType:"user",...r.id!=null?{resourceId:r.id}:{},oldData:{roleId:r.roleId}}),y(200,{success:!0})})}}function zi(s,e,t){async function n(i,o){let r=await C(i,s,e,t);return{user:r,denied:P(r,o)}}return{"GET /roles":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"role:view");if(r)return r;let a=await s.getRoles("default");return y(200,a)}),"GET /roles/:id/permissions":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"role:view");if(r)return r;let a=await s.getPermissionsForRole(o.id??"");return y(200,a)}),"POST /roles":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"role:create");if(a)return a;let c=await v(i);if(!c||typeof c!="object")return m(400,"Invalid body");let l=c;if(typeof l.name!="string"||!l.name)return m(400,"name is required");let u=await s.createRole({tenantId:"default",name:l.name,...typeof l.description=="string"?{description:l.description}:{}});return await s.createLog({tenantId:"default",userId:r.sub,action:"role.created",resourceType:"role",resourceId:u.id,newData:u}),y(201,u)}),"PUT /roles/:id":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"role:update");if(a)return a;let c=await v(i);if(!c||typeof c!="object")return m(400,"Invalid body");let l=c,u=await s.updateRole(o.id??"",{...typeof l.name=="string"?{name:l.name}:{},...typeof l.description=="string"?{description:l.description}:{}});return await s.createLog({tenantId:"default",userId:r.sub,action:"role.updated",resourceType:"role",resourceId:u.id,newData:u}),y(200,u)}),"DELETE /roles/:id":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"role:delete");return a||(await s.deleteRole(o.id??""),await s.createLog({tenantId:"default",userId:r.sub,action:"role.deleted",resourceType:"role",...o.id!=null?{resourceId:o.id}:{}}),y(200,{success:!0}))}),"GET /permissions":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"role:view");if(r)return r;let a=await s.getAllPermissions();return y(200,a)}),"POST /roles/:id/permissions":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"role:update");if(r)return r;let a=await v(i);if(!a||typeof a!="object")return m(400,"Invalid body");let c=a;return typeof c.permissionId!="string"?m(400,"permissionId is required"):(await s.assignPermissionToRole(o.id??"",c.permissionId),y(200,{success:!0}))}),"DELETE /roles/:id/permissions/:permissionId":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"role:update");return r||(await s.revokePermissionFromRole(o.id??"",o.permissionId??""),y(200,{success:!0}))})}}function Qi(s,e,t){async function n(i,o){let r=await C(i,s,e,t);return{user:r,denied:P(r,o)}}return{"GET /audit":async(i,o)=>g(async()=>{let{user:r,denied:a}=await n(i,"audit:view");if(a)return a;if(r?.allowedTenants.length&&!r.allowedTenants.includes("default"))return y(200,{items:[],total:0,page:1,limit:50});let c=new URL(i.url),l=k(c,"action"),u=k(c,"resourceType"),d=k(c,"from"),p=k(c,"to"),E=Y(c,"limit",50);if(E>500)return m(400,"limit must not exceed 500");let S={tenantId:"default",page:Y(c,"page",1),limit:E,...l!==void 0?{action:l}:{},...u!==void 0?{resourceType:u}:{},...d!==void 0?{from:d}:{},...p!==void 0?{to:p}:{}},f=await s.getLogs(S);return y(200,f)})}}function Xi(s,e,t){async function n(i){let o=await C(i,s,e,t);return{denied:P(o,"consent:view")}}return{"GET /stats/overview":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await s.getOverviewStats("default");return y(200,a)}),"GET /stats/categories":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await s.getCategoryStats("default");return y(200,a)}),"GET /stats/timeline":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=new URL(i.url),c=Y(a,"days",30),l=await s.getTimeline("default",c);return y(200,l)}),"GET /stats/countries":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await s.getCountries("default");return y(200,a)}),"GET /stats/gpc":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await s.getGpcStats("default");return y(200,a)}),"GET /stats/aggregate":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await s.getTenants(),c=await Promise.all(a.map(async u=>{let d=await s.getOverviewStats(u.id);return{tenantId:u.id,tenantName:u.name,...d}})),l=c.reduce((u,d)=>({totalConsents:u.totalConsents+d.totalConsents,totalVisitors:u.totalVisitors+d.totalVisitors,gpcDetectedCount:u.gpcDetectedCount+d.gpcDetectedCount}),{totalConsents:0,totalVisitors:0,gpcDetectedCount:0});return y(200,{aggregate:l,perTenant:c})})}}function Yt(s){let e=s==null?"":String(s);return e.includes(",")||e.includes('"')||e.includes(`
162
- `)?`"${e.replace(/"/g,'""')}"`:e}function Fo(s){return[s.id,s.visitorId,s.profileId,s.profileVersion,s.locale,JSON.stringify(s.consentJson),s.gpcDetected?"1":"0",s.source,s.createdAt,s.updatedAt].map(Yt).join(",")+`
163
- `}function Ho(s){return[s.id,s.userId??"",s.action,s.resourceType,s.resourceId??"",s.createdAt].map(Yt).join(",")+`
164
- `}function Zi(s,e,t){async function n(i){let o=await C(i,s,e,t);return{denied:P(o,"export:run")}}return{"GET /export/consents":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=new URL(i.url),c=k(a,"format")??"csv",l=k(a,"profileId"),u=k(a,"from"),d=k(a,"to"),p={tenantId:"default",...l!==void 0?{profileId:l}:{},...u!==void 0?{from:u}:{},...d!==void 0?{to:d}:{}};if(c==="json"){let _=[];for await(let h of s.streamConsents(p))_.push(h);return new Response(JSON.stringify(_),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":'attachment; filename="consents.json"'}})}let E=new TextEncoder,S=`id,visitor_id,profile_id,profile_version,locale,consent_json,gpc_detected,source,created_at,updated_at
165
- `,f=new ReadableStream({async start(_){_.enqueue(E.encode(S));for await(let h of s.streamConsents(p))_.enqueue(E.encode(Fo(h)));_.close()}});return new Response(f,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":'attachment; filename="consents.csv"'}})}),"GET /export/consents/xlsx":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=null;try{a=await import("xlsx")}catch{return new Response(JSON.stringify({error:"xlsx peer dependency not installed. Run: npm install xlsx"}),{status:501,headers:{"Content-Type":"application/json"}})}if(!a)return new Response(null,{status:501});let c=new URL(i.url),l=c.searchParams.get("profileId")??void 0,u=c.searchParams.get("from")??void 0,d=c.searchParams.get("to")??void 0,p={tenantId:"default",...l!==void 0?{profileId:l}:{},...u!==void 0?{from:u}:{},...d!==void 0?{to:d}:{}},E=[];for await(let h of s.streamConsents(p))E.push({id:h.id,visitor_id:h.visitorId,profile_id:h.profileId,profile_version:h.profileVersion,locale:h.locale,consent_json:JSON.stringify(h.consentJson),gpc_detected:h.gpcDetected?1:0,age_verified:h.ageVerified?1:0,tcf_string:h.tcfString??"",source:h.source,created_at:h.createdAt,updated_at:h.updatedAt});let S=a.utils.book_new(),f=a.utils.json_to_sheet(E);a.utils.book_append_sheet(S,f,"Consents");let _=a.write(S,{type:"buffer",bookType:"xlsx"});return new Response(_,{status:200,headers:{"Content-Type":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","Content-Disposition":'attachment; filename="consents.xlsx"'}})}),"GET /export/translations/:profileId":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=o.profileId??"",c=await s.getProfile(a);if(!c)return m(404,"Profile not found");let l=c.profileJson.translations??{},u=Object.keys(l);if(u.length===0)return new Response(`locale,field,value
166
- `,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${a}-translations.csv"`}});let d=["locale,section,field,value"];for(let p of u){let E=l[p];if(E){for(let[S,f]of Object.entries(E))if(typeof f=="object"&&f!==null)for(let[_,h]of Object.entries(f))typeof h=="string"&&d.push([p,S,_,h].map(Yt).join(","))}}return new Response(d.join(`
150
+ </EntityDescriptor>`}async function ra(i,e){let t;try{t=await import("samlify")}catch{return console.warn("[Consenti] samlify is not installed. Install it to use SAML auth mode."),null}try{let n=t.ServiceProvider({entityID:"saml:sp:consenti",assertionConsumerService:[{Binding:"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",Location:e.callbackUrl}]}),o=t.IdentityProvider({entityID:e.issuer,singleSignOnService:[{Binding:"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",Location:e.entryPoint}],signingCert:e.cert}),r=await n.parseLoginResponse(o,"post",{body:{SAMLResponse:i}}),s=r.extract.nameID,a=r.extract.attributes.roles,c=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];return{email:s,roles:c}}catch(n){return console.warn("[Consenti] SAML response validation failed:",n),null}}p();var Ge=require("node:crypto"),hi="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function bd(i){let e="",t=0,n=0;for(let o of i)for(n=n<<8|o,t+=8;t>=5;)e+=hi[n>>>t-5&31],t-=5;return t>0&&(e+=hi[n<<5-t&31]),e}function Od(i){let e=i.toUpperCase().replace(/[^A-Z2-7]/g,""),t=[],n=0,o=0;for(let r of e){let s=hi.indexOf(r);s<0||(o=o<<5|s,n+=5,n>=8&&(t.push(o>>>n-8&255),n-=8))}return Buffer.from(t)}function Dd(i,e){let t=Buffer.alloc(8),n=e;for(let a=7;a>=0;a--)t[a]=n&255,n=Math.floor(n/256);let o=(0,Ge.createHmac)("sha1",i).update(t).digest(),r=o[o.length-1]&15,s=(o[r]&127)<<24|(o[r+1]&255)<<16|(o[r+2]&255)<<8|o[r+3]&255;return String(s%1e6).padStart(6,"0")}function sa(){return bd((0,Ge.randomBytes)(20))}var _n=new Map;setInterval(()=>{let i=Date.now();for(let[e,t]of _n)i>=t&&_n.delete(e)},9e4).unref();function aa(i,e,t=1){if(_n.has(e))return!1;let n=Math.floor(Date.now()/3e4),o=Od(i),r=Buffer.from(e);for(let s=-t;s<=t;s++){let a=Buffer.from(Dd(o,n+s));if(a.length===r.length&&(0,Ge.timingSafeEqual)(a,r))return _n.set(e,Date.now()+9e4),!0}return!1}function ca(i,e,t="Consenti"){let n=encodeURIComponent(`${t}:${e}`),o=new URLSearchParams({secret:i,issuer:t,algorithm:"SHA1",digits:"6",period:"30"});return`otpauth://totp/${n}?${o.toString()}`}function la(i){return i.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function da(i,e,t,n,o){function r(s){if(!o)return null;let a=s.headers.get("x-real-ip")??"";return o.checkRequest(a)?null:g(429,"Too Many Requests")}return{"POST /auth/login":async(s,a)=>E(async()=>{let c=r(s);if(c)return c;if(t.mode!=="local")return g(400,"Login not available in this auth mode");let l=await I(s);if(!l||typeof l!="object")return g(400,"Invalid body");let d=l;if(typeof d.email!="string"||typeof d.password!="string")return g(400,"email and password are required");let u=await i.login(d.email,d.password);return u?y(200,{token:u}):g(401,"Invalid credentials")}),"GET /auth/me":async(s,a)=>E(async()=>{let c=await b(s,e,t,n);if(!c)return g(401,"Unauthorized");let l=await e.getUserById(c.sub);if(!l)return g(401,"User not found");let d=await e.getUserRoles(l.id);return y(200,{id:l.id,email:l.email,name:l.name,isActive:l.isActive,totpEnabled:l.totpEnabled??!1,roles:d.map(u=>u.name),permissions:c.permissions})}),"POST /auth/logout":async(s,a)=>E(async()=>y(200,{success:!0})),"POST /auth/refresh":async(s,a)=>E(async()=>{let c=await b(s,e,t,n);if(!c)return g(401,"Unauthorized");let l=i.signToken({sub:c.sub,email:c.email,roles:c.roles,permissions:c.permissions,allowedTenants:c.allowedTenants});return y(200,{token:l})}),"GET /auth/oidc/authorize":async(s,a)=>E(async()=>{if(t.mode!=="oidc"||!t.oidc)return g(400,"OIDC not configured");let c=await fi(t.oidc.issuer),l=la((0,yi.randomBytes)(16)),d=la((0,yi.randomBytes)(16)),{verifier:u,challenge:m}=Ys();na(l,u,d);let h=Qs(t.oidc,c.authorization_endpoint,l,d,m);return new Response(null,{status:302,headers:{Location:h}})}),"GET /auth/oidc/callback":async(s,a)=>E(async()=>{if(t.mode!=="oidc"||!t.oidc)return g(400,"OIDC not configured");let c=new URL(s.url),l=c.searchParams.get("code"),d=c.searchParams.get("state");if(!l||!d)return g(400,"Missing code or state");let u=ia(d);if(!u)return g(400,"Invalid or expired state");let m=await fi(t.oidc.issuer),h=await Zs(t.oidc,m.token_endpoint,l,u.verifier),S=await Xs(h.id_token,m.jwks_uri),_=ea(S,t.oidc.claimsMapping),w=ta(S,t.oidc.claimsMapping),R=await e.getUserByEmail(_);if(R||(R=await e.createUser({tenantId:"default",name:_,email:_,passwordHash:""})),w.length>0){let O=await e.getRoles("default");for(let D of w){let G=O.find(N=>N.name===D);G&&await e.assignRole(R.id,G.id).catch(()=>{})}}let v=await e.getUserRoles(R.id),A=[];for(let O of v){let D=await e.getPermissionsForRole(O.id);A.push(...D.map(G=>G.name))}let P=i.signToken({sub:R.id,email:R.email,roles:v.map(O=>O.name),permissions:[...new Set(A)]});return y(200,{token:P})}),"GET /auth/saml/metadata":async(s,a)=>E(async()=>{if(t.mode!=="saml"||!t.saml)return g(400,"SAML not configured");let c=oa(t.saml);return new Response(c,{status:200,headers:{"Content-Type":"application/xml"}})}),"POST /auth/saml/acs":async(s,a)=>E(async()=>{let c=r(s);if(c)return c;if(t.mode!=="saml"||!t.saml)return g(400,"SAML not configured");let d=new URLSearchParams(await s.text()).get("SAMLResponse");if(typeof d!="string")return g(400,"Missing SAMLResponse");let u=await ra(d,t.saml);if(!u)return g(401,"SAML validation failed");let m=await e.getUserByEmail(u.email);m||(m=await e.createUser({tenantId:"default",name:u.email,email:u.email,passwordHash:""}));let h=await e.getUserRoles(m.id),S=[];for(let w of h){let R=await e.getPermissionsForRole(w.id);S.push(...R.map(v=>v.name))}let _=i.signToken({sub:m.id,email:m.email,roles:h.map(w=>w.name),permissions:[...new Set(S)]});return y(200,{token:_})}),"POST /auth/totp/setup":async(s,a)=>E(async()=>{let c=await b(s,e,t,n);if(!c)return g(401,"Unauthorized");let l=await e.getUserById(c.sub);if(!l)return g(401,"User not found");let d=sa(),u=ca(d,l.email);return await e.updateUser(l.id,{totpSecret:d,totpEnabled:!1}),y(200,{qrUrl:u,message:"Scan QR code, then verify with POST /auth/totp/verify"})}),"POST /auth/totp/verify":async(s,a)=>E(async()=>{let c=r(s);if(c)return c;let l=await b(s,e,t,n);if(!l)return g(401,"Unauthorized");let d=await e.getUserById(l.sub);if(!d)return g(401,"User not found");if(!d.totpSecret)return g(400,"TOTP not set up \u2014 call POST /auth/totp/setup first");let u=await I(s);if(!u||typeof u!="object")return g(400,"Invalid body");let m=u;return typeof m.token!="string"?g(400,"token is required"):aa(d.totpSecret,m.token)?(await e.updateUser(d.id,{totpEnabled:!0}),y(200,{success:!0,message:"TOTP enabled successfully"})):g(400,"Invalid TOTP token")}),"POST /auth/totp/disable":async(s,a)=>E(async()=>{let c=await b(s,e,t,n);if(!c)return g(401,"Unauthorized");let l=await e.getUserById(c.sub);return l?(await e.updateUser(l.id,{totpSecret:null,totpEnabled:!1}),y(200,{success:!0,message:"TOTP disabled"})):g(401,"User not found")})}}p();re();p();function ua(i){if(!i||typeof i!="object")return{valid:!1,error:"Request body must be a JSON object"};let e=i;if(typeof e.name!="string"||!e.name)return{valid:!1,error:"name is required"};if(typeof e.defaultLocale!="string"||!e.defaultLocale)return{valid:!1,error:"defaultLocale is required"};if(!e.profileJson||typeof e.profileJson!="object")return{valid:!1,error:"profileJson is required"};let t=e.profileJson;return typeof t.consentTemplateId!="string"||!t.consentTemplateId?{valid:!1,error:"profileJson.consentTemplateId is required"}:typeof t.uiTemplateId!="string"||!t.uiTemplateId?{valid:!1,error:"profileJson.uiTemplateId is required"}:{valid:!0}}function pa(i){return!i||typeof i!="object"?{valid:!1,error:"Request body must be a JSON object"}:{valid:!0}}function ma(i,e){return{tenantId:e,name:i.name,defaultLocale:i.defaultLocale,profileJson:i.profileJson,...i.localeContent!=null?{localeContent:i.localeContent}:{}}}function ga(i){let e={};return typeof i.name=="string"&&(e.name=i.name),typeof i.defaultLocale=="string"&&(e.defaultLocale=i.defaultLocale),i.profileJson!=null&&(e.profileJson=i.profileJson),i.localeContent!=null&&(e.localeContent=i.localeContent),e}p();re();function je(i,e,t){let n=ti[t];if(!n)return{valid:!0,errors:[],warnings:[]};let o=[],r=[],s=xe(e);for(let[a,c]of Object.entries(e)){let l=c;for(let d of n.categoryErrors)d.check(l,void 0)&&o.push({cookieId:a,field:d.field,message:d.message(a),rule:d.rule});for(let d of n.categoryWarnings)d.check(l,void 0)&&r.push({cookieId:a,field:d.field,message:d.message(a),suggestion:d.suggestion})}for(let[a,c]of Object.entries(i)){let l=c,d=Me(a,s);for(let u of n.cookieErrors)u.check(l,d)&&o.push({cookieId:a,field:u.field,message:u.message(a),rule:u.rule});for(let u of n.cookieWarnings)u.check(l,d)&&r.push({cookieId:a,field:u.field,message:u.message(a),suggestion:u.suggestion})}return{valid:o.length===0,errors:o,warnings:r}}p();re();function fa(i,e,t){let n=[];tn(t.htmlText)||n.push({locale:i,section:e,field:"htmlText",message:"Body text is required"});for(let[o,r]of Object.entries(t.buttons))r.text?.trim()||n.push({locale:i,section:e,field:`buttons.${o}`,message:`Label for button "${o}" is required`});return n}function kd(i,e){let t=[];e.heading?.trim()||t.push({locale:i,section:"preferenceModal",field:"heading",message:"Heading is required"}),tn(e.htmlText)||t.push({locale:i,section:"preferenceModal",field:"htmlText",message:"Intro text is required"});for(let[n,o]of Object.entries(e.buttons))o.text?.trim()||t.push({locale:i,section:"preferenceModal",field:`buttons.${n}`,message:`Label for button "${n}" is required`});for(let[n,o]of Object.entries(e.categories))o.heading?.trim()||t.push({locale:i,section:"preferenceModal",field:`categories.${n}.heading`,message:`Heading for category "${n}" is required`});return t}function _i(i){let e=[];for(let[t,n]of Object.entries(i))e.push(...fa(t,"mainBanner",n.mainBanner)),n.gpcBanner&&e.push(...fa(t,"gpcBanner",n.gpcBanner)),e.push(...kd(t,n.preferenceModal));return{valid:e.length===0,errors:e}}function ha(i,e){let t={...e};return i?.defaultLocale&&i.mainBanner&&i.preferenceModal&&(t[i.defaultLocale]={mainBanner:i.mainBanner,...i.gpcBanner?{gpcBanner:i.gpcBanner}:{},preferenceModal:i.preferenceModal}),t}function ya(i,e,t,n){async function o(s,a){let c=await b(s,e,t,n);return{user:c,denied:k(c,a)}}function r(s,a){return s?s.allowedTenants.length===0||s.allowedTenants.includes(a):!1}return{"GET /profiles":async(s,a)=>E(async()=>{let{user:c,denied:l}=await o(s,"profile:view");return l||(r(c,"default")?new URL(s.url).searchParams.get("summary")==="1"?y(200,await i.listSummary()):y(200,await i.list()):y(200,[]))}),"GET /profiles/archived":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:view");return c||y(200,await i.listArchivedProfiles())}),"GET /profiles/:id":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:view");if(c)return c;let l=await i.get(a.id??"");return l?y(200,l):g(404,"Profile not found")}),"POST /profiles/validate":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:view");if(c)return c;let l=await I(s);return!l.complianceGroup||!l.cookies||typeof l.cookies!="object"||!l.categories||typeof l.categories!="object"?g(400,"complianceGroup, cookies, and categories are required"):y(200,je(l.cookies,l.categories,l.complianceGroup))}),"GET /compliance-coverage":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:view");if(c)return c;let l={};for(let[d,u]of Object.entries(Xe)){let m=await i.findActiveByComplianceGroup(d);l[d]={label:u.label,compliances:u.compliances,activeProfile:m?{id:m.id,name:m.name}:null}}return y(200,{groups:l})}),"POST /profiles":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:create");if(c)return c;let l=await I(s),d=ua(l);if(!d.valid)return g(400,d.error??"Invalid body");let u=ma(l,"default"),m=_i(ha(u.profileJson,u.localeContent));if(!m.valid)return g(422,"Profile content is missing required fields",{errors:m.errors});let h=u.profileJson.complianceGroup,S=u.profileJson.customComplianceGroup,_=typeof l.choice=="string"?l.choice:void 0;if(h){let R=u.profileJson.cookies??{},v=u.profileJson.preferenceModal?.categories??{},A=je(R,v,h);if(!A.valid)return g(422,"Profile does not meet compliance requirements",{errors:A.errors,warnings:A.warnings});let P=await i.findActiveByComplianceGroup(h);if(P){if(!_)return y(200,{conflict:{id:P.id,name:P.name},requiresChoice:!0});_==="deactivate"?(await i.deactivate(P.id),u.profileJson.isActive=!0):_==="inactive"&&(u.profileJson.isActive=!1)}let O=await i.create(u);return y(201,{profile:O,warnings:A.warnings})}if(S){let R=await i.findActiveByComplianceGroup(S);if(R){if(!_)return y(200,{conflict:{id:R.id,name:R.name},requiresChoice:!0});_==="deactivate"?(await i.deactivate(R.id),u.profileJson.isActive=!0):_==="inactive"&&(u.profileJson.isActive=!1)}}let w=await i.create(u);return y(201,w)}),"PUT /profiles/:id":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:update");if(c)return c;let l=a.id??"",d=await I(s),u=pa(d);if(!u.valid)return g(400,u.error??"Invalid body");let m=ga(d),h=ha(m.profileJson,m.localeContent);if(Object.keys(h).length>0){let v=_i(h);if(!v.valid)return g(422,"Profile content is missing required fields",{errors:v.errors})}let S=m.profileJson?.complianceGroup,_=m.profileJson?.customComplianceGroup,w=typeof d.choice=="string"?d.choice:void 0;if(S){let v=m.profileJson?.cookies??{},A=m.profileJson?.preferenceModal?.categories??{},P=je(v,A,S);if(!P.valid)return g(422,"Profile does not meet compliance requirements",{errors:P.errors,warnings:P.warnings});let O=await i.findActiveByComplianceGroup(S);if(O&&O.id!==l){if(!w)return y(200,{conflict:{id:O.id,name:O.name},requiresChoice:!0});w==="deactivate"?(await i.deactivate(O.id),m.profileJson.isActive=!0):w==="inactive"&&(m.profileJson.isActive=!1)}let D=await i.update(l,m);return y(200,{profile:D,warnings:P.warnings})}if(_){let v=await i.findActiveByComplianceGroup(_);if(v&&v.id!==l){if(!w)return y(200,{conflict:{id:v.id,name:v.name},requiresChoice:!0});w==="deactivate"?(await i.deactivate(v.id),m.profileJson.isActive=!0):w==="inactive"&&(m.profileJson.isActive=!1)}}let R=await i.update(l,m);return y(200,R)}),"DELETE /profiles/:id":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:delete");return c||(await i.delete(a.id??""),y(200,{success:!0}))}),"POST /profiles/:id/copy":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:create");if(c)return c;let l=a.id??"";if(!await i.get(l))return g(404,"Profile not found");let u=await I(s),m=typeof u?.name=="string"?u.name:void 0,h=await i.copy(l,m);return y(201,h)}),"POST /profiles/:id/activate":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:update");if(c)return c;let l=a.id??"",d=await I(s),u=typeof d?.choice=="string"?d.choice:void 0,m=await i.get(l);if(!m)return g(404,"Profile not found");let h=m.profileJson,S=h.complianceGroup||h.customComplianceGroup;if(S){let w=await i.findActiveByComplianceGroup(S);if(w&&w.id!==l){if(!u)return y(200,{conflict:{id:w.id,name:w.name},requiresChoice:!0});u==="deactivate"&&await i.deactivate(w.id)}}let _=await i.activate(l);return y(200,_)}),"POST /profiles/:id/deactivate":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:update");if(c)return c;let l=await i.deactivate(a.id??"");return y(200,l)}),"GET /profiles/:id/versions":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:view");return c||y(200,await i.listVersions(a.id??""))}),"GET /profiles/:id/versions/:entryId":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"profile:view");if(c)return c;let d=new URL(s.url).searchParams.get("locale")??"default",u=a.entryId??"";if(!u)return g(400,"Invalid version id");let m=await i.getVersionFile(a.id??"",u,d);return m?new Response(m,{headers:{"Content-Type":"application/json"}}):g(404,"Version file not found")})}}p();function _a(i,e,t){async function n(o,r){let s=await b(o,i,e,t);return{user:s,denied:k(s,r)}}return{"GET /consents":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"consent:view");if(a)return a;if(s?.allowedTenants.length&&!s.allowedTenants.includes("default"))return y(200,{items:[],total:0,page:1,limit:50});let c=new URL(o.url),l=U(c,"profileId"),d=U(c,"from"),u=U(c,"to"),m=U(c,"q"),h=Ue(c);if("error"in h)return g(400,h.error);let{page:S,limit:_}=h,w={tenantId:"default",page:S,limit:_,...l!==void 0?{profileId:l}:{},...d!==void 0?{from:d}:{},...u!==void 0?{to:u}:{},...m!==void 0?{q:m}:{}},R=await i.getConsents(w);return y(200,R)}),"GET /consents/:visitorId":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"consent:view");if(a)return a;if(s?.allowedTenants.length&&!s.allowedTenants.includes("default"))return g(403,"Forbidden");let c=await i.getConsent(r.visitorId??"");return c?y(200,c):g(404,"Consent not found")}),"GET /consents/:visitorId/history":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"consent:view");if(a)return a;if(s?.allowedTenants.length&&!s.allowedTenants.includes("default"))return g(403,"Forbidden");let c=await i.getConsentHistory(r.visitorId??"");return y(200,c)})}}p();var Ld=!1;function wa(i,e,t){async function n(o,r){let s=await b(o,i,e,t);return{user:s,denied:k(s,r)}}return{"GET /visitors":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"visitor:view");if(a)return a;if(s?.allowedTenants.length&&!s.allowedTenants.includes("default"))return y(200,{items:[],total:0,page:1,limit:50});let c=new URL(o.url),l=U(c,"from"),d=U(c,"to"),u=U(c,"q"),m=Ue(c);if("error"in m)return g(400,m.error);let{page:h,limit:S}=m,_={tenantId:"default",page:h,limit:S,...l!==void 0?{from:l}:{},...d!==void 0?{to:d}:{},...u!==void 0?{q:u}:{}},w=await i.getVisitors(_);return y(200,w)}),"GET /visitors/:visitorId/notice-shown":async(o,r)=>E(async()=>{if(!Ld)return g(404,"Not found");let{denied:s}=await n(o,"visitor:view");if(s)return s;let a=await i.getNoticeShownForVisitor(r.visitorId??"");return y(200,a)})}}p();var Ea="role_super_admin";function Ra(i,e,t,n){async function o(s,a){let c=await b(s,e,t,n);return{user:c,denied:k(c,a)}}async function r(s){return(await i.getRoles(s)).some(c=>c.id===Ea)}return{"GET /users":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"user:view");if(c)return c;let l=await i.list(),d=await Promise.all(l.map(async u=>({...u,roles:(await i.getRoles(u.id)).map(m=>({id:m.id,name:m.name}))})));return y(200,d)}),"GET /users/:id":async(s,a)=>E(async()=>{let{denied:c}=await o(s,"user:view");if(c)return c;let l=await i.get(a.id??"");if(!l)return g(404,"User not found");let d=await i.getRoles(l.id);return y(200,{...l,roles:d.map(u=>({id:u.id,name:u.name}))})}),"POST /users":async(s,a)=>E(async()=>{let{user:c,denied:l}=await o(s,"user:create");if(l)return l;let d=await I(s);if(!d||typeof d!="object")return g(400,"Invalid body");let u=d;if(typeof u.name!="string"||!u.name)return g(400,"name is required");if(typeof u.email!="string"||!u.email)return g(400,"email is required");if(typeof u.password!="string"||!u.password)return g(400,"password is required");if(u.password.length<12)return g(400,"password must be at least 12 characters");let m=await i.create({name:u.name,email:u.email,password:u.password,...typeof u.roleId=="string"?{roleId:u.roleId}:{},...Array.isArray(u.allowedTenants)?{allowedTenants:u.allowedTenants}:{}},c.sub);return y(201,m)}),"PUT /users/:id":async(s,a)=>E(async()=>{let{user:c,denied:l}=await o(s,"user:update");if(l)return l;let d=a.id??"";if(d!==c.sub&&await r(d))return g(403,"Super admin users cannot be modified");let u=await I(s);if(!u||typeof u!="object")return g(400,"Invalid body");let m=u;if(typeof m.password=="string"&&m.password.length<12)return g(400,"password must be at least 12 characters");let h=await i.update(d,{...typeof m.name=="string"?{name:m.name}:{},...typeof m.email=="string"?{email:m.email}:{},...m.isActive!=null?{isActive:!!m.isActive}:{},...typeof m.password=="string"?{password:m.password}:{},...Array.isArray(m.allowedTenants)?{allowedTenants:m.allowedTenants}:{}},c.sub);return y(200,h)}),"DELETE /users/:id":async(s,a)=>E(async()=>{let{user:c,denied:l}=await o(s,"user:delete");if(l)return l;let d=a.id??"";return d===c.sub?g(400,"Cannot delete your own account"):await r(d)?g(403,"Super admin users cannot be deleted"):(await i.delete(d,c.sub),y(200,{success:!0}))}),"POST /users/:id/roles":async(s,a)=>E(async()=>{let{user:c,denied:l}=await o(s,"role:update");if(l)return l;let d=await I(s);if(!d||typeof d!="object")return g(400,"Invalid body");let u=d;if(typeof u.roleId!="string")return g(400,"roleId is required");let m=typeof u.tenantId=="string"?u.tenantId:void 0;return await i.assignRole(a.id??"",u.roleId,m),await e.createLog({tenantId:"default",userId:c.sub,action:"user.role_assigned",resourceType:"user",...a.id!=null?{resourceId:a.id}:{},newData:{roleId:u.roleId}}),y(200,{success:!0})}),"DELETE /users/:id/roles/:roleId":async(s,a)=>E(async()=>{let{user:c,denied:l}=await o(s,"role:update");if(l)return l;if(a.roleId===Ea)return g(403,"The super_admin role cannot be revoked");let u=new URL(s.url).searchParams.get("tenantId")??void 0;return await i.revokeRole(a.id??"",a.roleId??"",u),await e.createLog({tenantId:"default",userId:c.sub,action:"user.role_revoked",resourceType:"user",...a.id!=null?{resourceId:a.id}:{},oldData:{roleId:a.roleId}}),y(200,{success:!0})})}}p();var wn="role_super_admin";function Sa(i,e,t){async function n(o,r){let s=await b(o,i,e,t);return{user:s,denied:k(s,r)}}return{"GET /roles":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"role:view");if(s)return s;let a=await i.getRoles("default");return y(200,a)}),"GET /roles/:id/permissions":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"role:view");if(s)return s;let a=await i.getPermissionsForRole(r.id??"");return y(200,a)}),"POST /roles":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"role:create");if(a)return a;let c=await I(o);if(!c||typeof c!="object")return g(400,"Invalid body");let l=c;if(typeof l.name!="string"||!l.name)return g(400,"name is required");let d=await i.createRole({tenantId:"default",name:l.name,...typeof l.description=="string"?{description:l.description}:{}});return await i.createLog({tenantId:"default",userId:s.sub,action:"role.created",resourceType:"role",resourceId:d.id,newData:d}),y(201,d)}),"PUT /roles/:id":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"role:update");if(a)return a;if(r.id===wn)return g(403,"The super_admin role cannot be modified");let c=await I(o);if(!c||typeof c!="object")return g(400,"Invalid body");let l=c,d=await i.updateRole(r.id??"",{...typeof l.name=="string"?{name:l.name}:{},...typeof l.description=="string"?{description:l.description}:{}});return await i.createLog({tenantId:"default",userId:s.sub,action:"role.updated",resourceType:"role",resourceId:d.id,newData:d}),y(200,d)}),"DELETE /roles/:id":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"role:delete");return a||(r.id===wn?g(403,"The super_admin role cannot be deleted"):(await i.deleteRole(r.id??""),await i.createLog({tenantId:"default",userId:s.sub,action:"role.deleted",resourceType:"role",...r.id!=null?{resourceId:r.id}:{}}),y(200,{success:!0})))}),"GET /permissions":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"role:view");if(s)return s;let a=await i.getAllPermissions();return y(200,a)}),"POST /roles/:id/permissions":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"role:update");if(s)return s;if(r.id===wn)return g(403,"The super_admin role cannot be modified");let a=await I(o);if(!a||typeof a!="object")return g(400,"Invalid body");let c=a;return typeof c.permissionId!="string"?g(400,"permissionId is required"):(await i.assignPermissionToRole(r.id??"",c.permissionId),y(200,{success:!0}))}),"DELETE /roles/:id/permissions/:permissionId":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"role:update");return s||(r.id===wn?g(403,"The super_admin role cannot be modified"):(await i.revokePermissionFromRole(r.id??"",r.permissionId??""),y(200,{success:!0})))})}}p();function va(i,e,t){async function n(o,r){let s=await b(o,i,e,t);return{user:s,denied:k(s,r)}}return{"GET /audit":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"audit:view");if(a)return a;if(s?.allowedTenants.length&&!s.allowedTenants.includes("default"))return y(200,{items:[],total:0,page:1,limit:50});let c=new URL(o.url),l=U(c,"action"),d=U(c,"resourceType"),u=U(c,"from"),m=U(c,"to"),h=U(c,"q"),S=Ue(c);if("error"in S)return g(400,S.error);let{page:_,limit:w}=S,R={tenantId:"default",page:_,limit:w,...l!==void 0?{action:l}:{},...d!==void 0?{resourceType:d}:{},...u!==void 0?{from:u}:{},...m!==void 0?{to:m}:{},...h!==void 0?{q:h}:{}},v=await i.getLogs(R);return y(200,v)}),"GET /audit/:id":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o,"audit:view");if(a)return a;if(s?.allowedTenants.length&&!s.allowedTenants.includes("default"))return g(403,"Forbidden");let c=await i.getAuditLogById(r.id??"");return!c||c.tenantId!=="default"?g(404,"Audit log entry not found"):y(200,c)})}}p();function Ca(i,e,t,n){async function o(r){let s=await b(r,i,t,n);return{denied:k(s,"consent:view")}}return{"GET /stats/overview":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=await e.getOverview("default");return y(200,c)}),"GET /stats/categories":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=await e.getCategories("default");return y(200,c)}),"GET /stats/timeline":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=new URL(r.url),l=gn(c,"days",30),d=await e.getTimeline("default",l);return y(200,d)}),"GET /stats/countries":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=await e.getCountries("default");return y(200,c)}),"GET /stats/gpc":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=await e.getGpc("default");return y(200,c)}),"GET /stats/aggregate":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=await e.getTenants(),l=await Promise.all(c.map(async u=>{let m=await e.getOverview(u.id);return{tenantId:u.id,tenantName:u.name,...m}})),d=l.reduce((u,m)=>({totalConsents:u.totalConsents+m.totalConsents,totalVisitors:u.totalVisitors+m.totalVisitors,gpcDetectedCount:u.gpcDetectedCount+m.gpcDetectedCount}),{totalConsents:0,totalVisitors:0,gpcDetectedCount:0});return y(200,{aggregate:d,perTenant:l})})}}p();function wi(i){let e=i==null?"":String(i);return e.includes(",")||e.includes('"')||e.includes(`
151
+ `)?`"${e.replace(/"/g,'""')}"`:e}function Nd(i){return[i.id,i.visitorId,i.profileId,i.locale,JSON.stringify(i.consentJson),i.gpcDetected?"1":"0",i.source,i.signature??"",i.createdAt,i.updatedAt].map(wi).join(",")+`
152
+ `}function xd(i){return[i.id,i.userId??"",i.action,i.resourceType,i.resourceId??"",i.createdAt].map(wi).join(",")+`
153
+ `}function Aa(i,e,t,n){async function o(r){let s=await b(r,i,e,t);return{denied:k(s,"export:run")}}return{"GET /export/consents":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=new URL(r.url),l=U(c,"format")??"csv",d=U(c,"profileId"),u=U(c,"from"),m=U(c,"to"),h={tenantId:"default",...d!==void 0?{profileId:d}:{},...u!==void 0?{from:u}:{},...m!==void 0?{to:m}:{}};if(l==="json"){let R=[];for await(let v of i.streamConsents(h))R.push(v);return new Response(JSON.stringify(R),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":'attachment; filename="consents.json"'}})}let S=new TextEncoder,_=`id,visitor_id,profile_id,locale,consent_json,gpc_detected,source,signature,created_at,updated_at
154
+ `,w=new ReadableStream({async start(R){R.enqueue(S.encode(_));for await(let v of i.streamConsents(h))R.enqueue(S.encode(Nd(v)));R.close()}});return new Response(w,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":'attachment; filename="consents.csv"'}})}),"GET /export/consents/xlsx":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=null;try{c=await import("xlsx")}catch{return new Response(JSON.stringify({error:"xlsx peer dependency not installed. Run: npm install xlsx"}),{status:501,headers:{"Content-Type":"application/json"}})}if(!c)return new Response(null,{status:501});let l=new URL(r.url),d=l.searchParams.get("profileId")??void 0,u=l.searchParams.get("from")??void 0,m=l.searchParams.get("to")??void 0,h={tenantId:"default",...d!==void 0?{profileId:d}:{},...u!==void 0?{from:u}:{},...m!==void 0?{to:m}:{}},S=[];for await(let v of i.streamConsents(h))S.push({id:v.id,visitor_id:v.visitorId,profile_id:v.profileId,locale:v.locale,consent_json:JSON.stringify(v.consentJson),gpc_detected:v.gpcDetected?1:0,age_verified:v.ageVerified?1:0,tcf_string:v.tcfString??"",signature:v.signature??"",source:v.source,created_at:v.createdAt,updated_at:v.updatedAt});let _=c.utils.book_new(),w=c.utils.json_to_sheet(S);c.utils.book_append_sheet(_,w,"Consents");let R=c.write(_,{type:"buffer",bookType:"xlsx"});return new Response(R,{status:200,headers:{"Content-Type":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","Content-Disposition":'attachment; filename="consents.xlsx"'}})}),"GET /export/translations/:profileId":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=s.profileId??"",l=await i.getProfile(c);if(!l)return g(404,"Profile not found");let d=l.profileJson,u=d.locales?.length?d.locales:[l.defaultLocale],m={};for(let S of u){if(S===l.defaultLocale){m[S]={mainBanner:d.mainBanner,...d.gpcBanner?{gpcBanner:d.gpcBanner}:{},preferenceModal:d.preferenceModal};continue}let _=await n.getVersionFile(c,String(l.version),S);if(_)try{let w=JSON.parse(_);m[S]={mainBanner:w.mainBanner,...w.gpcBanner?{gpcBanner:w.gpcBanner}:{},preferenceModal:w.preferenceModal}}catch{}}if(Object.keys(m).length===0)return new Response(`locale,field,value
155
+ `,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${c}-translations.csv"`}});let h=["locale,section,field,value"];for(let[S,_]of Object.entries(m))for(let[w,R]of Object.entries(_))if(typeof R=="object"&&R!==null)for(let[v,A]of Object.entries(R))typeof A=="string"&&h.push([S,w,v,A].map(wi).join(","));return new Response(h.join(`
167
156
  `)+`
168
- `,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${a}-translations.csv"`}})}),"GET /export/audit":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=new URL(i.url),c=k(a,"format")??"csv",l=k(a,"from"),u=k(a,"to"),d={tenantId:"default",...l!==void 0?{from:l}:{},...u!==void 0?{to:u}:{}};if(c==="json"){let f=[];for await(let _ of s.streamAuditLogs(d))f.push(_);return new Response(JSON.stringify(f),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":'attachment; filename="audit.json"'}})}let p=new TextEncoder,E=`id,user_id,action,resource_type,resource_id,created_at
169
- `,S=new ReadableStream({async start(f){f.enqueue(p.encode(E));for await(let _ of s.streamAuditLogs(d))f.enqueue(p.encode(Ho(_)));f.close()}});return new Response(S,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":'attachment; filename="audit.csv"'}})})}}var Tt=require("node:crypto");function jo(){let s=`ck_live_${(0,Tt.randomBytes)(24).toString("hex")}`,e=(0,Tt.createHash)("sha256").update(s).digest("hex");return{raw:s,hash:e}}function es(s,e,t){async function n(i){let o=await C(i,s,e,t);return{user:o,denied:P(o,"settings:update")}}return{"GET /apikeys":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await s.getApiKeys("default");return y(200,a.map(c=>({id:c.id,name:c.name,isActive:c.isActive,createdAt:c.createdAt})))}),"POST /apikeys":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await i.json();if(!a.name)return y(400,{error:"name is required"});let{raw:c,hash:l}=jo(),u=await s.createApiKey({tenantId:a.tenantId??"default",name:a.name,keyHash:l});return y(201,{id:u.id,name:u.name,key:c,createdAt:u.createdAt})}),"DELETE /apikeys/:id":async(i,o)=>g(async()=>{let{denied:r}=await n(i);return r||(await s.revokeApiKey(o.id??""),y(204,null))})}}function ts(s,e,t){async function n(i,o){let r=await C(i,s,e,t);return{user:r,denied:P(r,o)}}return{"GET /tenants":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"settings:update");if(r)return r;let a=await s.getTenants();return y(200,a)}),"POST /tenants":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"settings:update");if(r)return r;let a=await v(i);if(!a||typeof a!="object")return m(400,"Invalid body");let c=a;if(typeof c.name!="string"||typeof c.slug!="string")return m(400,"name and slug are required");let l=await s.createTenant({name:c.name,slug:c.slug});return y(201,l)}),"PUT /tenants/:id":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"settings:update");if(r)return r;let a=await v(i);if(!a||typeof a!="object")return m(400,"Invalid body");let c=a,l=await s.updateTenant(o.id??"",{...typeof c.name=="string"?{name:c.name}:{},...typeof c.slug=="string"?{slug:c.slug}:{}});return y(200,l)}),"DELETE /tenants/:id":async(i,o)=>g(async()=>{let{denied:r}=await n(i,"settings:update");if(r)return r;let a=o.id??"";return a==="default"?m(400,"Cannot delete the default tenant"):(await s.deleteTenant(a),y(200,{success:!0}))})}}function ns(s,e,t){async function n(i){let o=await C(i,s,e,t);return{denied:P(o,"consent:view")}}return{"GET /tcf/vendors":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await ae();if(!a)return y(503,{error:"GVL not available. Enable tcf.enabled in config."});let c=new URL(i.url),l=c.searchParams.get("q")?.toLowerCase(),u=Math.max(1,parseInt(c.searchParams.get("page")??"1",10)),d=Math.min(200,Math.max(1,parseInt(c.searchParams.get("limit")??"100",10))),p=Object.values(a.vendors),E=l?p.filter(A=>A.name.toLowerCase().includes(l)):p,S=E.length,f=Math.max(1,Math.ceil(S/d)),_=Math.min(u,f),h=(_-1)*d;return y(200,{vendorListVersion:a.vendorListVersion,total:S,page:_,totalPages:f,vendors:E.slice(h,h+d)})}),"GET /tcf/purposes":async(i,o)=>g(async()=>{let{denied:r}=await n(i);if(r)return r;let a=await ae();return a?y(200,{purposes:Object.values(a.purposes)}):y(503,{error:"GVL not available. Enable tcf.enabled in config."})})}}function is(s,e,t,n="default"){async function i(o,r){let a=await C(o,s,e,t);return{user:a,denied:P(a,r)}}return{"GET /cookie-templates":async o=>g(async()=>{let{denied:r}=await i(o,"profile:view");return r||y(200,await s.getCookieTemplates(n))}),"GET /cookie-templates/:id":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:view");if(a)return a;let c=await s.getCookieTemplate(r.id);return c?y(200,c):m(404,"Cookie template not found")}),"POST /cookie-templates":async o=>g(async()=>{let{denied:r}=await i(o,"profile:create");if(r)return r;let a=await v(o);if(!a?.name||typeof a.name!="string")return m(400,"name is required");if(!Array.isArray(a.cookies))return m(400,"cookies must be an array");let c=await s.createCookieTemplate({tenantId:n,name:a.name,cookies:a.cookies});return y(201,c)}),"PUT /cookie-templates/:id":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:update");if(a)return a;let c=r.id,l=await v(o),u={};if(l?.name!==void 0&&typeof l.name=="string"&&(u.name=l.name),l?.cookies!==void 0&&Array.isArray(l.cookies)&&(u.cookies=l.cookies),Array.isArray(l?.cookies)){let p=await s.getCookieTemplate(c);if(p){let E=new Set(l.cookies.map(f=>f.id)),S=p.cookies.map(f=>f.id).filter(f=>!E.has(f));if(S.length>0){let f=await s.findProfilesUsingCookieTemplate(c),_=[];for(let h of f){if(!h.complianceGroup)continue;we(l.cookies,h.complianceGroup).valid||_.push({id:h.id,name:h.name,complianceGroup:h.complianceGroup})}if(_.length>0)return m(422,"Removing these cookies would break compliance for affected profiles",{blockingProfiles:_,removedCookieIds:S})}}}let d=await s.updateCookieTemplate(c,u);return y(200,d)}),"DELETE /cookie-templates/:id":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:delete");if(a)return a;let c=r.id,l=await s.findProfilesUsingCookieTemplate(c);return l.length>0?m(422,"Cannot delete: template is used by profiles",{profiles:l.map(u=>({id:u.id,name:u.name,isActive:u.isActive}))}):(await s.deleteCookieTemplate(c),y(200,{ok:!0}))}),"POST /cookie-templates/:id/copy":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:create");if(a)return a;let c=await v(o),l=await s.getCookieTemplate(r.id);if(!l)return m(404,"Cookie template not found");let u=typeof c?.name=="string"&&c.name.trim()?c.name.trim():`${l.name} (Copy)`,d=await s.copyCookieTemplate(r.id,u);return y(201,d)}),"GET /cookie-templates/:id/profile-usage":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:view");if(a)return a;let c=await s.findProfilesUsingCookieTemplate(r.id);return y(200,c)})}}function ss(s,e,t,n="default"){async function i(o,r){let a=await C(o,s,e,t);return{user:a,denied:P(a,r)}}return{"GET /ui-templates":async o=>g(async()=>{let{denied:r}=await i(o,"profile:view");return r||y(200,await s.getUITemplates(n))}),"GET /ui-templates/:id":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:view");if(a)return a;let c=await s.getUITemplate(r.id);return c?y(200,c):m(404,"UI template not found")}),"POST /ui-templates":async o=>g(async()=>{let{denied:r}=await i(o,"profile:create");if(r)return r;let a=await v(o);if(!a?.name||typeof a.name!="string")return m(400,"name is required");if(!a.mainBanner||!a.gpcBanner||!a.preferenceModal)return m(400,"mainBanner, gpcBanner, and preferenceModal are required");let c=await s.createUITemplate({tenantId:n,name:a.name,mainBanner:a.mainBanner,gpcBanner:a.gpcBanner,preferenceModal:a.preferenceModal});return y(201,c)}),"PUT /ui-templates/:id":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:update");if(a)return a;let c=await v(o),l={};typeof c?.name=="string"&&(l.name=c.name),c?.mainBanner&&(l.mainBanner=c.mainBanner),c?.gpcBanner&&(l.gpcBanner=c.gpcBanner),c?.preferenceModal&&(l.preferenceModal=c.preferenceModal);let u=await s.updateUITemplate(r.id,l);return y(200,u)}),"DELETE /ui-templates/:id":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:delete");if(a)return a;let c=r.id,l=await s.findProfilesUsingUITemplate(c);return l.length>0?m(422,"Cannot delete: template is used by profiles",{profiles:l.map(u=>({id:u.id,name:u.name,isActive:u.isActive}))}):(await s.deleteUITemplate(c),y(200,{ok:!0}))}),"POST /ui-templates/:id/copy":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:create");if(a)return a;let c=await v(o),l=await s.getUITemplate(r.id);if(!l)return m(404,"UI template not found");let u=typeof c?.name=="string"&&c.name.trim()?c.name.trim():`${l.name} (Copy)`,d=await s.copyUITemplate(r.id,u);return y(201,d)}),"GET /ui-templates/:id/profile-usage":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"profile:view");if(a)return a;let c=await s.findProfilesUsingUITemplate(r.id);return y(200,c)})}}function os(s,e,t,n="default"){async function i(o,r){let a=await C(o,s,e,t);return{user:a,denied:P(a,r)}}return{"GET /analytics/opt-in":async(o,r)=>g(async()=>{let{denied:a}=await i(o,"stats:view");if(a)return a;let c=new URL(o.url),l=c.searchParams.get("tenantId")??n,u={},d=c.searchParams.get("profileId"),p=c.searchParams.get("complianceGroup"),E=c.searchParams.get("from"),S=c.searchParams.get("to"),f=c.searchParams.get("locale");d&&(u.profileId=d),p&&(u.complianceGroup=p),E&&(u.from=E),S&&(u.to=S),f&&(u.locale=f);let _=await s.getOptInStats(l,u);return y(200,_)})}}var rs=require("node:crypto");async function as(s,e,t){let n=s.headers.get("authorization");if(!n?.startsWith("Bearer ck_"))return t;let i=n.slice(7),o=(0,rs.createHash)("sha256").update(i).digest("hex");return(await e.getApiKeyByHash(o))?.tenantId??t}var xe=class{constructor(e=6e4,t=60){this.windowMs=e;this.maxRequests=t;setInterval(()=>{let n=Date.now();for(let[i,o]of this.store)n>=o.resetAt&&this.store.delete(i)},this.windowMs).unref()}windowMs;maxRequests;store=new Map;check(e){let t=Date.now(),n=this.store.get(e);return!n||t>=n.resetAt?(this.store.set(e,{count:1,resetAt:t+this.windowMs}),!0):(n.count+=1,n.count<=this.maxRequests)}checkRequest(e,t){return this.check(`ip:${e}`)?t?this.check(`profile:${t}`):!0:!1}};var zt=(0,M.dirname)((0,Qt.fileURLToPath)(R)),$o=(0,Qt.fileURLToPath)(new URL("./dashboard",R)),us={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json",".png":"image/png",".svg":"image/svg+xml",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf"};async function Bo(s,e,t,n,i){let o=s.slice(e.length)||"/";if(o.startsWith("/api/")||o.startsWith("/admin/"))return!1;let r=o==="/"||o===""||!(0,M.extname)(o)?(0,M.join)(t,"index.html"):(0,M.join)(t,o);if(!r.startsWith(t))return!1;try{let a=await(0,Re.readFile)(r),c=(0,M.extname)(r).toLowerCase(),l=c===".html"||c==="",u=us[c]??"application/octet-stream";return n.writeHead(200,{"Content-Type":u}),n.end(l?Te(a,i):a),!0}catch{return!1}}async function cs(s,e){try{let t=await(0,Re.readFile)(s);return new Response(t,{headers:{"Content-Type":e,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Not Found",{status:404})}}function Vo(s){let e=[],t=s.split("/").map(n=>n.startsWith(":")?(e.push(n.slice(1)),"([^/]+)"):n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return{pattern:new RegExp(`^${t.join("\\/")}$`),paramNames:e}}function Wo(s){let t=`<!DOCTYPE html>
157
+ `,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${c}-translations.csv"`}})}),"GET /export/audit":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;let c=new URL(r.url),l=U(c,"format")??"csv",d=U(c,"from"),u=U(c,"to"),m={tenantId:"default",...d!==void 0?{from:d}:{},...u!==void 0?{to:u}:{}};if(l==="json"){let w=[];for await(let R of i.streamAuditLogs(m))w.push(R);return new Response(JSON.stringify(w),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":'attachment; filename="audit.json"'}})}let h=new TextEncoder,S=`id,user_id,action,resource_type,resource_id,created_at
158
+ `,_=new ReadableStream({async start(w){w.enqueue(h.encode(S));for await(let R of i.streamAuditLogs(m))w.enqueue(h.encode(xd(R)));w.close()}});return new Response(_,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":'attachment; filename="audit.csv"'}})})}}p();var ct=require("node:crypto");function Md(){let i=`ck_live_${(0,ct.randomBytes)(12).toString("hex")}${(0,ct.randomBytes)(12).toString("hex")}`,e=(0,ct.createHash)("sha256").update(i).digest("hex");return{raw:i,hash:e}}function Pa(i,e,t){async function n(o){let r=await b(o,i,e,t);return{user:r,denied:k(r,"settings:update")}}return{"GET /apikeys":async(o,r)=>E(async()=>{let{denied:s}=await n(o);if(s)return s;let a=await i.getApiKeys("default"),c=new Date,l=await Promise.all(a.map(async d=>{let u=d.isActive&&!!d.expireBy&&new Date(d.expireBy)<=c;return u&&await i.revokeApiKey(d.id).catch(()=>{}),{id:d.id,name:d.name,isActive:u?!1:d.isActive,createdAt:d.createdAt,updatedAt:d.updatedAt,...d.createdBy!==void 0?{createdBy:d.createdBy}:{},...d.expireBy!==void 0?{expireBy:d.expireBy}:{}}}));return y(200,l)}),"POST /apikeys":async(o,r)=>E(async()=>{let{user:s,denied:a}=await n(o);if(a)return a;let c=await o.json();if(!c.name)return y(400,{error:"name is required"});if(c.expireBy!==void 0&&Number.isNaN(new Date(c.expireBy).getTime()))return y(400,{error:"expireBy must be a valid date"});let{raw:l,hash:d}=Md(),u=await i.createApiKey({tenantId:c.tenantId??"default",name:c.name,keyHash:d,...s?{createdBy:s.sub}:{},...c.expireBy!==void 0?{expireBy:c.expireBy}:{}});return y(201,{id:u.id,name:u.name,key:l,createdAt:u.createdAt})}),"DELETE /apikeys/:id":async(o,r)=>E(async()=>{let{denied:s}=await n(o);return s||(await i.revokeApiKey(r.id??""),new Response(null,{status:204}))}),"POST /apikeys/:id/reactivate":async(o,r)=>E(async()=>{let{denied:s}=await n(o);return s||(await i.reactivateApiKey(r.id??""),new Response(null,{status:204}))}),"DELETE /apikeys/:id/permanent":async(o,r)=>E(async()=>{let{denied:s}=await n(o);return s||(await i.deleteApiKey(r.id??""),new Response(null,{status:204}))})}}p();function Ta(i,e,t){async function n(o,r){let s=await b(o,i,e,t);return{user:s,denied:k(s,r)}}return{"GET /tenants":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"settings:update");if(s)return s;let a=await i.getTenants();return y(200,a)}),"POST /tenants":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"settings:update");if(s)return s;let a=await I(o);if(!a||typeof a!="object")return g(400,"Invalid body");let c=a;if(typeof c.name!="string"||typeof c.slug!="string")return g(400,"name and slug are required");let l=await i.createTenant({name:c.name,slug:c.slug});return y(201,l)}),"PUT /tenants/:id":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"settings:update");if(s)return s;let a=await I(o);if(!a||typeof a!="object")return g(400,"Invalid body");let c=a,l=await i.updateTenant(r.id??"",{...typeof c.name=="string"?{name:c.name}:{},...typeof c.slug=="string"?{slug:c.slug}:{}});return y(200,l)}),"DELETE /tenants/:id":async(o,r)=>E(async()=>{let{denied:s}=await n(o,"settings:update");if(s)return s;let a=r.id??"";return a==="default"?g(400,"Cannot delete the default tenant"):(await i.deleteTenant(a),y(200,{success:!0}))})}}p();function Ia(i,e,t){async function n(o){let r=await b(o,i,e,t);return{user:r,denied:k(r,"settings:update")}}return{"GET /settings":async(o,r)=>E(async()=>{let{denied:s}=await n(o);if(s)return s;let a=await i.getSettings("default");return y(200,a)}),"PATCH /settings":async(o,r)=>E(async()=>{let{denied:s}=await n(o);if(s)return s;let a=await I(o);if(!a||typeof a!="object")return g(400,"Invalid body");let c=a;if(c.allowedOrigins!==void 0&&!Array.isArray(c.allowedOrigins))return g(400,"allowedOrigins must be an array of strings");if(c.adminAllowedOrigins!==void 0&&!Array.isArray(c.adminAllowedOrigins))return g(400,"adminAllowedOrigins must be an array of strings");let l=await i.updateSettings("default",{...c.allowedOrigins!==void 0?{allowedOrigins:c.allowedOrigins}:{},...c.adminAllowedOrigins!==void 0?{adminAllowedOrigins:c.adminAllowedOrigins}:{}});return y(200,l)})}}p();function ba(i,e,t,n){async function o(s){let a=await b(s,i,e,t);return{user:a,denied:k(a,"consent:view")}}async function r(s){let a=await b(s,i,e,t);return{user:a,denied:k(a,"settings:update")}}return{"GET /tcf/vendors":async(s,a)=>E(async()=>{let{denied:c}=await o(s);if(c)return c;let l=await Ae();if(!l)return y(503,{error:"GVL not available. Enable tcf.enabled in config."});let d=new URL(s.url),u=d.searchParams.get("q")?.toLowerCase(),m=Math.max(1,parseInt(d.searchParams.get("page")??"1",10)),h=Math.min(200,Math.max(1,parseInt(d.searchParams.get("limit")??"100",10))),S=Object.values(l.vendors),_=u?S.filter(P=>P.name.toLowerCase().includes(u)):S,w=_.length,R=Math.max(1,Math.ceil(w/h)),v=Math.min(m,R),A=(v-1)*h;return y(200,{vendorListVersion:l.vendorListVersion,total:w,page:v,totalPages:R,vendors:_.slice(A,A+h)})}),"GET /tcf/purposes":async(s,a)=>E(async()=>{let{denied:c}=await o(s);if(c)return c;let l=await Ae();return l?y(200,{purposes:Object.values(l.purposes)}):y(503,{error:"GVL not available. Enable tcf.enabled in config."})}),"GET /tcf/registration-status":async(s,a)=>E(async()=>{let{denied:c}=await r(s);if(c)return c;if(!n)return y(200,{enabled:!1,confirmed:!0});let l=await i.getSettings("default"),d=le(n.enabled,{cmpId:n.cmpId,cmpVersion:n.cmpVersion,publisherCC:n.publisherCC},l.tcfConfirmation),m=new URL(s.url).searchParams.get("refresh")==="true",h=n.enabled?await We(m):null,S=h?.cmps[String(n.cmpId)];return y(200,{enabled:n.enabled,cmpId:n.cmpId,cmpVersion:n.cmpVersion,...n.publisherCC?{publisherCC:n.publisherCC}:{},confirmed:d,...l.tcfConfirmation?{confirmedAt:l.tcfConfirmation.confirmedAt,confirmedBy:l.tcfConfirmation.confirmedBy}:{},...h?{cmpListVersion:h.cmpListVersion}:{},...n.enabled?{cmpListEntry:{found:!!S,deregistered:!!S?.deletedDate,...S?.deletedDate?{deletedDate:S.deletedDate}:{}}}:{}})}),"POST /tcf/confirm-registration":async(s,a)=>E(async()=>{let{user:c,denied:l}=await r(s);if(l)return l;if(!n?.enabled)return g(400,"TCF is not enabled in the server config \u2014 nothing to confirm.");if(!(await I(s))?.acknowledge)return g(400,"acknowledge: true is required to confirm TCF registration.");let m=(await We())?.cmps[String(n.cmpId)];if(m?.deletedDate)return g(409,`cmpId ${n.cmpId} was deregistered on ${m.deletedDate} per IAB's CMP List. Registration confirmation blocked.`);if(!m)return g(404,`cmpId ${n.cmpId} was not found in the cached CMP List. Registration can take time to propagate after signing up with IAB Europe \u2014 try "Refresh Status" and confirm again shortly.`);let h=nt({cmpId:n.cmpId,cmpVersion:n.cmpVersion,publisherCC:n.publisherCC}),S=await i.updateSettings("default",{tcfConfirmation:{configHash:h,confirmedAt:new Date().toISOString(),confirmedBy:c.sub}});return y(200,{confirmed:!0,tcfConfirmation:S.tcfConfirmation})})}}p();function Oa(i,e,t,n){async function o(r){let s=await b(r,i,e,t);return{user:s,denied:k(s,"settings:update")}}return{"GET /gpp/registration-status":async(r,s)=>E(async()=>{let{denied:a}=await o(r);if(a)return a;if(!n)return y(200,{enabled:!1,confirmed:!0});let c=await i.getSettings("default"),l=le(n.enabled,{cmpId:n.cmpId,cmpVersion:n.cmpVersion},c.gppConfirmation);return y(200,{enabled:n.enabled,cmpId:n.cmpId,cmpVersion:n.cmpVersion,confirmed:l,...c.gppConfirmation?{confirmedAt:c.gppConfirmation.confirmedAt,confirmedBy:c.gppConfirmation.confirmedBy}:{}})}),"POST /gpp/confirm-registration":async(r,s)=>E(async()=>{let{user:a,denied:c}=await o(r);if(c)return c;if(!n?.enabled)return g(400,"GPP is not enabled in the server config \u2014 nothing to confirm.");if(!(await I(r))?.acknowledge)return g(400,"acknowledge: true is required to confirm GPP registration.");let d=nt({cmpId:n.cmpId,cmpVersion:n.cmpVersion}),u=await i.updateSettings("default",{gppConfirmation:{configHash:d,confirmedAt:new Date().toISOString(),confirmedBy:a.sub}});return y(200,{confirmed:!0,gppConfirmation:u.gppConfirmation})})}}p();p();re();var Da=["mandatory","consent","legitimate_interest"],ka=["sale","sharing","sensitive"];function Ud(i){if(!i||typeof i!="object"||Array.isArray(i))return{valid:!1,error:"cookies must be an object keyed by parameter id"};for(let[e,t]of Object.entries(i)){if(!e.trim())return{valid:!1,error:"cookie id must be non-empty"};if(!t||typeof t!="object")return{valid:!1,error:`cookies["${e}"] must be an object`};let n=t;if(!en.includes(n.purpose))return{valid:!1,error:`cookies["${e}"].purpose must be one of: ${en.join(", ")}`};if(typeof n.listenGpc!="boolean")return{valid:!1,error:`cookies["${e}"].listenGpc must be a boolean`};if(n.preGrant!==void 0&&typeof n.preGrant!="boolean")return{valid:!1,error:`cookies["${e}"].preGrant must be a boolean`};if(n.cpraCategory!==void 0&&!ka.includes(n.cpraCategory))return{valid:!1,error:`cookies["${e}"].cpraCategory must be one of: ${ka.join(", ")}`}}return{valid:!0}}function Gd(i){if(!i||typeof i!="object"||Array.isArray(i))return{valid:!1,error:"categories must be an object keyed by category id"};let e=Object.entries(i);if(e.length===0)return{valid:!1,error:"at least one category is required"};for(let[t,n]of e){if(!n||typeof n!="object")return{valid:!1,error:`categories["${t}"] must be an object`};let o=n;if(typeof o.heading!="string"||!o.heading.trim())return{valid:!1,error:`categories["${t}"].heading is required`};if(typeof o.htmlText!="string")return{valid:!1,error:`categories["${t}"].htmlText is required`};if(!Da.includes(o.legalBasis))return{valid:!1,error:`categories["${t}"].legalBasis must be one of: ${Da.join(", ")}`};if(!Array.isArray(o.cookies))return{valid:!1,error:`categories["${t}"].cookies must be an array of parameter ids`}}return{valid:!0}}function jd(i,e){let t=new Map;for(let n of Object.keys(i))t.set(n,0);for(let n of Object.values(e))for(let o of n.cookies)t.set(o,(t.get(o)??0)+1);for(let[n,o]of t){if(o===0)return{valid:!1,error:`Parameter "${n}" is not assigned to any category`};if(o>1)return{valid:!1,error:`Parameter "${n}" is assigned to more than one category`}}return{valid:!0}}function Bd(i,e){let t=new Map;for(let[o,r]of Object.entries(e))for(let s of r.cookies)t.set(s,o);let n=[];for(let[o,r]of Object.entries(i)){let s=t.get(o);if(!s)continue;let a=e[s].legalBasis,c=r.purpose;if(a==="mandatory"&&c!=="necessary")return{valid:!1,error:`Parameter "${o}" has purpose "${c??"unknown"}" but is assigned to a Strictly Necessary category \u2014 this grants a tracking parameter with no consent gate.`};a!=="mandatory"&&c==="necessary"&&n.push(`Parameter "${o}" has purpose "necessary" but is assigned to a non-mandatory category \u2014 this may break site functionality since it can be denied.`)}return{valid:!0,...n.length>0?{warnings:n}:{}}}function Ei(i,e){let t=Ud(i);if(!t.valid)return t;let n=Gd(e);if(!n.valid)return n;let o=i,r=e,s=jd(o,r);return s.valid?Bd(o,r):s}function La(i,e,t,n="default"){async function o(r,s){let a=await b(r,i,e,t);return{user:a,denied:k(a,s)}}return{"GET /consent-templates":async r=>E(async()=>{let{denied:s}=await o(r,"profile:view");return s||y(200,await i.getConsentTemplates(n))}),"GET /consent-templates/:id":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:view");if(a)return a;let c=await i.getConsentTemplate(s.id);return c?y(200,c):g(404,"Consent template not found")}),"POST /consent-templates":async r=>E(async()=>{let{denied:s}=await o(r,"profile:create");if(s)return s;let a=await I(r);if(!a?.name||typeof a.name!="string")return g(400,"name is required");let c=Ei(a.cookies,a.categories);if(!c.valid)return g(400,c.error);let l=await i.createConsentTemplate({tenantId:n,name:a.name,cookies:a.cookies,categories:a.categories});return y(201,l)}),"PUT /consent-templates/:id":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:update");if(a)return a;let c=s.id,l=await I(r),d=await i.getConsentTemplate(c);if(!d)return g(404,"Consent template not found");let u={};l?.name!==void 0&&typeof l.name=="string"&&(u.name=l.name);let m=l?.cookies!==void 0,h=l?.categories!==void 0,S=m?l.cookies:d.cookies,_=h?l.categories:d.categories;if(m||h){let R=Ei(S,_);if(!R.valid)return g(400,R.error);m&&(u.cookies=S),h&&(u.categories=_);let v=await i.findProfilesUsingConsentTemplate(c),A=[];for(let P of v){if(!P.complianceGroup)continue;je(S,_,P.complianceGroup).valid||A.push({id:P.id,name:P.name,complianceGroup:P.complianceGroup})}if(A.length>0)return g(422,"This change would break compliance for affected profiles",{blockingProfiles:A})}let w=await i.updateConsentTemplate(c,u);return y(200,w)}),"DELETE /consent-templates/:id":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:delete");if(a)return a;let c=s.id,l=await i.findProfilesUsingConsentTemplate(c);return l.length>0?g(422,"Cannot delete: template is used by profiles",{profiles:l.map(d=>({id:d.id,name:d.name,isActive:d.isActive}))}):(await i.deleteConsentTemplate(c),y(200,{ok:!0}))}),"POST /consent-templates/:id/copy":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:create");if(a)return a;let c=await I(r),l=await i.getConsentTemplate(s.id);if(!l)return g(404,"Consent template not found");let d=typeof c?.name=="string"&&c.name.trim()?c.name.trim():`${l.name} (Copy)`,u=await i.copyConsentTemplate(s.id,d);return y(201,u)}),"GET /consent-templates/:id/profile-usage":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:view");if(a)return a;let c=await i.findProfilesUsingConsentTemplate(s.id);return y(200,c)})}}p();function Na(i,e,t,n="default"){async function o(r,s){let a=await b(r,i,e,t);return{user:a,denied:k(a,s)}}return{"GET /ui-templates":async r=>E(async()=>{let{denied:s}=await o(r,"profile:view");return s||y(200,await i.getUITemplates(n))}),"GET /ui-templates/:id":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:view");if(a)return a;let c=await i.getUITemplate(s.id);return c?y(200,c):g(404,"UI template not found")}),"POST /ui-templates":async r=>E(async()=>{let{denied:s}=await o(r,"profile:create");if(s)return s;let a=await I(r);if(!a?.name||typeof a.name!="string")return g(400,"name is required");if(!a.mainBanner||!a.gpcBanner||!a.preferenceModal)return g(400,"mainBanner, gpcBanner, and preferenceModal are required");let c=await i.createUITemplate({tenantId:n,name:a.name,mainBanner:a.mainBanner,gpcBanner:a.gpcBanner,preferenceModal:a.preferenceModal});return y(201,c)}),"PUT /ui-templates/:id":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:update");if(a)return a;let c=await I(r),l={};typeof c?.name=="string"&&(l.name=c.name),c?.mainBanner&&(l.mainBanner=c.mainBanner),c?.gpcBanner&&(l.gpcBanner=c.gpcBanner),c?.preferenceModal&&(l.preferenceModal=c.preferenceModal);let d=await i.updateUITemplate(s.id,l);return y(200,d)}),"DELETE /ui-templates/:id":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:delete");if(a)return a;let c=s.id,l=await i.findProfilesUsingUITemplate(c);return l.length>0?g(422,"Cannot delete: template is used by profiles",{profiles:l.map(d=>({id:d.id,name:d.name,isActive:d.isActive}))}):(await i.deleteUITemplate(c),y(200,{ok:!0}))}),"POST /ui-templates/:id/copy":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:create");if(a)return a;let c=await I(r),l=await i.getUITemplate(s.id);if(!l)return g(404,"UI template not found");let d=typeof c?.name=="string"&&c.name.trim()?c.name.trim():`${l.name} (Copy)`,u=await i.copyUITemplate(s.id,d);return y(201,u)}),"GET /ui-templates/:id/profile-usage":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"profile:view");if(a)return a;let c=await i.findProfilesUsingUITemplate(s.id);return y(200,c)})}}p();function xa(i,e,t,n="default"){async function o(r,s){let a=await b(r,i,e,t);return{user:a,denied:k(a,s)}}return{"GET /analytics/opt-in":async(r,s)=>E(async()=>{let{denied:a}=await o(r,"stats:view");if(a)return a;let c=new URL(r.url),l=c.searchParams.get("tenantId")??n,d={},u=c.searchParams.get("profileId"),m=c.searchParams.get("complianceGroup"),h=c.searchParams.get("from"),S=c.searchParams.get("to"),_=c.searchParams.get("locale");u&&(d.profileId=u),m&&(d.complianceGroup=m),h&&(d.from=h),S&&(d.to=S),_&&(d.locale=_);let w=await i.getOptInStats(l,d);return y(200,w)})}}p();re();p();var he="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";function Ma(i){let e=i.storage,t=i.auth,n=i.compliance,o=i.dashboard;return{basePath:i.basePath,dashboard:typeof o=="object"?{enabled:o.enabled,path:o.path}:o,...e?{storage:{driver:e.driver,...e.path!==void 0?{path:e.path}:{},...e.uri!==void 0?{uri:he}:{},...e.database!==void 0?{database:e.database}:{},...e.host!==void 0?{host:e.host}:{},...e.port!==void 0?{port:e.port}:{},...e.user!==void 0?{user:e.user}:{},...e.password!==void 0?{password:he}:{},...e.poolMax!==void 0?{poolMax:e.poolMax}:{},...e.statementTimeoutMs!==void 0?{statementTimeoutMs:e.statementTimeoutMs}:{},...e.idleInTransactionTimeoutMs!==void 0?{idleInTransactionTimeoutMs:e.idleInTransactionTimeoutMs}:{}}}:{},...t?{auth:{mode:t.mode,...t.adminEmail!==void 0?{adminEmail:t.adminEmail}:{},...t.adminPassword!==void 0?{adminPassword:he}:{},...t.masterSecret!==void 0?{masterSecret:he}:{},...t.oidc?{oidc:{issuer:t.oidc.issuer,clientId:t.oidc.clientId,clientSecret:he,redirectUri:t.oidc.redirectUri}}:{},...t.saml?{saml:{issuer:t.saml.issuer,entryPoint:t.saml.entryPoint,cert:he,callbackUrl:t.saml.callbackUrl}}:{}}}:{},...i.rateLimit?{rateLimit:i.rateLimit}:{},...n?{compliance:{...n.type!==void 0?{type:n.type}:{},...n.gpc!==void 0?{gpc:n.gpc}:{},...n.geoDataProvider!==void 0?{geoDataProvider:typeof n.geoDataProvider=="function"?"<custom function>":n.geoDataProvider}:{},...n.complianceMap!==void 0?{complianceMap:typeof n.complianceMap=="object"?`<custom map, ${Object.keys(n.complianceMap.countries).length} countries>`:n.complianceMap}:{},...n.tcf?{tcf:n.tcf}:{},...n.gpp?{gpp:n.gpp}:{},...n.dataRetention?{dataRetention:n.dataRetention}:{},...n.parentalConsentTokenTtlDays!==void 0?{parentalConsentTokenTtlDays:n.parentalConsentTokenTtlDays}:{},...n.dataSigningHash!==void 0?{dataSigningHash:he}:{}}}:{},...i.multiTenant?{multiTenant:i.multiTenant}:{},...i.plugins?{plugins:{count:i.plugins.length}}:{},...i.maxBodySize!==void 0?{maxBodySize:i.maxBodySize}:{},...i.trustedProxies?{trustedProxies:i.trustedProxies}:{},...i.branding?{branding:i.branding}:{},...i.s3Api?{s3Api:{enabled:i.s3Api.enabled,region:i.s3Api.region,bucketName:i.s3Api.bucketName,accessKeyId:he,secretAccessKey:he}}:{}}}function Ua(i,e,t,n,o,r){async function s(c){let l=await b(c,e,t,n);return{denied:k(l,"settings:update")}}async function a(){return(await e.getSettings("default")).setupCompleted===!0?g(409,"Setup has already been completed"):null}return{"GET /setup/status":async(c,l)=>E(async()=>{let{denied:d}=await s(c);if(d)return d;let u=await e.getSettings("default");return y(200,{completed:u.setupCompleted===!0})}),"GET /setup/config":async(c,l)=>E(async()=>{let{denied:d}=await s(c);return d||y(200,{config:Ma(o),...r})}),"GET /setup/compliance-groups":async(c,l)=>E(async()=>{let{denied:d}=await s(c);if(d)return d;let u=Xt.map(m=>({id:m,...Xe[m]}));return y(200,u)}),"POST /setup/seed-profiles":async(c,l)=>E(async()=>{let{denied:d}=await s(c);if(d)return d;let u=await a();if(u)return u;let h=(await I(c))?.groups;if(!Array.isArray(h)||h.some(_=>typeof _!="string"))return g(400,"groups must be an array of compliance group ids");let S=h.filter(_=>!Xt.includes(_));return S.length>0?g(400,`Unknown compliance group id(s): ${S.join(", ")}`):(await Promise.all(h.map(_=>i.seedDefaultProfile(_))),await e.updateSettings("default",{profilesSeeded:!0}),y(200,{seeded:h}))}),"POST /setup/complete":async(c,l)=>E(async()=>{let{denied:d}=await s(c);if(d)return d;let u=await a();if(u)return u;if((await e.getSettings("default")).profilesSeeded!==!0)return g(409,"POST /setup/seed-profiles must be called at least once (an empty groups: [] call is a valid pass) before setup can be completed");let h=await e.updateSettings("default",{setupCompleted:!0});return y(200,h)})}}p();var Ga=require("node:crypto");async function ja(i,e,t){let n=i.headers.get("authorization");if(!n?.startsWith("Bearer ck_"))return t;let o=n.slice(7),r=(0,Ga.createHash)("sha256").update(o).digest("hex"),s=await e.getApiKeyByHash(r);return!s||!s.isActive?t:s.expireBy&&new Date(s.expireBy)<=new Date?(await e.revokeApiKey(s.id).catch(()=>{}),t):s.tenantId}p();var lt=class{constructor(e=6e4,t=60){this.windowMs=e;this.maxRequests=t;setInterval(()=>{let n=Date.now();for(let[o,r]of this.store)n>=r.resetAt&&this.store.delete(o)},this.windowMs).unref()}windowMs;maxRequests;store=new Map;check(e){let t=Date.now(),n=this.store.get(e);return!n||t>=n.resetAt?(this.store.set(e,{count:1,resetAt:t+this.windowMs}),!0):(n.count+=1,n.count<=this.maxRequests)}checkRequest(e,t){return this.check(`ip:${e}`)?t?this.check(`profile:${t}`):!0:!1}};re();p();p();var En=class{constructor(e){this.options=e;e.eventBus.on("consent:created",this.onCreated),e.eventBus.on("consent:updated",this.onUpdated)}options;onCreated=e=>this.fire(e,void 0);onUpdated=({previous:e,current:t})=>this.fire(t,e);fire(e,t){let n=e.consentJson[this.options.id]??"denied",o=t?.consentJson[this.options.id]??"denied";if(n===o)return;let r={visitorId:e.visitorId,cookieId:this.options.id,status:n,record:e};n==="granted"?this.options.onGrant?.(r):this.options.onDeny?.(r)}destroy(){this.options.eventBus.off("consent:created",this.onCreated),this.options.eventBus.off("consent:updated",this.onUpdated)}};p();function Ba(i,e){return e.length>0&&e.every(t=>i[t]==="granted")}var Rn=class{constructor(e){this.options=e;e.eventBus.on("consent:created",this.onCreated),e.eventBus.on("consent:updated",this.onUpdated)}options;onCreated=e=>{this.fire(e,void 0)};onUpdated=({previous:e,current:t})=>{this.fire(t,e)};async fire(e,t){let o=(await this.options.profiles.getResolved(e.profileId))?.preferenceModal.categories[this.options.categoryId]?.cookies??[];if(o.length===0)return;let r=Ba(e.consentJson,o)?"granted":"denied",s=t&&Ba(t.consentJson,o)?"granted":"denied";if(r===s)return;let a={visitorId:e.visitorId,categoryId:this.options.categoryId,status:r,record:e};r==="granted"?this.options.onGrant?.(a):this.options.onDeny?.(a)}destroy(){this.options.eventBus.off("consent:created",this.onCreated),this.options.eventBus.off("consent:updated",this.onUpdated)}};var Ri=(0,V.dirname)((0,Si.fileURLToPath)(f)),Fd=(0,Si.fileURLToPath)(new URL("./dashboard",f)),qa={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json",".png":"image/png",".svg":"image/svg+xml",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf"};async function $d(i,e,t,n,o){let r=i.slice(e.length)||"/";if(r.startsWith("/api/")||r.startsWith("/admin/"))return!1;let s=r==="/"||r===""||!(0,V.extname)(r)?(0,V.join)(t,"index.html"):(0,V.join)(t,r);if(!s.startsWith(t))return!1;try{let a=await(0,Be.readFile)(s),c=(0,V.extname)(s).toLowerCase(),l=c===".html"||c==="",d=qa[c]??"application/octet-stream";return n.writeHead(200,{"Content-Type":d}),n.end(l?$e(a,o):a),!0}catch{return!1}}async function Fa(i,e){try{let t=await(0,Be.readFile)(i);return new Response(t,{headers:{"Content-Type":e,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Not Found",{status:404})}}function Hd(i){let e=[],t=i.split("/").map(n=>n.startsWith(":")?(e.push(n.slice(1)),"([^/]+)"):n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return{pattern:new RegExp(`^${t.join("\\/")}$`),paramNames:e}}function Vd(i){let t=`<!DOCTYPE html>
170
159
  <html lang="en">
171
160
  <head>
172
161
  <meta charset="UTF-8">
@@ -195,19 +184,19 @@ ${l.map(u=>` (${V(c)},${V(u)})`).join(`,
195
184
  <h1>404</h1>
196
185
  <h2>Page not found</h2>
197
186
  <p>The admin dashboard is not enabled on this instance.<br>Use the API or enable <code style="background:#1e2330;padding:.1rem .35rem;border-radius:.25rem;font-size:.8rem">dashboard: true</code> in your config.</p>
198
- <a href="${`${s}/api/docs`}">
187
+ <a href="${`${i}/api/docs`}">
199
188
  <svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
200
189
  View API Documentation
201
190
  </a>
202
191
  </div>
203
192
  </body>
204
- </html>`;return new Response(t,{status:404,headers:{"Content-Type":"text/html; charset=utf-8"}})}function Jo(s,e,t){let n=[];for(let i of e)for(let[o,r]of Object.entries(i.routes)){let a=o.indexOf(" "),c=o.slice(0,a).toUpperCase(),l=o.slice(a+1),{pattern:u,paramNames:d}=Vo(`${i.prefix}${l}`);n.push({method:c,pattern:u,paramNames:d,handler:r,rateLimit:i.rateLimit??!1})}return async i=>{let o=fi(i);if(o)return o;let a=new URL(i.url).pathname,c=i.method.toUpperCase();if(t&&n.find(d=>d.rateLimit&&a.match(d.pattern))){let d=i.headers.get("x-real-ip")??"";if(!t.checkRequest(d))return Et(m(429,"Too Many Requests"),i)}for(let u of n){if(u.method!==c)continue;let d=a.match(u.pattern);if(!d)continue;let p={};u.paramNames.forEach((S,f)=>{let _=d[f+1];_!=null&&(p[S]=_)});let E=await u.handler(i,p);return Wt(Et(E,i))}let l=a.startsWith(s)&&!a.startsWith(`${s}/api/`)&&!a.startsWith(`${s}/admin/`);return Wt(Et(l?Wo(s):m(404,"Not Found"),i))}}function ls(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function ps(s,e){let t={...s};for(let n of Object.keys(e)){let i=e[n],o=t[n];i!==void 0&&ls(i)&&ls(o)?t[n]=ps(o,i):i!==void 0&&(t[n]=i)}return t}var qo={dashboard:!0,basePath:process.env.CONSENTI_BASE_PATH??"/consenti",...process.env.CONSENTI_MAX_BODY_SIZE?{maxBodySize:Number(process.env.CONSENTI_MAX_BODY_SIZE)}:{},storage:{driver:process.env.CONSENTI_DB_DRIVER??"json",path:process.env.CONSENTI_DB_PATH??"./consenti-data.json",...process.env.CONSENTI_DB_URI?{uri:process.env.CONSENTI_DB_URI}:{},...process.env.CONSENTI_DB_DATABASE?{database:process.env.CONSENTI_DB_DATABASE}:{},...process.env.CONSENTI_DB_HOST?{host:process.env.CONSENTI_DB_HOST}:{},...process.env.CONSENTI_DB_PORT?{port:Number(process.env.CONSENTI_DB_PORT)}:{},...process.env.CONSENTI_DB_USER?{user:process.env.CONSENTI_DB_USER}:{},...process.env.CONSENTI_DB_PASSWORD?{password:process.env.CONSENTI_DB_PASSWORD}:{}},auth:{mode:"local",adminEmail:process.env.CONSENTI_ADMIN_EMAIL??"user@consenti.dev",adminPassword:process.env.CONSENTI_ADMIN_PASSWORD??"Consenti@123",...process.env.CONSENTI_ADMIN_JWT_SECRET?{jwtSecret:process.env.CONSENTI_ADMIN_JWT_SECRET}:{}},rateLimit:{windowMs:process.env.CONSENTI_RATE_LIMIT_WINDOW_MS?Number(process.env.CONSENTI_RATE_LIMIT_WINDOW_MS):6e4,maxRequests:process.env.CONSENTI_RATE_LIMIT_MAX_REQUESTS?Number(process.env.CONSENTI_RATE_LIMIT_MAX_REQUESTS):60},branding:{appLogoPath:"./logo-dark.svg",appName:"Consenti",hidePoweredBy:!1}};function Ko(s){switch(s.driver){case"mongodb":return new ye(s);case"mysql":return new he(s);case"postgresql":return new _e(s);case"node:sqlite":return new Ke(s);case"better-sqlite3":case"sqlite":return new ce(s);case"node-sqlite3-wasm":new qe(s);default:return new it(s)}}function Yo(s){let e=ps(qo,s);s.storage||console.warn("[Consenti] No storage config \u2014 using node-sqlite3-wasm (SQLite WASM) at ./consenti-data.db. Switch to a database driver for production."),!s.auth&&!process.env.CONSENTI_ADMIN_PASSWORD&&console.warn("[Consenti] No auth config or CONSENTI_ADMIN_PASSWORD env var \u2014 using demo credentials. Set CONSENTI_ADMIN_EMAIL and CONSENTI_ADMIN_PASSWORD before going to production.");let t=e.storage,n=e.auth,o=Q(t.path??"./consenti-data",t.driver??"json").profilesDir,r=Ko(t),a=new ds.EventEmitter,c=new st(r),l=new ot(r),u=new rt(r),d=new at(r),p=new ct(r),E=new We;e.plugins?.length&&E.register(e.plugins);let S=e.compliance??{},f=S.type??"auto",_=f==="auto",h=e.localeJsonCache?.enabled?new gt(e.localeJsonCache.dir):void 0,A=_?new mt(S.geoDataProvider??"default",At):void 0;f==="auto"&&!S.geoDataProvider&&console.info("[Consenti] compliance.geoDataProvider not set \u2014 defaulting to timezone+language heuristic"),f!=="auto"&&S.geoDataProvider&&console.warn("[Consenti] compliance.geoDataProvider is ignored when compliance.type is a fixed group");let T=new pt(c,d,"default",r,a,h,o,e.handleCache,e.s3Api),I=new yt(u,"default",a),O=new ft(l,u,c,d,"default",e.compliance,E,a,e.tcf),z=new ht(p,d),L=n.jwtSecret??"",Fe=new _t(r,L),Ct=e.rateLimit,ms=Ct.enabled===!1?null:new xe(Ct.windowMs,Ct.maxRequests),gs=new xe(15*6e4,10),fs=e.multiTenant?.enabled===!0?D=>as(D,r,"default"):async D=>"default",G=e.basePath,Xt=`${G}/api/v1`,ys=`${G}/admin`,vt=`${G}/api`,He=!!e.dashboard,oe=(0,M.join)(zt,"dashboard"),je=He?cn(an(oe,G,e.branding,e.compliance)):"",Zt=`<!DOCTYPE html><html><head><title>Consenti API Docs</title>
193
+ </html>`;return new Response(t,{status:404,headers:{"Content-Type":"text/html; charset=utf-8"}})}function Wd(i,e,t,n,o){let r=[];for(let s of e)for(let[a,c]of Object.entries(s.routes)){let l=a.indexOf(" "),d=a.slice(0,l).toUpperCase(),u=a.slice(l+1),{pattern:m,paramNames:h}=Hd(`${s.prefix}${u}`);r.push({method:d,pattern:m,paramNames:h,handler:c,rateLimit:s.rateLimit??!1,originCheck:s.originCheck??!1})}return async s=>{let a=Us(s);if(a)return a;let l=new URL(s.url).pathname,d=s.method.toUpperCase();if(t&&r.find(h=>h.rateLimit&&l.match(h.pattern))){let h=s.headers.get("x-real-ip")??"";if(!t.checkRequest(h))return rt(g(429,"Too Many Requests"),s)}for(let m of r){if(m.method!==d)continue;let h=l.match(m.pattern);if(!h)continue;if(m.originCheck){let w=await o(s),{adminAllowedOrigins:R}=await n.getSettings(w);if(!hn(s,R??[]))return rt(g(403,"Origin not allowed for the admin API"),s)}let S={};m.paramNames.forEach((w,R)=>{let v=h[R+1];v!=null&&(S[w]=v)});let _=await m.handler(s,S);return gi(rt(_,s))}let u=l.startsWith(i)&&!l.startsWith(`${i}/api/`)&&!l.startsWith(`${i}/admin/`);return gi(rt(u?Vd(i):g(404,"Not Found"),s))}}function $a(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function Ja(i,e){let t={...i};for(let n of Object.keys(e)){let o=e[n],r=t[n];o!==void 0&&$a(o)&&$a(r)?t[n]=Ja(r,o):o!==void 0&&(t[n]=o)}return t}var qd={dashboard:!0,basePath:process.env.CONSENTI_BASE_PATH??"/consenti",...process.env.CONSENTI_MAX_BODY_SIZE?{maxBodySize:Number(process.env.CONSENTI_MAX_BODY_SIZE)}:{},storage:{driver:process.env.CONSENTI_DB_DRIVER??"json",path:process.env.CONSENTI_DB_PATH??"./consenti-data.json",...process.env.CONSENTI_DB_URI?{uri:process.env.CONSENTI_DB_URI}:{},...process.env.CONSENTI_DB_DATABASE?{database:process.env.CONSENTI_DB_DATABASE}:{},...process.env.CONSENTI_DB_HOST?{host:process.env.CONSENTI_DB_HOST}:{},...process.env.CONSENTI_DB_PORT?{port:Number(process.env.CONSENTI_DB_PORT)}:{},...process.env.CONSENTI_DB_USER?{user:process.env.CONSENTI_DB_USER}:{},...process.env.CONSENTI_DB_PASSWORD?{password:process.env.CONSENTI_DB_PASSWORD}:{}},auth:{mode:"local",adminEmail:process.env.CONSENTI_ADMIN_EMAIL??"user@consenti.dev",adminPassword:process.env.CONSENTI_ADMIN_PASSWORD??"Consenti@123",...process.env.CONSENTI_ADMIN_MASTER_SECRET?{masterSecret:process.env.CONSENTI_ADMIN_MASTER_SECRET}:{}},...process.env.CONSENTI_DATA_SIGNING_HASH?{compliance:{dataSigningHash:process.env.CONSENTI_DATA_SIGNING_HASH}}:{},rateLimit:{windowMs:process.env.CONSENTI_RATE_LIMIT_WINDOW_MS?Number(process.env.CONSENTI_RATE_LIMIT_WINDOW_MS):6e4,maxRequests:process.env.CONSENTI_RATE_LIMIT_MAX_REQUESTS?Number(process.env.CONSENTI_RATE_LIMIT_MAX_REQUESTS):60},branding:{appLogoPath:"./logo-dark.svg",appName:"Consenti",hidePoweredBy:!1}};function Ha(){return(0,Wa.randomBytes)(32).toString("hex")}function Jd(i){switch(i.driver){case"mongodb":return new ke(i);case"mysql":return new Le(i);case"postgresql":return new Ne(i);case"node:sqlite":return new wt(i);case"better-sqlite3":case"sqlite":return new Te(i);case"node-sqlite3-wasm":return new _t(i);default:return new Dt(i)}}function zd(i){let e=Ja(qd,i),t=e.storage?.driver==="json",n=!i.auth&&!process.env.CONSENTI_ADMIN_PASSWORD;if(process.env.NODE_ENV==="production"){let L=[];if(n&&L.push('auth.adminPassword / CONSENTI_ADMIN_PASSWORD (currently the published default "Consenti@123")'),e.auth?.masterSecret||L.push("auth.masterSecret / CONSENTI_ADMIN_MASTER_SECRET"),e.compliance?.dataSigningHash||L.push("compliance.dataSigningHash / CONSENTI_DATA_SIGNING_HASH"),L.length>0)throw new Error(`[Consenti] Refusing to boot with NODE_ENV=production while unset or default: ${L.join("; ")}. These are fine to leave auto-generated for a local trial, but not for production \u2014 set them explicitly. See SECURITY.md.`)}t&&console.warn("[Consenti] Using the JSON file storage driver \u2014 fine for development, but switch to a database driver (node:sqlite, postgresql, mysql, mongodb) for production. Set storage.driver or CONSENTI_DB_DRIVER."),n&&console.warn("[Consenti] No auth config or CONSENTI_ADMIN_PASSWORD env var \u2014 using demo credentials. Set CONSENTI_ADMIN_EMAIL and CONSENTI_ADMIN_PASSWORD before going to production.");let o=e.storage,r=e.auth;r.masterSecret||(r.masterSecret=Ha(),console.warn("[Consenti] auth.masterSecret not set \u2014 generated a random one for this process. Admin sessions will be invalidated on every restart. Set auth.masterSecret or CONSENTI_ADMIN_MASTER_SECRET for production."));let a=ue(o.path??"./consenti-data",o.driver??"json").profilesDir,c=Jd(o),l=new Va.EventEmitter,d=new kt(c),u=new Lt(c),m=new Nt(c),h=new xt(c),S=new Mt(c),_=new jt(c),w=new Gt(c),R=new ft;e.plugins?.length&&R.register(e.plugins),e.compliance||(e.compliance={});let v=e.compliance;v.dataSigningHash||(v.dataSigningHash=Ha(),console.warn("[Consenti] compliance.dataSigningHash not set \u2014 generated a random one for this process. Ownership cookies, parental-consent tokens, and stored consent-record signatures will all be invalidated on every restart. Set compliance.dataSigningHash or CONSENTI_DATA_SIGNING_HASH for production."));let A=v.type??"auto",P=A==="auto",O=e.localeJsonCache?.enabled?new rn(e.localeJsonCache.dir):void 0,D=P?new on(v.geoDataProvider??"default",Ie):void 0,G=D?as(v.complianceMap,D):void 0;A==="auto"&&!v.geoDataProvider&&console.info("[Consenti] compliance.geoDataProvider not set \u2014 defaulting to timezone+language heuristic"),A!=="auto"&&v.geoDataProvider&&console.warn("[Consenti] compliance.geoDataProvider is ignored when compliance.type is a fixed group"),A!=="auto"&&v.complianceMap&&console.warn("[Consenti] compliance.complianceMap is ignored when compliance.type is a fixed group");let N=new nn(d,S,"default",c,l,O,a,e.handleCache,e.s3Api),se=new dn(m,"default",l,v.dataSigningHash),ne=new un(h,"default"),Fe=new ln(u,m,d,S,"default",e.compliance,R,l,v.tcf,c,v.dataSigningHash,v.gpp),vi=new pn(_,S),B=r.masterSecret??"",Ci=new mn(c,B),Sn=e.rateLimit,za=Sn.enabled===!1?null:new lt(Sn.windowMs,Sn.maxRequests),Ka=new lt(15*6e4,10),Ai=e.multiTenant?.enabled===!0?L=>ja(L,c,"default"):async L=>"default",$=e.basePath,Pi=`${$}/api/v1`,Ti=`${$}/admin/v1`,vn=`${$}/api`,dt=!!e.dashboard,Se=(0,V.join)(Ri,"dashboard"),ut=dt?Mi(xi(Se,$,e.branding,e.compliance,r.mode)):"",Ii=`<!DOCTYPE html><html><head><title>Consenti API Docs</title>
205
194
  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui.css" crossorigin="anonymous"></head>
206
195
  <body><div id="swagger-ui"></div>
207
196
  <script src="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui-bundle.js" crossorigin="anonymous"></script>
208
197
  <script src="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui-standalone-preset.js" crossorigin="anonymous"></script>
209
- <script>SwaggerUIBundle({urls:[{url:'${vt}/openapi.json',name:'Public API (/consenti/api)'},{url:'${vt}/openapi-admin.json',name:'Admin API (/consenti/admin)'}],'urls.primaryName':'Public API (/consenti/api)',dom_id:'#swagger-ui',presets:[SwaggerUIBundle.presets.apis,SwaggerUIStandalonePreset],layout:'StandaloneLayout'})</script>
210
- </body></html>`,hs=`User-agent: *
211
- Disallow: ${G}/
212
- `,en=Jo(G,[{prefix:vt,rateLimit:!1,routes:{"GET /docs":async()=>new Response(Zt,{headers:{"Content-Type":"text/html; charset=utf-8"}}),"GET /openapi.json":async()=>new Response(JSON.stringify(Ot,null,2),{headers:{"Content-Type":"application/json"}}),"GET /openapi-admin.json":async()=>new Response(JSON.stringify(Dt,null,2),{headers:{"Content-Type":"application/json"}})}},{prefix:"",rateLimit:!1,routes:{"GET /robots.txt":async()=>new Response(hs,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}},{prefix:Xt,rateLimit:!0,routes:{...ui(T,A,o,Xt),...Si(O,I,T,fs)}},{prefix:ys,rateLimit:!1,routes:{"GET /widget.js":async()=>cs((0,M.join)(zt,"widget","widget.js"),"application/javascript; charset=utf-8"),"GET /widget.css":async()=>cs((0,M.join)(zt,"widget","widget.css"),"text/css; charset=utf-8"),...Fi(Fe,r,n,L,gs),...Ji(T,r,n,L),...qi(r,n,L),...Ki(r,n,L),...Yi(z,r,n,L),...zi(r,n,L),...Qi(r,n,L),...Xi(r,n,L),...Zi(r,n,L),...es(r,n,L),...ts(r,n,L),...ns(r,n,L),...is(r,n,L),...ss(r,n,L),...os(r,n,L)}}],ms),It=null,tn,nn,_s=new Promise((D,b)=>{tn=D,nn=b});r.connect().then(async()=>{if(n.mode==="local"&&n.adminEmail&&n.adminPassword&&await Fe.bootstrap(n.adminEmail,n.adminPassword),await E.initialize({storage:r,config:e}),a.emit("ready"),tn(),e.tcf?.enabled&&dn(),e.dataRetention?.purgeAfterDays){let D=e.dataRetention.purgeAfterDays,b=()=>r.purgeExpiredConsents(D).then(x=>{x>0&&console.warn(`[consenti] Purged ${x} consent records older than ${D} days`)}).catch(x=>console.warn("[consenti] Data retention purge failed:",x));b(),It=setInterval(()=>{b()},1440*6e4)}}).catch(D=>{console.warn("[consenti] Storage connection failed:",D),nn(D)});async function Pt(D,b){try{let X=D.headers["x-forwarded-proto"]==="https"?"https":"http",Se=D.headers.host??"localhost",F=new URL(D.url??"/",`${X}://${Se}`);if(He&&F.pathname.startsWith(G)&&await Bo(F.pathname,G,oe,b,je))return;let Ae=await ci(D,e.maxBodySize,e.trustedProxies),$e=await en(Ae);if(F.pathname===`${G}/api/openapi.json`){b.writeHead(200,{"Content-Type":"application/json"}),b.end(JSON.stringify(Ot,null,2));return}if(F.pathname===`${G}/api/openapi-admin.json`){b.writeHead(200,{"Content-Type":"application/json"}),b.end(JSON.stringify(Dt,null,2));return}if(F.pathname===`${G}/api/docs`){b.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),b.end(Zt);return}if($e.status===404&&He&&F.pathname.startsWith(G)&&!F.pathname.startsWith(G+"/api/")&&!F.pathname.startsWith(G+"/admin/"))try{let Be=await(0,Re.readFile)((0,M.join)(oe,"index.html"));b.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),b.end(Te(Be,je));return}catch{}await li($e,b)}catch(x){b.headersSent||(x instanceof Me?(b.writeHead(413,{"Content-Type":"application/json"}),b.end(JSON.stringify({error:"Payload Too Large"}))):(b.writeHead(500,{"Content-Type":"application/json"}),b.end(JSON.stringify({error:"Internal Server Error"}))))}}function Es(D,b,x){Pt(D,b).then(()=>{b.writableEnded||x()}).catch(x)}function ws(D,b){return Pt(D,b)}let sn=async(D,b)=>{D.all("/*",async(x,X)=>{await Pt(x.raw,X.raw),X.hijack()})};return Object.defineProperty(sn,Symbol.for("skip-override"),{value:!0}),{router:Es,handler:ws,fastifyHandler:sn,honoApp:{fetch:async D=>{if(He){let x=new URL(D.url).pathname;if(x.startsWith(G)){let X=x.slice(G.length)||"/";if(!X.startsWith("/api/")&&!X.startsWith("/admin/")){let Se=(0,M.extname)(X)?(0,M.join)(oe,X):(0,M.join)(oe,"index.html");if(!Se.startsWith(oe))return new Response("Forbidden",{status:403});try{let F=await(0,Re.readFile)(Se),Ae=(0,M.extname)(Se).toLowerCase(),$e=Ae===".html"||Ae==="",Be=us[Ae]??"application/octet-stream",Rs=$e?Te(F,je):F;return new Response(Rs,{headers:{"Content-Type":Be}})}catch{try{let F=await(0,Re.readFile)((0,M.join)(oe,"index.html"));return new Response(Te(F,je),{headers:{"Content-Type":"text/html; charset=utf-8"}})}catch{return new Response("Dashboard not built. Run: npm run build --workspace=apps/api",{status:404,headers:{"Content-Type":"text/plain"}})}}}}}return en(D)}},services:{profile:T,consent:O,visitor:I,user:z},storage:r,eventBus:a,ready:_s,destroy:async()=>{It&&clearInterval(It),e.tcf?.enabled&&un(),await E.destroy()}}}0&&(module.exports={MongoDBAdapter,MySQLAdapter,PostgreSQLAdapter,SQLiteAdapter,createConsenti,dashboardDir});
198
+ <script>SwaggerUIBundle({urls:[{url:'${vn}/openapi.json',name:'Public API (/consenti/api)'},{url:'${vn}/openapi-admin.json',name:'Admin API (/consenti/admin)'}],'urls.primaryName':'Public API (/consenti/api)',dom_id:'#swagger-ui',presets:[SwaggerUIBundle.presets.apis,SwaggerUIStandalonePreset],layout:'StandaloneLayout'})</script>
199
+ </body></html>`,Ya=`User-agent: *
200
+ Disallow: ${$}/
201
+ `,bi=Wd($,[{prefix:vn,rateLimit:!1,routes:{"GET /docs":async()=>new Response(Ii,{headers:{"Content-Type":"text/html; charset=utf-8"}}),"GET /openapi.json":async()=>new Response(JSON.stringify(In,null,2),{headers:{"Content-Type":"application/json"}}),"GET /openapi-admin.json":async()=>new Response(JSON.stringify(bn,null,2),{headers:{"Content-Type":"application/json"}})}},{prefix:"",rateLimit:!1,routes:{"GET /robots.txt":async()=>new Response(Ya,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}},{prefix:Pi,rateLimit:!0,routes:{...bs(N,D,a,Pi),...Hs(Fe,se,N,Ai,c,v.dataSigningHash,l,v.parentalConsentTokenTtlDays??7),...Vs(ne),...Ws(c,v.tcf),...qs(c,v.gpp)}},{prefix:Ti,rateLimit:!1,routes:{"GET /widget.js":async()=>Fa((0,V.join)(Ri,"widget","widget.js"),"application/javascript; charset=utf-8"),"GET /widget.css":async()=>Fa((0,V.join)(Ri,"widget","widget.css"),"text/css; charset=utf-8")}},{prefix:Ti,rateLimit:!1,originCheck:!0,routes:{...da(Ci,c,r,B,Ka),...ya(N,c,r,B),..._a(c,r,B),...wa(c,r,B),...Ra(vi,c,r,B),...Sa(c,r,B),...va(c,r,B),...Ca(c,w,r,B),...Aa(c,r,B,N),...Pa(c,r,B),...Ta(c,r,B),...Ia(c,r,B),...ba(c,r,B,v.tcf),...Oa(c,r,B,v.gpp),...La(c,r,B),...Na(c,r,B),...xa(c,r,B),...Ua(N,c,r,B,e,{usingJsonStorage:t,usingDefaultCredentials:n})}}],za,c,Ai),Cn=null,Oi,Di,Qa=new Promise((L,M)=>{Oi=L,Di=M});c.connect().then(async()=>{if(r.mode==="local"&&r.adminEmail&&r.adminPassword&&await Ci.bootstrap(r.adminEmail,r.adminPassword),await R.initialize({storage:c,config:e}),l.emit("ready"),Oi(),v.tcf?.enabled&&(Gi(),Fi()),v.dataRetention?.purgeAfterDays){let L=v.dataRetention.purgeAfterDays,M=()=>c.purgeExpiredConsents(L).then(W=>{W>0&&console.warn(`[consenti] Purged ${W} consent records older than ${L} days`)}).catch(W=>console.warn("[consenti] Data retention purge failed:",W));M(),Cn=setInterval(()=>{M()},1440*6e4)}}).catch(L=>{console.warn("[consenti] Storage connection failed:",L),Di(L)});async function An(L,M){try{let de=L.headers["x-forwarded-proto"]==="https"?"https":"http",ve=L.headers.host??"localhost",J=new URL(L.url??"/",`${de}://${ve}`);if(dt&&J.pathname.startsWith($)&&await $d(J.pathname,$,Se,M,ut))return;let ye=await Ps(L,e.maxBodySize,e.trustedProxies),pt=await bi(ye);if(J.pathname===`${$}/api/openapi.json`){M.writeHead(200,{"Content-Type":"application/json"}),M.end(JSON.stringify(In,null,2));return}if(J.pathname===`${$}/api/openapi-admin.json`){M.writeHead(200,{"Content-Type":"application/json"}),M.end(JSON.stringify(bn,null,2));return}if(J.pathname===`${$}/api/docs`){M.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),M.end(Ii);return}if(pt.status===404&&dt&&J.pathname.startsWith($)&&!J.pathname.startsWith($+"/api/")&&!J.pathname.startsWith($+"/admin/"))try{let mt=await(0,Be.readFile)((0,V.join)(Se,"index.html"));M.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),M.end($e(mt,ut));return}catch{}await Ts(pt,M)}catch(W){M.headersSent||(W instanceof it?(M.writeHead(413,{"Content-Type":"application/json"}),M.end(JSON.stringify({error:"Payload Too Large"}))):(M.writeHead(500,{"Content-Type":"application/json"}),M.end(JSON.stringify({error:"Internal Server Error"}))))}}function Za(L,M,W){let ve=L.headers["x-forwarded-proto"]==="https"?"https":"http",J=L.headers.host??"localhost",{pathname:ye}=new URL(L.url??"/",`${ve}://${J}`);if(ye!=="/robots.txt"&&!ye.startsWith($)){W();return}An(L,M).then(()=>{M.writableEnded||W()}).catch(W)}function Xa(L,M){return An(L,M)}let ki=async(L,M)=>{L.all("/*",async(W,de)=>{await An(W.raw,de.raw),de.hijack()})};return Object.defineProperty(ki,Symbol.for("skip-override"),{value:!0}),{router:Za,handler:Xa,fastifyHandler:ki,honoApp:{fetch:async L=>{if(dt){let W=new URL(L.url).pathname;if(W.startsWith($)){let de=W.slice($.length)||"/";if(!de.startsWith("/api/")&&!de.startsWith("/admin/")){let ve=(0,V.extname)(de)?(0,V.join)(Se,de):(0,V.join)(Se,"index.html");if(!ve.startsWith(Se))return new Response("Forbidden",{status:403});try{let J=await(0,Be.readFile)(ve),ye=(0,V.extname)(ve).toLowerCase(),pt=ye===".html"||ye==="",mt=qa[ye]??"application/octet-stream",ec=pt?$e(J,ut):J;return new Response(ec,{headers:{"Content-Type":mt}})}catch{try{let J=await(0,Be.readFile)((0,V.join)(Se,"index.html"));return new Response($e(J,ut),{headers:{"Content-Type":"text/html; charset=utf-8"}})}catch{return new Response("Dashboard not built. Run: npm run build --workspace=apps/api",{status:404,headers:{"Content-Type":"text/plain"}})}}}}}return bi(L)}},services:{profile:N,consent:Fe,visitor:se,user:vi},storage:c,eventBus:l,ready:Qa,destroy:async()=>{Cn&&clearInterval(Cn),w.dispose(),v.tcf?.enabled&&(ji(),$i()),G?.stop(),await R.destroy()}}}0&&(module.exports={CategoryAction,ConsentAction,MongoDBAdapter,MySQLAdapter,PostgreSQLAdapter,SQLiteAdapter,createConsenti,dashboardDir});
213
202
  //# sourceMappingURL=index.cjs.map