nucleus-core-ts 0.9.174 → 0.9.175

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 (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -86,7 +86,7 @@ and limitations under the License.
86
86
  `)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let separatorIndex=trimmed.indexOf(":");if(separatorIndex===-1)continue;let key=trimmed.slice(0,separatorIndex),value=trimmed.slice(separatorIndex+1);fields[key]=value}return fields}toNumber(value){if(!value)return 0;let num=Number.parseFloat(value);return Number.isNaN(num)?0:num}}import*as fs3 from"fs";import*as os from"os";class SystemCollector{config;lastCpuInfo=null;constructor(config){this.config=config}async collect(){if(!this.config?.enabled)return null;let metrics={cpu:{usage:0,cores:0},memory:{total:0,used:0,free:0,usagePercent:0,heapUsed:0,heapTotal:0},disk:{total:0,used:0,free:0,usagePercent:0},network:{bytesIn:0,bytesOut:0},process:{uptime:0,pid:0,eventLoopLag:0}};if(this.config.metrics?.cpu!==!1)metrics.cpu=this.collectCpu();if(this.config.metrics?.memory!==!1)metrics.memory=this.collectMemory();if(this.config.metrics?.disk!==!1)metrics.disk=await this.collectDisk();if(this.config.metrics?.network)metrics.network=this.collectNetwork();if(this.config.metrics?.process!==!1)metrics.process=await this.collectProcess();return metrics}collectCpu(){let cpus2=os.cpus(),cores=cpus2.length,idle=0,total=0;for(let cpu of cpus2)idle+=cpu.times.idle,total+=cpu.times.user+cpu.times.nice+cpu.times.sys+cpu.times.idle+cpu.times.irq;let usage=0;if(this.lastCpuInfo){let idleDiff=idle-this.lastCpuInfo.idle,totalDiff=total-this.lastCpuInfo.total;usage=totalDiff>0?Math.round((1-idleDiff/totalDiff)*100*100)/100:0}return this.lastCpuInfo={idle,total},{usage,cores}}collectMemory(){let total=os.totalmem(),free=os.freemem(),used=total-free,usagePercent=Math.round(used/total*100*100)/100,memUsage=process.memoryUsage();return{total,used,free,usagePercent,heapUsed:memUsage.heapUsed,heapTotal:memUsage.heapTotal}}async collectDisk(){try{let stats=fs3.statfsSync("/"),total=stats.blocks*stats.bsize,free=stats.bfree*stats.bsize,used=total-free,usagePercent=Math.round(used/total*100*100)/100;return{total,used,free,usagePercent}}catch{return{total:0,used:0,free:0,usagePercent:0}}}collectNetwork(){try{let content=fs3.readFileSync("/proc/net/dev","utf-8"),bytesIn=0,bytesOut=0;for(let line of content.split(`
87
87
  `).slice(2)){let[namePart,dataPart]=line.split(":");if(!namePart||!dataPart)continue;if(namePart.trim()==="lo")continue;let fields=dataPart.trim().split(/\s+/);bytesIn+=Number.parseInt(fields[0]??"0",10)||0,bytesOut+=Number.parseInt(fields[8]??"0",10)||0}return{bytesIn,bytesOut}}catch{return{bytesIn:0,bytesOut:0}}}async collectProcess(){let uptime=process.uptime(),pid=process.pid,lagStart=Date.now(),eventLoopLag=await new Promise((resolve)=>{setImmediate(()=>{resolve(Date.now()-lagStart)})});return{uptime,pid,eventLoopLag}}}var init_SystemCollector=()=>{};import{randomUUID as randomUUID3}from"crypto";import*as os2 from"os";class LiveMonitoringService{store;memoryInterval=null;cpuInterval=null;lastCpuInfo=null;isRunning=!1;constructor(config){let merged={...DEFAULT_LIVE_CONFIG,...config};this.store={requests:[],configs:{logMemory:merged.logMemory,logCpu:merged.logCpu,logDapr:merged.logDapr,logWebSocket:merged.logWebSocket,cpuLogInterval:merged.cpuLogInterval,memoryLogInterval:merged.memoryLogInterval},logs:{memory:[],cpu:[],dapr:[],ws:[]},logLimits:{memory:merged.memoryLogLimit,cpu:merged.cpuLogLimit,dapr:merged.daprLogLimit,ws:merged.wsLogLimit,request:merged.requestLogLimit},worker:{pid:process.pid,workerId:null,memory:null,cpu:null,updatedAt:Date.now()},allWorkers:[],daprEvents:[],wsEvents:[]}}start(){if(this.isRunning)return;if(this.isRunning=!0,this.store.configs.logMemory)this.startMemoryCollector();if(this.store.configs.logCpu)this.startCpuCollector()}stop(){if(!this.isRunning)return;if(this.isRunning=!1,this.memoryInterval)clearInterval(this.memoryInterval),this.memoryInterval=null;if(this.cpuInterval)clearInterval(this.cpuInterval),this.cpuInterval=null}startMemoryCollector(){if(this.memoryInterval)clearInterval(this.memoryInterval);let collect=()=>{if(!this.store.configs.logMemory)return;let mem=process.memoryUsage(),entry={timestamp:Date.now(),rss:mem.rss,heapUsed:mem.heapUsed,heapTotal:mem.heapTotal};if(this.store.logs.memory.push(entry),this.store.logs.memory.length>this.store.logLimits.memory*2)this.store.logs.memory=this.store.logs.memory.slice(-this.store.logLimits.memory);this.store.worker.memory=entry,this.store.worker.updatedAt=Date.now()};collect(),this.memoryInterval=setInterval(collect,this.store.configs.memoryLogInterval)}startCpuCollector(){if(this.cpuInterval)clearInterval(this.cpuInterval);let collect=()=>{if(!this.store.configs.logCpu)return;let cpus3=os2.cpus(),userTime=0,sysTime=0,idle=0,total=0;for(let cpu of cpus3)userTime+=cpu.times.user,sysTime+=cpu.times.sys,idle+=cpu.times.idle,total+=cpu.times.user+cpu.times.nice+cpu.times.sys+cpu.times.idle+cpu.times.irq;let userPercent=0,sysPercent=0;if(this.lastCpuInfo){let totalDiff=total-this.lastCpuInfo.total,idleDiff=idle-this.lastCpuInfo.idle;if(totalDiff>0){let activeDiff=totalDiff-idleDiff;userPercent=Math.round((userTime-0)/(activeDiff||1)*100*100)/100,sysPercent=Math.round((sysTime-0)/(activeDiff||1)*100*100)/100;let totalActive=Math.round((1-idleDiff/totalDiff)*100*100)/100;userPercent=Math.round(totalActive*0.7*100)/100,sysPercent=Math.round(totalActive*0.3*100)/100}}this.lastCpuInfo={idle,total};let entry={timestamp:Date.now(),user:userPercent,system:sysPercent};if(this.store.logs.cpu.push(entry),this.store.logs.cpu.length>this.store.logLimits.cpu*2)this.store.logs.cpu=this.store.logs.cpu.slice(-this.store.logLimits.cpu);this.store.worker.cpu=entry,this.store.worker.updatedAt=Date.now()};collect(),this.cpuInterval=setInterval(collect,this.store.configs.cpuLogInterval)}recordRequest(request){if(this.store.requests.push(request),this.store.requests.length>this.store.logLimits.request*2)this.store.requests=this.store.requests.slice(-this.store.logLimits.request)}recordDaprEvent(type,details){if(!this.store.configs.logDapr)return;let event={id:randomUUID3(),type,timestamp:Date.now(),...details};if(this.store.logs.dapr.push(event),this.store.daprEvents.push(event),this.store.logs.dapr.length>this.store.logLimits.dapr*2)this.store.logs.dapr=this.store.logs.dapr.slice(-this.store.logLimits.dapr);if(this.store.daprEvents.length>this.store.logLimits.dapr*2)this.store.daprEvents=this.store.daprEvents.slice(-this.store.logLimits.dapr)}recordWsEvent(type,details){if(!this.store.configs.logWebSocket)return;let event={id:randomUUID3(),type,timestamp:Date.now(),...details};if(this.store.logs.ws.push(event),this.store.wsEvents.push(event),this.store.logs.ws.length>this.store.logLimits.ws*2)this.store.logs.ws=this.store.logs.ws.slice(-this.store.logLimits.ws);if(this.store.wsEvents.length>this.store.logLimits.ws*2)this.store.wsEvents=this.store.wsEvents.slice(-this.store.logLimits.ws)}getSnapshot(){return{memory:this.store.logs.memory.slice(-this.store.logLimits.memory),cpu:this.store.logs.cpu.slice(-this.store.logLimits.cpu),requests:this.store.requests.slice(-this.store.logLimits.request),dapr:this.store.logs.dapr.slice(-this.store.logLimits.dapr),ws:this.store.logs.ws.slice(-this.store.logLimits.ws),workers:this.store.allWorkers.length?this.store.allWorkers:[this.store.worker],logLimits:{...this.store.logLimits},configs:{...this.store.configs}}}getUpdatesSince(timestamps){let memoryUpdates=this.store.logs.memory.filter((m)=>m.timestamp>timestamps.memory),cpuUpdates=this.store.logs.cpu.filter((c)=>c.timestamp>timestamps.cpu),requestUpdates=this.store.requests.filter((r)=>r.timestamp>timestamps.request),daprUpdates=this.store.logs.dapr.filter((d)=>d.timestamp>timestamps.dapr),wsUpdates=this.store.logs.ws.filter((w)=>w.timestamp>timestamps.ws);if(!(memoryUpdates.length>0||cpuUpdates.length>0||requestUpdates.length>0||daprUpdates.length>0||wsUpdates.length>0))return null;return{memory:memoryUpdates,cpu:cpuUpdates,requests:requestUpdates,dapr:daprUpdates,ws:wsUpdates,timestamp:Date.now()}}getLogs(){return{memory:this.store.logs.memory,cpu:this.store.logs.cpu,requests:this.store.requests,dapr:this.store.logs.dapr,ws:this.store.logs.ws,daprEvents:this.store.daprEvents,wsEvents:this.store.wsEvents,configs:{logMemory:this.store.configs.logMemory,logCpu:this.store.configs.logCpu,logDapr:this.store.configs.logDapr,logWebSocket:this.store.configs.logWebSocket},limits:{...this.store.logLimits}}}getSettings(){return{configs:{...this.store.configs},logLimits:{...this.store.logLimits}}}changeSettings(payload){if(payload.logMemory!==void 0)this.store.configs.logMemory=payload.logMemory;if(payload.logCpu!==void 0)this.store.configs.logCpu=payload.logCpu;if(payload.logDapr!==void 0)this.store.configs.logDapr=payload.logDapr;if(payload.logWebSocket!==void 0)this.store.configs.logWebSocket=payload.logWebSocket;if(payload.cpuLogInterval!==void 0){if(this.store.configs.cpuLogInterval=payload.cpuLogInterval,this.isRunning&&this.store.configs.logCpu)this.startCpuCollector()}if(payload.memoryLogInterval!==void 0){if(this.store.configs.memoryLogInterval=payload.memoryLogInterval,this.isRunning&&this.store.configs.logMemory)this.startMemoryCollector()}if(payload.memoryLogLimit!==void 0)this.store.logLimits.memory=payload.memoryLogLimit;if(payload.cpuLogLimit!==void 0)this.store.logLimits.cpu=payload.cpuLogLimit;if(payload.daprLogLimit!==void 0)this.store.logLimits.dapr=payload.daprLogLimit;if(payload.wsLogLimit!==void 0)this.store.logLimits.ws=payload.wsLogLimit;if(payload.requestLogLimit!==void 0)this.store.logLimits.request=payload.requestLogLimit;return{message:"Settings updated successfully",configs:{...this.store.configs},logLimits:{...this.store.logLimits}}}getStore(){return this.store}isEnabled(){return this.isRunning}}var DEFAULT_LIVE_CONFIG;var init_LiveMonitoringService=__esm(()=>{DEFAULT_LIVE_CONFIG={enabled:!0,logMemory:!0,logCpu:!0,logDapr:!0,logWebSocket:!0,memoryLogInterval:1000,cpuLogInterval:1000,memoryLogLimit:100,cpuLogLimit:100,daprLogLimit:100,wsLogLimit:100,requestLogLimit:100,streamInterval:150}});class MonitoringService{redis;logger;config;appId;flushToDb;systemCollector;applicationCollector;databaseCollector=null;redisCollector=null;alertService;collectInterval=null;flushInterval=null;pendingMetrics=[];isRunning=!1;constructor(deps){if(this.redis=deps.redis,this.logger=deps.logger,this.config=this.mergeConfig(deps.config),this.appId=deps.appId,this.flushToDb=deps.flushToDb,this.config.database.enabled)if(deps.dbQuery)this.databaseCollector=new DatabaseCollector(this.config.database,deps.dbQuery);else this.logger.warn("[Monitoring] monitoring.database is enabled but no database query executor is wired \u2014 database metrics are skipped");if(this.config.redis.enabled)if(deps.redis.getDirectClient())this.redisCollector=new RedisCollector(()=>deps.redis.getDirectClient());else this.logger.warn("[Monitoring] monitoring.redis is enabled but Redis runs in Dapr mode \u2014 INFO is unavailable, Redis metrics are skipped");if(this.config.persistence.enabled&&!deps.flushToDb)this.logger.warn("[Monitoring] monitoring.persistence is enabled but no flushToDb handler is wired \u2014 metrics are kept in Redis only");this.systemCollector=new SystemCollector(this.config.system),this.applicationCollector=new ApplicationCollector(this.config.application),this.alertService=new AlertService({logger:deps.logger,emailService:deps.emailService,config:this.config,appId:deps.appId})}mergeConfig(config){return{enabled:config.enabled??DEFAULT_CONFIG3.enabled,system:{enabled:config.system?.enabled??DEFAULT_CONFIG3.system.enabled,collectInterval:config.system?.collectInterval??DEFAULT_CONFIG3.system.collectInterval,metrics:{cpu:config.system?.metrics?.cpu??DEFAULT_CONFIG3.system.metrics.cpu,memory:config.system?.metrics?.memory??DEFAULT_CONFIG3.system.metrics.memory,disk:config.system?.metrics?.disk??DEFAULT_CONFIG3.system.metrics.disk,network:config.system?.metrics?.network??DEFAULT_CONFIG3.system.metrics.network,process:config.system?.metrics?.process??DEFAULT_CONFIG3.system.metrics.process}},application:{enabled:config.application?.enabled??DEFAULT_CONFIG3.application.enabled,metrics:{requests:config.application?.metrics?.requests??DEFAULT_CONFIG3.application.metrics.requests,responseTime:config.application?.metrics?.responseTime??DEFAULT_CONFIG3.application.metrics.responseTime,errors:config.application?.metrics?.errors??DEFAULT_CONFIG3.application.metrics.errors,rateLimits:config.application?.metrics?.rateLimits??DEFAULT_CONFIG3.application.metrics.rateLimits}},database:{enabled:config.database?.enabled??DEFAULT_CONFIG3.database.enabled,metrics:{connections:config.database?.metrics?.connections??DEFAULT_CONFIG3.database.metrics.connections,queryTime:config.database?.metrics?.queryTime??DEFAULT_CONFIG3.database.metrics.queryTime,slowQueryThreshold:config.database?.metrics?.slowQueryThreshold??DEFAULT_CONFIG3.database.metrics.slowQueryThreshold}},redis:{enabled:config.redis?.enabled??DEFAULT_CONFIG3.redis.enabled},persistence:{enabled:config.persistence?.enabled??DEFAULT_CONFIG3.persistence.enabled,flushInterval:config.persistence?.flushInterval??DEFAULT_CONFIG3.persistence.flushInterval,retentionDays:config.persistence?.retentionDays??DEFAULT_CONFIG3.persistence.retentionDays},alerts:{enabled:config.alerts?.enabled??DEFAULT_CONFIG3.alerts.enabled,email:{enabled:config.alerts?.email?.enabled??DEFAULT_CONFIG3.alerts.email.enabled,recipients:config.alerts?.email?.recipients??DEFAULT_CONFIG3.alerts.email.recipients},thresholds:{cpuPercent:config.alerts?.thresholds?.cpuPercent??DEFAULT_CONFIG3.alerts.thresholds.cpuPercent,memoryPercent:config.alerts?.thresholds?.memoryPercent??DEFAULT_CONFIG3.alerts.thresholds.memoryPercent,diskPercent:config.alerts?.thresholds?.diskPercent??DEFAULT_CONFIG3.alerts.thresholds.diskPercent,errorRatePercent:config.alerts?.thresholds?.errorRatePercent??DEFAULT_CONFIG3.alerts.thresholds.errorRatePercent,responseTimeMs:config.alerts?.thresholds?.responseTimeMs??DEFAULT_CONFIG3.alerts.thresholds.responseTimeMs,rateLimitBlocksPerMinute:config.alerts?.thresholds?.rateLimitBlocksPerMinute??DEFAULT_CONFIG3.alerts.thresholds.rateLimitBlocksPerMinute},cooldown:config.alerts?.cooldown??DEFAULT_CONFIG3.alerts.cooldown}}}parseTimeToMs(time){let match=time.match(/^(\d+)(ms|s|m|h|d)$/);if(!match||!match[1]||!match[2])return 1e4;let value=parseInt(match[1],10);switch(match[2]){case"ms":return value;case"s":return value*1000;case"m":return value*60*1000;case"h":return value*60*60*1000;case"d":return value*24*60*60*1000;default:return 1e4}}start(){if(!this.config.enabled||this.isRunning)return;this.isRunning=!0,this.logger.info("[Monitoring] Starting monitoring service");let collectIntervalMs=this.parseTimeToMs(this.config.system.collectInterval);if(this.collectInterval=setInterval(()=>{this.collect()},collectIntervalMs),this.config.persistence.enabled&&this.flushToDb){let flushIntervalMs=this.parseTimeToMs(this.config.persistence.flushInterval);this.flushInterval=setInterval(()=>{this.flush()},flushIntervalMs)}this.collect()}stop(){if(!this.isRunning)return;if(this.isRunning=!1,this.logger.info("[Monitoring] Stopping monitoring service"),this.collectInterval)clearInterval(this.collectInterval),this.collectInterval=null;if(this.flushInterval)clearInterval(this.flushInterval),this.flushInterval=null;this.flush()}async collect(){let now=Date.now(),snapshot={timestamp:now};if(this.config.system.enabled){let systemMetrics=await this.systemCollector.collect();if(systemMetrics)snapshot.system=systemMetrics,this.addMetricPoints("system",systemMetrics,now)}if(this.config.application.enabled){let appMetrics=this.applicationCollector.collect();if(appMetrics)snapshot.application=appMetrics,this.addMetricPoints("application",appMetrics,now)}if(this.databaseCollector){let dbMetrics=await this.databaseCollector.collect();if(dbMetrics)snapshot.database=dbMetrics,this.addMetricPoints("database",dbMetrics,now)}if(this.redisCollector){let redisMetrics=await this.redisCollector.collect();if(redisMetrics)snapshot.redis=redisMetrics,this.addMetricPoints("redis",redisMetrics,now)}if(await this.storeSnapshot(snapshot),this.config.alerts.enabled)await this.alertService.checkAndAlert(snapshot)}addMetricPoints(type,metrics,timestamp){let flatten=(obj,prefix="")=>{for(let key in obj){let value=obj[key],newKey=prefix?`${prefix}.${key}`:key;if(typeof value==="number")this.pendingMetrics.push({timestamp,metricType:type,metricName:newKey,value});else if(typeof value==="object"&&value!==null&&!Array.isArray(value))flatten(value,newKey)}};flatten(metrics)}async storeSnapshot(snapshot){let key=`monitoring:${this.appId}:latest`;await this.redis.create(key,snapshot,3600);let historyKey=`monitoring:${this.appId}:history`,historyResult=await this.redis.read(historyKey),history=historyResult.success&&historyResult.data?historyResult.data:[];history.push(snapshot);let oneHourAgo=Date.now()-3600000,filteredHistory=history.filter((s)=>s.timestamp>oneHourAgo);await this.redis.create(historyKey,filteredHistory,3600)}async flush(){if(this.pendingMetrics.length===0)return;if(!this.flushToDb)return;let metricsToFlush=[...this.pendingMetrics];this.pendingMetrics=[];try{await this.flushToDb(metricsToFlush),this.logger.debug(`[Monitoring] Flushed ${metricsToFlush.length} metrics to database`)}catch(error){this.logger.error(`[Monitoring] Failed to flush metrics: ${error}`),this.pendingMetrics=[...metricsToFlush,...this.pendingMetrics]}}recordRequest(params){if(!this.config.enabled||!this.config.application.enabled)return;this.applicationCollector.recordRequest(params)}recordRateLimitBlock(){if(!this.config.enabled||!this.config.application.enabled)return;this.applicationCollector.recordRateLimitBlock()}async getLatestSnapshot(){let key=`monitoring:${this.appId}:latest`,result=await this.redis.read(key);return result.success?result.data:null}async getHistory(minutes=60){let key=`monitoring:${this.appId}:history`,result=await this.redis.read(key);if(!result.success||!result.data)return[];let cutoff=Date.now()-minutes*60000;return result.data.filter((s)=>s.timestamp>cutoff)}getActiveAlerts(){return this.alertService.getActiveAlerts()}acknowledgeAlert(alertId){return this.alertService.acknowledgeAlert(alertId)}isEnabled(){return this.config.enabled}getConfig(){return this.config}}var DEFAULT_CONFIG3;var init_Monitoring=__esm(()=>{init_SystemCollector();init_LiveMonitoringService();DEFAULT_CONFIG3={enabled:!1,system:{enabled:!0,collectInterval:"10s",metrics:{cpu:!0,memory:!0,disk:!0,network:!1,process:!0}},application:{enabled:!0,metrics:{requests:!0,responseTime:!0,errors:!0,rateLimits:!0}},database:{enabled:!1,metrics:{connections:!0,queryTime:!0,slowQueryThreshold:"100ms"}},redis:{enabled:!1},persistence:{enabled:!0,flushInterval:"1m",retentionDays:30},alerts:{enabled:!1,email:{enabled:!1,recipients:[]},thresholds:{cpuPercent:80,memoryPercent:85,diskPercent:90,errorRatePercent:5,responseTimeMs:1000,rateLimitBlocksPerMinute:100},cooldown:"5m"}}});function snakeToCamel(name){return name.replace(/_([a-z])/g,(_,c)=>c.toUpperCase())}function resolveSchemaTable(schemaTables,name,logger2){let direct=schemaTables[name];if(direct)return direct;let camel=snakeToCamel(name);if(camel!==name){let viaCamel=schemaTables[camel];if(viaCamel)return viaCamel}if(logger2){let keys=Object.keys(schemaTables),preview=keys.slice(0,20).join(", "),suffix=keys.length>20?`, ...(+${keys.length-20} more)`:"";logger2.warn(`[SchemaTables] Table "${name}" not found (tried "${name}" and "${camel}"). Known keys: ${preview}${suffix}`)}return}var init_types4=()=>{};import{and as and4,desc,eq as eq9}from"drizzle-orm";function resolveEnvValue2(value){if(!value)return;return process.env[value]??value}function toCamel(obj){let result={};for(let[key,value]of Object.entries(obj)){let camelKey=key.replace(/_([a-z])/g,(_,c)=>c.toUpperCase());result[camelKey]=value}return result}function fromCamel(obj){let result={};for(let[key,value]of Object.entries(obj)){let snakeKey=key.replace(/[A-Z]/g,(c)=>`_${c.toLowerCase()}`);result[snakeKey]=value}return result}class NotificationService{db;schemaTables;config;logger;emailService;constructor(serviceConfig){this.db=serviceConfig.db,this.schemaTables=serviceConfig.schemaTables,this.config=serviceConfig.config,this.logger=serviceConfig.logger,this.emailService=serviceConfig.emailService}getTable(name){return resolveSchemaTable(this.schemaTables,name,this.logger)}getCol(table,col4){return table[col4]}isChannelEnabled(channel){let channels=this.config.channels;if(!channels)return channel==="portal";switch(channel){case"portal":return channels.portal!==!1;case"email":return channels.email===!0;case"telegram":return channels.telegram?.enabled===!0;case"webhook":return channels.webhook?.enabled===!0;default:return!1}}interpolateTemplate(template,context){let result=template;for(let[key,value]of Object.entries(context))result=result.replace(new RegExp(`{{${key}}}`,"g"),String(value??""));for(let[key,value]of Object.entries(this.config.templateVariables||{}))result=result.replace(new RegExp(`{{${key}}}`,"g"),value);return result}async triggerNotifications(params){let{trigger,flow_id,entity_name,entity_id,node_id,context={}}=params,rulesTable=this.getTable("verificationNotificationRules"),recipientsTable=this.getTable("verificationNotificationRecipients"),channelsTable=this.getTable("verificationNotificationChannels");if(!rulesTable||!recipientsTable){this.logger.warn("[Notification] Notification tables not found");return}let now=new Date,rules=await this.db.select().from(rulesTable).where(and4(eq9(this.getCol(rulesTable,"flowId"),flow_id),eq9(this.getCol(rulesTable,"trigger"),trigger)));this.logger.info(`[Notification] Found ${rules.length} rules for trigger=${trigger} flow_id=${flow_id}, filter_node_id=${node_id||"NONE"}`);for(let r of rules)this.logger.info(`[Notification] Rule ${r.id}: nodeId=${r.nodeId}, trigger=${r.trigger}, title=${JSON.stringify(r.titleTemplate)}`);let filteredRules=rules.filter((rule)=>{if(node_id&&rule.nodeId!==node_id)return this.logger.info(`[Notification] EXCLUDED rule ${rule.id}: rule.nodeId=${rule.nodeId} !== filter_node_id=${node_id}`),!1;if(rule.startsAt&&new Date(rule.startsAt)>now)return!1;if(rule.expiresAt&&new Date(rule.expiresAt)<now)return!1;return!0});for(let rule of filteredRules){let recipients=await this.db.select().from(recipientsTable).where(eq9(this.getCol(recipientsTable,"ruleId"),rule.id)),ruleChannels=["portal"];if(channelsTable){let channelEntries=await this.db.select().from(channelsTable).where(eq9(this.getCol(channelsTable,"ruleId"),rule.id));if(channelEntries.length>0)ruleChannels=channelEntries.map((c)=>c.channel)}let enabledChannels=ruleChannels.filter((ch)=>this.isChannelEnabled(ch));if(enabledChannels.length===0)continue;this.logger.info(`[Notification] Rule ${rule.id}: ${recipients.length} recipients, ${enabledChannels.length} channels (${enabledChannels.join(",")})`);let userIds=await this.resolveRecipients(recipients,params.verifier_id,flow_id,entity_name,entity_id);this.logger.info(`[Notification] Rule ${rule.id}: resolved ${userIds.length} user IDs: ${userIds.join(", ")}`);let enrichedContext={...context,entity_name,entity_id,trigger,decision:params.decision};this.logger.info(`[Notification] Rule ${rule.id}: titleTemplate=${JSON.stringify(rule.titleTemplate)}, bodyTemplate=${JSON.stringify(rule.bodyTemplate)}, context=${JSON.stringify(enrichedContext)}`);let title=rule.titleTemplate?this.interpolateTemplate(rule.titleTemplate,enrichedContext):`Verification ${trigger.replace("on_","").replace("_"," ")}`,body=rule.bodyTemplate?this.interpolateTemplate(rule.bodyTemplate,enrichedContext):void 0;this.logger.info(`[Notification] Rule ${rule.id}: final title="${title}", body="${body}"`);for(let userId of userIds)await this.send({user_id:userId,title,body,entity_name,entity_id,type:"verification",source:`flow:${flow_id}`,channels:enabledChannels})}this.logger.debug(`[Notification] Triggered ${filteredRules.length} rules for ${trigger} on ${entity_name}:${entity_id}`)}async resolveRecipients(recipients,currentVerifierId,flowId,entityName,entityId){let userIds=new Set,userRolesTable=this.getTable("userRoles"),rolesTable=this.getTable("roles");for(let recipient of recipients)switch(recipient.recipientType){case"user":if(recipient.recipientUserId)userIds.add(recipient.recipientUserId);break;case"role":if(recipient.recipientRole&&userRolesTable&&rolesTable){let rolesCols=rolesTable,userRolesCols=userRolesTable,role=(await this.db.select().from(rolesTable).where(eq9(rolesCols.name,recipient.recipientRole)).limit(1))[0];if(role){let usersInRole=await this.db.select({user_id:userRolesCols.userId}).from(userRolesTable).where(eq9(userRolesCols.roleId,role.id));for(let ur of usersInRole)userIds.add(ur.user_id)}}break;case"step_verifier":if(currentVerifierId)userIds.add(currentVerifierId);break;case"entity_creator":{if(entityName&&entityId){let instancesTable=this.getTable("verificationInstances");if(instancesTable){let inst=(await this.db.select().from(instancesTable).where(and4(eq9(this.getCol(instancesTable,"entityName"),entityName),eq9(this.getCol(instancesTable,"entityId"),entityId))).orderBy(desc(this.getCol(instancesTable,"createdAt"))).limit(1))[0];if(inst?.startedBy)userIds.add(inst.startedBy)}}break}case"all_verifiers":{if(flowId){let verifierConfigsTable=this.getTable("verificationVerifierConfigs");if(verifierConfigsTable){let configs=await this.db.select().from(verifierConfigsTable).where(eq9(this.getCol(verifierConfigsTable,"flowId"),flowId));this.logger.info(`[Notification] all_verifiers: found ${configs.length} verifier configs for flow ${flowId}`);for(let cfg of configs){let row=cfg;if(this.logger.info(`[Notification] all_verifiers: config node_id=${row.nodeId}, type=${row.verifierType}, userId=${row.verifierUserId}, role=${row.verifierRole}`),row.verifierUserId)userIds.add(row.verifierUserId);if(row.verifierType==="role"&&row.verifierRole&&userRolesTable&&rolesTable){let rCols=rolesTable,urCols=userRolesTable,roleRow=(await this.db.select().from(rolesTable).where(eq9(rCols.name,row.verifierRole)).limit(1))[0];if(roleRow){let usersInRole=await this.db.select({user_id:urCols.userId}).from(userRolesTable).where(eq9(urCols.roleId,roleRow.id));for(let ur of usersInRole)userIds.add(ur.user_id)}}}}}break}}return Array.from(userIds)}async send(params){let{user_id,title,body,entity_name,entity_id,type,source,channels}=params;for(let channel of channels)switch(channel){case"portal":await this.sendPortalNotification(user_id,title,body,entity_name,entity_id,type,source);break;case"email":await this.sendEmailNotification(user_id,title,body);break;case"sms":this.logger.warn(`[Notification] SMS delivery is not supported \u2014 skipping sms notification for user ${user_id}`);break;case"telegram":await this.sendTelegramNotification(params);break;case"webhook":await this.sendWebhookNotification(params);break}}async sendPortalNotification(userId,title,body,entityName,entityId,type,source){let notificationsTable=this.getTable("notifications");if(!notificationsTable){this.logger.warn("[Notification] notifications table not found");return}await this.db.insert(notificationsTable).values(toCamel({user_id:userId,title,body:body||null,entity_name:entityName||null,entity_id:entityId||null,type:type||"system",source:source||null,is_seen:!1})),this.logger.debug(`[Notification] Portal notification sent to ${userId}: ${title}`)}async sendTelegramNotification(params){let telegramConfig=this.config.channels?.telegram,botToken=resolveEnvValue2(telegramConfig?.botToken),chatId=resolveEnvValue2(telegramConfig?.chatId);if(!botToken||!chatId){this.logger.warn("[Notification] Telegram channel enabled but botToken/chatId is missing or unresolved \u2014 skipping delivery");return}let text=params.body?`*${params.title}*
88
88
 
89
- ${params.body}`:`*${params.title}*`,timeoutMs=telegramConfig?.timeoutMs??DEFAULT_DELIVERY_TIMEOUT_MS;try{let response=await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:chatId,text,parse_mode:"Markdown"}),signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){let errBody=await response.text().catch(()=>"");this.logger.error(`[Notification] Telegram delivery failed (${response.status}): ${errBody.slice(0,300)}`);return}this.logger.debug(`[Notification] Telegram notification sent: ${params.title}`)}catch(error){this.logger.error(`[Notification] Telegram delivery error: ${error.message}`)}}async sendWebhookNotification(params){let webhookConfig=this.config.channels?.webhook,url=resolveEnvValue2(webhookConfig?.url);if(!url){this.logger.warn("[Notification] Webhook channel enabled but url is missing or unresolved \u2014 skipping delivery");return}let headers={"Content-Type":"application/json"};for(let[key,value]of Object.entries(webhookConfig?.headers||{})){let resolved=resolveEnvValue2(value);if(resolved)headers[key]=resolved}let timeoutMs=webhookConfig?.timeoutMs??DEFAULT_DELIVERY_TIMEOUT_MS;try{let response=await fetch(url,{method:"POST",headers,body:JSON.stringify({user_id:params.user_id,title:params.title,body:params.body??null,entity_name:params.entity_name??null,entity_id:params.entity_id??null,type:params.type??"system",source:params.source??null,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){let errBody=await response.text().catch(()=>"");this.logger.error(`[Notification] Webhook delivery failed (${response.status}): ${errBody.slice(0,300)}`);return}this.logger.debug(`[Notification] Webhook notification sent: ${params.title}`)}catch(error){this.logger.error(`[Notification] Webhook delivery error: ${error.message}`)}}async sendEmailNotification(userId,title,body){if(!this.emailService?.isAvailable()){this.logger.warn("[Notification] Email service not available for email notification");return}let usersTable=this.getTable("users");if(!usersTable){this.logger.warn("[Notification] users table not found");return}let user=(await this.db.select({email:this.getCol(usersTable,"email")}).from(usersTable).where(eq9(this.getCol(usersTable,"id"),userId)).limit(1))[0];if(!user?.email){this.logger.warn(`[Notification] No email found for user ${userId}`);return}await this.emailService.sendEmail({to:user.email,subject:title,html:body||title}),this.logger.debug(`[Notification] Email notification sent to ${user.email}: ${title}`)}async getNotifications(userId,options){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return[];let conditions=[eq9(this.getCol(notificationsTable,"userId"),userId)];if(options?.type)conditions.push(eq9(this.getCol(notificationsTable,"type"),options.type));return(await this.db.select().from(notificationsTable).where(and4(...conditions)).orderBy(desc(this.getCol(notificationsTable,"createdAt"))).limit(options?.limit||50).offset(options?.offset||0)).map((r)=>fromCamel(r))}async getUnseenCount(userId){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return 0;return(await this.db.select().from(notificationsTable).where(and4(eq9(this.getCol(notificationsTable,"userId"),userId),eq9(this.getCol(notificationsTable,"isSeen"),!1)))).length}async markAsSeen(notificationId,userId){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return!1;return await this.db.update(notificationsTable).set(toCamel({is_seen:!0,seen_at:new Date})).where(and4(eq9(this.getCol(notificationsTable,"id"),notificationId),eq9(this.getCol(notificationsTable,"userId"),userId))),!0}async markAllAsSeen(userId){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return 0;return(await this.db.update(notificationsTable).set(toCamel({is_seen:!0,seen_at:new Date})).where(and4(eq9(this.getCol(notificationsTable,"userId"),userId),eq9(this.getCol(notificationsTable,"isSeen"),!1))).returning()).length}}var DEFAULT_DELIVERY_TIMEOUT_MS=1e4;var init_Notification=__esm(()=>{init_types4()});function buildGenericAuthUrl(config,state){if(!config.authorizationUrl)throw Error("Generic OAuth provider requires authorizationUrl");let scopes2=config.scopes??[],params=new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,response_type:"code",state,...scopes2.length>0?{scope:scopes2.join(" ")}:{},...config.extraAuthParams});return`${config.authorizationUrl}?${params.toString()}`}async function exchangeGenericCode(code,config){if(!config.tokenUrl)throw Error("Generic OAuth provider requires tokenUrl");let tokenRes=await fetch(config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri,grant_type:"authorization_code"}).toString()});if(!tokenRes.ok){let err=await tokenRes.text();throw Error(`Generic OAuth token exchange failed: ${err}`)}let tokenData=await tokenRes.json();if(tokenData.error)throw Error(`OAuth error: ${tokenData.error_description||tokenData.error}`);let tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope};if(!config.userInfoUrl)return{profile:{providerAccountId:tokenData.access_token,rawProfile:tokenData},tokens};let userRes=await fetch(config.userInfoUrl,{headers:{Authorization:`Bearer ${tokenData.access_token}`}});if(!userRes.ok)throw Error("Failed to fetch user info from generic OAuth provider");let rawProfile=await userRes.json();return{profile:{providerAccountId:rawProfile.id??rawProfile.sub??rawProfile.user_id??tokenData.access_token,email:rawProfile.email,name:rawProfile.name??rawProfile.display_name??rawProfile.username,avatarUrl:rawProfile.avatar_url??rawProfile.picture??rawProfile.photo,rawProfile},tokens}}function buildGithubAuthUrl(config,state){let scopes2=config.scopes??["read:user","user:email"];return`https://github.com/login/oauth/authorize?${new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,scope:scopes2.join(" "),state,...config.extraAuthParams}).toString()}`}async function exchangeGithubCode(code,config){let tokenRes=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri}).toString()});if(!tokenRes.ok){let err=await tokenRes.text();throw Error(`GitHub token exchange failed: ${err}`)}let tokenData=await tokenRes.json();if(tokenData.error)throw Error(`GitHub OAuth error: ${tokenData.error_description||tokenData.error}`);let tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope},userRes=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${tokenData.access_token}`,Accept:"application/vnd.github+json"}});if(!userRes.ok)throw Error("Failed to fetch GitHub user info");let rawProfile=await userRes.json(),email=rawProfile.email;if(!email)try{let emailsRes=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${tokenData.access_token}`,Accept:"application/vnd.github+json"}});if(emailsRes.ok){let emails=await emailsRes.json();email=emails.find((e)=>e.primary&&e.verified)?.email??emails[0]?.email}}catch{}return{profile:{providerAccountId:String(rawProfile.id),email,name:rawProfile.name??rawProfile.login,avatarUrl:rawProfile.avatar_url,rawProfile},tokens}}function buildGoogleAuthUrl(config,state){let scopes2=config.scopes??["openid","email","profile"];return`https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,response_type:"code",scope:scopes2.join(" "),state,access_type:"offline",prompt:"select_account",...config.extraAuthParams}).toString()}`}async function exchangeGoogleCode(code,config){let tokenRes=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri,grant_type:"authorization_code"}).toString()});if(!tokenRes.ok){let err=await tokenRes.text();throw Error(`Google token exchange failed: ${err}`)}let tokenData=await tokenRes.json(),tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope},userRes=await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${tokenData.access_token}`}});if(!userRes.ok)throw Error("Failed to fetch Google user info");let rawProfile=await userRes.json();return{profile:{providerAccountId:rawProfile.sub,email:rawProfile.email,name:rawProfile.name,avatarUrl:rawProfile.picture,rawProfile},tokens}}function getMicrosoftBaseUrl(config){return`https://login.microsoftonline.com/${config.tenantId??"common"}/oauth2/v2.0`}function describeFetchError(err){if(err&&typeof err==="object"){let e=err,cause=e.cause,parts=[];if(e.message)parts.push(`message=${e.message}`);if(e.code)parts.push(`code=${e.code}`);if(cause?.code)parts.push(`cause.code=${cause.code}`);if(cause?.name)parts.push(`cause.name=${cause.name}`);if(cause?.message)parts.push(`cause.message=${cause.message}`);return parts.join(" | ")||String(err)}return String(err)}function buildMicrosoftAuthUrl(config,state){let scopes2=config.scopes??["openid","email","profile","User.Read"],params=new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,response_type:"code",scope:scopes2.join(" "),state,response_mode:"query",prompt:"select_account",...config.extraAuthParams});return`${getMicrosoftBaseUrl(config)}/authorize?${params.toString()}`}async function exchangeMicrosoftCode(code,config){let tokenUrl=`${getMicrosoftBaseUrl(config)}/token`,tokenRes;try{tokenRes=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri,grant_type:"authorization_code"}).toString()})}catch(err){throw Error(`Microsoft token endpoint fetch failed | url=${tokenUrl} | redirect_uri=${config.redirectUri} | ${describeFetchError(err)}`,{cause:err})}if(!tokenRes.ok){let body=await tokenRes.text().catch(()=>"<unable to read body>");throw Error(`Microsoft token exchange failed | status=${tokenRes.status} | url=${tokenUrl} | redirect_uri=${config.redirectUri} | body=${body}`)}let tokenData=await tokenRes.json();if(tokenData.error)throw Error(`Microsoft OAuth error: ${tokenData.error_description||tokenData.error} | url=${tokenUrl}`);let tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope},userRes;try{userRes=await fetch("https://graph.microsoft.com/v1.0/me",{headers:{Authorization:`Bearer ${tokenData.access_token}`}})}catch(err){throw Error(`Microsoft userinfo fetch failed | url=https://graph.microsoft.com/v1.0/me | ${describeFetchError(err)}`,{cause:err})}if(!userRes.ok){let body=await userRes.text().catch(()=>"<unable to read body>");throw Error(`Microsoft userinfo failed | status=${userRes.status} | url=https://graph.microsoft.com/v1.0/me | body=${body}`)}let rawProfile=await userRes.json();return{profile:{providerAccountId:rawProfile.id,email:rawProfile.mail??rawProfile.userPrincipalName,name:rawProfile.displayName,avatarUrl:void 0,rawProfile},tokens}}import{randomBytes as randomBytes2}from"crypto";class OAuthService{config;stateStore=new Map;cleanupInterval=null;constructor(config){this.config=config;let ttl=(config.stateTtlSeconds??600)*1000;this.cleanupInterval=setInterval(()=>{let now=Date.now();for(let[key,val]of this.stateStore.entries())if(val.expiresAt<now)this.stateStore.delete(key)},ttl)}stop(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isProviderEnabled(provider){return!!(this.config.enabled&&this.config.providers[provider])}getEnabledProviders(){if(!this.config.enabled)return[];return Object.keys(this.config.providers)}buildAuthorizationUrl(provider,linkUserId,redirectUrl){let providerConfig=this.config.providers[provider];if(!providerConfig)throw Error(`OAuth provider "${provider}" is not configured`);let statePayload={provider,linkUserId,redirectUrl,createdAt:Date.now()},state=randomBytes2(32).toString("hex"),ttl=(this.config.stateTtlSeconds??600)*1000;switch(this.stateStore.set(state,{payload:statePayload,expiresAt:Date.now()+ttl}),provider){case"google":return buildGoogleAuthUrl(providerConfig,state);case"github":return buildGithubAuthUrl(providerConfig,state);case"microsoft":return buildMicrosoftAuthUrl(providerConfig,state);default:return buildGenericAuthUrl(providerConfig,state)}}consumeState(state){let entry=this.stateStore.get(state);if(!entry)return null;if(entry.expiresAt<Date.now())return this.stateStore.delete(state),null;return this.stateStore.delete(state),entry.payload}async exchangeCode(provider,code){let providerConfig=this.config.providers[provider];if(!providerConfig)throw Error(`OAuth provider "${provider}" is not configured`);switch(provider){case"google":return exchangeGoogleCode(code,providerConfig);case"github":return exchangeGithubCode(code,providerConfig);case"microsoft":return exchangeMicrosoftCode(code,providerConfig);default:return exchangeGenericCode(code,providerConfig)}}get allowAccountLinking(){return this.config.allowAccountLinking??!0}get autoCreateUser(){return this.config.autoCreateUser??!0}get successRedirectUrl(){return this.config.successRedirectUrl??"/"}get errorRedirectUrl(){return this.config.errorRedirectUrl??"/login"}get sendInviteOnCreate(){return this.config.sendInviteOnCreate??!1}get basePath(){return this.config.basePath??"/auth/oauth"}}var init_OAuthService=()=>{};var init_OAuth=__esm(()=>{init_OAuthService()});class RateLimiter{redis;logger;config;constructor(deps){this.redis=deps.redis,this.logger=deps.logger,this.config=this.mergeConfig(deps.config)}mergeConfig(config){return{enabled:config.enabled??DEFAULT_CONFIG4.enabled,strategy:config.strategy??DEFAULT_CONFIG4.strategy,keyPrefix:config.keyPrefix??DEFAULT_CONFIG4.keyPrefix,authRoutes:{window:config.authRoutes?.window??DEFAULT_CONFIG4.authRoutes.window,max:config.authRoutes?.max??DEFAULT_CONFIG4.authRoutes.max,login:{window:config.authRoutes?.login?.window??DEFAULT_AUTH_LOGIN.window,max:config.authRoutes?.login?.max??DEFAULT_AUTH_LOGIN.max,blockDuration:config.authRoutes?.login?.blockDuration??DEFAULT_AUTH_LOGIN.blockDuration},register:{window:config.authRoutes?.register?.window??DEFAULT_AUTH_REGISTER.window,max:config.authRoutes?.register?.max??DEFAULT_AUTH_REGISTER.max,blockDuration:config.authRoutes?.register?.blockDuration??DEFAULT_AUTH_REGISTER.blockDuration},passwordReset:{window:config.authRoutes?.passwordReset?.window??DEFAULT_AUTH_PASSWORD_RESET.window,max:config.authRoutes?.passwordReset?.max??DEFAULT_AUTH_PASSWORD_RESET.max,blockDuration:config.authRoutes?.passwordReset?.blockDuration??DEFAULT_AUTH_PASSWORD_RESET.blockDuration},magicLink:{window:config.authRoutes?.magicLink?.window??DEFAULT_AUTH_MAGIC_LINK.window,max:config.authRoutes?.magicLink?.max??DEFAULT_AUTH_MAGIC_LINK.max,blockDuration:config.authRoutes?.magicLink?.blockDuration??DEFAULT_AUTH_MAGIC_LINK.blockDuration}},publicRoutes:{window:config.publicRoutes?.window??DEFAULT_CONFIG4.publicRoutes.window,max:config.publicRoutes?.max??DEFAULT_CONFIG4.publicRoutes.max},privateRoutes:{window:config.privateRoutes?.window??DEFAULT_CONFIG4.privateRoutes.window,max:config.privateRoutes?.max??DEFAULT_CONFIG4.privateRoutes.max},byIp:config.byIp??DEFAULT_CONFIG4.byIp,byUserId:config.byUserId??DEFAULT_CONFIG4.byUserId,byEndpoint:config.byEndpoint??DEFAULT_CONFIG4.byEndpoint,skipSuccessfulRequests:config.skipSuccessfulRequests??DEFAULT_CONFIG4.skipSuccessfulRequests,headers:{remaining:config.headers?.remaining??DEFAULT_CONFIG4.headers.remaining,reset:config.headers?.reset??DEFAULT_CONFIG4.headers.reset,limit:config.headers?.limit??DEFAULT_CONFIG4.headers.limit},whitelist:config.whitelist??DEFAULT_CONFIG4.whitelist,blacklist:config.blacklist??DEFAULT_CONFIG4.blacklist}}parseTimeToMs(time){let match=time.match(/^(\d+)(ms|s|m|h|d)$/);if(!match||!match[1]||!match[2])return 60000;let value=parseInt(match[1],10);switch(match[2]){case"ms":return value;case"s":return value*1000;case"m":return value*60*1000;case"h":return value*60*60*1000;case"d":return value*24*60*60*1000;default:return 60000}}buildKey(params){let parts=[this.config.keyPrefix,params.category];if(params.authType&&params.authType!=="other")parts.push(params.authType);if(this.config.byIp&&params.ip)parts.push(`ip:${params.ip}`);if(this.config.byUserId&&params.userId)parts.push(`user:${params.userId}`);if(this.config.byEndpoint&&params.endpoint)parts.push(`ep:${params.endpoint.replace(/\//g,"_")}`);return parts.join(":")}getLimits(category,authType){if(category==="auth"){if(authType&&authType!=="other"){let authConfig=this.config.authRoutes[authType];if(authConfig)return authConfig}return{window:this.config.authRoutes.window,max:this.config.authRoutes.max}}if(category==="public")return this.config.publicRoutes;return this.config.privateRoutes}isWhitelisted(ip){return this.config.whitelist.some((pattern)=>{if(pattern.includes("*"))return new RegExp(`^${pattern.replace(/\*/g,".*")}$`).test(ip);return pattern===ip})}isBlacklisted(ip){return this.config.blacklist.some((pattern)=>{if(pattern.includes("*"))return new RegExp(`^${pattern.replace(/\*/g,".*")}$`).test(ip);return pattern===ip})}async readRedis(key){let result=await this.redis.read(key);if(result.success)return result.data;return null}async check(params){if(!this.config.enabled)return{allowed:!0,remaining:-1,resetAt:0,limit:-1};if(this.isWhitelisted(params.ip))return{allowed:!0,remaining:-1,resetAt:0,limit:-1};if(this.isBlacklisted(params.ip))return this.logger.warn(`[RateLimit] Blacklisted IP: ${params.ip}`),{allowed:!1,remaining:0,resetAt:Date.now()+86400000,limit:0,retryAfter:86400};let key=this.buildKey(params),limits=this.getLimits(params.category,params.authType),windowMs=this.parseTimeToMs(limits.window),blockKey=`${key}:blocked`,isBlocked=await this.readRedis(blockKey);if(isBlocked&&isBlocked.until>Date.now()){let retryAfter=Math.ceil((isBlocked.until-Date.now())/1000);return this.logger.warn(`[RateLimit] Blocked: ${key}, retry after ${retryAfter}s`),{allowed:!1,remaining:0,resetAt:isBlocked.until,limit:limits.max,retryAfter}}if(this.config.strategy==="sliding-window")return this.slidingWindowCheck(key,limits.max,windowMs,limits.blockDuration);if(this.config.strategy==="fixed-window")return this.fixedWindowCheck(key,limits.max,windowMs,limits.blockDuration);return this.tokenBucketCheck(key,limits.max,windowMs)}async slidingWindowCheck(key,max,windowMs,blockDuration){let now=Date.now(),windowStart=now-windowMs,dataKey=`${key}:sw`,timestamps=(await this.readRedis(dataKey))?.timestamps||[];timestamps=timestamps.filter((ts)=>ts>windowStart);let count=timestamps.length,firstTimestamp=timestamps[0],resetAt=firstTimestamp!==void 0?firstTimestamp+windowMs:now+windowMs;if(count>=max){if(blockDuration){let blockMs=this.parseTimeToMs(blockDuration);await this.redis.create(`${key}:blocked`,{until:now+blockMs},Math.ceil(blockMs/1000))}return{allowed:!1,remaining:0,resetAt,limit:max,retryAfter:Math.ceil((resetAt-now)/1000)}}return timestamps.push(now),await this.redis.create(dataKey,{timestamps},Math.ceil(windowMs/1000)+1),{allowed:!0,remaining:max-timestamps.length,resetAt,limit:max}}async fixedWindowCheck(key,max,windowMs,blockDuration){let now=Date.now(),windowId=Math.floor(now/windowMs),dataKey=`${key}:fw:${windowId}`,resetAt=(windowId+1)*windowMs,count=(await this.readRedis(dataKey))?.count||0;if(count>=max){if(blockDuration){let blockMs=this.parseTimeToMs(blockDuration);await this.redis.create(`${key}:blocked`,{until:now+blockMs},Math.ceil(blockMs/1000))}return{allowed:!1,remaining:0,resetAt,limit:max,retryAfter:Math.ceil((resetAt-now)/1000)}}return await this.redis.create(dataKey,{count:count+1},Math.ceil(windowMs/1000)+1),{allowed:!0,remaining:max-(count+1),resetAt,limit:max}}async tokenBucketCheck(key,max,windowMs){let now=Date.now(),refillRate=max/windowMs,dataKey=`${key}:tb`,data=await this.readRedis(dataKey),tokens=data?.tokens??max,lastRefill=data?.lastRefill??now,refill=(now-lastRefill)*refillRate;if(tokens=Math.min(max,tokens+refill),tokens<1){let waitTime=Math.ceil((1-tokens)/refillRate);return{allowed:!1,remaining:0,resetAt:now+waitTime,limit:max,retryAfter:Math.ceil(waitTime/1000)}}return tokens-=1,await this.redis.create(dataKey,{tokens,lastRefill:now},Math.ceil(windowMs/1000)*2),{allowed:!0,remaining:Math.floor(tokens),resetAt:now+windowMs,limit:max}}async decrement(params){if(!this.config.skipSuccessfulRequests)return;let key=this.buildKey(params);if(this.config.strategy==="sliding-window"){let dataKey=`${key}:sw`,data=await this.readRedis(dataKey);if(data?.timestamps?.length){data.timestamps.pop();let windowMs=this.parseTimeToMs(this.getLimits(params.category,params.authType).window);await this.redis.create(dataKey,data,Math.ceil(windowMs/1000)+1)}}else if(this.config.strategy==="fixed-window"){let windowMs=this.parseTimeToMs(this.getLimits(params.category,params.authType).window),windowId=Math.floor(Date.now()/windowMs),dataKey=`${key}:fw:${windowId}`,data=await this.readRedis(dataKey);if(data?.count)await this.redis.create(dataKey,{count:data.count-1},Math.ceil(windowMs/1000)+1)}}getHeaders(result){let headers={};return headers[this.config.headers.remaining]=String(result.remaining),headers[this.config.headers.reset]=String(Math.ceil(result.resetAt/1000)),headers[this.config.headers.limit]=String(result.limit),headers}isEnabled(){return this.config.enabled}}var DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{DEFAULT_AUTH_LOGIN={window:"15m",max:5,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,blockDuration:"1h"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:100},privateRoutes:{window:"1m",max:60},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});var exports_schema={};__export(exports_schema,{ensureSchemaExists:()=>ensureSchemaExists,applySchemaPush:()=>applySchemaPush});import{sql as sql2}from"drizzle-orm";var validateIdentifier=(name)=>{if(!name||name.length>63)throw Error(`Invalid identifier: must be 1-63 characters, got ${name.length}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))throw Error(`Invalid identifier: "${name}" contains unsafe characters`);return name},ensureSchemaExists=async(db,schemaName)=>{let safeName=validateIdentifier(schemaName);await db.execute(sql2.raw(`CREATE SCHEMA IF NOT EXISTS "${safeName}"`))},applySchemaPush=async(push,opts)=>{let{schemaName,allowDataLoss,logger:logger2}=opts;if(push.hasDataLoss&&!allowDataLoss)return logger2.error(`[Schema] Destructive changes detected for schema "${schemaName}" but database.allowDataLoss is not enabled \u2014 skipping schema sync for this schema. Set database.allowDataLoss: true to apply them.`,{warnings:push.warnings,statements:push.statementsToExecute}),!1;if(push.hasDataLoss)logger2.warn(`[Schema] Applying destructive changes to schema "${schemaName}" (database.allowDataLoss=true)`,{warnings:push.warnings});return await push.apply(),!0};var init_schema=()=>{};var rowToTenantRecord=(row)=>({id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}),rowToFeatureRecord=(row,parseConfig)=>({id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}),parseStatus=(value)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value||"provisioning");return valid.includes(str2)?str2:"provisioning"},parseJsonbToConfig=(value)=>{if(!value||typeof value!=="object")return{};let result={};for(let[k,v]of Object.entries(value))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value)=>{if(!Array.isArray(value))return[];return value.map((item)=>{let entry=item;return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:Array.isArray(entry.allowedIps||entry.allowed_ips)?entry.allowedIps||entry.allowed_ips:void 0,allowedServices:Array.isArray(entry.allowedServices||entry.allowed_services)?entry.allowedServices||entry.allowed_services:void 0}})},normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix))return!1;let ipParts=ip.split(".").map(Number),cidrParts=cidrIp.split(".").map(Number);if(ipParts.length!==4||cidrParts.length!==4)return!1;let ipNum=(ipParts[0]||0)<<24|(ipParts[1]||0)<<16|(ipParts[2]||0)<<8|(ipParts[3]||0),cidrNum=(cidrParts[0]||0)<<24|(cidrParts[1]||0)<<16|(cidrParts[2]||0)<<8|(cidrParts[3]||0),mask=~((1<<32-prefix)-1);return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return authMode==="consumer";let clientIp=request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||request.headers.get("x-real-ip")?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}if((!source.allowedIps||source.allowedIps.length===0)&&(!source.allowedServices||source.allowedServices.length===0))return!0}return!1};function getDatabaseAuthMode(){return process.env.DATABASE_AUTH_MODE||"password"}function getRedisAuthMode(){return process.env.REDIS_AUTH_MODE||"password"}async function acquireToken(scope,label){let{DefaultAzureCredential,ManagedIdentityCredential,ClientSecretCredential}=await import("@azure/identity"),authMode=scope===PG_TOKEN_SCOPE?getDatabaseAuthMode():getRedisAuthMode(),clientId=process.env.AZURE_CLIENT_ID||"",tenantId=process.env.AZURE_TENANT_ID||"",clientSecret=process.env.AZURE_CLIENT_SECRET||"",credential;if(authMode==="managed_identity")credential=clientId?new ManagedIdentityCredential(clientId):new DefaultAzureCredential;else if(authMode==="service_principal"){if(!tenantId||!clientId||!clientSecret)throw Error("[azure-auth] service_principal auth requires AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET");credential=new ClientSecretCredential(tenantId,clientId,clientSecret)}else throw Error(`[azure-auth] Unsupported auth mode: ${authMode}`);let result=await credential.getToken(scope);if(!result)throw Error(`[azure-auth] Failed to acquire token for ${label}`);return logger.scoped("database.connect").info(`[azure-auth] ${label} token acquired`,{expiresAt:new Date(result.expiresOnTimestamp).toISOString(),authMode}),{token:result.token,expiresAt:result.expiresOnTimestamp}}async function getPostgresToken(){let now=Date.now();if(pgCachedToken&&now<pgTokenExpiresAt-REFRESH_BUFFER_MS)return pgCachedToken;let{token,expiresAt}=await acquireToken(PG_TOKEN_SCOPE,"PostgreSQL");return pgCachedToken=token,pgTokenExpiresAt=expiresAt,pgCachedToken}async function getRedisToken(){let now=Date.now();if(redisCachedToken&&now<redisTokenExpiresAt-REFRESH_BUFFER_MS)return redisCachedToken;let{token,expiresAt}=await acquireToken(REDIS_TOKEN_SCOPE,"Redis");return redisCachedToken=token,redisTokenExpiresAt=expiresAt,redisCachedToken}function getRedisTokenExpiresAt(){return redisTokenExpiresAt}var PG_TOKEN_SCOPE="https://ossrdbms-aad.database.windows.net/.default",REDIS_TOKEN_SCOPE="https://redis.azure.com/.default",REFRESH_BUFFER_MS=300000,pgCachedToken=null,pgTokenExpiresAt=0,redisCachedToken=null,redisTokenExpiresAt=0;var init_AzureTokenProvider=__esm(()=>{init_Logger2()});var exports_Azure={};__export(exports_Azure,{getRedisTokenExpiresAt:()=>getRedisTokenExpiresAt,getRedisToken:()=>getRedisToken,getRedisAuthMode:()=>getRedisAuthMode,getPostgresToken:()=>getPostgresToken,getDatabaseAuthMode:()=>getDatabaseAuthMode});var init_Azure=__esm(()=>{init_AzureTokenProvider()});import{access,mkdir as mkdir2}from"fs/promises";import{dirname,resolve}from"path";var DEFAULT_CONFIG5,FILE_SIZE_UNITS,resolvePath=(path2)=>{if(!path2||typeof path2!=="string")throw createFileManagerError("INVALID_PATH","Path must be a non-empty string",path2,"resolvePath");return resolve(path2)},extractDirectoryPath=(filePath)=>{let resolvedPath=resolvePath(filePath);return dirname(resolvedPath)},ensureDirectoryExists=async(dirPath)=>{let resolvedPath=resolve(dirPath);try{await mkdir2(resolvedPath,{recursive:!0})}catch(error){if(error.code!=="EEXIST")throw createFileManagerError("DIRECTORY_CREATE_FAILED",`Failed to create directory: ${resolvedPath}`,resolvedPath,"ensureDirectory")}},formatFileSize=(bytes)=>{let size=bytes,unitIndex=0;while(size>=1024&&unitIndex<FILE_SIZE_UNITS.length-1)size/=1024,unitIndex++;return`${size.toFixed(2)} ${FILE_SIZE_UNITS[unitIndex]}`},validateFileExtension=(fileName,expectedExtension)=>{return fileName.toLowerCase().endsWith(expectedExtension.toLowerCase())},ensureFileExtension=(fileName,extension)=>{let normalizedExtension=extension.startsWith(".")?extension:`.${extension}`;if(validateFileExtension(fileName,normalizedExtension))return fileName;return`${fileName}${normalizedExtension}`},createFileManagerError=(code,message,path2,operation)=>{return{code,message,path:path2,operation:operation||"unknown"}},safeJsonStringify=(data)=>{try{return JSON.stringify(data,null,2)}catch{return"{}"}},executeBulkOperation=async(items,operation,concurrency=DEFAULT_CONFIG5.maxConcurrency)=>{let results=[];for(let i=0;i<items.length;i+=concurrency){let batch3=items.slice(i,i+concurrency),batchPromises=[];for(let item of batch3)batchPromises.push(operation(item));let batchResults=await Promise.allSettled(batchPromises);results.push(...batchResults)}return results},validateConfig=(config,options={})=>{let errors=[],warnings=[],strict=options.strict??!0;if(config.defaultEncoding!==void 0){if(!["utf-8","utf8","ascii","base64","hex"].includes(config.defaultEncoding))errors.push(`Invalid defaultEncoding: ${config.defaultEncoding}`)}if(config.maxConcurrency!==void 0){if(!Number.isInteger(config.maxConcurrency)||config.maxConcurrency<1)errors.push("maxConcurrency must be a positive integer");if(config.maxConcurrency>50)warnings.push("maxConcurrency > 50 may cause performance issues")}if(config.defaultCreateDir!==void 0&&typeof config.defaultCreateDir!=="boolean")errors.push("defaultCreateDir must be a boolean");if(config.defaultRecursive!==void 0&&typeof config.defaultRecursive!=="boolean")errors.push("defaultRecursive must be a boolean");if(strict&&!options.allowUnknownKeys){let validKeys=["defaultEncoding","defaultCreateDir","defaultRecursive","maxConcurrency"],configKeys=Object.keys(config);for(let key of configKeys)if(!validKeys.includes(key))errors.push(`Unknown configuration key: ${key}`)}return{isValid:errors.length===0,errors,warnings}},mergeConfig=(partial,base=DEFAULT_CONFIG5)=>{let validation=validateConfig(partial);if(!validation.isValid)throw createFileManagerError("CONFIG_VALIDATION_FAILED",`Configuration validation failed: ${validation.errors.join(", ")}`,void 0,"mergeConfig");return{...base,...partial}},parsePermissions=(mode)=>{let parseOctal=(octal)=>({read:Boolean(octal&4),write:Boolean(octal&2),execute:Boolean(octal&1)}),ownerMode=mode>>6&7,groupMode=mode>>3&7,othersMode=mode&7;return{owner:parseOctal(ownerMode),group:parseOctal(groupMode),others:parseOctal(othersMode)}},validatePermissionMode=(mode)=>{return Number.isInteger(mode)&&mode>=0&&mode<=511};var init_utils4=__esm(()=>{DEFAULT_CONFIG5={defaultEncoding:"utf-8",defaultCreateDir:!0,defaultRecursive:!0,maxConcurrency:5},FILE_SIZE_UNITS=["B","KB","MB","GB","TB"]});import{copyFile,rename,unlink as unlink2}from"fs/promises";import{basename,dirname as dirname2,extname,join as join2}from"path";var DEFAULT_ATOMIC_CONFIG,generateTempPath=(originalPath,suffix=".tmp")=>{let resolvedPath=resolvePath(originalPath),timestamp=Date.now(),random=Math.random().toString(36).substring(2,8);return`${resolvedPath}${suffix}.${timestamp}.${random}`},generateBackupPath=(originalPath,backupDir,useTimestamp=!0)=>{let resolvedPath=resolvePath(originalPath),dir=backupDir?resolvePath(backupDir):dirname2(resolvedPath),name=basename(resolvedPath),ext=extname(name),nameWithoutExt=basename(name,ext),timestamp=useTimestamp?`.${new Date().toISOString().replace(/[:.]/g,"-")}`:"",backupName=`${nameWithoutExt}.backup${timestamp}${ext}`;return join2(dir,backupName)},atomicWrite=async({path:path2,data,tempSuffix=DEFAULT_ATOMIC_CONFIG.tempSuffix,backup=DEFAULT_ATOMIC_CONFIG.backup,sync=DEFAULT_ATOMIC_CONFIG.sync})=>{let resolvedPath=resolvePath(path2),tempPath=generateTempPath(resolvedPath,tempSuffix),backupPath;try{if(await ensureDirectoryExists(extractDirectoryPath(resolvedPath)),backup){if(await Bun.file(resolvedPath).exists())backupPath=generateBackupPath(resolvedPath),await copyFile(resolvedPath,backupPath)}let bytesWritten=await Bun.write(tempPath,data);return await rename(tempPath,resolvedPath),{success:!0,bytesWritten,tempPath,backupPath}}catch(error){try{await unlink2(tempPath)}catch{}throw createFileManagerError("ATOMIC_WRITE_FAILED",`Atomic write failed: ${error}`,resolvedPath,"atomicWrite")}},atomicJsonWrite=async(path2,data,options={})=>{let jsonString=JSON.stringify(data,null,2);return atomicWrite({path:path2,data:jsonString,...options})},createBackup=async({sourcePath,backupDir,keepOriginal=!0,timestamp=DEFAULT_ATOMIC_CONFIG.timestamp})=>{let resolvedSource=resolvePath(sourcePath);if(!await Bun.file(resolvedSource).exists())throw createFileManagerError("SOURCE_NOT_FOUND",`Source file not found: ${sourcePath}`,resolvedSource,"createBackup");let backupPath=generateBackupPath(resolvedSource,backupDir,timestamp);if(await ensureDirectoryExists(dirname2(backupPath)),keepOriginal)await copyFile(resolvedSource,backupPath);else await rename(resolvedSource,backupPath);return backupPath},restoreFromBackup=async(backupPath,targetPath,deleteBackup=!1)=>{let resolvedBackup=resolvePath(backupPath),resolvedTarget=resolvePath(targetPath);if(!await Bun.file(resolvedBackup).exists())throw createFileManagerError("BACKUP_NOT_FOUND",`Backup file not found: ${backupPath}`,resolvedBackup,"restoreFromBackup");try{if(await ensureDirectoryExists(extractDirectoryPath(resolvedTarget)),deleteBackup)await rename(resolvedBackup,resolvedTarget);else await copyFile(resolvedBackup,resolvedTarget);return!0}catch(error){return logger.scoped("storage.fs").error(`Failed to restore from backup ${backupPath}`,error,{backupPath}),!1}},safeUpdate=async(path2,updateFunction,options={})=>{let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath),backupPath;try{if(await file.exists())backupPath=await createBackup({sourcePath:resolvedPath,keepOriginal:!0,timestamp:!0});let currentData=await file.exists()?await file.text():"",newData=await updateFunction(currentData),result=await atomicWrite({path:resolvedPath,data:newData,backup:!1,...options});return{success:result.success,bytesWritten:result.bytesWritten,tempPath:result.tempPath,backupPath}}catch(error){if(backupPath)try{await restoreFromBackup(backupPath,resolvedPath,!1)}catch(rollbackError){logger.scoped("storage.fs").error("Atomic write rollback failed",rollbackError,{backupPath})}throw error}},batchAtomicWrite=async(operations)=>{let successful=[],failed=[];for(let operation of operations)try{let result=await atomicWrite(operation);successful.push(result)}catch(error){failed.push({operation,error})}return{successful,failed}};var init_atomic=__esm(()=>{init_Logger2();init_utils4();DEFAULT_ATOMIC_CONFIG={tempSuffix:".tmp",backup:!1,sync:!0,timestamp:!0}});import{chmod,stat as stat2}from"fs/promises";var PERMISSION_MODES,setFilePermissions=async(path2,mode)=>{let resolvedPath=resolvePath(path2);if(!validatePermissionMode(mode))throw createFileManagerError("INVALID_PERMISSION_MODE",`Invalid permission mode: ${mode.toString(8)}`,resolvedPath,"setFilePermissions");try{return await chmod(resolvedPath,mode),!0}catch(error){return logger.scoped("storage.fs").error(`Failed to set permissions for ${path2}`,error,{path:path2,mode}),!1}},getFilePermissions=async(path2)=>{let resolvedPath=resolvePath(path2);try{let mode=(await stat2(resolvedPath)).mode&511,permissions=parsePermissions(mode);return{path:resolvedPath,mode,owner:permissions.owner,group:permissions.group,others:permissions.others}}catch(error){throw createFileManagerError("PERMISSION_READ_FAILED",`Failed to read permissions: ${error}`,resolvedPath,"getFilePermissions")}},hasPermissions=async(path2,requiredMode)=>{try{return((await getFilePermissions(path2)).mode&requiredMode)===requiredMode}catch{return!1}},makeReadable=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode|256;return setFilePermissions(path2,newMode)},makeWritable=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode|128;return setFilePermissions(path2,newMode)},makeExecutable=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode|64;return setFilePermissions(path2,newMode)},makeReadOnly=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode&-147;return setFilePermissions(path2,newMode)},setCommonPermissions=async(path2,pattern)=>{let mode=PERMISSION_MODES[pattern];return setFilePermissions(path2,mode)};var init_permissions=__esm(()=>{init_Logger2();init_utils4();PERMISSION_MODES={OWNER_READ_WRITE:384,OWNER_ALL:448,GROUP_READ:416,GROUP_READ_WRITE:432,ALL_READ:420,ALL_READ_WRITE:438,ALL_READ_EXECUTE:493,ALL_FULL:511,READ_ONLY:292,EXECUTABLE:493}});var DEFAULT_STREAM_CONFIG,createFileWriter=async(path2,options={})=>{let resolvedPath=resolvePath(path2),config={...DEFAULT_STREAM_CONFIG,...options};await ensureDirectoryExists(extractDirectoryPath(resolvedPath));let writer=Bun.file(resolvedPath).writer({highWaterMark:config.highWaterMark}),isClosed=!1;return{write:(chunk)=>{if(isClosed)throw createFileManagerError("WRITER_CLOSED","Cannot write to closed writer",resolvedPath,"streamWrite");try{let result=writer.write(chunk);if(config.autoFlush)writer.flush();return result}catch(error){throw createFileManagerError("WRITE_FAILED",`Failed to write chunk: ${error}`,resolvedPath,"streamWrite")}},flush:()=>{if(isClosed)return 0;try{return writer.flush()}catch(error){throw createFileManagerError("FLUSH_FAILED",`Failed to flush writer: ${error}`,resolvedPath,"streamFlush")}},end:async(error)=>{if(isClosed)return 0;try{let result=await writer.end(error);return isClosed=!0,result}catch(err){throw isClosed=!0,createFileManagerError("END_FAILED",`Failed to end writer: ${err}`,resolvedPath,"streamEnd")}},ref:()=>{if(!isClosed)writer.ref()},unref:()=>{if(!isClosed)writer.unref()}}},writeStream=async(path2,chunks,options={})=>{let writer=await createFileWriter(path2,options),totalBytes=0;try{for(let chunk of chunks){let bytesWritten=writer.write(chunk);totalBytes+=bytesWritten}return await writer.flush(),await writer.end(),totalBytes}catch(error){try{await writer.end(error)}catch{}throw error}},appendStream=async(path2,chunks,options={})=>{let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath),existingContent=await file.exists()?await file.arrayBuffer():new ArrayBuffer(0),allChunks=[];if(existingContent.byteLength>0)allChunks.push(existingContent);return allChunks.push(...chunks),writeStream(resolvedPath,allChunks,options)},copyFileStream=async(sourcePath,destinationPath,options={})=>{let resolvedSource=resolvePath(sourcePath),sourceFile=Bun.file(resolvedSource);if(!await sourceFile.exists())throw createFileManagerError("SOURCE_NOT_FOUND",`Source file not found: ${sourcePath}`,resolvedSource,"copyFileStream");let sourceStream=sourceFile.stream(),writer=await createFileWriter(destinationPath,options),totalBytes=0;try{let reader=sourceStream.getReader();while(!0){let{done,value}=await reader.read();if(done)break;let bytesWritten=writer.write(value);totalBytes+=bytesWritten}return await writer.flush(),await writer.end(),totalBytes}catch(error){try{await writer.end(error)}catch{}throw error}},readFileStream=async(path2,chunkProcessor)=>{let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath);if(!await file.exists())throw createFileManagerError("FILE_NOT_FOUND",`File not found: ${path2}`,resolvedPath,"readFileStream");let reader=file.stream().getReader();try{while(!0){let{done,value}=await reader.read();if(done)break;await chunkProcessor(value)}}finally{reader.releaseLock()}};var init_streaming=__esm(()=>{init_utils4();DEFAULT_STREAM_CONFIG={highWaterMark:1048576,autoFlush:!0,closeOnEnd:!0}});import{readdir,rm,rmdir,stat as stat3}from"fs/promises";import{extname as extname2,join as join3}from"path";class BunFileManager{static instance;config;constructor(){this.config={...DEFAULT_CONFIG5}}static getInstance(){if(!BunFileManager.instance)BunFileManager.instance=new BunFileManager;return BunFileManager.instance}async createFile({dir,name,data,options={}}){let filePath=resolvePath(join3(dir,name));if(options.createDir!==!1)await ensureDirectoryExists(extractDirectoryPath(filePath));let fileData=options.type?new Blob([data],{type:options.type}):data;return await Bun.write(filePath,fileData)}async createJsonFile(dir,name,data){let fileName=ensureFileExtension(name,".json"),jsonString=safeJsonStringify(data);return this.createFile({dir,name:fileName,data:jsonString,options:{type:"application/json"}})}async createDirectory({path:path2}){await ensureDirectoryExists(path2)}async readFile({path:path2,format="text"}){let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath);if(!await file.exists())throw createFileManagerError("FILE_NOT_FOUND",`File not found: ${path2}`,resolvedPath,"readFile");switch(format){case"text":return await file.text();case"json":return await file.json();case"buffer":return await file.arrayBuffer();case"bytes":return await file.bytes();case"stream":return file.stream();default:return await file.text()}}async readJsonFile(path2){return this.readFile({path:path2,format:"json"})}async getFileInfo(path2){let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath),fileName=path2.split("/").pop()||path2,stats=null;try{stats=await stat3(resolvedPath)}catch{}return{name:fileName,path:resolvedPath,size:file.size,type:file.type,exists:await file.exists(),extension:extname2(fileName),createdAt:stats?.birthtime,modifiedAt:stats?.mtime}}async readDirectory({path:path2,recursive=!1}){let resolvedPath=resolvePath(path2);return await readdir(resolvedPath,{recursive,encoding:"utf8"})}async getFilesByExtension(dir,extension){let files=await this.readDirectory({path:dir}),normalizedExt=extension.startsWith(".")?extension:`.${extension}`;return files.filter((file)=>file.endsWith(normalizedExt))}async updateFile({path:path2,data,mode="overwrite"}){let resolvedPath=resolvePath(path2);if(mode==="append"){let combinedData=await this.readFile({path:path2,format:"text"})+data;return await Bun.write(resolvedPath,combinedData)}return await Bun.write(resolvedPath,data)}async updateJsonFile(path2,data,merge=!1){let finalData=data;if(merge)try{let existingData=await this.readJsonFile(path2);if(typeof existingData==="object"&&existingData!==null&&!Array.isArray(existingData)&&typeof data==="object"&&data!==null&&!Array.isArray(data))finalData={...existingData,...data}}catch{}return this.updateFile({path:path2,data:safeJsonStringify(finalData),mode:"overwrite"})}async appendToFile(path2,data){return this.updateFile({path:path2,data,mode:"append"})}async deleteFile(path2){try{let resolvedPath=resolvePath(path2);return await Bun.file(resolvedPath).delete(),!0}catch(error){return logger.scoped("storage.fs").error(`Failed to delete file ${path2}`,error,{path:path2}),!1}}async deleteDirectory({path:path2,recursive=!1}){try{let resolvedPath=resolvePath(path2);if(recursive)await rm(resolvedPath,{recursive:!0,force:!0});else await rmdir(resolvedPath);return!0}catch(error){return logger.scoped("storage.fs").error(`Failed to delete directory ${path2}`,error,{path:path2}),!1}}async deleteFiles(paths){let results=await executeBulkOperation(paths,async(path2)=>{if(!await this.deleteFile(path2))throw Error(`Failed to delete: ${path2}`);return path2}),success=[],failed=[];for(let i=0;i<results.length;i++){let result=results[i],originalPath=paths[i];if(result?.status==="fulfilled")success.push(originalPath||"");else failed.push(originalPath||"")}return{success,failed}}async exists(path2){let resolvedPath=resolvePath(path2);return await Bun.file(resolvedPath).exists()}async copyFile(sourcePath,destinationPath){let resolvedSource=resolvePath(sourcePath),resolvedDestination=resolvePath(destinationPath),sourceFile=Bun.file(resolvedSource);if(!await sourceFile.exists())throw createFileManagerError("SOURCE_NOT_FOUND",`Source file not found: ${sourcePath}`,resolvedSource,"copyFile");return await ensureDirectoryExists(extractDirectoryPath(resolvedDestination)),await Bun.write(resolvedDestination,sourceFile)}async moveFile(sourcePath,destinationPath){try{return await this.copyFile(sourcePath,destinationPath),await this.deleteFile(sourcePath),!0}catch(error){return logger.scoped("storage.fs").error("Failed to move file",error,{sourcePath,destinationPath}),!1}}getFormattedFileSize(bytes){return formatFileSize(bytes)}getConfig(){return{...this.config}}updateConfig(newConfig){let validation=validateConfig(newConfig);if(validation.isValid){let mergedConfig=mergeConfig(newConfig,this.config);Object.assign(this.config,mergedConfig)}return validation}validateConfiguration(config){return validateConfig(config)}async createStreamWriter(path2,options={}){return createFileWriter(path2,options)}async writeStream(path2,chunks,options={}){return writeStream(path2,chunks,options)}async appendStream(path2,chunks,options={}){return appendStream(path2,chunks,options)}async copyFileStream(sourcePath,destinationPath,options={}){return copyFileStream(sourcePath,destinationPath,options)}async readFileStream(path2,chunkProcessor){return readFileStream(path2,chunkProcessor)}async setPermissions(path2,mode){return setFilePermissions(path2,mode)}async setPermissionsAdvanced(options){return setFilePermissions(options.path,options.mode)}async getPermissions(path2){return getFilePermissions(path2)}async checkPermissions(path2,requiredMode){return hasPermissions(path2,requiredMode)}async makeFileReadable(path2){return makeReadable(path2)}async makeFileWritable(path2){return makeWritable(path2)}async makeFileExecutable(path2){return makeExecutable(path2)}async makeFileReadOnly(path2){return makeReadOnly(path2)}async setCommonPermission(path2,pattern){return setCommonPermissions(path2,pattern)}async atomicWrite(options){return atomicWrite(options)}async atomicJsonWrite(path2,data,options={}){return atomicJsonWrite(path2,data,options)}async createFileBackup(options){return createBackup(options)}async restoreFileFromBackup(backupPath,targetPath,deleteBackup=!1){return restoreFromBackup(backupPath,targetPath,deleteBackup)}async safeFileUpdate(path2,updateFunction,options={}){return safeUpdate(path2,updateFunction,options)}async batchAtomicOperations(operations){return batchAtomicWrite(operations)}}var init_core=__esm(()=>{init_Logger2();init_atomic();init_permissions();init_streaming();init_utils4()});var fileManager;var init_File=__esm(()=>{init_core();init_utils4();init_core();fileManager=BunFileManager.getInstance()});import{Pool}from"pg";var init_Postgre=__esm(()=>{init_Logger2()});var init_Managers=__esm(()=>{init_Azure();init_Dapr();init_File();init_Postgre();init_Redis()});var exports_utils={};__export(exports_utils,{validatePayload:()=>validatePayload,validateEnvVariables:()=>validateEnvVariables,toAudit:()=>toAudit,signNewAccessToken:()=>signNewAccessToken,sanitizePayload:()=>sanitizePayload,refreshAccessTokenWithLock:()=>refreshAccessTokenWithLock,parseTokenValuesFromHeaders:()=>parseTokenValuesFromHeaders,parseTimeToSeconds:()=>parseTimeToSeconds2,parseQueryParams:()=>parseQueryParams,initiateRedisManager:()=>initiateRedisManager,getRedisManager:()=>getRedisManager,ensureDatabaseExists:()=>ensureDatabaseExists,createAuditLog:()=>createAuditLog,buildPaginationMeta:()=>buildPaginationMeta});function parseTokenValuesFromHeaders(headers,tokenNames){let cookies=(headers.get("cookie")?.split(";")||[]).reduce((acc,cookie)=>{let trimmed=cookie.trim(),eqIndex=trimmed.indexOf("=");if(eqIndex>0)acc[trimmed.slice(0,eqIndex)]=trimmed.slice(eqIndex+1);return acc},{});return{access_token:cookies[tokenNames.access_token]||headers.get("authorization")?.split(" ")[1],refresh_token:cookies[tokenNames.refresh_token],session_token:cookies[tokenNames.session_token]}}async function initiateRedisManager(config){if(!config.redis){logger.info("[Redis] Not configured, skipping");return}let rawWithDapr=config.redis.withDapr;if(typeof rawWithDapr==="string"?process.env[rawWithDapr]?.toLowerCase()!=="false":rawWithDapr??!1){redisManagerInstance=new RedisManager({withDapr:!0,stateStoreName:config.redis.stateStoreName});return}let resolvedUrl=config.redis.url?process.env[config.redis.url]:void 0,resolvedHost=config.redis.host?process.env[config.redis.host]:void 0,resolvedPort=config.redis.port?parseInt(process.env[config.redis.port]||"",10):void 0;if((process.env.REDIS_AUTH_MODE||"password")!=="password"){let{getRedisToken:getRedisToken2,getRedisTokenExpiresAt:getRedisTokenExpiresAt2}=await Promise.resolve().then(() => (init_Azure(),exports_Azure)),clientId=process.env.AZURE_CLIENT_ID||"",initialToken=await getRedisToken2();redisManagerInstance=new RedisManager({host:resolvedHost,port:Number.isNaN(resolvedPort)?void 0:resolvedPort,password:initialToken,username:clientId,tls:!0});let scheduleRedisTokenRefresh=()=>{let expiresAt=getRedisTokenExpiresAt2(),refreshIn=Math.max(expiresAt-Date.now()-300000,30000);setTimeout(async()=>{try{let newToken=await getRedisToken2();if(redisManagerInstance)await redisManagerInstance.reauthenticate(clientId,newToken),logger.info("[Redis] Entra ID token refreshed successfully");scheduleRedisTokenRefresh()}catch(err){logger.error("[Redis] Token refresh failed \u2014 retrying in 30s",err),setTimeout(scheduleRedisTokenRefresh,30000)}},refreshIn)};scheduleRedisTokenRefresh()}else{let resolvedPassword=process.env.REDIS_PASSWORD||void 0;redisManagerInstance=new RedisManager({url:resolvedUrl,host:resolvedHost,port:Number.isNaN(resolvedPort)?void 0:resolvedPort,...resolvedPassword?{password:resolvedPassword}:{}})}}function getRedisManager(){return redisManagerInstance}function parseTimeToSeconds2(timeString){if(typeof timeString==="number")return timeString;if(!timeString||timeString.trim()==="")throw Error("Time string cannot be empty");let match=timeString.trim().match(/^(\d+(?:\.\d+)?)\s*([smhdwMy])$/);if(!match||!match[1]||!match[2])throw Error(`Invalid time format: "${timeString}". Expected format: "75s", "10m", "2h", "1d", "1w", "2M", "1y"`);let value=parseFloat(match[1]),unit=match[2],multiplier={s:1,m:60,h:3600,d:86400,w:604800,M:2592000,y:31536000}[unit];if(multiplier===void 0)throw Error(`Unknown time unit: "${unit}"`);let seconds=Math.floor(value*multiplier);if(seconds<=0)throw Error(`Time value must be positive: "${timeString}"`);return seconds}function signNewAccessToken({sessionData,options,refreshTokenId,roles,claims}){let secretEnvName=options.authentication?.accessToken?.secret;if(!secretEnvName)throw Error("Access token secret env name is not configured");let secret=process.env[secretEnvName];if(!secret)throw Error(`Access token secret env "${secretEnvName}" is not set`);return signJWT({subject:sessionData.userId,issuer:options.authentication?.accessToken?.issuer,audience:options.authentication?.accessToken?.audience,algorithm:options.authentication?.accessToken?.algorithm,expiresInSeconds:parseTimeToSeconds2(options.authentication?.accessToken?.expiresIn??"15m"),sessionId:sessionData.id,customClaims:{refreshTokenId,...roles&&roles.length>0?{roles}:{},...claims&&claims.length>0?{claims}:{}}},secret)}function toAudit(payload,summary){return payload?{entityName:payload.entity_name,entityId:payload.entity_id===" - "?null:payload.entity_id,operation:payload.operation_type,userId:payload.user_id==="unknown"?null:payload.user_id,summary,ipAddress:payload.ip_address,userAgent:payload.user_agent,path:payload.path,query:payload.query}:void 0}function reconstructBracketParams(query){let result={},arrayGroups={};for(let[key,value]of Object.entries(query)){let match=key.match(/^(\w+)\[\d*\]\[(\w+)\]$/),arrayName=match?.[1],prop=match?.[2];if(arrayName&&prop){if(!arrayGroups[arrayName])arrayGroups[arrayName]={};let group=arrayGroups[arrayName];if(!group[prop])group[prop]=[];let arr=group[prop];if(Array.isArray(value))for(let v of value)arr.push(v);else arr.push(value)}else result[key]=value}for(let[arrayName,props]of Object.entries(arrayGroups)){let propNames=Object.keys(props);if(propNames.length===0)continue;let maxLen=Math.max(...propNames.map((p)=>(props[p]||[]).length)),items=[];for(let i=0;i<maxLen;i++){let item={};for(let p of propNames)item[p]=(props[p]||[])[i];items.push(item)}result[arrayName]=items}return result}function parseQueryParams(query){let q=reconstructBracketParams(query),parseJSONOrPassthrough=(value)=>{if(value===void 0||value===null)return;if(typeof value==="object")return value;if(typeof value==="string")try{return JSON.parse(value)}catch{return}return},page=q.page?parseInt(q.page,10):1,limit=q.limit?parseInt(q.limit,10):20,offset=q.offset?parseInt(q.offset,10):(page-1)*limit;return{page,limit,offset,search:q.search,searchFields:q.searchFields?q.searchFields.split(","):void 0,filters:parseJSONOrPassthrough(q.filters),sort:parseJSONOrPassthrough(q.sort),select:q.select?q.select.split(","):void 0,with:parseJSONOrPassthrough(q.with),distinct:q.distinct==="true",distinctOn:q.distinctOn?q.distinctOn.split(","):void 0}}function buildPaginationMeta(page,limit,offset,totalItems){let totalPages=Math.ceil(totalItems/limit),hasNextPage=page<totalPages,hasPrevPage=page>1;return{page,limit,offset,totalItems,totalPages,hasNextPage,hasPrevPage,nextPage:hasNextPage?page+1:null,prevPage:hasPrevPage?page-1:null}}function getBaseTypeValidator(type){let stringTypes=["varchar","char","text","uuid","citext","bit","varbit"],numberTypes=["integer","smallint","bigint","serial","smallserial","bigserial","real","doublePrecision","numeric","decimal"],booleanTypes=["boolean"];if(stringTypes.includes(type))return(v)=>({valid:typeof v==="string",expectedType:"string"});if(numberTypes.includes(type))return(v)=>({valid:typeof v==="number",expectedType:"number"});if(booleanTypes.includes(type))return(v)=>({valid:typeof v==="boolean",expectedType:"boolean"});if(type==="json"||type==="jsonb")return(v)=>({valid:typeof v==="object",expectedType:"object"});return()=>({valid:!0,expectedType:"any"})}function validatePayload(payload,columns,isPartial=!1){let errors=[];for(let col4 of columns){let value=payload[col4.name]??payload[col4.name.replace(/_([a-z])/g,(_,l)=>l.toUpperCase())],hasDbDefault=col4.default!==void 0||!!col4.defaultRaw||!!col4.generatedByDefaultAsIdentity||!!col4.generatedAlwaysAsIdentity||!!col4.generatedAlwaysAs,isRequired=col4.notNull&&!col4.nullable&&!hasDbDefault;if(value===void 0||value===null){if(isRequired&&!isPartial)errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} is required`});continue}if(col4.array){let baseValidator=getBaseTypeValidator(col4.type),expectedType=baseValidator(void 0).expectedType;if(!Array.isArray(value)){errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be an array of ${expectedType}`});continue}if(value.some((el)=>el!==null&&!baseValidator(el).valid))errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be an array of ${expectedType}`});continue}let typeCheck=getBaseTypeValidator(col4.type)(value);if(!typeCheck.valid){errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be of type ${typeCheck.expectedType}`});continue}if(typeof value==="string"){let len=value.length;if(col4.length&&len>col4.length)errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} exceeds max length of ${col4.length}`});if(col4.validation?.minLength&&len<col4.validation.minLength)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at least ${col4.validation.minLength} characters`});if(col4.validation?.maxLength&&len>col4.validation.maxLength)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at most ${col4.validation.maxLength} characters`});if(col4.validation?.pattern){if(!new RegExp(col4.validation.pattern).test(value))errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} does not match required pattern`})}if(col4.validation?.format){let formatRegex=FORMAT_PATTERNS[col4.validation.format];if(formatRegex&&!formatRegex.test(value))errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be a valid ${col4.validation.format}`})}}if(typeof value==="number"){if(col4.validation?.min!==void 0&&value<col4.validation.min)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at least ${col4.validation.min}`});if(col4.validation?.max!==void 0&&value>col4.validation.max)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at most ${col4.validation.max}`})}if(col4.enumValues&&col4.enumValues.length>0){if(!col4.enumValues.includes(value))errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be one of: ${col4.enumValues.join(", ")}`})}}return{valid:errors.length===0,errors}}function escapeHtml(str2){return str2.replace(/[&<>"'`=/]/g,(char)=>HTML_ENTITIES[char]||char)}function stripTags(str2){return str2.replace(/<[^>]*>/g,"")}function normalizeEmail(email){let parts=email.split("@"),localPart=parts[0],domain=parts[1];if(!localPart||!domain)return email;let beforePlus=localPart.split("+")[0];if(!beforePlus)return email;return`${beforePlus.replace(/\./g,"")}@${domain.toLowerCase()}`}function slugify(str2){return str2.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function applySanitizer(value,sanitizer){if(value===null||value===void 0)return value;switch(sanitizer){case"trim":return typeof value==="string"?value.trim():value;case"lowercase":return typeof value==="string"?value.toLowerCase():value;case"uppercase":return typeof value==="string"?value.toUpperCase():value;case"escapeHtml":return typeof value==="string"?escapeHtml(value):value;case"stripTags":return typeof value==="string"?stripTags(value):value;case"normalizeEmail":return typeof value==="string"?normalizeEmail(value):value;case"toNumber":if(typeof value==="number")return value;if(typeof value==="string"){let num=Number(value);return Number.isNaN(num)?value:num}return value;case"toBoolean":if(typeof value==="boolean")return value;if(typeof value==="string"){let lower=value.toLowerCase();if(lower==="true"||lower==="1"||lower==="yes")return!0;if(lower==="false"||lower==="0"||lower==="no")return!1}if(typeof value==="number")return value!==0;return value;case"slugify":return typeof value==="string"?slugify(value):value;default:return value}}function sanitizePayload(payload,columns){let sanitized={},toCamel2=(s)=>s.replace(/_([a-z])/g,(_,l)=>l.toUpperCase());for(let key of Object.keys(payload)){let value=payload[key],snakeKey=key.replace(/[A-Z]/g,(l)=>`_${l.toLowerCase()}`),col4=columns.find((c)=>c.name===key||c.name===snakeKey);if(col4?.sanitize&&col4.sanitize.length>0)for(let sanitizer of col4.sanitize)value=applySanitizer(value,sanitizer);if(col4&&(col4.type==="timestamp"||col4.type==="timestamptz"||col4.type==="date")&&typeof value==="string"){let parsed=new Date(value);if(!Number.isNaN(parsed.getTime()))value=parsed}let normalizedKey=key.includes("_")?toCamel2(key):key;sanitized[normalizedKey]=value}return sanitized}function createAuditLog(db,auditTable,entry){if(!db||!auditTable)return;let logEntry={user_id:entry.user_id,entity_name:entry.entity_name,entity_id:entry.entity_id,operation:entry.operation,old_data:entry.old_data??null,new_data:entry.new_data??null,timestamp:new Date().toISOString()};db.insert(auditTable).values(logEntry).execute().catch((err)=>{logger.error("[Audit] Database audit write failed",err,{entity:logEntry.entity_name,operation:logEntry.operation})})}async function refreshAccessTokenWithLock(userId,sessionId,generateToken){let redis=new RedisManager,lockKey=`${REFRESH_LOCK_PREFIX}${userId}`,cacheKey=`${ACCESS_TOKEN_CACHE_PREFIX}${userId}:${sessionId}`,cachedResult=await redis.read(cacheKey);if(cachedResult.success&&cachedResult.data)return{success:!0,accessToken:cachedResult.data,fromCache:!0};let lockResult=await redis.acquireLock(lockKey,LOCK_TTL_SECONDS);if(!lockResult.success)return{success:!1,error:lockResult.error};if(lockResult.data)try{let newToken=generateToken();return await redis.create(cacheKey,newToken,ACCESS_TOKEN_CACHE_TTL_SECONDS),{success:!0,accessToken:newToken,fromCache:!1}}finally{await redis.releaseLock(lockKey)}let waitResult=await redis.waitForLock(lockKey,LOCK_WAIT_TIMEOUT_MS,50);if(!waitResult.success)return{success:!1,error:waitResult.error};if(!waitResult.data)return{success:!1,error:"Lock wait timeout"};let newCachedResult=await redis.read(cacheKey);if(newCachedResult.success&&newCachedResult.data)return{success:!0,accessToken:newCachedResult.data,fromCache:!0};let fallbackToken=generateToken();return await redis.create(cacheKey,fallbackToken,ACCESS_TOKEN_CACHE_TTL_SECONDS),{success:!0,accessToken:fallbackToken,fromCache:!1}}function validateEnvVariables(config){let errors=[],resolved={},databaseAuthMode=process.env.DATABASE_AUTH_MODE||"password",redisAuthMode=process.env.REDIS_AUTH_MODE||"password";resolved.databaseAuthMode=databaseAuthMode,resolved.redisAuthMode=redisAuthMode;let entraIdModes=["managed_identity","service_principal"];if(entraIdModes.includes(databaseAuthMode)||entraIdModes.includes(redisAuthMode)){if(!process.env.AZURE_CLIENT_ID)logger.warn("[Config] AZURE_CLIENT_ID is not set. Required for user-assigned managed identity.");if([databaseAuthMode,redisAuthMode].filter((m)=>m==="service_principal").length>0){if(!process.env.AZURE_TENANT_ID)errors.push({field:"azure.tenantId",envName:"AZURE_TENANT_ID",message:"AZURE_TENANT_ID is required for service_principal auth mode."});if(!process.env.AZURE_CLIENT_SECRET)errors.push({field:"azure.clientSecret",envName:"AZURE_CLIENT_SECRET",message:"AZURE_CLIENT_SECRET is required for service_principal auth mode."})}}if(config.database?.url){let envValue=process.env[config.database.url];if(!envValue)errors.push({field:"database.url",envName:config.database.url,message:`Environment variable "${config.database.url}" is not set. Please set it in your .env file.`});else resolved.databaseUrl=envValue}let validationWithDapr=typeof config.redis?.withDapr==="string"?process.env[config.redis.withDapr]?.toLowerCase()!=="false":config.redis?.withDapr??!1;if(config.redis&&!validationWithDapr)if(config.redis.url){let envValue=process.env[config.redis.url];if(!envValue)errors.push({field:"redis.url",envName:config.redis.url,message:`Environment variable "${config.redis.url}" is not set. Please set it in your .env file.`});else resolved.redisUrl=envValue}else{if(config.redis.host){if(!process.env[config.redis.host])errors.push({field:"redis.host",envName:config.redis.host,message:`Environment variable "${config.redis.host}" is not set. Please set it in your .env file.`})}if(config.redis.port){if(!process.env[config.redis.port])errors.push({field:"redis.port",envName:config.redis.port,message:`Environment variable "${config.redis.port}" is not set. Please set it in your .env file.`})}}if(config.authentication?.enabled){if(!config.authentication.mode)errors.push({field:"authentication.mode",envName:"",message:'authentication.mode is required when authentication is enabled. Use "full" for IDP/standalone services, "consumer" for resource servers.'});if(config.authentication.accessToken?.secret){let envValue=process.env[config.authentication.accessToken.secret];if(!envValue)errors.push({field:"authentication.accessToken.secret",envName:config.authentication.accessToken.secret,message:`Environment variable "${config.authentication.accessToken.secret}" is not set. Please set it in your .env file.`});else resolved.accessTokenSecret=envValue}else errors.push({field:"authentication.accessToken.secret",envName:"",message:"authentication.accessToken.secret is required when authentication is enabled."});let isConsumerMode=config.authentication.mode==="consumer";if(config.authentication.refreshToken?.secret){let envValue=process.env[config.authentication.refreshToken.secret];if(!envValue)errors.push({field:"authentication.refreshToken.secret",envName:config.authentication.refreshToken.secret,message:`Environment variable "${config.authentication.refreshToken.secret}" is not set. Please set it in your .env file.`});else resolved.refreshTokenSecret=envValue}else if(!isConsumerMode)errors.push({field:"authentication.refreshToken.secret",envName:"",message:"authentication.refreshToken.secret is required when authentication is enabled."});if(config.authentication.sessionToken?.secret){let envValue=process.env[config.authentication.sessionToken.secret];if(!envValue)errors.push({field:"authentication.sessionToken.secret",envName:config.authentication.sessionToken.secret,message:`Environment variable "${config.authentication.sessionToken.secret}" is not set. Please set it in your .env file.`});else resolved.sessionTokenSecret=envValue}else if(!isConsumerMode)errors.push({field:"authentication.sessionToken.secret",envName:"",message:"authentication.sessionToken.secret is required when authentication is enabled."})}if(config.authentication?.oauth?.enabled&&config.authentication.oauth.providers){let resolvedProviders={};for(let[providerName,providerConfig]of Object.entries(config.authentication.oauth.providers)){if(!providerConfig)continue;let{clientId:clientIdEnvName,clientSecret:clientSecretEnvName,redirectUri:redirectUriEnvName,tenantId:tenantIdEnvName}=providerConfig,clientId=process.env[clientIdEnvName],clientSecret=process.env[clientSecretEnvName],redirectUri=process.env[redirectUriEnvName]??redirectUriEnvName,tenantId=tenantIdEnvName?process.env[tenantIdEnvName]??tenantIdEnvName:void 0;if(!clientId)errors.push({field:`authentication.oauth.providers.${providerName}.clientId`,envName:clientIdEnvName,message:`Environment variable "${clientIdEnvName}" is not set (OAuth ${providerName} clientId).`});if(!clientSecret)errors.push({field:`authentication.oauth.providers.${providerName}.clientSecret`,envName:clientSecretEnvName,message:`Environment variable "${clientSecretEnvName}" is not set (OAuth ${providerName} clientSecret).`});if(clientId&&clientSecret)resolvedProviders[providerName]={clientId,clientSecret,redirectUri,tenantId,scopes:providerConfig.scopes,authorizationUrl:providerConfig.authorizationUrl,tokenUrl:providerConfig.tokenUrl,userInfoUrl:providerConfig.userInfoUrl,extraAuthParams:providerConfig.extraAuthParams}}if(Object.keys(resolvedProviders).length>0)resolved.oauthProviders=resolvedProviders}return{valid:errors.length===0,errors,resolved}}async function ensureDatabaseExists(databaseUrl,logger2,authMode){let{Pool:Pool2}=await import("pg"),targetDb=new URL(databaseUrl).pathname.replace("/","");if(!targetDb)return;let adminUrl=new URL(databaseUrl);adminUrl.pathname="/postgres";let pool;if(authMode&&authMode!=="password"){let{getPostgresToken:getPostgresToken2}=await Promise.resolve().then(() => (init_Azure(),exports_Azure));pool=new Pool2({connectionString:adminUrl.toString(),password:getPostgresToken2,ssl:{rejectUnauthorized:!0}})}else pool=new Pool2({connectionString:adminUrl.toString()});try{if((await pool.query("SELECT 1 FROM pg_database WHERE datname = $1",[targetDb])).rowCount===0)logger2.info(`[Database] Creating database "${targetDb}"...`),await pool.query(`CREATE DATABASE "${targetDb}" TEMPLATE template0`),logger2.info(`[Database] Database "${targetDb}" created successfully`);else logger2.info(`[Database] Database "${targetDb}" exists`)}catch(err){let message=err instanceof Error?err.message:String(err);logger2.warn(`[Database] Could not auto-create database: ${message}`)}finally{await pool.end()}}var redisManagerInstance=null,FORMAT_PATTERNS,HTML_ENTITIES,ACCESS_TOKEN_CACHE_PREFIX="access_token:",REFRESH_LOCK_PREFIX="refresh_lock:",LOCK_TTL_SECONDS=5,LOCK_WAIT_TIMEOUT_MS=3000,ACCESS_TOKEN_CACHE_TTL_SECONDS=60;var init_utils5=__esm(()=>{init_Managers();init_Services();init_Logger2();FORMAT_PATTERNS={email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,url:/^https?:\/\/.+/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/,time:/^\d{2}:\d{2}:\d{2}$/,uri:/^[a-z][a-z0-9+.-]*:/i,ipv4:/^(\d{1,3}\.){3}\d{1,3}$/,ipv6:/^([0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$/i};HTML_ENTITIES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#96;","=":"&#x3D;"}});import{eq as eq10}from"drizzle-orm";import{pgSchema}from"drizzle-orm/pg-core";class TenantRegistry{db;logger;mainSchemaName;mainSchemaTables;mainSchemaRelations;createAllTablesForSchema;createAllRelationsForSchema;appId;authMode;tenantResolution;tenantHeader;redisCacheTtlSeconds;defaultTrustedSources;idpUrl;allowDataLoss;tenantsBySubdomain=new Map;tenantsBySchemaName=new Map;tenantsById=new Map;schemaContexts=new Map;tenantFeatures=new Map;tenantsByDomainHostname=new Map;constructor(config){this.db=config.db,this.logger=config.logger,this.mainSchemaName=config.mainSchemaName,this.mainSchemaTables=config.mainSchemaTables,this.mainSchemaRelations=config.mainSchemaRelations,this.createAllTablesForSchema=config.createAllTablesForSchema,this.createAllRelationsForSchema=config.createAllRelationsForSchema,this.appId=config.appId,this.authMode=config.authMode,this.tenantResolution=config.tenantResolution,this.tenantHeader=config.tenantHeader,this.redisCacheTtlSeconds=config.redisCacheTtlSeconds,this.defaultTrustedSources=config.defaultTrustedSources,this.idpUrl=config.idpUrl,this.allowDataLoss=config.allowDataLoss===!0}async initialize(){this.logger.info("[TenantRegistry] Initializing..."),this.schemaContexts.set(this.mainSchemaName,{schemaName:this.mainSchemaName,schemaTables:this.mainSchemaTables,schemaRelations:this.mainSchemaRelations,tenant:null});let tenants=await this.loadTenantsFromDb();this.logger.info(`[TenantRegistry] Loaded ${tenants.length} tenants from database`);let features=await this.loadTenantFeaturesFromDb();this.logger.info(`[TenantRegistry] Loaded ${features.length} tenant feature mappings`);for(let tenant of tenants)this.indexTenant(tenant);for(let feature of features){let existing=this.tenantFeatures.get(feature.tenantId)||[];existing.push(feature),this.tenantFeatures.set(feature.tenantId,existing)}let activeTenants=tenants.filter((t)=>t.status==="active");for(let tenant of activeTenants)await this.buildSchemaContext(tenant);await this.loadDomainHostnames(),this.logger.info(`[TenantRegistry] Initialized with ${activeTenants.length} active tenant schemas + main schema`)}resolveFromRequest(request){let url=new URL(request.url),host=request.headers.get("host")||url.host||"",normalizedHost=normalizeHost(host);if(normalizedHost){let byHostname=this.tenantsByDomainHostname.get(normalizedHost);if(byHostname)return this.validateAndReturnTenant(byHostname)}if(this.tenantResolution==="subdomain"||this.tenantResolution==="both"){let subdomain=extractSubdomain(host);if(subdomain){let tenant=this.tenantsBySubdomain.get(subdomain);if(tenant)return this.validateAndReturnTenant(tenant);return{resolved:!1,error:`Tenant not found for subdomain: ${subdomain}`,statusCode:404}}}if(this.tenantResolution==="header"||this.tenantResolution==="both"){let tenantIdOrSubdomain=request.headers.get(this.tenantHeader);if(tenantIdOrSubdomain){let result=this.resolveFromHeader(tenantIdOrSubdomain,request);if(result)return result}}let mainContext=this.schemaContexts.get(this.mainSchemaName);if(mainContext)return{resolved:!0,context:mainContext};return{resolved:!1,error:"No tenant could be resolved and main schema is unavailable",statusCode:500}}getSchemaContext(schemaName){return this.schemaContexts.get(schemaName)}getMainContext(){let ctx=this.schemaContexts.get(this.mainSchemaName);if(!ctx)throw Error("[TenantRegistry] Main schema context not initialized");return ctx}getActiveTenants(){return Array.from(this.tenantsById.values()).filter((t)=>t.status==="active")}getTenantById(id){return this.tenantsById.get(id)}getTenantFeatures(tenantId){return this.tenantFeatures.get(tenantId)||[]}isTenantFeatureEnabled(tenantId,featureName){return(this.tenantFeatures.get(tenantId)||[]).find((f)=>f.featureName===featureName)?.enabled??!1}getTenantIdsWithFeature(featureName){let result=[];for(let[tenantId,features]of this.tenantFeatures)if(features.find((f)=>f.featureName===featureName&&f.enabled))result.push(tenantId);return result}getSchemaNamesWithFeature(featureName){let tenantIds=this.getTenantIdsWithFeature(featureName),schemaNames=[];for(let tenantId of tenantIds){let tenant=this.tenantsById.get(tenantId);if(tenant&&tenant.status==="active")schemaNames.push(tenant.schemaName)}return schemaNames}getAllSchemaNames(){return Array.from(this.schemaContexts.keys())}async provisionTenant(tenant){this.logger.info(`[TenantRegistry] Provisioning tenant: ${tenant.subdomain} \u2192 ${tenant.schemaName}`),await ensureSchemaExists(this.db,tenant.schemaName);let context=await this.buildSchemaContext(tenant);return this.indexTenant(tenant),await this.syncSchemaToDb(context),this.logger.info(`[TenantRegistry] Tenant provisioned: ${tenant.subdomain}`),context}async syncSchemaToDb(context){let{pushSchema}=await import("drizzle-kit/api"),{applySchemaPush:applySchemaPush2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),targetSchema=pgSchema(context.schemaName);try{let push=await pushSchema({schema:targetSchema,...context.schemaTables},this.db,[context.schemaName]);if(await applySchemaPush2(push,{schemaName:context.schemaName,allowDataLoss:this.allowDataLoss,logger:this.logger}))this.logger.info(`[TenantRegistry] Schema sync completed for: ${context.schemaName}`)}catch(err){let msg=err instanceof Error?err.message:String(err);this.logger.warn(`[TenantRegistry] Schema sync warning for ${context.schemaName}: ${msg}`)}}async syncAllSchemas(){for(let[schemaName,context]of this.schemaContexts)this.logger.info(`[TenantRegistry] Syncing schema: ${schemaName}`),await ensureSchemaExists(this.db,schemaName),await this.syncSchemaToDb(context)}async invalidateCache(subdomain){try{let{getRedisManager:getRedisManager2}=await Promise.resolve().then(() => (init_utils5(),exports_utils)),redis=getRedisManager2();if(redis)await redis.remove(`tenant:${subdomain}`),this.logger.info(`[TenantRegistry] Cache invalidated for: ${subdomain}`)}catch{}}async refreshTenant(tenantId){let tenantsTable=this.mainSchemaTables.tenants;if(!tenantsTable)return;let row=(await this.db.select().from(tenantsTable).where(eq10(tenantsTable.id,tenantId)).limit(1))[0];if(!row)return;let tenant=rowToTenantRecord(row),oldTenant=this.tenantsById.get(tenantId);if(oldTenant)this.tenantsBySubdomain.delete(oldTenant.subdomain),this.tenantsBySchemaName.delete(oldTenant.schemaName);if(this.indexTenant(tenant),tenant.status==="active")await this.buildSchemaContext(tenant);else this.schemaContexts.delete(tenant.schemaName);if(oldTenant)await this.invalidateCache(oldTenant.subdomain);await this.invalidateCache(tenant.subdomain)}async initializeFromIdp(){if(!this.idpUrl){this.logger.error("[TenantRegistry] Consumer multi-tenant requires idpUrl (IDP_URL)");return}this.logger.info(`[TenantRegistry] Initializing from IDP: ${this.idpUrl}`),this.schemaContexts.set(this.mainSchemaName,{schemaName:this.mainSchemaName,schemaTables:this.mainSchemaTables,schemaRelations:this.mainSchemaRelations,tenant:null});let tenants=await this.loadTenantsFromIdp();this.logger.info(`[TenantRegistry] Fetched ${tenants.length} tenants from IDP`);for(let tenant of tenants)this.indexTenant(tenant);let activeTenants=tenants.filter((t)=>t.status==="active");for(let tenant of activeTenants)await this.buildSchemaContext(tenant);await this.loadDomainHostnames(),this.logger.info(`[TenantRegistry] Consumer initialized with ${activeTenants.length} active tenant schemas + main schema`)}isConsumerMode(){return this.authMode==="consumer"&&!!this.idpUrl}async syncFromIdp(){if(!this.isConsumerMode())return{added:[],removed:[],total:this.tenantsById.size};let tenants=await this.loadTenantsFromIdp(),added=[],removed=[],seenSchemaNames=new Set;for(let tenant of tenants){seenSchemaNames.add(tenant.schemaName);let known=this.tenantsById.get(tenant.id);if(known)this.tenantsBySubdomain.delete(known.subdomain),this.tenantsBySchemaName.delete(known.schemaName);if(this.indexTenant(tenant),tenant.status==="active"){if(!this.schemaContexts.has(tenant.schemaName)){await ensureSchemaExists(this.db,tenant.schemaName);let ctx=await this.buildSchemaContext(tenant);await this.syncSchemaToDb(ctx),added.push(tenant.schemaName),await this.invalidateCache(tenant.subdomain),this.logger.info(`[TenantRegistry] Synced new tenant from IDP: ${tenant.subdomain}`)}}else if(this.schemaContexts.has(tenant.schemaName))this.schemaContexts.delete(tenant.schemaName),removed.push(tenant.schemaName),await this.invalidateCache(tenant.subdomain),this.logger.info(`[TenantRegistry] Deactivated tenant context: ${tenant.subdomain}`)}for(let[schemaName,ctx]of this.schemaContexts){if(schemaName===this.mainSchemaName)continue;if(!seenSchemaNames.has(schemaName)){if(this.schemaContexts.delete(schemaName),removed.push(schemaName),ctx.tenant)this.tenantsBySubdomain.delete(ctx.tenant.subdomain),this.tenantsById.delete(ctx.tenant.id),this.tenantsBySchemaName.delete(schemaName),await this.invalidateCache(ctx.tenant.subdomain)}}return{added,removed,total:tenants.length}}registerDomainHostname(hostname,tenantId){let tenant=this.tenantsById.get(tenantId);if(!tenant)return;this.tenantsByDomainHostname.set(normalizeHost(hostname),tenant)}unregisterDomainHostname(hostname){this.tenantsByDomainHostname.delete(normalizeHost(hostname))}async loadDomainHostnames(){let table=this.mainSchemaTables.domainHostnames;if(!table)return 0;try{let rows=await this.db.select().from(table),count=0;this.tenantsByDomainHostname.clear();for(let row of rows){let status=String(row.status??""),tenantId=String(row.tenantId??row.tenant_id??""),hostname=String(row.normalizedHostname??row.normalized_hostname??"");if(status!=="active"||!tenantId||!hostname)continue;let tenant=this.tenantsById.get(tenantId);if(!tenant)continue;this.tenantsByDomainHostname.set(normalizeHost(hostname),tenant),count++}if(count>0)this.logger.info(`[TenantRegistry] Indexed ${count} active custom hostnames`);return count}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to load custom hostnames: ${msg}`),0}}async loadTenantsFromIdp(){if(!this.idpUrl)return[];try{let response=await fetch(`${this.idpUrl}/tenants`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!response.ok)return this.logger.warn(`[TenantRegistry] IDP tenant fetch failed: ${response.status} ${response.statusText}`),[];return((await response.json())?.data?.items||[]).map((item)=>rowToTenantRecord(item))}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to fetch tenants from IDP: ${msg}`),[]}}async loadTenantsFromDb(){let tenantsTable=this.mainSchemaTables.tenants;if(!tenantsTable)return this.logger.warn("[TenantRegistry] No tenants table found in main schema"),[];try{return(await this.db.select().from(tenantsTable)).map((row)=>rowToTenantRecord(row))}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to load tenants: ${msg}`),[]}}async loadTenantFeaturesFromDb(){let featuresTable=this.mainSchemaTables.tenantFeatures;if(!featuresTable)return this.logger.warn("[TenantRegistry] No tenant_features table found in main schema"),[];try{return(await this.db.select().from(featuresTable)).map((row)=>rowToFeatureRecord(row,parseJsonbToConfig))}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to load tenant features: ${msg}`),[]}}indexTenant(tenant){if(this.tenantsById.set(tenant.id,tenant),this.tenantsBySubdomain.set(tenant.subdomain,tenant),this.tenantsBySchemaName.set(tenant.schemaName,tenant),tenant.domain)this.tenantsBySubdomain.set(tenant.domain,tenant)}async buildSchemaContext(tenant){let schema=pgSchema(tenant.schemaName),schemaTables=this.createAllTablesForSchema(schema),schemaRelations=this.createAllRelationsForSchema?this.createAllRelationsForSchema(schema):{},context={schemaName:tenant.schemaName,schemaTables,schemaRelations,tenant};return this.schemaContexts.set(tenant.schemaName,context),context}resolveFromHeader(tenantIdOrSubdomain,request){let tenant=this.tenantsBySubdomain.get(tenantIdOrSubdomain);if(!tenant)tenant=this.tenantsById.get(tenantIdOrSubdomain);if(!tenant)tenant=this.tenantsBySchemaName.get(tenantIdOrSubdomain);if(!tenant)return{resolved:!1,error:`Tenant not found for header value: ${tenantIdOrSubdomain}`,statusCode:404};if(!isTrustedSource(tenant,request,this.authMode,this.defaultTrustedSources))return{resolved:!1,error:`Untrusted source for tenant: ${tenant.subdomain}`,statusCode:403};return this.validateAndReturnTenant(tenant)}validateAndReturnTenant(tenant){if(tenant.status==="suspended")return{resolved:!1,error:`Tenant ${tenant.subdomain} is suspended: ${tenant.suspendedReason||"No reason provided"}`,statusCode:403};if(tenant.status==="provisioning")return{resolved:!1,error:`Tenant ${tenant.subdomain} is still being provisioned`,statusCode:503};if(tenant.status==="archived")return{resolved:!1,error:`Tenant ${tenant.subdomain} has been archived`,statusCode:410};let context=this.schemaContexts.get(tenant.schemaName);if(!context)return{resolved:!1,error:`Schema context not found for tenant: ${tenant.subdomain}`,statusCode:500};return{resolved:!0,context}}}var init_TenantRegistry=__esm(()=>{init_schema()});var init_Tenant=__esm(()=>{init_schema();init_TenantRegistry()});var init_types5=()=>{};import{and as and5,desc as desc2,eq as eq11,inArray as inArray2}from"drizzle-orm";function toCamel2(obj){let result={};for(let[key,value]of Object.entries(obj)){let camelKey=key.replace(/_([a-z])/g,(_,c)=>c.toUpperCase());result[camelKey]=value}return result}function fromCamel2(obj){let result={};for(let[key,value]of Object.entries(obj)){let snakeKey=key.replace(/[A-Z]/g,(c)=>`_${c.toLowerCase()}`);result[snakeKey]=value}return result}class VerificationService{db;schemaTables;config;logger;onNotificationTrigger;constructor(serviceConfig){this.db=serviceConfig.db,this.schemaTables=serviceConfig.schemaTables,this.config=serviceConfig.config,this.logger=serviceConfig.logger}setNotificationHandler(handler){this.onNotificationTrigger=handler}getConnectedNotificationNodeIds(stepNodeId,steps,edges){let result=new Set,getNeighbors=(nid)=>{let neighbors=[];for(let edge of edges){let{sourceNodeId:src,targetNodeId:tgt}=edge;if(src===nid)neighbors.push(tgt);else if(tgt===nid)neighbors.push(src)}return neighbors},directNeighbors=getNeighbors(stepNodeId);for(let neighborId of directNeighbors)if(steps.find((s)=>s.nodeId===neighborId)?.nodeType==="notification")result.add(neighborId);for(let neighborId of directNeighbors)if(steps.find((s)=>s.nodeId===neighborId)?.nodeType==="verifier"){let verifierNeighbors=getNeighbors(neighborId);for(let vNeighborId of verifierNeighbors){if(vNeighborId===stepNodeId)continue;if(steps.find((s)=>s.nodeId===vNeighborId)?.nodeType==="notification")result.add(vNeighborId)}}let ids=[...result];return this.logger.info(`[Verification] Connected notification nodes for step ${stepNodeId}: [${ids.join(", ")}]`),ids}getTable(name){return resolveSchemaTable(this.schemaTables,name,this.logger)}getCol(table,col4){return table[col4]}async listFlows(entityName){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return[];return(await(entityName?this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"entityName"),entityName)):this.db.select().from(flowsTable))).map((r)=>fromCamel2(r))}async getFlow(flowId){let flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),notifRulesTable=this.getTable("verificationNotificationRules"),notifRecipientsTable=this.getTable("verificationNotificationRecipients"),notifChannelsTable=this.getTable("verificationNotificationChannels");if(!flowsTable)return null;let flowRow=(await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),flowId)).limit(1))[0];if(!flowRow)return null;let flow=fromCamel2(flowRow),steps=(stepsTable?await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),edges=(edgesTable?await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),verifierConfigs=(verifierConfigsTable?await this.db.select().from(verifierConfigsTable).where(eq11(this.getCol(verifierConfigsTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),notifRules=(notifRulesTable?await this.db.select().from(notifRulesTable).where(eq11(this.getCol(notifRulesTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),ruleIds=notifRules.map((r)=>r.id),notifRecipients=(notifRecipientsTable&&ruleIds.length>0?await this.db.select().from(notifRecipientsTable).where(inArray2(this.getCol(notifRecipientsTable,"ruleId"),ruleIds)):[]).map((r)=>fromCamel2(r)),notifChannels=(notifChannelsTable&&ruleIds.length>0?await this.db.select().from(notifChannelsTable).where(inArray2(this.getCol(notifChannelsTable,"ruleId"),ruleIds)):[]).map((r)=>fromCamel2(r));return{flow,graph:{steps,edges,verifier_configs:verifierConfigs,notification_rules:notifRules,notification_recipients:notifRecipients,notification_channels:notifChannels}}}async saveFlow(params){let flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),notifRulesTable=this.getTable("verificationNotificationRules"),notifRecipientsTable=this.getTable("verificationNotificationRecipients"),notifChannelsTable=this.getTable("verificationNotificationChannels");if(!flowsTable||!stepsTable||!edgesTable)throw Error("Verification tables not configured");let existingFlows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),params.flow_id)).limit(1),flowId=params.flow_id;if(existingFlows.length>0)await this.db.update(flowsTable).set(toCamel2({entity_name:params.entity_name,name:params.name,description:params.description||null,trigger_on:params.trigger_on,trigger_fields:params.trigger_fields||null,is_draft:params.is_draft,viewport:params.viewport||null})).where(eq11(this.getCol(flowsTable,"id"),flowId));else{let[newFlow]=await this.db.insert(flowsTable).values(toCamel2({id:flowId,entity_name:params.entity_name,name:params.name,description:params.description||null,trigger_on:params.trigger_on,trigger_fields:params.trigger_fields||null,is_draft:params.is_draft,viewport:params.viewport||null})).returning();flowId=newFlow.id}if(await this.db.delete(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),flowId)),edgesTable)await this.db.delete(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),flowId));if(verifierConfigsTable)await this.db.delete(verifierConfigsTable).where(eq11(this.getCol(verifierConfigsTable,"flowId"),flowId));if(notifRulesTable){let oldRuleIds=(await this.db.select().from(notifRulesTable).where(eq11(this.getCol(notifRulesTable,"flowId"),flowId))).map((r)=>r.id);if(oldRuleIds.length>0){if(notifRecipientsTable)for(let rid of oldRuleIds)await this.db.delete(notifRecipientsTable).where(eq11(this.getCol(notifRecipientsTable,"ruleId"),rid));if(notifChannelsTable)for(let rid of oldRuleIds)await this.db.delete(notifChannelsTable).where(eq11(this.getCol(notifChannelsTable,"ruleId"),rid))}await this.db.delete(notifRulesTable).where(eq11(this.getCol(notifRulesTable,"flowId"),flowId))}let{graph}=params;if(graph.steps.length>0)await this.db.insert(stepsTable).values(graph.steps.map((s)=>toCamel2({flow_id:flowId,entity_name:params.entity_name,node_id:s.node_id,node_type:s.node_type,step_order:s.step_order,name:s.name||null,description:s.description||null,position_x:s.position_x,position_y:s.position_y,width:s.width||null,height:s.height||null,style:s.style||null,data:s.data||null})));if(graph.edges.length>0&&edgesTable)await this.db.insert(edgesTable).values(graph.edges.map((e)=>toCamel2({flow_id:flowId,edge_id:e.edge_id,source_node_id:e.source_node_id,target_node_id:e.target_node_id,source_handle:e.source_handle||null,target_handle:e.target_handle||null,edge_type:e.edge_type,label:e.label||null,condition:e.condition||null,style:e.style||null,animated:e.animated})));if(graph.verifier_configs.length>0&&verifierConfigsTable)await this.db.insert(verifierConfigsTable).values(graph.verifier_configs.map((vc)=>toCamel2({flow_id:flowId,node_id:vc.node_id,verifier_type:vc.verifier_type,verifier_user_id:vc.verifier_user_id||null,verifier_role:vc.verifier_role||null,require_signature:vc.require_signature,all_must_approve:vc.all_must_approve})));if(this.logger.info(`[Verification] Save: ${graph.notification_rules.length} rules, ${graph.notification_recipients.length} recipients, ${graph.notification_channels.length} channels`),graph.notification_rules.length>0&&notifRulesTable)for(let rule of graph.notification_rules){this.logger.info(`[Verification] Saving notification rule: node_id=${rule.node_id}, trigger=${rule.trigger}, title_template=${JSON.stringify(rule.title_template)}, body_template=${JSON.stringify(rule.body_template)}`);let[insertedRule]=await this.db.insert(notifRulesTable).values(toCamel2({flow_id:flowId,node_id:rule.node_id,trigger:rule.trigger,title_template:rule.title_template||null,body_template:rule.body_template||null,starts_at:rule.starts_at||null,expires_at:rule.expires_at||null})).returning(),ruleId=insertedRule.id,ruleRecipients=graph.notification_recipients.filter((r)=>r.rule_id===rule.node_id);if(ruleRecipients.length>0&&notifRecipientsTable)await this.db.insert(notifRecipientsTable).values(ruleRecipients.map((r)=>toCamel2({rule_id:ruleId,recipient_type:r.recipient_type,recipient_user_id:r.recipient_user_id||null,recipient_role:r.recipient_role||null})));let ruleChannels=graph.notification_channels.filter((c)=>c.rule_id===rule.node_id);if(ruleChannels.length>0&&notifChannelsTable)await this.db.insert(notifChannelsTable).values(ruleChannels.map((c)=>toCamel2({rule_id:ruleId,channel:c.channel})))}return this.logger.info(`[Verification] Flow saved: ${flowId} for ${params.entity_name}`),{success:!0,flow_id:flowId}}async publishFlow(flowId){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return{success:!1,message:"Flow table not configured"};return await this.db.update(flowsTable).set(toCamel2({is_draft:!1,published_at:new Date})).where(eq11(this.getCol(flowsTable,"id"),flowId)),this.logger.info(`[Verification] Flow published: ${flowId}`),{success:!0,message:"Flow published"}}async deleteFlow(flowId){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return{success:!1,message:"Flow table not configured"};return await this.db.delete(flowsTable).where(eq11(this.getCol(flowsTable,"id"),flowId)),this.logger.info(`[Verification] Flow deleted: ${flowId}`),{success:!0,message:"Flow deleted"}}async startFlow(params){let flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),instancesTable=this.getTable("verificationInstances"),requirementsTable=this.getTable("verificationRequirements"),userRolesTable=this.getTable("userRoles");if(!flowsTable||!stepsTable||!edgesTable||!instancesTable||!requirementsTable)return{success:!1,message:"Verification tables not configured"};let flow=(await this.db.select().from(flowsTable).where(and5(eq11(this.getCol(flowsTable,"id"),params.flow_id),eq11(this.getCol(flowsTable,"isDraft"),!1))).limit(1))[0];if(!flow)return{success:!1,message:"Published flow not found"};if((await this.db.select().from(instancesTable).where(and5(eq11(this.getCol(instancesTable,"entityName"),params.entity_name),eq11(this.getCol(instancesTable,"entityId"),params.entity_id),eq11(this.getCol(instancesTable,"status"),"active"))).limit(1)).length>0)return{success:!1,message:"An active verification instance already exists for this entity"};let steps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),params.flow_id)),edges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),params.flow_id)),stepNodes=steps.filter((s)=>s.nodeType==="step");if(stepNodes.sort((a,b)=>a.stepOrder-b.stepOrder),stepNodes.length===0)return{success:!1,message:"Flow has no step nodes"};let[instance]=await this.db.insert(instancesTable).values(toCamel2({flow_id:params.flow_id,entity_name:params.entity_name,entity_id:params.entity_id,started_by:params.started_by||null,status:"active",current_step_order:1,started_at:new Date})).returning(),instanceId=instance.id;if(await this.materializeRequirementsForStep(instanceId,params.flow_id,params.entity_name,params.entity_id,1,steps,edges,verifierConfigsTable,requirementsTable,userRolesTable),this.onNotificationTrigger){let firstStep=stepNodes[0],firstStepNodeId=firstStep?.nodeId,connectedNotifIds=firstStepNodeId?this.getConnectedNotificationNodeIds(firstStepNodeId,steps,edges):[],ctx={flow_name:flow.name,step_name:firstStep?.name||"Step 1",step_order:1,total_steps:stepNodes.length};if(connectedNotifIds.length>0)for(let notifNodeId of connectedNotifIds)await this.onNotificationTrigger({trigger:"on_flow_started",flow_id:params.flow_id,entity_name:params.entity_name,entity_id:params.entity_id,node_id:notifNodeId,context:ctx});else await this.onNotificationTrigger({trigger:"on_flow_started",flow_id:params.flow_id,entity_name:params.entity_name,entity_id:params.entity_id,context:ctx})}return this.logger.info(`[Verification] Flow started: instance ${instanceId} for ${params.entity_name}:${params.entity_id}`),{success:!0,instance_id:instanceId,message:"Flow started"}}async materializeRequirementsForStep(instanceId,flowId,entityName,entityId,stepOrder,steps,edges,verifierConfigsTable,requirementsTable,userRolesTable){if(!requirementsTable)return;let stepNode=steps.find((s)=>s.nodeType==="step"&&s.stepOrder===stepOrder);if(!stepNode)return;let stepNodeId=stepNode.nodeId,verifierNodeIds=edges.filter((e)=>e.targetNodeId===stepNodeId).map((e)=>e.sourceNodeId),verifierNodes=steps.filter((s)=>s.nodeType==="verifier"&&verifierNodeIds.includes(s.nodeId));if(verifierNodes.length===0)return;let verifierConfigs=[];if(verifierConfigsTable)verifierConfigs=await this.db.select().from(verifierConfigsTable).where(eq11(this.getCol(verifierConfigsTable,"flowId"),flowId));for(let verifierNode of verifierNodes){let nodeId=verifierNode.nodeId,config=verifierConfigs.find((vc)=>vc.nodeId===nodeId);if(!config)continue;let{verifierType,allMustApprove}=config;if(verifierType==="role"&&allMustApprove&&userRolesTable){let rolesTable=this.getTable("roles");if(rolesTable){let rolesCols=rolesTable,userRolesCols=userRolesTable,role=(await this.db.select().from(rolesTable).where(eq11(rolesCols.name,config.verifierRole)).limit(1))[0];if(role){let usersWithRole=await this.db.select({user_id:userRolesCols.userId}).from(userRolesTable).where(eq11(userRolesCols.roleId,role.id));for(let userRole of usersWithRole)await this.db.insert(requirementsTable).values(toCamel2({instance_id:instanceId,step_node_id:stepNodeId,verifier_node_id:nodeId,entity_name:entityName,entity_id:entityId,verifier_type:"user",verifier_user_id:userRole.user_id,verifier_role:config.verifierRole||null,require_signature:config.requireSignature,all_must_approve:!0,step_order:stepOrder,status:"pending"}))}}}else await this.db.insert(requirementsTable).values(toCamel2({instance_id:instanceId,step_node_id:stepNodeId,verifier_node_id:nodeId,entity_name:entityName,entity_id:entityId,verifier_type:verifierType,verifier_user_id:config.verifierUserId||null,verifier_role:config.verifierRole||null,require_signature:config.requireSignature,all_must_approve:allMustApprove,step_order:stepOrder,status:"pending"}))}if(this.onNotificationTrigger){let connectedNotifIds=this.getConnectedNotificationNodeIds(stepNodeId,steps,edges);if(this.logger.info(`[Verification] on_step_reached: stepNodeId=${stepNodeId}, connectedNotifIds=[${connectedNotifIds.join(", ")}]`),connectedNotifIds.length>0)for(let notifNodeId of connectedNotifIds)this.logger.info(`[Verification] Triggering on_step_reached for notifNodeId=${notifNodeId}`),await this.onNotificationTrigger({trigger:"on_step_reached",flow_id:flowId,entity_name:entityName,entity_id:entityId,node_id:notifNodeId,context:{step_name:stepNode.name||`Step ${stepOrder}`,step_order:stepOrder}});else await this.onNotificationTrigger({trigger:"on_step_reached",flow_id:flowId,entity_name:entityName,entity_id:entityId,context:{step_name:stepNode.name||`Step ${stepOrder}`,step_order:stepOrder}})}}async getStatus(entityName,entityId){let instancesTable=this.getTable("verificationInstances"),flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),verificationsTable=this.getTable("verifications"),requirementsTable=this.getTable("verificationRequirements"),emptyStatus={entity_name:entityName,entity_id:entityId,instance:null,flow:null,current_step:0,total_steps:0,is_completed:!1,is_rejected:!1,verifications:[],pending_requirements:[]};if(!instancesTable||!flowsTable||!verificationsTable||!requirementsTable)return this.logger.error("[Verification] Required tables not found"),emptyStatus;let instanceRow=(await this.db.select().from(instancesTable).where(and5(eq11(this.getCol(instancesTable,"entityName"),entityName),eq11(this.getCol(instancesTable,"entityId"),entityId))).orderBy(desc2(this.getCol(instancesTable,"createdAt"))).limit(1))[0];if(!instanceRow)return emptyStatus;let instance=fromCamel2(instanceRow),flows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),instance.flow_id)).limit(1),flow=flows[0]?fromCamel2(flows[0]):void 0,totalSteps=(stepsTable?await this.db.select().from(stepsTable).where(and5(eq11(this.getCol(stepsTable,"flowId"),instance.flow_id),eq11(this.getCol(stepsTable,"nodeType"),"step"))):[]).length,verifications=(await this.db.select().from(verificationsTable).where(eq11(this.getCol(verificationsTable,"instanceId"),instance.id)).orderBy(desc2(this.getCol(verificationsTable,"createdAt")))).map((r)=>fromCamel2(r)),pendingRequirements=(await this.db.select().from(requirementsTable).where(and5(eq11(this.getCol(requirementsTable,"instanceId"),instance.id),eq11(this.getCol(requirementsTable,"status"),"pending")))).map((r)=>fromCamel2(r));return{entity_name:entityName,entity_id:entityId,instance,flow:flow||null,current_step:instance.current_step_order,total_steps:totalSteps,is_completed:instance.status==="completed",is_rejected:instance.status==="rejected",verifications,pending_requirements:pendingRequirements}}async decide(params){let{entity_name,entity_id,user_id,decision,reason,signature_id,diff}=params,verificationsTable=this.getTable("verifications"),requirementsTable=this.getTable("verificationRequirements"),instancesTable=this.getTable("verificationInstances"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),userRolesTable=this.getTable("userRoles"),rolesTable=this.getTable("roles");if(!verificationsTable||!requirementsTable||!instancesTable)return{success:!1,message:"Verification tables not configured"};let status=await this.getStatus(entity_name,entity_id);if(!status.instance||status.instance.status!=="active")return{success:!1,message:"No active verification instance"};let currentPending=status.pending_requirements.filter((r)=>r.step_order===status.current_step);if(currentPending.length===0)return{success:!1,message:"No pending requirements for current step"};let matchedReq=null;for(let req of currentPending){if(req.verifier_type==="user"&&req.verifier_user_id===user_id){matchedReq=req;break}if(req.verifier_type==="role"&&req.verifier_role&&userRolesTable&&rolesTable){let userRolesCols=userRolesTable,rolesCols=rolesTable;if((await this.db.select({role_name:rolesCols.name}).from(userRolesTable).innerJoin(rolesTable,eq11(userRolesCols.roleId,rolesCols.id)).where(eq11(userRolesCols.userId,user_id))).some((ur)=>ur.role_name===req.verifier_role)){matchedReq=req;break}}}if(!matchedReq)return{success:!1,message:"User is not authorized to verify at this step"};if(matchedReq.require_signature&&!signature_id)return{success:!1,message:"Signature is required for this verification step"};let[newVerification]=await this.db.insert(verificationsTable).values(toCamel2({instance_id:status.instance.id,requirement_id:matchedReq.id,verifier_id:user_id,signature_id:signature_id||null,entity_name,entity_id,step_order:status.current_step,decision,reason:reason||null,diff:diff||null})).returning();if(await this.db.update(requirementsTable).set({status:decision}).where(eq11(this.getCol(requirementsTable,"id"),matchedReq.id)),this.onNotificationTrigger&&status.instance){let stepName=`Step ${status.current_step}`,allSteps=[],allEdges=[];if(stepsTable){allSteps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),status.instance.flow_id));let stepRow=allSteps.find((s)=>s.nodeId===matchedReq.step_node_id);if(stepRow?.name)stepName=stepRow.name}if(edgesTable)allEdges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),status.instance.flow_id));let triggerName=decision==="approved"?"on_approved":"on_rejected",ctx={flow_name:status.flow?.name||"",step_name:stepName,step_order:status.current_step,total_steps:status.total_steps,decision},connectedNotifIds=this.getConnectedNotificationNodeIds(matchedReq.step_node_id,allSteps,allEdges);if(connectedNotifIds.length>0)for(let notifNodeId of connectedNotifIds)await this.onNotificationTrigger({trigger:triggerName,flow_id:status.instance.flow_id,entity_name,entity_id,node_id:notifNodeId,verifier_id:user_id,decision,context:ctx});else await this.onNotificationTrigger({trigger:triggerName,flow_id:status.instance.flow_id,entity_name,entity_id,verifier_id:user_id,decision,context:ctx})}if(decision==="rejected"){await this.db.update(instancesTable).set(toCamel2({status:"rejected",completed_at:new Date})).where(eq11(this.getCol(instancesTable,"id"),status.instance.id));let newInstanceId;if(this.config.autoResetOnRejection){this.logger.info(`[Verification] Flow rejected for ${entity_name}:${entity_id}, auto-restarting from step 1`);let restartResult=await this.startFlow({flow_id:status.instance.flow_id,entity_name,entity_id,started_by:status.instance.started_by});if(restartResult.success)newInstanceId=restartResult.instance_id}return{success:!0,message:this.config.autoResetOnRejection?"Verification rejected \u2014 flow restarted from step 1":"Verification rejected",verification:newVerification,flow_completed:!1,new_instance_id:newInstanceId}}let matchedReqId=matchedReq.id,remainingPending=currentPending.filter((r)=>r.id!==matchedReqId);if(remainingPending.length>0)return{success:!0,message:`Step ${status.current_step} partially approved, ${remainingPending.length} verifier(s) remaining`,verification:newVerification,flow_completed:!1};let nextStep=status.current_step+1;if(nextStep>status.total_steps){if(await this.db.update(instancesTable).set(toCamel2({status:"completed",completed_at:new Date})).where(eq11(this.getCol(instancesTable,"id"),status.instance.id)),this.onNotificationTrigger){let completedSteps=[],completedEdges=[];if(stepsTable)completedSteps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),status.instance.flow_id));if(edgesTable)completedEdges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),status.instance.flow_id));let lastStepNodeId=matchedReq.step_node_id,completedNotifIds=this.getConnectedNotificationNodeIds(lastStepNodeId,completedSteps,completedEdges),completedCtx={flow_name:status.flow?.name||"",step_order:status.current_step,total_steps:status.total_steps};if(completedNotifIds.length>0)for(let notifNodeId of completedNotifIds)await this.onNotificationTrigger({trigger:"on_flow_completed",flow_id:status.instance.flow_id,entity_name,entity_id,node_id:notifNodeId,context:completedCtx});else await this.onNotificationTrigger({trigger:"on_flow_completed",flow_id:status.instance.flow_id,entity_name,entity_id,context:completedCtx})}return{success:!0,message:"Verification flow completed",verification:newVerification,flow_completed:!0}}if(await this.db.update(instancesTable).set(toCamel2({current_step_order:nextStep})).where(eq11(this.getCol(instancesTable,"id"),status.instance.id)),stepsTable&&edgesTable){let steps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),status.instance.flow_id)),edges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),status.instance.flow_id));await this.materializeRequirementsForStep(status.instance.id,status.instance.flow_id,entity_name,entity_id,nextStep,steps,edges,verifierConfigsTable,requirementsTable,userRolesTable)}return{success:!0,message:`Step ${status.current_step} approved, moving to step ${nextStep}`,verification:newVerification,flow_completed:!1,next_step:nextStep}}async startFlowForEntity(params){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return{success:!1,message:"Flow table not configured"};let flow=(await this.db.select().from(flowsTable).where(and5(eq11(this.getCol(flowsTable,"entityName"),params.entity_name),eq11(this.getCol(flowsTable,"isDraft"),!1))).limit(1))[0];if(!flow)return{success:!1,message:`No published flow found for entity '${params.entity_name}'`};return this.startFlow({flow_id:flow.id,entity_name:params.entity_name,entity_id:params.entity_id,started_by:params.started_by})}async listEntityStatuses(params){let instancesTable=this.getTable("verificationInstances"),flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),emptyResult={items:[],total:0,page:1,limit:20};if(!instancesTable||!flowsTable)return emptyResult;let page=params.page||1,limit=params.limit||20,offset=(page-1)*limit,conditions=[eq11(this.getCol(instancesTable,"entityName"),params.entity_name)];if(params.status)conditions.push(eq11(this.getCol(instancesTable,"status"),params.status));let whereClause=conditions.length===1?conditions[0]:and5(...conditions),allInstances=(await this.db.select().from(instancesTable).where(whereClause).orderBy(desc2(this.getCol(instancesTable,"createdAt")))).map((r)=>fromCamel2(r)),total=allInstances.length,paged=allInstances.slice(offset,offset+limit),items=[];for(let inst of paged){let flowId=inst.flow_id,flows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),flowId)).limit(1),flow=flows[0]?fromCamel2(flows[0]):void 0,totalSteps=0;if(stepsTable)totalSteps=(await this.db.select().from(stepsTable).where(and5(eq11(this.getCol(stepsTable,"flowId"),flowId),eq11(this.getCol(stepsTable,"nodeType"),"step")))).length;items.push({instance_id:inst.id,entity_name:inst.entity_name,entity_id:inst.entity_id,flow_id:flowId,flow_name:flow?.name||"Unknown",status:inst.status,current_step_order:inst.current_step_order,total_steps:totalSteps,started_by:inst.started_by,started_at:inst.started_at,completed_at:inst.completed_at})}return{items,total,page,limit}}async getPending(userId){let requirementsTable=this.getTable("verificationRequirements"),instancesTable=this.getTable("verificationInstances"),flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),userRolesTable=this.getTable("userRoles"),rolesTable=this.getTable("roles");if(this.logger.info(`[Verification.getPending] userId=${userId}, tables: req=${!!requirementsTable} inst=${!!instancesTable} flow=${!!flowsTable} steps=${!!stepsTable} roles=${!!rolesTable} userRoles=${!!userRolesTable}`),!requirementsTable||!instancesTable||!flowsTable)return this.logger.warn("[Verification.getPending] Missing required tables, returning empty"),[];let userRolesCols=userRolesTable,rolesCols=rolesTable,userRoleNames=(userRolesTable&&rolesTable?await this.db.select({role_name:rolesCols.name}).from(userRolesTable).innerJoin(rolesTable,eq11(userRolesCols.roleId,rolesCols.id)).where(eq11(userRolesCols.userId,userId)):[]).map((ur)=>ur.role_name),pendingReqs=(await this.db.select().from(requirementsTable).where(eq11(this.getCol(requirementsTable,"status"),"pending"))).map((r)=>fromCamel2(r));this.logger.info(`[Verification.getPending] Found ${pendingReqs.length} pending requirements, userRoles=${JSON.stringify(userRoleNames)}`);for(let req of pendingReqs)this.logger.info(`[Verification.getPending] Req: verifier_type=${req.verifier_type} verifier_user_id=${req.verifier_user_id} verifier_role=${req.verifier_role} step_order=${req.step_order} entity=${req.entity_name}/${req.entity_id}`);let pendingItems=[];for(let req of pendingReqs){if(!(req.verifier_type==="user"&&req.verifier_user_id===userId||req.verifier_type==="role"&&userRoleNames.includes(req.verifier_role))){this.logger.info(`[Verification.getPending] Skipping req: canVerify=false (type=${req.verifier_type}, reqUserId=${req.verifier_user_id}, loggedInUserId=${userId})`);continue}let instances=await this.db.select().from(instancesTable).where(and5(eq11(this.getCol(instancesTable,"id"),req.instance_id),eq11(this.getCol(instancesTable,"status"),"active"))).limit(1),instance=instances[0]?fromCamel2(instances[0]):void 0;if(!instance)continue;if(instance.current_step_order!==req.step_order)continue;let flows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),instance.flow_id)).limit(1),flow=flows[0]?fromCamel2(flows[0]):void 0;if(!flow)continue;let stepName;if(stepsTable&&req.step_node_id){let stepRow=(await this.db.select().from(stepsTable).where(and5(eq11(this.getCol(stepsTable,"flowId"),instance.flow_id),eq11(this.getCol(stepsTable,"nodeId"),req.step_node_id))).limit(1))[0];if(stepRow?.name)stepName=stepRow.name}pendingItems.push({instance_id:instance.id,entity_name:req.entity_name,entity_id:req.entity_id,flow_name:flow.name,step_order:req.step_order,step_name:stepName,require_signature:req.require_signature,created_at:req.created_at})}return pendingItems}}var init_Verification=__esm(()=>{init_types5()});import*as crypto5 from"crypto";var IYZICO_PATHS,generateAuthString=(apiKey,secretKey,path2,payload,randomKey)=>{let compound=payload?randomKey+path2+payload:randomKey+path2,encryptedData=crypto5.createHmac("sha256",secretKey).update(compound).digest("hex"),authorizationString=`apiKey:${apiKey}&randomKey:${randomKey}&signature:${encryptedData}`;return`IYZWSv2 ${Buffer.from(authorizationString).toString("base64")}`},buildRequest=(config,path2,payload)=>{let body=JSON.stringify(payload),randomKey=Date.now().toString(32),headers=new Headers;return headers.set("Content-Type","application/json"),headers.set("x-iyzi-rnd",randomKey),headers.set("Authorization",generateAuthString(config.apiKey,config.secretKey,path2,body,randomKey)),{url:new URL(`${config.apiUrl}${path2}`).toString(),headers,body}},iyzicoFetch=async(config,path2,payload)=>{let{url,headers,body}=buildRequest(config,path2,payload);try{let json=await(await fetch(url,{method:"POST",headers,body})).json(),isSuccess=json.status==="success";return{success:isSuccess,data:isSuccess?json:null,errorCode:json.errorCode??void 0,errorMessage:json.errorMessage??void 0,rawResponse:json}}catch(error){let message=error instanceof Error?error.message:"Unknown fetch error";return{success:!1,data:null,errorCode:"NETWORK_ERROR",errorMessage:message,rawResponse:{error:message}}}},createIyzicoProvider=(config)=>{let generateConversationId=()=>`nk-${Date.now().toString(16)}`;return{get name(){return"iyzico"},async initialize3DS(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId,price:request.price,paidPrice:request.paidPrice,currency:request.currency,installment:request.installment??1,paymentChannel:request.paymentChannel??"WEB",basketId:request.basketId??Date.now().toString(16),paymentGroup:request.paymentGroup??"PRODUCT",paymentCard:request.paymentCard,buyer:request.buyer,shippingAddress:request.shippingAddress,billingAddress:request.billingAddress,basketItems:request.basketItems,callbackUrl:request.callbackUrl},result=await iyzicoFetch(config,IYZICO_PATHS.INITIALIZE_3DS,payload);return{success:result.success,threeDSHtmlContent:result.data?.threeDSHtmlContent,paymentId:result.data?.paymentId,signature:result.data?.signature,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async complete3DS(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId,paymentId:request.paymentId},result=await iyzicoFetch(config,IYZICO_PATHS.COMPLETE_3DS,payload);return{success:result.success,paymentId:result.data?.paymentId,price:result.data?.price,paidPrice:result.data?.paidPrice,currency:result.data?.currency,installment:result.data?.installment,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,cardFamily:result.data?.cardFamily,binNumber:result.data?.binNumber,lastFourDigits:result.data?.lastFourDigits,basketId:result.data?.basketId,authCode:result.data?.authCode,signature:result.data?.signature,fraudStatus:result.data?.fraudStatus,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async getPaymentDetail(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),paymentId:request.paymentId,paymentConversationId:request.paymentConversationId},result=await iyzicoFetch(config,IYZICO_PATHS.PAYMENT_DETAIL,payload);return{success:result.success,paymentId:result.data?.paymentId,price:result.data?.price,paidPrice:result.data?.paidPrice,currency:result.data?.currency,basketId:result.data?.basketId,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,lastFourDigits:result.data?.lastFourDigits,binNumber:result.data?.binNumber,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async queryBin(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),binNumber:request.binNumber.slice(0,6)};if(request.price!==void 0)payload.price=request.price;let result=await iyzicoFetch(config,IYZICO_PATHS.BIN_CHECK,payload);return{success:result.success,binNumber:result.data?.binNumber,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,cardFamily:result.data?.cardFamily,bankName:result.data?.bankName,bankCode:result.data?.bankCode,commercial:result.data?.commercial,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async saveCard(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),card:request.card,email:request.email,externalId:request.externalId},result=await iyzicoFetch(config,IYZICO_PATHS.CARD_SAVE,payload);return{success:result.success,cardUserKey:result.data?.cardUserKey,cardToken:result.data?.cardToken,cardAlias:result.data?.cardAlias,binNumber:result.data?.binNumber,lastFourDigits:result.data?.lastFourDigits,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,cardFamily:result.data?.cardFamily,cardBankName:result.data?.cardBankName,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async listCards(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),cardUserKey:request.cardUserKey},result=await iyzicoFetch(config,IYZICO_PATHS.CARD_LIST,payload),cards=(result.data?.cardDetails??[]).map((cd)=>({cardToken:cd.cardToken,cardAlias:cd.cardAlias,binNumber:cd.binNumber,lastFourDigits:cd.lastFourDigits,cardType:cd.cardType,cardAssociation:cd.cardAssociation,cardFamily:cd.cardFamily,cardBankName:cd.cardBankName,cardBankCode:cd.cardBankCode}));return{success:result.success,cardUserKey:result.data?.cardUserKey,cards,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async deleteCard(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),cardUserKey:request.cardUserKey,cardToken:request.cardToken},result=await iyzicoFetch(config,IYZICO_PATHS.CARD_DELETE,payload);return{success:result.success,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async refund(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),paymentTransactionId:request.paymentTransactionId,price:request.price,currency:request.currency??"TRY"};if(request.ip)payload.ip=request.ip;let result=await iyzicoFetch(config,IYZICO_PATHS.REFUND,payload);return{success:result.success,paymentId:result.data?.paymentId,price:result.data?.price,currency:result.data?.currency,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},parseCallback(formData){return{success:formData.mdStatus==="1",paymentId:formData.paymentId??"",conversationId:formData.conversationId??"",mdStatus:formData.mdStatus??"",rawData:formData}},async registerSubMerchant(request){let typeMap={personal:"PERSONAL",private_company:"PRIVATE_COMPANY",limited_or_joint_stock_company:"LIMITED_OR_JOINT_STOCK_COMPANY"},payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),subMerchantExternalId:request.subMerchantExternalId,subMerchantType:typeMap[request.subMerchantType]??"PERSONAL",name:request.name,email:request.email,gsmNumber:request.gsmNumber,address:request.address,iban:request.iban,contactName:request.contactName,contactSurname:request.contactSurname,identityNumber:request.identityNumber,currency:request.currency??"TRY"};if(request.subMerchantType==="private_company")payload.taxOffice=request.taxOffice,payload.legalCompanyTitle=request.legalCompanyTitle;if(request.subMerchantType==="limited_or_joint_stock_company")payload.taxOffice=request.taxOffice,payload.taxNumber=request.taxNumber,payload.legalCompanyTitle=request.legalCompanyTitle;let result=await iyzicoFetch(config,IYZICO_PATHS.SUB_MERCHANT_CREATE,payload);return{success:result.success,subMerchantKey:result.data?.subMerchantKey,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async updateSubMerchant(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),subMerchantKey:request.subMerchantKey};if(request.name)payload.name=request.name;if(request.email)payload.email=request.email;if(request.gsmNumber)payload.gsmNumber=request.gsmNumber;if(request.address)payload.address=request.address;if(request.iban)payload.iban=request.iban;if(request.contactName)payload.contactName=request.contactName;if(request.contactSurname)payload.contactSurname=request.contactSurname;if(request.identityNumber)payload.identityNumber=request.identityNumber;if(request.taxOffice)payload.taxOffice=request.taxOffice;if(request.taxNumber)payload.taxNumber=request.taxNumber;if(request.legalCompanyTitle)payload.legalCompanyTitle=request.legalCompanyTitle;if(request.currency)payload.currency=request.currency;let result=await iyzicoFetch(config,IYZICO_PATHS.SUB_MERCHANT_UPDATE,payload);return{success:result.success,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async getSubMerchant(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),subMerchantExternalId:request.subMerchantExternalId},result=await iyzicoFetch(config,IYZICO_PATHS.SUB_MERCHANT_DETAIL,payload);return{success:result.success,subMerchantKey:result.data?.subMerchantKey,name:result.data?.name,email:result.data?.email,gsmNumber:result.data?.gsmNumber,address:result.data?.address,iban:result.data?.iban,subMerchantType:result.data?.subMerchantType,currency:result.data?.currency,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async approveSplit(request){let payload={locale:request.locale??"tr",paymentTransactionId:request.paymentTransactionId},result=await iyzicoFetch(config,IYZICO_PATHS.APPROVAL,payload);return{success:result.success,paymentTransactionId:result.data?.paymentTransactionId,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async disapproveSplit(request){let payload={locale:request.locale??"tr",paymentTransactionId:request.paymentTransactionId},result=await iyzicoFetch(config,IYZICO_PATHS.DISAPPROVAL,payload);return{success:result.success,paymentTransactionId:result.data?.paymentTransactionId,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async createProduct(request){let localId=`iyzico-prod-${Date.now().toString(36)}`;return{success:!0,providerProductId:localId,name:request.name,rawResponse:{local:!0,id:localId}}},async updateProduct(request){return{success:!0,providerProductId:request.providerProductId,rawResponse:{local:!0,updated:request.providerProductId}}},async getProduct(request){return{success:!0,providerProductId:request.providerProductId,rawResponse:{local:!0,message:"Product data is stored locally for iyzico"}}},async listProducts(_request){return{success:!0,products:[],hasMore:!1,rawResponse:{local:!0,message:"Products are stored locally for iyzico"}}},async archiveProduct(request){return{success:!0,rawResponse:{local:!0,archived:request.providerProductId}}},async createPrice(request){let localId=`iyzico-price-${Date.now().toString(36)}`;return{success:!0,providerPriceId:localId,rawResponse:{local:!0,id:localId,product:request.providerProductId}}},async updatePrice(request){return{success:!0,providerPriceId:request.providerPriceId,rawResponse:{local:!0,updated:request.providerPriceId}}},async getPrice(request){return{success:!0,providerPriceId:request.providerPriceId,rawResponse:{local:!0,message:"Price data is stored locally for iyzico"}}},async listPrices(_request){return{success:!0,prices:[],hasMore:!1,rawResponse:{local:!0,message:"Prices are stored locally for iyzico"}}},async archivePrice(request){return{success:!0,rawResponse:{local:!0,archived:request.providerPriceId}}},async createCustomer(request){return{success:!0,providerCustomerId:`local_cus_${Date.now()}`,email:request.email,rawResponse:{local:!0,message:"Customer stored locally for iyzico"}}},async updateCustomer(request){return{success:!0,providerCustomerId:request.providerCustomerId,rawResponse:{local:!0,message:"Customer updated locally for iyzico"}}},async getCustomer(request){return{success:!0,providerCustomerId:request.providerCustomerId,rawResponse:{local:!0,message:"Customer data is stored locally for iyzico"}}},async listCustomers(_request){return{success:!0,customers:[],hasMore:!1,rawResponse:{local:!0,message:"Customers are stored locally for iyzico"}}},async deleteCustomer(_request){return{success:!0,rawResponse:{local:!0,message:"Customer deleted locally for iyzico"}}},async createSubscription(_request){return{success:!0,providerSubscriptionId:`local_sub_${Date.now()}`,status:"active",rawResponse:{local:!0,message:"Subscription stored locally for iyzico"}}},async updateSubscription(request){return{success:!0,providerSubscriptionId:request.providerSubscriptionId,status:"active",rawResponse:{local:!0,message:"Subscription updated locally for iyzico"}}},async cancelSubscription(request){return{success:!0,providerSubscriptionId:request.providerSubscriptionId,status:"canceled",rawResponse:{local:!0,message:"Subscription canceled locally for iyzico"}}},async getSubscription(request){return{success:!0,providerSubscriptionId:request.providerSubscriptionId,rawResponse:{local:!0,message:"Subscription data is stored locally for iyzico"}}},async listSubscriptions(_request){return{success:!0,subscriptions:[],hasMore:!1,rawResponse:{local:!0,message:"Subscriptions are stored locally for iyzico"}}},async reportUsage(request){return{success:!0,usageRecordId:`local_ur_${Date.now()}`,quantity:request.quantity,timestamp:request.timestamp??Math.floor(Date.now()/1000),rawResponse:{local:!0,message:"Usage recorded locally for iyzico"}}},async listUsageRecordSummaries(_request){return{success:!0,summaries:[],hasMore:!1,rawResponse:{local:!0,message:"Usage summaries are stored locally for iyzico"}}},async createInvoice(_request){return{success:!0,providerInvoiceId:`local_inv_${Date.now()}`,status:"draft",rawResponse:{local:!0,message:"Invoice stored locally for iyzico"}}},async finalizeInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,status:"open",rawResponse:{local:!0,message:"Invoice finalized locally for iyzico"}}},async sendInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,rawResponse:{local:!0,message:"Invoice send is a no-op for iyzico"}}},async voidInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,rawResponse:{local:!0,message:"Invoice voided locally for iyzico"}}},async payInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,status:"paid",rawResponse:{local:!0,message:"Invoice payment is a no-op for iyzico"}}},async getInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,rawResponse:{local:!0,message:"Invoice data is stored locally for iyzico"}}},async listInvoices(_request){return{success:!0,invoices:[],hasMore:!1,rawResponse:{local:!0,message:"Invoices are stored locally for iyzico"}}},async getBalance(){return{success:!0,available:[],pending:[],rawResponse:{local:!0,message:"Balance is not tracked by iyzico provider"}}},async createPayout(_request){return{success:!0,providerPayoutId:`local_po_${Date.now()}`,status:"pending",rawResponse:{local:!0,message:"Payout created locally for iyzico"}}},async getPayout(request){return{success:!0,providerPayoutId:request.providerPayoutId,rawResponse:{local:!0,message:"Payout data is stored locally for iyzico"}}},async cancelPayout(request){return{success:!0,providerPayoutId:request.providerPayoutId,status:"canceled",rawResponse:{local:!0,message:"Payout cancelled locally for iyzico"}}},async listPayouts(_request){return{success:!0,payouts:[],hasMore:!1,rawResponse:{local:!0,message:"Payouts are stored locally for iyzico"}}},async createTransfer(_request){return{success:!0,providerTransferId:`local_tr_${Date.now()}`,rawResponse:{local:!0,message:"Transfer created locally for iyzico"}}},async listTransfers(_request){return{success:!0,transfers:[],hasMore:!1,rawResponse:{local:!0,message:"Transfers are stored locally for iyzico"}}}}};var init_IyzicoProvider=__esm(()=>{IYZICO_PATHS={INITIALIZE_3DS:"/payment/3dsecure/initialize",COMPLETE_3DS:"/payment/3dsecure/auth",PAYMENT_AUTH:"/payment/auth",PAYMENT_DETAIL:"/payment/detail",BIN_CHECK:"/payment/bin/check",CARD_SAVE:"/cardstorage/card",CARD_LIST:"/cardstorage/cards",CARD_DELETE:"/cardstorage/card/delete",REFUND:"/payment/refund",SUB_MERCHANT_CREATE:"/onboarding/submerchant",SUB_MERCHANT_UPDATE:"/onboarding/submerchant",SUB_MERCHANT_DETAIL:"/onboarding/submerchant/detail",APPROVAL:"/payment/iyzipos/item/approve",DISAPPROVAL:"/payment/iyzipos/item/disapprove"}});var resolveMarketplaceConfig=(payment)=>{let m=payment?.marketplace;return{enabled:m?.enabled===!0,defaultSettlementDelayDays:m?.defaultSettlementDelayDays??7,newSellerDelayDays:m?.newSellerDelayDays??14,reserveRate:clampRate(m?.reserveRate??0),reserveReleaseDays:m?.reserveReleaseDays??0,minimumPayoutAmount:m?.minimumPayoutAmount??0,defaultCurrency:m?.defaultCurrency??payment?.defaultCurrency??"USD",autoReleaseReserves:m?.autoReleaseReserves===!0}},clampRate=(rate)=>{if(Number.isNaN(rate)||rate<0)return 0;if(rate>1)return 1;return rate},addDays=(base,days)=>new Date(base.getTime()+days*24*60*60*1000),computeSplitBreakdown=(input,config,policy,now=new Date)=>{let providerFee=Math.max(0,Math.round(input.providerFeeAmount??0)),platformFee=Math.max(0,Math.round(input.platformFeeAmount)),afterFees=Math.max(0,input.grossAmount-providerFee-platformFee),reserveRate=input.reserveRate??policy?.reserveRate??config.reserveRate,reserveAmount=Math.min(afterFees,Math.floor(afterFees*clampRate(reserveRate))),netPayable=afterFees-reserveAmount,delayDays=input.settlementDelayDays??(input.isNewSeller?policy?.newSellerDelayDays??config.newSellerDelayDays:policy?.defaultDelayDays??config.defaultSettlementDelayDays);return{grossAmount:input.grossAmount,providerFeeAmount:providerFee,platformFeeAmount:platformFee,reserveAmount,netPayableAmount:netPayable,availableForPayoutAt:addDays(now,Math.max(0,delayDays))}},str2=(v)=>v==null?"":String(v),strOrNull2=(v)=>v==null?null:String(v),num=(v)=>{let n=typeof v==="number"?v:Number(v);return Number.isFinite(n)?n:0},rowToSplit=(row)=>({id:str2(row.id),transactionId:strOrNull2(row.transactionId??row.transaction_id),recipientOwnerType:str2(row.recipientOwnerType??row.recipient_owner_type)||"seller",recipientOwnerId:str2(row.recipientOwnerId??row.recipient_owner_id),provider:str2(row.provider),grossAmount:num(row.grossAmount??row.gross_amount),providerFeeAmount:num(row.providerFeeAmount??row.provider_fee_amount),platformFeeAmount:num(row.platformFeeAmount??row.platform_fee_amount),reserveAmount:num(row.reserveAmount??row.reserve_amount),netPayableAmount:num(row.netPayableAmount??row.net_payable_amount),currency:str2(row.currency),availableForPayoutAt:strOrNull2(row.availableForPayoutAt??row.available_for_payout_at),status:str2(row.status)||"pending",sourceType:strOrNull2(row.sourceType??row.source_type),sourceId:strOrNull2(row.sourceId??row.source_id)}),rowToPayoutRequest=(row)=>({id:str2(row.id),recipientOwnerType:str2(row.recipientOwnerType??row.recipient_owner_type)||"seller",recipientOwnerId:str2(row.recipientOwnerId??row.recipient_owner_id),amount:num(row.amount),currency:str2(row.currency),status:str2(row.status)||"pending",provider:strOrNull2(row.provider),providerPayoutId:strOrNull2(row.providerPayoutId??row.provider_payout_id),providerTransferId:strOrNull2(row.providerTransferId??row.provider_transfer_id),destination:strOrNull2(row.destination),failureReason:strOrNull2(row.failureReason??row.failure_reason)}),rowToSettlementPolicy=(row)=>({id:str2(row.id),ownerType:str2(row.ownerType??row.owner_type),ownerId:str2(row.ownerId??row.owner_id),defaultDelayDays:num(row.defaultDelayDays??row.default_delay_days),newSellerDelayDays:num(row.newSellerDelayDays??row.new_seller_delay_days),reserveRate:num(row.reserveRate??row.reserve_rate),reserveDays:num(row.reserveDays??row.reserve_days),minimumPayoutAmount:num(row.minimumPayoutAmount??row.minimum_payout_amount),currency:strOrNull2(row.currency),earlyPayoutEnabled:Boolean(row.earlyPayoutEnabled??row.early_payout_enabled),status:str2(row.status)||"active"}),rowToDispute=(row)=>({id:str2(row.id),transactionId:strOrNull2(row.transactionId??row.transaction_id),provider:str2(row.provider),providerDisputeId:strOrNull2(row.providerDisputeId??row.provider_dispute_id),ownerType:strOrNull2(row.ownerType??row.owner_type),ownerId:strOrNull2(row.ownerId??row.owner_id),amount:row.amount==null?null:num(row.amount),currency:strOrNull2(row.currency),reason:strOrNull2(row.reason),status:str2(row.status)||"open",resolvedAt:strOrNull2(row.resolvedAt??row.resolved_at)});import{eq as eq12}from"drizzle-orm";class MarketplacePayoutService{getDb;provider;logger;t;marketplace;constructor(cfg,marketplace){this.getDb=cfg.getDb,this.provider=cfg.provider,this.logger=cfg.logger.scoped("payment.payout"),this.t=cfg.tables,this.marketplace=marketplace}table(name){return this.t[name]}async requestPayout(input){let db=this.getDb();if(!db)throw Error("Marketplace payouts not ready");let recipientType=input.recipientOwnerType??"seller",currency=input.currency??this.marketplace.config.defaultCurrency;if(input.amount<=0)throw Error("Payout amount must be positive");let minimum=this.marketplace.config.minimumPayoutAmount;if(input.amount<minimum)throw Error(`Payout amount is below the minimum of ${minimum}`);let balance=await this.marketplace.getBalance(recipientType,input.recipientOwnerId,currency);if(input.amount>balance.available)throw Error(`Insufficient available balance: requested ${input.amount}, available ${balance.available}`);let table=this.table("payoutRequests"),rows=await db.insert(table).values({recipientOwnerType:recipientType,recipientOwnerId:input.recipientOwnerId,amount:input.amount,currency,status:"pending",destination:input.destination??null,requestedBy:input.requestedBy??null,metadata:JSON.stringify({})}).returning();return rowToPayoutRequest(rows[0])}async listPayoutRequests(filter){let db=this.getDb();if(!db)return[];let table=this.table("payoutRequests"),where=filter.recipientOwnerId?eq12(col4(table,"recipientOwnerId"),filter.recipientOwnerId):void 0,mapped=(where?await db.select().from(table).where(where):await db.select().from(table)).map((r)=>rowToPayoutRequest(r));return filter.status?mapped.filter((p)=>p.status===filter.status):mapped}async getPayoutRequest(id){let db=this.getDb();if(!db)return null;let table=this.table("payoutRequests"),rows=await db.select().from(table).where(eq12(col4(table,"id"),id)).limit(1);return rows[0]?rowToPayoutRequest(rows[0]):null}async rejectPayout(id,deciderId){let db=this.getDb();if(!db)return null;let table=this.table("payoutRequests");return await db.update(table).set({status:"rejected",decidedBy:deciderId??null,decidedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),this.getPayoutRequest(id)}async approvePayout(id,opts){let db=this.getDb();if(!db)return null;let request=await this.getPayoutRequest(id);if(!request)return null;if(request.status!=="pending")throw Error(`Payout is not pending (status: ${request.status})`);let table=this.table("payoutRequests"),destination=opts?.destination??request.destination;if(await db.update(table).set({status:"processing",decidedBy:opts?.deciderId??null,decidedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),!this.provider)return this.logger.warn("No payment provider configured; payout left in processing",{id}),this.getPayoutRequest(id);try{let result=destination?await this.provider.createTransfer({amount:request.amount,currency:request.currency,destination,transferGroup:`payout:${id}`}):await this.provider.createPayout({amount:request.amount,currency:request.currency}),providerId="providerTransferId"in result?result.providerTransferId:void 0,providerPayoutId="providerPayoutId"in result?result.providerPayoutId:void 0;if(!result.success)throw Error(result.errorMessage||"Provider payout failed");return await db.update(table).set({status:"completed",provider:this.provider?"configured":null,providerTransferId:providerId??null,providerPayoutId:providerPayoutId??null,completedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),await this.marketplace.recordLedgerEntry({account:"seller_payable",direction:"debit",amount:request.amount,currency:request.currency,entryType:"payout",ownerType:request.recipientOwnerType,ownerId:request.recipientOwnerId,referenceType:"payout_request",referenceId:id}),await this.marketplace.recordLedgerEntry({account:"payout_completed",direction:"credit",amount:request.amount,currency:request.currency,entryType:"payout",ownerType:request.recipientOwnerType,ownerId:request.recipientOwnerId,referenceType:"payout_request",referenceId:id}),await this.consumeSplits(request.recipientOwnerId,request.amount,request.currency),this.getPayoutRequest(id)}catch(err){let reason=err instanceof Error?err.message:"Payout execution failed";return await db.update(table).set({status:"failed",failureReason:reason,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),this.logger.error("Payout execution failed",{id,reason}),this.getPayoutRequest(id)}}async consumeSplits(ownerId,amount,currency){let db=this.getDb();if(!db)return;let table=this.table("splits"),splits=await this.marketplace.listSplits({recipientOwnerId:ownerId}),remaining=amount,now=Date.now();for(let s of splits){if(remaining<=0)break;if(s.currency!==currency)continue;if(s.status!=="pending"&&s.status!=="available")continue;if(!(s.availableForPayoutAt?new Date(s.availableForPayoutAt).getTime()<=now:!0))continue;if(s.netPayableAmount>remaining)continue;await db.update(table).set({status:"paid",updatedAt:new Date}).where(eq12(col4(table,"id"),s.id)),remaining-=s.netPayableAmount}}async openDispute(input){let db=this.getDb();if(!db)return null;let table=this.table("disputes"),rows=await db.insert(table).values({transactionId:input.transactionId??null,provider:input.provider,providerDisputeId:input.providerDisputeId??null,ownerType:input.ownerType??null,ownerId:input.ownerId??null,amount:input.amount??null,currency:input.currency??null,reason:input.reason??null,status:"open",evidenceDueAt:input.evidenceDueAt??null,metadata:JSON.stringify(input.metadata??{})}).returning(),dispute=rowToDispute(rows[0]);if(input.amount&&input.amount>0&&input.currency)await this.marketplace.recordLedgerEntry({account:"dispute_liability",direction:"credit",amount:input.amount,currency:input.currency,entryType:"dispute",ownerType:input.ownerType,ownerId:input.ownerId,referenceType:"dispute",referenceId:dispute.id});return dispute}async listDisputes(filter){let db=this.getDb();if(!db)return[];let table=this.table("disputes"),where=filter.ownerId?eq12(col4(table,"ownerId"),filter.ownerId):void 0,mapped=(where?await db.select().from(table).where(where):await db.select().from(table)).map((r)=>rowToDispute(r));return filter.status?mapped.filter((d)=>d.status===filter.status):mapped}async getDispute(id){let db=this.getDb();if(!db)return null;let table=this.table("disputes"),rows=await db.select().from(table).where(eq12(col4(table,"id"),id)).limit(1);return rows[0]?rowToDispute(rows[0]):null}async resolveDispute(id,outcome){let db=this.getDb();if(!db)return null;let dispute=await this.getDispute(id);if(!dispute)return null;let table=this.table("disputes");if(await db.update(table).set({status:outcome,resolvedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),(outcome==="lost"||outcome==="accepted")&&dispute.amount&&dispute.currency)await this.marketplace.recordLedgerEntry({account:"seller_payable",direction:"debit",amount:dispute.amount,currency:dispute.currency,entryType:"dispute",ownerType:dispute.ownerType??void 0,ownerId:dispute.ownerId??void 0,referenceType:"dispute",referenceId:id});return this.getDispute(id)}}var col4=(table,name)=>table[name];var init_MarketplacePayoutService=()=>{};import{and as and6,eq as eq13}from"drizzle-orm";class MarketplaceService{getDb;config;logger;t;constructor(cfg){this.getDb=cfg.getDb,this.config=cfg.config,this.logger=cfg.logger.scoped("payment.marketplace"),this.t=cfg.tables}table(name){return this.t[name]}async recordLedgerEntry(entry){let db=this.getDb();if(!db)return;await db.insert(this.table("ledgerEntries")).values({account:entry.account,ownerType:entry.ownerType??null,ownerId:entry.ownerId??null,direction:entry.direction,amount:entry.amount,currency:entry.currency,entryType:entry.entryType,referenceType:entry.referenceType??null,referenceId:entry.referenceId??null,splitId:entry.splitId??null,description:entry.description??null,metadata:JSON.stringify({})})}async getSettlementPolicy(ownerType,ownerId){let db=this.getDb();if(!db)return null;let table=this.table("settlementPolicies"),rows=await db.select().from(table).where(and6(eq13(col5(table,"ownerType"),ownerType),eq13(col5(table,"ownerId"),ownerId))).limit(1);return rows[0]?rowToSettlementPolicy(rows[0]):null}async upsertSettlementPolicy(input){let db=this.getDb();if(!db)return null;let table=this.table("settlementPolicies"),existing=await this.getSettlementPolicy(input.ownerType,input.ownerId),values={ownerType:input.ownerType,ownerId:input.ownerId,defaultDelayDays:input.defaultDelayDays??this.config.defaultSettlementDelayDays,newSellerDelayDays:input.newSellerDelayDays??this.config.newSellerDelayDays,reserveRate:String(input.reserveRate??this.config.reserveRate),reserveDays:input.reserveDays??this.config.reserveReleaseDays,minimumPayoutAmount:input.minimumPayoutAmount??this.config.minimumPayoutAmount,currency:input.currency??null,earlyPayoutEnabled:input.earlyPayoutEnabled??!1,updatedAt:new Date};if(existing)await db.update(table).set(values).where(eq13(col5(table,"id"),existing.id));else await db.insert(table).values(values);return this.getSettlementPolicy(input.ownerType,input.ownerId)}async recordSplit(input){let db=this.getDb();if(!db)return null;let recipientType=input.recipientOwnerType??"seller",currency=input.currency??this.config.defaultCurrency,now=new Date,policy=await this.getSettlementPolicy(recipientType,input.recipientOwnerId),breakdown=computeSplitBreakdown(input,this.config,policy,now),splitTable=this.table("splits"),rows=await db.insert(splitTable).values({transactionId:input.transactionId??null,recipientOwnerType:recipientType,recipientOwnerId:input.recipientOwnerId,provider:input.provider,grossAmount:breakdown.grossAmount,providerFeeAmount:breakdown.providerFeeAmount,platformFeeAmount:breakdown.platformFeeAmount,reserveAmount:breakdown.reserveAmount,netPayableAmount:breakdown.netPayableAmount,currency,availableForPayoutAt:breakdown.availableForPayoutAt,status:"pending",sourceType:input.sourceType??null,sourceId:input.sourceId??null,metadata:JSON.stringify(input.metadata??{})}).returning(),split=rowToSplit(rows[0]);if(await this.recordLedgerEntry({account:"seller_payable",direction:"credit",amount:breakdown.netPayableAmount,currency,entryType:"split",ownerType:recipientType,ownerId:input.recipientOwnerId,referenceType:"split",referenceId:split.id,splitId:split.id}),breakdown.platformFeeAmount>0)await this.recordLedgerEntry({account:"platform_revenue",direction:"credit",amount:breakdown.platformFeeAmount,currency,entryType:"split",referenceType:"split",referenceId:split.id,splitId:split.id});if(breakdown.providerFeeAmount>0)await this.recordLedgerEntry({account:"provider_fee",direction:"credit",amount:breakdown.providerFeeAmount,currency,entryType:"split",referenceType:"split",referenceId:split.id,splitId:split.id});if(breakdown.reserveAmount>0){let reserveDays=policy?.reserveDays??this.config.reserveReleaseDays;await db.insert(this.table("reserves")).values({ownerType:recipientType,ownerId:input.recipientOwnerId,splitId:split.id,amount:breakdown.reserveAmount,currency,reason:input.isNewSeller?"new_seller":"refund_window",status:"held",releaseAt:reserveDays>0?addDays(now,reserveDays):null,metadata:JSON.stringify({})}),await this.recordLedgerEntry({account:"reserve",direction:"credit",amount:breakdown.reserveAmount,currency,entryType:"reserve_hold",ownerType:recipientType,ownerId:input.recipientOwnerId,referenceType:"split",referenceId:split.id,splitId:split.id})}return this.logger.info("Recorded split",{splitId:split.id,gross:breakdown.grossAmount,netPayable:breakdown.netPayableAmount,reserve:breakdown.reserveAmount}),split}async listSplits(filter){let db=this.getDb();if(!db)return[];let table=this.table("splits"),where=filter.recipientOwnerId?eq13(col5(table,"recipientOwnerId"),filter.recipientOwnerId):void 0,mapped=(where?await db.select().from(table).where(where):await db.select().from(table)).map((r)=>rowToSplit(r));return filter.status?mapped.filter((s)=>s.status===filter.status):mapped}async releaseReserve(id){let db=this.getDb();if(!db)return!1;let table=this.table("reserves"),row=(await db.select().from(table).where(eq13(col5(table,"id"),id)).limit(1))[0];if(!row||String(row.status)!=="held")return!1;return await db.update(table).set({status:"released",releasedAt:new Date,updatedAt:new Date}).where(eq13(col5(table,"id"),id)),await this.recordLedgerEntry({account:"reserve",direction:"debit",amount:Number(row.amount),currency:String(row.currency),entryType:"reserve_release",ownerType:String(row.ownerType??row.owner_type??""),ownerId:String(row.ownerId??row.owner_id??""),referenceType:"reserve",referenceId:id}),!0}async autoReleaseDueReserves(ownerType,ownerId){if(!this.config.autoReleaseReserves)return;let db=this.getDb();if(!db)return;let table=this.table("reserves"),rows=await db.select().from(table).where(and6(eq13(col5(table,"ownerType"),ownerType),eq13(col5(table,"ownerId"),ownerId))),now=Date.now();for(let r of rows){let releaseAt=r.releaseAt??r.release_at;if(String(r.status)==="held"&&releaseAt&&new Date(String(releaseAt)).getTime()<=now)await this.releaseReserve(String(r.id))}}async getBalance(ownerType,ownerId,currency){let cur=currency??this.config.defaultCurrency,db=this.getDb(),base={ownerType,ownerId,currency:cur,available:0,pending:0,reserved:0,payoutInFlight:0};if(!db)return base;await this.autoReleaseDueReserves(ownerType,ownerId);let splits=await this.listSplits({recipientOwnerId:ownerId}),now=Date.now();for(let s of splits){if(s.currency!==cur)continue;if(s.status==="pending"||s.status==="available")if(s.availableForPayoutAt?new Date(s.availableForPayoutAt).getTime()<=now:!0)base.available+=s.netPayableAmount;else base.pending+=s.netPayableAmount}let reserveTable=this.table("reserves"),reserveRows=await db.select().from(reserveTable).where(and6(eq13(col5(reserveTable,"ownerType"),ownerType),eq13(col5(reserveTable,"ownerId"),ownerId)));for(let r of reserveRows)if(String(r.status)==="held"&&String(r.currency)===cur)base.reserved+=Number(r.amount);let payoutTable=this.table("payoutRequests"),payoutRows=await db.select().from(payoutTable).where(and6(eq13(col5(payoutTable,"recipientOwnerType"),ownerType),eq13(col5(payoutTable,"recipientOwnerId"),ownerId)));for(let p of payoutRows){let st=String(p.status);if((st==="pending"||st==="approved"||st==="processing")&&String(p.currency)===cur)base.payoutInFlight+=Number(p.amount),base.available-=Number(p.amount)}if(base.available<0)base.available=0;return base}}var col5=(table,name)=>table[name];var init_MarketplaceService=()=>{};var pick=(schemaTables,camel,snake)=>schemaTables[camel]??schemaTables[snake]??{},createMarketplaceServices=(params)=>{let config=resolveMarketplaceConfig(params.options.payment);if(!config.enabled)return null;let tables={splits:pick(params.schemaTables,"paymentSplits","payment_splits"),ledgerEntries:pick(params.schemaTables,"paymentLedgerEntries","payment_ledger_entries"),settlementPolicies:pick(params.schemaTables,"paymentSettlementPolicies","payment_settlement_policies"),reserves:pick(params.schemaTables,"paymentReserves","payment_reserves"),payoutRequests:pick(params.schemaTables,"paymentPayoutRequests","payment_payout_requests"),disputes:pick(params.schemaTables,"paymentDisputes","payment_disputes")},serviceConfig={getDb:params.getDb,provider:params.provider,config,logger:params.logger,tables},marketplaceService=new MarketplaceService(serviceConfig),payoutService=new MarketplacePayoutService(serviceConfig,marketplaceService);return{marketplaceService,payoutService}};var init_Marketplace=__esm(()=>{init_MarketplacePayoutService();init_MarketplaceService();init_MarketplacePayoutService();init_MarketplaceService()});var loadStripe=(config)=>{try{let StripeModule=__require("stripe");return new(StripeModule.default??StripeModule)(config.secretKey,{maxNetworkRetries:config.maxNetworkRetries??2,timeout:config.timeout??30000,...config.apiVersion?{apiVersion:config.apiVersion}:{}})}catch(error){return logger.scoped("payment.init").error("Failed to load stripe package. Install it: bun add stripe",error),null}},createStripeProvider=(config)=>{let stripe=loadStripe(config);if(!stripe)return null;let providerName="stripe";return{get name(){return providerName},async initialize3DS(request){try{let params={amount:Math.round(Number(request.paidPrice)*100),currency:request.currency.toLowerCase(),payment_method_types:["card"],description:`Order ${request.conversationId}`,metadata:{conversationId:request.conversationId,basketId:request.basketId??"",buyerEmail:request.buyer.email,buyerId:request.buyer.id}};if("cardToken"in request.paymentCard&&request.paymentCard.cardToken)params.payment_method=request.paymentCard.cardToken,params.confirm=!0,params.return_url=request.callbackUrl;let paymentIntent=await stripe.paymentIntents.create(params),clientSecret=paymentIntent.client_secret,piId=paymentIntent.id,status=paymentIntent.status;return{success:!0,paymentId:piId,threeDSHtmlContent:clientSecret,signature:status,rawResponse:paymentIntent}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Payment initialization failed",rawResponse:{error:err.message}}}},async complete3DS(request){try{let paymentIntent=await stripe.paymentIntents.retrieve(request.paymentId,{expand:["payment_method"]}),status=paymentIntent.status,isSuccess=status==="succeeded",amountReceived=paymentIntent.amount_received??0,card=paymentIntent.payment_method?.card;return{success:isSuccess,paymentId:paymentIntent.id,price:amountReceived/100,paidPrice:amountReceived/100,currency:paymentIntent.currency?.toUpperCase(),cardType:card?.brand??void 0,cardAssociation:card?.brand??void 0,cardFamily:card?.funding??void 0,lastFourDigits:card?.last4??void 0,authCode:status,errorCode:isSuccess?void 0:"PAYMENT_NOT_SUCCEEDED",errorMessage:isSuccess?void 0:`Payment status: ${status}`,rawResponse:paymentIntent}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Payment completion failed",rawResponse:{error:err.message}}}},async getPaymentDetail(request){try{let paymentIntent=await stripe.paymentIntents.retrieve(request.paymentId,{expand:["payment_method"]}),amountReceived=paymentIntent.amount_received??paymentIntent.amount??0,card=paymentIntent.payment_method?.card;return{success:!0,paymentId:paymentIntent.id,price:amountReceived/100,paidPrice:amountReceived/100,currency:paymentIntent.currency?.toUpperCase(),cardType:card?.brand??void 0,cardAssociation:card?.brand??void 0,lastFourDigits:card?.last4??void 0,binNumber:void 0,rawResponse:paymentIntent}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Payment detail query failed",rawResponse:{error:err.message}}}},async queryBin(_request){return{success:!1,errorCode:"NOT_SUPPORTED",errorMessage:"BIN query is not supported by Stripe. Card info is available after payment method creation.",rawResponse:{}}},async saveCard(request){try{let customer=await stripe.customers.create({email:request.email,metadata:{externalId:request.externalId??""}}),paymentMethod=await stripe.paymentMethods.create({type:"card",card:{number:request.card.cardNumber,exp_month:Number(request.card.expireMonth),exp_year:Number(request.card.expireYear)}});await stripe.paymentMethods.attach(paymentMethod.id,{customer:customer.id});let card=paymentMethod.card;return{success:!0,cardUserKey:customer.id,cardToken:paymentMethod.id,cardAlias:request.card.cardAlias,binNumber:void 0,lastFourDigits:card?.last4??void 0,cardType:card?.brand??void 0,cardAssociation:card?.brand??void 0,cardFamily:card?.funding??void 0,cardBankName:void 0,rawResponse:{customer,paymentMethod}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to save card",rawResponse:{error:err.message}}}},async listCards(request){try{let response=await stripe.paymentMethods.list({customer:request.cardUserKey,type:"card"}),cards=response.data.map((pm)=>{let card=pm.card;return{cardToken:pm.id,cardAlias:pm.metadata?.alias??"",binNumber:"",lastFourDigits:card?.last4??"",cardType:card?.brand??"",cardAssociation:card?.brand??"",cardFamily:card?.funding??"",cardBankName:"",cardBankCode:0}});return{success:!0,cardUserKey:request.cardUserKey,cards,rawResponse:response}}catch(error){let err=error;return{success:!1,cards:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list cards",rawResponse:{error:err.message}}}},async deleteCard(request){try{return await stripe.paymentMethods.detach(request.cardToken),{success:!0,rawResponse:{detached:request.cardToken}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to delete card",rawResponse:{error:err.message}}}},async refund(request){try{let amountInCents=Math.round(Number(request.price)*100),refund=await stripe.refunds.create({payment_intent:request.paymentTransactionId,amount:amountInCents});return{success:refund.status==="succeeded",paymentId:refund.payment_intent,price:amountInCents/100,currency:refund.currency?.toUpperCase(),errorCode:refund.status!=="succeeded"?"REFUND_FAILED":void 0,errorMessage:refund.status!=="succeeded"?`Refund status: ${refund.status}`:void 0,rawResponse:refund}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Refund failed",rawResponse:{error:err.message}}}},parseCallback(formData){let paymentIntent=formData.payment_intent??formData.paymentId??"",redirectStatus=formData.redirect_status??"";return{success:redirectStatus==="succeeded",paymentId:paymentIntent,conversationId:formData.conversationId??"",mdStatus:redirectStatus,rawData:formData}},async registerSubMerchant(request){try{let account=await stripe.accounts.create({type:"express",country:request.currency==="TRY"?"TR":void 0,email:request.email,business_type:request.subMerchantType==="personal"?"individual":"company",metadata:{externalId:request.subMerchantExternalId,name:request.name,contactName:request.contactName??"",contactSurname:request.contactSurname??""},capabilities:{transfers:{requested:!0}}});return{success:!0,subMerchantKey:account.id,rawResponse:account}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create connected account",rawResponse:{error:err.message}}}},async updateSubMerchant(request){try{let params={metadata:{}},meta=params.metadata;if(request.name)meta.name=request.name;if(request.email)params.email=request.email;if(request.contactName)meta.contactName=request.contactName;if(request.contactSurname)meta.contactSurname=request.contactSurname;return await stripe.accounts.update(request.subMerchantKey,params),{success:!0,rawResponse:{updated:request.subMerchantKey}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update connected account",rawResponse:{error:err.message}}}},async getSubMerchant(request){try{let account=await stripe.accounts.retrieve(request.subMerchantExternalId),meta=account.metadata??{};return{success:!0,subMerchantKey:account.id,name:meta.name,email:account.email,subMerchantType:account.business_type==="individual"?"personal":"company",currency:account.default_currency?.toUpperCase(),rawResponse:account}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to retrieve connected account",rawResponse:{error:err.message}}}},async approveSplit(request){return{success:!0,paymentTransactionId:request.paymentTransactionId,rawResponse:{message:"Stripe transfers are automatic; no manual approval needed."}}},async disapproveSplit(request){try{let reversal=await stripe.transfers.createReversal(request.paymentTransactionId);return{success:!0,paymentTransactionId:reversal.id,rawResponse:reversal}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to reverse transfer",rawResponse:{error:err.message}}}},async createProduct(request){try{let params={name:request.name};if(request.description)params.description=request.description;if(request.type)params.type=request.type;if(request.images)params.images=request.images;if(request.unitLabel)params.unit_label=request.unitLabel;if(request.url)params.url=request.url;if(request.metadata)params.metadata=request.metadata;let product=await stripe.products.create(params);return{success:!0,providerProductId:product.id,name:product.name,rawResponse:product}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create product",rawResponse:{error:err.message}}}},async updateProduct(request){try{let params={};if(request.name)params.name=request.name;if(request.description!==void 0)params.description=request.description;if(request.images)params.images=request.images;if(request.unitLabel!==void 0)params.unit_label=request.unitLabel;if(request.url!==void 0)params.url=request.url;if(request.active!==void 0)params.active=request.active;if(request.metadata)params.metadata=request.metadata;let product=await stripe.products.update(request.providerProductId,params);return{success:!0,providerProductId:product.id,rawResponse:product}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update product",rawResponse:{error:err.message}}}},async getProduct(request){try{let product=await stripe.products.retrieve(request.providerProductId);return{success:!0,providerProductId:product.id,name:product.name,description:product.description,type:product.type,active:product.active,images:product.images,unitLabel:product.unit_label,url:product.url,metadata:product.metadata,rawResponse:product}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get product",rawResponse:{error:err.message}}}},async listProducts(request){try{let params={};if(request.active!==void 0)params.active=request.active;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.products.list(params);return{success:!0,products:response.data.map((p)=>({providerProductId:p.id,name:p.name,description:p.description,type:p.type,active:p.active,images:p.images,unitLabel:p.unit_label,metadata:p.metadata})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,products:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list products",rawResponse:{error:err.message}}}},async archiveProduct(request){try{return await stripe.products.update(request.providerProductId,{active:!1}),{success:!0,rawResponse:{archived:request.providerProductId}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to archive product",rawResponse:{error:err.message}}}},async createPrice(request){try{let params={product:request.providerProductId,currency:request.currency.toLowerCase(),unit_amount:request.unitAmount};if(request.nickname)params.nickname=request.nickname;if(request.billingScheme)params.billing_scheme=request.billingScheme;if(request.unitAmountDecimal)params.unit_amount_decimal=request.unitAmountDecimal;if(request.metadata)params.metadata=request.metadata;if(request.recurring)params.recurring={interval:request.recurring.interval,...request.recurring.intervalCount?{interval_count:request.recurring.intervalCount}:{},...request.recurring.usageType?{usage_type:request.recurring.usageType}:{},...request.recurring.aggregateUsage?{aggregate_usage:request.recurring.aggregateUsage}:{}};if(request.transformQuantity)params.transform_quantity={divide_by:request.transformQuantity.divideBy,round:request.transformQuantity.round};let price=await stripe.prices.create(params);return{success:!0,providerPriceId:price.id,rawResponse:price}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create price",rawResponse:{error:err.message}}}},async updatePrice(request){try{let params={};if(request.nickname!==void 0)params.nickname=request.nickname;if(request.active!==void 0)params.active=request.active;if(request.metadata)params.metadata=request.metadata;let price=await stripe.prices.update(request.providerPriceId,params);return{success:!0,providerPriceId:price.id,rawResponse:price}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update price",rawResponse:{error:err.message}}}},async getPrice(request){try{let price=await stripe.prices.retrieve(request.providerPriceId),rec=price.recurring;return{success:!0,providerPriceId:price.id,providerProductId:price.product,currency:price.currency?.toUpperCase(),unitAmount:price.unit_amount,type:price.type,billingScheme:price.billing_scheme,nickname:price.nickname,active:price.active,recurring:rec?{interval:rec.interval,intervalCount:rec.interval_count??1,usageType:rec.usage_type}:void 0,metadata:price.metadata,rawResponse:price}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get price",rawResponse:{error:err.message}}}},async listPrices(request){try{let params={};if(request.providerProductId)params.product=request.providerProductId;if(request.active!==void 0)params.active=request.active;if(request.type)params.type=request.type;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.prices.list(params);return{success:!0,prices:response.data.map((p)=>{let rec=p.recurring;return{providerPriceId:p.id,providerProductId:p.product,currency:p.currency?.toUpperCase(),unitAmount:p.unit_amount,type:p.type,billingScheme:p.billing_scheme,nickname:p.nickname,active:p.active,recurring:rec?{interval:rec.interval,intervalCount:rec.interval_count??1,usageType:rec.usage_type}:void 0,metadata:p.metadata}}),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,prices:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list prices",rawResponse:{error:err.message}}}},async archivePrice(request){try{return await stripe.prices.update(request.providerPriceId,{active:!1}),{success:!0,rawResponse:{archived:request.providerPriceId}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to archive price",rawResponse:{error:err.message}}}},async createCustomer(request){try{let params={email:request.email};if(request.name)params.name=request.name;if(request.phone)params.phone=request.phone;if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.address)params.address={line1:request.address.line1,line2:request.address.line2,city:request.address.city,state:request.address.state,postal_code:request.address.postalCode,country:request.address.country};let customer=await stripe.customers.create(params);if(request.taxId)try{await stripe.taxIds?.create({customer:customer.id,type:request.taxId.type,value:request.taxId.value})}catch(_){}return{success:!0,providerCustomerId:customer.id,email:customer.email,rawResponse:customer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create customer",rawResponse:{error:err.message}}}},async updateCustomer(request){try{let params={};if(request.email)params.email=request.email;if(request.name!==void 0)params.name=request.name;if(request.phone!==void 0)params.phone=request.phone;if(request.description!==void 0)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.address)params.address={line1:request.address.line1,line2:request.address.line2,city:request.address.city,state:request.address.state,postal_code:request.address.postalCode,country:request.address.country};let customer=await stripe.customers.update(request.providerCustomerId,params);return{success:!0,providerCustomerId:customer.id,rawResponse:customer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update customer",rawResponse:{error:err.message}}}},async getCustomer(request){try{let customer=await stripe.customers.retrieve(request.providerCustomerId);return{success:!0,providerCustomerId:customer.id,email:customer.email,name:customer.name,phone:customer.phone,description:customer.description,metadata:customer.metadata,rawResponse:customer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get customer",rawResponse:{error:err.message}}}},async listCustomers(request){try{let params={};if(request.email)params.email=request.email;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.customers.list(params);return{success:!0,customers:response.data.map((c)=>({providerCustomerId:c.id,email:c.email,name:c.name,phone:c.phone})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,customers:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list customers",rawResponse:{error:err.message}}}},async deleteCustomer(request){try{return await stripe.customers.del(request.providerCustomerId),{success:!0,rawResponse:{deleted:request.providerCustomerId}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to delete customer",rawResponse:{error:err.message}}}},async createSubscription(request){try{let params={customer:request.providerCustomerId,items:request.items.map((i)=>({price:i.providerPriceId,...i.quantity!==void 0?{quantity:i.quantity}:{}}))};if(request.trialPeriodDays)params.trial_period_days=request.trialPeriodDays;if(request.collectionMethod)params.collection_method=request.collectionMethod;if(request.daysUntilDue)params.days_until_due=request.daysUntilDue;if(request.cancelAtPeriodEnd!==void 0)params.cancel_at_period_end=request.cancelAtPeriodEnd;if(request.metadata)params.metadata=request.metadata;if(request.defaultPaymentMethod)params.default_payment_method=request.defaultPaymentMethod;params.payment_behavior="default_incomplete",params.payment_settings={save_default_payment_method:"on_subscription"},params.expand=["latest_invoice.payment_intent"];let sub=await stripe.subscriptions.create(params),pi=sub.latest_invoice?.payment_intent;return{success:!0,providerSubscriptionId:sub.id,status:sub.status,currentPeriodStart:sub.current_period_start?new Date(sub.current_period_start*1000).toISOString():void 0,currentPeriodEnd:sub.current_period_end?new Date(sub.current_period_end*1000).toISOString():void 0,clientSecret:pi?.client_secret,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create subscription",rawResponse:{error:err.message}}}},async updateSubscription(request){try{let params={};if(request.items)params.items=request.items.map((i)=>({...i.id?{id:i.id}:{},price:i.providerPriceId,...i.quantity!==void 0?{quantity:i.quantity}:{}}));if(request.cancelAtPeriodEnd!==void 0)params.cancel_at_period_end=request.cancelAtPeriodEnd;if(request.trialEnd!==void 0)params.trial_end=request.trialEnd;if(request.metadata)params.metadata=request.metadata;if(request.collectionMethod)params.collection_method=request.collectionMethod;if(request.daysUntilDue)params.days_until_due=request.daysUntilDue;if(request.defaultPaymentMethod)params.default_payment_method=request.defaultPaymentMethod;if(request.prorationBehavior)params.proration_behavior=request.prorationBehavior;let sub=await stripe.subscriptions.update(request.providerSubscriptionId,params);return{success:!0,providerSubscriptionId:sub.id,status:sub.status,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update subscription",rawResponse:{error:err.message}}}},async cancelSubscription(request){try{if(request.cancelAtPeriodEnd){let sub2=await stripe.subscriptions.update(request.providerSubscriptionId,{cancel_at_period_end:!0});return{success:!0,providerSubscriptionId:sub2.id,status:sub2.status,rawResponse:sub2}}let params={};if(request.invoiceNow)params.invoice_now=request.invoiceNow;if(request.prorate)params.prorate=request.prorate;let sub=await stripe.subscriptions.cancel(request.providerSubscriptionId,params);return{success:!0,providerSubscriptionId:sub.id,status:sub.status,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to cancel subscription",rawResponse:{error:err.message}}}},async getSubscription(request){try{let sub=await stripe.subscriptions.retrieve(request.providerSubscriptionId),itemsData=sub.items?.data??[];return{success:!0,providerSubscriptionId:sub.id,providerCustomerId:sub.customer,status:sub.status,currentPeriodStart:sub.current_period_start?new Date(sub.current_period_start*1000).toISOString():void 0,currentPeriodEnd:sub.current_period_end?new Date(sub.current_period_end*1000).toISOString():void 0,cancelAtPeriodEnd:sub.cancel_at_period_end,canceledAt:sub.canceled_at?new Date(sub.canceled_at*1000).toISOString():void 0,trialStart:sub.trial_start?new Date(sub.trial_start*1000).toISOString():void 0,trialEnd:sub.trial_end?new Date(sub.trial_end*1000).toISOString():void 0,items:itemsData.map((i)=>({id:i.id,providerPriceId:i.price?.id??i.price,quantity:i.quantity??1})),metadata:sub.metadata,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get subscription",rawResponse:{error:err.message}}}},async listSubscriptions(request){try{let params={};if(request.providerCustomerId)params.customer=request.providerCustomerId;if(request.status)params.status=request.status;if(request.providerPriceId)params.price=request.providerPriceId;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.subscriptions.list(params);return{success:!0,subscriptions:response.data.map((s)=>({providerSubscriptionId:s.id,providerCustomerId:s.customer,status:s.status,currentPeriodStart:s.current_period_start?new Date(s.current_period_start*1000).toISOString():void 0,currentPeriodEnd:s.current_period_end?new Date(s.current_period_end*1000).toISOString():void 0,cancelAtPeriodEnd:s.cancel_at_period_end})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,subscriptions:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list subscriptions",rawResponse:{error:err.message}}}},async reportUsage(request){try{let params={quantity:request.quantity,action:request.action??"increment"};if(request.timestamp)params.timestamp=request.timestamp;let record=await stripe.subscriptionItems.usageRecords.create(request.subscriptionItemId,params);return{success:!0,usageRecordId:record.id,quantity:record.quantity,timestamp:record.timestamp,rawResponse:record}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to report usage",rawResponse:{error:err.message}}}},async listUsageRecordSummaries(request){try{let params={};if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.subscriptionItems.usageRecordSummaries.list(request.subscriptionItemId,params);return{success:!0,summaries:response.data.map((s)=>({id:s.id,totalUsage:s.total_usage,period:s.period,subscriptionItem:s.subscription_item})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,summaries:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list usage summaries",rawResponse:{error:err.message}}}},async createInvoice(request){try{let params={customer:request.providerCustomerId};if(request.collectionMethod)params.collection_method=request.collectionMethod;if(request.daysUntilDue)params.days_until_due=request.daysUntilDue;if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.autoAdvance!==void 0)params.auto_advance=request.autoAdvance;let invoice=await stripe.invoices.create(params);if(request.items?.length)for(let item of request.items){let lineParams={customer:request.providerCustomerId,invoice:invoice.id};if(item.providerPriceId)lineParams.price=item.providerPriceId;if(item.quantity)lineParams.quantity=item.quantity;if(item.unitAmount!==void 0)lineParams.unit_amount=item.unitAmount;if(item.currency)lineParams.currency=item.currency;if(item.description)lineParams.description=item.description;await stripe.invoiceItems.create(lineParams)}return{success:!0,providerInvoiceId:invoice.id,status:invoice.status,hostedInvoiceUrl:invoice.hosted_invoice_url,invoicePdf:invoice.invoice_pdf,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create invoice",rawResponse:{error:err.message}}}},async finalizeInvoice(request){try{let params={};if(request.autoAdvance!==void 0)params.auto_advance=request.autoAdvance;let invoice=await stripe.invoices.finalizeInvoice(request.providerInvoiceId,params);return{success:!0,providerInvoiceId:invoice.id,status:invoice.status,hostedInvoiceUrl:invoice.hosted_invoice_url,invoicePdf:invoice.invoice_pdf,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to finalize invoice",rawResponse:{error:err.message}}}},async sendInvoice(request){try{let invoice=await stripe.invoices.sendInvoice(request.providerInvoiceId);return{success:!0,providerInvoiceId:invoice.id,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to send invoice",rawResponse:{error:err.message}}}},async voidInvoice(request){try{let invoice=await stripe.invoices.voidInvoice(request.providerInvoiceId);return{success:!0,providerInvoiceId:invoice.id,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to void invoice",rawResponse:{error:err.message}}}},async payInvoice(request){try{let params={};if(request.paymentMethod)params.payment_method=request.paymentMethod;let invoice=await stripe.invoices.pay(request.providerInvoiceId,params);return{success:!0,providerInvoiceId:invoice.id,status:invoice.status,amountPaid:invoice.amount_paid,amountDue:invoice.amount_due,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to pay invoice",rawResponse:{error:err.message}}}},async getInvoice(request){try{let invoice=await stripe.invoices.retrieve(request.providerInvoiceId),linesData=invoice.lines?.data??[];return{success:!0,providerInvoiceId:invoice.id,providerCustomerId:invoice.customer,providerSubscriptionId:invoice.subscription,status:invoice.status,amountDue:invoice.amount_due,amountPaid:invoice.amount_paid,amountRemaining:invoice.amount_remaining,currency:invoice.currency?.toUpperCase(),description:invoice.description,hostedInvoiceUrl:invoice.hosted_invoice_url,invoicePdf:invoice.invoice_pdf,dueDate:invoice.due_date?new Date(invoice.due_date*1000).toISOString():void 0,periodStart:invoice.period_start?new Date(invoice.period_start*1000).toISOString():void 0,periodEnd:invoice.period_end?new Date(invoice.period_end*1000).toISOString():void 0,metadata:invoice.metadata,lines:linesData.map((l)=>({id:l.id,description:l.description,amount:l.amount,currency:l.currency?.toUpperCase(),quantity:l.quantity,providerPriceId:l.price?.id})),rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get invoice",rawResponse:{error:err.message}}}},async listInvoices(request){try{let params={};if(request.providerCustomerId)params.customer=request.providerCustomerId;if(request.providerSubscriptionId)params.subscription=request.providerSubscriptionId;if(request.status)params.status=request.status;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.invoices.list(params);return{success:!0,invoices:response.data.map((inv)=>({providerInvoiceId:inv.id,providerCustomerId:inv.customer,status:inv.status,amountDue:inv.amount_due,amountPaid:inv.amount_paid,currency:inv.currency?.toUpperCase(),dueDate:inv.due_date?new Date(inv.due_date*1000).toISOString():void 0,hostedInvoiceUrl:inv.hosted_invoice_url})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,invoices:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list invoices",rawResponse:{error:err.message}}}},async getBalance(){try{let bal=await stripe.balance.retrieve(),mapAmounts=(arr)=>(arr??[]).map((a)=>({amount:a.amount,currency:a.currency?.toUpperCase()}));return{success:!0,available:mapAmounts(bal.available),pending:mapAmounts(bal.pending),connectReserved:mapAmounts(bal.connect_reserved),rawResponse:bal}}catch(error){let err=error;return{success:!1,available:[],pending:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get balance",rawResponse:{error:err.message}}}},async createPayout(request){try{let params={amount:request.amount,currency:request.currency.toLowerCase()};if(request.destination)params.destination=request.destination;if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.method)params.method=request.method;if(request.sourceType)params.source_type=request.sourceType;if(request.statementDescriptor)params.statement_descriptor=request.statementDescriptor;let payout=await stripe.payouts.create(params);return{success:!0,providerPayoutId:payout.id,amount:payout.amount,currency:payout.currency?.toUpperCase(),status:payout.status,arrivalDate:payout.arrival_date?new Date(payout.arrival_date*1000).toISOString():void 0,method:payout.method,rawResponse:payout}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create payout",rawResponse:{error:err.message}}}},async getPayout(request){try{let payout=await stripe.payouts.retrieve(request.providerPayoutId);return{success:!0,providerPayoutId:payout.id,amount:payout.amount,currency:payout.currency?.toUpperCase(),status:payout.status,arrivalDate:payout.arrival_date?new Date(payout.arrival_date*1000).toISOString():void 0,method:payout.method,description:payout.description,destination:payout.destination,metadata:payout.metadata,failureCode:payout.failure_code,failureMessage:payout.failure_message,rawResponse:payout}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get payout",rawResponse:{error:err.message}}}},async cancelPayout(request){try{let payout=await stripe.payouts.cancel(request.providerPayoutId);return{success:!0,providerPayoutId:payout.id,status:payout.status,rawResponse:payout}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to cancel payout",rawResponse:{error:err.message}}}},async listPayouts(request){try{let params={};if(request.status)params.status=request.status;if(request.destination)params.destination=request.destination;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;if(request.arrivalDateGte||request.arrivalDateLte){let arrival={};if(request.arrivalDateGte)arrival.gte=request.arrivalDateGte;if(request.arrivalDateLte)arrival.lte=request.arrivalDateLte;params.arrival_date=arrival}let response=await stripe.payouts.list(params);return{success:!0,payouts:response.data.map((p)=>({providerPayoutId:p.id,amount:p.amount,currency:p.currency?.toUpperCase(),status:p.status,arrivalDate:p.arrival_date?new Date(p.arrival_date*1000).toISOString():void 0,method:p.method,description:p.description})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,payouts:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list payouts",rawResponse:{error:err.message}}}},async createTransfer(request){try{let params={amount:request.amount,currency:request.currency.toLowerCase(),destination:request.destination};if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.sourceTransaction)params.source_transaction=request.sourceTransaction;if(request.transferGroup)params.transfer_group=request.transferGroup;let transfer=await stripe.transfers.create(params);return{success:!0,providerTransferId:transfer.id,amount:transfer.amount,currency:transfer.currency?.toUpperCase(),destination:transfer.destination,rawResponse:transfer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create transfer",rawResponse:{error:err.message}}}},async listTransfers(request){try{let params={};if(request.destination)params.destination=request.destination;if(request.transferGroup)params.transfer_group=request.transferGroup;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.transfers.list(params);return{success:!0,transfers:response.data.map((t)=>({providerTransferId:t.id,amount:t.amount,currency:t.currency?.toUpperCase(),destination:t.destination,description:t.description,created:t.created?new Date(t.created*1000).toISOString():void 0})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,transfers:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list transfers",rawResponse:{error:err.message}}}}}},verifyStripeWebhook=(rawBody,signature,webhookSecret)=>{try{let StripeModule=__require("stripe");return{success:!0,event:new(StripeModule.default??StripeModule)("sk_dummy_for_webhook_verification").webhooks.constructEvent(rawBody,signature,webhookSecret)}}catch(error){return{success:!1,event:null,error:error instanceof Error?error.message:"Webhook verification failed"}}};var init_StripeProvider=__esm(()=>{init_Logger2()});var resolveEnvValue3=(value)=>{let envValue=process.env[value];if(envValue)return envValue;return value},createPaymentService=(config)=>{let paymentConfig=config.payment;if(!paymentConfig?.enabled)return null;let log2=logger.scoped("payment.init"),providerName=paymentConfig.provider;if(!providerName)return log2.warn("payment.enabled=true but no provider specified"),null;let providerConfig=null,provider=null,webhookSecret;switch(providerName){case"iyzico":{let iyzicoConf=paymentConfig.iyzico;if(!iyzicoConf)return log2.warn("payment.provider=iyzico but no iyzico config block"),null;let apiUrl=resolveEnvValue3(iyzicoConf.apiUrl),apiKey=resolveEnvValue3(iyzicoConf.apiKey),secretKey=resolveEnvValue3(iyzicoConf.secretKey);if(!apiUrl||!apiKey||!secretKey)return log2.warn("iyzico credentials missing \u2014 ensure env vars are set",{apiUrl:iyzicoConf.apiUrl,apiKeyEnv:iyzicoConf.apiKey,secretKeyEnv:iyzicoConf.secretKey}),null;providerConfig={name:"iyzico",apiUrl,apiKey,secretKey},provider=createIyzicoProvider(providerConfig);break}case"stripe":{let stripeConf=paymentConfig.stripe;if(!stripeConf)return log2.warn("payment.provider=stripe but no stripe config block"),null;let secretKey=resolveEnvValue3(stripeConf.secretKey),whSecret=resolveEnvValue3(stripeConf.webhookSecret);if(!secretKey)return log2.warn("Stripe secret key missing \u2014 ensure env var is set",{secretKeyEnv:stripeConf.secretKey}),null;if(!whSecret)log2.warn("Stripe webhook secret missing \u2014 webhook verification will fail",{webhookSecretEnv:stripeConf.webhookSecret});webhookSecret=whSecret,provider=createStripeProvider({secretKey,webhookSecret:whSecret,apiVersion:stripeConf.apiVersion,maxNetworkRetries:stripeConf.maxNetworkRetries,timeout:stripeConf.timeout});break}default:return log2.warn(`Unknown provider: ${providerName}`),null}if(!provider)return null;return log2.info(`Initialized provider: ${providerName}`),{provider:providerName,providerInstance:provider,webhookSecret}};var init_PaymentService=__esm(()=>{init_Logger2();init_IyzicoProvider();init_StripeProvider()});var exports_Payment={};__export(exports_Payment,{verifyStripeWebhook:()=>verifyStripeWebhook,resolveMarketplaceConfig:()=>resolveMarketplaceConfig,createStripeProvider:()=>createStripeProvider,createPaymentService:()=>createPaymentService,createMarketplaceServices:()=>createMarketplaceServices,createIyzicoProvider:()=>createIyzicoProvider,computeSplitBreakdown:()=>computeSplitBreakdown,MarketplaceService:()=>MarketplaceService,MarketplacePayoutService:()=>MarketplacePayoutService});var init_Payment=__esm(()=>{init_IyzicoProvider();init_Marketplace();init_PaymentService();init_StripeProvider()});var genLookup=(target)=>{let lookupTemp=typeof Uint8Array>"u"?[]:new Uint8Array(256),len=64;for(let i=0;i<64;i++)lookupTemp[target.charCodeAt(i)]=i;return lookupTemp},lookup,lookupUrl,base64UrlPattern,base64Pattern,base64,base64_default;var init_base64=__esm(()=>{lookup=genLookup("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),lookupUrl=genLookup("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),base64UrlPattern=/^[-A-Za-z0-9\-_]*$/,base64Pattern=/^[-A-Za-z0-9+/]*={0,3}$/,base64={};base64.toArrayBuffer=(data,urlMode)=>{let len=data.length,bufferLength=data.length*0.75,i,p=0,encoded1,encoded2,encoded3,encoded4;if(data[data.length-1]==="="){if(bufferLength--,data[data.length-2]==="=")bufferLength--}let arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer),target=urlMode?lookupUrl:lookup;for(i=0;i<len;i+=4)encoded1=target[data.charCodeAt(i)],encoded2=target[data.charCodeAt(i+1)],encoded3=target[data.charCodeAt(i+2)],encoded4=target[data.charCodeAt(i+3)],bytes[p++]=encoded1<<2|encoded2>>4,bytes[p++]=(encoded2&15)<<4|encoded3>>2,bytes[p++]=(encoded3&3)<<6|encoded4&63;return arraybuffer};base64.fromArrayBuffer=(arrBuf,urlMode)=>{let bytes=new Uint8Array(arrBuf),i,result="",len=bytes.length,target=urlMode?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(i=0;i<len;i+=3)result+=target[bytes[i]>>2],result+=target[(bytes[i]&3)<<4|bytes[i+1]>>4],result+=target[(bytes[i+1]&15)<<2|bytes[i+2]>>6],result+=target[bytes[i+2]&63];let remainder=len%3;if(remainder===2)result=result.substring(0,result.length-1)+(urlMode?"":"=");else if(remainder===1)result=result.substring(0,result.length-2)+(urlMode?"":"==");return result};base64.toString=(str3,urlMode)=>{return new TextDecoder().decode(base64.toArrayBuffer(str3,urlMode))};base64.fromString=(str3,urlMode)=>{return base64.fromArrayBuffer(new TextEncoder().encode(str3),urlMode)};base64.validate=(encoded,urlMode)=>{if(!(typeof encoded==="string"||encoded instanceof String))return!1;try{return urlMode?base64UrlPattern.test(encoded):base64Pattern.test(encoded)}catch(_e){return!1}};base64.base64=base64;base64_default=base64});var exports_isoBase64URL={};__export(exports_isoBase64URL,{trimPadding:()=>trimPadding,toUTF8String:()=>toUTF8String,toBuffer:()=>toBuffer,toBase64:()=>toBase64,isBase64URL:()=>isBase64URL,isBase64:()=>isBase64,fromUTF8String:()=>fromUTF8String,fromBuffer:()=>fromBuffer});function toBuffer(base64urlString,from="base64url"){let _buffer=base64_default.toArrayBuffer(base64urlString,from==="base64url");return new Uint8Array(_buffer)}function fromBuffer(buffer,to="base64url"){let _normalized=new Uint8Array(buffer);return base64_default.fromArrayBuffer(_normalized.buffer,to==="base64url")}function toBase64(base64urlString){let fromBase64Url=base64_default.toArrayBuffer(base64urlString,!0);return base64_default.fromArrayBuffer(fromBase64Url)}function fromUTF8String(utf8String){return base64_default.fromString(utf8String,!0)}function toUTF8String(base64urlString){return base64_default.toString(base64urlString,!0)}function isBase64(input){return base64_default.validate(input,!1)}function isBase64URL(input){return input=trimPadding(input),base64_default.validate(input,!0)}function trimPadding(input){return input.replace(/=/g,"")}var init_isoBase64URL=__esm(()=>{init_base64()});function decodeLength(data,argument,index){if(argument<24)return[argument,1];let remainingDataLength=data.byteLength-index-1,view=new DataView(data.buffer,index+1),output,bytes=0;switch(argument){case 24:{if(remainingDataLength>0)output=view.getUint8(0),bytes=2;break}case 25:{if(remainingDataLength>1)output=view.getUint16(0,!1),bytes=3;break}case 26:{if(remainingDataLength>3)output=view.getUint32(0,!1),bytes=5;break}case 27:{if(remainingDataLength>7){let bigOutput=view.getBigUint64(0,!1);if(bigOutput>=24n&&bigOutput<=Number.MAX_SAFE_INTEGER)return[Number(bigOutput),9]}break}}if(output&&output>=24)return[output,bytes];throw Error("Length not supported or not well formed")}function encodeLength(major,argument){let majorEncoded=major<<5;if(argument<0)throw Error("CBOR Data Item argument must not be negative");let bigintArgument;if(typeof argument=="number"){if(!Number.isInteger(argument))throw Error("CBOR Data Item argument must be an integer");bigintArgument=BigInt(argument)}else bigintArgument=argument;if(major==MAJOR_TYPE_NEGATIVE_INTEGER){if(bigintArgument==0n)throw Error("CBOR Data Item argument cannot be zero when negative");bigintArgument=bigintArgument-1n}if(bigintArgument>18446744073709551615n)throw Error("CBOR number out of range");let buffer=new Uint8Array(8);if(new DataView(buffer.buffer).setBigUint64(0,bigintArgument,!1),bigintArgument<=23)return[majorEncoded|buffer[7]];else if(bigintArgument<=255)return[majorEncoded|24,buffer[7]];else if(bigintArgument<=65535)return[majorEncoded|25,...buffer.slice(6)];else if(bigintArgument<=4294967295)return[majorEncoded|26,...buffer.slice(4)];else return[majorEncoded|27,...buffer]}var MAJOR_TYPE_UNSIGNED_INTEGER=0,MAJOR_TYPE_NEGATIVE_INTEGER=1,MAJOR_TYPE_BYTE_STRING=2,MAJOR_TYPE_TEXT_STRING=3,MAJOR_TYPE_ARRAY=4,MAJOR_TYPE_MAP=5,MAJOR_TYPE_TAG=6,MAJOR_TYPE_SIMPLE_OR_FLOAT=7;class CBORTag{constructor(tag,value){Object.defineProperty(this,"tagId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tagValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tagId=tag,this.tagValue=value}get tag(){return this.tagId}get value(){return this.tagValue}}function decodeUnsignedInteger(data,argument,index){return decodeLength(data,argument,index)}function decodeNegativeInteger(data,argument,index){let[value,length]=decodeUnsignedInteger(data,argument,index);return[-value-1,length]}function decodeByteString(data,argument,index){let[lengthValue,lengthConsumed]=decodeLength(data,argument,index),dataStartIndex=index+lengthConsumed;return[new Uint8Array(data.buffer.slice(dataStartIndex,dataStartIndex+lengthValue)),lengthConsumed+lengthValue]}function decodeString(data,argument,index){let[value,length]=decodeByteString(data,argument,index);return[TEXT_DECODER.decode(value),length]}function decodeArray(data,argument,index){if(argument===0)return[[],1];let[length,lengthConsumed]=decodeLength(data,argument,index),consumedLength=lengthConsumed,value=[];for(let i=0;i<length;i++){if(data.byteLength-index-consumedLength<=0)throw Error("array is not supported or well formed");let[decodedValue,consumed]=decodeNext(data,index+consumedLength);value.push(decodedValue),consumedLength+=consumed}return[value,consumedLength]}function decodeMap(data,argument,index){if(argument===0)return[new Map,1];let[length,lengthConsumed]=decodeLength(data,argument,index),consumedLength=lengthConsumed,result=new Map;for(let i=0;i<length;i++){let remainingDataLength=data.byteLength-index-consumedLength;if(remainingDataLength<=0)throw Error(MAP_ERROR);let[key,keyConsumed]=decodeNext(data,index+consumedLength);if(consumedLength+=keyConsumed,remainingDataLength-=keyConsumed,remainingDataLength<=0)throw Error(MAP_ERROR);if(typeof key!=="string"&&typeof key!=="number")throw Error(MAP_ERROR);if(result.has(key))throw Error(MAP_ERROR);let[value,valueConsumed]=decodeNext(data,index+consumedLength);consumedLength+=valueConsumed,result.set(key,value)}return[result,consumedLength]}function decodeFloat16(data,index){if(index+3>data.byteLength)throw Error("CBOR stream ended before end of Float 16");let result=data.getUint16(index+1,!1);if(result==31744)return[1/0,3];else if(result==32256)return[NaN,3];else if(result==64512)return[-1/0,3];throw Error("Float16 data is unsupported")}function decodeFloat32(data,index){if(index+5>data.byteLength)throw Error("CBOR stream ended before end of Float 32");return[data.getFloat32(index+1,!1),5]}function decodeFloat64(data,index){if(index+9>data.byteLength)throw Error("CBOR stream ended before end of Float 64");return[data.getFloat64(index+1,!1),9]}function decodeTag(data,argument,index){let[tag,tagBytes]=decodeLength(data,argument,index),[value,valueBytes]=decodeNext(data,index+tagBytes);return[new CBORTag(tag,value),tagBytes+valueBytes]}function decodeNext(data,index){if(index>=data.byteLength)throw Error("CBOR stream ended before tag value");let byte=data.getUint8(index),majorType=byte>>5,argument=byte&31;switch(majorType){case MAJOR_TYPE_UNSIGNED_INTEGER:return decodeUnsignedInteger(data,argument,index);case MAJOR_TYPE_NEGATIVE_INTEGER:return decodeNegativeInteger(data,argument,index);case MAJOR_TYPE_BYTE_STRING:return decodeByteString(data,argument,index);case MAJOR_TYPE_TEXT_STRING:return decodeString(data,argument,index);case MAJOR_TYPE_ARRAY:return decodeArray(data,argument,index);case MAJOR_TYPE_MAP:return decodeMap(data,argument,index);case MAJOR_TYPE_TAG:return decodeTag(data,argument,index);case MAJOR_TYPE_SIMPLE_OR_FLOAT:switch(argument){case 20:return[!1,1];case 21:return[!0,1];case 22:return[null,1];case 23:return[void 0,1];case 25:return decodeFloat16(data,index);case 26:return decodeFloat32(data,index);case 27:return decodeFloat64(data,index)}}throw Error(`Unsupported or not well formed at ${index}`)}function encodeSimple(data){if(data===!0)return 245;else if(data===!1)return 244;else if(data===null)return 246;return 247}function encodeFloat(data){if(Math.fround(data)==data||!Number.isFinite(data)||Number.isNaN(data)){let output=new Uint8Array(5);return output[0]=250,new DataView(output.buffer).setFloat32(1,data,!1),output}else{let output=new Uint8Array(9);return output[0]=251,new DataView(output.buffer).setFloat64(1,data,!1),output}}function encodeNumber(data){if(typeof data=="number"){if(Number.isSafeInteger(data))if(data<0)return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER,Math.abs(data));else return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER,data);return[encodeFloat(data)]}else if(data<0n)return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER,data*-1n);else return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER,data)}function encodeString(data,output){output.push(...encodeLength(MAJOR_TYPE_TEXT_STRING,data.length)),output.push(ENCODER.encode(data))}function encodeBytes(data,output){output.push(...encodeLength(MAJOR_TYPE_BYTE_STRING,data.length)),output.push(data)}function encodeArray(data,output){output.push(...encodeLength(MAJOR_TYPE_ARRAY,data.length));for(let element of data)encodePartialCBOR(element,output)}function encodeMap(data,output){output.push(new Uint8Array(encodeLength(MAJOR_TYPE_MAP,data.size)));for(let[key,value]of data.entries())encodePartialCBOR(key,output),encodePartialCBOR(value,output)}function encodeTag(tag,output){output.push(...encodeLength(MAJOR_TYPE_TAG,tag.tag)),encodePartialCBOR(tag.value,output)}function encodePartialCBOR(data,output){if(typeof data=="boolean"||data===null||data==null){output.push(encodeSimple(data));return}if(typeof data=="number"||typeof data=="bigint"){output.push(...encodeNumber(data));return}if(typeof data=="string"){encodeString(data,output);return}if(data instanceof Uint8Array){encodeBytes(data,output);return}if(Array.isArray(data)){encodeArray(data,output);return}if(data instanceof Map){encodeMap(data,output);return}if(data instanceof CBORTag){encodeTag(data,output);return}throw Error("Not implemented")}function decodePartialCBOR(data,index){if(data.byteLength===0||data.byteLength<=index||index<0)throw Error("No data");if(data instanceof Uint8Array)return decodeNext(new DataView(data.buffer),index);else if(data instanceof ArrayBuffer)return decodeNext(new DataView(data),index);return decodeNext(data,index)}function encodeCBOR(data){let results=[];encodePartialCBOR(data,results);let length=0;for(let result of results)if(typeof result=="number")length+=1;else length+=result.length;let output=new Uint8Array(length),index=0;for(let result of results)if(typeof result=="number")output[index]=result,index+=1;else output.set(result,index),index+=result.length;return output}var TEXT_DECODER,MAP_ERROR="Map is not supported or well formed",ENCODER;var init_cbor=__esm(()=>{TEXT_DECODER=new TextDecoder;ENCODER=new TextEncoder});var init_esm=__esm(()=>{init_cbor()});var exports_isoCBOR={};__export(exports_isoCBOR,{encode:()=>encode,decodeFirst:()=>decodeFirst});function decodeFirst(input){let _input=new Uint8Array(input),decoded=decodePartialCBOR(_input,0),[first]=decoded;return first}function encode(input){return encodeCBOR(input)}var init_isoCBOR=__esm(()=>{init_esm()});function isCOSEPublicKeyOKP(cosePublicKey){let kty=cosePublicKey.get(COSEKEYS.kty);return isCOSEKty(kty)&&kty===COSEKTY.OKP}function isCOSEPublicKeyEC2(cosePublicKey){let kty=cosePublicKey.get(COSEKEYS.kty);return isCOSEKty(kty)&&kty===COSEKTY.EC2}function isCOSEPublicKeyRSA(cosePublicKey){let kty=cosePublicKey.get(COSEKEYS.kty);return isCOSEKty(kty)&&kty===COSEKTY.RSA}function isCOSEKty(kty){return Object.values(COSEKTY).indexOf(kty)>=0}function isCOSECrv(crv){return Object.values(COSECRV).indexOf(crv)>=0}function isCOSEAlg(alg){return Object.values(COSEALG).indexOf(alg)>=0}var COSEKEYS,COSEKTY,COSECRV,COSEALG;var init_cose=__esm(()=>{(function(COSEKEYS2){COSEKEYS2[COSEKEYS2.kty=1]="kty",COSEKEYS2[COSEKEYS2.alg=3]="alg",COSEKEYS2[COSEKEYS2.crv=-1]="crv",COSEKEYS2[COSEKEYS2.x=-2]="x",COSEKEYS2[COSEKEYS2.y=-3]="y",COSEKEYS2[COSEKEYS2.n=-1]="n",COSEKEYS2[COSEKEYS2.e=-2]="e"})(COSEKEYS||(COSEKEYS={}));(function(COSEKTY2){COSEKTY2[COSEKTY2.OKP=1]="OKP",COSEKTY2[COSEKTY2.EC2=2]="EC2",COSEKTY2[COSEKTY2.RSA=3]="RSA"})(COSEKTY||(COSEKTY={}));(function(COSECRV2){COSECRV2[COSECRV2.P256=1]="P256",COSECRV2[COSECRV2.P384=2]="P384",COSECRV2[COSECRV2.P521=3]="P521",COSECRV2[COSECRV2.ED25519=6]="ED25519",COSECRV2[COSECRV2.SECP256K1=8]="SECP256K1"})(COSECRV||(COSECRV={}));(function(COSEALG2){COSEALG2[COSEALG2.ES256=-7]="ES256",COSEALG2[COSEALG2.EdDSA=-8]="EdDSA",COSEALG2[COSEALG2.ES384=-35]="ES384",COSEALG2[COSEALG2.ES512=-36]="ES512",COSEALG2[COSEALG2.PS256=-37]="PS256",COSEALG2[COSEALG2.PS384=-38]="PS384",COSEALG2[COSEALG2.PS512=-39]="PS512",COSEALG2[COSEALG2.ES256K=-47]="ES256K",COSEALG2[COSEALG2.RS256=-257]="RS256",COSEALG2[COSEALG2.RS384=-258]="RS384",COSEALG2[COSEALG2.RS512=-259]="RS512",COSEALG2[COSEALG2.RS1=-65535]="RS1"})(COSEALG||(COSEALG={}))});function mapCoseAlgToWebCryptoAlg(alg){if([COSEALG.RS1].indexOf(alg)>=0)return"SHA-1";else if([COSEALG.ES256,COSEALG.PS256,COSEALG.RS256].indexOf(alg)>=0)return"SHA-256";else if([COSEALG.ES384,COSEALG.PS384,COSEALG.RS384].indexOf(alg)>=0)return"SHA-384";else if([COSEALG.ES512,COSEALG.PS512,COSEALG.RS512,COSEALG.EdDSA].indexOf(alg)>=0)return"SHA-512";throw Error(`Could not map COSE alg value of ${alg} to a WebCrypto alg`)}var init_mapCoseAlgToWebCryptoAlg=__esm(()=>{init_cose()});function getWebCrypto(){return new Promise((resolve2,reject)=>{if(webCrypto)return resolve2(webCrypto);let _globalThisCrypto=_getWebCryptoInternals.stubThisGlobalThisCrypto();if(_globalThisCrypto)return webCrypto=_globalThisCrypto,resolve2(webCrypto);return reject(new MissingWebCrypto)})}var webCrypto=void 0,MissingWebCrypto,_getWebCryptoInternals;var init_getWebCrypto=__esm(()=>{MissingWebCrypto=class MissingWebCrypto extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}};_getWebCryptoInternals={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(newCrypto)=>{webCrypto=newCrypto}}});async function digest(data,algorithm){let WebCrypto=await getWebCrypto(),subtleAlgorithm=mapCoseAlgToWebCryptoAlg(algorithm),hashed=await WebCrypto.subtle.digest(subtleAlgorithm,data);return new Uint8Array(hashed)}var init_digest=__esm(()=>{init_mapCoseAlgToWebCryptoAlg();init_getWebCrypto()});async function getRandomValues(array){return(await getWebCrypto()).getRandomValues(array),array}var init_getRandomValues=__esm(()=>{init_getWebCrypto()});async function importKey(opts){let WebCrypto=await getWebCrypto(),{keyData,algorithm}=opts;return WebCrypto.subtle.importKey("jwk",keyData,algorithm,!1,["verify"])}var init_importKey=__esm(()=>{init_getWebCrypto()});async function verifyEC2(opts){let{cosePublicKey,signature,data,shaHashOverride}=opts,WebCrypto=await getWebCrypto(),alg=cosePublicKey.get(COSEKEYS.alg),crv=cosePublicKey.get(COSEKEYS.crv),x=cosePublicKey.get(COSEKEYS.x),y=cosePublicKey.get(COSEKEYS.y);if(!alg)throw Error("Public key was missing alg (EC2)");if(!crv)throw Error("Public key was missing crv (EC2)");if(!x)throw Error("Public key was missing x (EC2)");if(!y)throw Error("Public key was missing y (EC2)");let _crv;if(crv===COSECRV.P256)_crv="P-256";else if(crv===COSECRV.P384)_crv="P-384";else if(crv===COSECRV.P521)_crv="P-521";else throw Error(`Unexpected COSE crv value of ${crv} (EC2)`);let keyData={kty:"EC",crv:_crv,x:exports_isoBase64URL.fromBuffer(x),y:exports_isoBase64URL.fromBuffer(y),ext:!1},key=await importKey({keyData,algorithm:{name:"ECDSA",namedCurve:_crv}}),subtleAlg=mapCoseAlgToWebCryptoAlg(alg);if(shaHashOverride)subtleAlg=mapCoseAlgToWebCryptoAlg(shaHashOverride);let verifyAlgorithm={name:"ECDSA",hash:{name:subtleAlg}};return WebCrypto.subtle.verify(verifyAlgorithm,key,signature,data)}var init_verifyEC2=__esm(()=>{init_cose();init_mapCoseAlgToWebCryptoAlg();init_importKey();init_iso();init_getWebCrypto()});function mapCoseAlgToWebCryptoKeyAlgName(alg){if([COSEALG.EdDSA].indexOf(alg)>=0)return"Ed25519";else if([COSEALG.ES256,COSEALG.ES384,COSEALG.ES512,COSEALG.ES256K].indexOf(alg)>=0)return"ECDSA";else if([COSEALG.RS256,COSEALG.RS384,COSEALG.RS512,COSEALG.RS1].indexOf(alg)>=0)return"RSASSA-PKCS1-v1_5";else if([COSEALG.PS256,COSEALG.PS384,COSEALG.PS512].indexOf(alg)>=0)return"RSA-PSS";throw Error(`Could not map COSE alg value of ${alg} to a WebCrypto key alg name`)}var init_mapCoseAlgToWebCryptoKeyAlgName=__esm(()=>{init_cose()});async function verifyRSA(opts){let{cosePublicKey,signature,data,shaHashOverride}=opts,WebCrypto=await getWebCrypto(),alg=cosePublicKey.get(COSEKEYS.alg),n=cosePublicKey.get(COSEKEYS.n),e=cosePublicKey.get(COSEKEYS.e);if(!alg)throw Error("Public key was missing alg (RSA)");if(!isCOSEAlg(alg))throw Error(`Public key had invalid alg ${alg} (RSA)`);if(!n)throw Error("Public key was missing n (RSA)");if(!e)throw Error("Public key was missing e (RSA)");let keyData={kty:"RSA",alg:"",n:exports_isoBase64URL.fromBuffer(n),e:exports_isoBase64URL.fromBuffer(e),ext:!1},keyAlgorithm={name:mapCoseAlgToWebCryptoKeyAlgName(alg),hash:{name:mapCoseAlgToWebCryptoAlg(alg)}},verifyAlgorithm={name:mapCoseAlgToWebCryptoKeyAlgName(alg)};if(shaHashOverride)keyAlgorithm.hash.name=mapCoseAlgToWebCryptoAlg(shaHashOverride);if(keyAlgorithm.name==="RSASSA-PKCS1-v1_5"){if(keyAlgorithm.hash.name==="SHA-256")keyData.alg="RS256";else if(keyAlgorithm.hash.name==="SHA-384")keyData.alg="RS384";else if(keyAlgorithm.hash.name==="SHA-512")keyData.alg="RS512";else if(keyAlgorithm.hash.name==="SHA-1")keyData.alg="RS1"}else if(keyAlgorithm.name==="RSA-PSS"){let saltLength=0;if(keyAlgorithm.hash.name==="SHA-256")keyData.alg="PS256",saltLength=32;else if(keyAlgorithm.hash.name==="SHA-384")keyData.alg="PS384",saltLength=48;else if(keyAlgorithm.hash.name==="SHA-512")keyData.alg="PS512",saltLength=64;verifyAlgorithm.saltLength=saltLength}else throw Error(`Unexpected RSA key algorithm ${alg} (${keyAlgorithm.name})`);let key=await importKey({keyData,algorithm:keyAlgorithm});return WebCrypto.subtle.verify(verifyAlgorithm,key,signature,data)}var init_verifyRSA=__esm(()=>{init_cose();init_mapCoseAlgToWebCryptoAlg();init_importKey();init_iso();init_mapCoseAlgToWebCryptoKeyAlgName();init_getWebCrypto()});function convertAAGUIDToString(aaguid){let hex=exports_isoUint8Array.toHex(aaguid);return[hex.slice(0,8),hex.slice(8,12),hex.slice(12,16),hex.slice(16,20),hex.slice(20,32)].join("-")}var init_convertAAGUIDToString=__esm(()=>{init_iso()});function convertCertBufferToPEM(certBuffer){let b64cert;if(typeof certBuffer==="string")if(exports_isoBase64URL.isBase64URL(certBuffer))b64cert=exports_isoBase64URL.toBase64(certBuffer);else if(exports_isoBase64URL.isBase64(certBuffer))b64cert=certBuffer;else throw Error("Certificate is not a valid base64 or base64url string");else b64cert=exports_isoBase64URL.fromBuffer(certBuffer,"base64");let PEMKey="";for(let i=0;i<Math.ceil(b64cert.length/64);i+=1){let start=64*i;PEMKey+=`${b64cert.substr(start,64)}
89
+ ${params.body}`:`*${params.title}*`,timeoutMs=telegramConfig?.timeoutMs??DEFAULT_DELIVERY_TIMEOUT_MS;try{let response=await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:chatId,text,parse_mode:"Markdown"}),signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){let errBody=await response.text().catch(()=>"");this.logger.error(`[Notification] Telegram delivery failed (${response.status}): ${errBody.slice(0,300)}`);return}this.logger.debug(`[Notification] Telegram notification sent: ${params.title}`)}catch(error){this.logger.error(`[Notification] Telegram delivery error: ${error.message}`)}}async sendWebhookNotification(params){let webhookConfig=this.config.channels?.webhook,url=resolveEnvValue2(webhookConfig?.url);if(!url){this.logger.warn("[Notification] Webhook channel enabled but url is missing or unresolved \u2014 skipping delivery");return}let headers={"Content-Type":"application/json"};for(let[key,value]of Object.entries(webhookConfig?.headers||{})){let resolved=resolveEnvValue2(value);if(resolved)headers[key]=resolved}let timeoutMs=webhookConfig?.timeoutMs??DEFAULT_DELIVERY_TIMEOUT_MS;try{let response=await fetch(url,{method:"POST",headers,body:JSON.stringify({user_id:params.user_id,title:params.title,body:params.body??null,entity_name:params.entity_name??null,entity_id:params.entity_id??null,type:params.type??"system",source:params.source??null,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){let errBody=await response.text().catch(()=>"");this.logger.error(`[Notification] Webhook delivery failed (${response.status}): ${errBody.slice(0,300)}`);return}this.logger.debug(`[Notification] Webhook notification sent: ${params.title}`)}catch(error){this.logger.error(`[Notification] Webhook delivery error: ${error.message}`)}}async sendEmailNotification(userId,title,body){if(!this.emailService?.isAvailable()){this.logger.warn("[Notification] Email service not available for email notification");return}let usersTable=this.getTable("users");if(!usersTable){this.logger.warn("[Notification] users table not found");return}let user=(await this.db.select({email:this.getCol(usersTable,"email")}).from(usersTable).where(eq9(this.getCol(usersTable,"id"),userId)).limit(1))[0];if(!user?.email){this.logger.warn(`[Notification] No email found for user ${userId}`);return}await this.emailService.sendEmail({to:user.email,subject:title,html:body||title}),this.logger.debug(`[Notification] Email notification sent to ${user.email}: ${title}`)}async getNotifications(userId,options){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return[];let conditions=[eq9(this.getCol(notificationsTable,"userId"),userId)];if(options?.type)conditions.push(eq9(this.getCol(notificationsTable,"type"),options.type));return(await this.db.select().from(notificationsTable).where(and4(...conditions)).orderBy(desc(this.getCol(notificationsTable,"createdAt"))).limit(options?.limit||50).offset(options?.offset||0)).map((r)=>fromCamel(r))}async getUnseenCount(userId){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return 0;return(await this.db.select().from(notificationsTable).where(and4(eq9(this.getCol(notificationsTable,"userId"),userId),eq9(this.getCol(notificationsTable,"isSeen"),!1)))).length}async markAsSeen(notificationId,userId){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return!1;return await this.db.update(notificationsTable).set(toCamel({is_seen:!0,seen_at:new Date})).where(and4(eq9(this.getCol(notificationsTable,"id"),notificationId),eq9(this.getCol(notificationsTable,"userId"),userId))),!0}async markAllAsSeen(userId){let notificationsTable=this.getTable("notifications");if(!notificationsTable)return 0;return(await this.db.update(notificationsTable).set(toCamel({is_seen:!0,seen_at:new Date})).where(and4(eq9(this.getCol(notificationsTable,"userId"),userId),eq9(this.getCol(notificationsTable,"isSeen"),!1))).returning()).length}}var DEFAULT_DELIVERY_TIMEOUT_MS=1e4;var init_Notification=__esm(()=>{init_types4()});function buildGenericAuthUrl(config,state){if(!config.authorizationUrl)throw Error("Generic OAuth provider requires authorizationUrl");let scopes2=config.scopes??[],params=new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,response_type:"code",state,...scopes2.length>0?{scope:scopes2.join(" ")}:{},...config.extraAuthParams});return`${config.authorizationUrl}?${params.toString()}`}async function exchangeGenericCode(code,config){if(!config.tokenUrl)throw Error("Generic OAuth provider requires tokenUrl");let tokenRes=await fetch(config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri,grant_type:"authorization_code"}).toString()});if(!tokenRes.ok){let err=await tokenRes.text();throw Error(`Generic OAuth token exchange failed: ${err}`)}let tokenData=await tokenRes.json();if(tokenData.error)throw Error(`OAuth error: ${tokenData.error_description||tokenData.error}`);let tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope};if(!config.userInfoUrl)return{profile:{providerAccountId:tokenData.access_token,rawProfile:tokenData},tokens};let userRes=await fetch(config.userInfoUrl,{headers:{Authorization:`Bearer ${tokenData.access_token}`}});if(!userRes.ok)throw Error("Failed to fetch user info from generic OAuth provider");let rawProfile=await userRes.json();return{profile:{providerAccountId:rawProfile.id??rawProfile.sub??rawProfile.user_id??tokenData.access_token,email:rawProfile.email,name:rawProfile.name??rawProfile.display_name??rawProfile.username,avatarUrl:rawProfile.avatar_url??rawProfile.picture??rawProfile.photo,rawProfile},tokens}}function buildGithubAuthUrl(config,state){let scopes2=config.scopes??["read:user","user:email"];return`https://github.com/login/oauth/authorize?${new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,scope:scopes2.join(" "),state,...config.extraAuthParams}).toString()}`}async function exchangeGithubCode(code,config){let tokenRes=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri}).toString()});if(!tokenRes.ok){let err=await tokenRes.text();throw Error(`GitHub token exchange failed: ${err}`)}let tokenData=await tokenRes.json();if(tokenData.error)throw Error(`GitHub OAuth error: ${tokenData.error_description||tokenData.error}`);let tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope},userRes=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${tokenData.access_token}`,Accept:"application/vnd.github+json"}});if(!userRes.ok)throw Error("Failed to fetch GitHub user info");let rawProfile=await userRes.json(),email=rawProfile.email;if(!email)try{let emailsRes=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${tokenData.access_token}`,Accept:"application/vnd.github+json"}});if(emailsRes.ok){let emails=await emailsRes.json();email=emails.find((e)=>e.primary&&e.verified)?.email??emails[0]?.email}}catch{}return{profile:{providerAccountId:String(rawProfile.id),email,name:rawProfile.name??rawProfile.login,avatarUrl:rawProfile.avatar_url,rawProfile},tokens}}function buildGoogleAuthUrl(config,state){let scopes2=config.scopes??["openid","email","profile"];return`https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,response_type:"code",scope:scopes2.join(" "),state,access_type:"offline",prompt:"select_account",...config.extraAuthParams}).toString()}`}async function exchangeGoogleCode(code,config){let tokenRes=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri,grant_type:"authorization_code"}).toString()});if(!tokenRes.ok){let err=await tokenRes.text();throw Error(`Google token exchange failed: ${err}`)}let tokenData=await tokenRes.json(),tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope},userRes=await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${tokenData.access_token}`}});if(!userRes.ok)throw Error("Failed to fetch Google user info");let rawProfile=await userRes.json();return{profile:{providerAccountId:rawProfile.sub,email:rawProfile.email,name:rawProfile.name,avatarUrl:rawProfile.picture,rawProfile},tokens}}function getMicrosoftBaseUrl(config){return`https://login.microsoftonline.com/${config.tenantId??"common"}/oauth2/v2.0`}function describeFetchError(err){if(err&&typeof err==="object"){let e=err,cause=e.cause,parts=[];if(e.message)parts.push(`message=${e.message}`);if(e.code)parts.push(`code=${e.code}`);if(cause?.code)parts.push(`cause.code=${cause.code}`);if(cause?.name)parts.push(`cause.name=${cause.name}`);if(cause?.message)parts.push(`cause.message=${cause.message}`);return parts.join(" | ")||String(err)}return String(err)}function buildMicrosoftAuthUrl(config,state){let scopes2=config.scopes??["openid","email","profile","User.Read"],params=new URLSearchParams({client_id:config.clientId,redirect_uri:config.redirectUri,response_type:"code",scope:scopes2.join(" "),state,response_mode:"query",prompt:"select_account",...config.extraAuthParams});return`${getMicrosoftBaseUrl(config)}/authorize?${params.toString()}`}async function exchangeMicrosoftCode(code,config){let tokenUrl=`${getMicrosoftBaseUrl(config)}/token`,tokenRes;try{tokenRes=await fetch(tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code,client_id:config.clientId,client_secret:config.clientSecret,redirect_uri:config.redirectUri,grant_type:"authorization_code"}).toString()})}catch(err){throw Error(`Microsoft token endpoint fetch failed | url=${tokenUrl} | redirect_uri=${config.redirectUri} | ${describeFetchError(err)}`,{cause:err})}if(!tokenRes.ok){let body=await tokenRes.text().catch(()=>"<unable to read body>");throw Error(`Microsoft token exchange failed | status=${tokenRes.status} | url=${tokenUrl} | redirect_uri=${config.redirectUri} | body=${body}`)}let tokenData=await tokenRes.json();if(tokenData.error)throw Error(`Microsoft OAuth error: ${tokenData.error_description||tokenData.error} | url=${tokenUrl}`);let tokens={accessToken:tokenData.access_token,refreshToken:tokenData.refresh_token,expiresAt:tokenData.expires_in?new Date(Date.now()+tokenData.expires_in*1000):void 0,scope:tokenData.scope},userRes;try{userRes=await fetch("https://graph.microsoft.com/v1.0/me",{headers:{Authorization:`Bearer ${tokenData.access_token}`}})}catch(err){throw Error(`Microsoft userinfo fetch failed | url=https://graph.microsoft.com/v1.0/me | ${describeFetchError(err)}`,{cause:err})}if(!userRes.ok){let body=await userRes.text().catch(()=>"<unable to read body>");throw Error(`Microsoft userinfo failed | status=${userRes.status} | url=https://graph.microsoft.com/v1.0/me | body=${body}`)}let rawProfile=await userRes.json();return{profile:{providerAccountId:rawProfile.id,email:rawProfile.mail??rawProfile.userPrincipalName,name:rawProfile.displayName,avatarUrl:void 0,rawProfile},tokens}}import{randomBytes as randomBytes2}from"crypto";class OAuthService{config;stateStore=new Map;cleanupInterval=null;constructor(config){this.config=config;let ttl=(config.stateTtlSeconds??600)*1000;this.cleanupInterval=setInterval(()=>{let now=Date.now();for(let[key,val]of this.stateStore.entries())if(val.expiresAt<now)this.stateStore.delete(key)},ttl)}stop(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isProviderEnabled(provider){return!!(this.config.enabled&&this.config.providers[provider])}getEnabledProviders(){if(!this.config.enabled)return[];return Object.keys(this.config.providers)}buildAuthorizationUrl(provider,linkUserId,redirectUrl){let providerConfig=this.config.providers[provider];if(!providerConfig)throw Error(`OAuth provider "${provider}" is not configured`);let statePayload={provider,linkUserId,redirectUrl,createdAt:Date.now()},state=randomBytes2(32).toString("hex"),ttl=(this.config.stateTtlSeconds??600)*1000;switch(this.stateStore.set(state,{payload:statePayload,expiresAt:Date.now()+ttl}),provider){case"google":return buildGoogleAuthUrl(providerConfig,state);case"github":return buildGithubAuthUrl(providerConfig,state);case"microsoft":return buildMicrosoftAuthUrl(providerConfig,state);default:return buildGenericAuthUrl(providerConfig,state)}}consumeState(state){let entry=this.stateStore.get(state);if(!entry)return null;if(entry.expiresAt<Date.now())return this.stateStore.delete(state),null;return this.stateStore.delete(state),entry.payload}async exchangeCode(provider,code){let providerConfig=this.config.providers[provider];if(!providerConfig)throw Error(`OAuth provider "${provider}" is not configured`);switch(provider){case"google":return exchangeGoogleCode(code,providerConfig);case"github":return exchangeGithubCode(code,providerConfig);case"microsoft":return exchangeMicrosoftCode(code,providerConfig);default:return exchangeGenericCode(code,providerConfig)}}get allowAccountLinking(){return this.config.allowAccountLinking??!0}get autoCreateUser(){return this.config.autoCreateUser??!0}get successRedirectUrl(){return this.config.successRedirectUrl??"/"}get errorRedirectUrl(){return this.config.errorRedirectUrl??"/login"}get sendInviteOnCreate(){return this.config.sendInviteOnCreate??!1}get basePath(){return this.config.basePath??"/auth/oauth"}}var init_OAuthService=()=>{};var init_OAuth=__esm(()=>{init_OAuthService()});class RateLimiter{redis;logger;config;constructor(deps){this.redis=deps.redis,this.logger=deps.logger,this.config=this.mergeConfig(deps.config)}mergeConfig(config){return{enabled:config.enabled??DEFAULT_CONFIG4.enabled,strategy:config.strategy??DEFAULT_CONFIG4.strategy,keyPrefix:config.keyPrefix??DEFAULT_CONFIG4.keyPrefix,authRoutes:{window:config.authRoutes?.window??DEFAULT_CONFIG4.authRoutes.window,max:config.authRoutes?.max??DEFAULT_CONFIG4.authRoutes.max,login:{window:config.authRoutes?.login?.window??DEFAULT_AUTH_LOGIN.window,max:config.authRoutes?.login?.max??DEFAULT_AUTH_LOGIN.max,blockDuration:config.authRoutes?.login?.blockDuration??DEFAULT_AUTH_LOGIN.blockDuration},register:{window:config.authRoutes?.register?.window??DEFAULT_AUTH_REGISTER.window,max:config.authRoutes?.register?.max??DEFAULT_AUTH_REGISTER.max,blockDuration:config.authRoutes?.register?.blockDuration??DEFAULT_AUTH_REGISTER.blockDuration},passwordReset:{window:config.authRoutes?.passwordReset?.window??DEFAULT_AUTH_PASSWORD_RESET.window,max:config.authRoutes?.passwordReset?.max??DEFAULT_AUTH_PASSWORD_RESET.max,blockDuration:config.authRoutes?.passwordReset?.blockDuration??DEFAULT_AUTH_PASSWORD_RESET.blockDuration},magicLink:{window:config.authRoutes?.magicLink?.window??DEFAULT_AUTH_MAGIC_LINK.window,max:config.authRoutes?.magicLink?.max??DEFAULT_AUTH_MAGIC_LINK.max,blockDuration:config.authRoutes?.magicLink?.blockDuration??DEFAULT_AUTH_MAGIC_LINK.blockDuration}},publicRoutes:{window:config.publicRoutes?.window??DEFAULT_CONFIG4.publicRoutes.window,max:config.publicRoutes?.max??DEFAULT_CONFIG4.publicRoutes.max},privateRoutes:{window:config.privateRoutes?.window??DEFAULT_CONFIG4.privateRoutes.window,max:config.privateRoutes?.max??DEFAULT_CONFIG4.privateRoutes.max},byIp:config.byIp??DEFAULT_CONFIG4.byIp,byUserId:config.byUserId??DEFAULT_CONFIG4.byUserId,byEndpoint:config.byEndpoint??DEFAULT_CONFIG4.byEndpoint,skipSuccessfulRequests:config.skipSuccessfulRequests??DEFAULT_CONFIG4.skipSuccessfulRequests,headers:{remaining:config.headers?.remaining??DEFAULT_CONFIG4.headers.remaining,reset:config.headers?.reset??DEFAULT_CONFIG4.headers.reset,limit:config.headers?.limit??DEFAULT_CONFIG4.headers.limit},whitelist:config.whitelist??DEFAULT_CONFIG4.whitelist,blacklist:config.blacklist??DEFAULT_CONFIG4.blacklist}}parseTimeToMs(time){let match=time.match(/^(\d+)(ms|s|m|h|d)$/);if(!match||!match[1]||!match[2])return 60000;let value=parseInt(match[1],10);switch(match[2]){case"ms":return value;case"s":return value*1000;case"m":return value*60*1000;case"h":return value*60*60*1000;case"d":return value*24*60*60*1000;default:return 60000}}buildKey(params){let parts=[this.config.keyPrefix,params.category];if(params.authType&&params.authType!=="other")parts.push(params.authType);if(this.config.byIp&&params.ip)parts.push(`ip:${params.ip}`);if(this.config.byUserId&&params.userId)parts.push(`user:${params.userId}`);if(this.config.byEndpoint&&params.endpoint)parts.push(`ep:${params.endpoint.replace(/\//g,"_")}`);return parts.join(":")}getLimits(category,authType){if(category==="auth"){if(authType&&authType!=="other"){let authConfig=this.config.authRoutes[authType];if(authConfig)return authConfig}return{window:this.config.authRoutes.window,max:this.config.authRoutes.max}}if(category==="public")return this.config.publicRoutes;return this.config.privateRoutes}isWhitelisted(ip){return this.config.whitelist.some((pattern)=>{if(pattern.includes("*"))return new RegExp(`^${pattern.replace(/\*/g,".*")}$`).test(ip);return pattern===ip})}isBlacklisted(ip){return this.config.blacklist.some((pattern)=>{if(pattern.includes("*"))return new RegExp(`^${pattern.replace(/\*/g,".*")}$`).test(ip);return pattern===ip})}async readRedis(key){let result=await this.redis.read(key);if(result.success)return result.data;return null}async check(params){if(!this.config.enabled)return{allowed:!0,remaining:-1,resetAt:0,limit:-1};if(this.isWhitelisted(params.ip))return{allowed:!0,remaining:-1,resetAt:0,limit:-1};if(this.isBlacklisted(params.ip))return this.logger.warn(`[RateLimit] Blacklisted IP: ${params.ip}`),{allowed:!1,remaining:0,resetAt:Date.now()+86400000,limit:0,retryAfter:86400};let key=this.buildKey(params),limits=this.getLimits(params.category,params.authType),windowMs=this.parseTimeToMs(limits.window),blockKey=`${key}:blocked`,isBlocked=await this.readRedis(blockKey);if(isBlocked&&isBlocked.until>Date.now()){let retryAfter=Math.ceil((isBlocked.until-Date.now())/1000);return this.logger.warn(`[RateLimit] Blocked: ${key}, retry after ${retryAfter}s`),{allowed:!1,remaining:0,resetAt:isBlocked.until,limit:limits.max,retryAfter}}if(this.config.strategy==="sliding-window")return this.slidingWindowCheck(key,limits.max,windowMs,limits.blockDuration);if(this.config.strategy==="fixed-window")return this.fixedWindowCheck(key,limits.max,windowMs,limits.blockDuration);return this.tokenBucketCheck(key,limits.max,windowMs)}async slidingWindowCheck(key,max,windowMs,blockDuration){let now=Date.now(),windowStart=now-windowMs,dataKey=`${key}:sw`,timestamps=(await this.readRedis(dataKey))?.timestamps||[];timestamps=timestamps.filter((ts)=>ts>windowStart);let count=timestamps.length,firstTimestamp=timestamps[0],resetAt=firstTimestamp!==void 0?firstTimestamp+windowMs:now+windowMs;if(count>=max){if(blockDuration){let blockMs=this.parseTimeToMs(blockDuration);await this.redis.create(`${key}:blocked`,{until:now+blockMs},Math.ceil(blockMs/1000))}return{allowed:!1,remaining:0,resetAt,limit:max,retryAfter:Math.ceil((resetAt-now)/1000)}}return timestamps.push(now),await this.redis.create(dataKey,{timestamps},Math.ceil(windowMs/1000)+1),{allowed:!0,remaining:max-timestamps.length,resetAt,limit:max}}async fixedWindowCheck(key,max,windowMs,blockDuration){let now=Date.now(),windowId=Math.floor(now/windowMs),dataKey=`${key}:fw:${windowId}`,resetAt=(windowId+1)*windowMs,count=(await this.readRedis(dataKey))?.count||0;if(count>=max){if(blockDuration){let blockMs=this.parseTimeToMs(blockDuration);await this.redis.create(`${key}:blocked`,{until:now+blockMs},Math.ceil(blockMs/1000))}return{allowed:!1,remaining:0,resetAt,limit:max,retryAfter:Math.ceil((resetAt-now)/1000)}}return await this.redis.create(dataKey,{count:count+1},Math.ceil(windowMs/1000)+1),{allowed:!0,remaining:max-(count+1),resetAt,limit:max}}async tokenBucketCheck(key,max,windowMs){let now=Date.now(),refillRate=max/windowMs,dataKey=`${key}:tb`,data=await this.readRedis(dataKey),tokens=data?.tokens??max,lastRefill=data?.lastRefill??now,refill=(now-lastRefill)*refillRate;if(tokens=Math.min(max,tokens+refill),tokens<1){let waitTime=Math.ceil((1-tokens)/refillRate);return{allowed:!1,remaining:0,resetAt:now+waitTime,limit:max,retryAfter:Math.ceil(waitTime/1000)}}return tokens-=1,await this.redis.create(dataKey,{tokens,lastRefill:now},Math.ceil(windowMs/1000)*2),{allowed:!0,remaining:Math.floor(tokens),resetAt:now+windowMs,limit:max}}async decrement(params){if(!this.config.skipSuccessfulRequests)return;let key=this.buildKey(params);if(this.config.strategy==="sliding-window"){let dataKey=`${key}:sw`,data=await this.readRedis(dataKey);if(data?.timestamps?.length){data.timestamps.pop();let windowMs=this.parseTimeToMs(this.getLimits(params.category,params.authType).window);await this.redis.create(dataKey,data,Math.ceil(windowMs/1000)+1)}}else if(this.config.strategy==="fixed-window"){let windowMs=this.parseTimeToMs(this.getLimits(params.category,params.authType).window),windowId=Math.floor(Date.now()/windowMs),dataKey=`${key}:fw:${windowId}`,data=await this.readRedis(dataKey);if(data?.count)await this.redis.create(dataKey,{count:data.count-1},Math.ceil(windowMs/1000)+1)}}getHeaders(result){let headers={};return headers[this.config.headers.remaining]=String(result.remaining),headers[this.config.headers.reset]=String(Math.ceil(result.resetAt/1000)),headers[this.config.headers.limit]=String(result.limit),headers}isEnabled(){return this.config.enabled}}var DEFAULT_AUTH_LOGIN,DEFAULT_AUTH_REGISTER,DEFAULT_AUTH_PASSWORD_RESET,DEFAULT_AUTH_MAGIC_LINK,DEFAULT_CONFIG4;var init_RateLimiter=__esm(()=>{DEFAULT_AUTH_LOGIN={window:"15m",max:5,blockDuration:"30m"},DEFAULT_AUTH_REGISTER={window:"1h",max:3,blockDuration:"1h"},DEFAULT_AUTH_PASSWORD_RESET={window:"1h",max:3,blockDuration:"1h"},DEFAULT_AUTH_MAGIC_LINK={window:"1h",max:5,blockDuration:"1h"},DEFAULT_CONFIG4={enabled:!0,strategy:"sliding-window",keyPrefix:"rl:",authRoutes:{window:"1m",max:10,login:DEFAULT_AUTH_LOGIN,register:DEFAULT_AUTH_REGISTER,passwordReset:DEFAULT_AUTH_PASSWORD_RESET,magicLink:DEFAULT_AUTH_MAGIC_LINK},publicRoutes:{window:"1m",max:100},privateRoutes:{window:"1m",max:60},byIp:!0,byUserId:!0,byEndpoint:!1,skipSuccessfulRequests:!1,headers:{remaining:"X-RateLimit-Remaining",reset:"X-RateLimit-Reset",limit:"X-RateLimit-Limit"},whitelist:[],blacklist:[]}});var exports_schema={};__export(exports_schema,{ensureSchemaExists:()=>ensureSchemaExists,applySchemaPush:()=>applySchemaPush});import{sql as sql2}from"drizzle-orm";var validateIdentifier=(name)=>{if(!name||name.length>63)throw Error(`Invalid identifier: must be 1-63 characters, got ${name.length}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))throw Error(`Invalid identifier: "${name}" contains unsafe characters`);return name},ensureSchemaExists=async(db,schemaName)=>{let safeName=validateIdentifier(schemaName);await db.execute(sql2.raw(`CREATE SCHEMA IF NOT EXISTS "${safeName}"`))},applySchemaPush=async(push,opts)=>{let{schemaName,allowDataLoss,logger:logger2}=opts;if(push.hasDataLoss&&!allowDataLoss)return logger2.error(`[Schema] Destructive changes detected for schema "${schemaName}" but database.allowDataLoss is not enabled \u2014 skipping schema sync for this schema. Set database.allowDataLoss: true to apply them.`,{warnings:push.warnings,statements:push.statementsToExecute}),!1;if(push.hasDataLoss)logger2.warn(`[Schema] Applying destructive changes to schema "${schemaName}" (database.allowDataLoss=true)`,{warnings:push.warnings});return await push.apply(),!0};var init_schema=()=>{};var rowToTenantRecord=(row)=>({id:String(row.id||""),subdomain:String(row.subdomain||""),schemaName:String(row.schemaName||row.schema_name||""),companyId:String(row.companyId||row.company_id||""),companyName:row.companyName!=null?String(row.companyName):row.company_name!=null?String(row.company_name):null,godAdminEmail:String(row.godAdminEmail||row.god_admin_email||""),status:parseStatus(row.status),plan:row.plan!=null?String(row.plan):null,domain:row.domain!=null?String(row.domain):null,settings:parseJsonbToConfig(row.settings),trustedSources:parseTrustedSources(row.trustedSources||row.trusted_sources),maxUsers:row.maxUsers!=null?Number(row.maxUsers):row.max_users!=null?Number(row.max_users):null,provisionedAt:row.provisionedAt!=null?String(row.provisionedAt):row.provisioned_at!=null?String(row.provisioned_at):null,suspendedAt:row.suspendedAt!=null?String(row.suspendedAt):row.suspended_at!=null?String(row.suspended_at):null,suspendedReason:row.suspendedReason!=null?String(row.suspendedReason):row.suspended_reason!=null?String(row.suspended_reason):null}),rowToFeatureRecord=(row,parseConfig)=>({id:String(row.id||""),tenantId:String(row.tenantId||row.tenant_id||""),featureName:String(row.featureName||row.feature_name||""),enabled:Boolean(row.enabled),featureConfig:parseConfig(row.config)}),parseStatus=(value)=>{let valid=["provisioning","active","suspended","archived"],str2=String(value||"provisioning");return valid.includes(str2)?str2:"provisioning"},parseJsonbToConfig=(value)=>{if(!value||typeof value!=="object")return{};let result={};for(let[k,v]of Object.entries(value))if(typeof v==="string"||typeof v==="number"||typeof v==="boolean")result[k]=v;return result},parseTrustedSources=(value)=>{if(!Array.isArray(value))return[];return value.map((item)=>{let entry=item;return{allowHeaderAuth:entry.allowHeaderAuth===!0||entry.allow_header_auth===!0,allowedIps:Array.isArray(entry.allowedIps||entry.allowed_ips)?entry.allowedIps||entry.allowed_ips:void 0,allowedServices:Array.isArray(entry.allowedServices||entry.allowed_services)?entry.allowedServices||entry.allowed_services:void 0}})},normalizeHost=(host)=>{return((host||"").split(":")[0]||"").toLowerCase().replace(/\.$/,"")},extractSubdomain=(host)=>{let hostWithoutPort=host.split(":")[0]||"";if(hostWithoutPort==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(hostWithoutPort))return null;let parts=hostWithoutPort.split(".");if(parts.length<3)return null;let subdomain=parts[0]||"";if(!subdomain||subdomain==="www")return null;return subdomain},isIpInCidr=(ip,cidr)=>{let[cidrIp,prefixStr]=cidr.split("/");if(!cidrIp||!prefixStr)return!1;let prefix=Number.parseInt(prefixStr,10);if(Number.isNaN(prefix))return!1;let ipParts=ip.split(".").map(Number),cidrParts=cidrIp.split(".").map(Number);if(ipParts.length!==4||cidrParts.length!==4)return!1;let ipNum=(ipParts[0]||0)<<24|(ipParts[1]||0)<<16|(ipParts[2]||0)<<8|(ipParts[3]||0),cidrNum=(cidrParts[0]||0)<<24|(cidrParts[1]||0)<<16|(cidrParts[2]||0)<<8|(cidrParts[3]||0),mask=~((1<<32-prefix)-1);return(ipNum&mask)===(cidrNum&mask)},isTrustedSource=(tenant,request,authMode,fallbackSources)=>{let ownSources=tenant.trustedSources,trustedSources=Array.isArray(ownSources)&&ownSources.length>0?ownSources:fallbackSources;if(!trustedSources||!Array.isArray(trustedSources)||trustedSources.length===0)return authMode==="consumer";let clientIp=request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||request.headers.get("x-real-ip")?.trim()||"",serviceId=request.headers.get("x-service-id")||"";for(let source of trustedSources){if(!source.allowHeaderAuth)continue;if(source.allowedIps&&source.allowedIps.length>0){if(source.allowedIps.some((allowedIp)=>{if(allowedIp.includes("/"))return isIpInCidr(clientIp,allowedIp);return clientIp===allowedIp}))return!0}if(source.allowedServices&&source.allowedServices.length>0){if(source.allowedServices.includes(serviceId))return!0}if((!source.allowedIps||source.allowedIps.length===0)&&(!source.allowedServices||source.allowedServices.length===0))return!0}return!1};function getDatabaseAuthMode(){return process.env.DATABASE_AUTH_MODE||"password"}function getRedisAuthMode(){return process.env.REDIS_AUTH_MODE||"password"}async function acquireToken(scope,label){let{DefaultAzureCredential,ManagedIdentityCredential,ClientSecretCredential}=await import("@azure/identity"),authMode=scope===PG_TOKEN_SCOPE?getDatabaseAuthMode():getRedisAuthMode(),clientId=process.env.AZURE_CLIENT_ID||"",tenantId=process.env.AZURE_TENANT_ID||"",clientSecret=process.env.AZURE_CLIENT_SECRET||"",credential;if(authMode==="managed_identity")credential=clientId?new ManagedIdentityCredential(clientId):new DefaultAzureCredential;else if(authMode==="service_principal"){if(!tenantId||!clientId||!clientSecret)throw Error("[azure-auth] service_principal auth requires AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET");credential=new ClientSecretCredential(tenantId,clientId,clientSecret)}else throw Error(`[azure-auth] Unsupported auth mode: ${authMode}`);let result=await credential.getToken(scope);if(!result)throw Error(`[azure-auth] Failed to acquire token for ${label}`);return logger.scoped("database.connect").info(`[azure-auth] ${label} token acquired`,{expiresAt:new Date(result.expiresOnTimestamp).toISOString(),authMode}),{token:result.token,expiresAt:result.expiresOnTimestamp}}async function getPostgresToken(){let now=Date.now();if(pgCachedToken&&now<pgTokenExpiresAt-REFRESH_BUFFER_MS)return pgCachedToken;let{token,expiresAt}=await acquireToken(PG_TOKEN_SCOPE,"PostgreSQL");return pgCachedToken=token,pgTokenExpiresAt=expiresAt,pgCachedToken}async function getRedisToken(){let now=Date.now();if(redisCachedToken&&now<redisTokenExpiresAt-REFRESH_BUFFER_MS)return redisCachedToken;let{token,expiresAt}=await acquireToken(REDIS_TOKEN_SCOPE,"Redis");return redisCachedToken=token,redisTokenExpiresAt=expiresAt,redisCachedToken}function getRedisTokenExpiresAt(){return redisTokenExpiresAt}var PG_TOKEN_SCOPE="https://ossrdbms-aad.database.windows.net/.default",REDIS_TOKEN_SCOPE="https://redis.azure.com/.default",REFRESH_BUFFER_MS=300000,pgCachedToken=null,pgTokenExpiresAt=0,redisCachedToken=null,redisTokenExpiresAt=0;var init_AzureTokenProvider=__esm(()=>{init_Logger2()});var exports_Azure={};__export(exports_Azure,{getRedisTokenExpiresAt:()=>getRedisTokenExpiresAt,getRedisToken:()=>getRedisToken,getRedisAuthMode:()=>getRedisAuthMode,getPostgresToken:()=>getPostgresToken,getDatabaseAuthMode:()=>getDatabaseAuthMode});var init_Azure=__esm(()=>{init_AzureTokenProvider()});import{access,mkdir as mkdir2}from"fs/promises";import{dirname,resolve}from"path";var DEFAULT_CONFIG5,FILE_SIZE_UNITS,resolvePath=(path2)=>{if(!path2||typeof path2!=="string")throw createFileManagerError("INVALID_PATH","Path must be a non-empty string",path2,"resolvePath");return resolve(path2)},extractDirectoryPath=(filePath)=>{let resolvedPath=resolvePath(filePath);return dirname(resolvedPath)},ensureDirectoryExists=async(dirPath)=>{let resolvedPath=resolve(dirPath);try{await mkdir2(resolvedPath,{recursive:!0})}catch(error){if(error.code!=="EEXIST")throw createFileManagerError("DIRECTORY_CREATE_FAILED",`Failed to create directory: ${resolvedPath}`,resolvedPath,"ensureDirectory")}},formatFileSize=(bytes)=>{let size=bytes,unitIndex=0;while(size>=1024&&unitIndex<FILE_SIZE_UNITS.length-1)size/=1024,unitIndex++;return`${size.toFixed(2)} ${FILE_SIZE_UNITS[unitIndex]}`},validateFileExtension=(fileName,expectedExtension)=>{return fileName.toLowerCase().endsWith(expectedExtension.toLowerCase())},ensureFileExtension=(fileName,extension)=>{let normalizedExtension=extension.startsWith(".")?extension:`.${extension}`;if(validateFileExtension(fileName,normalizedExtension))return fileName;return`${fileName}${normalizedExtension}`},createFileManagerError=(code,message,path2,operation)=>{return{code,message,path:path2,operation:operation||"unknown"}},safeJsonStringify=(data)=>{try{return JSON.stringify(data,null,2)}catch{return"{}"}},executeBulkOperation=async(items,operation,concurrency=DEFAULT_CONFIG5.maxConcurrency)=>{let results=[];for(let i=0;i<items.length;i+=concurrency){let batch3=items.slice(i,i+concurrency),batchPromises=[];for(let item of batch3)batchPromises.push(operation(item));let batchResults=await Promise.allSettled(batchPromises);results.push(...batchResults)}return results},validateConfig=(config,options={})=>{let errors=[],warnings=[],strict=options.strict??!0;if(config.defaultEncoding!==void 0){if(!["utf-8","utf8","ascii","base64","hex"].includes(config.defaultEncoding))errors.push(`Invalid defaultEncoding: ${config.defaultEncoding}`)}if(config.maxConcurrency!==void 0){if(!Number.isInteger(config.maxConcurrency)||config.maxConcurrency<1)errors.push("maxConcurrency must be a positive integer");if(config.maxConcurrency>50)warnings.push("maxConcurrency > 50 may cause performance issues")}if(config.defaultCreateDir!==void 0&&typeof config.defaultCreateDir!=="boolean")errors.push("defaultCreateDir must be a boolean");if(config.defaultRecursive!==void 0&&typeof config.defaultRecursive!=="boolean")errors.push("defaultRecursive must be a boolean");if(strict&&!options.allowUnknownKeys){let validKeys=["defaultEncoding","defaultCreateDir","defaultRecursive","maxConcurrency"],configKeys=Object.keys(config);for(let key of configKeys)if(!validKeys.includes(key))errors.push(`Unknown configuration key: ${key}`)}return{isValid:errors.length===0,errors,warnings}},mergeConfig=(partial,base=DEFAULT_CONFIG5)=>{let validation=validateConfig(partial);if(!validation.isValid)throw createFileManagerError("CONFIG_VALIDATION_FAILED",`Configuration validation failed: ${validation.errors.join(", ")}`,void 0,"mergeConfig");return{...base,...partial}},parsePermissions=(mode)=>{let parseOctal=(octal)=>({read:Boolean(octal&4),write:Boolean(octal&2),execute:Boolean(octal&1)}),ownerMode=mode>>6&7,groupMode=mode>>3&7,othersMode=mode&7;return{owner:parseOctal(ownerMode),group:parseOctal(groupMode),others:parseOctal(othersMode)}},validatePermissionMode=(mode)=>{return Number.isInteger(mode)&&mode>=0&&mode<=511};var init_utils4=__esm(()=>{DEFAULT_CONFIG5={defaultEncoding:"utf-8",defaultCreateDir:!0,defaultRecursive:!0,maxConcurrency:5},FILE_SIZE_UNITS=["B","KB","MB","GB","TB"]});import{copyFile,rename,unlink as unlink2}from"fs/promises";import{basename,dirname as dirname2,extname,join as join2}from"path";var DEFAULT_ATOMIC_CONFIG,generateTempPath=(originalPath,suffix=".tmp")=>{let resolvedPath=resolvePath(originalPath),timestamp=Date.now(),random=Math.random().toString(36).substring(2,8);return`${resolvedPath}${suffix}.${timestamp}.${random}`},generateBackupPath=(originalPath,backupDir,useTimestamp=!0)=>{let resolvedPath=resolvePath(originalPath),dir=backupDir?resolvePath(backupDir):dirname2(resolvedPath),name=basename(resolvedPath),ext=extname(name),nameWithoutExt=basename(name,ext),timestamp=useTimestamp?`.${new Date().toISOString().replace(/[:.]/g,"-")}`:"",backupName=`${nameWithoutExt}.backup${timestamp}${ext}`;return join2(dir,backupName)},atomicWrite=async({path:path2,data,tempSuffix=DEFAULT_ATOMIC_CONFIG.tempSuffix,backup=DEFAULT_ATOMIC_CONFIG.backup,sync=DEFAULT_ATOMIC_CONFIG.sync})=>{let resolvedPath=resolvePath(path2),tempPath=generateTempPath(resolvedPath,tempSuffix),backupPath;try{if(await ensureDirectoryExists(extractDirectoryPath(resolvedPath)),backup){if(await Bun.file(resolvedPath).exists())backupPath=generateBackupPath(resolvedPath),await copyFile(resolvedPath,backupPath)}let bytesWritten=await Bun.write(tempPath,data);return await rename(tempPath,resolvedPath),{success:!0,bytesWritten,tempPath,backupPath}}catch(error){try{await unlink2(tempPath)}catch{}throw createFileManagerError("ATOMIC_WRITE_FAILED",`Atomic write failed: ${error}`,resolvedPath,"atomicWrite")}},atomicJsonWrite=async(path2,data,options={})=>{let jsonString=JSON.stringify(data,null,2);return atomicWrite({path:path2,data:jsonString,...options})},createBackup=async({sourcePath,backupDir,keepOriginal=!0,timestamp=DEFAULT_ATOMIC_CONFIG.timestamp})=>{let resolvedSource=resolvePath(sourcePath);if(!await Bun.file(resolvedSource).exists())throw createFileManagerError("SOURCE_NOT_FOUND",`Source file not found: ${sourcePath}`,resolvedSource,"createBackup");let backupPath=generateBackupPath(resolvedSource,backupDir,timestamp);if(await ensureDirectoryExists(dirname2(backupPath)),keepOriginal)await copyFile(resolvedSource,backupPath);else await rename(resolvedSource,backupPath);return backupPath},restoreFromBackup=async(backupPath,targetPath,deleteBackup=!1)=>{let resolvedBackup=resolvePath(backupPath),resolvedTarget=resolvePath(targetPath);if(!await Bun.file(resolvedBackup).exists())throw createFileManagerError("BACKUP_NOT_FOUND",`Backup file not found: ${backupPath}`,resolvedBackup,"restoreFromBackup");try{if(await ensureDirectoryExists(extractDirectoryPath(resolvedTarget)),deleteBackup)await rename(resolvedBackup,resolvedTarget);else await copyFile(resolvedBackup,resolvedTarget);return!0}catch(error){return logger.scoped("storage.fs").error(`Failed to restore from backup ${backupPath}`,error,{backupPath}),!1}},safeUpdate=async(path2,updateFunction,options={})=>{let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath),backupPath;try{if(await file.exists())backupPath=await createBackup({sourcePath:resolvedPath,keepOriginal:!0,timestamp:!0});let currentData=await file.exists()?await file.text():"",newData=await updateFunction(currentData),result=await atomicWrite({path:resolvedPath,data:newData,backup:!1,...options});return{success:result.success,bytesWritten:result.bytesWritten,tempPath:result.tempPath,backupPath}}catch(error){if(backupPath)try{await restoreFromBackup(backupPath,resolvedPath,!1)}catch(rollbackError){logger.scoped("storage.fs").error("Atomic write rollback failed",rollbackError,{backupPath})}throw error}},batchAtomicWrite=async(operations)=>{let successful=[],failed=[];for(let operation of operations)try{let result=await atomicWrite(operation);successful.push(result)}catch(error){failed.push({operation,error})}return{successful,failed}};var init_atomic=__esm(()=>{init_Logger2();init_utils4();DEFAULT_ATOMIC_CONFIG={tempSuffix:".tmp",backup:!1,sync:!0,timestamp:!0}});import{chmod,stat as stat2}from"fs/promises";var PERMISSION_MODES,setFilePermissions=async(path2,mode)=>{let resolvedPath=resolvePath(path2);if(!validatePermissionMode(mode))throw createFileManagerError("INVALID_PERMISSION_MODE",`Invalid permission mode: ${mode.toString(8)}`,resolvedPath,"setFilePermissions");try{return await chmod(resolvedPath,mode),!0}catch(error){return logger.scoped("storage.fs").error(`Failed to set permissions for ${path2}`,error,{path:path2,mode}),!1}},getFilePermissions=async(path2)=>{let resolvedPath=resolvePath(path2);try{let mode=(await stat2(resolvedPath)).mode&511,permissions=parsePermissions(mode);return{path:resolvedPath,mode,owner:permissions.owner,group:permissions.group,others:permissions.others}}catch(error){throw createFileManagerError("PERMISSION_READ_FAILED",`Failed to read permissions: ${error}`,resolvedPath,"getFilePermissions")}},hasPermissions=async(path2,requiredMode)=>{try{return((await getFilePermissions(path2)).mode&requiredMode)===requiredMode}catch{return!1}},makeReadable=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode|256;return setFilePermissions(path2,newMode)},makeWritable=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode|128;return setFilePermissions(path2,newMode)},makeExecutable=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode|64;return setFilePermissions(path2,newMode)},makeReadOnly=async(path2)=>{let newMode=(await getFilePermissions(path2)).mode&-147;return setFilePermissions(path2,newMode)},setCommonPermissions=async(path2,pattern)=>{let mode=PERMISSION_MODES[pattern];return setFilePermissions(path2,mode)};var init_permissions=__esm(()=>{init_Logger2();init_utils4();PERMISSION_MODES={OWNER_READ_WRITE:384,OWNER_ALL:448,GROUP_READ:416,GROUP_READ_WRITE:432,ALL_READ:420,ALL_READ_WRITE:438,ALL_READ_EXECUTE:493,ALL_FULL:511,READ_ONLY:292,EXECUTABLE:493}});var DEFAULT_STREAM_CONFIG,createFileWriter=async(path2,options={})=>{let resolvedPath=resolvePath(path2),config={...DEFAULT_STREAM_CONFIG,...options};await ensureDirectoryExists(extractDirectoryPath(resolvedPath));let writer=Bun.file(resolvedPath).writer({highWaterMark:config.highWaterMark}),isClosed=!1;return{write:(chunk)=>{if(isClosed)throw createFileManagerError("WRITER_CLOSED","Cannot write to closed writer",resolvedPath,"streamWrite");try{let result=writer.write(chunk);if(config.autoFlush)writer.flush();return result}catch(error){throw createFileManagerError("WRITE_FAILED",`Failed to write chunk: ${error}`,resolvedPath,"streamWrite")}},flush:()=>{if(isClosed)return 0;try{return writer.flush()}catch(error){throw createFileManagerError("FLUSH_FAILED",`Failed to flush writer: ${error}`,resolvedPath,"streamFlush")}},end:async(error)=>{if(isClosed)return 0;try{let result=await writer.end(error);return isClosed=!0,result}catch(err){throw isClosed=!0,createFileManagerError("END_FAILED",`Failed to end writer: ${err}`,resolvedPath,"streamEnd")}},ref:()=>{if(!isClosed)writer.ref()},unref:()=>{if(!isClosed)writer.unref()}}},writeStream=async(path2,chunks,options={})=>{let writer=await createFileWriter(path2,options),totalBytes=0;try{for(let chunk of chunks){let bytesWritten=writer.write(chunk);totalBytes+=bytesWritten}return await writer.flush(),await writer.end(),totalBytes}catch(error){try{await writer.end(error)}catch{}throw error}},appendStream=async(path2,chunks,options={})=>{let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath),existingContent=await file.exists()?await file.arrayBuffer():new ArrayBuffer(0),allChunks=[];if(existingContent.byteLength>0)allChunks.push(existingContent);return allChunks.push(...chunks),writeStream(resolvedPath,allChunks,options)},copyFileStream=async(sourcePath,destinationPath,options={})=>{let resolvedSource=resolvePath(sourcePath),sourceFile=Bun.file(resolvedSource);if(!await sourceFile.exists())throw createFileManagerError("SOURCE_NOT_FOUND",`Source file not found: ${sourcePath}`,resolvedSource,"copyFileStream");let sourceStream=sourceFile.stream(),writer=await createFileWriter(destinationPath,options),totalBytes=0;try{let reader=sourceStream.getReader();while(!0){let{done,value}=await reader.read();if(done)break;let bytesWritten=writer.write(value);totalBytes+=bytesWritten}return await writer.flush(),await writer.end(),totalBytes}catch(error){try{await writer.end(error)}catch{}throw error}},readFileStream=async(path2,chunkProcessor)=>{let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath);if(!await file.exists())throw createFileManagerError("FILE_NOT_FOUND",`File not found: ${path2}`,resolvedPath,"readFileStream");let reader=file.stream().getReader();try{while(!0){let{done,value}=await reader.read();if(done)break;await chunkProcessor(value)}}finally{reader.releaseLock()}};var init_streaming=__esm(()=>{init_utils4();DEFAULT_STREAM_CONFIG={highWaterMark:1048576,autoFlush:!0,closeOnEnd:!0}});import{readdir,rm,rmdir,stat as stat3}from"fs/promises";import{extname as extname2,join as join3}from"path";class BunFileManager{static instance;config;constructor(){this.config={...DEFAULT_CONFIG5}}static getInstance(){if(!BunFileManager.instance)BunFileManager.instance=new BunFileManager;return BunFileManager.instance}async createFile({dir,name,data,options={}}){let filePath=resolvePath(join3(dir,name));if(options.createDir!==!1)await ensureDirectoryExists(extractDirectoryPath(filePath));let fileData=options.type?new Blob([data],{type:options.type}):data;return await Bun.write(filePath,fileData)}async createJsonFile(dir,name,data){let fileName=ensureFileExtension(name,".json"),jsonString=safeJsonStringify(data);return this.createFile({dir,name:fileName,data:jsonString,options:{type:"application/json"}})}async createDirectory({path:path2}){await ensureDirectoryExists(path2)}async readFile({path:path2,format="text"}){let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath);if(!await file.exists())throw createFileManagerError("FILE_NOT_FOUND",`File not found: ${path2}`,resolvedPath,"readFile");switch(format){case"text":return await file.text();case"json":return await file.json();case"buffer":return await file.arrayBuffer();case"bytes":return await file.bytes();case"stream":return file.stream();default:return await file.text()}}async readJsonFile(path2){return this.readFile({path:path2,format:"json"})}async getFileInfo(path2){let resolvedPath=resolvePath(path2),file=Bun.file(resolvedPath),fileName=path2.split("/").pop()||path2,stats=null;try{stats=await stat3(resolvedPath)}catch{}return{name:fileName,path:resolvedPath,size:file.size,type:file.type,exists:await file.exists(),extension:extname2(fileName),createdAt:stats?.birthtime,modifiedAt:stats?.mtime}}async readDirectory({path:path2,recursive=!1}){let resolvedPath=resolvePath(path2);return await readdir(resolvedPath,{recursive,encoding:"utf8"})}async getFilesByExtension(dir,extension){let files=await this.readDirectory({path:dir}),normalizedExt=extension.startsWith(".")?extension:`.${extension}`;return files.filter((file)=>file.endsWith(normalizedExt))}async updateFile({path:path2,data,mode="overwrite"}){let resolvedPath=resolvePath(path2);if(mode==="append"){let combinedData=await this.readFile({path:path2,format:"text"})+data;return await Bun.write(resolvedPath,combinedData)}return await Bun.write(resolvedPath,data)}async updateJsonFile(path2,data,merge=!1){let finalData=data;if(merge)try{let existingData=await this.readJsonFile(path2);if(typeof existingData==="object"&&existingData!==null&&!Array.isArray(existingData)&&typeof data==="object"&&data!==null&&!Array.isArray(data))finalData={...existingData,...data}}catch{}return this.updateFile({path:path2,data:safeJsonStringify(finalData),mode:"overwrite"})}async appendToFile(path2,data){return this.updateFile({path:path2,data,mode:"append"})}async deleteFile(path2){try{let resolvedPath=resolvePath(path2);return await Bun.file(resolvedPath).delete(),!0}catch(error){return logger.scoped("storage.fs").error(`Failed to delete file ${path2}`,error,{path:path2}),!1}}async deleteDirectory({path:path2,recursive=!1}){try{let resolvedPath=resolvePath(path2);if(recursive)await rm(resolvedPath,{recursive:!0,force:!0});else await rmdir(resolvedPath);return!0}catch(error){return logger.scoped("storage.fs").error(`Failed to delete directory ${path2}`,error,{path:path2}),!1}}async deleteFiles(paths){let results=await executeBulkOperation(paths,async(path2)=>{if(!await this.deleteFile(path2))throw Error(`Failed to delete: ${path2}`);return path2}),success=[],failed=[];for(let i=0;i<results.length;i++){let result=results[i],originalPath=paths[i];if(result?.status==="fulfilled")success.push(originalPath||"");else failed.push(originalPath||"")}return{success,failed}}async exists(path2){let resolvedPath=resolvePath(path2);return await Bun.file(resolvedPath).exists()}async copyFile(sourcePath,destinationPath){let resolvedSource=resolvePath(sourcePath),resolvedDestination=resolvePath(destinationPath),sourceFile=Bun.file(resolvedSource);if(!await sourceFile.exists())throw createFileManagerError("SOURCE_NOT_FOUND",`Source file not found: ${sourcePath}`,resolvedSource,"copyFile");return await ensureDirectoryExists(extractDirectoryPath(resolvedDestination)),await Bun.write(resolvedDestination,sourceFile)}async moveFile(sourcePath,destinationPath){try{return await this.copyFile(sourcePath,destinationPath),await this.deleteFile(sourcePath),!0}catch(error){return logger.scoped("storage.fs").error("Failed to move file",error,{sourcePath,destinationPath}),!1}}getFormattedFileSize(bytes){return formatFileSize(bytes)}getConfig(){return{...this.config}}updateConfig(newConfig){let validation=validateConfig(newConfig);if(validation.isValid){let mergedConfig=mergeConfig(newConfig,this.config);Object.assign(this.config,mergedConfig)}return validation}validateConfiguration(config){return validateConfig(config)}async createStreamWriter(path2,options={}){return createFileWriter(path2,options)}async writeStream(path2,chunks,options={}){return writeStream(path2,chunks,options)}async appendStream(path2,chunks,options={}){return appendStream(path2,chunks,options)}async copyFileStream(sourcePath,destinationPath,options={}){return copyFileStream(sourcePath,destinationPath,options)}async readFileStream(path2,chunkProcessor){return readFileStream(path2,chunkProcessor)}async setPermissions(path2,mode){return setFilePermissions(path2,mode)}async setPermissionsAdvanced(options){return setFilePermissions(options.path,options.mode)}async getPermissions(path2){return getFilePermissions(path2)}async checkPermissions(path2,requiredMode){return hasPermissions(path2,requiredMode)}async makeFileReadable(path2){return makeReadable(path2)}async makeFileWritable(path2){return makeWritable(path2)}async makeFileExecutable(path2){return makeExecutable(path2)}async makeFileReadOnly(path2){return makeReadOnly(path2)}async setCommonPermission(path2,pattern){return setCommonPermissions(path2,pattern)}async atomicWrite(options){return atomicWrite(options)}async atomicJsonWrite(path2,data,options={}){return atomicJsonWrite(path2,data,options)}async createFileBackup(options){return createBackup(options)}async restoreFileFromBackup(backupPath,targetPath,deleteBackup=!1){return restoreFromBackup(backupPath,targetPath,deleteBackup)}async safeFileUpdate(path2,updateFunction,options={}){return safeUpdate(path2,updateFunction,options)}async batchAtomicOperations(operations){return batchAtomicWrite(operations)}}var init_core=__esm(()=>{init_Logger2();init_atomic();init_permissions();init_streaming();init_utils4()});var fileManager;var init_File=__esm(()=>{init_core();init_utils4();init_core();fileManager=BunFileManager.getInstance()});import{Pool}from"pg";var init_Postgre=__esm(()=>{init_Logger2()});var init_Managers=__esm(()=>{init_Azure();init_Dapr();init_File();init_Postgre();init_Redis()});var exports_utils={};__export(exports_utils,{validatePayload:()=>validatePayload,validateEnvVariables:()=>validateEnvVariables,toAudit:()=>toAudit,signNewAccessToken:()=>signNewAccessToken,sanitizePayload:()=>sanitizePayload,refreshAccessTokenWithLock:()=>refreshAccessTokenWithLock,parseTokenValuesFromHeaders:()=>parseTokenValuesFromHeaders,parseTimeToSeconds:()=>parseTimeToSeconds2,parseQueryParams:()=>parseQueryParams,initiateRedisManager:()=>initiateRedisManager,getRedisManager:()=>getRedisManager,ensureDatabaseExists:()=>ensureDatabaseExists,createAuditLog:()=>createAuditLog,buildPaginationMeta:()=>buildPaginationMeta});function parseTokenValuesFromHeaders(headers,tokenNames){let cookies=(headers.get("cookie")?.split(";")||[]).reduce((acc,cookie)=>{let trimmed=cookie.trim(),eqIndex=trimmed.indexOf("=");if(eqIndex>0)acc[trimmed.slice(0,eqIndex)]=trimmed.slice(eqIndex+1);return acc},{});return{access_token:cookies[tokenNames.access_token]||headers.get("authorization")?.split(" ")[1],refresh_token:cookies[tokenNames.refresh_token],session_token:cookies[tokenNames.session_token]}}async function initiateRedisManager(config){if(!config.redis){logger.info("[Redis] Not configured, skipping");return}let rawWithDapr=config.redis.withDapr;if(typeof rawWithDapr==="string"?process.env[rawWithDapr]?.toLowerCase()!=="false":rawWithDapr??!1){redisManagerInstance=new RedisManager({withDapr:!0,stateStoreName:config.redis.stateStoreName});return}let resolvedUrl=config.redis.url?process.env[config.redis.url]:void 0,resolvedHost=config.redis.host?process.env[config.redis.host]:void 0,resolvedPort=config.redis.port?parseInt(process.env[config.redis.port]||"",10):void 0;if((process.env.REDIS_AUTH_MODE||"password")!=="password"){let{getRedisToken:getRedisToken2,getRedisTokenExpiresAt:getRedisTokenExpiresAt2}=await Promise.resolve().then(() => (init_Azure(),exports_Azure)),clientId=process.env.AZURE_CLIENT_ID||"",initialToken=await getRedisToken2();redisManagerInstance=new RedisManager({host:resolvedHost,port:Number.isNaN(resolvedPort)?void 0:resolvedPort,password:initialToken,username:clientId,tls:!0});let scheduleRedisTokenRefresh=()=>{let expiresAt=getRedisTokenExpiresAt2(),refreshIn=Math.max(expiresAt-Date.now()-300000,30000);setTimeout(async()=>{try{let newToken=await getRedisToken2();if(redisManagerInstance)await redisManagerInstance.reauthenticate(clientId,newToken),logger.info("[Redis] Entra ID token refreshed successfully");scheduleRedisTokenRefresh()}catch(err){logger.error("[Redis] Token refresh failed \u2014 retrying in 30s",err),setTimeout(scheduleRedisTokenRefresh,30000)}},refreshIn)};scheduleRedisTokenRefresh()}else{let resolvedPassword=process.env.REDIS_PASSWORD||void 0;redisManagerInstance=new RedisManager({url:resolvedUrl,host:resolvedHost,port:Number.isNaN(resolvedPort)?void 0:resolvedPort,...resolvedPassword?{password:resolvedPassword}:{}})}}function getRedisManager(){return redisManagerInstance}function parseTimeToSeconds2(timeString){if(typeof timeString==="number")return timeString;if(!timeString||timeString.trim()==="")throw Error("Time string cannot be empty");let match=timeString.trim().match(/^(\d+(?:\.\d+)?)\s*([smhdwMy])$/);if(!match||!match[1]||!match[2])throw Error(`Invalid time format: "${timeString}". Expected format: "75s", "10m", "2h", "1d", "1w", "2M", "1y"`);let value=parseFloat(match[1]),unit=match[2],multiplier={s:1,m:60,h:3600,d:86400,w:604800,M:2592000,y:31536000}[unit];if(multiplier===void 0)throw Error(`Unknown time unit: "${unit}"`);let seconds=Math.floor(value*multiplier);if(seconds<=0)throw Error(`Time value must be positive: "${timeString}"`);return seconds}function signNewAccessToken({sessionData,options,refreshTokenId,roles,claims}){let secretEnvName=options.authentication?.accessToken?.secret;if(!secretEnvName)throw Error("Access token secret env name is not configured");let secret=process.env[secretEnvName];if(!secret)throw Error(`Access token secret env "${secretEnvName}" is not set`);return signJWT({subject:sessionData.userId,issuer:options.authentication?.accessToken?.issuer,audience:options.authentication?.accessToken?.audience,algorithm:options.authentication?.accessToken?.algorithm,expiresInSeconds:parseTimeToSeconds2(options.authentication?.accessToken?.expiresIn??"15m"),sessionId:sessionData.id,customClaims:{refreshTokenId,...roles&&roles.length>0?{roles}:{},...claims&&claims.length>0?{claims}:{}}},secret)}function toAudit(payload,summary){return payload?{entityName:payload.entity_name,entityId:payload.entity_id===" - "?null:payload.entity_id,operation:payload.operation_type,userId:payload.user_id==="unknown"?null:payload.user_id,summary,ipAddress:payload.ip_address,userAgent:payload.user_agent,path:payload.path,query:payload.query}:void 0}function reconstructBracketParams(query){let result={},arrayGroups={};for(let[key,value]of Object.entries(query)){let match=key.match(/^(\w+)\[\d*\]\[(\w+)\]$/),arrayName=match?.[1],prop=match?.[2];if(arrayName&&prop){if(!arrayGroups[arrayName])arrayGroups[arrayName]={};let group=arrayGroups[arrayName];if(!group[prop])group[prop]=[];let arr=group[prop];if(Array.isArray(value))for(let v of value)arr.push(v);else arr.push(value)}else result[key]=value}for(let[arrayName,props]of Object.entries(arrayGroups)){let propNames=Object.keys(props);if(propNames.length===0)continue;let maxLen=Math.max(...propNames.map((p)=>(props[p]||[]).length)),items=[];for(let i=0;i<maxLen;i++){let item={};for(let p of propNames)item[p]=(props[p]||[])[i];items.push(item)}result[arrayName]=items}return result}function parseQueryParams(query){let q=reconstructBracketParams(query),parseJSONOrPassthrough=(value)=>{if(value===void 0||value===null)return;if(typeof value==="object")return value;if(typeof value==="string")try{return JSON.parse(value)}catch{return}return},page=q.page?parseInt(q.page,10):1,limit=q.limit?parseInt(q.limit,10):20,offset=q.offset?parseInt(q.offset,10):(page-1)*limit;return{page,limit,offset,search:q.search,searchFields:q.searchFields?q.searchFields.split(","):void 0,filters:parseJSONOrPassthrough(q.filters),sort:parseJSONOrPassthrough(q.sort),select:q.select?q.select.split(","):void 0,with:parseJSONOrPassthrough(q.with),distinct:q.distinct==="true",distinctOn:q.distinctOn?q.distinctOn.split(","):void 0}}function buildPaginationMeta(page,limit,offset,totalItems){let totalPages=Math.ceil(totalItems/limit),hasNextPage=page<totalPages,hasPrevPage=page>1;return{page,limit,offset,totalItems,totalPages,hasNextPage,hasPrevPage,nextPage:hasNextPage?page+1:null,prevPage:hasPrevPage?page-1:null}}function getBaseTypeValidator(type){let stringTypes=["varchar","char","text","uuid","citext","bit","varbit"],numberTypes=["integer","smallint","bigint","serial","smallserial","bigserial","real","doublePrecision","numeric","decimal"],booleanTypes=["boolean"];if(stringTypes.includes(type))return(v)=>({valid:typeof v==="string",expectedType:"string"});if(numberTypes.includes(type))return(v)=>({valid:typeof v==="number",expectedType:"number"});if(booleanTypes.includes(type))return(v)=>({valid:typeof v==="boolean",expectedType:"boolean"});if(type==="json"||type==="jsonb")return(v)=>({valid:typeof v==="object",expectedType:"object"});return()=>({valid:!0,expectedType:"any"})}function validatePayload(payload,columns,isPartial=!1){let errors=[];for(let col4 of columns){let value=payload[col4.name]??payload[col4.name.replace(/_([a-z])/g,(_,l)=>l.toUpperCase())],hasDbDefault=col4.default!==void 0||!!col4.defaultRaw||!!col4.generatedByDefaultAsIdentity||!!col4.generatedAlwaysAsIdentity||!!col4.generatedAlwaysAs,isRequired=col4.notNull&&!col4.nullable&&!hasDbDefault;if(value===void 0||value===null){if(isRequired&&!isPartial)errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} is required`});continue}if(col4.array){let baseValidator=getBaseTypeValidator(col4.type),expectedType=baseValidator(void 0).expectedType;if(!Array.isArray(value)){errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be an array of ${expectedType}`});continue}if(value.some((el)=>el!==null&&!baseValidator(el).valid))errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be an array of ${expectedType}`});continue}let typeCheck=getBaseTypeValidator(col4.type)(value);if(!typeCheck.valid){errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be of type ${typeCheck.expectedType}`});continue}if(typeof value==="string"){let len=value.length;if(col4.length&&len>col4.length)errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} exceeds max length of ${col4.length}`});if(col4.validation?.minLength&&len<col4.validation.minLength)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at least ${col4.validation.minLength} characters`});if(col4.validation?.maxLength&&len>col4.validation.maxLength)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at most ${col4.validation.maxLength} characters`});if(col4.validation?.pattern){if(!new RegExp(col4.validation.pattern).test(value))errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} does not match required pattern`})}if(col4.validation?.format){let formatRegex=FORMAT_PATTERNS[col4.validation.format];if(formatRegex&&!formatRegex.test(value))errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be a valid ${col4.validation.format}`})}}if(typeof value==="number"){if(col4.validation?.min!==void 0&&value<col4.validation.min)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at least ${col4.validation.min}`});if(col4.validation?.max!==void 0&&value>col4.validation.max)errors.push({field:col4.name,message:col4.validation.customMessage||`${col4.name} must be at most ${col4.validation.max}`})}if(col4.enumValues&&col4.enumValues.length>0){if(!col4.enumValues.includes(value))errors.push({field:col4.name,message:col4.validation?.customMessage||`${col4.name} must be one of: ${col4.enumValues.join(", ")}`})}}return{valid:errors.length===0,errors}}function escapeHtml(str2){return str2.replace(/[&<>"'`=/]/g,(char)=>HTML_ENTITIES[char]||char)}function stripTags(str2){return str2.replace(/<[^>]*>/g,"")}function normalizeEmail(email){let parts=email.split("@"),localPart=parts[0],domain=parts[1];if(!localPart||!domain)return email;let beforePlus=localPart.split("+")[0];if(!beforePlus)return email;return`${beforePlus.replace(/\./g,"")}@${domain.toLowerCase()}`}function slugify(str2){return str2.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function applySanitizer(value,sanitizer){if(value===null||value===void 0)return value;switch(sanitizer){case"trim":return typeof value==="string"?value.trim():value;case"lowercase":return typeof value==="string"?value.toLowerCase():value;case"uppercase":return typeof value==="string"?value.toUpperCase():value;case"escapeHtml":return typeof value==="string"?escapeHtml(value):value;case"stripTags":return typeof value==="string"?stripTags(value):value;case"normalizeEmail":return typeof value==="string"?normalizeEmail(value):value;case"toNumber":if(typeof value==="number")return value;if(typeof value==="string"){let num=Number(value);return Number.isNaN(num)?value:num}return value;case"toBoolean":if(typeof value==="boolean")return value;if(typeof value==="string"){let lower=value.toLowerCase();if(lower==="true"||lower==="1"||lower==="yes")return!0;if(lower==="false"||lower==="0"||lower==="no")return!1}if(typeof value==="number")return value!==0;return value;case"slugify":return typeof value==="string"?slugify(value):value;default:return value}}function sanitizePayload(payload,columns){let sanitized={},toCamel2=(s)=>s.replace(/_([a-z])/g,(_,l)=>l.toUpperCase());for(let key of Object.keys(payload)){let value=payload[key],snakeKey=key.replace(/[A-Z]/g,(l)=>`_${l.toLowerCase()}`),col4=columns.find((c)=>c.name===key||c.name===snakeKey);if(col4?.sanitize&&col4.sanitize.length>0)for(let sanitizer of col4.sanitize)value=applySanitizer(value,sanitizer);if(col4&&(col4.type==="timestamp"||col4.type==="timestamptz"||col4.type==="date")&&typeof value==="string"){let parsed=new Date(value);if(!Number.isNaN(parsed.getTime()))value=parsed}let normalizedKey=key.includes("_")?toCamel2(key):key;sanitized[normalizedKey]=value}return sanitized}function createAuditLog(db,auditTable,entry){if(!db||!auditTable)return;let logEntry={user_id:entry.user_id,entity_name:entry.entity_name,entity_id:entry.entity_id,operation:entry.operation,old_data:entry.old_data??null,new_data:entry.new_data??null,timestamp:new Date().toISOString()};db.insert(auditTable).values(logEntry).execute().catch((err)=>{logger.error("[Audit] Database audit write failed",err,{entity:logEntry.entity_name,operation:logEntry.operation})})}async function refreshAccessTokenWithLock(userId,sessionId,generateToken){let redis=new RedisManager,lockKey=`${REFRESH_LOCK_PREFIX}${userId}`,cacheKey=`${ACCESS_TOKEN_CACHE_PREFIX}${userId}:${sessionId}`,cachedResult=await redis.read(cacheKey);if(cachedResult.success&&cachedResult.data)return{success:!0,accessToken:cachedResult.data,fromCache:!0};let lockResult=await redis.acquireLock(lockKey,LOCK_TTL_SECONDS);if(!lockResult.success)return{success:!1,error:lockResult.error};if(lockResult.data)try{let newToken=generateToken();return await redis.create(cacheKey,newToken,ACCESS_TOKEN_CACHE_TTL_SECONDS),{success:!0,accessToken:newToken,fromCache:!1}}finally{await redis.releaseLock(lockKey)}let waitResult=await redis.waitForLock(lockKey,LOCK_WAIT_TIMEOUT_MS,50);if(!waitResult.success)return{success:!1,error:waitResult.error};if(!waitResult.data)return{success:!1,error:"Lock wait timeout"};let newCachedResult=await redis.read(cacheKey);if(newCachedResult.success&&newCachedResult.data)return{success:!0,accessToken:newCachedResult.data,fromCache:!0};let fallbackToken=generateToken();return await redis.create(cacheKey,fallbackToken,ACCESS_TOKEN_CACHE_TTL_SECONDS),{success:!0,accessToken:fallbackToken,fromCache:!1}}function validateEnvVariables(config){let errors=[],resolved={},databaseAuthMode=process.env.DATABASE_AUTH_MODE||"password",redisAuthMode=process.env.REDIS_AUTH_MODE||"password";resolved.databaseAuthMode=databaseAuthMode,resolved.redisAuthMode=redisAuthMode;let entraIdModes=["managed_identity","service_principal"];if(entraIdModes.includes(databaseAuthMode)||entraIdModes.includes(redisAuthMode)){if(!process.env.AZURE_CLIENT_ID)logger.warn("[Config] AZURE_CLIENT_ID is not set. Required for user-assigned managed identity.");if([databaseAuthMode,redisAuthMode].filter((m)=>m==="service_principal").length>0){if(!process.env.AZURE_TENANT_ID)errors.push({field:"azure.tenantId",envName:"AZURE_TENANT_ID",message:"AZURE_TENANT_ID is required for service_principal auth mode."});if(!process.env.AZURE_CLIENT_SECRET)errors.push({field:"azure.clientSecret",envName:"AZURE_CLIENT_SECRET",message:"AZURE_CLIENT_SECRET is required for service_principal auth mode."})}}if(config.database?.url){let envValue=process.env[config.database.url];if(!envValue)errors.push({field:"database.url",envName:config.database.url,message:`Environment variable "${config.database.url}" is not set. Please set it in your .env file.`});else resolved.databaseUrl=envValue}let validationWithDapr=typeof config.redis?.withDapr==="string"?process.env[config.redis.withDapr]?.toLowerCase()!=="false":config.redis?.withDapr??!1;if(config.redis&&!validationWithDapr)if(config.redis.url){let envValue=process.env[config.redis.url];if(!envValue)errors.push({field:"redis.url",envName:config.redis.url,message:`Environment variable "${config.redis.url}" is not set. Please set it in your .env file.`});else resolved.redisUrl=envValue}else{if(config.redis.host){if(!process.env[config.redis.host])errors.push({field:"redis.host",envName:config.redis.host,message:`Environment variable "${config.redis.host}" is not set. Please set it in your .env file.`})}if(config.redis.port){if(!process.env[config.redis.port])errors.push({field:"redis.port",envName:config.redis.port,message:`Environment variable "${config.redis.port}" is not set. Please set it in your .env file.`})}}if(config.authentication?.enabled){if(!config.authentication.mode)errors.push({field:"authentication.mode",envName:"",message:'authentication.mode is required when authentication is enabled. Use "full" for IDP/standalone services, "consumer" for resource servers.'});if(config.authentication.accessToken?.secret){let envValue=process.env[config.authentication.accessToken.secret];if(!envValue)errors.push({field:"authentication.accessToken.secret",envName:config.authentication.accessToken.secret,message:`Environment variable "${config.authentication.accessToken.secret}" is not set. Please set it in your .env file.`});else resolved.accessTokenSecret=envValue}else errors.push({field:"authentication.accessToken.secret",envName:"",message:"authentication.accessToken.secret is required when authentication is enabled."});let isConsumerMode=config.authentication.mode==="consumer";if(config.authentication.refreshToken?.secret){let envValue=process.env[config.authentication.refreshToken.secret];if(!envValue)errors.push({field:"authentication.refreshToken.secret",envName:config.authentication.refreshToken.secret,message:`Environment variable "${config.authentication.refreshToken.secret}" is not set. Please set it in your .env file.`});else resolved.refreshTokenSecret=envValue}else if(!isConsumerMode)errors.push({field:"authentication.refreshToken.secret",envName:"",message:"authentication.refreshToken.secret is required when authentication is enabled."});if(config.authentication.sessionToken?.secret){let envValue=process.env[config.authentication.sessionToken.secret];if(!envValue)errors.push({field:"authentication.sessionToken.secret",envName:config.authentication.sessionToken.secret,message:`Environment variable "${config.authentication.sessionToken.secret}" is not set. Please set it in your .env file.`});else resolved.sessionTokenSecret=envValue}else if(!isConsumerMode)errors.push({field:"authentication.sessionToken.secret",envName:"",message:"authentication.sessionToken.secret is required when authentication is enabled."})}if(config.authentication?.oauth?.enabled&&config.authentication.oauth.providers){let resolvedProviders={};for(let[providerName,providerConfig]of Object.entries(config.authentication.oauth.providers)){if(!providerConfig)continue;let{clientId:clientIdEnvName,clientSecret:clientSecretEnvName,redirectUri:redirectUriEnvName,tenantId:tenantIdEnvName}=providerConfig,clientId=process.env[clientIdEnvName],clientSecret=process.env[clientSecretEnvName],redirectUri=process.env[redirectUriEnvName]??redirectUriEnvName,tenantId=tenantIdEnvName?process.env[tenantIdEnvName]??tenantIdEnvName:void 0;if(!clientId)errors.push({field:`authentication.oauth.providers.${providerName}.clientId`,envName:clientIdEnvName,message:`Environment variable "${clientIdEnvName}" is not set (OAuth ${providerName} clientId).`});if(!clientSecret)errors.push({field:`authentication.oauth.providers.${providerName}.clientSecret`,envName:clientSecretEnvName,message:`Environment variable "${clientSecretEnvName}" is not set (OAuth ${providerName} clientSecret).`});if(clientId&&clientSecret)resolvedProviders[providerName]={clientId,clientSecret,redirectUri,tenantId,scopes:providerConfig.scopes,authorizationUrl:providerConfig.authorizationUrl,tokenUrl:providerConfig.tokenUrl,userInfoUrl:providerConfig.userInfoUrl,extraAuthParams:providerConfig.extraAuthParams}}if(Object.keys(resolvedProviders).length>0)resolved.oauthProviders=resolvedProviders}return{valid:errors.length===0,errors,resolved}}async function ensureDatabaseExists(databaseUrl,logger2,authMode){let{Pool:Pool2}=await import("pg"),targetDb=new URL(databaseUrl).pathname.replace("/","");if(!targetDb)return;let adminUrl=new URL(databaseUrl);adminUrl.pathname="/postgres";let pool;if(authMode&&authMode!=="password"){let{getPostgresToken:getPostgresToken2}=await Promise.resolve().then(() => (init_Azure(),exports_Azure));pool=new Pool2({connectionString:adminUrl.toString(),password:getPostgresToken2,ssl:{rejectUnauthorized:!0}})}else pool=new Pool2({connectionString:adminUrl.toString()});try{if((await pool.query("SELECT 1 FROM pg_database WHERE datname = $1",[targetDb])).rowCount===0)logger2.info(`[Database] Creating database "${targetDb}"...`),await pool.query(`CREATE DATABASE "${targetDb}" TEMPLATE template0`),logger2.info(`[Database] Database "${targetDb}" created successfully`);else logger2.info(`[Database] Database "${targetDb}" exists`)}catch(err){let message=err instanceof Error?err.message:String(err);logger2.warn(`[Database] Could not auto-create database: ${message}`)}finally{await pool.end()}}var redisManagerInstance=null,FORMAT_PATTERNS,HTML_ENTITIES,ACCESS_TOKEN_CACHE_PREFIX="access_token:",REFRESH_LOCK_PREFIX="refresh_lock:",LOCK_TTL_SECONDS=5,LOCK_WAIT_TIMEOUT_MS=3000,ACCESS_TOKEN_CACHE_TTL_SECONDS=60;var init_utils5=__esm(()=>{init_Managers();init_Services();init_Logger2();FORMAT_PATTERNS={email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,url:/^https?:\/\/.+/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/,time:/^\d{2}:\d{2}:\d{2}$/,uri:/^[a-z][a-z0-9+.-]*:/i,ipv4:/^(\d{1,3}\.){3}\d{1,3}$/,ipv6:/^([0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$/i};HTML_ENTITIES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#96;","=":"&#x3D;"}});import{eq as eq10}from"drizzle-orm";import{pgSchema}from"drizzle-orm/pg-core";class TenantRegistry{db;logger;mainSchemaName;mainSchemaTables;mainSchemaRelations;createAllTablesForSchema;createAllRelationsForSchema;appId;authMode;tenantResolution;tenantHeader;redisCacheTtlSeconds;defaultTrustedSources;idpUrl;allowDataLoss;tenantsBySubdomain=new Map;tenantsBySchemaName=new Map;tenantsById=new Map;schemaContexts=new Map;tenantFeatures=new Map;tenantsByDomainHostname=new Map;constructor(config){this.db=config.db,this.logger=config.logger,this.mainSchemaName=config.mainSchemaName,this.mainSchemaTables=config.mainSchemaTables,this.mainSchemaRelations=config.mainSchemaRelations,this.createAllTablesForSchema=config.createAllTablesForSchema,this.createAllRelationsForSchema=config.createAllRelationsForSchema,this.appId=config.appId,this.authMode=config.authMode,this.tenantResolution=config.tenantResolution,this.tenantHeader=config.tenantHeader,this.redisCacheTtlSeconds=config.redisCacheTtlSeconds,this.defaultTrustedSources=config.defaultTrustedSources,this.idpUrl=config.idpUrl,this.allowDataLoss=config.allowDataLoss===!0}async initialize(){this.logger.info("[TenantRegistry] Initializing..."),this.schemaContexts.set(this.mainSchemaName,{schemaName:this.mainSchemaName,schemaTables:this.mainSchemaTables,schemaRelations:this.mainSchemaRelations,tenant:null});let tenants=await this.loadTenantsFromDb();this.logger.info(`[TenantRegistry] Loaded ${tenants.length} tenants from database`);let features=await this.loadTenantFeaturesFromDb();this.logger.info(`[TenantRegistry] Loaded ${features.length} tenant feature mappings`);for(let tenant of tenants)this.indexTenant(tenant);for(let feature of features){let existing=this.tenantFeatures.get(feature.tenantId)||[];existing.push(feature),this.tenantFeatures.set(feature.tenantId,existing)}let activeTenants=tenants.filter((t)=>t.status==="active");for(let tenant of activeTenants)await this.buildSchemaContext(tenant);await this.loadDomainHostnames(),this.logger.info(`[TenantRegistry] Initialized with ${activeTenants.length} active tenant schemas + main schema`)}resolveFromRequest(request){let url=new URL(request.url),host=request.headers.get("host")||url.host||"",normalizedHost=normalizeHost(host);if(normalizedHost){let byHostname=this.tenantsByDomainHostname.get(normalizedHost);if(byHostname)return this.validateAndReturnTenant(byHostname)}if(this.tenantResolution==="subdomain"||this.tenantResolution==="both"){let subdomain=extractSubdomain(host);if(subdomain){let tenant=this.tenantsBySubdomain.get(subdomain);if(tenant)return this.validateAndReturnTenant(tenant);return{resolved:!1,error:`Tenant not found for subdomain: ${subdomain}`,statusCode:404}}}if(this.tenantResolution==="header"||this.tenantResolution==="both"){let tenantIdOrSubdomain=request.headers.get(this.tenantHeader);if(tenantIdOrSubdomain){let result=this.resolveFromHeader(tenantIdOrSubdomain,request);if(result)return result}}let mainContext=this.schemaContexts.get(this.mainSchemaName);if(mainContext)return{resolved:!0,context:mainContext};return{resolved:!1,error:"No tenant could be resolved and main schema is unavailable",statusCode:500}}getSchemaContext(schemaName){return this.schemaContexts.get(schemaName)}getMainContext(){let ctx=this.schemaContexts.get(this.mainSchemaName);if(!ctx)throw Error("[TenantRegistry] Main schema context not initialized");return ctx}getActiveTenants(){return Array.from(this.tenantsById.values()).filter((t)=>t.status==="active")}getTenantById(id){return this.tenantsById.get(id)}getTenantFeatures(tenantId){return this.tenantFeatures.get(tenantId)||[]}isTenantFeatureEnabled(tenantId,featureName){return(this.tenantFeatures.get(tenantId)||[]).find((f)=>f.featureName===featureName)?.enabled??!1}getTenantIdsWithFeature(featureName){let result=[];for(let[tenantId,features]of this.tenantFeatures)if(features.find((f)=>f.featureName===featureName&&f.enabled))result.push(tenantId);return result}getSchemaNamesWithFeature(featureName){let tenantIds=this.getTenantIdsWithFeature(featureName),schemaNames=[];for(let tenantId of tenantIds){let tenant=this.tenantsById.get(tenantId);if(tenant&&tenant.status==="active")schemaNames.push(tenant.schemaName)}return schemaNames}getAllSchemaNames(){return Array.from(this.schemaContexts.keys())}async provisionTenant(tenant){this.logger.info(`[TenantRegistry] Provisioning tenant: ${tenant.subdomain} \u2192 ${tenant.schemaName}`),await ensureSchemaExists(this.db,tenant.schemaName);let context=await this.buildSchemaContext(tenant);return this.indexTenant(tenant),await this.syncSchemaToDb(context),this.logger.info(`[TenantRegistry] Tenant provisioned: ${tenant.subdomain}`),context}async syncSchemaToDb(context){let{pushSchema}=await import("drizzle-kit/api"),{applySchemaPush:applySchemaPush2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),targetSchema=pgSchema(context.schemaName);try{let push=await pushSchema({schema:targetSchema,...context.schemaTables},this.db,[context.schemaName]);if(await applySchemaPush2(push,{schemaName:context.schemaName,allowDataLoss:this.allowDataLoss,logger:this.logger}))this.logger.info(`[TenantRegistry] Schema sync completed for: ${context.schemaName}`)}catch(err){let msg=err instanceof Error?err.message:String(err);this.logger.warn(`[TenantRegistry] Schema sync warning for ${context.schemaName}: ${msg}`)}}async syncAllSchemas(){for(let[schemaName,context]of this.schemaContexts)this.logger.info(`[TenantRegistry] Syncing schema: ${schemaName}`),await ensureSchemaExists(this.db,schemaName),await this.syncSchemaToDb(context)}async invalidateCache(subdomain){try{let{getRedisManager:getRedisManager2}=await Promise.resolve().then(() => (init_utils5(),exports_utils)),redis=getRedisManager2();if(redis)await redis.remove(`tenant:${subdomain}`),this.logger.info(`[TenantRegistry] Cache invalidated for: ${subdomain}`)}catch{}}async refreshTenant(tenantId){let tenantsTable=this.mainSchemaTables.tenants;if(!tenantsTable)return;let row=(await this.db.select().from(tenantsTable).where(eq10(tenantsTable.id,tenantId)).limit(1))[0];if(!row)return;let tenant=rowToTenantRecord(row),oldTenant=this.tenantsById.get(tenantId);if(oldTenant)this.tenantsBySubdomain.delete(oldTenant.subdomain),this.tenantsBySchemaName.delete(oldTenant.schemaName);if(this.indexTenant(tenant),tenant.status==="active")await this.buildSchemaContext(tenant);else this.schemaContexts.delete(tenant.schemaName);if(oldTenant)await this.invalidateCache(oldTenant.subdomain);await this.invalidateCache(tenant.subdomain)}async initializeFromIdp(){if(!this.idpUrl){this.logger.error("[TenantRegistry] Consumer multi-tenant requires idpUrl (IDP_URL)");return}this.logger.info(`[TenantRegistry] Initializing from IDP: ${this.idpUrl}`),this.schemaContexts.set(this.mainSchemaName,{schemaName:this.mainSchemaName,schemaTables:this.mainSchemaTables,schemaRelations:this.mainSchemaRelations,tenant:null});let tenants=await this.loadTenantsFromIdp();this.logger.info(`[TenantRegistry] Fetched ${tenants.length} tenants from IDP`);for(let tenant of tenants)this.indexTenant(tenant);let activeTenants=tenants.filter((t)=>t.status==="active");for(let tenant of activeTenants)await this.buildSchemaContext(tenant);await this.loadDomainHostnames(),this.logger.info(`[TenantRegistry] Consumer initialized with ${activeTenants.length} active tenant schemas + main schema`)}isConsumerMode(){return this.authMode==="consumer"&&!!this.idpUrl}async syncFromIdp(){if(!this.isConsumerMode())return{added:[],removed:[],total:this.tenantsById.size};let tenants=await this.loadTenantsFromIdp(),added=[],removed=[],seenSchemaNames=new Set;for(let tenant of tenants){seenSchemaNames.add(tenant.schemaName);let known=this.tenantsById.get(tenant.id);if(known)this.tenantsBySubdomain.delete(known.subdomain),this.tenantsBySchemaName.delete(known.schemaName);if(this.indexTenant(tenant),tenant.status==="active"){if(!this.schemaContexts.has(tenant.schemaName)){await ensureSchemaExists(this.db,tenant.schemaName);let ctx=await this.buildSchemaContext(tenant);await this.syncSchemaToDb(ctx),added.push(tenant.schemaName),await this.invalidateCache(tenant.subdomain),this.logger.info(`[TenantRegistry] Synced new tenant from IDP: ${tenant.subdomain}`)}}else if(this.schemaContexts.has(tenant.schemaName))this.schemaContexts.delete(tenant.schemaName),removed.push(tenant.schemaName),await this.invalidateCache(tenant.subdomain),this.logger.info(`[TenantRegistry] Deactivated tenant context: ${tenant.subdomain}`)}for(let[schemaName,ctx]of this.schemaContexts){if(schemaName===this.mainSchemaName)continue;if(!seenSchemaNames.has(schemaName)){if(this.schemaContexts.delete(schemaName),removed.push(schemaName),ctx.tenant)this.tenantsBySubdomain.delete(ctx.tenant.subdomain),this.tenantsById.delete(ctx.tenant.id),this.tenantsBySchemaName.delete(schemaName),await this.invalidateCache(ctx.tenant.subdomain)}}return{added,removed,total:tenants.length}}registerDomainHostname(hostname,tenantId){let tenant=this.tenantsById.get(tenantId);if(!tenant)return;this.tenantsByDomainHostname.set(normalizeHost(hostname),tenant)}unregisterDomainHostname(hostname){this.tenantsByDomainHostname.delete(normalizeHost(hostname))}async loadDomainHostnames(){let table=this.mainSchemaTables.domainHostnames;if(!table)return 0;try{let rows=await this.db.select().from(table),count=0;this.tenantsByDomainHostname.clear();for(let row of rows){let status=String(row.status??""),tenantId=String(row.tenantId??row.tenant_id??""),hostname=String(row.normalizedHostname??row.normalized_hostname??"");if(status!=="active"||!tenantId||!hostname)continue;let tenant=this.tenantsById.get(tenantId);if(!tenant)continue;this.tenantsByDomainHostname.set(normalizeHost(hostname),tenant),count++}if(count>0)this.logger.info(`[TenantRegistry] Indexed ${count} active custom hostnames`);return count}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to load custom hostnames: ${msg}`),0}}async loadTenantsFromIdp(){if(!this.idpUrl)return[];try{let response=await fetch(`${this.idpUrl}/tenants`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!response.ok)return this.logger.warn(`[TenantRegistry] IDP tenant fetch failed: ${response.status} ${response.statusText}`),[];return((await response.json())?.data?.items||[]).map((item)=>rowToTenantRecord(item))}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to fetch tenants from IDP: ${msg}`),[]}}async loadTenantsFromDb(){let tenantsTable=this.mainSchemaTables.tenants;if(!tenantsTable)return this.logger.warn("[TenantRegistry] No tenants table found in main schema"),[];try{return(await this.db.select().from(tenantsTable)).map((row)=>rowToTenantRecord(row))}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to load tenants: ${msg}`),[]}}async loadTenantFeaturesFromDb(){let featuresTable=this.mainSchemaTables.tenantFeatures;if(!featuresTable)return this.logger.warn("[TenantRegistry] No tenant_features table found in main schema"),[];try{return(await this.db.select().from(featuresTable)).map((row)=>rowToFeatureRecord(row,parseJsonbToConfig))}catch(err){let msg=err instanceof Error?err.message:String(err);return this.logger.warn(`[TenantRegistry] Failed to load tenant features: ${msg}`),[]}}indexTenant(tenant){if(this.tenantsById.set(tenant.id,tenant),this.tenantsBySubdomain.set(tenant.subdomain,tenant),this.tenantsBySchemaName.set(tenant.schemaName,tenant),tenant.domain)this.tenantsBySubdomain.set(tenant.domain,tenant)}async buildSchemaContext(tenant){let schema=pgSchema(tenant.schemaName),schemaTables=this.createAllTablesForSchema(schema),schemaRelations=this.createAllRelationsForSchema?this.createAllRelationsForSchema(schema):{},context={schemaName:tenant.schemaName,schemaTables,schemaRelations,tenant};return this.schemaContexts.set(tenant.schemaName,context),context}resolveFromHeader(tenantIdOrSubdomain,request){let tenant=this.tenantsBySubdomain.get(tenantIdOrSubdomain);if(!tenant)tenant=this.tenantsById.get(tenantIdOrSubdomain);if(!tenant)tenant=this.tenantsBySchemaName.get(tenantIdOrSubdomain);if(!tenant)return{resolved:!1,error:`Tenant not found for header value: ${tenantIdOrSubdomain}`,statusCode:404};if(!isTrustedSource(tenant,request,this.authMode,this.defaultTrustedSources))return{resolved:!1,error:`Untrusted source for tenant: ${tenant.subdomain}`,statusCode:403};return this.validateAndReturnTenant(tenant)}validateAndReturnTenant(tenant){if(tenant.status==="suspended")return{resolved:!1,error:`Tenant ${tenant.subdomain} is suspended: ${tenant.suspendedReason||"No reason provided"}`,statusCode:403};if(tenant.status==="provisioning")return{resolved:!1,error:`Tenant ${tenant.subdomain} is still being provisioned`,statusCode:503};if(tenant.status==="archived")return{resolved:!1,error:`Tenant ${tenant.subdomain} has been archived`,statusCode:410};let context=this.schemaContexts.get(tenant.schemaName);if(!context)return{resolved:!1,error:`Schema context not found for tenant: ${tenant.subdomain}`,statusCode:500};return{resolved:!0,context}}}var init_TenantRegistry=__esm(()=>{init_schema()});var init_Tenant=__esm(()=>{init_schema();init_TenantRegistry()});var init_types5=()=>{};import{and as and5,desc as desc2,eq as eq11,inArray as inArray2}from"drizzle-orm";function toCamel2(obj){let result={};for(let[key,value]of Object.entries(obj)){let camelKey=key.replace(/_([a-z])/g,(_,c)=>c.toUpperCase());result[camelKey]=value}return result}function fromCamel2(obj){let result={};for(let[key,value]of Object.entries(obj)){let snakeKey=key.replace(/[A-Z]/g,(c)=>`_${c.toLowerCase()}`);result[snakeKey]=value}return result}class VerificationService{db;schemaTables;config;logger;onNotificationTrigger;constructor(serviceConfig){this.db=serviceConfig.db,this.schemaTables=serviceConfig.schemaTables,this.config=serviceConfig.config,this.logger=serviceConfig.logger}setNotificationHandler(handler){this.onNotificationTrigger=handler}getConnectedNotificationNodeIds(stepNodeId,steps,edges){let result=new Set,getNeighbors=(nid)=>{let neighbors=[];for(let edge of edges){let{sourceNodeId:src,targetNodeId:tgt}=edge;if(src===nid)neighbors.push(tgt);else if(tgt===nid)neighbors.push(src)}return neighbors},directNeighbors=getNeighbors(stepNodeId);for(let neighborId of directNeighbors)if(steps.find((s)=>s.nodeId===neighborId)?.nodeType==="notification")result.add(neighborId);for(let neighborId of directNeighbors)if(steps.find((s)=>s.nodeId===neighborId)?.nodeType==="verifier"){let verifierNeighbors=getNeighbors(neighborId);for(let vNeighborId of verifierNeighbors){if(vNeighborId===stepNodeId)continue;if(steps.find((s)=>s.nodeId===vNeighborId)?.nodeType==="notification")result.add(vNeighborId)}}let ids=[...result];return this.logger.info(`[Verification] Connected notification nodes for step ${stepNodeId}: [${ids.join(", ")}]`),ids}getTable(name){return resolveSchemaTable(this.schemaTables,name,this.logger)}getCol(table,col4){return table[col4]}async listFlows(entityName){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return[];return(await(entityName?this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"entityName"),entityName)):this.db.select().from(flowsTable))).map((r)=>fromCamel2(r))}async getFlow(flowId){let flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),notifRulesTable=this.getTable("verificationNotificationRules"),notifRecipientsTable=this.getTable("verificationNotificationRecipients"),notifChannelsTable=this.getTable("verificationNotificationChannels");if(!flowsTable)return null;let flowRow=(await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),flowId)).limit(1))[0];if(!flowRow)return null;let flow=fromCamel2(flowRow),steps=(stepsTable?await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),edges=(edgesTable?await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),verifierConfigs=(verifierConfigsTable?await this.db.select().from(verifierConfigsTable).where(eq11(this.getCol(verifierConfigsTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),notifRules=(notifRulesTable?await this.db.select().from(notifRulesTable).where(eq11(this.getCol(notifRulesTable,"flowId"),flowId)):[]).map((r)=>fromCamel2(r)),ruleIds=notifRules.map((r)=>r.id),notifRecipients=(notifRecipientsTable&&ruleIds.length>0?await this.db.select().from(notifRecipientsTable).where(inArray2(this.getCol(notifRecipientsTable,"ruleId"),ruleIds)):[]).map((r)=>fromCamel2(r)),notifChannels=(notifChannelsTable&&ruleIds.length>0?await this.db.select().from(notifChannelsTable).where(inArray2(this.getCol(notifChannelsTable,"ruleId"),ruleIds)):[]).map((r)=>fromCamel2(r));return{flow,graph:{steps,edges,verifier_configs:verifierConfigs,notification_rules:notifRules,notification_recipients:notifRecipients,notification_channels:notifChannels}}}async saveFlow(params){let flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),notifRulesTable=this.getTable("verificationNotificationRules"),notifRecipientsTable=this.getTable("verificationNotificationRecipients"),notifChannelsTable=this.getTable("verificationNotificationChannels");if(!flowsTable||!stepsTable||!edgesTable)throw Error("Verification tables not configured");let existingFlows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),params.flow_id)).limit(1),flowId=params.flow_id;if(existingFlows.length>0)await this.db.update(flowsTable).set(toCamel2({entity_name:params.entity_name,name:params.name,description:params.description||null,trigger_on:params.trigger_on,trigger_fields:params.trigger_fields||null,is_draft:params.is_draft,viewport:params.viewport||null})).where(eq11(this.getCol(flowsTable,"id"),flowId));else{let[newFlow]=await this.db.insert(flowsTable).values(toCamel2({id:flowId,entity_name:params.entity_name,name:params.name,description:params.description||null,trigger_on:params.trigger_on,trigger_fields:params.trigger_fields||null,is_draft:params.is_draft,viewport:params.viewport||null})).returning();flowId=newFlow.id}if(await this.db.delete(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),flowId)),edgesTable)await this.db.delete(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),flowId));if(verifierConfigsTable)await this.db.delete(verifierConfigsTable).where(eq11(this.getCol(verifierConfigsTable,"flowId"),flowId));if(notifRulesTable){let oldRuleIds=(await this.db.select().from(notifRulesTable).where(eq11(this.getCol(notifRulesTable,"flowId"),flowId))).map((r)=>r.id);if(oldRuleIds.length>0){if(notifRecipientsTable)for(let rid of oldRuleIds)await this.db.delete(notifRecipientsTable).where(eq11(this.getCol(notifRecipientsTable,"ruleId"),rid));if(notifChannelsTable)for(let rid of oldRuleIds)await this.db.delete(notifChannelsTable).where(eq11(this.getCol(notifChannelsTable,"ruleId"),rid))}await this.db.delete(notifRulesTable).where(eq11(this.getCol(notifRulesTable,"flowId"),flowId))}let{graph}=params;if(graph.steps.length>0)await this.db.insert(stepsTable).values(graph.steps.map((s)=>toCamel2({flow_id:flowId,entity_name:params.entity_name,node_id:s.node_id,node_type:s.node_type,step_order:s.step_order,name:s.name||null,description:s.description||null,position_x:s.position_x,position_y:s.position_y,width:s.width||null,height:s.height||null,style:s.style||null,data:s.data||null})));if(graph.edges.length>0&&edgesTable)await this.db.insert(edgesTable).values(graph.edges.map((e)=>toCamel2({flow_id:flowId,edge_id:e.edge_id,source_node_id:e.source_node_id,target_node_id:e.target_node_id,source_handle:e.source_handle||null,target_handle:e.target_handle||null,edge_type:e.edge_type,label:e.label||null,condition:e.condition||null,style:e.style||null,animated:e.animated})));if(graph.verifier_configs.length>0&&verifierConfigsTable)await this.db.insert(verifierConfigsTable).values(graph.verifier_configs.map((vc)=>toCamel2({flow_id:flowId,node_id:vc.node_id,verifier_type:vc.verifier_type,verifier_user_id:vc.verifier_user_id||null,verifier_role:vc.verifier_role||null,require_signature:vc.require_signature,all_must_approve:vc.all_must_approve})));if(this.logger.info(`[Verification] Save: ${graph.notification_rules.length} rules, ${graph.notification_recipients.length} recipients, ${graph.notification_channels.length} channels`),graph.notification_rules.length>0&&notifRulesTable)for(let rule of graph.notification_rules){this.logger.info(`[Verification] Saving notification rule: node_id=${rule.node_id}, trigger=${rule.trigger}, title_template=${JSON.stringify(rule.title_template)}, body_template=${JSON.stringify(rule.body_template)}`);let[insertedRule]=await this.db.insert(notifRulesTable).values(toCamel2({flow_id:flowId,node_id:rule.node_id,trigger:rule.trigger,title_template:rule.title_template||null,body_template:rule.body_template||null,starts_at:rule.starts_at||null,expires_at:rule.expires_at||null})).returning(),ruleId=insertedRule.id,ruleRecipients=graph.notification_recipients.filter((r)=>r.rule_id===rule.node_id);if(ruleRecipients.length>0&&notifRecipientsTable)await this.db.insert(notifRecipientsTable).values(ruleRecipients.map((r)=>toCamel2({rule_id:ruleId,recipient_type:r.recipient_type,recipient_user_id:r.recipient_user_id||null,recipient_role:r.recipient_role||null})));let ruleChannels=graph.notification_channels.filter((c)=>c.rule_id===rule.node_id);if(ruleChannels.length>0&&notifChannelsTable)await this.db.insert(notifChannelsTable).values(ruleChannels.map((c)=>toCamel2({rule_id:ruleId,channel:c.channel})))}return this.logger.info(`[Verification] Flow saved: ${flowId} for ${params.entity_name}`),{success:!0,flow_id:flowId}}async publishFlow(flowId){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return{success:!1,message:"Flow table not configured"};return await this.db.update(flowsTable).set(toCamel2({is_draft:!1,published_at:new Date})).where(eq11(this.getCol(flowsTable,"id"),flowId)),this.logger.info(`[Verification] Flow published: ${flowId}`),{success:!0,message:"Flow published"}}async deleteFlow(flowId){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return{success:!1,message:"Flow table not configured"};return await this.db.delete(flowsTable).where(eq11(this.getCol(flowsTable,"id"),flowId)),this.logger.info(`[Verification] Flow deleted: ${flowId}`),{success:!0,message:"Flow deleted"}}async startFlow(params){let flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),instancesTable=this.getTable("verificationInstances"),requirementsTable=this.getTable("verificationRequirements"),userRolesTable=this.getTable("userRoles");if(!flowsTable||!stepsTable||!edgesTable||!instancesTable||!requirementsTable)return{success:!1,message:"Verification tables not configured"};let flow=(await this.db.select().from(flowsTable).where(and5(eq11(this.getCol(flowsTable,"id"),params.flow_id),eq11(this.getCol(flowsTable,"isDraft"),!1))).limit(1))[0];if(!flow)return{success:!1,message:"Published flow not found"};if((await this.db.select().from(instancesTable).where(and5(eq11(this.getCol(instancesTable,"entityName"),params.entity_name),eq11(this.getCol(instancesTable,"entityId"),params.entity_id),eq11(this.getCol(instancesTable,"status"),"active"))).limit(1)).length>0)return{success:!1,message:"An active verification instance already exists for this entity"};let steps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),params.flow_id)),edges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),params.flow_id)),stepNodes=steps.filter((s)=>s.nodeType==="step");if(stepNodes.sort((a,b)=>a.stepOrder-b.stepOrder),stepNodes.length===0)return{success:!1,message:"Flow has no step nodes"};let[instance]=await this.db.insert(instancesTable).values(toCamel2({flow_id:params.flow_id,entity_name:params.entity_name,entity_id:params.entity_id,started_by:params.started_by||null,status:"active",current_step_order:1,started_at:new Date})).returning(),instanceId=instance.id;if(await this.materializeRequirementsForStep(instanceId,params.flow_id,params.entity_name,params.entity_id,1,steps,edges,verifierConfigsTable,requirementsTable,userRolesTable),this.onNotificationTrigger){let firstStep=stepNodes[0],firstStepNodeId=firstStep?.nodeId,connectedNotifIds=firstStepNodeId?this.getConnectedNotificationNodeIds(firstStepNodeId,steps,edges):[],ctx={flow_name:flow.name,step_name:firstStep?.name||"Step 1",step_order:1,total_steps:stepNodes.length};if(connectedNotifIds.length>0)for(let notifNodeId of connectedNotifIds)await this.onNotificationTrigger({trigger:"on_flow_started",flow_id:params.flow_id,entity_name:params.entity_name,entity_id:params.entity_id,node_id:notifNodeId,context:ctx});else await this.onNotificationTrigger({trigger:"on_flow_started",flow_id:params.flow_id,entity_name:params.entity_name,entity_id:params.entity_id,context:ctx})}return this.logger.info(`[Verification] Flow started: instance ${instanceId} for ${params.entity_name}:${params.entity_id}`),{success:!0,instance_id:instanceId,message:"Flow started"}}async materializeRequirementsForStep(instanceId,flowId,entityName,entityId,stepOrder,steps,edges,verifierConfigsTable,requirementsTable,userRolesTable){if(!requirementsTable)return;let stepNode=steps.find((s)=>s.nodeType==="step"&&s.stepOrder===stepOrder);if(!stepNode)return;let stepNodeId=stepNode.nodeId,verifierNodeIds=edges.filter((e)=>e.targetNodeId===stepNodeId).map((e)=>e.sourceNodeId),verifierNodes=steps.filter((s)=>s.nodeType==="verifier"&&verifierNodeIds.includes(s.nodeId));if(verifierNodes.length===0)return;let verifierConfigs=[];if(verifierConfigsTable)verifierConfigs=await this.db.select().from(verifierConfigsTable).where(eq11(this.getCol(verifierConfigsTable,"flowId"),flowId));for(let verifierNode of verifierNodes){let nodeId=verifierNode.nodeId,config=verifierConfigs.find((vc)=>vc.nodeId===nodeId);if(!config)continue;let{verifierType,allMustApprove}=config;if(verifierType==="role"&&allMustApprove&&userRolesTable){let rolesTable=this.getTable("roles");if(rolesTable){let rolesCols=rolesTable,userRolesCols=userRolesTable,role=(await this.db.select().from(rolesTable).where(eq11(rolesCols.name,config.verifierRole)).limit(1))[0];if(role){let usersWithRole=await this.db.select({user_id:userRolesCols.userId}).from(userRolesTable).where(eq11(userRolesCols.roleId,role.id));for(let userRole of usersWithRole)await this.db.insert(requirementsTable).values(toCamel2({instance_id:instanceId,step_node_id:stepNodeId,verifier_node_id:nodeId,entity_name:entityName,entity_id:entityId,verifier_type:"user",verifier_user_id:userRole.user_id,verifier_role:config.verifierRole||null,require_signature:config.requireSignature,all_must_approve:!0,step_order:stepOrder,status:"pending"}))}}}else await this.db.insert(requirementsTable).values(toCamel2({instance_id:instanceId,step_node_id:stepNodeId,verifier_node_id:nodeId,entity_name:entityName,entity_id:entityId,verifier_type:verifierType,verifier_user_id:config.verifierUserId||null,verifier_role:config.verifierRole||null,require_signature:config.requireSignature,all_must_approve:allMustApprove,step_order:stepOrder,status:"pending"}))}if(this.onNotificationTrigger){let connectedNotifIds=this.getConnectedNotificationNodeIds(stepNodeId,steps,edges);if(this.logger.info(`[Verification] on_step_reached: stepNodeId=${stepNodeId}, connectedNotifIds=[${connectedNotifIds.join(", ")}]`),connectedNotifIds.length>0)for(let notifNodeId of connectedNotifIds)this.logger.info(`[Verification] Triggering on_step_reached for notifNodeId=${notifNodeId}`),await this.onNotificationTrigger({trigger:"on_step_reached",flow_id:flowId,entity_name:entityName,entity_id:entityId,node_id:notifNodeId,context:{step_name:stepNode.name||`Step ${stepOrder}`,step_order:stepOrder}});else await this.onNotificationTrigger({trigger:"on_step_reached",flow_id:flowId,entity_name:entityName,entity_id:entityId,context:{step_name:stepNode.name||`Step ${stepOrder}`,step_order:stepOrder}})}}async getStatus(entityName,entityId){let instancesTable=this.getTable("verificationInstances"),flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),verificationsTable=this.getTable("verifications"),requirementsTable=this.getTable("verificationRequirements"),emptyStatus={entity_name:entityName,entity_id:entityId,instance:null,flow:null,current_step:0,total_steps:0,is_completed:!1,is_rejected:!1,verifications:[],pending_requirements:[]};if(!instancesTable||!flowsTable||!verificationsTable||!requirementsTable)return this.logger.error("[Verification] Required tables not found"),emptyStatus;let instanceRow=(await this.db.select().from(instancesTable).where(and5(eq11(this.getCol(instancesTable,"entityName"),entityName),eq11(this.getCol(instancesTable,"entityId"),entityId))).orderBy(desc2(this.getCol(instancesTable,"createdAt"))).limit(1))[0];if(!instanceRow)return emptyStatus;let instance=fromCamel2(instanceRow),flows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),instance.flow_id)).limit(1),flow=flows[0]?fromCamel2(flows[0]):void 0,totalSteps=(stepsTable?await this.db.select().from(stepsTable).where(and5(eq11(this.getCol(stepsTable,"flowId"),instance.flow_id),eq11(this.getCol(stepsTable,"nodeType"),"step"))):[]).length,verifications=(await this.db.select().from(verificationsTable).where(eq11(this.getCol(verificationsTable,"instanceId"),instance.id)).orderBy(desc2(this.getCol(verificationsTable,"createdAt")))).map((r)=>fromCamel2(r)),pendingRequirements=(await this.db.select().from(requirementsTable).where(and5(eq11(this.getCol(requirementsTable,"instanceId"),instance.id),eq11(this.getCol(requirementsTable,"status"),"pending")))).map((r)=>fromCamel2(r));return{entity_name:entityName,entity_id:entityId,instance,flow:flow||null,current_step:instance.current_step_order,total_steps:totalSteps,is_completed:instance.status==="completed",is_rejected:instance.status==="rejected",verifications,pending_requirements:pendingRequirements}}async decide(params){let{entity_name,entity_id,user_id,decision,reason,signature_id,diff}=params,verificationsTable=this.getTable("verifications"),requirementsTable=this.getTable("verificationRequirements"),instancesTable=this.getTable("verificationInstances"),stepsTable=this.getTable("verificationSteps"),edgesTable=this.getTable("verificationEdges"),verifierConfigsTable=this.getTable("verificationVerifierConfigs"),userRolesTable=this.getTable("userRoles"),rolesTable=this.getTable("roles");if(!verificationsTable||!requirementsTable||!instancesTable)return{success:!1,message:"Verification tables not configured"};let status=await this.getStatus(entity_name,entity_id);if(!status.instance||status.instance.status!=="active")return{success:!1,message:"No active verification instance"};let currentPending=status.pending_requirements.filter((r)=>r.step_order===status.current_step);if(currentPending.length===0)return{success:!1,message:"No pending requirements for current step"};let matchedReq=null;for(let req of currentPending){if(req.verifier_type==="user"&&req.verifier_user_id===user_id){matchedReq=req;break}if(req.verifier_type==="role"&&req.verifier_role&&userRolesTable&&rolesTable){let userRolesCols=userRolesTable,rolesCols=rolesTable;if((await this.db.select({role_name:rolesCols.name}).from(userRolesTable).innerJoin(rolesTable,eq11(userRolesCols.roleId,rolesCols.id)).where(eq11(userRolesCols.userId,user_id))).some((ur)=>ur.role_name===req.verifier_role)){matchedReq=req;break}}}if(!matchedReq)return{success:!1,message:"User is not authorized to verify at this step"};if(matchedReq.require_signature&&!signature_id)return{success:!1,message:"Signature is required for this verification step"};let[newVerification]=await this.db.insert(verificationsTable).values(toCamel2({instance_id:status.instance.id,requirement_id:matchedReq.id,verifier_id:user_id,signature_id:signature_id||null,entity_name,entity_id,step_order:status.current_step,decision,reason:reason||null,diff:diff||null})).returning();if(await this.db.update(requirementsTable).set({status:decision}).where(eq11(this.getCol(requirementsTable,"id"),matchedReq.id)),this.onNotificationTrigger&&status.instance){let stepName=`Step ${status.current_step}`,allSteps=[],allEdges=[];if(stepsTable){allSteps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),status.instance.flow_id));let stepRow=allSteps.find((s)=>s.nodeId===matchedReq.step_node_id);if(stepRow?.name)stepName=stepRow.name}if(edgesTable)allEdges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),status.instance.flow_id));let triggerName=decision==="approved"?"on_approved":"on_rejected",ctx={flow_name:status.flow?.name||"",step_name:stepName,step_order:status.current_step,total_steps:status.total_steps,decision},connectedNotifIds=this.getConnectedNotificationNodeIds(matchedReq.step_node_id,allSteps,allEdges);if(connectedNotifIds.length>0)for(let notifNodeId of connectedNotifIds)await this.onNotificationTrigger({trigger:triggerName,flow_id:status.instance.flow_id,entity_name,entity_id,node_id:notifNodeId,verifier_id:user_id,decision,context:ctx});else await this.onNotificationTrigger({trigger:triggerName,flow_id:status.instance.flow_id,entity_name,entity_id,verifier_id:user_id,decision,context:ctx})}if(decision==="rejected"){await this.db.update(instancesTable).set(toCamel2({status:"rejected",completed_at:new Date})).where(eq11(this.getCol(instancesTable,"id"),status.instance.id));let newInstanceId;if(this.config.autoResetOnRejection){this.logger.info(`[Verification] Flow rejected for ${entity_name}:${entity_id}, auto-restarting from step 1`);let restartResult=await this.startFlow({flow_id:status.instance.flow_id,entity_name,entity_id,started_by:status.instance.started_by});if(restartResult.success)newInstanceId=restartResult.instance_id}return{success:!0,message:this.config.autoResetOnRejection?"Verification rejected \u2014 flow restarted from step 1":"Verification rejected",verification:newVerification,flow_completed:!1,new_instance_id:newInstanceId}}let matchedReqId=matchedReq.id,remainingPending=currentPending.filter((r)=>r.id!==matchedReqId);if(remainingPending.length>0)return{success:!0,message:`Step ${status.current_step} partially approved, ${remainingPending.length} verifier(s) remaining`,verification:newVerification,flow_completed:!1};let nextStep=status.current_step+1;if(nextStep>status.total_steps){if(await this.db.update(instancesTable).set(toCamel2({status:"completed",completed_at:new Date})).where(eq11(this.getCol(instancesTable,"id"),status.instance.id)),this.onNotificationTrigger){let completedSteps=[],completedEdges=[];if(stepsTable)completedSteps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),status.instance.flow_id));if(edgesTable)completedEdges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),status.instance.flow_id));let lastStepNodeId=matchedReq.step_node_id,completedNotifIds=this.getConnectedNotificationNodeIds(lastStepNodeId,completedSteps,completedEdges),completedCtx={flow_name:status.flow?.name||"",step_order:status.current_step,total_steps:status.total_steps};if(completedNotifIds.length>0)for(let notifNodeId of completedNotifIds)await this.onNotificationTrigger({trigger:"on_flow_completed",flow_id:status.instance.flow_id,entity_name,entity_id,node_id:notifNodeId,context:completedCtx});else await this.onNotificationTrigger({trigger:"on_flow_completed",flow_id:status.instance.flow_id,entity_name,entity_id,context:completedCtx})}return{success:!0,message:"Verification flow completed",verification:newVerification,flow_completed:!0}}if(await this.db.update(instancesTable).set(toCamel2({current_step_order:nextStep})).where(eq11(this.getCol(instancesTable,"id"),status.instance.id)),stepsTable&&edgesTable){let steps=await this.db.select().from(stepsTable).where(eq11(this.getCol(stepsTable,"flowId"),status.instance.flow_id)),edges=await this.db.select().from(edgesTable).where(eq11(this.getCol(edgesTable,"flowId"),status.instance.flow_id));await this.materializeRequirementsForStep(status.instance.id,status.instance.flow_id,entity_name,entity_id,nextStep,steps,edges,verifierConfigsTable,requirementsTable,userRolesTable)}return{success:!0,message:`Step ${status.current_step} approved, moving to step ${nextStep}`,verification:newVerification,flow_completed:!1,next_step:nextStep}}async startFlowForEntity(params){let flowsTable=this.getTable("verificationFlows");if(!flowsTable)return{success:!1,message:"Flow table not configured"};let flow=(await this.db.select().from(flowsTable).where(and5(eq11(this.getCol(flowsTable,"entityName"),params.entity_name),eq11(this.getCol(flowsTable,"isDraft"),!1))).limit(1))[0];if(!flow)return{success:!1,message:`No published flow found for entity '${params.entity_name}'`};return this.startFlow({flow_id:flow.id,entity_name:params.entity_name,entity_id:params.entity_id,started_by:params.started_by})}async listEntityStatuses(params){let instancesTable=this.getTable("verificationInstances"),flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),emptyResult={items:[],total:0,page:1,limit:20};if(!instancesTable||!flowsTable)return emptyResult;let page=params.page||1,limit=params.limit||20,offset=(page-1)*limit,conditions=[eq11(this.getCol(instancesTable,"entityName"),params.entity_name)];if(params.status)conditions.push(eq11(this.getCol(instancesTable,"status"),params.status));let whereClause=conditions.length===1?conditions[0]:and5(...conditions),allInstances=(await this.db.select().from(instancesTable).where(whereClause).orderBy(desc2(this.getCol(instancesTable,"createdAt")))).map((r)=>fromCamel2(r)),total=allInstances.length,paged=allInstances.slice(offset,offset+limit),items=[];for(let inst of paged){let flowId=inst.flow_id,flows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),flowId)).limit(1),flow=flows[0]?fromCamel2(flows[0]):void 0,totalSteps=0;if(stepsTable)totalSteps=(await this.db.select().from(stepsTable).where(and5(eq11(this.getCol(stepsTable,"flowId"),flowId),eq11(this.getCol(stepsTable,"nodeType"),"step")))).length;items.push({instance_id:inst.id,entity_name:inst.entity_name,entity_id:inst.entity_id,flow_id:flowId,flow_name:flow?.name||"Unknown",status:inst.status,current_step_order:inst.current_step_order,total_steps:totalSteps,started_by:inst.started_by,started_at:inst.started_at,completed_at:inst.completed_at})}return{items,total,page,limit}}async getPending(userId){let requirementsTable=this.getTable("verificationRequirements"),instancesTable=this.getTable("verificationInstances"),flowsTable=this.getTable("verificationFlows"),stepsTable=this.getTable("verificationSteps"),userRolesTable=this.getTable("userRoles"),rolesTable=this.getTable("roles");if(this.logger.info(`[Verification.getPending] userId=${userId}, tables: req=${!!requirementsTable} inst=${!!instancesTable} flow=${!!flowsTable} steps=${!!stepsTable} roles=${!!rolesTable} userRoles=${!!userRolesTable}`),!requirementsTable||!instancesTable||!flowsTable)return this.logger.warn("[Verification.getPending] Missing required tables, returning empty"),[];let userRolesCols=userRolesTable,rolesCols=rolesTable,userRoleNames=(userRolesTable&&rolesTable?await this.db.select({role_name:rolesCols.name}).from(userRolesTable).innerJoin(rolesTable,eq11(userRolesCols.roleId,rolesCols.id)).where(eq11(userRolesCols.userId,userId)):[]).map((ur)=>ur.role_name),pendingReqs=(await this.db.select().from(requirementsTable).where(eq11(this.getCol(requirementsTable,"status"),"pending"))).map((r)=>fromCamel2(r));this.logger.info(`[Verification.getPending] Found ${pendingReqs.length} pending requirements, userRoles=${JSON.stringify(userRoleNames)}`);for(let req of pendingReqs)this.logger.info(`[Verification.getPending] Req: verifier_type=${req.verifier_type} verifier_user_id=${req.verifier_user_id} verifier_role=${req.verifier_role} step_order=${req.step_order} entity=${req.entity_name}/${req.entity_id}`);let pendingItems=[];for(let req of pendingReqs){if(!(req.verifier_type==="user"&&req.verifier_user_id===userId||req.verifier_type==="role"&&userRoleNames.includes(req.verifier_role))){this.logger.info(`[Verification.getPending] Skipping req: canVerify=false (type=${req.verifier_type}, reqUserId=${req.verifier_user_id}, loggedInUserId=${userId})`);continue}let instances=await this.db.select().from(instancesTable).where(and5(eq11(this.getCol(instancesTable,"id"),req.instance_id),eq11(this.getCol(instancesTable,"status"),"active"))).limit(1),instance=instances[0]?fromCamel2(instances[0]):void 0;if(!instance)continue;if(instance.current_step_order!==req.step_order)continue;let flows=await this.db.select().from(flowsTable).where(eq11(this.getCol(flowsTable,"id"),instance.flow_id)).limit(1),flow=flows[0]?fromCamel2(flows[0]):void 0;if(!flow)continue;let stepName;if(stepsTable&&req.step_node_id){let stepRow=(await this.db.select().from(stepsTable).where(and5(eq11(this.getCol(stepsTable,"flowId"),instance.flow_id),eq11(this.getCol(stepsTable,"nodeId"),req.step_node_id))).limit(1))[0];if(stepRow?.name)stepName=stepRow.name}pendingItems.push({instance_id:instance.id,entity_name:req.entity_name,entity_id:req.entity_id,flow_name:flow.name,step_order:req.step_order,step_name:stepName,require_signature:req.require_signature,created_at:req.created_at})}return pendingItems}}var init_Verification=__esm(()=>{init_types5()});import*as crypto5 from"crypto";var IYZICO_PATHS,generateAuthString=(apiKey,secretKey,path2,payload,randomKey)=>{let compound=payload?randomKey+path2+payload:randomKey+path2,encryptedData=crypto5.createHmac("sha256",secretKey).update(compound).digest("hex"),authorizationString=`apiKey:${apiKey}&randomKey:${randomKey}&signature:${encryptedData}`;return`IYZWSv2 ${Buffer.from(authorizationString).toString("base64")}`},buildRequest=(config,path2,payload)=>{let body=JSON.stringify(payload),randomKey=Date.now().toString(32),headers=new Headers;return headers.set("Content-Type","application/json"),headers.set("x-iyzi-rnd",randomKey),headers.set("Authorization",generateAuthString(config.apiKey,config.secretKey,path2,body,randomKey)),{url:new URL(`${config.apiUrl}${path2}`).toString(),headers,body}},iyzicoFetch=async(config,path2,payload)=>{let{url,headers,body}=buildRequest(config,path2,payload);try{let json=await(await fetch(url,{method:"POST",headers,body})).json(),isSuccess=json.status==="success";return{success:isSuccess,data:isSuccess?json:null,errorCode:json.errorCode??void 0,errorMessage:json.errorMessage??void 0,rawResponse:json}}catch(error){let message=error instanceof Error?error.message:"Unknown fetch error";return{success:!1,data:null,errorCode:"NETWORK_ERROR",errorMessage:message,rawResponse:{error:message}}}},createIyzicoProvider=(config)=>{let generateConversationId=()=>`nk-${Date.now().toString(16)}`;return{get name(){return"iyzico"},async initialize3DS(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId,price:request.price,paidPrice:request.paidPrice,currency:request.currency,installment:request.installment??1,paymentChannel:request.paymentChannel??"WEB",basketId:request.basketId??Date.now().toString(16),paymentGroup:request.paymentGroup??"PRODUCT",paymentCard:request.paymentCard,buyer:request.buyer,shippingAddress:request.shippingAddress,billingAddress:request.billingAddress,basketItems:request.basketItems,callbackUrl:request.callbackUrl},result=await iyzicoFetch(config,IYZICO_PATHS.INITIALIZE_3DS,payload);return{success:result.success,threeDSHtmlContent:result.data?.threeDSHtmlContent,paymentId:result.data?.paymentId,signature:result.data?.signature,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async complete3DS(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId,paymentId:request.paymentId},result=await iyzicoFetch(config,IYZICO_PATHS.COMPLETE_3DS,payload);return{success:result.success,paymentId:result.data?.paymentId,price:result.data?.price,paidPrice:result.data?.paidPrice,currency:result.data?.currency,installment:result.data?.installment,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,cardFamily:result.data?.cardFamily,binNumber:result.data?.binNumber,lastFourDigits:result.data?.lastFourDigits,basketId:result.data?.basketId,authCode:result.data?.authCode,signature:result.data?.signature,fraudStatus:result.data?.fraudStatus,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async getPaymentDetail(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),paymentId:request.paymentId,paymentConversationId:request.paymentConversationId},result=await iyzicoFetch(config,IYZICO_PATHS.PAYMENT_DETAIL,payload);return{success:result.success,paymentId:result.data?.paymentId,price:result.data?.price,paidPrice:result.data?.paidPrice,currency:result.data?.currency,basketId:result.data?.basketId,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,lastFourDigits:result.data?.lastFourDigits,binNumber:result.data?.binNumber,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async queryBin(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),binNumber:request.binNumber.slice(0,6)};if(request.price!==void 0)payload.price=request.price;let result=await iyzicoFetch(config,IYZICO_PATHS.BIN_CHECK,payload);return{success:result.success,binNumber:result.data?.binNumber,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,cardFamily:result.data?.cardFamily,bankName:result.data?.bankName,bankCode:result.data?.bankCode,commercial:result.data?.commercial,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async saveCard(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),card:request.card,email:request.email,externalId:request.externalId},result=await iyzicoFetch(config,IYZICO_PATHS.CARD_SAVE,payload);return{success:result.success,cardUserKey:result.data?.cardUserKey,cardToken:result.data?.cardToken,cardAlias:result.data?.cardAlias,binNumber:result.data?.binNumber,lastFourDigits:result.data?.lastFourDigits,cardType:result.data?.cardType,cardAssociation:result.data?.cardAssociation,cardFamily:result.data?.cardFamily,cardBankName:result.data?.cardBankName,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async listCards(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),cardUserKey:request.cardUserKey},result=await iyzicoFetch(config,IYZICO_PATHS.CARD_LIST,payload),cards=(result.data?.cardDetails??[]).map((cd)=>({cardToken:cd.cardToken,cardAlias:cd.cardAlias,binNumber:cd.binNumber,lastFourDigits:cd.lastFourDigits,cardType:cd.cardType,cardAssociation:cd.cardAssociation,cardFamily:cd.cardFamily,cardBankName:cd.cardBankName,cardBankCode:cd.cardBankCode}));return{success:result.success,cardUserKey:result.data?.cardUserKey,cards,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async deleteCard(request){let payload={locale:request.locale??"tr",conversationId:generateConversationId(),cardUserKey:request.cardUserKey,cardToken:request.cardToken},result=await iyzicoFetch(config,IYZICO_PATHS.CARD_DELETE,payload);return{success:result.success,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async refund(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),paymentTransactionId:request.paymentTransactionId,price:request.price,currency:request.currency??"TRY"};if(request.ip)payload.ip=request.ip;let result=await iyzicoFetch(config,IYZICO_PATHS.REFUND,payload);return{success:result.success,paymentId:result.data?.paymentId,price:result.data?.price,currency:result.data?.currency,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},parseCallback(formData){return{success:formData.mdStatus==="1",paymentId:formData.paymentId??"",conversationId:formData.conversationId??"",mdStatus:formData.mdStatus??"",rawData:formData}},async registerSubMerchant(request){let typeMap={personal:"PERSONAL",private_company:"PRIVATE_COMPANY",limited_or_joint_stock_company:"LIMITED_OR_JOINT_STOCK_COMPANY"},payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),subMerchantExternalId:request.subMerchantExternalId,subMerchantType:typeMap[request.subMerchantType]??"PERSONAL",name:request.name,email:request.email,gsmNumber:request.gsmNumber,address:request.address,iban:request.iban,contactName:request.contactName,contactSurname:request.contactSurname,identityNumber:request.identityNumber,currency:request.currency??"TRY"};if(request.subMerchantType==="private_company")payload.taxOffice=request.taxOffice,payload.legalCompanyTitle=request.legalCompanyTitle;if(request.subMerchantType==="limited_or_joint_stock_company")payload.taxOffice=request.taxOffice,payload.taxNumber=request.taxNumber,payload.legalCompanyTitle=request.legalCompanyTitle;let result=await iyzicoFetch(config,IYZICO_PATHS.SUB_MERCHANT_CREATE,payload);return{success:result.success,subMerchantKey:result.data?.subMerchantKey,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async updateSubMerchant(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),subMerchantKey:request.subMerchantKey};if(request.name)payload.name=request.name;if(request.email)payload.email=request.email;if(request.gsmNumber)payload.gsmNumber=request.gsmNumber;if(request.address)payload.address=request.address;if(request.iban)payload.iban=request.iban;if(request.contactName)payload.contactName=request.contactName;if(request.contactSurname)payload.contactSurname=request.contactSurname;if(request.identityNumber)payload.identityNumber=request.identityNumber;if(request.taxOffice)payload.taxOffice=request.taxOffice;if(request.taxNumber)payload.taxNumber=request.taxNumber;if(request.legalCompanyTitle)payload.legalCompanyTitle=request.legalCompanyTitle;if(request.currency)payload.currency=request.currency;let result=await iyzicoFetch(config,IYZICO_PATHS.SUB_MERCHANT_UPDATE,payload);return{success:result.success,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async getSubMerchant(request){let payload={locale:request.locale??"tr",conversationId:request.conversationId??generateConversationId(),subMerchantExternalId:request.subMerchantExternalId},result=await iyzicoFetch(config,IYZICO_PATHS.SUB_MERCHANT_DETAIL,payload);return{success:result.success,subMerchantKey:result.data?.subMerchantKey,name:result.data?.name,email:result.data?.email,gsmNumber:result.data?.gsmNumber,address:result.data?.address,iban:result.data?.iban,subMerchantType:result.data?.subMerchantType,currency:result.data?.currency,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async approveSplit(request){let payload={locale:request.locale??"tr",paymentTransactionId:request.paymentTransactionId},result=await iyzicoFetch(config,IYZICO_PATHS.APPROVAL,payload);return{success:result.success,paymentTransactionId:result.data?.paymentTransactionId,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async disapproveSplit(request){let payload={locale:request.locale??"tr",paymentTransactionId:request.paymentTransactionId},result=await iyzicoFetch(config,IYZICO_PATHS.DISAPPROVAL,payload);return{success:result.success,paymentTransactionId:result.data?.paymentTransactionId,errorCode:result.errorCode,errorMessage:result.errorMessage,rawResponse:result.rawResponse}},async createProduct(request){let localId=`iyzico-prod-${Date.now().toString(36)}`;return{success:!0,providerProductId:localId,name:request.name,rawResponse:{local:!0,id:localId}}},async updateProduct(request){return{success:!0,providerProductId:request.providerProductId,rawResponse:{local:!0,updated:request.providerProductId}}},async getProduct(request){return{success:!0,providerProductId:request.providerProductId,rawResponse:{local:!0,message:"Product data is stored locally for iyzico"}}},async listProducts(_request){return{success:!0,products:[],hasMore:!1,rawResponse:{local:!0,message:"Products are stored locally for iyzico"}}},async archiveProduct(request){return{success:!0,rawResponse:{local:!0,archived:request.providerProductId}}},async createPrice(request){let localId=`iyzico-price-${Date.now().toString(36)}`;return{success:!0,providerPriceId:localId,rawResponse:{local:!0,id:localId,product:request.providerProductId}}},async updatePrice(request){return{success:!0,providerPriceId:request.providerPriceId,rawResponse:{local:!0,updated:request.providerPriceId}}},async getPrice(request){return{success:!0,providerPriceId:request.providerPriceId,rawResponse:{local:!0,message:"Price data is stored locally for iyzico"}}},async listPrices(_request){return{success:!0,prices:[],hasMore:!1,rawResponse:{local:!0,message:"Prices are stored locally for iyzico"}}},async archivePrice(request){return{success:!0,rawResponse:{local:!0,archived:request.providerPriceId}}},async createCustomer(request){return{success:!0,providerCustomerId:`local_cus_${Date.now()}`,email:request.email,rawResponse:{local:!0,message:"Customer stored locally for iyzico"}}},async updateCustomer(request){return{success:!0,providerCustomerId:request.providerCustomerId,rawResponse:{local:!0,message:"Customer updated locally for iyzico"}}},async getCustomer(request){return{success:!0,providerCustomerId:request.providerCustomerId,rawResponse:{local:!0,message:"Customer data is stored locally for iyzico"}}},async listCustomers(_request){return{success:!0,customers:[],hasMore:!1,rawResponse:{local:!0,message:"Customers are stored locally for iyzico"}}},async deleteCustomer(_request){return{success:!0,rawResponse:{local:!0,message:"Customer deleted locally for iyzico"}}},async createSubscription(_request){return{success:!0,providerSubscriptionId:`local_sub_${Date.now()}`,status:"active",rawResponse:{local:!0,message:"Subscription stored locally for iyzico"}}},async updateSubscription(request){return{success:!0,providerSubscriptionId:request.providerSubscriptionId,status:"active",rawResponse:{local:!0,message:"Subscription updated locally for iyzico"}}},async cancelSubscription(request){return{success:!0,providerSubscriptionId:request.providerSubscriptionId,status:"canceled",rawResponse:{local:!0,message:"Subscription canceled locally for iyzico"}}},async getSubscription(request){return{success:!0,providerSubscriptionId:request.providerSubscriptionId,rawResponse:{local:!0,message:"Subscription data is stored locally for iyzico"}}},async listSubscriptions(_request){return{success:!0,subscriptions:[],hasMore:!1,rawResponse:{local:!0,message:"Subscriptions are stored locally for iyzico"}}},async reportUsage(request){return{success:!0,usageRecordId:`local_ur_${Date.now()}`,quantity:request.quantity,timestamp:request.timestamp??Math.floor(Date.now()/1000),rawResponse:{local:!0,message:"Usage recorded locally for iyzico"}}},async listUsageRecordSummaries(_request){return{success:!0,summaries:[],hasMore:!1,rawResponse:{local:!0,message:"Usage summaries are stored locally for iyzico"}}},async createInvoice(_request){return{success:!0,providerInvoiceId:`local_inv_${Date.now()}`,status:"draft",rawResponse:{local:!0,message:"Invoice stored locally for iyzico"}}},async finalizeInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,status:"open",rawResponse:{local:!0,message:"Invoice finalized locally for iyzico"}}},async sendInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,rawResponse:{local:!0,message:"Invoice send is a no-op for iyzico"}}},async voidInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,rawResponse:{local:!0,message:"Invoice voided locally for iyzico"}}},async payInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,status:"paid",rawResponse:{local:!0,message:"Invoice payment is a no-op for iyzico"}}},async getInvoice(request){return{success:!0,providerInvoiceId:request.providerInvoiceId,rawResponse:{local:!0,message:"Invoice data is stored locally for iyzico"}}},async listInvoices(_request){return{success:!0,invoices:[],hasMore:!1,rawResponse:{local:!0,message:"Invoices are stored locally for iyzico"}}},async getBalance(){return{success:!0,available:[],pending:[],rawResponse:{local:!0,message:"Balance is not tracked by iyzico provider"}}},async createPayout(_request){return{success:!0,providerPayoutId:`local_po_${Date.now()}`,status:"pending",rawResponse:{local:!0,message:"Payout created locally for iyzico"}}},async getPayout(request){return{success:!0,providerPayoutId:request.providerPayoutId,rawResponse:{local:!0,message:"Payout data is stored locally for iyzico"}}},async cancelPayout(request){return{success:!0,providerPayoutId:request.providerPayoutId,status:"canceled",rawResponse:{local:!0,message:"Payout cancelled locally for iyzico"}}},async listPayouts(_request){return{success:!0,payouts:[],hasMore:!1,rawResponse:{local:!0,message:"Payouts are stored locally for iyzico"}}},async createTransfer(_request){return{success:!0,providerTransferId:`local_tr_${Date.now()}`,rawResponse:{local:!0,message:"Transfer created locally for iyzico"}}},async listTransfers(_request){return{success:!0,transfers:[],hasMore:!1,rawResponse:{local:!0,message:"Transfers are stored locally for iyzico"}}}}};var init_IyzicoProvider=__esm(()=>{IYZICO_PATHS={INITIALIZE_3DS:"/payment/3dsecure/initialize",COMPLETE_3DS:"/payment/3dsecure/auth",PAYMENT_AUTH:"/payment/auth",PAYMENT_DETAIL:"/payment/detail",BIN_CHECK:"/payment/bin/check",CARD_SAVE:"/cardstorage/card",CARD_LIST:"/cardstorage/cards",CARD_DELETE:"/cardstorage/card/delete",REFUND:"/payment/refund",SUB_MERCHANT_CREATE:"/onboarding/submerchant",SUB_MERCHANT_UPDATE:"/onboarding/submerchant",SUB_MERCHANT_DETAIL:"/onboarding/submerchant/detail",APPROVAL:"/payment/iyzipos/item/approve",DISAPPROVAL:"/payment/iyzipos/item/disapprove"}});var resolveMarketplaceConfig=(payment)=>{let m=payment?.marketplace;return{enabled:m?.enabled===!0,defaultSettlementDelayDays:m?.defaultSettlementDelayDays??7,newSellerDelayDays:m?.newSellerDelayDays??14,reserveRate:clampRate(m?.reserveRate??0),reserveReleaseDays:m?.reserveReleaseDays??0,minimumPayoutAmount:m?.minimumPayoutAmount??0,defaultCurrency:m?.defaultCurrency??payment?.defaultCurrency??"USD",autoReleaseReserves:m?.autoReleaseReserves===!0}},clampRate=(rate)=>{if(Number.isNaN(rate)||rate<0)return 0;if(rate>1)return 1;return rate},addDays=(base,days)=>new Date(base.getTime()+days*24*60*60*1000),computeSplitBreakdown=(input,config,policy,now=new Date)=>{let providerFee=Math.max(0,Math.round(input.providerFeeAmount??0)),platformFee=Math.max(0,Math.round(input.platformFeeAmount)),afterFees=Math.max(0,input.grossAmount-providerFee-platformFee),reserveRate=input.reserveRate??policy?.reserveRate??config.reserveRate,reserveAmount=Math.min(afterFees,Math.floor(afterFees*clampRate(reserveRate))),netPayable=afterFees-reserveAmount,delayDays=input.settlementDelayDays??(input.isNewSeller?policy?.newSellerDelayDays??config.newSellerDelayDays:policy?.defaultDelayDays??config.defaultSettlementDelayDays);return{grossAmount:input.grossAmount,providerFeeAmount:providerFee,platformFeeAmount:platformFee,reserveAmount,netPayableAmount:netPayable,availableForPayoutAt:addDays(now,Math.max(0,delayDays))}},str2=(v)=>v==null?"":String(v),strOrNull2=(v)=>v==null?null:String(v),num=(v)=>{let n=typeof v==="number"?v:Number(v);return Number.isFinite(n)?n:0},rowToSplit=(row)=>({id:str2(row.id),transactionId:strOrNull2(row.transactionId??row.transaction_id),recipientOwnerType:str2(row.recipientOwnerType??row.recipient_owner_type)||"seller",recipientOwnerId:str2(row.recipientOwnerId??row.recipient_owner_id),provider:str2(row.provider),grossAmount:num(row.grossAmount??row.gross_amount),providerFeeAmount:num(row.providerFeeAmount??row.provider_fee_amount),platformFeeAmount:num(row.platformFeeAmount??row.platform_fee_amount),reserveAmount:num(row.reserveAmount??row.reserve_amount),netPayableAmount:num(row.netPayableAmount??row.net_payable_amount),currency:str2(row.currency),availableForPayoutAt:strOrNull2(row.availableForPayoutAt??row.available_for_payout_at),status:str2(row.status)||"pending",sourceType:strOrNull2(row.sourceType??row.source_type),sourceId:strOrNull2(row.sourceId??row.source_id)}),rowToPayoutRequest=(row)=>({id:str2(row.id),recipientOwnerType:str2(row.recipientOwnerType??row.recipient_owner_type)||"seller",recipientOwnerId:str2(row.recipientOwnerId??row.recipient_owner_id),amount:num(row.amount),currency:str2(row.currency),status:str2(row.status)||"pending",provider:strOrNull2(row.provider),providerPayoutId:strOrNull2(row.providerPayoutId??row.provider_payout_id),providerTransferId:strOrNull2(row.providerTransferId??row.provider_transfer_id),destination:strOrNull2(row.destination),failureReason:strOrNull2(row.failureReason??row.failure_reason)}),rowToSettlementPolicy=(row)=>({id:str2(row.id),ownerType:str2(row.ownerType??row.owner_type),ownerId:str2(row.ownerId??row.owner_id),defaultDelayDays:num(row.defaultDelayDays??row.default_delay_days),newSellerDelayDays:num(row.newSellerDelayDays??row.new_seller_delay_days),reserveRate:num(row.reserveRate??row.reserve_rate),reserveDays:num(row.reserveDays??row.reserve_days),minimumPayoutAmount:num(row.minimumPayoutAmount??row.minimum_payout_amount),currency:strOrNull2(row.currency),earlyPayoutEnabled:Boolean(row.earlyPayoutEnabled??row.early_payout_enabled),status:str2(row.status)||"active"}),rowToDispute=(row)=>({id:str2(row.id),transactionId:strOrNull2(row.transactionId??row.transaction_id),provider:str2(row.provider),providerDisputeId:strOrNull2(row.providerDisputeId??row.provider_dispute_id),ownerType:strOrNull2(row.ownerType??row.owner_type),ownerId:strOrNull2(row.ownerId??row.owner_id),amount:row.amount==null?null:num(row.amount),currency:strOrNull2(row.currency),reason:strOrNull2(row.reason),status:str2(row.status)||"open",resolvedAt:strOrNull2(row.resolvedAt??row.resolved_at)});import{eq as eq12}from"drizzle-orm";class MarketplacePayoutService{getDb;provider;logger;t;marketplace;constructor(cfg,marketplace){this.getDb=cfg.getDb,this.provider=cfg.provider,this.logger=cfg.logger.scoped("payment.payout"),this.t=cfg.tables,this.marketplace=marketplace}table(name){return this.t[name]}async requestPayout(input){let db=this.getDb();if(!db)throw Error("Marketplace payouts not ready");let recipientType=input.recipientOwnerType??"seller",currency=input.currency??this.marketplace.config.defaultCurrency;if(input.amount<=0)throw Error("Payout amount must be positive");let minimum=this.marketplace.config.minimumPayoutAmount;if(input.amount<minimum)throw Error(`Payout amount is below the minimum of ${minimum}`);let balance=await this.marketplace.getBalance(recipientType,input.recipientOwnerId,currency);if(input.amount>balance.available)throw Error(`Insufficient available balance: requested ${input.amount}, available ${balance.available}`);let table=this.table("payoutRequests"),rows=await db.insert(table).values({recipientOwnerType:recipientType,recipientOwnerId:input.recipientOwnerId,amount:input.amount,currency,status:"pending",destination:input.destination??null,requestedBy:input.requestedBy??null,metadata:JSON.stringify({})}).returning();return rowToPayoutRequest(rows[0])}async listPayoutRequests(filter){let db=this.getDb();if(!db)return[];let table=this.table("payoutRequests"),where=filter.recipientOwnerId?eq12(col4(table,"recipientOwnerId"),filter.recipientOwnerId):void 0,mapped=(where?await db.select().from(table).where(where):await db.select().from(table)).map((r)=>rowToPayoutRequest(r));return filter.status?mapped.filter((p)=>p.status===filter.status):mapped}async getPayoutRequest(id){let db=this.getDb();if(!db)return null;let table=this.table("payoutRequests"),rows=await db.select().from(table).where(eq12(col4(table,"id"),id)).limit(1);return rows[0]?rowToPayoutRequest(rows[0]):null}async rejectPayout(id,deciderId){let db=this.getDb();if(!db)return null;let table=this.table("payoutRequests");return await db.update(table).set({status:"rejected",decidedBy:deciderId??null,decidedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),this.getPayoutRequest(id)}async approvePayout(id,opts){let db=this.getDb();if(!db)return null;let request=await this.getPayoutRequest(id);if(!request)return null;if(request.status!=="pending")throw Error(`Payout is not pending (status: ${request.status})`);let table=this.table("payoutRequests"),destination=opts?.destination??request.destination;if(await db.update(table).set({status:"processing",decidedBy:opts?.deciderId??null,decidedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),!this.provider)return this.logger.warn("No payment provider configured; payout left in processing",{id}),this.getPayoutRequest(id);try{let result=destination?await this.provider.createTransfer({amount:request.amount,currency:request.currency,destination,transferGroup:`payout:${id}`}):await this.provider.createPayout({amount:request.amount,currency:request.currency}),providerId="providerTransferId"in result?result.providerTransferId:void 0,providerPayoutId="providerPayoutId"in result?result.providerPayoutId:void 0;if(!result.success)throw Error(result.errorMessage||"Provider payout failed");return await db.update(table).set({status:"completed",provider:this.provider?"configured":null,providerTransferId:providerId??null,providerPayoutId:providerPayoutId??null,completedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),await this.marketplace.recordLedgerEntry({account:"seller_payable",direction:"debit",amount:request.amount,currency:request.currency,entryType:"payout",ownerType:request.recipientOwnerType,ownerId:request.recipientOwnerId,referenceType:"payout_request",referenceId:id}),await this.marketplace.recordLedgerEntry({account:"payout_completed",direction:"credit",amount:request.amount,currency:request.currency,entryType:"payout",ownerType:request.recipientOwnerType,ownerId:request.recipientOwnerId,referenceType:"payout_request",referenceId:id}),await this.consumeSplits(request.recipientOwnerId,request.amount,request.currency),this.getPayoutRequest(id)}catch(err){let reason=err instanceof Error?err.message:"Payout execution failed";return await db.update(table).set({status:"failed",failureReason:reason,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),this.logger.error("Payout execution failed",{id,reason}),this.getPayoutRequest(id)}}async consumeSplits(ownerId,amount,currency){let db=this.getDb();if(!db)return;let table=this.table("splits"),splits=await this.marketplace.listSplits({recipientOwnerId:ownerId}),remaining=amount,now=Date.now();for(let s of splits){if(remaining<=0)break;if(s.currency!==currency)continue;if(s.status!=="pending"&&s.status!=="available")continue;if(!(s.availableForPayoutAt?new Date(s.availableForPayoutAt).getTime()<=now:!0))continue;if(s.netPayableAmount>remaining)continue;await db.update(table).set({status:"paid",updatedAt:new Date}).where(eq12(col4(table,"id"),s.id)),remaining-=s.netPayableAmount}}async openDispute(input){let db=this.getDb();if(!db)return null;let table=this.table("disputes"),rows=await db.insert(table).values({transactionId:input.transactionId??null,provider:input.provider,providerDisputeId:input.providerDisputeId??null,ownerType:input.ownerType??null,ownerId:input.ownerId??null,amount:input.amount??null,currency:input.currency??null,reason:input.reason??null,status:"open",evidenceDueAt:input.evidenceDueAt??null,metadata:JSON.stringify(input.metadata??{})}).returning(),dispute=rowToDispute(rows[0]);if(input.amount&&input.amount>0&&input.currency)await this.marketplace.recordLedgerEntry({account:"dispute_liability",direction:"credit",amount:input.amount,currency:input.currency,entryType:"dispute",ownerType:input.ownerType,ownerId:input.ownerId,referenceType:"dispute",referenceId:dispute.id});return dispute}async listDisputes(filter){let db=this.getDb();if(!db)return[];let table=this.table("disputes"),where=filter.ownerId?eq12(col4(table,"ownerId"),filter.ownerId):void 0,mapped=(where?await db.select().from(table).where(where):await db.select().from(table)).map((r)=>rowToDispute(r));return filter.status?mapped.filter((d)=>d.status===filter.status):mapped}async getDispute(id){let db=this.getDb();if(!db)return null;let table=this.table("disputes"),rows=await db.select().from(table).where(eq12(col4(table,"id"),id)).limit(1);return rows[0]?rowToDispute(rows[0]):null}async resolveDispute(id,outcome){let db=this.getDb();if(!db)return null;let dispute=await this.getDispute(id);if(!dispute)return null;let table=this.table("disputes");if(await db.update(table).set({status:outcome,resolvedAt:new Date,updatedAt:new Date}).where(eq12(col4(table,"id"),id)),(outcome==="lost"||outcome==="accepted")&&dispute.amount&&dispute.currency)await this.marketplace.recordLedgerEntry({account:"seller_payable",direction:"debit",amount:dispute.amount,currency:dispute.currency,entryType:"dispute",ownerType:dispute.ownerType??void 0,ownerId:dispute.ownerId??void 0,referenceType:"dispute",referenceId:id});return this.getDispute(id)}}var col4=(table,name)=>table[name];var init_MarketplacePayoutService=()=>{};import{and as and6,eq as eq13}from"drizzle-orm";class MarketplaceService{getDb;config;logger;t;constructor(cfg){this.getDb=cfg.getDb,this.config=cfg.config,this.logger=cfg.logger.scoped("payment.marketplace"),this.t=cfg.tables}table(name){return this.t[name]}async recordLedgerEntry(entry){let db=this.getDb();if(!db)return;await db.insert(this.table("ledgerEntries")).values({account:entry.account,ownerType:entry.ownerType??null,ownerId:entry.ownerId??null,direction:entry.direction,amount:entry.amount,currency:entry.currency,entryType:entry.entryType,referenceType:entry.referenceType??null,referenceId:entry.referenceId??null,splitId:entry.splitId??null,description:entry.description??null,metadata:JSON.stringify({})})}async getSettlementPolicy(ownerType,ownerId){let db=this.getDb();if(!db)return null;let table=this.table("settlementPolicies"),rows=await db.select().from(table).where(and6(eq13(col5(table,"ownerType"),ownerType),eq13(col5(table,"ownerId"),ownerId))).limit(1);return rows[0]?rowToSettlementPolicy(rows[0]):null}async upsertSettlementPolicy(input){let db=this.getDb();if(!db)return null;let table=this.table("settlementPolicies"),existing=await this.getSettlementPolicy(input.ownerType,input.ownerId),values={ownerType:input.ownerType,ownerId:input.ownerId,defaultDelayDays:input.defaultDelayDays??this.config.defaultSettlementDelayDays,newSellerDelayDays:input.newSellerDelayDays??this.config.newSellerDelayDays,reserveRate:String(input.reserveRate??this.config.reserveRate),reserveDays:input.reserveDays??this.config.reserveReleaseDays,minimumPayoutAmount:input.minimumPayoutAmount??this.config.minimumPayoutAmount,currency:input.currency??null,earlyPayoutEnabled:input.earlyPayoutEnabled??!1,updatedAt:new Date};if(existing)await db.update(table).set(values).where(eq13(col5(table,"id"),existing.id));else await db.insert(table).values(values);return this.getSettlementPolicy(input.ownerType,input.ownerId)}async recordSplit(input){let db=this.getDb();if(!db)return null;let recipientType=input.recipientOwnerType??"seller",currency=input.currency??this.config.defaultCurrency,now=new Date,policy=await this.getSettlementPolicy(recipientType,input.recipientOwnerId),breakdown=computeSplitBreakdown(input,this.config,policy,now),splitTable=this.table("splits"),rows=await db.insert(splitTable).values({transactionId:input.transactionId??null,recipientOwnerType:recipientType,recipientOwnerId:input.recipientOwnerId,provider:input.provider,grossAmount:breakdown.grossAmount,providerFeeAmount:breakdown.providerFeeAmount,platformFeeAmount:breakdown.platformFeeAmount,reserveAmount:breakdown.reserveAmount,netPayableAmount:breakdown.netPayableAmount,currency,availableForPayoutAt:breakdown.availableForPayoutAt,status:"pending",sourceType:input.sourceType??null,sourceId:input.sourceId??null,metadata:JSON.stringify(input.metadata??{})}).returning(),split=rowToSplit(rows[0]);if(await this.recordLedgerEntry({account:"seller_payable",direction:"credit",amount:breakdown.netPayableAmount,currency,entryType:"split",ownerType:recipientType,ownerId:input.recipientOwnerId,referenceType:"split",referenceId:split.id,splitId:split.id}),breakdown.platformFeeAmount>0)await this.recordLedgerEntry({account:"platform_revenue",direction:"credit",amount:breakdown.platformFeeAmount,currency,entryType:"split",referenceType:"split",referenceId:split.id,splitId:split.id});if(breakdown.providerFeeAmount>0)await this.recordLedgerEntry({account:"provider_fee",direction:"credit",amount:breakdown.providerFeeAmount,currency,entryType:"split",referenceType:"split",referenceId:split.id,splitId:split.id});if(breakdown.reserveAmount>0){let reserveDays=policy?.reserveDays??this.config.reserveReleaseDays;await db.insert(this.table("reserves")).values({ownerType:recipientType,ownerId:input.recipientOwnerId,splitId:split.id,amount:breakdown.reserveAmount,currency,reason:input.isNewSeller?"new_seller":"refund_window",status:"held",releaseAt:reserveDays>0?addDays(now,reserveDays):null,metadata:JSON.stringify({})}),await this.recordLedgerEntry({account:"reserve",direction:"credit",amount:breakdown.reserveAmount,currency,entryType:"reserve_hold",ownerType:recipientType,ownerId:input.recipientOwnerId,referenceType:"split",referenceId:split.id,splitId:split.id})}return this.logger.info("Recorded split",{splitId:split.id,gross:breakdown.grossAmount,netPayable:breakdown.netPayableAmount,reserve:breakdown.reserveAmount}),split}async listSplits(filter){let db=this.getDb();if(!db)return[];let table=this.table("splits"),where=filter.recipientOwnerId?eq13(col5(table,"recipientOwnerId"),filter.recipientOwnerId):void 0,mapped=(where?await db.select().from(table).where(where):await db.select().from(table)).map((r)=>rowToSplit(r));return filter.status?mapped.filter((s)=>s.status===filter.status):mapped}async releaseReserve(id){let db=this.getDb();if(!db)return!1;let table=this.table("reserves"),row=(await db.select().from(table).where(eq13(col5(table,"id"),id)).limit(1))[0];if(!row||String(row.status)!=="held")return!1;await db.update(table).set({status:"released",releasedAt:new Date,updatedAt:new Date}).where(eq13(col5(table,"id"),id));let reserveOwnerType=String(row.ownerType??row.owner_type??""),reserveOwnerId=String(row.ownerId??row.owner_id??"");return await this.recordLedgerEntry({account:"reserve",direction:"debit",amount:Number(row.amount),currency:String(row.currency),entryType:"reserve_release",ownerType:reserveOwnerType,ownerId:reserveOwnerId,referenceType:"reserve",referenceId:id}),await this.recordLedgerEntry({account:"seller_payable",direction:"credit",amount:Number(row.amount),currency:String(row.currency),entryType:"reserve_release",ownerType:reserveOwnerType,ownerId:reserveOwnerId,referenceType:"reserve",referenceId:id}),!0}async autoReleaseDueReserves(ownerType,ownerId){if(!this.config.autoReleaseReserves)return;let db=this.getDb();if(!db)return;let table=this.table("reserves"),rows=await db.select().from(table).where(and6(eq13(col5(table,"ownerType"),ownerType),eq13(col5(table,"ownerId"),ownerId))),now=Date.now();for(let r of rows){let releaseAt=r.releaseAt??r.release_at;if(String(r.status)==="held"&&releaseAt&&new Date(String(releaseAt)).getTime()<=now)await this.releaseReserve(String(r.id))}}async getBalance(ownerType,ownerId,currency){let cur=currency??this.config.defaultCurrency,db=this.getDb(),base={ownerType,ownerId,currency:cur,available:0,pending:0,reserved:0,payoutInFlight:0};if(!db)return base;await this.autoReleaseDueReserves(ownerType,ownerId);let splits=await this.listSplits({recipientOwnerId:ownerId}),now=Date.now();for(let s of splits){if(s.currency!==cur)continue;if(s.status!=="pending"&&s.status!=="available")continue;if(!(s.availableForPayoutAt?new Date(s.availableForPayoutAt).getTime()<=now:!0))base.pending+=s.netPayableAmount}let ledgerTable=this.table("ledgerEntries"),ledgerRows=await db.select().from(ledgerTable).where(and6(eq13(col5(ledgerTable,"ownerType"),ownerType),eq13(col5(ledgerTable,"ownerId"),ownerId))),payableNet=0;for(let e of ledgerRows){if(String(e.account)!=="seller_payable"||String(e.currency)!==cur)continue;let amt=Number(e.amount);payableNet+=String(e.direction)==="credit"?amt:-amt}base.available=payableNet-base.pending;let reserveTable=this.table("reserves"),reserveRows=await db.select().from(reserveTable).where(and6(eq13(col5(reserveTable,"ownerType"),ownerType),eq13(col5(reserveTable,"ownerId"),ownerId)));for(let r of reserveRows)if(String(r.status)==="held"&&String(r.currency)===cur)base.reserved+=Number(r.amount);let payoutTable=this.table("payoutRequests"),payoutRows=await db.select().from(payoutTable).where(and6(eq13(col5(payoutTable,"recipientOwnerType"),ownerType),eq13(col5(payoutTable,"recipientOwnerId"),ownerId)));for(let p of payoutRows){let st=String(p.status);if((st==="pending"||st==="approved"||st==="processing")&&String(p.currency)===cur)base.payoutInFlight+=Number(p.amount),base.available-=Number(p.amount)}if(base.available<0)base.available=0;return base}}var col5=(table,name)=>table[name];var init_MarketplaceService=()=>{};var pick=(schemaTables,camel,snake)=>schemaTables[camel]??schemaTables[snake]??{},createMarketplaceServices=(params)=>{let config=resolveMarketplaceConfig(params.options.payment);if(!config.enabled)return null;let tables={splits:pick(params.schemaTables,"paymentSplits","payment_splits"),ledgerEntries:pick(params.schemaTables,"paymentLedgerEntries","payment_ledger_entries"),settlementPolicies:pick(params.schemaTables,"paymentSettlementPolicies","payment_settlement_policies"),reserves:pick(params.schemaTables,"paymentReserves","payment_reserves"),payoutRequests:pick(params.schemaTables,"paymentPayoutRequests","payment_payout_requests"),disputes:pick(params.schemaTables,"paymentDisputes","payment_disputes")},serviceConfig={getDb:params.getDb,provider:params.provider,config,logger:params.logger,tables},marketplaceService=new MarketplaceService(serviceConfig),payoutService=new MarketplacePayoutService(serviceConfig,marketplaceService);return{marketplaceService,payoutService}};var init_Marketplace=__esm(()=>{init_MarketplacePayoutService();init_MarketplaceService();init_MarketplacePayoutService();init_MarketplaceService()});var loadStripe=(config)=>{try{let StripeModule=__require("stripe");return new(StripeModule.default??StripeModule)(config.secretKey,{maxNetworkRetries:config.maxNetworkRetries??2,timeout:config.timeout??30000,...config.apiVersion?{apiVersion:config.apiVersion}:{}})}catch(error){return logger.scoped("payment.init").error("Failed to load stripe package. Install it: bun add stripe",error),null}},createStripeProvider=(config)=>{let stripe=loadStripe(config);if(!stripe)return null;let providerName="stripe";return{get name(){return providerName},async initialize3DS(request){try{let params={amount:Math.round(Number(request.paidPrice)*100),currency:request.currency.toLowerCase(),payment_method_types:["card"],description:`Order ${request.conversationId}`,metadata:{conversationId:request.conversationId,basketId:request.basketId??"",buyerEmail:request.buyer.email,buyerId:request.buyer.id}};if("cardToken"in request.paymentCard&&request.paymentCard.cardToken)params.payment_method=request.paymentCard.cardToken,params.confirm=!0,params.return_url=request.callbackUrl;let paymentIntent=await stripe.paymentIntents.create(params),clientSecret=paymentIntent.client_secret,piId=paymentIntent.id,status=paymentIntent.status;return{success:!0,paymentId:piId,threeDSHtmlContent:clientSecret,signature:status,rawResponse:paymentIntent}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Payment initialization failed",rawResponse:{error:err.message}}}},async complete3DS(request){try{let paymentIntent=await stripe.paymentIntents.retrieve(request.paymentId,{expand:["payment_method"]}),status=paymentIntent.status,isSuccess=status==="succeeded",amountReceived=paymentIntent.amount_received??0,card=paymentIntent.payment_method?.card;return{success:isSuccess,paymentId:paymentIntent.id,price:amountReceived/100,paidPrice:amountReceived/100,currency:paymentIntent.currency?.toUpperCase(),cardType:card?.brand??void 0,cardAssociation:card?.brand??void 0,cardFamily:card?.funding??void 0,lastFourDigits:card?.last4??void 0,authCode:status,errorCode:isSuccess?void 0:"PAYMENT_NOT_SUCCEEDED",errorMessage:isSuccess?void 0:`Payment status: ${status}`,rawResponse:paymentIntent}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Payment completion failed",rawResponse:{error:err.message}}}},async getPaymentDetail(request){try{let paymentIntent=await stripe.paymentIntents.retrieve(request.paymentId,{expand:["payment_method"]}),amountReceived=paymentIntent.amount_received??paymentIntent.amount??0,card=paymentIntent.payment_method?.card;return{success:!0,paymentId:paymentIntent.id,price:amountReceived/100,paidPrice:amountReceived/100,currency:paymentIntent.currency?.toUpperCase(),cardType:card?.brand??void 0,cardAssociation:card?.brand??void 0,lastFourDigits:card?.last4??void 0,binNumber:void 0,rawResponse:paymentIntent}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Payment detail query failed",rawResponse:{error:err.message}}}},async queryBin(_request){return{success:!1,errorCode:"NOT_SUPPORTED",errorMessage:"BIN query is not supported by Stripe. Card info is available after payment method creation.",rawResponse:{}}},async saveCard(request){try{let customer=await stripe.customers.create({email:request.email,metadata:{externalId:request.externalId??""}}),paymentMethod=await stripe.paymentMethods.create({type:"card",card:{number:request.card.cardNumber,exp_month:Number(request.card.expireMonth),exp_year:Number(request.card.expireYear)}});await stripe.paymentMethods.attach(paymentMethod.id,{customer:customer.id});let card=paymentMethod.card;return{success:!0,cardUserKey:customer.id,cardToken:paymentMethod.id,cardAlias:request.card.cardAlias,binNumber:void 0,lastFourDigits:card?.last4??void 0,cardType:card?.brand??void 0,cardAssociation:card?.brand??void 0,cardFamily:card?.funding??void 0,cardBankName:void 0,rawResponse:{customer,paymentMethod}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to save card",rawResponse:{error:err.message}}}},async listCards(request){try{let response=await stripe.paymentMethods.list({customer:request.cardUserKey,type:"card"}),cards=response.data.map((pm)=>{let card=pm.card;return{cardToken:pm.id,cardAlias:pm.metadata?.alias??"",binNumber:"",lastFourDigits:card?.last4??"",cardType:card?.brand??"",cardAssociation:card?.brand??"",cardFamily:card?.funding??"",cardBankName:"",cardBankCode:0}});return{success:!0,cardUserKey:request.cardUserKey,cards,rawResponse:response}}catch(error){let err=error;return{success:!1,cards:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list cards",rawResponse:{error:err.message}}}},async deleteCard(request){try{return await stripe.paymentMethods.detach(request.cardToken),{success:!0,rawResponse:{detached:request.cardToken}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to delete card",rawResponse:{error:err.message}}}},async refund(request){try{let amountInCents=Math.round(Number(request.price)*100),refund=await stripe.refunds.create({payment_intent:request.paymentTransactionId,amount:amountInCents});return{success:refund.status==="succeeded",paymentId:refund.payment_intent,price:amountInCents/100,currency:refund.currency?.toUpperCase(),errorCode:refund.status!=="succeeded"?"REFUND_FAILED":void 0,errorMessage:refund.status!=="succeeded"?`Refund status: ${refund.status}`:void 0,rawResponse:refund}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Refund failed",rawResponse:{error:err.message}}}},parseCallback(formData){let paymentIntent=formData.payment_intent??formData.paymentId??"",redirectStatus=formData.redirect_status??"";return{success:redirectStatus==="succeeded",paymentId:paymentIntent,conversationId:formData.conversationId??"",mdStatus:redirectStatus,rawData:formData}},async registerSubMerchant(request){try{let account=await stripe.accounts.create({type:"express",country:request.currency==="TRY"?"TR":void 0,email:request.email,business_type:request.subMerchantType==="personal"?"individual":"company",metadata:{externalId:request.subMerchantExternalId,name:request.name,contactName:request.contactName??"",contactSurname:request.contactSurname??""},capabilities:{transfers:{requested:!0}}});return{success:!0,subMerchantKey:account.id,rawResponse:account}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create connected account",rawResponse:{error:err.message}}}},async updateSubMerchant(request){try{let params={metadata:{}},meta=params.metadata;if(request.name)meta.name=request.name;if(request.email)params.email=request.email;if(request.contactName)meta.contactName=request.contactName;if(request.contactSurname)meta.contactSurname=request.contactSurname;return await stripe.accounts.update(request.subMerchantKey,params),{success:!0,rawResponse:{updated:request.subMerchantKey}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update connected account",rawResponse:{error:err.message}}}},async getSubMerchant(request){try{let account=await stripe.accounts.retrieve(request.subMerchantExternalId),meta=account.metadata??{};return{success:!0,subMerchantKey:account.id,name:meta.name,email:account.email,subMerchantType:account.business_type==="individual"?"personal":"company",currency:account.default_currency?.toUpperCase(),rawResponse:account}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to retrieve connected account",rawResponse:{error:err.message}}}},async approveSplit(request){return{success:!0,paymentTransactionId:request.paymentTransactionId,rawResponse:{message:"Stripe transfers are automatic; no manual approval needed."}}},async disapproveSplit(request){try{let reversal=await stripe.transfers.createReversal(request.paymentTransactionId);return{success:!0,paymentTransactionId:reversal.id,rawResponse:reversal}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to reverse transfer",rawResponse:{error:err.message}}}},async createProduct(request){try{let params={name:request.name};if(request.description)params.description=request.description;if(request.type)params.type=request.type;if(request.images)params.images=request.images;if(request.unitLabel)params.unit_label=request.unitLabel;if(request.url)params.url=request.url;if(request.metadata)params.metadata=request.metadata;let product=await stripe.products.create(params);return{success:!0,providerProductId:product.id,name:product.name,rawResponse:product}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create product",rawResponse:{error:err.message}}}},async updateProduct(request){try{let params={};if(request.name)params.name=request.name;if(request.description!==void 0)params.description=request.description;if(request.images)params.images=request.images;if(request.unitLabel!==void 0)params.unit_label=request.unitLabel;if(request.url!==void 0)params.url=request.url;if(request.active!==void 0)params.active=request.active;if(request.metadata)params.metadata=request.metadata;let product=await stripe.products.update(request.providerProductId,params);return{success:!0,providerProductId:product.id,rawResponse:product}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update product",rawResponse:{error:err.message}}}},async getProduct(request){try{let product=await stripe.products.retrieve(request.providerProductId);return{success:!0,providerProductId:product.id,name:product.name,description:product.description,type:product.type,active:product.active,images:product.images,unitLabel:product.unit_label,url:product.url,metadata:product.metadata,rawResponse:product}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get product",rawResponse:{error:err.message}}}},async listProducts(request){try{let params={};if(request.active!==void 0)params.active=request.active;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.products.list(params);return{success:!0,products:response.data.map((p)=>({providerProductId:p.id,name:p.name,description:p.description,type:p.type,active:p.active,images:p.images,unitLabel:p.unit_label,metadata:p.metadata})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,products:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list products",rawResponse:{error:err.message}}}},async archiveProduct(request){try{return await stripe.products.update(request.providerProductId,{active:!1}),{success:!0,rawResponse:{archived:request.providerProductId}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to archive product",rawResponse:{error:err.message}}}},async createPrice(request){try{let params={product:request.providerProductId,currency:request.currency.toLowerCase(),unit_amount:request.unitAmount};if(request.nickname)params.nickname=request.nickname;if(request.billingScheme)params.billing_scheme=request.billingScheme;if(request.unitAmountDecimal)params.unit_amount_decimal=request.unitAmountDecimal;if(request.metadata)params.metadata=request.metadata;if(request.recurring)params.recurring={interval:request.recurring.interval,...request.recurring.intervalCount?{interval_count:request.recurring.intervalCount}:{},...request.recurring.usageType?{usage_type:request.recurring.usageType}:{},...request.recurring.aggregateUsage?{aggregate_usage:request.recurring.aggregateUsage}:{}};if(request.transformQuantity)params.transform_quantity={divide_by:request.transformQuantity.divideBy,round:request.transformQuantity.round};let price=await stripe.prices.create(params);return{success:!0,providerPriceId:price.id,rawResponse:price}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create price",rawResponse:{error:err.message}}}},async updatePrice(request){try{let params={};if(request.nickname!==void 0)params.nickname=request.nickname;if(request.active!==void 0)params.active=request.active;if(request.metadata)params.metadata=request.metadata;let price=await stripe.prices.update(request.providerPriceId,params);return{success:!0,providerPriceId:price.id,rawResponse:price}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update price",rawResponse:{error:err.message}}}},async getPrice(request){try{let price=await stripe.prices.retrieve(request.providerPriceId),rec=price.recurring;return{success:!0,providerPriceId:price.id,providerProductId:price.product,currency:price.currency?.toUpperCase(),unitAmount:price.unit_amount,type:price.type,billingScheme:price.billing_scheme,nickname:price.nickname,active:price.active,recurring:rec?{interval:rec.interval,intervalCount:rec.interval_count??1,usageType:rec.usage_type}:void 0,metadata:price.metadata,rawResponse:price}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get price",rawResponse:{error:err.message}}}},async listPrices(request){try{let params={};if(request.providerProductId)params.product=request.providerProductId;if(request.active!==void 0)params.active=request.active;if(request.type)params.type=request.type;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.prices.list(params);return{success:!0,prices:response.data.map((p)=>{let rec=p.recurring;return{providerPriceId:p.id,providerProductId:p.product,currency:p.currency?.toUpperCase(),unitAmount:p.unit_amount,type:p.type,billingScheme:p.billing_scheme,nickname:p.nickname,active:p.active,recurring:rec?{interval:rec.interval,intervalCount:rec.interval_count??1,usageType:rec.usage_type}:void 0,metadata:p.metadata}}),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,prices:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list prices",rawResponse:{error:err.message}}}},async archivePrice(request){try{return await stripe.prices.update(request.providerPriceId,{active:!1}),{success:!0,rawResponse:{archived:request.providerPriceId}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to archive price",rawResponse:{error:err.message}}}},async createCustomer(request){try{let params={email:request.email};if(request.name)params.name=request.name;if(request.phone)params.phone=request.phone;if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.address)params.address={line1:request.address.line1,line2:request.address.line2,city:request.address.city,state:request.address.state,postal_code:request.address.postalCode,country:request.address.country};let customer=await stripe.customers.create(params);if(request.taxId)try{await stripe.taxIds?.create({customer:customer.id,type:request.taxId.type,value:request.taxId.value})}catch(_){}return{success:!0,providerCustomerId:customer.id,email:customer.email,rawResponse:customer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create customer",rawResponse:{error:err.message}}}},async updateCustomer(request){try{let params={};if(request.email)params.email=request.email;if(request.name!==void 0)params.name=request.name;if(request.phone!==void 0)params.phone=request.phone;if(request.description!==void 0)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.address)params.address={line1:request.address.line1,line2:request.address.line2,city:request.address.city,state:request.address.state,postal_code:request.address.postalCode,country:request.address.country};let customer=await stripe.customers.update(request.providerCustomerId,params);return{success:!0,providerCustomerId:customer.id,rawResponse:customer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update customer",rawResponse:{error:err.message}}}},async getCustomer(request){try{let customer=await stripe.customers.retrieve(request.providerCustomerId);return{success:!0,providerCustomerId:customer.id,email:customer.email,name:customer.name,phone:customer.phone,description:customer.description,metadata:customer.metadata,rawResponse:customer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get customer",rawResponse:{error:err.message}}}},async listCustomers(request){try{let params={};if(request.email)params.email=request.email;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.customers.list(params);return{success:!0,customers:response.data.map((c)=>({providerCustomerId:c.id,email:c.email,name:c.name,phone:c.phone})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,customers:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list customers",rawResponse:{error:err.message}}}},async deleteCustomer(request){try{return await stripe.customers.del(request.providerCustomerId),{success:!0,rawResponse:{deleted:request.providerCustomerId}}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to delete customer",rawResponse:{error:err.message}}}},async createSubscription(request){try{let params={customer:request.providerCustomerId,items:request.items.map((i)=>({price:i.providerPriceId,...i.quantity!==void 0?{quantity:i.quantity}:{}}))};if(request.trialPeriodDays)params.trial_period_days=request.trialPeriodDays;if(request.collectionMethod)params.collection_method=request.collectionMethod;if(request.daysUntilDue)params.days_until_due=request.daysUntilDue;if(request.cancelAtPeriodEnd!==void 0)params.cancel_at_period_end=request.cancelAtPeriodEnd;if(request.metadata)params.metadata=request.metadata;if(request.defaultPaymentMethod)params.default_payment_method=request.defaultPaymentMethod;params.payment_behavior="default_incomplete",params.payment_settings={save_default_payment_method:"on_subscription"},params.expand=["latest_invoice.payment_intent"];let sub=await stripe.subscriptions.create(params),pi=sub.latest_invoice?.payment_intent;return{success:!0,providerSubscriptionId:sub.id,status:sub.status,currentPeriodStart:sub.current_period_start?new Date(sub.current_period_start*1000).toISOString():void 0,currentPeriodEnd:sub.current_period_end?new Date(sub.current_period_end*1000).toISOString():void 0,clientSecret:pi?.client_secret,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create subscription",rawResponse:{error:err.message}}}},async updateSubscription(request){try{let params={};if(request.items)params.items=request.items.map((i)=>({...i.id?{id:i.id}:{},price:i.providerPriceId,...i.quantity!==void 0?{quantity:i.quantity}:{}}));if(request.cancelAtPeriodEnd!==void 0)params.cancel_at_period_end=request.cancelAtPeriodEnd;if(request.trialEnd!==void 0)params.trial_end=request.trialEnd;if(request.metadata)params.metadata=request.metadata;if(request.collectionMethod)params.collection_method=request.collectionMethod;if(request.daysUntilDue)params.days_until_due=request.daysUntilDue;if(request.defaultPaymentMethod)params.default_payment_method=request.defaultPaymentMethod;if(request.prorationBehavior)params.proration_behavior=request.prorationBehavior;let sub=await stripe.subscriptions.update(request.providerSubscriptionId,params);return{success:!0,providerSubscriptionId:sub.id,status:sub.status,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to update subscription",rawResponse:{error:err.message}}}},async cancelSubscription(request){try{if(request.cancelAtPeriodEnd){let sub2=await stripe.subscriptions.update(request.providerSubscriptionId,{cancel_at_period_end:!0});return{success:!0,providerSubscriptionId:sub2.id,status:sub2.status,rawResponse:sub2}}let params={};if(request.invoiceNow)params.invoice_now=request.invoiceNow;if(request.prorate)params.prorate=request.prorate;let sub=await stripe.subscriptions.cancel(request.providerSubscriptionId,params);return{success:!0,providerSubscriptionId:sub.id,status:sub.status,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to cancel subscription",rawResponse:{error:err.message}}}},async getSubscription(request){try{let sub=await stripe.subscriptions.retrieve(request.providerSubscriptionId),itemsData=sub.items?.data??[];return{success:!0,providerSubscriptionId:sub.id,providerCustomerId:sub.customer,status:sub.status,currentPeriodStart:sub.current_period_start?new Date(sub.current_period_start*1000).toISOString():void 0,currentPeriodEnd:sub.current_period_end?new Date(sub.current_period_end*1000).toISOString():void 0,cancelAtPeriodEnd:sub.cancel_at_period_end,canceledAt:sub.canceled_at?new Date(sub.canceled_at*1000).toISOString():void 0,trialStart:sub.trial_start?new Date(sub.trial_start*1000).toISOString():void 0,trialEnd:sub.trial_end?new Date(sub.trial_end*1000).toISOString():void 0,items:itemsData.map((i)=>({id:i.id,providerPriceId:i.price?.id??i.price,quantity:i.quantity??1})),metadata:sub.metadata,rawResponse:sub}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get subscription",rawResponse:{error:err.message}}}},async listSubscriptions(request){try{let params={};if(request.providerCustomerId)params.customer=request.providerCustomerId;if(request.status)params.status=request.status;if(request.providerPriceId)params.price=request.providerPriceId;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.subscriptions.list(params);return{success:!0,subscriptions:response.data.map((s)=>({providerSubscriptionId:s.id,providerCustomerId:s.customer,status:s.status,currentPeriodStart:s.current_period_start?new Date(s.current_period_start*1000).toISOString():void 0,currentPeriodEnd:s.current_period_end?new Date(s.current_period_end*1000).toISOString():void 0,cancelAtPeriodEnd:s.cancel_at_period_end})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,subscriptions:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list subscriptions",rawResponse:{error:err.message}}}},async reportUsage(request){try{let params={quantity:request.quantity,action:request.action??"increment"};if(request.timestamp)params.timestamp=request.timestamp;let record=await stripe.subscriptionItems.usageRecords.create(request.subscriptionItemId,params);return{success:!0,usageRecordId:record.id,quantity:record.quantity,timestamp:record.timestamp,rawResponse:record}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to report usage",rawResponse:{error:err.message}}}},async listUsageRecordSummaries(request){try{let params={};if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.subscriptionItems.usageRecordSummaries.list(request.subscriptionItemId,params);return{success:!0,summaries:response.data.map((s)=>({id:s.id,totalUsage:s.total_usage,period:s.period,subscriptionItem:s.subscription_item})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,summaries:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list usage summaries",rawResponse:{error:err.message}}}},async createInvoice(request){try{let params={customer:request.providerCustomerId};if(request.collectionMethod)params.collection_method=request.collectionMethod;if(request.daysUntilDue)params.days_until_due=request.daysUntilDue;if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.autoAdvance!==void 0)params.auto_advance=request.autoAdvance;let invoice=await stripe.invoices.create(params);if(request.items?.length)for(let item of request.items){let lineParams={customer:request.providerCustomerId,invoice:invoice.id};if(item.providerPriceId)lineParams.price=item.providerPriceId;if(item.quantity)lineParams.quantity=item.quantity;if(item.unitAmount!==void 0)lineParams.unit_amount=item.unitAmount;if(item.currency)lineParams.currency=item.currency;if(item.description)lineParams.description=item.description;await stripe.invoiceItems.create(lineParams)}return{success:!0,providerInvoiceId:invoice.id,status:invoice.status,hostedInvoiceUrl:invoice.hosted_invoice_url,invoicePdf:invoice.invoice_pdf,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create invoice",rawResponse:{error:err.message}}}},async finalizeInvoice(request){try{let params={};if(request.autoAdvance!==void 0)params.auto_advance=request.autoAdvance;let invoice=await stripe.invoices.finalizeInvoice(request.providerInvoiceId,params);return{success:!0,providerInvoiceId:invoice.id,status:invoice.status,hostedInvoiceUrl:invoice.hosted_invoice_url,invoicePdf:invoice.invoice_pdf,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to finalize invoice",rawResponse:{error:err.message}}}},async sendInvoice(request){try{let invoice=await stripe.invoices.sendInvoice(request.providerInvoiceId);return{success:!0,providerInvoiceId:invoice.id,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to send invoice",rawResponse:{error:err.message}}}},async voidInvoice(request){try{let invoice=await stripe.invoices.voidInvoice(request.providerInvoiceId);return{success:!0,providerInvoiceId:invoice.id,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to void invoice",rawResponse:{error:err.message}}}},async payInvoice(request){try{let params={};if(request.paymentMethod)params.payment_method=request.paymentMethod;let invoice=await stripe.invoices.pay(request.providerInvoiceId,params);return{success:!0,providerInvoiceId:invoice.id,status:invoice.status,amountPaid:invoice.amount_paid,amountDue:invoice.amount_due,rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to pay invoice",rawResponse:{error:err.message}}}},async getInvoice(request){try{let invoice=await stripe.invoices.retrieve(request.providerInvoiceId),linesData=invoice.lines?.data??[];return{success:!0,providerInvoiceId:invoice.id,providerCustomerId:invoice.customer,providerSubscriptionId:invoice.subscription,status:invoice.status,amountDue:invoice.amount_due,amountPaid:invoice.amount_paid,amountRemaining:invoice.amount_remaining,currency:invoice.currency?.toUpperCase(),description:invoice.description,hostedInvoiceUrl:invoice.hosted_invoice_url,invoicePdf:invoice.invoice_pdf,dueDate:invoice.due_date?new Date(invoice.due_date*1000).toISOString():void 0,periodStart:invoice.period_start?new Date(invoice.period_start*1000).toISOString():void 0,periodEnd:invoice.period_end?new Date(invoice.period_end*1000).toISOString():void 0,metadata:invoice.metadata,lines:linesData.map((l)=>({id:l.id,description:l.description,amount:l.amount,currency:l.currency?.toUpperCase(),quantity:l.quantity,providerPriceId:l.price?.id})),rawResponse:invoice}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get invoice",rawResponse:{error:err.message}}}},async listInvoices(request){try{let params={};if(request.providerCustomerId)params.customer=request.providerCustomerId;if(request.providerSubscriptionId)params.subscription=request.providerSubscriptionId;if(request.status)params.status=request.status;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.invoices.list(params);return{success:!0,invoices:response.data.map((inv)=>({providerInvoiceId:inv.id,providerCustomerId:inv.customer,status:inv.status,amountDue:inv.amount_due,amountPaid:inv.amount_paid,currency:inv.currency?.toUpperCase(),dueDate:inv.due_date?new Date(inv.due_date*1000).toISOString():void 0,hostedInvoiceUrl:inv.hosted_invoice_url})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,invoices:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list invoices",rawResponse:{error:err.message}}}},async getBalance(){try{let bal=await stripe.balance.retrieve(),mapAmounts=(arr)=>(arr??[]).map((a)=>({amount:a.amount,currency:a.currency?.toUpperCase()}));return{success:!0,available:mapAmounts(bal.available),pending:mapAmounts(bal.pending),connectReserved:mapAmounts(bal.connect_reserved),rawResponse:bal}}catch(error){let err=error;return{success:!1,available:[],pending:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get balance",rawResponse:{error:err.message}}}},async createPayout(request){try{let params={amount:request.amount,currency:request.currency.toLowerCase()};if(request.destination)params.destination=request.destination;if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.method)params.method=request.method;if(request.sourceType)params.source_type=request.sourceType;if(request.statementDescriptor)params.statement_descriptor=request.statementDescriptor;let payout=await stripe.payouts.create(params);return{success:!0,providerPayoutId:payout.id,amount:payout.amount,currency:payout.currency?.toUpperCase(),status:payout.status,arrivalDate:payout.arrival_date?new Date(payout.arrival_date*1000).toISOString():void 0,method:payout.method,rawResponse:payout}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create payout",rawResponse:{error:err.message}}}},async getPayout(request){try{let payout=await stripe.payouts.retrieve(request.providerPayoutId);return{success:!0,providerPayoutId:payout.id,amount:payout.amount,currency:payout.currency?.toUpperCase(),status:payout.status,arrivalDate:payout.arrival_date?new Date(payout.arrival_date*1000).toISOString():void 0,method:payout.method,description:payout.description,destination:payout.destination,metadata:payout.metadata,failureCode:payout.failure_code,failureMessage:payout.failure_message,rawResponse:payout}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to get payout",rawResponse:{error:err.message}}}},async cancelPayout(request){try{let payout=await stripe.payouts.cancel(request.providerPayoutId);return{success:!0,providerPayoutId:payout.id,status:payout.status,rawResponse:payout}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to cancel payout",rawResponse:{error:err.message}}}},async listPayouts(request){try{let params={};if(request.status)params.status=request.status;if(request.destination)params.destination=request.destination;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;if(request.arrivalDateGte||request.arrivalDateLte){let arrival={};if(request.arrivalDateGte)arrival.gte=request.arrivalDateGte;if(request.arrivalDateLte)arrival.lte=request.arrivalDateLte;params.arrival_date=arrival}let response=await stripe.payouts.list(params);return{success:!0,payouts:response.data.map((p)=>({providerPayoutId:p.id,amount:p.amount,currency:p.currency?.toUpperCase(),status:p.status,arrivalDate:p.arrival_date?new Date(p.arrival_date*1000).toISOString():void 0,method:p.method,description:p.description})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,payouts:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list payouts",rawResponse:{error:err.message}}}},async createTransfer(request){try{let params={amount:request.amount,currency:request.currency.toLowerCase(),destination:request.destination};if(request.description)params.description=request.description;if(request.metadata)params.metadata=request.metadata;if(request.sourceTransaction)params.source_transaction=request.sourceTransaction;if(request.transferGroup)params.transfer_group=request.transferGroup;let transfer=await stripe.transfers.create(params);return{success:!0,providerTransferId:transfer.id,amount:transfer.amount,currency:transfer.currency?.toUpperCase(),destination:transfer.destination,rawResponse:transfer}}catch(error){let err=error;return{success:!1,errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to create transfer",rawResponse:{error:err.message}}}},async listTransfers(request){try{let params={};if(request.destination)params.destination=request.destination;if(request.transferGroup)params.transfer_group=request.transferGroup;if(request.limit)params.limit=request.limit;if(request.startingAfter)params.starting_after=request.startingAfter;let response=await stripe.transfers.list(params);return{success:!0,transfers:response.data.map((t)=>({providerTransferId:t.id,amount:t.amount,currency:t.currency?.toUpperCase(),destination:t.destination,description:t.description,created:t.created?new Date(t.created*1000).toISOString():void 0})),hasMore:response.has_more,rawResponse:response}}catch(error){let err=error;return{success:!1,transfers:[],errorCode:err.code??"STRIPE_ERROR",errorMessage:err.message??"Failed to list transfers",rawResponse:{error:err.message}}}}}},verifyStripeWebhook=(rawBody,signature,webhookSecret)=>{try{let StripeModule=__require("stripe");return{success:!0,event:new(StripeModule.default??StripeModule)("sk_dummy_for_webhook_verification").webhooks.constructEvent(rawBody,signature,webhookSecret)}}catch(error){return{success:!1,event:null,error:error instanceof Error?error.message:"Webhook verification failed"}}};var init_StripeProvider=__esm(()=>{init_Logger2()});var resolveEnvValue3=(value)=>{let envValue=process.env[value];if(envValue)return envValue;return value},createPaymentService=(config)=>{let paymentConfig=config.payment;if(!paymentConfig?.enabled)return null;let log2=logger.scoped("payment.init"),providerName=paymentConfig.provider;if(!providerName)return log2.warn("payment.enabled=true but no provider specified"),null;let providerConfig=null,provider=null,webhookSecret;switch(providerName){case"iyzico":{let iyzicoConf=paymentConfig.iyzico;if(!iyzicoConf)return log2.warn("payment.provider=iyzico but no iyzico config block"),null;let apiUrl=resolveEnvValue3(iyzicoConf.apiUrl),apiKey=resolveEnvValue3(iyzicoConf.apiKey),secretKey=resolveEnvValue3(iyzicoConf.secretKey);if(!apiUrl||!apiKey||!secretKey)return log2.warn("iyzico credentials missing \u2014 ensure env vars are set",{apiUrl:iyzicoConf.apiUrl,apiKeyEnv:iyzicoConf.apiKey,secretKeyEnv:iyzicoConf.secretKey}),null;providerConfig={name:"iyzico",apiUrl,apiKey,secretKey},provider=createIyzicoProvider(providerConfig);break}case"stripe":{let stripeConf=paymentConfig.stripe;if(!stripeConf)return log2.warn("payment.provider=stripe but no stripe config block"),null;let secretKey=resolveEnvValue3(stripeConf.secretKey),whSecret=resolveEnvValue3(stripeConf.webhookSecret);if(!secretKey)return log2.warn("Stripe secret key missing \u2014 ensure env var is set",{secretKeyEnv:stripeConf.secretKey}),null;if(!whSecret)log2.warn("Stripe webhook secret missing \u2014 webhook verification will fail",{webhookSecretEnv:stripeConf.webhookSecret});webhookSecret=whSecret,provider=createStripeProvider({secretKey,webhookSecret:whSecret,apiVersion:stripeConf.apiVersion,maxNetworkRetries:stripeConf.maxNetworkRetries,timeout:stripeConf.timeout});break}default:return log2.warn(`Unknown provider: ${providerName}`),null}if(!provider)return null;return log2.info(`Initialized provider: ${providerName}`),{provider:providerName,providerInstance:provider,webhookSecret}};var init_PaymentService=__esm(()=>{init_Logger2();init_IyzicoProvider();init_StripeProvider()});var exports_Payment={};__export(exports_Payment,{verifyStripeWebhook:()=>verifyStripeWebhook,resolveMarketplaceConfig:()=>resolveMarketplaceConfig,createStripeProvider:()=>createStripeProvider,createPaymentService:()=>createPaymentService,createMarketplaceServices:()=>createMarketplaceServices,createIyzicoProvider:()=>createIyzicoProvider,computeSplitBreakdown:()=>computeSplitBreakdown,MarketplaceService:()=>MarketplaceService,MarketplacePayoutService:()=>MarketplacePayoutService});var init_Payment=__esm(()=>{init_IyzicoProvider();init_Marketplace();init_PaymentService();init_StripeProvider()});var genLookup=(target)=>{let lookupTemp=typeof Uint8Array>"u"?[]:new Uint8Array(256),len=64;for(let i=0;i<64;i++)lookupTemp[target.charCodeAt(i)]=i;return lookupTemp},lookup,lookupUrl,base64UrlPattern,base64Pattern,base64,base64_default;var init_base64=__esm(()=>{lookup=genLookup("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),lookupUrl=genLookup("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),base64UrlPattern=/^[-A-Za-z0-9\-_]*$/,base64Pattern=/^[-A-Za-z0-9+/]*={0,3}$/,base64={};base64.toArrayBuffer=(data,urlMode)=>{let len=data.length,bufferLength=data.length*0.75,i,p=0,encoded1,encoded2,encoded3,encoded4;if(data[data.length-1]==="="){if(bufferLength--,data[data.length-2]==="=")bufferLength--}let arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer),target=urlMode?lookupUrl:lookup;for(i=0;i<len;i+=4)encoded1=target[data.charCodeAt(i)],encoded2=target[data.charCodeAt(i+1)],encoded3=target[data.charCodeAt(i+2)],encoded4=target[data.charCodeAt(i+3)],bytes[p++]=encoded1<<2|encoded2>>4,bytes[p++]=(encoded2&15)<<4|encoded3>>2,bytes[p++]=(encoded3&3)<<6|encoded4&63;return arraybuffer};base64.fromArrayBuffer=(arrBuf,urlMode)=>{let bytes=new Uint8Array(arrBuf),i,result="",len=bytes.length,target=urlMode?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(i=0;i<len;i+=3)result+=target[bytes[i]>>2],result+=target[(bytes[i]&3)<<4|bytes[i+1]>>4],result+=target[(bytes[i+1]&15)<<2|bytes[i+2]>>6],result+=target[bytes[i+2]&63];let remainder=len%3;if(remainder===2)result=result.substring(0,result.length-1)+(urlMode?"":"=");else if(remainder===1)result=result.substring(0,result.length-2)+(urlMode?"":"==");return result};base64.toString=(str3,urlMode)=>{return new TextDecoder().decode(base64.toArrayBuffer(str3,urlMode))};base64.fromString=(str3,urlMode)=>{return base64.fromArrayBuffer(new TextEncoder().encode(str3),urlMode)};base64.validate=(encoded,urlMode)=>{if(!(typeof encoded==="string"||encoded instanceof String))return!1;try{return urlMode?base64UrlPattern.test(encoded):base64Pattern.test(encoded)}catch(_e){return!1}};base64.base64=base64;base64_default=base64});var exports_isoBase64URL={};__export(exports_isoBase64URL,{trimPadding:()=>trimPadding,toUTF8String:()=>toUTF8String,toBuffer:()=>toBuffer,toBase64:()=>toBase64,isBase64URL:()=>isBase64URL,isBase64:()=>isBase64,fromUTF8String:()=>fromUTF8String,fromBuffer:()=>fromBuffer});function toBuffer(base64urlString,from="base64url"){let _buffer=base64_default.toArrayBuffer(base64urlString,from==="base64url");return new Uint8Array(_buffer)}function fromBuffer(buffer,to="base64url"){let _normalized=new Uint8Array(buffer);return base64_default.fromArrayBuffer(_normalized.buffer,to==="base64url")}function toBase64(base64urlString){let fromBase64Url=base64_default.toArrayBuffer(base64urlString,!0);return base64_default.fromArrayBuffer(fromBase64Url)}function fromUTF8String(utf8String){return base64_default.fromString(utf8String,!0)}function toUTF8String(base64urlString){return base64_default.toString(base64urlString,!0)}function isBase64(input){return base64_default.validate(input,!1)}function isBase64URL(input){return input=trimPadding(input),base64_default.validate(input,!0)}function trimPadding(input){return input.replace(/=/g,"")}var init_isoBase64URL=__esm(()=>{init_base64()});function decodeLength(data,argument,index){if(argument<24)return[argument,1];let remainingDataLength=data.byteLength-index-1,view=new DataView(data.buffer,index+1),output,bytes=0;switch(argument){case 24:{if(remainingDataLength>0)output=view.getUint8(0),bytes=2;break}case 25:{if(remainingDataLength>1)output=view.getUint16(0,!1),bytes=3;break}case 26:{if(remainingDataLength>3)output=view.getUint32(0,!1),bytes=5;break}case 27:{if(remainingDataLength>7){let bigOutput=view.getBigUint64(0,!1);if(bigOutput>=24n&&bigOutput<=Number.MAX_SAFE_INTEGER)return[Number(bigOutput),9]}break}}if(output&&output>=24)return[output,bytes];throw Error("Length not supported or not well formed")}function encodeLength(major,argument){let majorEncoded=major<<5;if(argument<0)throw Error("CBOR Data Item argument must not be negative");let bigintArgument;if(typeof argument=="number"){if(!Number.isInteger(argument))throw Error("CBOR Data Item argument must be an integer");bigintArgument=BigInt(argument)}else bigintArgument=argument;if(major==MAJOR_TYPE_NEGATIVE_INTEGER){if(bigintArgument==0n)throw Error("CBOR Data Item argument cannot be zero when negative");bigintArgument=bigintArgument-1n}if(bigintArgument>18446744073709551615n)throw Error("CBOR number out of range");let buffer=new Uint8Array(8);if(new DataView(buffer.buffer).setBigUint64(0,bigintArgument,!1),bigintArgument<=23)return[majorEncoded|buffer[7]];else if(bigintArgument<=255)return[majorEncoded|24,buffer[7]];else if(bigintArgument<=65535)return[majorEncoded|25,...buffer.slice(6)];else if(bigintArgument<=4294967295)return[majorEncoded|26,...buffer.slice(4)];else return[majorEncoded|27,...buffer]}var MAJOR_TYPE_UNSIGNED_INTEGER=0,MAJOR_TYPE_NEGATIVE_INTEGER=1,MAJOR_TYPE_BYTE_STRING=2,MAJOR_TYPE_TEXT_STRING=3,MAJOR_TYPE_ARRAY=4,MAJOR_TYPE_MAP=5,MAJOR_TYPE_TAG=6,MAJOR_TYPE_SIMPLE_OR_FLOAT=7;class CBORTag{constructor(tag,value){Object.defineProperty(this,"tagId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tagValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tagId=tag,this.tagValue=value}get tag(){return this.tagId}get value(){return this.tagValue}}function decodeUnsignedInteger(data,argument,index){return decodeLength(data,argument,index)}function decodeNegativeInteger(data,argument,index){let[value,length]=decodeUnsignedInteger(data,argument,index);return[-value-1,length]}function decodeByteString(data,argument,index){let[lengthValue,lengthConsumed]=decodeLength(data,argument,index),dataStartIndex=index+lengthConsumed;return[new Uint8Array(data.buffer.slice(dataStartIndex,dataStartIndex+lengthValue)),lengthConsumed+lengthValue]}function decodeString(data,argument,index){let[value,length]=decodeByteString(data,argument,index);return[TEXT_DECODER.decode(value),length]}function decodeArray(data,argument,index){if(argument===0)return[[],1];let[length,lengthConsumed]=decodeLength(data,argument,index),consumedLength=lengthConsumed,value=[];for(let i=0;i<length;i++){if(data.byteLength-index-consumedLength<=0)throw Error("array is not supported or well formed");let[decodedValue,consumed]=decodeNext(data,index+consumedLength);value.push(decodedValue),consumedLength+=consumed}return[value,consumedLength]}function decodeMap(data,argument,index){if(argument===0)return[new Map,1];let[length,lengthConsumed]=decodeLength(data,argument,index),consumedLength=lengthConsumed,result=new Map;for(let i=0;i<length;i++){let remainingDataLength=data.byteLength-index-consumedLength;if(remainingDataLength<=0)throw Error(MAP_ERROR);let[key,keyConsumed]=decodeNext(data,index+consumedLength);if(consumedLength+=keyConsumed,remainingDataLength-=keyConsumed,remainingDataLength<=0)throw Error(MAP_ERROR);if(typeof key!=="string"&&typeof key!=="number")throw Error(MAP_ERROR);if(result.has(key))throw Error(MAP_ERROR);let[value,valueConsumed]=decodeNext(data,index+consumedLength);consumedLength+=valueConsumed,result.set(key,value)}return[result,consumedLength]}function decodeFloat16(data,index){if(index+3>data.byteLength)throw Error("CBOR stream ended before end of Float 16");let result=data.getUint16(index+1,!1);if(result==31744)return[1/0,3];else if(result==32256)return[NaN,3];else if(result==64512)return[-1/0,3];throw Error("Float16 data is unsupported")}function decodeFloat32(data,index){if(index+5>data.byteLength)throw Error("CBOR stream ended before end of Float 32");return[data.getFloat32(index+1,!1),5]}function decodeFloat64(data,index){if(index+9>data.byteLength)throw Error("CBOR stream ended before end of Float 64");return[data.getFloat64(index+1,!1),9]}function decodeTag(data,argument,index){let[tag,tagBytes]=decodeLength(data,argument,index),[value,valueBytes]=decodeNext(data,index+tagBytes);return[new CBORTag(tag,value),tagBytes+valueBytes]}function decodeNext(data,index){if(index>=data.byteLength)throw Error("CBOR stream ended before tag value");let byte=data.getUint8(index),majorType=byte>>5,argument=byte&31;switch(majorType){case MAJOR_TYPE_UNSIGNED_INTEGER:return decodeUnsignedInteger(data,argument,index);case MAJOR_TYPE_NEGATIVE_INTEGER:return decodeNegativeInteger(data,argument,index);case MAJOR_TYPE_BYTE_STRING:return decodeByteString(data,argument,index);case MAJOR_TYPE_TEXT_STRING:return decodeString(data,argument,index);case MAJOR_TYPE_ARRAY:return decodeArray(data,argument,index);case MAJOR_TYPE_MAP:return decodeMap(data,argument,index);case MAJOR_TYPE_TAG:return decodeTag(data,argument,index);case MAJOR_TYPE_SIMPLE_OR_FLOAT:switch(argument){case 20:return[!1,1];case 21:return[!0,1];case 22:return[null,1];case 23:return[void 0,1];case 25:return decodeFloat16(data,index);case 26:return decodeFloat32(data,index);case 27:return decodeFloat64(data,index)}}throw Error(`Unsupported or not well formed at ${index}`)}function encodeSimple(data){if(data===!0)return 245;else if(data===!1)return 244;else if(data===null)return 246;return 247}function encodeFloat(data){if(Math.fround(data)==data||!Number.isFinite(data)||Number.isNaN(data)){let output=new Uint8Array(5);return output[0]=250,new DataView(output.buffer).setFloat32(1,data,!1),output}else{let output=new Uint8Array(9);return output[0]=251,new DataView(output.buffer).setFloat64(1,data,!1),output}}function encodeNumber(data){if(typeof data=="number"){if(Number.isSafeInteger(data))if(data<0)return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER,Math.abs(data));else return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER,data);return[encodeFloat(data)]}else if(data<0n)return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER,data*-1n);else return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER,data)}function encodeString(data,output){output.push(...encodeLength(MAJOR_TYPE_TEXT_STRING,data.length)),output.push(ENCODER.encode(data))}function encodeBytes(data,output){output.push(...encodeLength(MAJOR_TYPE_BYTE_STRING,data.length)),output.push(data)}function encodeArray(data,output){output.push(...encodeLength(MAJOR_TYPE_ARRAY,data.length));for(let element of data)encodePartialCBOR(element,output)}function encodeMap(data,output){output.push(new Uint8Array(encodeLength(MAJOR_TYPE_MAP,data.size)));for(let[key,value]of data.entries())encodePartialCBOR(key,output),encodePartialCBOR(value,output)}function encodeTag(tag,output){output.push(...encodeLength(MAJOR_TYPE_TAG,tag.tag)),encodePartialCBOR(tag.value,output)}function encodePartialCBOR(data,output){if(typeof data=="boolean"||data===null||data==null){output.push(encodeSimple(data));return}if(typeof data=="number"||typeof data=="bigint"){output.push(...encodeNumber(data));return}if(typeof data=="string"){encodeString(data,output);return}if(data instanceof Uint8Array){encodeBytes(data,output);return}if(Array.isArray(data)){encodeArray(data,output);return}if(data instanceof Map){encodeMap(data,output);return}if(data instanceof CBORTag){encodeTag(data,output);return}throw Error("Not implemented")}function decodePartialCBOR(data,index){if(data.byteLength===0||data.byteLength<=index||index<0)throw Error("No data");if(data instanceof Uint8Array)return decodeNext(new DataView(data.buffer),index);else if(data instanceof ArrayBuffer)return decodeNext(new DataView(data),index);return decodeNext(data,index)}function encodeCBOR(data){let results=[];encodePartialCBOR(data,results);let length=0;for(let result of results)if(typeof result=="number")length+=1;else length+=result.length;let output=new Uint8Array(length),index=0;for(let result of results)if(typeof result=="number")output[index]=result,index+=1;else output.set(result,index),index+=result.length;return output}var TEXT_DECODER,MAP_ERROR="Map is not supported or well formed",ENCODER;var init_cbor=__esm(()=>{TEXT_DECODER=new TextDecoder;ENCODER=new TextEncoder});var init_esm=__esm(()=>{init_cbor()});var exports_isoCBOR={};__export(exports_isoCBOR,{encode:()=>encode,decodeFirst:()=>decodeFirst});function decodeFirst(input){let _input=new Uint8Array(input),decoded=decodePartialCBOR(_input,0),[first]=decoded;return first}function encode(input){return encodeCBOR(input)}var init_isoCBOR=__esm(()=>{init_esm()});function isCOSEPublicKeyOKP(cosePublicKey){let kty=cosePublicKey.get(COSEKEYS.kty);return isCOSEKty(kty)&&kty===COSEKTY.OKP}function isCOSEPublicKeyEC2(cosePublicKey){let kty=cosePublicKey.get(COSEKEYS.kty);return isCOSEKty(kty)&&kty===COSEKTY.EC2}function isCOSEPublicKeyRSA(cosePublicKey){let kty=cosePublicKey.get(COSEKEYS.kty);return isCOSEKty(kty)&&kty===COSEKTY.RSA}function isCOSEKty(kty){return Object.values(COSEKTY).indexOf(kty)>=0}function isCOSECrv(crv){return Object.values(COSECRV).indexOf(crv)>=0}function isCOSEAlg(alg){return Object.values(COSEALG).indexOf(alg)>=0}var COSEKEYS,COSEKTY,COSECRV,COSEALG;var init_cose=__esm(()=>{(function(COSEKEYS2){COSEKEYS2[COSEKEYS2.kty=1]="kty",COSEKEYS2[COSEKEYS2.alg=3]="alg",COSEKEYS2[COSEKEYS2.crv=-1]="crv",COSEKEYS2[COSEKEYS2.x=-2]="x",COSEKEYS2[COSEKEYS2.y=-3]="y",COSEKEYS2[COSEKEYS2.n=-1]="n",COSEKEYS2[COSEKEYS2.e=-2]="e"})(COSEKEYS||(COSEKEYS={}));(function(COSEKTY2){COSEKTY2[COSEKTY2.OKP=1]="OKP",COSEKTY2[COSEKTY2.EC2=2]="EC2",COSEKTY2[COSEKTY2.RSA=3]="RSA"})(COSEKTY||(COSEKTY={}));(function(COSECRV2){COSECRV2[COSECRV2.P256=1]="P256",COSECRV2[COSECRV2.P384=2]="P384",COSECRV2[COSECRV2.P521=3]="P521",COSECRV2[COSECRV2.ED25519=6]="ED25519",COSECRV2[COSECRV2.SECP256K1=8]="SECP256K1"})(COSECRV||(COSECRV={}));(function(COSEALG2){COSEALG2[COSEALG2.ES256=-7]="ES256",COSEALG2[COSEALG2.EdDSA=-8]="EdDSA",COSEALG2[COSEALG2.ES384=-35]="ES384",COSEALG2[COSEALG2.ES512=-36]="ES512",COSEALG2[COSEALG2.PS256=-37]="PS256",COSEALG2[COSEALG2.PS384=-38]="PS384",COSEALG2[COSEALG2.PS512=-39]="PS512",COSEALG2[COSEALG2.ES256K=-47]="ES256K",COSEALG2[COSEALG2.RS256=-257]="RS256",COSEALG2[COSEALG2.RS384=-258]="RS384",COSEALG2[COSEALG2.RS512=-259]="RS512",COSEALG2[COSEALG2.RS1=-65535]="RS1"})(COSEALG||(COSEALG={}))});function mapCoseAlgToWebCryptoAlg(alg){if([COSEALG.RS1].indexOf(alg)>=0)return"SHA-1";else if([COSEALG.ES256,COSEALG.PS256,COSEALG.RS256].indexOf(alg)>=0)return"SHA-256";else if([COSEALG.ES384,COSEALG.PS384,COSEALG.RS384].indexOf(alg)>=0)return"SHA-384";else if([COSEALG.ES512,COSEALG.PS512,COSEALG.RS512,COSEALG.EdDSA].indexOf(alg)>=0)return"SHA-512";throw Error(`Could not map COSE alg value of ${alg} to a WebCrypto alg`)}var init_mapCoseAlgToWebCryptoAlg=__esm(()=>{init_cose()});function getWebCrypto(){return new Promise((resolve2,reject)=>{if(webCrypto)return resolve2(webCrypto);let _globalThisCrypto=_getWebCryptoInternals.stubThisGlobalThisCrypto();if(_globalThisCrypto)return webCrypto=_globalThisCrypto,resolve2(webCrypto);return reject(new MissingWebCrypto)})}var webCrypto=void 0,MissingWebCrypto,_getWebCryptoInternals;var init_getWebCrypto=__esm(()=>{MissingWebCrypto=class MissingWebCrypto extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}};_getWebCryptoInternals={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(newCrypto)=>{webCrypto=newCrypto}}});async function digest(data,algorithm){let WebCrypto=await getWebCrypto(),subtleAlgorithm=mapCoseAlgToWebCryptoAlg(algorithm),hashed=await WebCrypto.subtle.digest(subtleAlgorithm,data);return new Uint8Array(hashed)}var init_digest=__esm(()=>{init_mapCoseAlgToWebCryptoAlg();init_getWebCrypto()});async function getRandomValues(array){return(await getWebCrypto()).getRandomValues(array),array}var init_getRandomValues=__esm(()=>{init_getWebCrypto()});async function importKey(opts){let WebCrypto=await getWebCrypto(),{keyData,algorithm}=opts;return WebCrypto.subtle.importKey("jwk",keyData,algorithm,!1,["verify"])}var init_importKey=__esm(()=>{init_getWebCrypto()});async function verifyEC2(opts){let{cosePublicKey,signature,data,shaHashOverride}=opts,WebCrypto=await getWebCrypto(),alg=cosePublicKey.get(COSEKEYS.alg),crv=cosePublicKey.get(COSEKEYS.crv),x=cosePublicKey.get(COSEKEYS.x),y=cosePublicKey.get(COSEKEYS.y);if(!alg)throw Error("Public key was missing alg (EC2)");if(!crv)throw Error("Public key was missing crv (EC2)");if(!x)throw Error("Public key was missing x (EC2)");if(!y)throw Error("Public key was missing y (EC2)");let _crv;if(crv===COSECRV.P256)_crv="P-256";else if(crv===COSECRV.P384)_crv="P-384";else if(crv===COSECRV.P521)_crv="P-521";else throw Error(`Unexpected COSE crv value of ${crv} (EC2)`);let keyData={kty:"EC",crv:_crv,x:exports_isoBase64URL.fromBuffer(x),y:exports_isoBase64URL.fromBuffer(y),ext:!1},key=await importKey({keyData,algorithm:{name:"ECDSA",namedCurve:_crv}}),subtleAlg=mapCoseAlgToWebCryptoAlg(alg);if(shaHashOverride)subtleAlg=mapCoseAlgToWebCryptoAlg(shaHashOverride);let verifyAlgorithm={name:"ECDSA",hash:{name:subtleAlg}};return WebCrypto.subtle.verify(verifyAlgorithm,key,signature,data)}var init_verifyEC2=__esm(()=>{init_cose();init_mapCoseAlgToWebCryptoAlg();init_importKey();init_iso();init_getWebCrypto()});function mapCoseAlgToWebCryptoKeyAlgName(alg){if([COSEALG.EdDSA].indexOf(alg)>=0)return"Ed25519";else if([COSEALG.ES256,COSEALG.ES384,COSEALG.ES512,COSEALG.ES256K].indexOf(alg)>=0)return"ECDSA";else if([COSEALG.RS256,COSEALG.RS384,COSEALG.RS512,COSEALG.RS1].indexOf(alg)>=0)return"RSASSA-PKCS1-v1_5";else if([COSEALG.PS256,COSEALG.PS384,COSEALG.PS512].indexOf(alg)>=0)return"RSA-PSS";throw Error(`Could not map COSE alg value of ${alg} to a WebCrypto key alg name`)}var init_mapCoseAlgToWebCryptoKeyAlgName=__esm(()=>{init_cose()});async function verifyRSA(opts){let{cosePublicKey,signature,data,shaHashOverride}=opts,WebCrypto=await getWebCrypto(),alg=cosePublicKey.get(COSEKEYS.alg),n=cosePublicKey.get(COSEKEYS.n),e=cosePublicKey.get(COSEKEYS.e);if(!alg)throw Error("Public key was missing alg (RSA)");if(!isCOSEAlg(alg))throw Error(`Public key had invalid alg ${alg} (RSA)`);if(!n)throw Error("Public key was missing n (RSA)");if(!e)throw Error("Public key was missing e (RSA)");let keyData={kty:"RSA",alg:"",n:exports_isoBase64URL.fromBuffer(n),e:exports_isoBase64URL.fromBuffer(e),ext:!1},keyAlgorithm={name:mapCoseAlgToWebCryptoKeyAlgName(alg),hash:{name:mapCoseAlgToWebCryptoAlg(alg)}},verifyAlgorithm={name:mapCoseAlgToWebCryptoKeyAlgName(alg)};if(shaHashOverride)keyAlgorithm.hash.name=mapCoseAlgToWebCryptoAlg(shaHashOverride);if(keyAlgorithm.name==="RSASSA-PKCS1-v1_5"){if(keyAlgorithm.hash.name==="SHA-256")keyData.alg="RS256";else if(keyAlgorithm.hash.name==="SHA-384")keyData.alg="RS384";else if(keyAlgorithm.hash.name==="SHA-512")keyData.alg="RS512";else if(keyAlgorithm.hash.name==="SHA-1")keyData.alg="RS1"}else if(keyAlgorithm.name==="RSA-PSS"){let saltLength=0;if(keyAlgorithm.hash.name==="SHA-256")keyData.alg="PS256",saltLength=32;else if(keyAlgorithm.hash.name==="SHA-384")keyData.alg="PS384",saltLength=48;else if(keyAlgorithm.hash.name==="SHA-512")keyData.alg="PS512",saltLength=64;verifyAlgorithm.saltLength=saltLength}else throw Error(`Unexpected RSA key algorithm ${alg} (${keyAlgorithm.name})`);let key=await importKey({keyData,algorithm:keyAlgorithm});return WebCrypto.subtle.verify(verifyAlgorithm,key,signature,data)}var init_verifyRSA=__esm(()=>{init_cose();init_mapCoseAlgToWebCryptoAlg();init_importKey();init_iso();init_mapCoseAlgToWebCryptoKeyAlgName();init_getWebCrypto()});function convertAAGUIDToString(aaguid){let hex=exports_isoUint8Array.toHex(aaguid);return[hex.slice(0,8),hex.slice(8,12),hex.slice(12,16),hex.slice(16,20),hex.slice(20,32)].join("-")}var init_convertAAGUIDToString=__esm(()=>{init_iso()});function convertCertBufferToPEM(certBuffer){let b64cert;if(typeof certBuffer==="string")if(exports_isoBase64URL.isBase64URL(certBuffer))b64cert=exports_isoBase64URL.toBase64(certBuffer);else if(exports_isoBase64URL.isBase64(certBuffer))b64cert=certBuffer;else throw Error("Certificate is not a valid base64 or base64url string");else b64cert=exports_isoBase64URL.fromBuffer(certBuffer,"base64");let PEMKey="";for(let i=0;i<Math.ceil(b64cert.length/64);i+=1){let start=64*i;PEMKey+=`${b64cert.substr(start,64)}
90
90
  `}return PEMKey=`-----BEGIN CERTIFICATE-----
91
91
  ${PEMKey}-----END CERTIFICATE-----
92
92
  `,PEMKey}var init_convertCertBufferToPEM=__esm(()=>{init_iso()});function convertCOSEtoPKCS(cosePublicKey){let struct=exports_isoCBOR.decodeFirst(cosePublicKey),tag=Uint8Array.from([4]),x=struct.get(COSEKEYS.x),y=struct.get(COSEKEYS.y);if(!x)throw Error("COSE public key was missing x");if(y)return exports_isoUint8Array.concat([tag,x,y]);return exports_isoUint8Array.concat([tag,x])}var init_convertCOSEtoPKCS=__esm(()=>{init_iso();init_cose()});function decodeAttestationObject(attestationObject){return _decodeAttestationObjectInternals.stubThis(exports_isoCBOR.decodeFirst(attestationObject))}var _decodeAttestationObjectInternals;var init_decodeAttestationObject=__esm(()=>{init_iso();_decodeAttestationObjectInternals={stubThis:(value)=>value}});function decodeClientDataJSON(data){let toString=exports_isoBase64URL.toUTF8String(data),clientData=JSON.parse(toString);return _decodeClientDataJSONInternals.stubThis(clientData)}var _decodeClientDataJSONInternals;var init_decodeClientDataJSON=__esm(()=>{init_iso();_decodeClientDataJSONInternals={stubThis:(value)=>value}});function decodeCredentialPublicKey(publicKey){return _decodeCredentialPublicKeyInternals.stubThis(exports_isoCBOR.decodeFirst(publicKey))}var _decodeCredentialPublicKeyInternals;var init_decodeCredentialPublicKey=__esm(()=>{init_iso();_decodeCredentialPublicKeyInternals={stubThis:(value)=>value}});async function generateUserID(){let newUserID=new Uint8Array(32);return await exports_isoCrypto.getRandomValues(newUserID),_generateUserIDInternals.stubThis(newUserID)}var _generateUserIDInternals;var init_generateUserID=__esm(()=>{init_iso();_generateUserIDInternals={stubThis:(value)=>value}});class BufferSourceConverter{static isArrayBuffer(data){return Object.prototype.toString.call(data)==="[object ArrayBuffer]"}static toArrayBuffer(data){if(this.isArrayBuffer(data))return data;if(data.byteLength===data.buffer.byteLength)return data.buffer;if(data.byteOffset===0&&data.byteLength===data.buffer.byteLength)return data.buffer;return this.toUint8Array(data.buffer).slice(data.byteOffset,data.byteOffset+data.byteLength).buffer}static toUint8Array(data){return this.toView(data,Uint8Array)}static toView(data,type){if(data.constructor===type)return data;if(this.isArrayBuffer(data))return new type(data);if(this.isArrayBufferView(data))return new type(data.buffer,data.byteOffset,data.byteLength);throw TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(data){return this.isArrayBufferView(data)||this.isArrayBuffer(data)}static isArrayBufferView(data){return ArrayBuffer.isView(data)||data&&this.isArrayBuffer(data.buffer)}static isEqual(a,b){let aView=BufferSourceConverter.toUint8Array(a),bView=BufferSourceConverter.toUint8Array(b);if(aView.length!==bView.byteLength)return!1;for(let i=0;i<aView.length;i++)if(aView[i]!==bView[i])return!1;return!0}static concat(...args){let buffers;if(Array.isArray(args[0])&&!(args[1]instanceof Function))buffers=args[0];else if(Array.isArray(args[0])&&args[1]instanceof Function)buffers=args[0];else if(args[args.length-1]instanceof Function)buffers=args.slice(0,args.length-1);else buffers=args;let size=0;for(let buffer of buffers)size+=buffer.byteLength;let res=new Uint8Array(size),offset=0;for(let buffer of buffers){let view=this.toUint8Array(buffer);res.set(view,offset),offset+=view.length}if(args[args.length-1]instanceof Function)return this.toView(res,args[args.length-1]);return res.buffer}}class Utf8Converter{static fromString(text){let s=unescape(encodeURIComponent(text)),uintArray=new Uint8Array(s.length);for(let i=0;i<s.length;i++)uintArray[i]=s.charCodeAt(i);return uintArray.buffer}static toString(buffer){let buf=BufferSourceConverter.toUint8Array(buffer),encodedString="";for(let i=0;i<buf.length;i++)encodedString+=String.fromCharCode(buf[i]);return decodeURIComponent(escape(encodedString))}}class Utf16Converter{static toString(buffer,littleEndian=!1){let arrayBuffer=BufferSourceConverter.toArrayBuffer(buffer),dataView=new DataView(arrayBuffer),res="";for(let i=0;i<arrayBuffer.byteLength;i+=2){let code=dataView.getUint16(i,littleEndian);res+=String.fromCharCode(code)}return res}static fromString(text,littleEndian=!1){let res=new ArrayBuffer(text.length*2),dataView=new DataView(res);for(let i=0;i<text.length;i++)dataView.setUint16(i*2,text.charCodeAt(i),littleEndian);return res}}class Convert{static isHex(data){return typeof data===STRING_TYPE&&HEX_REGEX.test(data)}static isBase64(data){return typeof data===STRING_TYPE&&BASE64_REGEX.test(data)}static isBase64Url(data){return typeof data===STRING_TYPE&&BASE64URL_REGEX.test(data)}static ToString(buffer,enc="utf8"){let buf=BufferSourceConverter.toUint8Array(buffer);switch(enc.toLowerCase()){case"utf8":return this.ToUtf8String(buf);case"binary":return this.ToBinary(buf);case"hex":return this.ToHex(buf);case"base64":return this.ToBase64(buf);case"base64url":return this.ToBase64Url(buf);case"utf16le":return Utf16Converter.toString(buf,!0);case"utf16":case"utf16be":return Utf16Converter.toString(buf);default:throw Error(`Unknown type of encoding '${enc}'`)}}static FromString(str3,enc="utf8"){if(!str3)return new ArrayBuffer(0);switch(enc.toLowerCase()){case"utf8":return this.FromUtf8String(str3);case"binary":return this.FromBinary(str3);case"hex":return this.FromHex(str3);case"base64":return this.FromBase64(str3);case"base64url":return this.FromBase64Url(str3);case"utf16le":return Utf16Converter.fromString(str3,!0);case"utf16":case"utf16be":return Utf16Converter.fromString(str3);default:throw Error(`Unknown type of encoding '${enc}'`)}}static ToBase64(buffer){let buf=BufferSourceConverter.toUint8Array(buffer);if(typeof btoa<"u"){let binary=this.ToString(buf,"binary");return btoa(binary)}else return Buffer.from(buf).toString("base64")}static FromBase64(base642){let formatted=this.formatString(base642);if(!formatted)return new ArrayBuffer(0);if(!Convert.isBase64(formatted))throw TypeError("Argument 'base64Text' is not Base64 encoded");if(typeof atob<"u")return this.FromBinary(atob(formatted));else return new Uint8Array(Buffer.from(formatted,"base64")).buffer}static FromBase64Url(base64url){let formatted=this.formatString(base64url);if(!formatted)return new ArrayBuffer(0);if(!Convert.isBase64Url(formatted))throw TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(formatted.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(data){return this.ToBase64(data).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(text,encoding=Convert.DEFAULT_UTF8_ENCODING){switch(encoding){case"ascii":return this.FromBinary(text);case"utf8":return Utf8Converter.fromString(text);case"utf16":case"utf16be":return Utf16Converter.fromString(text);case"utf16le":case"usc2":return Utf16Converter.fromString(text,!0);default:throw Error(`Unknown type of encoding '${encoding}'`)}}static ToUtf8String(buffer,encoding=Convert.DEFAULT_UTF8_ENCODING){switch(encoding){case"ascii":return this.ToBinary(buffer);case"utf8":return Utf8Converter.toString(buffer);case"utf16":case"utf16be":return Utf16Converter.toString(buffer);case"utf16le":case"usc2":return Utf16Converter.toString(buffer,!0);default:throw Error(`Unknown type of encoding '${encoding}'`)}}static FromBinary(text){let stringLength=text.length,resultView=new Uint8Array(stringLength);for(let i=0;i<stringLength;i++)resultView[i]=text.charCodeAt(i);return resultView.buffer}static ToBinary(buffer){let buf=BufferSourceConverter.toUint8Array(buffer),res="";for(let i=0;i<buf.length;i++)res+=String.fromCharCode(buf[i]);return res}static ToHex(buffer){let buf=BufferSourceConverter.toUint8Array(buffer),result="",len=buf.length;for(let i=0;i<len;i++){let byte=buf[i];if(byte<16)result+="0";result+=byte.toString(16)}return result}static FromHex(hexString){let formatted=this.formatString(hexString);if(!formatted)return new ArrayBuffer(0);if(!Convert.isHex(formatted))throw TypeError("Argument 'hexString' is not HEX encoded");if(formatted.length%2)formatted=`0${formatted}`;let res=new Uint8Array(formatted.length/2);for(let i=0;i<formatted.length;i=i+2){let c=formatted.slice(i,i+2);res[i/2]=parseInt(c,16)}return res.buffer}static ToUtf16String(buffer,littleEndian=!1){return Utf16Converter.toString(buffer,littleEndian)}static FromUtf16String(text,littleEndian=!1){return Utf16Converter.fromString(text,littleEndian)}static Base64Padding(base642){let padCount=4-base642.length%4;if(padCount<4)for(let i=0;i<padCount;i++)base642+="=";return base642}static formatString(data){return(data===null||data===void 0?void 0:data.replace(/[\n\r\t ]/g,""))||""}}function combine(...buf){let totalByteLength=buf.map((item)=>item.byteLength).reduce((prev,cur)=>prev+cur),res=new Uint8Array(totalByteLength),currentPos=0;return buf.map((item)=>new Uint8Array(item)).forEach((arr)=>{for(let item2 of arr)res[currentPos++]=item2}),res.buffer}function isEqual(bytes1,bytes2){if(!(bytes1&&bytes2))return!1;if(bytes1.byteLength!==bytes2.byteLength)return!1;let b1=new Uint8Array(bytes1),b2=new Uint8Array(bytes2);for(let i=0;i<bytes1.byteLength;i++)if(b1[i]!==b2[i])return!1;return!0}var STRING_TYPE="string",HEX_REGEX,BASE64_REGEX,BASE64URL_REGEX;var init_index_es=__esm(()=>{/*!
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nucleus-core-ts",
3
- "version": "0.9.174",
3
+ "version": "0.9.175",
4
4
  "description": "Production-ready, enterprise-grade TypeScript framework for building multi-tenant APIs",
5
5
  "author": "Hidayet Can Özcan <hidayetcan@gmail.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",