nucleus-core-ts 0.10.189 → 0.10.190

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.
package/dist/.build-ok CHANGED
@@ -1 +1 @@
1
- 0.10.189
1
+ 0.10.190
package/dist/index.js CHANGED
@@ -629,7 +629,7 @@ ${content}
629
629
  where id = ${id}`)}async function purgeExpiredIdempotencyKeys(executor,schema3,options={}){let batch3=Math.max(1,Math.floor(options.batchSize??1000)),total=0;for(let round=0;round<(options.maxBatches??100);round++){let result=await executor.execute(sql41`
630
630
  delete from ${table(schema3)}
631
631
  where id in (select id from ${table(schema3)} where expires_at <= now() limit ${batch3})
632
- returning id`),removed=rowsOfResult(result).length;if(total+=removed,removed<batch3)break}return total}var defaultEnvelope={success:(data)=>({success:!0,data:data??null}),failure:(failure)=>({success:!1,error:failure.code,message:failure.message,...failure.details===void 0?{}:{details:failure.details}})};function failureOf(error3){if(error3 instanceof ActionError)return{status:error3.status,code:error3.code,message:error3.message,details:error3.details};if(error3 instanceof IdempotencyConflictError)return{status:409,code:"idempotency_key_reused",message:error3.message};if(error3 instanceof ScopeViolationError)return{status:403,code:"scope_violation",message:"This write is outside your scope"};if(error3 instanceof Error){let constraint=toConstraintError(error3);if(constraint!==null)return{status:409,code:"constraint_violation",message:constraint.message,details:{kind:constraint.kind,constraint:constraint.constraint,columns:[...constraint.columns],table:constraint.table}}}if(isRetryable(error3))return{status:409,code:"serialization_failure",message:"The request conflicted with a concurrent one; repeat it"};return null}var ACTION_SCOPE="data.action",DEFAULT_IDEMPOTENCY_HEADER="Idempotency-Key",KEY_MAX_LENGTH=255;function schemaFor(host,action,request){if(action.scope==="main")return host.mainSchema;return host.schemaOf?.(request)??request.headers.get("x-tenant-schema")??host.mainSchema}function idempotencyOf(action,call,actorId){let settings=action.idempotency;if(settings===void 0)return null;let key2=call.request.headers.get(settings.header??DEFAULT_IDEMPOTENCY_HEADER)?.trim();if(key2===void 0||key2==="")return settings.required===!0?{status:400,code:"idempotency_key_required",message:"The Idempotency-Key header is required"}:null;if(key2.length>KEY_MAX_LENGTH)return{status:400,code:"idempotency_key_invalid",message:"The idempotency key is too long"};return{key:key2,action:action.name,actor:actorId??"",payloadHash:payloadHash({body:call.body,query:call.query,params:call.params}),ttlSeconds:settings.ttlSeconds??DEFAULT_IDEMPOTENCY_TTL_SECONDS}}function isFailure(value2){return value2!==null&&"status"in value2}function render(call,envelope,failure){return call.set.status=failure.status,envelope.failure(failure)}async function runAction(host,action,call){let log4=(host.logger??logger).scoped(ACTION_SCOPE),envelope=host.envelope??defaultEnvelope,actor=actorOf2(call.request),schema3=schemaFor(host,action,call.request),claim=idempotencyOf(action,call,actor.id);if(isFailure(claim))return render(call,envelope,claim);let nucleus=call.nucleus,ctx={request:call.request,actor,schema:schema3,set:call.set,nucleus:call.nucleus},db=host.db??nucleusDataOf(nucleus)?.db;if(db===void 0)throw new StoreError(`Action "${action.name}" has no database: the host gave no db and the server is not served by createNucleusServer`);let options={db,schema:schema3,mainSchema:host.mainSchema,scope:host.scopeFor(actor),tables:host.tables,relations:host.relations,logger:log4,retry:action.retry,isolationLevel:action.isolationLevel,readOnly:action.readOnly,notifier:nucleus===null?void 0:(params)=>nucleus.sendNotification(params)};try{let outcome=await runUnitOfWork(options,async(unit)=>{call.set.status=void 0;let keyRowId=null;if(claim!==null){let taken=await claimIdempotencyKey(executorOf2(unit),schema3,claim);if(taken.kind==="replay")return{status:taken.status,body:envelope.success(taken.body),replayed:!0};keyRowId=taken.id}let result=await action.handler({params:call.params,body:call.body,query:call.query},unit,ctx),status=call.set.status??200;if(claim!==null&&keyRowId!==null)await completeIdempotency(executorOf2(unit),schema3,keyRowId,status,result);return{status,body:envelope.success(result),replayed:!1}});if(call.set.status=outcome.status,outcome.replayed)call.set.headers["idempotent-replay"]="true";return outcome.body}catch(error3){let failure=failureOf(error3);if(failure===null)throw error3;return log4.warn("Action refused",{action:action.name,status:failure.status,code:failure.code}),render(call,envelope,failure)}}function accessGuard(spec,host){if(spec.public===!0&&spec.roles===void 0&&spec.claims===void 0)return null;let envelope=host.envelope??defaultEnvelope;return({request,set:set2})=>{let actor=actorOf2(request);if(actor.id===null&&spec.public!==!0)return set2.status=401,envelope.failure({status:401,code:"unauthorized",message:"Sign in first"});if(!actorMaySee(actor,spec))return set2.status=403,envelope.failure({status:403,code:"forbidden",message:"You may not do this"});return}}function defineActionFor(){return function(spec){return{name:spec.name,method:spec.method,path:spec.path,toRoute(host){let guard5=accessGuard(spec,host);return defineRoute({method:spec.method,path:spec.path,isPublic:spec.public,body:spec.body,query:spec.query,params:spec.params,response:spec.response,detail:{summary:spec.name,tags:["Actions"],...spec.detail},guards:guard5===null?[]:[guard5],handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,spec,{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}}var defineAction=defineActionFor();function actionGroup(host,actions){let names3=new Set;for(let action of actions){if(names3.has(action.name))throw Error(`Two actions are named "${action.name}"`);names3.add(action.name)}return{routes:actions.map((action)=>action.toRoute(host))}}function cellOf2(value2){if(value2 instanceof Date)return{d:value2.toISOString()};if(typeof value2==="bigint")return{n:value2.toString()};return value2}function isRecord6(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function scalarOf3(cell){if(!isRecord6(cell)){if(Array.isArray(cell))throw new ViewError("Invalid cursor");return cell}let{d,n}=cell;if(typeof d==="string"){let date4=new Date(d);if(Number.isNaN(date4.getTime()))throw new ViewError("Invalid cursor");return date4}if(typeof n==="string"&&/^-?\d+$/.test(n))return BigInt(n);throw new ViewError("Invalid cursor")}function sortLabel(sort){return sort===void 0?"default":sort.map((s)=>`${s.field}:${s.direction}`).join(",")}function encodeViewCursor(sort,values){let body={s:sortLabel(sort),v:values.map(cellOf2)};return Buffer.from(JSON.stringify(body),"utf8").toString("base64url")}function decodeViewCursor(token,sort){let body;try{body=JSON.parse(Buffer.from(token,"base64url").toString("utf8"))}catch{throw new ViewError("Invalid cursor")}if(!isRecord6(body)||typeof body.s!=="string"||!Array.isArray(body.v))throw new ViewError("Invalid cursor");if(body.s!==sortLabel(sort))throw new ViewError("The cursor was issued for a different sort");return body.v.map(scalarOf3)}function isPlain(value2){return!Array.isArray(value2)&&!(value2 instanceof Date)}function jsonOfValue(value2){if(value2===null||typeof value2==="string"||typeof value2==="boolean")return value2;if(typeof value2==="number")return Number.isFinite(value2)?value2:null;if(typeof value2==="bigint")return value2.toString();if(value2 instanceof Date)return value2.toISOString();if(Array.isArray(value2))return value2.map((item)=>jsonOfValue(item));let out={};if(!isPlain(value2))return out;for(let[key2,item]of Object.entries(value2))if(item!==void 0)out[key2]=jsonOfValue(item);return out}class ViewParamError extends Error{param;constructor(param,message){super(`View parameter "${param}": ${message}`);this.param=param}}var DAY3=/^(\d{4})-(\d{2})-(\d{2})$/;function asText2(name2,raw){if(typeof raw==="string")return raw;if(typeof raw==="number"||typeof raw==="boolean")return String(raw);throw new ViewParamError(name2,"expected text")}function toNumber(name2,raw,decl){let value2=typeof raw==="number"?raw:Number(asText2(name2,raw)),whole=decl.type==="number"||Number.isInteger(value2);if(!Number.isFinite(value2)||!whole)throw new ViewParamError(name2,`expected ${decl.type}`);if(decl.min!==void 0&&value2<decl.min)throw new ViewParamError(name2,`must be at least ${decl.min}`);if(decl.max!==void 0&&value2>decl.max)throw new ViewParamError(name2,`must be at most ${decl.max}`);return value2}function toDay(name2,raw){let text4=asText2(name2,raw),m=DAY3.exec(text4);if(!(m!==null&&new Date(Date.UTC(Number(m[1]),Number(m[2])-1,Number(m[3]))).toISOString().startsWith(text4)))throw new ViewParamError(name2,"expected a calendar day, YYYY-MM-DD");return text4}function toBoolean(name2,raw){if(typeof raw==="boolean")return raw;let text4=asText2(name2,raw);if(text4==="true"||text4==="1")return!0;if(text4==="false"||text4==="0")return!1;throw new ViewParamError(name2,"expected true or false")}function toTimestamp(name2,raw){let date4=raw instanceof Date?raw:new Date(asText2(name2,raw));if(Number.isNaN(date4.getTime()))throw new ViewParamError(name2,"expected a timestamp");return date4}function toList(name2,raw,allowed){let clean2=(Array.isArray(raw)?[...raw]:asText2(name2,raw).split(",")).map((s)=>s.trim()).filter((s)=>s!==""),bad=clean2.find((s)=>allowed!==void 0&&!allowed.includes(s));if(bad!==void 0)throw new ViewParamError(name2,`"${bad}" is not an allowed value`);return clean2}function toText(name2,raw,decl){let text4=asText2(name2,raw);if(decl.enum!==void 0&&!decl.enum.includes(text4))throw new ViewParamError(name2,`"${text4}" is not an allowed value`);return text4}function convert3(name2,raw,decl){switch(decl.type){case"string":return toText(name2,raw,decl);case"integer":case"number":return toNumber(name2,raw,decl);case"boolean":return toBoolean(name2,raw);case"date":return toDay(name2,raw);case"timestamp":return toTimestamp(name2,raw);case"csv":return toList(name2,raw,decl.enum)}}function fresh(value2){return value2 instanceof Date||typeof value2!=="object"?value2:[...value2]}function parseParams(decls,input){for(let name2 of Object.keys(input))if(!Object.hasOwn(decls,name2))throw new ViewParamError(name2,"is not declared by this view");let out={};for(let[name2,decl]of Object.entries(decls)){let raw=input[name2];if(raw===void 0||raw===""){if(decl.default!==void 0)out[name2]=fresh(decl.default);else if(decl.optional!==!0)throw new ViewParamError(name2,"is required");continue}out[name2]=convert3(name2,raw,decl)}return out}init_utils5();var RESERVED_QUERY_NAMES=["page","limit","after","filters","sort"],OPERATORS2=["eq","neq","gt","gte","lt","lte","like","ilike"],LISTS2=["in","notIn"];function isRecord7(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function jsonOf2(name2,text4){try{return JSON.parse(text4)}catch{throw new ViewError(`"${name2}" is not valid JSON`)}}function scalarOf4(name2,value2){if(typeof value2==="string"||typeof value2==="number"||typeof value2==="boolean")return value2;throw new ViewError(`"${name2}": the value must be a string, a number or a boolean`)}function opsOf(entry){let{operator,field:field2}=entry;if(typeof operator!=="string")throw new ViewError('A filter needs an "operator"');let label2=`Filter on "${String(field2)}"`,one=OPERATORS2.find((o)=>o===operator);if(one!==void 0)return{[one]:scalarOf4(label2,entry.value)};let list3=LISTS2.find((o)=>o===operator);if(list3!==void 0){let values=entry.value;if(!Array.isArray(values))throw new ViewError(`${label2}: "${operator}" takes an array`);return{[list3]:values.map((v)=>scalarOf4(label2,v))}}if(operator==="isNull")return{isNull:!0};if(operator==="isNotNull")return{isNull:!1};throw new ViewError(`${label2}: unknown operator "${operator}"`)}function parseFilters(text4){if(text4===void 0||text4==="")return{};let list3=jsonOf2("filters",text4);if(!Array.isArray(list3))throw new ViewError('"filters" must be a JSON array');let out={};for(let entry of list3){if(!isRecord7(entry)||typeof entry.field!=="string")throw new ViewError('A filter is { "field", "operator", "value" }');let ops=opsOf(entry),known=out[entry.field]??{};for(let key2 of Object.keys(ops))if(Object.hasOwn(known,key2))throw new ViewError(`Two "${key2}" filters on "${entry.field}"`);out[entry.field]={...known,...ops}}return out}function directionOf(value2){if(value2==="asc"||value2==="desc")return value2;throw new ViewError('A sort direction is "asc" or "desc"')}function parseSort(text4){if(text4===void 0||text4.trim()==="")return;let trimmed=text4.trim();if(!trimmed.startsWith("["))return trimmed.split(",").map((part)=>{let name2=part.trim(),desc9=name2.startsWith("-"),field2=desc9?name2.slice(1):name2;if(field2==="")throw new ViewError("An empty sort field");return{field:field2,direction:desc9?"desc":"asc"}});let list3=jsonOf2("sort",trimmed);if(!Array.isArray(list3))throw new ViewError('"sort" must be a JSON array');return list3.map((entry)=>{if(!isRecord7(entry)||typeof entry.field!=="string")throw new ViewError('A sort is { "field", "direction" }');return{field:entry.field,direction:directionOf(entry.direction)}})}function positive2(name2,text4,fallback){if(text4===null||text4==="")return fallback;let value2=Number(text4);if(!Number.isInteger(value2)||value2<1)throw new ViewError(`"${name2}" must be a positive integer`);return value2}function parseViewQuery(url){let query=url.searchParams,params={};for(let name2 of new Set(query.keys())){if(RESERVED_QUERY_NAMES.includes(name2))continue;let values=query.getAll(name2);params[name2]=values.length===1&&values[0]!==void 0?values[0]:values}let after=query.get("after")??void 0;if(after!==void 0&&query.has("page"))throw new ViewError('Send "page" or "after", not both');return{params,filters:parseFilters(query.get("filters")??void 0),sort:parseSort(query.get("sort")??void 0),page:positive2("page",query.get("page"),1)??1,limit:positive2("limit",query.get("limit"),void 0),after:after===""?void 0:after}}function refusal(error3){if(error3 instanceof ViewParamError)return new ActionError(422,"invalid_view_params",error3.message,{param:error3.param});return new ActionError(422,"invalid_view_request",error3.message)}function requestOf(view,ctx,paging){let url=new URL(ctx.request.url),query=parseViewQuery(url);if(paging==="cursor"&&url.searchParams.has("page"))throw new ViewError('This view pages with "after", not "page"');let size=query.limit??view.plan.limit,offset=paging==="offset"?(query.page-1)*size:void 0;return{request:{params:view.parseParams(query.params),filters:query.filters,sort:query.sort,limit:query.limit,offset,after:query.after===void 0?void 0:decodeViewCursor(query.after,query.sort)},page:query.page,offset:offset??0,sort:query.sort}}async function runViewCall(view,paging,unit,ctx){try{let{request,page,offset,sort}=requestOf(view,ctx,paging),result=await unit.store.view(view,request),items=result.items.map((row)=>jsonOfValue(row));if(paging==="cursor"){let nextCursor=result.next===null?null:encodeViewCursor(sort,result.next);return{items,meta:{limit:result.limit,hasNextPage:result.hasNextPage,nextCursor}}}let total=await unit.store.countView(view,request);return{items,meta:{...buildPaginationMeta(page,result.limit,offset,total)}}}catch(error3){if(error3 instanceof ViewParamError||error3 instanceof ViewError)throw refusal(error3);throw error3}}function viewClaimOf(name2){return`get.view.${name2}`}function check2(spec){let name2=spec.view.plan.name;if(!spec.path.startsWith("/")||spec.path.includes(":"))throw Error(`View "${name2}": the path must be a literal starting with "/" ("${spec.path}")`);let clash=Object.keys(spec.view.plan.params).find((p)=>RESERVED_QUERY_NAMES.includes(p));if(clash!==void 0)throw Error(`View "${name2}": the param name "${clash}" is reserved by the view route`)}function guardsOf(spec,host){let name2=spec.view.plan.name,claims=spec.roles===void 0&&spec.claims===void 0&&spec.public!==!0?[viewClaimOf(name2)]:spec.claims,access2=accessGuard({public:spec.public,roles:spec.roles,claims},host),guards2=access2===null?[]:[access2];if(spec.tenantFeature!==void 0){let registry5=host.getTenantRegistry;if(registry5===void 0)throw Error(`View "${name2}" declares tenant_feature but the host has no getTenantRegistry`);guards2.push(createTenantFeatureGuard(spec.tenantFeature,()=>registry5.call(host)))}return guards2}function defineViewRoute(spec){check2(spec);let name2=spec.view.plan.name;return{name:name2,path:spec.path,toRoute(host){let paging=spec.paging??"offset";return defineRoute({method:"GET",path:spec.path,isPublic:spec.public,detail:{summary:`View ${name2}`,tags:["Views"],...spec.detail},guards:guardsOf(spec,host),handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,{name:`view.${name2}`,scope:spec.scope,readOnly:!0,handler:(_input,unit,ctx)=>runViewCall(spec.view,paging,unit,ctx)},{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}function viewGroup(host,views){let names3=new Set;for(let view of views){if(names3.has(view.name))throw Error(`Two views are named "${view.name}"`);names3.add(view.name)}return{routes:views.map((view)=>view.toRoute(host))}}var PARAM="$param.";function fieldName(name2){return(name2.startsWith("$dim.")?name2.slice(5):name2).split(".").map(snakeToCamel).join(".")}function isRecord8(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function readParam(ctx,name2){let value2=Reflect.get(ctx.params,name2);if(value2===void 0||value2 instanceof Date)return value2;if(typeof value2==="string"||typeof value2==="number"||typeof value2==="boolean")return value2;if(Array.isArray(value2)&&value2.every((v)=>typeof v==="string"))return value2;throw new ViewError(`Param "${name2}" has a value no filter can use`)}function reference(value2,ctx){if(value2==="$now")return new Date;return value2.startsWith(PARAM)?readParam(ctx,value2.slice(PARAM.length)):value2}function scalarOf5(value2,ctx){let resolved=typeof value2==="string"?reference(value2,ctx):value2;if(resolved===void 0)return;if(Array.isArray(resolved)||typeof resolved==="object"&&!(resolved instanceof Date)&&resolved!==null)throw new ViewError("A list or object is not a single value here");return resolved}function listOf3(value2,ctx){let resolved=typeof value2==="string"?reference(value2,ctx):value2;if(resolved===void 0)return;if(!Array.isArray(resolved))throw new ViewError('"in" and "notIn" take a list');let items=resolved.map((item)=>typeof item==="object"&&item!==null?void 0:scalarOf5(item,ctx));if(items.includes(void 0))throw new ViewError("A list item reads a param that is not set");return items.filter((item)=>item!==void 0)}function operandOf(raw,ctx){return isRecord8(raw)?exprOf(raw,ctx):scalarOf5(raw,ctx)}var SINGLE={eq:(eq84)=>({eq:eq84}),neq:(neq)=>({neq}),gt:(gt2)=>({gt:gt2}),gte:(gte2)=>({gte:gte2}),lt:(lt4)=>({lt:lt4}),lte:(lte2)=>({lte:lte2})};function opOf(op,raw,ctx){let single=SINGLE[op];if(single!==void 0){let value2=operandOf(raw,ctx);return value2===void 0?null:single(value2)}switch(op){case"in":case"notIn":{let list3=isRecord8(raw)?exprOf(raw,ctx):listOf3(raw,ctx);if(list3===void 0)return null;return op==="in"?{in:list3}:{notIn:list3}}case"like":case"ilike":{let text4=scalarOf5(raw,ctx);if(text4===void 0)return null;if(typeof text4!=="string")throw new ViewError(`"${op}" takes text`);return op==="like"?{like:text4}:{ilike:text4}}case"isNull":if(typeof raw!=="boolean")throw new ViewError('"isNull" takes true or false');return{isNull:raw};case"between":{let[low,high,...extra]=Array.isArray(raw)?raw:[],a=low===void 0?void 0:operandOf(low,ctx),b=high===void 0?void 0:operandOf(high,ctx);if(low===void 0||high===void 0||extra.length>0)throw new ViewError('"between" takes exactly two values');return a===void 0||b===void 0?null:{between:[a,b]}}case"jsonContains":return{jsonContains:raw};case"jsonHasAny":return Array.isArray(raw)&&raw.every((k)=>typeof k==="string")?{jsonHasAny:raw.filter((k)=>typeof k==="string")}:null;case"olderThan":case"newerThan":{let seconds2=isRecord8(raw)?raw.seconds:void 0;if(typeof seconds2!=="number")throw new ViewError(`"${op}" takes { "seconds": number }`);return op==="olderThan"?{olderThan:{seconds:seconds2}}:{newerThan:{seconds:seconds2}}}default:throw new ViewError(`Unknown operator "${op}"`)}}function condOf(value2,ctx){if(!isRecord8(value2)){let scalar2=scalarOf5(value2,ctx);if(scalar2===void 0)throw new ViewError("A condition reads a param that is not set");return scalar2}if(typeof value2.kind==="string")return exprOf(value2,ctx);let{skipWhenNull,...ops}=value2,out={};for(let[op,raw]of Object.entries(ops)){let part=opOf(op,raw,ctx);if(part===null){if(skipWhenNull===!0)return;throw new ViewError(`"${op}" reads a param that is not set; add "skipWhenNull": true`)}Object.assign(out,part)}return out}function whereOf(body,ctx){let out={};for(let[key2,value2]of Object.entries(body))switch(key2){case"and":case"or":{if(!Array.isArray(value2))throw new ViewError(`"${key2}" takes a list of conditions`);out[key2]=value2.map((part)=>isRecord8(part)?whereOf(part,ctx):{});break}case"not":out.not=isRecord8(value2)?whereOf(value2,ctx):{};break;case"exists":{if(!isRecord8(value2)||typeof value2.entity!=="string"||!isRecord8(value2.on))throw new ViewError('"exists" is { "entity", "on", "where" }');let on=Object.fromEntries(Object.entries(value2.on).map(([child,parent])=>[fieldName(child),fieldName(String(parent))]));out.exists={entity:value2.entity,on,where:isRecord8(value2.where)?whereOf(value2.where,ctx):void 0};break}case"tuple":throw new ViewError('"tuple" is not available in a config view');case"$expr":out.$expr=isRecord8(value2)?exprOf(value2,ctx):void 0;break;default:out[fieldName(key2)]=condOf(value2,ctx)}return out}var COLUMN=(name2)=>({kind:"col",field:fieldName(name2)});function operand2(value2,ctx){if(value2===void 0)throw new ViewError("An expression operand is missing");if(typeof value2==="string"){if(value2==="$now"||value2.startsWith(PARAM))return{kind:"lit",value:litOf(value2,ctx)};return COLUMN(value2)}if(isRecord8(value2))return exprOf(value2,ctx);if(Array.isArray(value2))throw new ViewError("A list is not an expression operand");return{kind:"lit",value:value2}}function litOf(value2,ctx){let resolved=reference(value2,ctx);if(resolved===void 0)throw new ViewError(`Expression reads "${value2}", which is not set`);return resolved}function listArg(value2){if(!Array.isArray(value2))throw new ViewError("This expression takes a list");return value2}function canonical(body){if(typeof body.kind==="string")return body;let[only,...rest3]=Object.entries(body);if(only===void 0||rest3.length>0)throw new ViewError('An expression is { "kind": ... } or one function key');let[fn,arg]=only,list3=Array.isArray(arg)?arg:[arg],at=(index)=>list3[index]??null;switch(fn){case"col":return{kind:fn,field:arg};case"lit":return{kind:fn,value:arg};case"now":return{kind:fn,clock:arg};case"lower":case"upper":return{kind:fn,of:arg};case"translate":case"replace":return{kind:fn,of:at(0),from:at(1),to:at(2)};case"concat":return{kind:fn,args:list3};case"concatWs":return{kind:fn,separator:at(0),args:list3.slice(1)};case"add":case"sub":return{kind:fn,left:at(0),right:at(1)};case"diffSeconds":return{kind:fn,later:at(0),earlier:at(1)};case"coalesce":case"least":case"greatest":return{kind:fn,args:list3};case"safeCast":return{kind:fn,of:at(0),to:at(1)};case"round":return{kind:fn,of:at(0),digits:list3[1]??0};case"json":return{kind:fn,source:at(0),path:list3.slice(1)};case"case":return{kind:fn,...isRecord8(arg)?arg:{}};default:throw new ViewError(`Unknown expression function "${fn}"`)}}var CASTS=["text","integer","bigint","numeric","uuid","timestamptz","date"];function exprOf(input,ctx){let body=canonical(input);switch(body.kind){case"col":return COLUMN(String(body.field));case"lit":return{kind:"lit",value:scalarOf5(body.value??null,ctx)??null};case"now":return{kind:"now",clock:body.clock==="clock"?"clock":"tx"};case"lower":case"upper":return{kind:body.kind,of:operand2(body.of,ctx)};case"translate":case"replace":{if(typeof body.from!=="string"||typeof body.to!=="string")throw new ViewError(`"${body.kind}" takes literal text for from and to`);return{kind:body.kind,of:operand2(body.of,ctx),from:body.from,to:body.to}}case"concat":return{kind:"concat",args:listArg(body.args).map((a)=>operand2(a,ctx))};case"concatWs":{if(typeof body.separator!=="string")throw new ViewError('"concatWs" takes a literal text separator');return{kind:"concatWs",separator:body.separator,args:listArg(body.args).map((a)=>operand2(a,ctx))}}case"add":case"sub":return{kind:body.kind,left:operand2(body.left,ctx),right:operand2(body.right,ctx)};case"diffSeconds":return{kind:"diffSeconds",later:operand2(body.later,ctx),earlier:operand2(body.earlier,ctx)};case"coalesce":case"least":case"greatest":return{kind:body.kind,args:listArg(body.args).map((a)=>operand2(a,ctx))};case"safeCast":{let to=CASTS.find((c)=>c===body.to);if(to===void 0)throw new ViewError(`safeCast to "${String(body.to)}" is not supported`);return{kind:"safeCast",of:operand2(body.of,ctx),to}}case"round":return{kind:"round",of:operand2(body.of,ctx),digits:Number(body.digits??0)};case"json":{let path8=listArg(body.path);if(!path8.every((p)=>typeof p==="string"))throw new ViewError("A JSON path is text");return{kind:"json",source:operand2(body.source,ctx),path:path8}}case"case":return{kind:"case",when:listArg(body.when).map((entry)=>{if(!isRecord8(entry)||!isRecord8(entry.if))throw new ViewError('A "case" branch is { "if", "result" }');return{if:whereOf(entry.if,ctx),result:operand2(entry.result,ctx)}}),otherwise:body.otherwise===void 0?null:operand2(body.otherwise,ctx)};default:throw new ViewError(`Unknown or unsupported expression "${String(body.kind)}"`)}}function planJoins(join9){return Object.fromEntries(Object.entries(join9).map(([alias2,j])=>[alias2,{entity:j.entity,from:j.from,on:j.on,kind:j.kind,select:{}}]))}function aggregateOf(){return function(decl){let decls=decl.params??{},isParams=paramsGuard(decls),dimensions=Object.fromEntries(Object.entries(decl.dimensions).map(([alias2,def])=>[alias2,applyOrString(def,isParams)])),measures=Object.fromEntries(Object.entries(decl.measures).map(([alias2,def])=>[alias2,apply(def,isParams)])),outputs=[...Object.keys(dimensions),...Object.keys(measures)],plan={kind:"aggregate",name:decl.name,from:decl.from,join:planJoins(decl.join??{}),dimensions,measures,params:decls,where:apply(decl.where??{},isParams),having:apply(decl.having??{},isParams),filterable:decl.filterable??[],sortable:decl.sortable??[],sort:decl.sort,limit:decl.limit??DEFAULT_VIEW_LIMIT,maxLimit:decl.maxLimit??MAX_VIEW_LIMIT,outputs};if(checkOutputs(plan,!0),Object.keys(measures).length===0)throw new ViewError(`Aggregate view "${decl.name}" needs at least one measure`);return{plan,outputs,filterable:[...decl.filterable??[]],sortable:[...decl.sortable??[]],isRow:rowGuard(outputs),parseParams(input){let values=parseParams(decls,input);if(!isParams(values))throw new ViewError("Parsed params do not match the declaration");return values}}}}function linkOf(name2,on){let links=[];for(let[field2,target2]of Object.entries(on))if(typeof target2==="string")links.push([field2,target2]);let[only,...extra]=links;if(only===void 0||extra.length>0)throw new ViewError(`Child "${name2}": "on" must name exactly one foreign key pair`);return only}function buildChildPlans(parent,parentFields,children2,params,isParams){let plans={};for(let[alias2,decl]of Object.entries(children2)){let name2=`${parent}.${alias2}`,[field2,parentField]=linkOf(name2,decl.on);if(!parentFields.includes(parentField))throw new ViewError(`Child "${name2}": the parent view must select "${parentField}" (the key its children hang off)`);let computed2=Object.fromEntries(Object.entries(decl.computed??{}).map(([out,def])=>[out,apply(def,isParams)])),join9=decl.join??{},outputs=[...decl.select,...Object.values(join9).flatMap((j)=>Object.keys(j.select)),...Object.keys(computed2)],plan={kind:"rows",name:name2,from:decl.entity,select:decl.select,join:join9,computed:computed2,params,where:apply(decl.where??{},isParams),filterable:[],sortable:[],sort:decl.sort,limit:DEFAULT_VIEW_LIMIT,maxLimit:MAX_VIEW_LIMIT,outputs,children:buildChildPlans(name2,decl.select,decl.children??{},params,isParams)};if(checkOutputs({...plan,sort:[]},!0),decl.sort.length===0)throw new ViewError(`Child "${name2}" needs a sort`);plans[alias2]={alias:alias2,field:field2,parentField,plan}}return plans}function computed2(type4,expr,options){return assertNoAggregate(expr),{type:type4,expr,nullable:options?.nullable??!0}}function createViewBuilder(){return{rows(decl){let decls=decl.params??{},isParams=paramsGuard(decls),join9=decl.join??{},computedFns=Object.fromEntries(Object.entries(decl.computed??{}).map(([alias2,def])=>[alias2,apply(def,isParams)])),outputs=[...decl.select,...Object.values(join9).flatMap((j)=>Object.keys(j.select)),...Object.keys(computedFns)],children2=buildChildPlans(decl.name,decl.select,decl.children??{},decls,isParams);for(let alias2 of Object.keys(children2))if(outputs.includes(alias2))throw new ViewError(`View "${decl.name}": child "${alias2}" shares a name with an output`);let plan={kind:"rows",name:decl.name,from:decl.from,select:decl.select,join:join9,computed:computedFns,params:decls,where:apply(decl.where??{},isParams),filterable:decl.filterable??[],sortable:decl.sortable??[],sort:decl.sort,limit:decl.limit??DEFAULT_VIEW_LIMIT,maxLimit:decl.maxLimit??MAX_VIEW_LIMIT,outputs,children:children2};return checkOutputs(plan),{plan,outputs,filterable:[...decl.filterable??[]],sortable:[...decl.sortable??[]],isRow:rowGuard([...outputs,...Object.keys(children2)]),parseParams(input){let values=parseParams(decls,input);if(!isParams(values))throw new ViewError("Parsed params do not match the declaration");return values}}},aggregate:aggregateOf()}}function isStrings(value2){return Array.isArray(value2)}function paramOf(name2,p){let bad=(what)=>new ViewError(`Param "${name2}": ${what}`),optional3=p.optional,value2=p.default;switch(p.type){case"string":if(value2!==void 0&&typeof value2!=="string")throw bad("the default must be text");return{type:"string",enum:p.enum,default:value2,optional:optional3};case"integer":case"number":if(value2!==void 0&&typeof value2!=="number")throw bad("the default must be a number");return{type:p.type,min:p.min,max:p.max,default:value2,optional:optional3};case"boolean":if(value2!==void 0&&typeof value2!=="boolean")throw bad("the default must be true or false");return{type:"boolean",default:value2,optional:optional3};case"date":if(value2!==void 0&&typeof value2!=="string")throw bad("the default must be YYYY-MM-DD");return{type:"date",default:value2,optional:optional3};case"timestamp":{let at=typeof value2==="string"?new Date(value2):void 0;if(value2!==void 0&&(at===void 0||Number.isNaN(at.getTime())))throw bad("the default must be an ISO timestamp");return{type:"timestamp",default:at,optional:optional3}}case"csv":if(value2!==void 0&&!isStrings(value2))throw bad("the default must be a list of text");return{type:"csv",enum:p.enum,default:value2,optional:optional3}}}function paramDeclsOf(params){return Object.fromEntries(Object.entries(params??{}).map(([name2,p])=>[name2,paramOf(name2,p)]))}function joinsOf(joins,withOutputs){let out={};for(let join9 of joins??[]){let alias2=fieldName(join9.as??join9.entity);if(Object.hasOwn(out,alias2))throw new ViewError(`Join "${alias2}" is declared twice`);if(withOutputs&&join9.select===void 0)throw new ViewError(`Join "${alias2}" needs a "select" (output name to joined field)`);out[alias2]={entity:join9.entity,from:join9.from===void 0?void 0:fieldName(join9.from),on:Object.fromEntries(Object.entries(join9.on).map(([a,b])=>[fieldName(a),fieldName(b)])),kind:join9.kind,select:Object.fromEntries(Object.entries(join9.select??{}).map(([output,field2])=>[fieldName(output),fieldName(field2)]))}}return out}function computedOf(map3){return Object.fromEntries(Object.entries(map3??{}).map(([name2,def])=>[fieldName(name2),(params)=>{let ctx={params},expr=exprOf(typeof def.expr==="object"&&def.expr!==null&&!Array.isArray(def.expr)?def.expr:{col:String(def.expr)},ctx);return def.nullable===!1?computed2(def.type,expr,{nullable:!1}):computed2(def.type,expr)}]))}function sortOf(sort){return(sort??[]).map((s)=>({field:fieldName(s.field),direction:s.direction}))}var namesOf=(names3)=>(names3??[]).map(fieldName);function expression(body,params){let ctx={params};if(typeof body==="object"&&body!==null&&!Array.isArray(body))return exprOf(body,ctx);throw new ViewError("An expression is a JSON object")}function timezoneOf(value2,params){if(value2===void 0)return;if(!value2.startsWith("$param."))return lit(value2);let resolved=Reflect.get(params,value2.slice(7));if(typeof resolved!=="string")throw new ViewError(`Timezone "${value2}" is not set`);return lit(resolved)}function dimensionOf(d){if(d.bucket!==void 0){if(d.field===void 0)throw new ViewError(`Dimension "${d.as}": a bucket needs a "field"`);let field2=fieldName(d.field),unit=d.bucket;return(params)=>computed2(unit==="day"?"date":"integer",bucket(field2,unit,{timezone:timezoneOf(d.timezone,params),dayStart:d.day_start}),{nullable:!1})}if(d.expr!==void 0){let type4=d.type;if(type4===void 0)throw new ViewError(`Dimension "${d.as}": an expression needs a "type"`);return(params)=>computed2(type4,expression(d.expr,params))}if(d.field===void 0)throw new ViewError(`Dimension "${d.as}" needs a field, a bucket or an expression`);return fieldName(d.field)}function measureOf(m){return(params)=>{let of=m.expr!==void 0?expression(m.expr,params):m.field===void 0?void 0:fieldName(m.field),filter=m.filter===void 0?void 0:whereOf(m.filter,{params});switch(m.fn){case"count":return measure.count({of,distinct:m.distinct,filter});case"sum":case"avg":{let type4=m.type==="integer"?"integer":"number";if(m.type!==void 0&&m.type!=="integer"&&m.type!=="number")throw new ViewError(`Measure "${m.as}": ${m.fn} is an integer or a number`);if(of===void 0)throw new ViewError(`Measure "${m.as}": ${m.fn} needs a field or an expression`);let options={type:type4,round:m.round,filter};return m.default===void 0?measure[m.fn](of,options):measure[m.fn](of,{...options,default:m.default})}case"min":case"max":if(of===void 0||m.type===void 0)throw new ViewError(`Measure "${m.as}": ${m.fn} needs a field and a "type"`);return measure[m.fn](of,{type:m.type,filter})}}}function buildAggregate(builder,config){let dimensions=Object.fromEntries((config.dimensions??[]).map((d)=>[fieldName(d.as),dimensionOf(d)])),measures=Object.fromEntries((config.measures??[]).map((m)=>[fieldName(m.as),measureOf(m)])),joins=joinsOf(config.join,!1);return builder.aggregate({name:config.name,from:config.from,join:Object.fromEntries(Object.entries(joins).map(([alias2,j])=>[alias2,{entity:j.entity,from:j.from,on:j.on,kind:j.kind}])),params:paramDeclsOf(config.params),dimensions,measures,where:(params)=>whereOf(config.where??{},{params}),having:(params)=>whereOf(config.having??{},{params}),filterable:namesOf(config.filterable),sortable:namesOf(config.sortable),sort:sortOf(config.sort),limit:config.limit,maxLimit:config.max_limit})}var builder=createViewBuilder();function whereFn(body){return(params)=>whereOf(body??{},{params})}function childOf(child){return{entity:child.entity,on:Object.fromEntries(Object.entries(child.on).map(([a,b])=>[fieldName(a),fieldName(b)])),select:namesOf(child.select),join:joinsOf(child.join,!0),computed:computedOf(child.computed),where:whereFn(child.where),sort:sortOf(child.sort),children:childrenOf(child.children)}}function childrenOf(children2){let out={};for(let child of children2??[]){let alias2=fieldName(child.as);if(Object.hasOwn(out,alias2))throw new ViewError(`Child "${alias2}" is declared twice`);out[alias2]=childOf(child)}return out}function buildRows(config){if(config.select===void 0||config.select.length===0)throw new ViewError(`View "${config.name}": a row view needs "select"`);return builder.rows({name:config.name,from:config.from,select:namesOf(config.select),join:joinsOf(config.join,!0),computed:computedOf(config.computed),children:childrenOf(config.children),params:paramDeclsOf(config.params),where:whereFn(config.where),filterable:namesOf(config.filterable),sortable:namesOf(config.sortable),sort:sortOf(config.sort),limit:config.limit,maxLimit:config.max_limit})}function buildConfigView(config){return config.measures===void 0?buildRows(config):buildAggregate(builder,config)}function isViewConfig(entry){return typeof Reflect.get(entry,"name")==="string"&&typeof Reflect.get(entry,"from")==="string"}function viewsOfOptions(resolved){let list3=resolved===null?void 0:Reflect.get(resolved,"views");if(list3===void 0)return[];if(!Array.isArray(list3))throw Error("config.views must be an array of view declarations");return list3.map((entry,index)=>{if(typeof entry!=="object"||entry===null||!isViewConfig(entry))throw Error(`config.views[${index}] needs a "name" and a "from"`);return entry})}function configViewRoutes(configs){let routes=[];for(let config of configs??[]){if(config.path===void 0)continue;routes.push(defineViewRoute({view:buildConfigView(config),path:config.path,public:config.is_public,roles:config.roles,claims:config.claims,tenantFeature:config.tenant_feature,paging:config.paging,scope:config.scope}))}return routes}init_Logger2();var NAME3=/^[A-Za-z][A-Za-z0-9_.-]{0,99}$/,MAX_EVERY_SECONDS=86400;function validate(spec){if(!NAME3.test(spec.name))throw Error(`Job name "${spec.name}" must start with a letter and use letters, digits, ".", "_" or "-"`);if(!Number.isInteger(spec.everySeconds)||spec.everySeconds<1||spec.everySeconds>MAX_EVERY_SECONDS)throw Error(`Job "${spec.name}": everySeconds must be a whole number from 1 to ${MAX_EVERY_SECONDS}`);let first=spec.firstRunAfterSeconds;if(first!==void 0&&(!Number.isFinite(first)||first<0))throw Error(`Job "${spec.name}": firstRunAfterSeconds must be zero or more`)}function defineJobFor(){return function(spec){return validate(spec),{name:spec.name,everySeconds:spec.everySeconds,scope:spec.scope,firstRunAfterSeconds:spec.firstRunAfterSeconds,execute:(options,ctx)=>runUnitOfWork({...options,retry:spec.retry},(unit)=>spec.run(unit,ctx))}}}var defineJob=defineJobFor();var PURGE_EVERY_SECONDS=3600;function purgeJob(name2,scope){return defineJob({name:name2,everySeconds:PURGE_EVERY_SECONDS,scope,run:async(unit,ctx)=>{let removed=await purgeExpiredIdempotencyKeys(executorOf2(unit),ctx.schema);if(removed>0)ctx.logger.info("Expired idempotency keys removed",{schema:ctx.schema,removed});return{handled:removed,failed:0}}})}var IDEMPOTENCY_PURGE_JOBS=[purgeJob("nucleus.purgeIdempotencyKeys","active"),purgeJob("nucleus.purgeIdempotencyKeys.main","main")];import{sql as sql42}from"drizzle-orm";init_Logger2();var systemClock={now:()=>Date.now(),after(delayMs,callback){let timer=setTimeout(callback,delayMs);if(typeof timer==="object"&&typeof timer.unref==="function")timer.unref();return()=>clearTimeout(timer)}};function firstRunDelayMs(job,index){return((job.firstRunAfterSeconds??Math.min(job.everySeconds,20))+index*5)*1000}function nextDelayMs({everySeconds,failures}){let interval=everySeconds*1000;if(failures<=0)return interval;let base=Math.min(30000,interval);return Math.min(base*2**(failures-1),interval*8)}function createJobLoop(options){let{job,clock,log:log4}=options,cancel=null,running=null,active=!1,failures=0;function runNow(){return running??=options.pass().finally(()=>{running=null}),running}function schedule(delayMs){if(!active)return;cancel=clock.after(delayMs,()=>void cycle())}async function cycle(){cancel=null;let failed;try{let report=await runNow();if(failed=report.failed>0,report.skipped)log4.debug("Pass skipped: another replica holds the lock");else if(report.handled>0||report.failed>0)log4.info("Pass finished",{...report})}catch(error3){failed=!0,log4.error("Pass failed",error3)}failures=failed?failures+1:0;let delayMs=nextDelayMs({everySeconds:job.everySeconds,failures});if(failed)log4.warn("Retrying",{inSeconds:delayMs/1000,consecutiveFailures:failures});schedule(delayMs)}return{start(){active=!0,schedule(firstRunDelayMs(job,options.index))},async stop(){active=!1,cancel?.(),cancel=null,await running?.catch(()=>{return})},runNow}}function registrySource(registry5){return{list:()=>(registry5()?.getAllTenants()??[]).map((tenant)=>({id:tenant.id,schema:tenant.schemaName,status:tenant.status}))}}var PROVISIONED=["active","suspended","archived"];function targetsOf(scope,tenants,mainSchema){if(scope==="main")return[{id:null,schema:mainSchema,status:"active"}];let allowed=scope==="provisioned"?PROVISIONED:["active"];return tenants.list().filter((tenant)=>allowed.includes(tenant.status)).sort((a,b)=>a.schema<b.schema?-1:a.schema>b.schema?1:0)}var SKIPPED_PASS={tenants:0,handled:0,failed:0,skipped:!0};async function walkTargets(targets,visit,log4){let handled=0,failed=0;for(let target2 of targets)try{let result=await visit(target2);handled+=result.handled,failed+=result.failed}catch(error3){failed+=1,log4.error("Tenant failed; the others still run",error3,{schema:target2.schema})}return{tenants:targets.length,handled,failed,skipped:!1}}var JOBS_SCOPE="jobs",jobLockKey=(name2)=>`${JOBS_SCOPE}:${name2}`;async function tryJobLock(tx,name2){let result=await tx.execute(sql42`select pg_try_advisory_xact_lock(${advisoryKeyOf(jobLockKey(name2))}) as locked`),[row]=rowsOfResult(result);return row!==void 0&&Reflect.get(row,"locked")===!0}async function runPass(host,job,log4){let scoped2=log4.scoped(`${JOBS_SCOPE}.${job.name}`);return host.db.transaction(async(tx)=>{if(!await tryJobLock(tx,job.name))return SKIPPED_PASS;let targets=targetsOf(job.scope,host.tenants,host.mainSchema);return walkTargets(targets,(target2)=>{let options={db:host.db,schema:target2.schema,mainSchema:host.mainSchema,scope:host.scope??(()=>[]),tables:host.tables,relations:host.relations,logger:scoped2},ctx={job:job.name,schema:target2.schema,tenant:target2,logger:scoped2};return job.execute(options,ctx)},scoped2)})}function createJobRunner(options){let{host}=options,log4=host.logger??logger,clock=options.clock??systemClock,loops=new Map;for(let[index,job]of options.jobs.entries()){if(loops.has(job.name))throw Error(`Two jobs are named "${job.name}"`);loops.set(job.name,createJobLoop({job,index,clock,log:log4.scoped(`${JOBS_SCOPE}.${job.name}`),pass:()=>runPass(host,job,log4)}))}return{names:[...loops.keys()],start(){for(let loop of loops.values())loop.start()},async stop(){await Promise.allSettled([...loops.values()].map((loop)=>loop.stop()))},runNow(name2){let loop=loops.get(name2);if(loop===void 0)return Promise.reject(Error(`No job is named "${name2}"`));return loop.runNow()}}}function actionFlagsOf(resolved){let actions=resolved===null?void 0:Reflect.get(resolved,"actions");if(typeof actions!=="object"||actions===null)return{enabled:!1,purgeExpiredKeys:!0};return{enabled:Reflect.get(actions,"enabled")===!0,purgeExpiredKeys:Reflect.get(actions,"purgeExpiredKeys")!==!1}}function ownPool(data){if(data===void 0)throw Error("createNucleusServer: the job host names no database and nucleus has none to lend. Pass `jobHost: { db, mainSchema }`.");return data.db}function bootJobRunner(input){let jobs=[...input.actions.enabled&&input.actions.purgeExpiredKeys?IDEMPOTENCY_PURGE_JOBS:[],...input.jobs];if(jobs.length===0)return null;let base=input.jobHost??input.actionHost??(input.data===void 0?void 0:{mainSchema:input.data.mainSchema});if(base===void 0){if(input.jobs.length>0)throw Error("createNucleusServer: jobs need a database. Pass `jobHost: { db, mainSchema }` or `actions: { host }`.");return logger.scoped("jobs").warn("actions.enabled is on but no database was given for jobs: expired idempotency keys are not purged"),null}let host={db:base.db??ownPool(input.data),mainSchema:base.mainSchema,scope:input.jobHost?.scope,tables:base.tables,relations:base.relations,logger:base.logger,tenants:registrySource(currentRegistry)};return createJobRunner({host,jobs})}init_response();class BodyParseError extends Error{status=400;constructor(){super("Bad Request");this.name="BodyParseError"}}function looksStructured(value2){return value2.startsWith("{")||value2.startsWith("[")}function assignPath(target2,key2,value2){let steps=key2.replace(/\[(\w*)\]/g,".$1").split(".").filter((step)=>step!=="");if(steps.length<=1){mergeInto(target2,key2,value2);return}let cursor=target2;for(let index=0;index<steps.length-1;index++){let step=steps[index],next=steps[index+1],wanted=/^\d+$/.test(next)?[]:{},holder3=cursor;if(typeof holder3[step]!=="object"||holder3[step]===null)holder3[step]=wanted;cursor=holder3[step]}let last=steps[steps.length-1];if(Array.isArray(cursor))cursor[Number(last)]=value2;else mergeInto(cursor,last,value2)}function mergeInto(target2,key2,value2){if(key2 in target2){let existing=target2[key2];target2[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2];return}target2[key2]=value2}function fromFormData(form){let out={};for(let[key2,value2]of form.entries()){let parsed=value2;if(typeof value2==="string"&&looksStructured(value2))try{parsed=JSON.parse(value2)}catch{parsed=value2}assignPath(out,key2,parsed)}return out}async function parseBody(request,declared){let contentType=request.headers.get("content-type");if(!contentType&&!declared)return;let kind=(contentType?.includes("multipart/form-data")?"formdata":contentType?.includes("application/x-www-form-urlencoded")?"urlencoded":contentType?.includes("application/json")?"json":contentType?.startsWith("text/")?"text":contentType?.includes("octet-stream")?"binary":void 0)??declared;if(!kind)return;if(kind==="formdata")try{return fromFormData(await request.formData())}catch{throw new BodyParseError}if(kind==="urlencoded"){let params=new URLSearchParams(await request.text()),out={};for(let[key2,value2]of params)if(key2 in out){let existing=out[key2];out[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2]}else out[key2]=value2;return out}if(kind==="binary")return await request.arrayBuffer();if(kind==="text")return await request.text();let raw=await request.text();if(raw===""&&!request.body)return;try{return JSON.parse(raw)}catch{throw new BodyParseError}}init_response();init_esm();init_esm();var EMAIL2=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,UUID2=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,DATE_TIME=/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ANNOTATION_ONLY=["binary"],registered=!1;function registerStringFormats(){if(registered)return;registered=!0,exports_format.Set("email",(value2)=>EMAIL2.test(value2)),exports_format.Set("uuid",(value2)=>UUID2.test(value2)),exports_format.Set("date-time",(value2)=>DATE_TIME.test(value2));for(let name2 of ANNOTATION_ONLY)exports_format.Set(name2,()=>!0)}var REGISTERED_FORMATS=["email","uuid","date-time",...ANNOTATION_ONLY];var OPTIONAL_KIND=Symbol.for("TypeBox.Optional"),KIND=Symbol.for("TypeBox.Kind"),cleanable=new WeakMap;function honourOpenObjects(node){if(Array.isArray(node)){let changed2=!1,out2=node.map((entry)=>{let next=honourOpenObjects(entry);if(next!==entry)changed2=!0;return next});return changed2?out2:node}if(node===null||typeof node!=="object")return node;let source=node,isSchema=KIND in source,changed=!1,out={};for(let key2 of Object.keys(source)){let value2=source[key2];if(isSchema&&key2==="additionalProperties"&&value2===!0){out[key2]=Type.Any(),changed=!0;continue}let next=honourOpenObjects(value2);if(next!==value2)changed=!0;out[key2]=next}if(!changed)return node;for(let symbol3 of Object.getOwnPropertySymbols(source))out[symbol3]=source[symbol3];return out}function cleanSchemaFor(schema3){let cached=cleanable.get(schema3);if(cached)return cached;let rewritten=honourOpenObjects(schema3);return cleanable.set(schema3,rewritten),rewritten}function prepare(schema3,value2,on){if(!schema3)return value2;if(value2===void 0&&OPTIONAL_KIND in schema3)return;let prepared=value2;if(on==="query")try{prepared=exports_value2.Convert(schema3,prepared)}catch{}try{prepared=exports_value2.Default(schema3,prepared)}catch{}try{prepared=exports_value2.Clean(cleanSchemaFor(schema3),prepared)}catch{}return prepared}function sampleOf(schema3){try{return exports_value2.Create(schema3)}catch{return}}registerStringFormats();var REQUIRED_PROPERTY=45;function propertyName(path8){return path8.replace(/^\//,"").replace(/\//g,".")}function describe2(value2){if(value2===void 0)return"undefined";if(value2===null)return"null";if(typeof value2==="object")return JSON.stringify(value2);return String(value2)}function at(value2,path8){let current=value2;for(let segment of path8.split("/").filter(Boolean)){if(typeof current!=="object"||current===null)return;current=current[segment]}return current}function validate2(schema3,value2,on){if(!schema3)return null;if(exports_value2.Check(schema3,value2))return null;let all=[...exports_value2.Errors(schema3,value2)],errors2=all.filter((error3)=>error3.type!==REQUIRED_PROPERTY),primary=errors2[0]??all[0],path8=primary?.path??"",message=primary?.message??"Invalid value",atRoot=path8==="";return{isSuccess:!1,success:!1,type:"validation",on,property:atRoot?"root":path8,message,summary:atRoot?message:summarise(path8,message,at(value2,path8)),expected:sampleOf(schema3),found:redact(value2),errors:errors2.map((error3)=>({...error3,value:redact(error3.value),summary:summarise(error3.path,error3.message,at(value2,error3.path))}))}}function describeExpectation(message){return message.replace(/^Expected\s+/i,"")}function redact(value2){if(value2===null)return"null";if(Array.isArray(value2))return`array(${value2.length})`;if(value2 instanceof Date)return"Date";if(typeof value2==="object"){let shape={};for(let key2 of Object.keys(value2))shape[key2]=redact(value2[key2]);return shape}if(value2===void 0)return"undefined";return typeof value2}function summarise(path8,message,found){return`Expected property '${propertyName(path8)}' to be ${describeExpectation(message)} but found: ${describe2(redact(found))}`}class RouteCollisionError extends Error{constructor(method,path8){super(`${method} ${path8} is registered twice. Two groups claiming one path is a wiring mistake, not a fallback: which handler answers would depend on registration order.`);this.name="RouteCollisionError"}}function joinPath2(prefix,path8){if(!prefix)return path8;let left=prefix.endsWith("/")?prefix.slice(0,-1):prefix;if(path8==="/"||path8==="")return left||"/";let right=path8.startsWith("/")?path8:`/${path8}`;return`${left}${right}`||"/"}function buildRoutes(groups,options={}){let table2=new Map;for(let group of groups)for(let route of group.routes){let fullPath=joinPath2(group.prefix,route.path),method=route.method,byMethod=table2.get(fullPath);if(!byMethod)byMethod=new Map,table2.set(fullPath,byMethod);if(byMethod.has(method))throw new RouteCollisionError(method,fullPath);byMethod.set(method,{guards:[...group.guards??[],...route.guards??[]],route})}let out={},withSlashAlias=(path8)=>path8==="/"||path8.endsWith("/")?[path8]:[path8,`${path8}/`];for(let[path8,byMethod]of table2){let handlers={};for(let[method,registered2]of byMethod){handlers[method]=async(request,server)=>{let set2=createResponseSet(),response;try{response=await answer(request,server,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});response=finalizeResponse(answered,set2)}if(options.onAfter)try{set2.status=response.status,await options.onAfter({request,set:set2})}catch(error3){console.error("[router] after-handler failed",error3)}return response};let answer=async(request,server,set2)=>{let url=new URL(request.url),params=request.params??{},query=Object.fromEntries(url.searchParams);if(options.onRequest){let early=await options.onRequest({request,set:set2,body:void 0,params,query,server});if(early!==void 0)return finalizeResponse(early,set2)}let body;try{body=await parseBody(request.clone(),registered2.route.type)}catch(error3){if(error3 instanceof BodyParseError){let bodySchema=registered2.route.body;if(bodySchema&&OPTIONAL_KIND in bodySchema)body=void 0;else return new Response(error3.message,{status:error3.status})}else throw error3}body=prepare(registered2.route.body,body,"body"),query=prepare(registered2.route.query,query,"query"),params=prepare(registered2.route.params,params,"params");for(let[target2,schema3,value2]of[["body",registered2.route.body,body],["query",registered2.route.query,query],["params",registered2.route.params,params]]){if(value2===void 0&&schema3&&OPTIONAL_KIND in schema3)continue;let failure=validate2(schema3,value2,target2);if(failure){let headers=new Headers({"content-type":"application/json"});for(let[name2,value3]of Object.entries(set2.headers))if(value3!==void 0)headers.set(name2,String(value3));return new Response(JSON.stringify(failure,null,2),{status:422,headers})}}let guardContext={request,set:set2,body,params,query,server};if(options.beforeHandle){let early=await options.beforeHandle(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}for(let guard5 of registered2.guards){let early=await guard5(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}try{let result=await registered2.route.handler({...options.context,request,params,query,body,set:set2});return finalizeResponse(result,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}}for(let alias2 of withSlashAlias(path8))out[alias2]=handlers}return out}init_websocket();var NOT_FOUND=()=>new Response("NOT_FOUND",{status:404});async function staticAsset(request,assets){if(!assets)return null;if(request.method!=="GET"&&request.method!=="HEAD")return null;let{pathname}=new URL(request.url),prefix=assets.prefix.endsWith("/")?assets.prefix.slice(0,-1):assets.prefix;if(pathname!==prefix&&!pathname.startsWith(`${prefix}/`))return null;let relative;try{relative=decodeURIComponent(pathname.slice(prefix.length))}catch{return new Response("NOT_FOUND",{status:404})}let{join:join9,resolve:resolve2,sep}=await import("path"),root=resolve2(assets.directory),target2=resolve2(join9(root,relative));if(target2!==root&&!target2.startsWith(root+sep))return new Response("NOT_FOUND",{status:404});let file=Bun.file(target2);if(!await file.exists())return null;return new Response(request.method==="HEAD"?null:file)}function serve(options){let routes=buildRoutes(options.groups,{onRequest:options.onRequest,beforeHandle:options.beforeHandle,onError:options.onError,onAfter:options.onAfter,context:options.context}),notFound=options.notFound??NOT_FOUND,socket=options.socket,server=Bun.serve({port:options.port??0,hostname:options.hostname,idleTimeout:options.idleTimeout??30,reusePort:options.reusePort??!0,...options.maxRequestBodyBytes!==void 0?{maxRequestBodySize:options.maxRequestBodyBytes}:{},routes,fetch:async(request,self2)=>{let asset=await staticAsset(request,options.staticAssets);if(asset)return asset;let set2=createResponseSet();if(options.onRequest){let url=new URL(request.url);try{let early=await options.onRequest({request,set:set2,body:void 0,params:{},query:Object.fromEntries(url.searchParams),server:self2});if(early!==void 0)return finalizeResponse(early,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}if(socket){let upgraded=upgradeFor(socket,request,self2);if(upgraded)return upgraded}let missing=await notFound(request),headers=new Headers(missing.headers);for(let[name2,value2]of Object.entries(set2.headers))if(value2!==void 0&&!headers.has(name2))headers.set(name2,String(value2));let text4=await missing.text();return new Response(text4,{status:missing.status,headers})},websocket:socket?websocketHandlers(socket):void 0}),stopped=!1,runShutdown=async()=>{for(let step of options.onStop??[])try{await step()}catch(error3){console.error("[NucleusServer] shutdown step failed",error3)}},port=server.port??0,hostname=server.hostname??"localhost";return{port,hostname,url:`http://${hostname}:${port}`,stop:(closeActiveConnections=!1)=>{let stopping=Promise.resolve(server.stop(closeActiveConnections));if(stopped)return stopping;return stopped=!0,stopping.then(runShutdown)},raw:server}}function operationIdFor(method,path8){let tail2=path8.split("/").filter(Boolean).flatMap((segment)=>segment.startsWith(":")?["by",segment.slice(1)]:segment.split(/[-_]/)).filter(Boolean).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join("");return`${method.toLowerCase()}${tail2}`}function toOpenApiPath(path8){return path8.split("/").map((segment)=>segment.startsWith(":")?`{${segment.slice(1)}}`:segment).join("/")}function pathParametersOf(path8,schema3){let declared=schema3?.properties;return path8.split("/").filter((segment)=>segment.startsWith(":")).map((segment)=>{let name2=segment.slice(1);return{name:name2,in:"path",required:!0,schema:declared?.[name2]??{type:"string"}}})}function queryParametersOf(schema3){let object3=schema3;if(!object3?.properties)return[];return Object.entries(object3.properties).map(([name2,value2])=>({name:name2,in:"query",required:object3.required?.includes(name2)??!1,schema:value2}))}function buildOpenApiDocument(groups,config={}){let info=config.documentation?.info,exclude3=config.exclude??[],isExcluded=(path8)=>exclude3.some((rule)=>typeof rule==="string"?rule===path8:rule.test(path8)),paths={};for(let group of groups)for(let route of group.routes){let declared=route.path==="/"?"":route.path,joined=`${group.prefix??""}${declared}`||"/";if(isExcluded(joined))continue;let openApiPath=toOpenApiPath(joined),method=route.method.toLowerCase(),detail=route.detail,parameters4=[...pathParametersOf(joined,route.params),...queryParametersOf(route.query)],operation={operationId:operationIdFor(route.method,joined),responses:{"200":{}}};if(detail?.tags)operation.tags=detail.tags;if(detail?.summary)operation.summary=detail.summary;if(detail?.description)operation.description=detail.description;if(parameters4.length>0)operation.parameters=parameters4;if(route.body)operation.requestBody={content:{"application/json":{schema:route.body}}};if(paths[openApiPath]=paths[openApiPath]??{},!paths[openApiPath][method])paths[openApiPath][method]=operation}let document2={openapi:"3.0.3",info:{title:info?.title??"Nucleus API",description:info?.description??"Auto-generated API documentation",version:info?.version??"1.0.0",...info?.contact?{contact:info.contact}:{},...info?.license?{license:info.license}:{}},tags:config.documentation?.tags??[],paths};if(config.documentation?.servers)document2.servers=config.documentation.servers;return document2}function viewerHtml(documentUrl,title,description,viewerConfig){let forHtml=(value2)=>value2.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;"),configuration=viewerConfig&&Object.keys(viewerConfig).length>0?` data-configuration="${forHtml(JSON.stringify(viewerConfig))}"`:"";return`<!doctype html>
632
+ returning id`),removed=rowsOfResult(result).length;if(total+=removed,removed<batch3)break}return total}var defaultEnvelope={success:(data)=>({success:!0,data:data??null}),failure:(failure)=>({success:!1,error:failure.code,message:failure.message,...failure.details===void 0?{}:{details:failure.details}})};function failureOf(error3){if(error3 instanceof ActionError)return{status:error3.status,code:error3.code,message:error3.message,details:error3.details};if(error3 instanceof IdempotencyConflictError)return{status:409,code:"idempotency_key_reused",message:error3.message};if(error3 instanceof ScopeViolationError)return{status:403,code:"scope_violation",message:"This write is outside your scope"};if(error3 instanceof Error){let constraint=toConstraintError(error3);if(constraint!==null)return{status:409,code:"constraint_violation",message:constraint.message,details:{kind:constraint.kind,constraint:constraint.constraint,columns:[...constraint.columns],table:constraint.table}}}if(isRetryable(error3))return{status:409,code:"serialization_failure",message:"The request conflicted with a concurrent one; repeat it"};return null}var ACTION_SCOPE="data.action",DEFAULT_IDEMPOTENCY_HEADER="Idempotency-Key",KEY_MAX_LENGTH=255;function schemaFor(host,action,request){if(action.scope==="main")return host.mainSchema;return host.schemaOf?.(request)??request.headers.get("x-tenant-schema")??host.mainSchema}function idempotencyOf(action,call,actorId){let settings=action.idempotency;if(settings===void 0)return null;let key2=call.request.headers.get(settings.header??DEFAULT_IDEMPOTENCY_HEADER)?.trim();if(key2===void 0||key2==="")return settings.required===!0?{status:400,code:"idempotency_key_required",message:"The Idempotency-Key header is required"}:null;if(key2.length>KEY_MAX_LENGTH)return{status:400,code:"idempotency_key_invalid",message:"The idempotency key is too long"};return{key:key2,action:action.name,actor:actorId??"",payloadHash:payloadHash({body:call.body,query:call.query,params:call.params}),ttlSeconds:settings.ttlSeconds??DEFAULT_IDEMPOTENCY_TTL_SECONDS}}function isFailure(value2){return value2!==null&&"status"in value2}function render(call,envelope,failure){return call.set.status=failure.status,envelope.failure(failure)}async function runAction(host,action,call){let log4=(host.logger??logger).scoped(ACTION_SCOPE),envelope=host.envelope??defaultEnvelope,actor=actorOf2(call.request),schema3=schemaFor(host,action,call.request),claim=idempotencyOf(action,call,actor.id);if(isFailure(claim))return render(call,envelope,claim);let nucleus=call.nucleus,ctx={request:call.request,actor,schema:schema3,set:call.set,nucleus:call.nucleus},db=host.db??nucleusDataOf(nucleus)?.db;if(db===void 0)throw new StoreError(`Action "${action.name}" has no database: the host gave no db and the server is not served by createNucleusServer`);let options={db,schema:schema3,mainSchema:host.mainSchema,scope:host.scopeFor(actor),tables:host.tables,relations:host.relations,logger:log4,retry:action.retry,isolationLevel:action.isolationLevel,readOnly:action.readOnly,notifier:nucleus===null?void 0:(params)=>nucleus.sendNotification(params)};try{let outcome=await runUnitOfWork(options,async(unit)=>{call.set.status=void 0;let keyRowId=null;if(claim!==null){let taken=await claimIdempotencyKey(executorOf2(unit),schema3,claim);if(taken.kind==="replay")return{status:taken.status,body:envelope.success(taken.body),replayed:!0};keyRowId=taken.id}let result=await action.handler({params:call.params,body:call.body,query:call.query},unit,ctx),status=call.set.status??200;if(claim!==null&&keyRowId!==null)await completeIdempotency(executorOf2(unit),schema3,keyRowId,status,result);return{status,body:envelope.success(result),replayed:!1}});if(call.set.status=outcome.status,outcome.replayed)call.set.headers["idempotent-replay"]="true";return outcome.body}catch(error3){let failure=failureOf(error3);if(failure===null)throw error3;return log4.warn("Action refused",{action:action.name,status:failure.status,code:failure.code}),render(call,envelope,failure)}}function accessGuard(spec,host){if(spec.public===!0&&spec.roles===void 0&&spec.claims===void 0)return null;let envelope=host.envelope??defaultEnvelope;return({request,set:set2})=>{let actor=actorOf2(request);if(actor.id===null&&spec.public!==!0)return set2.status=401,envelope.failure({status:401,code:"unauthorized",message:"Sign in first"});if(!actorMaySee(actor,spec))return set2.status=403,envelope.failure({status:403,code:"forbidden",message:"You may not do this"});return}}function defineActionFor(){return function(spec){return{name:spec.name,method:spec.method,path:spec.path,toRoute(host){let guard5=accessGuard(spec,host);return defineRoute({method:spec.method,path:spec.path,isPublic:spec.public,body:spec.body,query:spec.query,params:spec.params,response:spec.response,detail:{summary:spec.name,tags:["Actions"],...spec.detail},guards:guard5===null?[]:[guard5],handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,spec,{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}}var defineAction=defineActionFor();function actionGroup(host,actions){let names3=new Set;for(let action of actions){if(names3.has(action.name))throw Error(`Two actions are named "${action.name}"`);names3.add(action.name)}return{routes:actions.map((action)=>action.toRoute(host))}}function cellOf2(value2){if(value2 instanceof Date)return{d:value2.toISOString()};if(typeof value2==="bigint")return{n:value2.toString()};return value2}function isRecord6(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function scalarOf3(cell){if(!isRecord6(cell)){if(Array.isArray(cell))throw new ViewError("Invalid cursor");return cell}let{d,n}=cell;if(typeof d==="string"){let date4=new Date(d);if(Number.isNaN(date4.getTime()))throw new ViewError("Invalid cursor");return date4}if(typeof n==="string"&&/^-?\d+$/.test(n))return BigInt(n);throw new ViewError("Invalid cursor")}function sortLabel(sort){return sort===void 0?"default":sort.map((s)=>`${s.field}:${s.direction}`).join(",")}function encodeViewCursor(sort,values){let body={s:sortLabel(sort),v:values.map(cellOf2)};return Buffer.from(JSON.stringify(body),"utf8").toString("base64url")}function decodeViewCursor(token,sort){let body;try{body=JSON.parse(Buffer.from(token,"base64url").toString("utf8"))}catch{throw new ViewError("Invalid cursor")}if(!isRecord6(body)||typeof body.s!=="string"||!Array.isArray(body.v))throw new ViewError("Invalid cursor");if(body.s!==sortLabel(sort))throw new ViewError("The cursor was issued for a different sort");return body.v.map(scalarOf3)}function isPlain(value2){return!Array.isArray(value2)&&!(value2 instanceof Date)}function jsonOfValue(value2){if(value2===null||typeof value2==="string"||typeof value2==="boolean")return value2;if(typeof value2==="number")return Number.isFinite(value2)?value2:null;if(typeof value2==="bigint")return value2.toString();if(value2 instanceof Date)return value2.toISOString();if(Array.isArray(value2))return value2.map((item)=>jsonOfValue(item));let out={};if(!isPlain(value2))return out;for(let[key2,item]of Object.entries(value2))if(item!==void 0)out[key2]=jsonOfValue(item);return out}class ViewParamError extends Error{param;constructor(param,message){super(`View parameter "${param}": ${message}`);this.param=param}}var DAY3=/^(\d{4})-(\d{2})-(\d{2})$/;function asText2(name2,raw){if(typeof raw==="string")return raw;if(typeof raw==="number"||typeof raw==="boolean")return String(raw);throw new ViewParamError(name2,"expected text")}function toNumber(name2,raw,decl){let value2=typeof raw==="number"?raw:Number(asText2(name2,raw)),whole=decl.type==="number"||Number.isInteger(value2);if(!Number.isFinite(value2)||!whole)throw new ViewParamError(name2,`expected ${decl.type}`);if(decl.min!==void 0&&value2<decl.min)throw new ViewParamError(name2,`must be at least ${decl.min}`);if(decl.max!==void 0&&value2>decl.max)throw new ViewParamError(name2,`must be at most ${decl.max}`);return value2}function toDay(name2,raw){let text4=asText2(name2,raw),m=DAY3.exec(text4);if(!(m!==null&&new Date(Date.UTC(Number(m[1]),Number(m[2])-1,Number(m[3]))).toISOString().startsWith(text4)))throw new ViewParamError(name2,"expected a calendar day, YYYY-MM-DD");return text4}function toBoolean(name2,raw){if(typeof raw==="boolean")return raw;let text4=asText2(name2,raw);if(text4==="true"||text4==="1")return!0;if(text4==="false"||text4==="0")return!1;throw new ViewParamError(name2,"expected true or false")}function toTimestamp(name2,raw){let date4=raw instanceof Date?raw:new Date(asText2(name2,raw));if(Number.isNaN(date4.getTime()))throw new ViewParamError(name2,"expected a timestamp");return date4}function toList(name2,raw,allowed){let clean2=(Array.isArray(raw)?[...raw]:asText2(name2,raw).split(",")).map((s)=>s.trim()).filter((s)=>s!==""),bad=clean2.find((s)=>allowed!==void 0&&!allowed.includes(s));if(bad!==void 0)throw new ViewParamError(name2,`"${bad}" is not an allowed value`);return clean2}function toText(name2,raw,decl){let text4=asText2(name2,raw);if(decl.enum!==void 0&&!decl.enum.includes(text4))throw new ViewParamError(name2,`"${text4}" is not an allowed value`);return text4}function convert3(name2,raw,decl){switch(decl.type){case"string":return toText(name2,raw,decl);case"integer":case"number":return toNumber(name2,raw,decl);case"boolean":return toBoolean(name2,raw);case"date":return toDay(name2,raw);case"timestamp":return toTimestamp(name2,raw);case"csv":return toList(name2,raw,decl.enum)}}function fresh(value2){return value2 instanceof Date||typeof value2!=="object"?value2:[...value2]}function parseParams(decls,input){for(let name2 of Object.keys(input))if(!Object.hasOwn(decls,name2))throw new ViewParamError(name2,"is not declared by this view");let out={};for(let[name2,decl]of Object.entries(decls)){let raw=input[name2];if(raw===void 0||raw===""){if(decl.default!==void 0)out[name2]=fresh(decl.default);else if(decl.optional!==!0)throw new ViewParamError(name2,"is required");continue}out[name2]=convert3(name2,raw,decl)}return out}init_utils5();var RESERVED_QUERY_NAMES=["page","limit","after","filters","sort"],OPERATORS2=["eq","neq","gt","gte","lt","lte","like","ilike"],LISTS2=["in","notIn"];function isRecord7(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function jsonOf2(name2,text4){try{return JSON.parse(text4)}catch{throw new ViewError(`"${name2}" is not valid JSON`)}}function scalarOf4(name2,value2){if(typeof value2==="string"||typeof value2==="number"||typeof value2==="boolean")return value2;throw new ViewError(`"${name2}": the value must be a string, a number or a boolean`)}function opsOf(entry){let{operator,field:field2}=entry;if(typeof operator!=="string")throw new ViewError('A filter needs an "operator"');let label2=`Filter on "${String(field2)}"`,one=OPERATORS2.find((o)=>o===operator);if(one!==void 0)return{[one]:scalarOf4(label2,entry.value)};let list3=LISTS2.find((o)=>o===operator);if(list3!==void 0){let values=entry.value;if(!Array.isArray(values))throw new ViewError(`${label2}: "${operator}" takes an array`);return{[list3]:values.map((v)=>scalarOf4(label2,v))}}if(operator==="isNull")return{isNull:!0};if(operator==="isNotNull")return{isNull:!1};throw new ViewError(`${label2}: unknown operator "${operator}"`)}function parseFilters(text4){if(text4===void 0||text4==="")return{};let list3=jsonOf2("filters",text4);if(!Array.isArray(list3))throw new ViewError('"filters" must be a JSON array');let out={};for(let entry of list3){if(!isRecord7(entry)||typeof entry.field!=="string")throw new ViewError('A filter is { "field", "operator", "value" }');let ops=opsOf(entry),known=out[entry.field]??{};for(let key2 of Object.keys(ops))if(Object.hasOwn(known,key2))throw new ViewError(`Two "${key2}" filters on "${entry.field}"`);out[entry.field]={...known,...ops}}return out}function directionOf(value2){if(value2==="asc"||value2==="desc")return value2;throw new ViewError('A sort direction is "asc" or "desc"')}function parseSort(text4){if(text4===void 0||text4.trim()==="")return;let trimmed=text4.trim();if(!trimmed.startsWith("["))return trimmed.split(",").map((part)=>{let name2=part.trim(),desc9=name2.startsWith("-"),field2=desc9?name2.slice(1):name2;if(field2==="")throw new ViewError("An empty sort field");return{field:field2,direction:desc9?"desc":"asc"}});let list3=jsonOf2("sort",trimmed);if(!Array.isArray(list3))throw new ViewError('"sort" must be a JSON array');return list3.map((entry)=>{if(!isRecord7(entry)||typeof entry.field!=="string")throw new ViewError('A sort is { "field", "direction" }');return{field:entry.field,direction:directionOf(entry.direction)}})}function positive2(name2,text4,fallback){if(text4===null||text4==="")return fallback;let value2=Number(text4);if(!Number.isInteger(value2)||value2<1)throw new ViewError(`"${name2}" must be a positive integer`);return value2}function parseViewQuery(url){let query=url.searchParams,params={};for(let name2 of new Set(query.keys())){if(RESERVED_QUERY_NAMES.includes(name2))continue;let values=query.getAll(name2);params[name2]=values.length===1&&values[0]!==void 0?values[0]:values}let after=query.get("after")??void 0;if(after!==void 0&&query.has("page"))throw new ViewError('Send "page" or "after", not both');return{params,filters:parseFilters(query.get("filters")??void 0),sort:parseSort(query.get("sort")??void 0),page:positive2("page",query.get("page"),1)??1,limit:positive2("limit",query.get("limit"),void 0),after:after===""?void 0:after}}function refusal(error3){if(error3 instanceof ViewParamError)return new ActionError(422,"invalid_view_params",error3.message,{param:error3.param});return new ActionError(422,"invalid_view_request",error3.message)}function requestOf(view,ctx,paging){let url=new URL(ctx.request.url),query=parseViewQuery(url);if(paging==="cursor"&&url.searchParams.has("page"))throw new ViewError('This view pages with "after", not "page"');let size=query.limit??view.plan.limit,offset=paging==="offset"?(query.page-1)*size:void 0;return{request:{params:view.parseParams(query.params),filters:query.filters,sort:query.sort,limit:query.limit,offset,after:query.after===void 0?void 0:decodeViewCursor(query.after,query.sort)},page:query.page,offset:offset??0,sort:query.sort}}async function runViewCall(view,paging,unit,ctx){try{let{request,page,offset,sort}=requestOf(view,ctx,paging),result=await unit.store.view(view,request),items=result.items.map((row)=>jsonOfValue(row));if(paging==="cursor"){let nextCursor=result.next===null?null:encodeViewCursor(sort,result.next);return{items,meta:{limit:result.limit,hasNextPage:result.hasNextPage,nextCursor}}}let total=await unit.store.countView(view,request);return{items,meta:{...buildPaginationMeta(page,result.limit,offset,total)}}}catch(error3){if(error3 instanceof ViewParamError||error3 instanceof ViewError)throw refusal(error3);throw error3}}function viewClaimOf(name2){return`get.view.${name2}`}function check2(spec){let name2=spec.view.plan.name;if(!spec.path.startsWith("/")||spec.path.includes(":"))throw Error(`View "${name2}": the path must be a literal starting with "/" ("${spec.path}")`);let clash=Object.keys(spec.view.plan.params).find((p)=>RESERVED_QUERY_NAMES.includes(p));if(clash!==void 0)throw Error(`View "${name2}": the param name "${clash}" is reserved by the view route`)}function guardsOf(spec,host){let name2=spec.view.plan.name,claims=spec.roles===void 0&&spec.claims===void 0&&spec.public!==!0?[viewClaimOf(name2)]:spec.claims,access2=accessGuard({public:spec.public,roles:spec.roles,claims},host),guards2=access2===null?[]:[access2];if(spec.tenantFeature!==void 0){let registry5=host.getTenantRegistry;if(registry5===void 0)throw Error(`View "${name2}" declares tenant_feature but the host has no getTenantRegistry`);guards2.push(createTenantFeatureGuard(spec.tenantFeature,()=>registry5.call(host)))}return guards2}function defineViewRoute(spec){check2(spec);let name2=spec.view.plan.name;return{name:name2,path:spec.path,toRoute(host){let paging=spec.paging??"offset";return defineRoute({method:"GET",path:spec.path,isPublic:spec.public,detail:{summary:`View ${name2}`,tags:["Views"],...spec.detail},guards:guardsOf(spec,host),handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,{name:`view.${name2}`,scope:spec.scope,readOnly:!0,handler:(_input,unit,ctx)=>runViewCall(spec.view,paging,unit,ctx)},{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}function viewGroup(host,views){let names3=new Set;for(let view of views){if(names3.has(view.name))throw Error(`Two views are named "${view.name}"`);names3.add(view.name)}return{routes:views.map((view)=>view.toRoute(host))}}var PARAM="$param.";function fieldName(name2){return(name2.startsWith("$dim.")?name2.slice(5):name2).split(".").map(snakeToCamel).join(".")}function isRecord8(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function readParam(ctx,name2){let value2=Reflect.get(ctx.params,name2);if(value2===void 0||value2 instanceof Date)return value2;if(typeof value2==="string"||typeof value2==="number"||typeof value2==="boolean")return value2;if(Array.isArray(value2)&&value2.every((v)=>typeof v==="string"))return value2;throw new ViewError(`Param "${name2}" has a value no filter can use`)}function reference(value2,ctx){if(value2==="$now")return new Date;return value2.startsWith(PARAM)?readParam(ctx,value2.slice(PARAM.length)):value2}function scalarOf5(value2,ctx){let resolved=typeof value2==="string"?reference(value2,ctx):value2;if(resolved===void 0)return;if(Array.isArray(resolved)||typeof resolved==="object"&&!(resolved instanceof Date)&&resolved!==null)throw new ViewError("A list or object is not a single value here");return resolved}function listOf3(value2,ctx){let resolved=typeof value2==="string"?reference(value2,ctx):value2;if(resolved===void 0)return;if(!Array.isArray(resolved))throw new ViewError('"in" and "notIn" take a list');let items=resolved.map((item)=>typeof item==="object"&&item!==null?void 0:scalarOf5(item,ctx));if(items.includes(void 0))throw new ViewError("A list item reads a param that is not set");return items.filter((item)=>item!==void 0)}function operandOf(raw,ctx){return isRecord8(raw)?exprOf(raw,ctx):scalarOf5(raw,ctx)}var SINGLE={eq:(eq84)=>({eq:eq84}),neq:(neq)=>({neq}),gt:(gt2)=>({gt:gt2}),gte:(gte2)=>({gte:gte2}),lt:(lt4)=>({lt:lt4}),lte:(lte2)=>({lte:lte2})};function opOf(op,raw,ctx){let single=SINGLE[op];if(single!==void 0){let value2=operandOf(raw,ctx);return value2===void 0?null:single(value2)}switch(op){case"in":case"notIn":{let list3=isRecord8(raw)?exprOf(raw,ctx):listOf3(raw,ctx);if(list3===void 0)return null;return op==="in"?{in:list3}:{notIn:list3}}case"like":case"ilike":{let text4=scalarOf5(raw,ctx);if(text4===void 0)return null;if(typeof text4!=="string")throw new ViewError(`"${op}" takes text`);return op==="like"?{like:text4}:{ilike:text4}}case"isNull":if(typeof raw!=="boolean")throw new ViewError('"isNull" takes true or false');return{isNull:raw};case"between":{let[low,high,...extra]=Array.isArray(raw)?raw:[],a=low===void 0?void 0:operandOf(low,ctx),b=high===void 0?void 0:operandOf(high,ctx);if(low===void 0||high===void 0||extra.length>0)throw new ViewError('"between" takes exactly two values');return a===void 0||b===void 0?null:{between:[a,b]}}case"jsonContains":return{jsonContains:raw};case"jsonHasAny":return Array.isArray(raw)&&raw.every((k)=>typeof k==="string")?{jsonHasAny:raw.filter((k)=>typeof k==="string")}:null;case"olderThan":case"newerThan":{let seconds2=isRecord8(raw)?raw.seconds:void 0;if(typeof seconds2!=="number")throw new ViewError(`"${op}" takes { "seconds": number }`);return op==="olderThan"?{olderThan:{seconds:seconds2}}:{newerThan:{seconds:seconds2}}}default:throw new ViewError(`Unknown operator "${op}"`)}}function condOf(value2,ctx){if(!isRecord8(value2)){let scalar2=scalarOf5(value2,ctx);if(scalar2===void 0)throw new ViewError("A condition reads a param that is not set");return scalar2}if(typeof value2.kind==="string")return exprOf(value2,ctx);let{skipWhenNull,...ops}=value2,out={};for(let[op,raw]of Object.entries(ops)){let part=opOf(op,raw,ctx);if(part===null){if(skipWhenNull===!0)return;throw new ViewError(`"${op}" reads a param that is not set; add "skipWhenNull": true`)}Object.assign(out,part)}return out}function whereOf(body,ctx){let out={};for(let[key2,value2]of Object.entries(body))switch(key2){case"and":case"or":{if(!Array.isArray(value2))throw new ViewError(`"${key2}" takes a list of conditions`);out[key2]=value2.map((part)=>isRecord8(part)?whereOf(part,ctx):{});break}case"not":out.not=isRecord8(value2)?whereOf(value2,ctx):{};break;case"exists":{if(!isRecord8(value2)||typeof value2.entity!=="string"||!isRecord8(value2.on))throw new ViewError('"exists" is { "entity", "on", "where" }');let on=Object.fromEntries(Object.entries(value2.on).map(([child,parent])=>[fieldName(child),fieldName(String(parent))]));out.exists={entity:value2.entity,on,where:isRecord8(value2.where)?whereOf(value2.where,ctx):void 0};break}case"tuple":throw new ViewError('"tuple" is not available in a config view');case"$expr":out.$expr=isRecord8(value2)?exprOf(value2,ctx):void 0;break;default:out[fieldName(key2)]=condOf(value2,ctx)}return out}var COLUMN=(name2)=>({kind:"col",field:fieldName(name2)});function operand2(value2,ctx){if(value2===void 0)throw new ViewError("An expression operand is missing");if(typeof value2==="string"){if(value2==="$now"||value2.startsWith(PARAM))return{kind:"lit",value:litOf(value2,ctx)};return COLUMN(value2)}if(isRecord8(value2))return exprOf(value2,ctx);if(Array.isArray(value2))throw new ViewError("A list is not an expression operand");return{kind:"lit",value:value2}}function litOf(value2,ctx){let resolved=reference(value2,ctx);if(resolved===void 0)throw new ViewError(`Expression reads "${value2}", which is not set`);return resolved}function listArg(value2){if(!Array.isArray(value2))throw new ViewError("This expression takes a list");return value2}function canonical(body){if(typeof body.kind==="string")return body;let[only,...rest3]=Object.entries(body);if(only===void 0||rest3.length>0)throw new ViewError('An expression is { "kind": ... } or one function key');let[fn,arg]=only,list3=Array.isArray(arg)?arg:[arg],at=(index)=>list3[index]??null;switch(fn){case"col":return{kind:fn,field:arg};case"lit":return{kind:fn,value:arg};case"now":return{kind:fn,clock:arg};case"lower":case"upper":return{kind:fn,of:arg};case"translate":case"replace":return{kind:fn,of:at(0),from:at(1),to:at(2)};case"concat":return{kind:fn,args:list3};case"concatWs":return{kind:fn,separator:at(0),args:list3.slice(1)};case"add":case"sub":return{kind:fn,left:at(0),right:at(1)};case"diffSeconds":return{kind:fn,later:at(0),earlier:at(1)};case"coalesce":case"least":case"greatest":return{kind:fn,args:list3};case"safeCast":return{kind:fn,of:at(0),to:at(1)};case"round":return{kind:fn,of:at(0),digits:list3[1]??0};case"json":return{kind:fn,source:at(0),path:list3.slice(1)};case"case":return{kind:fn,...isRecord8(arg)?arg:{}};default:throw new ViewError(`Unknown expression function "${fn}"`)}}var CASTS=["text","integer","bigint","numeric","uuid","timestamptz","date"];function exprOf(input,ctx){let body=canonical(input);switch(body.kind){case"col":return COLUMN(String(body.field));case"lit":return{kind:"lit",value:scalarOf5(body.value??null,ctx)??null};case"now":return{kind:"now",clock:body.clock==="clock"?"clock":"tx"};case"lower":case"upper":return{kind:body.kind,of:operand2(body.of,ctx)};case"translate":case"replace":{if(typeof body.from!=="string"||typeof body.to!=="string")throw new ViewError(`"${body.kind}" takes literal text for from and to`);return{kind:body.kind,of:operand2(body.of,ctx),from:body.from,to:body.to}}case"concat":return{kind:"concat",args:listArg(body.args).map((a)=>operand2(a,ctx))};case"concatWs":{if(typeof body.separator!=="string")throw new ViewError('"concatWs" takes a literal text separator');return{kind:"concatWs",separator:body.separator,args:listArg(body.args).map((a)=>operand2(a,ctx))}}case"add":case"sub":return{kind:body.kind,left:operand2(body.left,ctx),right:operand2(body.right,ctx)};case"diffSeconds":return{kind:"diffSeconds",later:operand2(body.later,ctx),earlier:operand2(body.earlier,ctx)};case"coalesce":case"least":case"greatest":return{kind:body.kind,args:listArg(body.args).map((a)=>operand2(a,ctx))};case"safeCast":{let to=CASTS.find((c)=>c===body.to);if(to===void 0)throw new ViewError(`safeCast to "${String(body.to)}" is not supported`);return{kind:"safeCast",of:operand2(body.of,ctx),to}}case"round":return{kind:"round",of:operand2(body.of,ctx),digits:Number(body.digits??0)};case"json":{let path8=listArg(body.path);if(!path8.every((p)=>typeof p==="string"))throw new ViewError("A JSON path is text");return{kind:"json",source:operand2(body.source,ctx),path:path8}}case"case":return{kind:"case",when:listArg(body.when).map((entry)=>{if(!isRecord8(entry)||!isRecord8(entry.if))throw new ViewError('A "case" branch is { "if", "result" }');return{if:whereOf(entry.if,ctx),result:operand2(entry.result,ctx)}}),otherwise:body.otherwise===void 0?null:operand2(body.otherwise,ctx)};default:throw new ViewError(`Unknown or unsupported expression "${String(body.kind)}"`)}}function planJoins(join9){return Object.fromEntries(Object.entries(join9).map(([alias2,j])=>[alias2,{entity:j.entity,from:j.from,on:j.on,kind:j.kind,select:{}}]))}function aggregateOf(){return function(decl){let decls=decl.params??{},isParams=paramsGuard(decls),dimensions=Object.fromEntries(Object.entries(decl.dimensions).map(([alias2,def])=>[alias2,applyOrString(def,isParams)])),measures=Object.fromEntries(Object.entries(decl.measures).map(([alias2,def])=>[alias2,apply(def,isParams)])),outputs=[...Object.keys(dimensions),...Object.keys(measures)],plan={kind:"aggregate",name:decl.name,from:decl.from,join:planJoins(decl.join??{}),dimensions,measures,params:decls,where:apply(decl.where??{},isParams),having:apply(decl.having??{},isParams),filterable:decl.filterable??[],sortable:decl.sortable??[],sort:decl.sort,limit:decl.limit??DEFAULT_VIEW_LIMIT,maxLimit:decl.maxLimit??MAX_VIEW_LIMIT,outputs};if(checkOutputs(plan,!0),Object.keys(measures).length===0)throw new ViewError(`Aggregate view "${decl.name}" needs at least one measure`);return{plan,outputs,filterable:[...decl.filterable??[]],sortable:[...decl.sortable??[]],isRow:rowGuard(outputs),parseParams(input){let values=parseParams(decls,input);if(!isParams(values))throw new ViewError("Parsed params do not match the declaration");return values}}}}function linkOf(name2,on){let links=[];for(let[field2,target2]of Object.entries(on))if(typeof target2==="string")links.push([field2,target2]);let[only,...extra]=links;if(only===void 0||extra.length>0)throw new ViewError(`Child "${name2}": "on" must name exactly one foreign key pair`);return only}function buildChildPlans(parent,parentFields,children2,params,isParams){let plans={};for(let[alias2,decl]of Object.entries(children2)){let name2=`${parent}.${alias2}`,[field2,parentField]=linkOf(name2,decl.on);if(!parentFields.includes(parentField))throw new ViewError(`Child "${name2}": the parent view must select "${parentField}" (the key its children hang off)`);let computed2=Object.fromEntries(Object.entries(decl.computed??{}).map(([out,def])=>[out,apply(def,isParams)])),join9=decl.join??{},outputs=[...decl.select,...Object.values(join9).flatMap((j)=>Object.keys(j.select)),...Object.keys(computed2)],plan={kind:"rows",name:name2,from:decl.entity,select:decl.select,join:join9,computed:computed2,params,where:apply(decl.where??{},isParams),filterable:[],sortable:[],sort:decl.sort,limit:DEFAULT_VIEW_LIMIT,maxLimit:MAX_VIEW_LIMIT,outputs,children:buildChildPlans(name2,decl.select,decl.children??{},params,isParams)};if(checkOutputs({...plan,sort:[]},!0),decl.sort.length===0)throw new ViewError(`Child "${name2}" needs a sort`);plans[alias2]={alias:alias2,field:field2,parentField,plan}}return plans}function computed2(type4,expr,options){return assertNoAggregate(expr),{type:type4,expr,nullable:options?.nullable??!0}}function createViewBuilder(){return{rows(decl){let decls=decl.params??{},isParams=paramsGuard(decls),join9=decl.join??{},computedFns=Object.fromEntries(Object.entries(decl.computed??{}).map(([alias2,def])=>[alias2,apply(def,isParams)])),outputs=[...decl.select,...Object.values(join9).flatMap((j)=>Object.keys(j.select)),...Object.keys(computedFns)],children2=buildChildPlans(decl.name,decl.select,decl.children??{},decls,isParams);for(let alias2 of Object.keys(children2))if(outputs.includes(alias2))throw new ViewError(`View "${decl.name}": child "${alias2}" shares a name with an output`);let plan={kind:"rows",name:decl.name,from:decl.from,select:decl.select,join:join9,computed:computedFns,params:decls,where:apply(decl.where??{},isParams),filterable:decl.filterable??[],sortable:decl.sortable??[],sort:decl.sort,limit:decl.limit??DEFAULT_VIEW_LIMIT,maxLimit:decl.maxLimit??MAX_VIEW_LIMIT,outputs,children:children2};return checkOutputs(plan),{plan,outputs,filterable:[...decl.filterable??[]],sortable:[...decl.sortable??[]],isRow:rowGuard([...outputs,...Object.keys(children2)]),parseParams(input){let values=parseParams(decls,input);if(!isParams(values))throw new ViewError("Parsed params do not match the declaration");return values}}},aggregate:aggregateOf()}}function isStrings(value2){return Array.isArray(value2)}function paramOf(name2,p){let bad=(what)=>new ViewError(`Param "${name2}": ${what}`),optional3=p.optional,value2=p.default;switch(p.type){case"string":if(value2!==void 0&&typeof value2!=="string")throw bad("the default must be text");return{type:"string",enum:p.enum,default:value2,optional:optional3};case"integer":case"number":if(value2!==void 0&&typeof value2!=="number")throw bad("the default must be a number");return{type:p.type,min:p.min,max:p.max,default:value2,optional:optional3};case"boolean":if(value2!==void 0&&typeof value2!=="boolean")throw bad("the default must be true or false");return{type:"boolean",default:value2,optional:optional3};case"date":if(value2!==void 0&&typeof value2!=="string")throw bad("the default must be YYYY-MM-DD");return{type:"date",default:value2,optional:optional3};case"timestamp":{let at=typeof value2==="string"?new Date(value2):void 0;if(value2!==void 0&&(at===void 0||Number.isNaN(at.getTime())))throw bad("the default must be an ISO timestamp");return{type:"timestamp",default:at,optional:optional3}}case"csv":if(value2!==void 0&&!isStrings(value2))throw bad("the default must be a list of text");return{type:"csv",enum:p.enum,default:value2,optional:optional3}}}function paramDeclsOf(params){return Object.fromEntries(Object.entries(params??{}).map(([name2,p])=>[name2,paramOf(name2,p)]))}function joinsOf(joins,withOutputs){let out={};for(let join9 of joins??[]){let alias2=fieldName(join9.as??join9.entity);if(Object.hasOwn(out,alias2))throw new ViewError(`Join "${alias2}" is declared twice`);if(withOutputs&&join9.select===void 0)throw new ViewError(`Join "${alias2}" needs a "select" (output name to joined field)`);out[alias2]={entity:join9.entity,from:join9.from===void 0?void 0:fieldName(join9.from),on:Object.fromEntries(Object.entries(join9.on).map(([a,b])=>[fieldName(a),fieldName(b)])),kind:join9.kind,select:Object.fromEntries(Object.entries(join9.select??{}).map(([output,field2])=>[fieldName(output),fieldName(field2)]))}}return out}function computedOf(map3){return Object.fromEntries(Object.entries(map3??{}).map(([name2,def])=>[fieldName(name2),(params)=>{let ctx={params},expr=exprOf(typeof def.expr==="object"&&def.expr!==null&&!Array.isArray(def.expr)?def.expr:{col:String(def.expr)},ctx);return def.nullable===!1?computed2(def.type,expr,{nullable:!1}):computed2(def.type,expr)}]))}function sortOf(sort){return(sort??[]).map((s)=>({field:fieldName(s.field),direction:s.direction}))}var namesOf=(names3)=>(names3??[]).map(fieldName);function expression(body,params){let ctx={params};if(typeof body==="object"&&body!==null&&!Array.isArray(body))return exprOf(body,ctx);throw new ViewError("An expression is a JSON object")}function timezoneOf(value2,params){if(value2===void 0)return;if(!value2.startsWith("$param."))return lit(value2);let resolved=Reflect.get(params,value2.slice(7));if(typeof resolved!=="string")throw new ViewError(`Timezone "${value2}" is not set`);return lit(resolved)}function dimensionOf(d){if(d.bucket!==void 0){if(d.field===void 0)throw new ViewError(`Dimension "${d.as}": a bucket needs a "field"`);let field2=fieldName(d.field),unit=d.bucket;return(params)=>computed2(unit==="day"?"date":"integer",bucket(field2,unit,{timezone:timezoneOf(d.timezone,params),dayStart:d.day_start}),{nullable:!1})}if(d.expr!==void 0){let type4=d.type;if(type4===void 0)throw new ViewError(`Dimension "${d.as}": an expression needs a "type"`);return(params)=>computed2(type4,expression(d.expr,params))}if(d.field===void 0)throw new ViewError(`Dimension "${d.as}" needs a field, a bucket or an expression`);return fieldName(d.field)}function measureOf(m){return(params)=>{let of=m.expr!==void 0?expression(m.expr,params):m.field===void 0?void 0:fieldName(m.field),filter=m.filter===void 0?void 0:whereOf(m.filter,{params});switch(m.fn){case"count":return measure.count({of,distinct:m.distinct,filter});case"sum":case"avg":{let type4=m.type==="integer"?"integer":"number";if(m.type!==void 0&&m.type!=="integer"&&m.type!=="number")throw new ViewError(`Measure "${m.as}": ${m.fn} is an integer or a number`);if(of===void 0)throw new ViewError(`Measure "${m.as}": ${m.fn} needs a field or an expression`);let options={type:type4,round:m.round,filter};return m.default===void 0?measure[m.fn](of,options):measure[m.fn](of,{...options,default:m.default})}case"min":case"max":if(of===void 0||m.type===void 0)throw new ViewError(`Measure "${m.as}": ${m.fn} needs a field and a "type"`);return measure[m.fn](of,{type:m.type,filter})}}}function buildAggregate(builder,config){let dimensions=Object.fromEntries((config.dimensions??[]).map((d)=>[fieldName(d.as),dimensionOf(d)])),measures=Object.fromEntries((config.measures??[]).map((m)=>[fieldName(m.as),measureOf(m)])),joins=joinsOf(config.join,!1);return builder.aggregate({name:config.name,from:config.from,join:Object.fromEntries(Object.entries(joins).map(([alias2,j])=>[alias2,{entity:j.entity,from:j.from,on:j.on,kind:j.kind}])),params:paramDeclsOf(config.params),dimensions,measures,where:(params)=>whereOf(config.where??{},{params}),having:(params)=>whereOf(config.having??{},{params}),filterable:namesOf(config.filterable),sortable:namesOf(config.sortable),sort:sortOf(config.sort),limit:config.limit,maxLimit:config.max_limit})}var builder=createViewBuilder();function whereFn(body){return(params)=>whereOf(body??{},{params})}function childOf(child){return{entity:child.entity,on:Object.fromEntries(Object.entries(child.on).map(([a,b])=>[fieldName(a),fieldName(b)])),select:namesOf(child.select),join:joinsOf(child.join,!0),computed:computedOf(child.computed),where:whereFn(child.where),sort:sortOf(child.sort),children:childrenOf(child.children)}}function childrenOf(children2){let out={};for(let child of children2??[]){let alias2=fieldName(child.as);if(Object.hasOwn(out,alias2))throw new ViewError(`Child "${alias2}" is declared twice`);out[alias2]=childOf(child)}return out}function buildRows(config){if(config.select===void 0||config.select.length===0)throw new ViewError(`View "${config.name}": a row view needs "select"`);return builder.rows({name:config.name,from:config.from,select:namesOf(config.select),join:joinsOf(config.join,!0),computed:computedOf(config.computed),children:childrenOf(config.children),params:paramDeclsOf(config.params),where:whereFn(config.where),filterable:namesOf(config.filterable),sortable:namesOf(config.sortable),sort:sortOf(config.sort),limit:config.limit,maxLimit:config.max_limit})}function buildConfigView(config){return config.measures===void 0?buildRows(config):buildAggregate(builder,config)}function isViewConfig(entry){return typeof Reflect.get(entry,"name")==="string"&&typeof Reflect.get(entry,"from")==="string"}function viewsOfOptions(resolved){let list3=resolved===null?void 0:Reflect.get(resolved,"views");if(list3===void 0)return[];if(!Array.isArray(list3))throw Error("config.views must be an array of view declarations");return list3.map((entry,index)=>{if(typeof entry!=="object"||entry===null||!isViewConfig(entry))throw Error(`config.views[${index}] needs a "name" and a "from"`);return entry})}function configViewRoutes(configs){let routes=[];for(let config of configs??[]){if(config.path===void 0)continue;routes.push(defineViewRoute({view:buildConfigView(config),path:config.path,public:config.is_public,roles:config.roles,claims:config.claims,tenantFeature:config.tenant_feature,paging:config.paging,scope:config.scope}))}return routes}init_Logger2();var JOBS_SCOPE="jobs",jobLockKey=(name2)=>`jobs:${name2}`;var JOB_LOCKED={locked:!0},NAME3=/^[A-Za-z][A-Za-z0-9_.-]{0,99}$/,MAX_EVERY_SECONDS=86400;function validate(spec){if(!NAME3.test(spec.name))throw Error(`Job name "${spec.name}" must start with a letter and use letters, digits, ".", "_" or "-"`);if(!Number.isInteger(spec.everySeconds)||spec.everySeconds<1||spec.everySeconds>MAX_EVERY_SECONDS)throw Error(`Job "${spec.name}": everySeconds must be a whole number from 1 to ${MAX_EVERY_SECONDS}`);let first=spec.firstRunAfterSeconds;if(first!==void 0&&(!Number.isFinite(first)||first<0))throw Error(`Job "${spec.name}": firstRunAfterSeconds must be zero or more`)}function defineJobFor(){return function(spec){return validate(spec),{name:spec.name,everySeconds:spec.everySeconds,scope:spec.scope,firstRunAfterSeconds:spec.firstRunAfterSeconds,execute:(options,ctx,run)=>run({...options,retry:spec.retry},async(unit)=>{if(!await unit.lock.tryAdvisory(jobLockKey(spec.name)))return JOB_LOCKED;return spec.run(unit,ctx)})}}}var defineJob=defineJobFor();var PURGE_EVERY_SECONDS=3600;function purgeJob(name2,scope){return defineJob({name:name2,everySeconds:PURGE_EVERY_SECONDS,scope,run:async(unit,ctx)=>{let removed=await purgeExpiredIdempotencyKeys(executorOf2(unit),ctx.schema);if(removed>0)ctx.logger.info("Expired idempotency keys removed",{schema:ctx.schema,removed});return{handled:removed,failed:0}}})}var IDEMPOTENCY_PURGE_JOBS=[purgeJob("nucleus.purgeIdempotencyKeys","active"),purgeJob("nucleus.purgeIdempotencyKeys.main","main")];init_Logger2();var systemClock={now:()=>Date.now(),after(delayMs,callback){let timer=setTimeout(callback,delayMs);if(typeof timer==="object"&&typeof timer.unref==="function")timer.unref();return()=>clearTimeout(timer)}};function firstRunDelayMs(job,index){return((job.firstRunAfterSeconds??Math.min(job.everySeconds,20))+index*5)*1000}function nextDelayMs({everySeconds,failures}){let interval=everySeconds*1000;if(failures<=0)return interval;let base=Math.min(30000,interval);return Math.min(base*2**(failures-1),interval*8)}function createJobLoop(options){let{job,clock,log:log4}=options,cancel=null,running=null,active=!1,failures=0;function runNow(){return running??=options.pass().finally(()=>{running=null}),running}function schedule(delayMs){if(!active)return;cancel=clock.after(delayMs,()=>void cycle())}async function cycle(){cancel=null;let failed;try{let report=await runNow();if(failed=report.failed>0,report.skipped)log4.debug("Pass skipped: another replica holds the lock");else if(report.handled>0||report.failed>0)log4.info("Pass finished",{...report})}catch(error3){failed=!0,log4.error("Pass failed",error3)}failures=failed?failures+1:0;let delayMs=nextDelayMs({everySeconds:job.everySeconds,failures});if(failed)log4.warn("Retrying",{inSeconds:delayMs/1000,consecutiveFailures:failures});schedule(delayMs)}return{start(){active=!0,schedule(firstRunDelayMs(job,options.index))},async stop(){active=!1,cancel?.(),cancel=null,await running?.catch(()=>{return})},runNow}}var DEFAULT_MAX_CONCURRENT_PASSES=1;function createJobSlots(size){if(!Number.isInteger(size)||size<1)throw Error("jobs.maxConcurrentPasses must be a whole number of 1 or more");let busy=0,closed=!1,waiting=[];return{get busy(){return busy},acquire(){if(closed)return Promise.resolve(!1);if(busy<size)return busy+=1,Promise.resolve(!0);return new Promise((resolve2)=>waiting.push(resolve2))},release(){let next=waiting.shift();if(next!==void 0)next(!0);else busy-=1},close(){closed=!0;for(let resolve2 of waiting.splice(0))resolve2(!1)}}}function registrySource(registry5){return{list:()=>(registry5()?.getAllTenants()??[]).map((tenant)=>({id:tenant.id,schema:tenant.schemaName,status:tenant.status}))}}var PROVISIONED=["active","suspended","archived"];function targetsOf(scope,tenants,mainSchema){if(scope==="main")return[{id:null,schema:mainSchema,status:"active"}];let allowed=scope==="provisioned"?PROVISIONED:["active"];return tenants.list().filter((tenant)=>allowed.includes(tenant.status)).sort((a,b)=>a.schema<b.schema?-1:a.schema>b.schema?1:0)}var SKIPPED_PASS={tenants:0,handled:0,failed:0,skipped:!0};async function walkTargets(targets,visit,log4){let handled=0,failed=0,visited2=0;for(let target2 of targets)try{let result=await visit(target2);if("locked"in result){if(visited2===0)return SKIPPED_PASS;log4.debug("Another replica took over the job; this pass stops here",{schema:target2.schema});break}visited2+=1,handled+=result.handled,failed+=result.failed}catch(error3){visited2+=1,failed+=1,log4.error("Tenant failed; the others still run",error3,{schema:target2.schema})}return{tenants:visited2,handled,failed,skipped:!1}}async function runPass(host,job,log4){let scoped2=log4.scoped(`${JOBS_SCOPE}.${job.name}`),targets=targetsOf(job.scope,host.tenants,host.mainSchema);return walkTargets(targets,(target2)=>{let options={schema:target2.schema,mainSchema:host.mainSchema,scope:host.scope??(()=>[]),tables:host.tables,relations:host.relations,logger:scoped2},ctx={job:job.name,schema:target2.schema,tenant:target2,logger:scoped2};return job.execute(options,ctx,unitRunnerOf(host))},scoped2)}function unitRunnerOf(host){if(host.runUnit!==void 0)return host.runUnit;return(options,work)=>runUnitOfWork({...options,db:host.db,mainSchema:options.mainSchema??host.mainSchema},work)}async function runInSlot(slots,pass,skippedPass){if(!await slots.acquire())return skippedPass;try{return await pass()}finally{slots.release()}}function createJobRunner(options){let{host}=options,log4=host.logger??logger,clock=options.clock??systemClock,slots=createJobSlots(host.maxConcurrentPasses??DEFAULT_MAX_CONCURRENT_PASSES),loops=new Map;for(let[index,job]of options.jobs.entries()){if(loops.has(job.name))throw Error(`Two jobs are named "${job.name}"`);loops.set(job.name,createJobLoop({job,index,clock,log:log4.scoped(`${JOBS_SCOPE}.${job.name}`),pass:()=>runInSlot(slots,()=>runPass(host,job,log4),SKIPPED_PASS)}))}return{names:[...loops.keys()],start(){for(let loop of loops.values())loop.start()},async stop(){slots.close(),await Promise.allSettled([...loops.values()].map((loop)=>loop.stop()))},runNow(name2){let loop=loops.get(name2);if(loop===void 0)return Promise.reject(Error(`No job is named "${name2}"`));return loop.runNow()}}}function actionFlagsOf(resolved){let actions=resolved===null?void 0:Reflect.get(resolved,"actions");if(typeof actions!=="object"||actions===null)return{enabled:!1,purgeExpiredKeys:!0};return{enabled:Reflect.get(actions,"enabled")===!0,purgeExpiredKeys:Reflect.get(actions,"purgeExpiredKeys")!==!1}}function ownPool(data){if(data===void 0)throw Error("createNucleusServer: the job host names no database and nucleus has none to lend. Pass `jobHost: { db, mainSchema }`.");return data.db}function bootJobRunner(input){let jobs=[...input.actions.enabled&&input.actions.purgeExpiredKeys?IDEMPOTENCY_PURGE_JOBS:[],...input.jobs];if(jobs.length===0)return null;let base=input.jobHost??input.actionHost??(input.data===void 0?void 0:{mainSchema:input.data.mainSchema});if(base===void 0){if(input.jobs.length>0)throw Error("createNucleusServer: jobs need a database. Pass `jobHost: { db, mainSchema }` or `actions: { host }`.");return logger.scoped("jobs").warn("actions.enabled is on but no database was given for jobs: expired idempotency keys are not purged"),null}let host={db:base.db??ownPool(input.data),runUnit:base.db===void 0?input.data?.runUnitOfWork:void 0,mainSchema:base.mainSchema,scope:input.jobHost?.scope,tables:base.tables,relations:base.relations,logger:base.logger,maxConcurrentPasses:input.jobHost?.maxConcurrentPasses,tenants:registrySource(currentRegistry)};return createJobRunner({host,jobs})}init_response();class BodyParseError extends Error{status=400;constructor(){super("Bad Request");this.name="BodyParseError"}}function looksStructured(value2){return value2.startsWith("{")||value2.startsWith("[")}function assignPath(target2,key2,value2){let steps=key2.replace(/\[(\w*)\]/g,".$1").split(".").filter((step)=>step!=="");if(steps.length<=1){mergeInto(target2,key2,value2);return}let cursor=target2;for(let index=0;index<steps.length-1;index++){let step=steps[index],next=steps[index+1],wanted=/^\d+$/.test(next)?[]:{},holder3=cursor;if(typeof holder3[step]!=="object"||holder3[step]===null)holder3[step]=wanted;cursor=holder3[step]}let last=steps[steps.length-1];if(Array.isArray(cursor))cursor[Number(last)]=value2;else mergeInto(cursor,last,value2)}function mergeInto(target2,key2,value2){if(key2 in target2){let existing=target2[key2];target2[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2];return}target2[key2]=value2}function fromFormData(form){let out={};for(let[key2,value2]of form.entries()){let parsed=value2;if(typeof value2==="string"&&looksStructured(value2))try{parsed=JSON.parse(value2)}catch{parsed=value2}assignPath(out,key2,parsed)}return out}async function parseBody(request,declared){let contentType=request.headers.get("content-type");if(!contentType&&!declared)return;let kind=(contentType?.includes("multipart/form-data")?"formdata":contentType?.includes("application/x-www-form-urlencoded")?"urlencoded":contentType?.includes("application/json")?"json":contentType?.startsWith("text/")?"text":contentType?.includes("octet-stream")?"binary":void 0)??declared;if(!kind)return;if(kind==="formdata")try{return fromFormData(await request.formData())}catch{throw new BodyParseError}if(kind==="urlencoded"){let params=new URLSearchParams(await request.text()),out={};for(let[key2,value2]of params)if(key2 in out){let existing=out[key2];out[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2]}else out[key2]=value2;return out}if(kind==="binary")return await request.arrayBuffer();if(kind==="text")return await request.text();let raw=await request.text();if(raw===""&&!request.body)return;try{return JSON.parse(raw)}catch{throw new BodyParseError}}init_response();init_esm();init_esm();var EMAIL2=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,UUID2=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,DATE_TIME=/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ANNOTATION_ONLY=["binary"],registered=!1;function registerStringFormats(){if(registered)return;registered=!0,exports_format.Set("email",(value2)=>EMAIL2.test(value2)),exports_format.Set("uuid",(value2)=>UUID2.test(value2)),exports_format.Set("date-time",(value2)=>DATE_TIME.test(value2));for(let name2 of ANNOTATION_ONLY)exports_format.Set(name2,()=>!0)}var REGISTERED_FORMATS=["email","uuid","date-time",...ANNOTATION_ONLY];var OPTIONAL_KIND=Symbol.for("TypeBox.Optional"),KIND=Symbol.for("TypeBox.Kind"),cleanable=new WeakMap;function honourOpenObjects(node){if(Array.isArray(node)){let changed2=!1,out2=node.map((entry)=>{let next=honourOpenObjects(entry);if(next!==entry)changed2=!0;return next});return changed2?out2:node}if(node===null||typeof node!=="object")return node;let source=node,isSchema=KIND in source,changed=!1,out={};for(let key2 of Object.keys(source)){let value2=source[key2];if(isSchema&&key2==="additionalProperties"&&value2===!0){out[key2]=Type.Any(),changed=!0;continue}let next=honourOpenObjects(value2);if(next!==value2)changed=!0;out[key2]=next}if(!changed)return node;for(let symbol3 of Object.getOwnPropertySymbols(source))out[symbol3]=source[symbol3];return out}function cleanSchemaFor(schema3){let cached=cleanable.get(schema3);if(cached)return cached;let rewritten=honourOpenObjects(schema3);return cleanable.set(schema3,rewritten),rewritten}function prepare(schema3,value2,on){if(!schema3)return value2;if(value2===void 0&&OPTIONAL_KIND in schema3)return;let prepared=value2;if(on==="query")try{prepared=exports_value2.Convert(schema3,prepared)}catch{}try{prepared=exports_value2.Default(schema3,prepared)}catch{}try{prepared=exports_value2.Clean(cleanSchemaFor(schema3),prepared)}catch{}return prepared}function sampleOf(schema3){try{return exports_value2.Create(schema3)}catch{return}}registerStringFormats();var REQUIRED_PROPERTY=45;function propertyName(path8){return path8.replace(/^\//,"").replace(/\//g,".")}function describe2(value2){if(value2===void 0)return"undefined";if(value2===null)return"null";if(typeof value2==="object")return JSON.stringify(value2);return String(value2)}function at(value2,path8){let current=value2;for(let segment of path8.split("/").filter(Boolean)){if(typeof current!=="object"||current===null)return;current=current[segment]}return current}function validate2(schema3,value2,on){if(!schema3)return null;if(exports_value2.Check(schema3,value2))return null;let all=[...exports_value2.Errors(schema3,value2)],errors2=all.filter((error3)=>error3.type!==REQUIRED_PROPERTY),primary=errors2[0]??all[0],path8=primary?.path??"",message=primary?.message??"Invalid value",atRoot=path8==="";return{isSuccess:!1,success:!1,type:"validation",on,property:atRoot?"root":path8,message,summary:atRoot?message:summarise(path8,message,at(value2,path8)),expected:sampleOf(schema3),found:redact(value2),errors:errors2.map((error3)=>({...error3,value:redact(error3.value),summary:summarise(error3.path,error3.message,at(value2,error3.path))}))}}function describeExpectation(message){return message.replace(/^Expected\s+/i,"")}function redact(value2){if(value2===null)return"null";if(Array.isArray(value2))return`array(${value2.length})`;if(value2 instanceof Date)return"Date";if(typeof value2==="object"){let shape={};for(let key2 of Object.keys(value2))shape[key2]=redact(value2[key2]);return shape}if(value2===void 0)return"undefined";return typeof value2}function summarise(path8,message,found){return`Expected property '${propertyName(path8)}' to be ${describeExpectation(message)} but found: ${describe2(redact(found))}`}class RouteCollisionError extends Error{constructor(method,path8){super(`${method} ${path8} is registered twice. Two groups claiming one path is a wiring mistake, not a fallback: which handler answers would depend on registration order.`);this.name="RouteCollisionError"}}function joinPath2(prefix,path8){if(!prefix)return path8;let left=prefix.endsWith("/")?prefix.slice(0,-1):prefix;if(path8==="/"||path8==="")return left||"/";let right=path8.startsWith("/")?path8:`/${path8}`;return`${left}${right}`||"/"}function buildRoutes(groups,options={}){let table2=new Map;for(let group of groups)for(let route of group.routes){let fullPath=joinPath2(group.prefix,route.path),method=route.method,byMethod=table2.get(fullPath);if(!byMethod)byMethod=new Map,table2.set(fullPath,byMethod);if(byMethod.has(method))throw new RouteCollisionError(method,fullPath);byMethod.set(method,{guards:[...group.guards??[],...route.guards??[]],route})}let out={},withSlashAlias=(path8)=>path8==="/"||path8.endsWith("/")?[path8]:[path8,`${path8}/`];for(let[path8,byMethod]of table2){let handlers={};for(let[method,registered2]of byMethod){handlers[method]=async(request,server)=>{let set2=createResponseSet(),response;try{response=await answer(request,server,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});response=finalizeResponse(answered,set2)}if(options.onAfter)try{set2.status=response.status,await options.onAfter({request,set:set2})}catch(error3){console.error("[router] after-handler failed",error3)}return response};let answer=async(request,server,set2)=>{let url=new URL(request.url),params=request.params??{},query=Object.fromEntries(url.searchParams);if(options.onRequest){let early=await options.onRequest({request,set:set2,body:void 0,params,query,server});if(early!==void 0)return finalizeResponse(early,set2)}let body;try{body=await parseBody(request.clone(),registered2.route.type)}catch(error3){if(error3 instanceof BodyParseError){let bodySchema=registered2.route.body;if(bodySchema&&OPTIONAL_KIND in bodySchema)body=void 0;else return new Response(error3.message,{status:error3.status})}else throw error3}body=prepare(registered2.route.body,body,"body"),query=prepare(registered2.route.query,query,"query"),params=prepare(registered2.route.params,params,"params");for(let[target2,schema3,value2]of[["body",registered2.route.body,body],["query",registered2.route.query,query],["params",registered2.route.params,params]]){if(value2===void 0&&schema3&&OPTIONAL_KIND in schema3)continue;let failure=validate2(schema3,value2,target2);if(failure){let headers=new Headers({"content-type":"application/json"});for(let[name2,value3]of Object.entries(set2.headers))if(value3!==void 0)headers.set(name2,String(value3));return new Response(JSON.stringify(failure,null,2),{status:422,headers})}}let guardContext={request,set:set2,body,params,query,server};if(options.beforeHandle){let early=await options.beforeHandle(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}for(let guard5 of registered2.guards){let early=await guard5(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}try{let result=await registered2.route.handler({...options.context,request,params,query,body,set:set2});return finalizeResponse(result,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}}for(let alias2 of withSlashAlias(path8))out[alias2]=handlers}return out}init_websocket();var NOT_FOUND=()=>new Response("NOT_FOUND",{status:404});async function staticAsset(request,assets){if(!assets)return null;if(request.method!=="GET"&&request.method!=="HEAD")return null;let{pathname}=new URL(request.url),prefix=assets.prefix.endsWith("/")?assets.prefix.slice(0,-1):assets.prefix;if(pathname!==prefix&&!pathname.startsWith(`${prefix}/`))return null;let relative;try{relative=decodeURIComponent(pathname.slice(prefix.length))}catch{return new Response("NOT_FOUND",{status:404})}let{join:join9,resolve:resolve2,sep}=await import("path"),root=resolve2(assets.directory),target2=resolve2(join9(root,relative));if(target2!==root&&!target2.startsWith(root+sep))return new Response("NOT_FOUND",{status:404});let file=Bun.file(target2);if(!await file.exists())return null;return new Response(request.method==="HEAD"?null:file)}function serve(options){let routes=buildRoutes(options.groups,{onRequest:options.onRequest,beforeHandle:options.beforeHandle,onError:options.onError,onAfter:options.onAfter,context:options.context}),notFound=options.notFound??NOT_FOUND,socket=options.socket,server=Bun.serve({port:options.port??0,hostname:options.hostname,idleTimeout:options.idleTimeout??30,reusePort:options.reusePort??!0,...options.maxRequestBodyBytes!==void 0?{maxRequestBodySize:options.maxRequestBodyBytes}:{},routes,fetch:async(request,self2)=>{let asset=await staticAsset(request,options.staticAssets);if(asset)return asset;let set2=createResponseSet();if(options.onRequest){let url=new URL(request.url);try{let early=await options.onRequest({request,set:set2,body:void 0,params:{},query:Object.fromEntries(url.searchParams),server:self2});if(early!==void 0)return finalizeResponse(early,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}if(socket){let upgraded=upgradeFor(socket,request,self2);if(upgraded)return upgraded}let missing=await notFound(request),headers=new Headers(missing.headers);for(let[name2,value2]of Object.entries(set2.headers))if(value2!==void 0&&!headers.has(name2))headers.set(name2,String(value2));let text4=await missing.text();return new Response(text4,{status:missing.status,headers})},websocket:socket?websocketHandlers(socket):void 0}),stopped=!1,runShutdown=async()=>{for(let step of options.onStop??[])try{await step()}catch(error3){console.error("[NucleusServer] shutdown step failed",error3)}},port=server.port??0,hostname=server.hostname??"localhost";return{port,hostname,url:`http://${hostname}:${port}`,stop:(closeActiveConnections=!1)=>{let stopping=Promise.resolve(server.stop(closeActiveConnections));if(stopped)return stopping;return stopped=!0,stopping.then(runShutdown)},raw:server}}function operationIdFor(method,path8){let tail2=path8.split("/").filter(Boolean).flatMap((segment)=>segment.startsWith(":")?["by",segment.slice(1)]:segment.split(/[-_]/)).filter(Boolean).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join("");return`${method.toLowerCase()}${tail2}`}function toOpenApiPath(path8){return path8.split("/").map((segment)=>segment.startsWith(":")?`{${segment.slice(1)}}`:segment).join("/")}function pathParametersOf(path8,schema3){let declared=schema3?.properties;return path8.split("/").filter((segment)=>segment.startsWith(":")).map((segment)=>{let name2=segment.slice(1);return{name:name2,in:"path",required:!0,schema:declared?.[name2]??{type:"string"}}})}function queryParametersOf(schema3){let object3=schema3;if(!object3?.properties)return[];return Object.entries(object3.properties).map(([name2,value2])=>({name:name2,in:"query",required:object3.required?.includes(name2)??!1,schema:value2}))}function buildOpenApiDocument(groups,config={}){let info=config.documentation?.info,exclude3=config.exclude??[],isExcluded=(path8)=>exclude3.some((rule)=>typeof rule==="string"?rule===path8:rule.test(path8)),paths={};for(let group of groups)for(let route of group.routes){let declared=route.path==="/"?"":route.path,joined=`${group.prefix??""}${declared}`||"/";if(isExcluded(joined))continue;let openApiPath=toOpenApiPath(joined),method=route.method.toLowerCase(),detail=route.detail,parameters4=[...pathParametersOf(joined,route.params),...queryParametersOf(route.query)],operation={operationId:operationIdFor(route.method,joined),responses:{"200":{}}};if(detail?.tags)operation.tags=detail.tags;if(detail?.summary)operation.summary=detail.summary;if(detail?.description)operation.description=detail.description;if(parameters4.length>0)operation.parameters=parameters4;if(route.body)operation.requestBody={content:{"application/json":{schema:route.body}}};if(paths[openApiPath]=paths[openApiPath]??{},!paths[openApiPath][method])paths[openApiPath][method]=operation}let document2={openapi:"3.0.3",info:{title:info?.title??"Nucleus API",description:info?.description??"Auto-generated API documentation",version:info?.version??"1.0.0",...info?.contact?{contact:info.contact}:{},...info?.license?{license:info.license}:{}},tags:config.documentation?.tags??[],paths};if(config.documentation?.servers)document2.servers=config.documentation.servers;return document2}function viewerHtml(documentUrl,title,description,viewerConfig){let forHtml=(value2)=>value2.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;"),configuration=viewerConfig&&Object.keys(viewerConfig).length>0?` data-configuration="${forHtml(JSON.stringify(viewerConfig))}"`:"";return`<!doctype html>
633
633
  <html>
634
634
  <head>
635
635
  <title>${forHtml(title)}</title>
package/dist/server.js CHANGED
@@ -629,7 +629,7 @@ ${content}
629
629
  ${warningBanner}
630
630
  ${deviceTable}
631
631
  <p style="margin:16px 0 0;color:#6b7280;font-size:13px;">If this wasn't you, please secure your account immediately.</p>
632
- `)}deliver(getEmailService(),{to:user.email,subject,html:emailHtml},"[AUTH] login notification").then((report)=>{if(report.level==="warn")logger2.warn(report.message,{userId:params.userId,trustScore,requiresApproval});else logger2.info(report.message,{userId:params.userId})})}}}if(logger2.info("[AUTH] Session saved to DB",{sessionId,userId:params.userId,isNewDevice,requiresApproval,deviceFingerprint,ipAddress:deviceInfo.ipAddress}),deviceTrustMint&&dtTable&&deviceTrustCfg?.enabled)try{let DT2=await Promise.resolve().then(() => (init_DeviceTrust(),exports_DeviceTrust)),DTStore2=await Promise.resolve().then(() => (init_store3(),exports_store)),{randomUUID:randomUUID12}=await import("crypto"),{raw,hash:hash2}=DT2.mintDeviceToken(),ttlSec=parseTimeToSeconds2(deviceTrustCfg.tokenExpiresIn??"30d");await DTStore2.insertDeviceRow(db,dtTable,{id:randomUUID12(),userId:params.userId,tokenHash:hash2,status:deviceTrustMint,originSessionId:sessionId,label:deviceInfo.deviceName||`${deviceInfo.browserName||"Unknown"} on ${deviceInfo.osName||"Unknown"}`,deviceFingerprint,firstSeenIp:deviceInfo.ipAddress,expiresAt:new Date(Date.now()+ttlSec*1000)});let rawDomainDT=authentication.cookieDomain,resolvedDomainDT=rawDomainDT?process.env[rawDomainDT]??rawDomainDT:void 0,domainDT=resolvedDomainDT==="localhost"||resolvedDomainDT===".localhost"?void 0:resolvedDomainDT;deviceTokenToSet=DT2.buildDeviceTokenCookie(raw,{cookieName:deviceTrustCfg.cookieName,cookiePrefix:deviceTrustCfg.cookiePrefix,sameSite:deviceTrustCfg.sameSite,maxAgeSeconds:ttlSec,domain:domainDT,secure:!!domainDT})}catch(dtErr){logger2.warn("[AUTH] Device-trust token mint failed \u2014 continuing",{userId:params.userId,error:dtErr instanceof Error?dtErr.message:String(dtErr)})}return{requiresApproval,sessionId,deviceTokenCookie:deviceTokenToSet??void 0}},storeResetToken:async(userId,token,expiresAt,reqSchemaName)=>{let resetTokensTable=resolveTableForTenant("passwordResetTokens",reqSchemaName);if(!resetTokensTable||!db)return;await db.insert(resetTokensTable).values({userId,tokenHash:createHash12("sha256").update(token).digest("hex"),expiresAt})},getResetToken:async(token,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),resetTokensTable=resolveTableForTenant("passwordResetTokens",reqSchemaName);if(!resetTokensTable||!db)return null;let tokenHash=createHash12("sha256").update(token).digest("hex"),row=(await db.select().from(resetTokensTable).where(eq84(resetTokensTable.tokenHash,tokenHash)).limit(1))[0];if(!row||row.usedAt)return null;return{userId:row.userId,expiresAt:row.expiresAt}},deleteResetToken:async(token,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),resetTokensTable=resolveTableForTenant("passwordResetTokens",reqSchemaName);if(!resetTokensTable||!db)return;let tokenHash=createHash12("sha256").update(token).digest("hex");await db.delete(resetTokensTable).where(eq84(resetTokensTable.tokenHash,tokenHash))},revokeSessionInDb:async(sessionId,reason,reqSchemaName)=>{let revokeTable=resolveTableForTenant("userSessions",reqSchemaName)||resolveTableForTenant("user_sessions",reqSchemaName)||resolveTableForTenant("sessions",reqSchemaName)||sessionsTable;if(!revokeTable||!db)return;await db.update(revokeTable).set({isActive:!1,revokedAt:new Date,revokedReason:reason}).where(eq83(revokeTable.id,sessionId)),logger2.info("[AUTH] Session revoked in DB",{sessionId,reason})},sendResetEmail:async(email,token,request,context)=>{if(isEmailExempt(email,authentication?.emailExemptDomains))return logger2.info("[AUTH] Skipping reset email \u2014 domain exempt",{email}),{sent:!1,reason:"exempt"};let mailer=getEmailService();if(!mailer?.isAvailable())return logger2.warn("[AUTH] Cannot send reset email \u2014 no email provider configured"),{sent:!1,reason:"no_provider"};let configuredResetUrl=authentication.passwordReset?.redirectUrl||"http://localhost:3000/reset-password",resetUrl=request?buildEmailActionLink({request,configuredUrl:configuredResetUrl,path:extractConfiguredPath(configuredResetUrl,"/reset-password"),query:{token},allowedOrigins:trustedAppOrigins()}):`${configuredResetUrl}?token=${token}`,content=renderPasswordResetEmail(authentication.passwordReset?.email,{link:resetUrl,locale:context?.locale,user:context?.user??{email}}),result=await mailer.sendEmail({to:email,subject:content.subject,html:content.html,...content.text===void 0?{}:{text:content.text}});if(result?.success===!1){let refused=result.rejected;return{sent:!1,reason:Array.isArray(refused)&&refused.length>0?"rejected":"error",detail:result.error}}return{sent:!0}},storeMagicToken:async(params,reqSchemaName)=>{let magicTokensTable=resolveTableForTenant("magicLinkTokens",reqSchemaName);if(!magicTokensTable||!db)return;await db.insert(magicTokensTable).values({userId:params.userId,email:params.email,tokenHash:params.tokenHash,expiresAt:params.expiresAt})},getMagicToken:async(tokenHash,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),magicTokensTable=resolveTableForTenant("magicLinkTokens",reqSchemaName);if(!magicTokensTable||!db)return null;let row=(await db.select().from(magicTokensTable).where(eq84(magicTokensTable.tokenHash,tokenHash)).limit(1))[0];if(!row||row.usedAt)return null;return{userId:row.userId,email:row.email,tokenHash:row.tokenHash,expiresAt:row.expiresAt}},deleteMagicToken:async(tokenHash,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),magicTokensTable=resolveTableForTenant("magicLinkTokens",reqSchemaName);if(!magicTokensTable||!db)return;await db.delete(magicTokensTable).where(eq84(magicTokensTable.tokenHash,tokenHash))}}}),logger2.info("[AUTH] Routes registered")}}if(resolvedOptions.storage?.enabled&&resolvedOptions.storage?.cdn?.enabled){let{createCdnRoutes:createCdnRoutes2,mergeCdnConfig:mergeCdnConfig2,mergeStorageConfig:mergeStorageConfig2}=(init_storage2(),__toCommonJS(exports_storage)),cdnConfig=mergeCdnConfig2(resolvedOptions.storage.cdn),storageConfig=mergeStorageConfig2(resolvedOptions.storage),filesTable=schemaTables.files;if(useRoutes(plugin,createCdnRoutes2({cdn:cdnConfig,storagePath:storageConfig.basePath,logger:logger2,getStorageProvider:()=>storageProvider,buildStorageProvider,authorizeFile:db?async({id,request,schemaName:reqSchemaName})=>{let tables2=schemaTables;if(reqSchemaName&&tenantRegistry){let ctx=tenantRegistry.getSchemaContext(reqSchemaName);if(ctx?.schemaTables)tables2=ctx.schemaTables}if(await checkAttachmentFileAccess({db,schemaTables:tables2,fileId:id,userId:request.headers.get("x-user-id")})==="denied")return!1;if(await isVerificationSignatureFile({db,schemaTables:tables2,fileId:id}))return!1;return!0}:void 0,getFileRecord:filesTable&&db?async(id,reqSchemaName)=>{let tbl=filesTable;if(reqSchemaName&&tenantRegistry){let ctx=tenantRegistry.getSchemaContext(reqSchemaName);if(ctx?.schemaTables.files)tbl=ctx.schemaTables.files}let t=tbl,result=await db.select().from(t).where(eq83(t.id,id)).limit(1);if(result.length===0)return null;let record4=result[0];return{id:record4.id,name:record4.name,path:record4.path,mime_type:record4.mimeType||record4.mime_type,original_name:record4.originalName||record4.original_name,is_active:record4.isActive??record4.is_active}}:void 0})),logger2.info(`[Storage] CDN routes enabled at ${cdnConfig.basePath}`),filesTable&&db){let{createResumableRoutes:createResumableRoutes2}=(init_resumable(),__toCommonJS(exports_resumable)),resumable=createResumableRoutes2({basePath:storageConfig.basePath,storage:storageConfig,logger:logger2,getUserId:(request)=>request.headers.get("x-user-id"),canUpload:(request)=>{if(resolvedOptions.authorization?.enabled===!1)return!0;return checkAuthorizationFromJWT({userClaims:decodeHeaderList(request.headers.get("x-user-claims")),userRoles:decodeHeaderList(request.headers.get("x-user-roles")),claimScopes:decodeClaimScopesHeader(request.headers.get("x-user-claim-scopes")),method:"POST",entity:"files",logger:logger2,requireClaimSpecificity:resolvedOptions.authorization?.requireClaimSpecificity}).authorized},register:async(input)=>{let nodePath=__require("path"),{rename:rename6}=__require("fs/promises"),{randomUUID:randomUUID12}=__require("crypto"),id=randomUUID12(),extension2=nodePath.extname(input.originalName),storedName=`${id}${extension2}`,destination=nodePath.join(storageConfig.basePath,storedName);try{await rename6(input.partPath,destination)}catch(error3){return logger2.error("[Storage] A finished upload could not be moved into place",{error:error3}),null}let uploaded={id,name:storedName,originalName:input.originalName,path:storageConfig.basePath,mimeType:input.mimeType,size:input.size,createdAt:new Date},{buildFileRecordPayload:buildFileRecordPayload2,scheduleUploadMediaProcessing:scheduleUploadMediaProcessing2}=(init_storage2(),__toCommonJS(exports_storage)),t=filesTable,payload={...buildFileRecordPayload2(uploaded,input.userId),type:input.type},row=(await db.insert(t).values(payload).returning())[0];if(!row?.id)return null;return scheduleUploadMediaProcessing2([uploaded],{storagePath:storageConfig.basePath,media:{transform:mergeTransformConfig(resolvedOptions.storage?.cdn?.transform),video:mergeVideoConfig(resolvedOptions.storage?.cdn?.video),pdf:mergePdfConfig(resolvedOptions.storage?.cdn?.pdf)},logger:logger2}),{id:String(row.id)}}});useRoutes(plugin,resumable.plugin),setInterval(()=>{resumable.sweep(Date.now()).then((removed)=>{if(removed>0)logger2.info(`[Storage] Reclaimed ${removed} abandoned upload(s)`)}).catch(()=>{})},3600000).unref?.(),logger2.info("[Storage] Resumable uploads enabled at /uploads")}}if(resolvedOptions.notification?.enabled&&db){let notificationConfig=resolvedOptions.notification;if(notificationConfig.endpoints?.enabled!==!1){warnOnEntityBasePathCollision("Notification",notificationConfig.endpoints?.basePath||"/notifications",resolvedOptions.entities,logger2);let{routes:notificationRoutes}=createNotificationRoutes({db,schemaTables,config:notificationConfig,logger:logger2,getEmailService,tenantRegistry,getTenantRegistry:()=>tenantRegistry});useRoutes(plugin,notificationRoutes),logger2.info(`[Notification] Routes registered at ${notificationConfig.endpoints?.basePath||"/notifications"}`)}}if(resolvedOptions.verification?.enabled&&db){let{routes:verificationRoutes}=createVerificationRoutes({db,schemaTables,config:resolvedOptions.verification,notificationConfig:resolvedOptions.notification,logger:logger2,getEmailService,tenantRegistry,getTenantRegistry:()=>tenantRegistry});useRoutes(plugin,verificationRoutes)}if(resolvedOptions.backup?.enabled&&db){let{createBackupRoutes:createBackupRoutes2}=(init_backup(),__toCommonJS(exports_backup)),{routes:backupRoutes}=createBackupRoutes2({db,logger:logger2,config:{enabled:!0,basePath:resolvedOptions.backup.basePath||"/admin/backup",storagePath:resolvedOptions.backup.storagePath||"./backups",format:resolvedOptions.backup.format||"json",maxBackups:resolvedOptions.backup.maxBackups||50,allowRestore:resolvedOptions.backup.allowRestore??!0,excludeTables:resolvedOptions.backup.excludeTables||["audit_logs","backup_logs"],encryptionKey:resolvedOptions.backup.encryptionKey?process.env[resolvedOptions.backup.encryptionKey]||resolvedOptions.backup.encryptionKey:void 0,schedule:{enabled:resolvedOptions.backup.schedule?.enabled??!1,cron:resolvedOptions.backup.schedule?.cron||"0 2 * * *",retentionDays:resolvedOptions.backup.schedule?.retentionDays||30,timeZone:resolvedOptions.backup.schedule?.timeZone}},schemaTables,schemaName:targetSchemaName,getTenantRegistry:()=>tenantRegistry,lock:getRedisManager()});useRoutes(plugin,backupRoutes),logger2.info("[Backup] Routes registered",{basePath:resolvedOptions.backup.basePath||"/admin/backup",scheduleEnabled:resolvedOptions.backup.schedule?.enabled??!1})}if(resolvedOptions.authorization?.endpointDiscovery?.enabled&&db&&resolvedOptions.authentication?.mode!=="consumer"){let{createAuthorizationDiscoveryRoutes:createAuthorizationDiscoveryRoutes2}=(init_authorization(),__toCommonJS(exports_authorization));useRoutes(plugin,createAuthorizationDiscoveryRoutes2({db,schemaTables,logger:logger2,discovery:resolvedOptions.authorization.endpointDiscovery,readState:async(key2)=>{let rm3=getRedisManager();if(!rm3)return null;let res=await rm3.read(key2);return res?.success?res.data:null}})),logger2.info("[Authorization] Endpoint-discovery routes registered",{discover:"/authorization/discover",manifest:"/authorization/route-manifest"})}let pubsubClientManager=null;if(resolvedOptions.pubsub?.enabled){let redis=getRedisManager();if(redis){let pubsubConfig=resolvedOptions.pubsub,{routes:pubsubRoutes,socket:pubsubSocket,clientManager}=createPubSubRoutes({redis,logger:logger2,basePath:pubsubConfig.basePath||"/subs",wsPath:pubsubConfig.wsPath||"/api/events/subscribe",pubsubName:pubsubConfig.pubsubName||"pubsub-redis",maxClientsPerUser:pubsubConfig.maxClientsPerUser??10,maxTopicsPerClient:pubsubConfig.maxTopicsPerClient??DEFAULT_MAX_TOPICS_PER_CLIENT,wsIdleTimeout:pubsubConfig.wsIdleTimeout??120,ack:{enabled:pubsubConfig.ack?.enabled??!0,ttlSeconds:pubsubConfig.ack?.ttlSeconds??300,maxRetries:pubsubConfig.ack?.maxRetries??3,retryIntervalMs:pubsubConfig.ack?.retryIntervalMs??5000},presence:{enabled:pubsubConfig.presence?.enabled??!0,debounceMs:pubsubConfig.presence?.debounceMs??5000},cleanupIntervalMs:pubsubConfig.cleanupIntervalMs??60000,daprApiToken:pubsubConfig.daprApiToken,getLiveMonitoringService:()=>liveMonitoringService,authenticate:envResolved.accessTokenSecret?createHandshakeAuthenticator({accessTokenSecret:envResolved.accessTokenSecret,tokenNames,issuer:authentication?.accessToken?.issuer,audience:authentication?.accessToken?.audience,requireLiveSession:authentication?.mode!=="consumer",db,resolveSessionsTable:(tenant)=>{let tables2=schemaTables;if(tenant&&tenantRegistry){let ctx=tenantRegistry.getSchemaContext(tenant);if(ctx?.schemaTables)tables2=ctx.schemaTables}return tables2?.userSessions??null},logger:logger2}):void 0});useRoutes(plugin,pubsubRoutes),recordSocket(pubsubSocket),recordAdapterStep((app)=>{mountWebSocketRoute(app,pubsubSocket)}),pubsubClientManager=clientManager,logger2.info("[PubSub] Enabled",{basePath:pubsubConfig.basePath||"/subs",wsPath:pubsubConfig.wsPath||"/api/events/subscribe"})}else logger2.warn("[PubSub] pubsub is enabled but Redis is not configured. Disabling PubSub.")}if(resolvedOptions.chat?.enabled&&db){let chatConfig=mergeChatConfig(resolvedOptions.chat),chatStorageConfig=mergeStorageConfig(resolvedOptions.storage),attachmentsAvailable=resolvedOptions.storage?.enabled===!0&&resolvedOptions.storage?.cdn?.enabled===!0&&chatConfig.attachments.enabled,cdnBasePath=resolvedOptions.storage?.cdn?.basePath||"/cdn",cdnMedia={transform:mergeTransformConfig(resolvedOptions.storage?.cdn?.transform),video:mergeVideoConfig(resolvedOptions.storage?.cdn?.video),pdf:mergePdfConfig(resolvedOptions.storage?.cdn?.pdf)},{routes:chatRoutes}=createChatRoutes({db,schemaTables,config:chatConfig,logger:logger2,broadcaster:pubsubClientManager,getTenantRegistry:()=>tenantRegistry,storageConfig:chatStorageConfig,attachmentsAvailable,cdnBasePath,cdnMedia});useRoutes(plugin,chatRoutes),logger2.info("[Chat] Enabled",{basePath:chatConfig.basePath,attachmentsAvailable,realtime:pubsubClientManager!==null})}if(resolvedOptions.payment?.enabled&&db){let{createPaymentService:createPaymentService2}=(init_Payment(),__toCommonJS(exports_Payment)),{createPaymentRoutes:createPaymentRoutes2}=(init_payment(),__toCommonJS(exports_payment)),paymentService=createPaymentService2(resolvedOptions);if(paymentService){let paymentConfig=resolvedOptions.payment,marketplaceServices=null;if(paymentConfig?.marketplace?.enabled){let{createMarketplaceServices:createMarketplaceServices2}=(init_Payment(),__toCommonJS(exports_Payment));marketplaceServices=createMarketplaceServices2({options:resolvedOptions,logger:logger2,getDb:()=>db,provider:paymentService.providerInstance,schemaTables})}let paymentRoutes=createPaymentRoutes2({provider:paymentService.providerInstance,webhookSecret:paymentService.webhookSecret,getPayoutService:()=>marketplaceServices?.payoutService??null,basePath:paymentConfig?.basePath||"/payment",defaultCurrency:paymentConfig?.defaultCurrency||"TRY",defaultLocale:paymentConfig?.defaultLocale||"tr",successRedirectUrl:paymentConfig?.successRedirectUrl||"/payment/success",failedRedirectUrl:paymentConfig?.failedRedirectUrl||"/payment/failed",errorRedirectUrl:paymentConfig?.errorRedirectUrl||"/payment/error",callbackUrl:paymentConfig?.callbackUrl,savedMethodsEnabled:paymentConfig?.savedMethodsEnabled??!0,threeDSecureEnabled:paymentConfig?.threeDSecureEnabled??!0,subMerchantsEnabled:paymentConfig?.subMerchantsEnabled??!1,transactionsTable:schemaTables.paymentTransactions??schemaTables.payment_transactions,methodsTable:schemaTables.paymentMethods??schemaTables.payment_methods,webhookLogsTable:schemaTables.paymentWebhookLogs??schemaTables.payment_webhook_logs,subMerchantsTable:schemaTables.paymentSubMerchants??schemaTables.payment_sub_merchants,commissionSplitsTable:schemaTables.paymentCommissionSplits??schemaTables.payment_commission_splits,productsTable:schemaTables.paymentProducts??schemaTables.payment_products,pricesTable:schemaTables.paymentPrices??schemaTables.payment_prices,customersTable:schemaTables.paymentCustomers??schemaTables.payment_customers,subscriptionsTable:schemaTables.paymentSubscriptions??schemaTables.payment_subscriptions,invoicesTable:schemaTables.paymentInvoices??schemaTables.payment_invoices,db,logger:logger2});if(useRoutes(plugin,paymentRoutes),logger2.info("[Payment] Routes registered",{basePath:paymentConfig?.basePath||"/payment",provider:paymentService.provider}),marketplaceServices){let{createMarketplaceRoutes:createMarketplaceRoutes2}=(init_marketplace(),__toCommonJS(exports_marketplace)),services=marketplaceServices;createMarketplaceRoutes2(plugin,{getMarketplaceService:()=>services.marketplaceService,getPayoutService:()=>services.payoutService,basePath:paymentConfig?.basePath||"/payment",logger:logger2}),logger2.info("[Payment] Marketplace routes registered",{basePath:`${paymentConfig?.basePath||"/payment"}/marketplace`})}}}let cohortConfig=authentication?.cohorts;if(cohortConfig?.enabled!==!1&&!isConsumerMode&&db){let cohortBasePath=cohortConfig?.basePath||"/auth/admin/cohorts",resolveTable=(key2,fallback)=>schemaTables[key2]??(fallback?schemaTables[fallback]:null)??null,resolvedCohortsTable=resolveTable("userCohorts","user_cohorts");if(!resolvedCohortsTable)logger2.warn("[Cohort] user_cohorts table not found in schema \u2014 cohort routes will be inactive. Re-generate schema with nucleus-core >= 0.9.120");if(useRoutes(plugin,createCohortRoutes({db,logger:logger2,cohortsTable:resolvedCohortsTable,usersTable:resolveTable("users"),sessionsTable:resolveTable("userSessions","user_sessions"),rolesTable:resolveTable("roles"),userRolesTable:resolveTable("userRoles","user_roles"),profilesTable:resolveTable("profiles"),basePath:cohortBasePath,get defaultRole(){return resolvedOptions.authentication?.defaultRole},get defaultRoles(){return resolvedOptions.authentication?.defaultRoles},emailExemptDomains:authentication?.emailExemptDomains,passwordPolicy:authentication?.passwordPolicy})),resolvedCohortsTable)logger2.info("[Cohort] Routes registered",{basePath:cohortBasePath})}if(resolvedOptions.configManagement?.enabled){let configBasePath=resolvedOptions.configManagement.basePath||"/nucleus/config";useRoutes(plugin,createConfigRoutes({logger:logger2,resolvedOptions,configFilePath,basePath:configBasePath,db,schemaTables,getRedis:()=>{let redis=getRedisManager();if(!redis)return null;return{read:async(key2)=>{let r=await redis.read(key2);return{success:r.success,data:r.success?r.data:null}},create:async(key2,value2)=>{return{success:(await redis.create(key2,value2)).success}}}},onConfigUpdate:(section,_newValue)=>{logger2.info(`[ConfigManagement] Section "${section}" updated in-memory`,{section})}})),logger2.info(`[ConfigManagement] Routes enabled at ${configBasePath}`)}if(resolvedOptions.secrets?.enabled){let secretsBasePath=resolvedOptions.secrets.basePath||"/secrets";warnOnEntityBasePathCollision("Secrets",secretsBasePath,resolvedOptions.entities,logger2),useRoutes(plugin,createSecretsRoutes({logger:logger2,basePath:secretsBasePath,db,schemaTables,resolvedOptions,getService:()=>secretsService,getEmailService,getStorageProvider:()=>storageProvider,buildStorageProvider,adminRoles:resolvedOptions.secrets.adminRoles})),logger2.info(`[Secrets] Routes enabled at ${secretsBasePath}`)}if(resolvedOptions.integrations?.enabled){let integrationsBasePath=resolvedOptions.integrations.basePath||"/integrations";warnOnEntityBasePathCollision("Integrations",integrationsBasePath,resolvedOptions.entities,logger2),useRoutes(plugin,createIntegrationRoutes({logger:logger2,basePath:integrationsBasePath,db,schemaTables,resolvedOptions,getEncryptionKey:()=>resolveMasterKey(resolvedOptions.secrets?.encryptionKey)??null,getLockStore:()=>getRedisManager(),publish:(topic,payload)=>pubsubClientManager?.broadcastEvent(topic,payload),adminRoles:resolvedOptions.integrations.adminRoles}))}recordBootStep(()=>{let assignments=resolvedOptions.authorization?.seed?.roleClaimAssignments;if(!assignments?.length)return;let ownership=[];for(let entity of resolvedOptions.entities??[]){let table2=entity.table_name;if(!table2)continue;for(let column3 of entity.columns??[]){let hasDefault=column3.default!==void 0||!!column3.defaultRaw||!!column3.generatedAlwaysAs;if(column3.notNull&&!column3.nullable&&!hasDefault)ownership.push({table:table2,column:column3.name})}}for(let line of describeUnstamped(findUnstampedOwnership(assignments,ownership)))logger2.warn(line)}),recordBootStep((app)=>{let requiredBody=requiredBodyCeiling({storageEnabled:resolvedOptions.storage?.enabled,maxFileSizeBytes:resolvedOptions.storage?.maxFileSizeBytes,maxFiles:resolvedOptions.storage?.formData?.maxFiles}),complaint=bodyCeilingComplaint({configured:app?.config?.serve?.maxRequestBodySize,required:requiredBody});if(complaint)logger2.error(`[Storage] ${complaint}`);else if(requiredBody!==null){let configuredCeiling=app?.config?.serve?.maxRequestBodySize,mb2=(bytes)=>`${Math.round(bytes/1048576)} MB`;logger2.info(`[Storage] Uploads are configured up to ${mb2(requiredBody)}, and the server accepts ${configuredCeiling?mb2(configuredCeiling):"Bun's default"}.`)}let memoryComplaint=memoryCeilingComplaint({required:requiredBody,cgroupLimit:readCgroupLimitBytes()});if(memoryComplaint)logger2.error(`[Storage] ${memoryComplaint}`);let memoryAdvice=readRuntimeMemoryAdvice();if(memoryAdvice){let mib=(bytes)=>`${Math.round(bytes/1024/1024)} MiB`;logger2.warn(`[Runtime] The JS engine sizes its heap for ${mib(memoryAdvice.hostTotal)} but this container is capped at ${mib(memoryAdvice.cgroupLimit)} \u2014 it feels no memory `+"pressure and may grow past the limit and be OOM-killed. Raising the container memory limit delays this; no runtime option we have measured prevents it.")}let port=Number(process.env.PORT)||3000,appId=resolvedOptions.appId||"nucleus",mode=resolvedOptions.mode||"production";console.log(""),console.log(` \x1B[32m\uD83D\uDE80 ${appId}\x1B[0m \x1B[90mv${Date.now()}\x1B[0m`),console.log(` \x1B[36m\u279C\x1B[0m Local: \x1B[36mhttp://localhost:${port}\x1B[0m`),console.log(` \x1B[36m\u279C\x1B[0m Mode: \x1B[33m${mode}\x1B[0m`),console.log("")});let shuttingDown=!1,drainResources=async(trigger)=>{if(shuttingDown)return;shuttingDown=!0,logger2.info(`[Shutdown] ${trigger} \u2014 draining resources`);try{await lifecycleRecorder?.recordStop(trigger)}catch{}try{liveMonitoringService?.stop(),monitoringService?.stop(),secretsService?.stop(),storageProvider?.close()}catch(err){logger2.warn("[Shutdown] failed stopping monitoring",{error:err instanceof Error?err.message:String(err)})}try{let redisClient=getRedisManager()?.getDirectClient?.();if(redisClient)await redisClient.quit()}catch(err){logger2.warn("[Shutdown] failed closing Redis",{error:err instanceof Error?err.message:String(err)})}try{for(let timer of backgroundIntervals)clearInterval(timer);backgroundIntervals.length=0}catch(err){logger2.warn("[Shutdown] failed clearing background intervals",{error:err instanceof Error?err.message:String(err)})}try{let{destroyAckCleanup:destroyAckCleanup2}=await Promise.resolve().then(() => (init_ack_manager(),exports_ack_manager));destroyAckCleanup2()}catch{}try{if(dbPool)await dbPool.end()}catch(err){logger2.warn("[Shutdown] failed draining DB pool",{error:err instanceof Error?err.message:String(err)})}logger2.info("[Shutdown] complete")};if(recordShutdownStep(async()=>{await drainResources("server stop")}),resolvedOptions.gracefulShutdown!==!1){let onSignal=(signal)=>{drainResources(signal).finally(()=>process.exit(0))};process.once("SIGTERM",()=>onSignal("SIGTERM")),process.once("SIGINT",()=>onSignal("SIGINT"))}return recordAdapterStep((app)=>{for(let step of getRecordedBootSteps())app.onStart(step);for(let step of getRecordedShutdownSteps())app.onStop(step)}),lastMountedSocket=getRecordedSocket(),lastStaticAssets=getRecordedStaticAssets(),lastBootSteps=getRecordedBootSteps(),lastShutdownSteps=getRecordedShutdownSteps(),lastMountedGroups=resolveOverrides(endRouteRecording(),logger2),lastAuthMiddleware=authMiddleware,lastErrorHandler=errorResponder,lastAfterHandler=afterHandler,plugin}init_createUserAccount();init_utils6();function isNucleusRuntime(value2){return typeof value2==="object"&&value2!==null&&typeof Reflect.get(value2,"sendNotification")==="function"&&typeof Reflect.get(value2,"sendEmail")==="function"}init_Logger2();function actorOf2(request){let id=request.headers.get("x-user-id");return{id:id===null||id===""?null:id,roles:decodeHeaderList(request.headers.get("x-user-roles")),claims:decodeHeaderList(request.headers.get("x-user-claims"))}}function actorMaySee(actor,required3){let roleOk=required3.roles===void 0||required3.roles.some((role)=>actor.roles.includes(role)),claimOk=required3.claims===void 0||required3.claims.some((claim)=>actor.claims.includes(claim));return roleOk&&claimOk}var defaultEnvelope={success:(data)=>({success:!0,data:data??null}),failure:(failure)=>({success:!1,error:failure.code,message:failure.message,...failure.details===void 0?{}:{details:failure.details}})};function failureOf(error3){if(error3 instanceof ActionError)return{status:error3.status,code:error3.code,message:error3.message,details:error3.details};if(error3 instanceof IdempotencyConflictError)return{status:409,code:"idempotency_key_reused",message:error3.message};if(error3 instanceof ScopeViolationError)return{status:403,code:"scope_violation",message:"This write is outside your scope"};if(error3 instanceof Error){let constraint=toConstraintError(error3);if(constraint!==null)return{status:409,code:"constraint_violation",message:constraint.message,details:{kind:constraint.kind,constraint:constraint.constraint,columns:[...constraint.columns],table:constraint.table}}}if(isRetryable(error3))return{status:409,code:"serialization_failure",message:"The request conflicted with a concurrent one; repeat it"};return null}var ACTION_SCOPE="data.action",DEFAULT_IDEMPOTENCY_HEADER="Idempotency-Key",KEY_MAX_LENGTH=255;function schemaFor(host,action,request){if(action.scope==="main")return host.mainSchema;return host.schemaOf?.(request)??request.headers.get("x-tenant-schema")??host.mainSchema}function idempotencyOf(action,call,actorId){let settings=action.idempotency;if(settings===void 0)return null;let key2=call.request.headers.get(settings.header??DEFAULT_IDEMPOTENCY_HEADER)?.trim();if(key2===void 0||key2==="")return settings.required===!0?{status:400,code:"idempotency_key_required",message:"The Idempotency-Key header is required"}:null;if(key2.length>KEY_MAX_LENGTH)return{status:400,code:"idempotency_key_invalid",message:"The idempotency key is too long"};return{key:key2,action:action.name,actor:actorId??"",payloadHash:payloadHash({body:call.body,query:call.query,params:call.params}),ttlSeconds:settings.ttlSeconds??DEFAULT_IDEMPOTENCY_TTL_SECONDS}}function isFailure(value2){return value2!==null&&"status"in value2}function render(call,envelope,failure){return call.set.status=failure.status,envelope.failure(failure)}async function runAction(host,action,call){let log4=(host.logger??logger).scoped(ACTION_SCOPE),envelope=host.envelope??defaultEnvelope,actor=actorOf2(call.request),schema3=schemaFor(host,action,call.request),claim=idempotencyOf(action,call,actor.id);if(isFailure(claim))return render(call,envelope,claim);let nucleus=call.nucleus,ctx={request:call.request,actor,schema:schema3,set:call.set,nucleus:call.nucleus},db=host.db??nucleusDataOf(nucleus)?.db;if(db===void 0)throw new StoreError(`Action "${action.name}" has no database: the host gave no db and the server is not served by createNucleusServer`);let options={db,schema:schema3,mainSchema:host.mainSchema,scope:host.scopeFor(actor),tables:host.tables,relations:host.relations,logger:log4,retry:action.retry,isolationLevel:action.isolationLevel,readOnly:action.readOnly,notifier:nucleus===null?void 0:(params)=>nucleus.sendNotification(params)};try{let outcome=await runUnitOfWork(options,async(unit)=>{call.set.status=void 0;let keyRowId=null;if(claim!==null){let taken=await claimIdempotencyKey(executorOf2(unit),schema3,claim);if(taken.kind==="replay")return{status:taken.status,body:envelope.success(taken.body),replayed:!0};keyRowId=taken.id}let result=await action.handler({params:call.params,body:call.body,query:call.query},unit,ctx),status=call.set.status??200;if(claim!==null&&keyRowId!==null)await completeIdempotency(executorOf2(unit),schema3,keyRowId,status,result);return{status,body:envelope.success(result),replayed:!1}});if(call.set.status=outcome.status,outcome.replayed)call.set.headers["idempotent-replay"]="true";return outcome.body}catch(error3){let failure=failureOf(error3);if(failure===null)throw error3;return log4.warn("Action refused",{action:action.name,status:failure.status,code:failure.code}),render(call,envelope,failure)}}function accessGuard(spec,host){if(spec.public===!0&&spec.roles===void 0&&spec.claims===void 0)return null;let envelope=host.envelope??defaultEnvelope;return({request,set:set2})=>{let actor=actorOf2(request);if(actor.id===null&&spec.public!==!0)return set2.status=401,envelope.failure({status:401,code:"unauthorized",message:"Sign in first"});if(!actorMaySee(actor,spec))return set2.status=403,envelope.failure({status:403,code:"forbidden",message:"You may not do this"});return}}function defineActionFor(){return function(spec){return{name:spec.name,method:spec.method,path:spec.path,toRoute(host){let guard5=accessGuard(spec,host);return defineRoute({method:spec.method,path:spec.path,isPublic:spec.public,body:spec.body,query:spec.query,params:spec.params,response:spec.response,detail:{summary:spec.name,tags:["Actions"],...spec.detail},guards:guard5===null?[]:[guard5],handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,spec,{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}}var defineAction=defineActionFor();function actionGroup(host,actions){let names3=new Set;for(let action of actions){if(names3.has(action.name))throw Error(`Two actions are named "${action.name}"`);names3.add(action.name)}return{routes:actions.map((action)=>action.toRoute(host))}}function isPlain(value2){return!Array.isArray(value2)&&!(value2 instanceof Date)}function jsonOfValue(value2){if(value2===null||typeof value2==="string"||typeof value2==="boolean")return value2;if(typeof value2==="number")return Number.isFinite(value2)?value2:null;if(typeof value2==="bigint")return value2.toString();if(value2 instanceof Date)return value2.toISOString();if(Array.isArray(value2))return value2.map((item)=>jsonOfValue(item));let out={};if(!isPlain(value2))return out;for(let[key2,item]of Object.entries(value2))if(item!==void 0)out[key2]=jsonOfValue(item);return out}init_utils5();var RESERVED_QUERY_NAMES=["page","limit","after","filters","sort"],OPERATORS2=["eq","neq","gt","gte","lt","lte","like","ilike"],LISTS2=["in","notIn"];function isRecord8(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function jsonOf2(name2,text4){try{return JSON.parse(text4)}catch{throw new ViewError(`"${name2}" is not valid JSON`)}}function scalarOf5(name2,value2){if(typeof value2==="string"||typeof value2==="number"||typeof value2==="boolean")return value2;throw new ViewError(`"${name2}": the value must be a string, a number or a boolean`)}function opsOf(entry){let{operator,field:field2}=entry;if(typeof operator!=="string")throw new ViewError('A filter needs an "operator"');let label2=`Filter on "${String(field2)}"`,one=OPERATORS2.find((o)=>o===operator);if(one!==void 0)return{[one]:scalarOf5(label2,entry.value)};let list3=LISTS2.find((o)=>o===operator);if(list3!==void 0){let values=entry.value;if(!Array.isArray(values))throw new ViewError(`${label2}: "${operator}" takes an array`);return{[list3]:values.map((v)=>scalarOf5(label2,v))}}if(operator==="isNull")return{isNull:!0};if(operator==="isNotNull")return{isNull:!1};throw new ViewError(`${label2}: unknown operator "${operator}"`)}function parseFilters(text4){if(text4===void 0||text4==="")return{};let list3=jsonOf2("filters",text4);if(!Array.isArray(list3))throw new ViewError('"filters" must be a JSON array');let out={};for(let entry of list3){if(!isRecord8(entry)||typeof entry.field!=="string")throw new ViewError('A filter is { "field", "operator", "value" }');let ops=opsOf(entry),known=out[entry.field]??{};for(let key2 of Object.keys(ops))if(Object.hasOwn(known,key2))throw new ViewError(`Two "${key2}" filters on "${entry.field}"`);out[entry.field]={...known,...ops}}return out}function directionOf(value2){if(value2==="asc"||value2==="desc")return value2;throw new ViewError('A sort direction is "asc" or "desc"')}function parseSort(text4){if(text4===void 0||text4.trim()==="")return;let trimmed=text4.trim();if(!trimmed.startsWith("["))return trimmed.split(",").map((part)=>{let name2=part.trim(),desc9=name2.startsWith("-"),field2=desc9?name2.slice(1):name2;if(field2==="")throw new ViewError("An empty sort field");return{field:field2,direction:desc9?"desc":"asc"}});let list3=jsonOf2("sort",trimmed);if(!Array.isArray(list3))throw new ViewError('"sort" must be a JSON array');return list3.map((entry)=>{if(!isRecord8(entry)||typeof entry.field!=="string")throw new ViewError('A sort is { "field", "direction" }');return{field:entry.field,direction:directionOf(entry.direction)}})}function positive2(name2,text4,fallback){if(text4===null||text4==="")return fallback;let value2=Number(text4);if(!Number.isInteger(value2)||value2<1)throw new ViewError(`"${name2}" must be a positive integer`);return value2}function parseViewQuery(url){let query=url.searchParams,params={};for(let name2 of new Set(query.keys())){if(RESERVED_QUERY_NAMES.includes(name2))continue;let values=query.getAll(name2);params[name2]=values.length===1&&values[0]!==void 0?values[0]:values}let after=query.get("after")??void 0;if(after!==void 0&&query.has("page"))throw new ViewError('Send "page" or "after", not both');return{params,filters:parseFilters(query.get("filters")??void 0),sort:parseSort(query.get("sort")??void 0),page:positive2("page",query.get("page"),1)??1,limit:positive2("limit",query.get("limit"),void 0),after:after===""?void 0:after}}function refusal(error3){if(error3 instanceof ViewParamError)return new ActionError(422,"invalid_view_params",error3.message,{param:error3.param});return new ActionError(422,"invalid_view_request",error3.message)}function requestOf(view,ctx,paging){let url=new URL(ctx.request.url),query=parseViewQuery(url);if(paging==="cursor"&&url.searchParams.has("page"))throw new ViewError('This view pages with "after", not "page"');let size=query.limit??view.plan.limit,offset=paging==="offset"?(query.page-1)*size:void 0;return{request:{params:view.parseParams(query.params),filters:query.filters,sort:query.sort,limit:query.limit,offset,after:query.after===void 0?void 0:decodeViewCursor(query.after,query.sort)},page:query.page,offset:offset??0,sort:query.sort}}async function runViewCall(view,paging,unit,ctx){try{let{request,page,offset,sort}=requestOf(view,ctx,paging),result=await unit.store.view(view,request),items=result.items.map((row)=>jsonOfValue(row));if(paging==="cursor"){let nextCursor=result.next===null?null:encodeViewCursor(sort,result.next);return{items,meta:{limit:result.limit,hasNextPage:result.hasNextPage,nextCursor}}}let total=await unit.store.countView(view,request);return{items,meta:{...buildPaginationMeta(page,result.limit,offset,total)}}}catch(error3){if(error3 instanceof ViewParamError||error3 instanceof ViewError)throw refusal(error3);throw error3}}function viewClaimOf(name2){return`get.view.${name2}`}function check2(spec){let name2=spec.view.plan.name;if(!spec.path.startsWith("/")||spec.path.includes(":"))throw Error(`View "${name2}": the path must be a literal starting with "/" ("${spec.path}")`);let clash=Object.keys(spec.view.plan.params).find((p)=>RESERVED_QUERY_NAMES.includes(p));if(clash!==void 0)throw Error(`View "${name2}": the param name "${clash}" is reserved by the view route`)}function guardsOf(spec,host){let name2=spec.view.plan.name,claims=spec.roles===void 0&&spec.claims===void 0&&spec.public!==!0?[viewClaimOf(name2)]:spec.claims,access2=accessGuard({public:spec.public,roles:spec.roles,claims},host),guards2=access2===null?[]:[access2];if(spec.tenantFeature!==void 0){let registry5=host.getTenantRegistry;if(registry5===void 0)throw Error(`View "${name2}" declares tenant_feature but the host has no getTenantRegistry`);guards2.push(createTenantFeatureGuard(spec.tenantFeature,()=>registry5.call(host)))}return guards2}function defineViewRoute(spec){check2(spec);let name2=spec.view.plan.name;return{name:name2,path:spec.path,toRoute(host){let paging=spec.paging??"offset";return defineRoute({method:"GET",path:spec.path,isPublic:spec.public,detail:{summary:`View ${name2}`,tags:["Views"],...spec.detail},guards:guardsOf(spec,host),handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,{name:`view.${name2}`,scope:spec.scope,readOnly:!0,handler:(_input,unit,ctx)=>runViewCall(spec.view,paging,unit,ctx)},{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}function viewGroup(host,views){let names3=new Set;for(let view of views){if(names3.has(view.name))throw Error(`Two views are named "${view.name}"`);names3.add(view.name)}return{routes:views.map((view)=>view.toRoute(host))}}function isViewConfig(entry){return typeof Reflect.get(entry,"name")==="string"&&typeof Reflect.get(entry,"from")==="string"}function viewsOfOptions(resolved){let list3=resolved===null?void 0:Reflect.get(resolved,"views");if(list3===void 0)return[];if(!Array.isArray(list3))throw Error("config.views must be an array of view declarations");return list3.map((entry,index)=>{if(typeof entry!=="object"||entry===null||!isViewConfig(entry))throw Error(`config.views[${index}] needs a "name" and a "from"`);return entry})}function configViewRoutes(configs){let routes=[];for(let config of configs??[]){if(config.path===void 0)continue;routes.push(defineViewRoute({view:buildConfigView(config),path:config.path,public:config.is_public,roles:config.roles,claims:config.claims,tenantFeature:config.tenant_feature,paging:config.paging,scope:config.scope}))}return routes}init_Logger2();var NAME3=/^[A-Za-z][A-Za-z0-9_.-]{0,99}$/,MAX_EVERY_SECONDS=86400;function validate(spec){if(!NAME3.test(spec.name))throw Error(`Job name "${spec.name}" must start with a letter and use letters, digits, ".", "_" or "-"`);if(!Number.isInteger(spec.everySeconds)||spec.everySeconds<1||spec.everySeconds>MAX_EVERY_SECONDS)throw Error(`Job "${spec.name}": everySeconds must be a whole number from 1 to ${MAX_EVERY_SECONDS}`);let first=spec.firstRunAfterSeconds;if(first!==void 0&&(!Number.isFinite(first)||first<0))throw Error(`Job "${spec.name}": firstRunAfterSeconds must be zero or more`)}function defineJobFor(){return function(spec){return validate(spec),{name:spec.name,everySeconds:spec.everySeconds,scope:spec.scope,firstRunAfterSeconds:spec.firstRunAfterSeconds,execute:(options,ctx)=>runUnitOfWork({...options,retry:spec.retry},(unit)=>spec.run(unit,ctx))}}}var defineJob=defineJobFor();var PURGE_EVERY_SECONDS=3600;function purgeJob(name2,scope){return defineJob({name:name2,everySeconds:PURGE_EVERY_SECONDS,scope,run:async(unit,ctx)=>{let removed=await purgeExpiredIdempotencyKeys(executorOf2(unit),ctx.schema);if(removed>0)ctx.logger.info("Expired idempotency keys removed",{schema:ctx.schema,removed});return{handled:removed,failed:0}}})}var IDEMPOTENCY_PURGE_JOBS=[purgeJob("nucleus.purgeIdempotencyKeys","active"),purgeJob("nucleus.purgeIdempotencyKeys.main","main")];import{sql as sql43}from"drizzle-orm";init_Logger2();var systemClock={now:()=>Date.now(),after(delayMs,callback){let timer=setTimeout(callback,delayMs);if(typeof timer==="object"&&typeof timer.unref==="function")timer.unref();return()=>clearTimeout(timer)}};function firstRunDelayMs(job,index){return((job.firstRunAfterSeconds??Math.min(job.everySeconds,20))+index*5)*1000}function nextDelayMs({everySeconds,failures}){let interval=everySeconds*1000;if(failures<=0)return interval;let base=Math.min(30000,interval);return Math.min(base*2**(failures-1),interval*8)}function createJobLoop(options){let{job,clock,log:log4}=options,cancel=null,running=null,active=!1,failures=0;function runNow(){return running??=options.pass().finally(()=>{running=null}),running}function schedule(delayMs){if(!active)return;cancel=clock.after(delayMs,()=>void cycle())}async function cycle(){cancel=null;let failed;try{let report=await runNow();if(failed=report.failed>0,report.skipped)log4.debug("Pass skipped: another replica holds the lock");else if(report.handled>0||report.failed>0)log4.info("Pass finished",{...report})}catch(error3){failed=!0,log4.error("Pass failed",error3)}failures=failed?failures+1:0;let delayMs=nextDelayMs({everySeconds:job.everySeconds,failures});if(failed)log4.warn("Retrying",{inSeconds:delayMs/1000,consecutiveFailures:failures});schedule(delayMs)}return{start(){active=!0,schedule(firstRunDelayMs(job,options.index))},async stop(){active=!1,cancel?.(),cancel=null,await running?.catch(()=>{return})},runNow}}function registrySource(registry5){return{list:()=>(registry5()?.getAllTenants()??[]).map((tenant)=>({id:tenant.id,schema:tenant.schemaName,status:tenant.status}))}}var PROVISIONED=["active","suspended","archived"];function targetsOf(scope,tenants,mainSchema){if(scope==="main")return[{id:null,schema:mainSchema,status:"active"}];let allowed=scope==="provisioned"?PROVISIONED:["active"];return tenants.list().filter((tenant)=>allowed.includes(tenant.status)).sort((a,b)=>a.schema<b.schema?-1:a.schema>b.schema?1:0)}var SKIPPED_PASS={tenants:0,handled:0,failed:0,skipped:!0};async function walkTargets(targets,visit,log4){let handled=0,failed=0;for(let target2 of targets)try{let result=await visit(target2);handled+=result.handled,failed+=result.failed}catch(error3){failed+=1,log4.error("Tenant failed; the others still run",error3,{schema:target2.schema})}return{tenants:targets.length,handled,failed,skipped:!1}}var JOBS_SCOPE="jobs",jobLockKey=(name2)=>`${JOBS_SCOPE}:${name2}`;async function tryJobLock(tx,name2){let result=await tx.execute(sql43`select pg_try_advisory_xact_lock(${advisoryKeyOf(jobLockKey(name2))}) as locked`),[row]=rowsOfResult(result);return row!==void 0&&Reflect.get(row,"locked")===!0}async function runPass(host,job,log4){let scoped2=log4.scoped(`${JOBS_SCOPE}.${job.name}`);return host.db.transaction(async(tx)=>{if(!await tryJobLock(tx,job.name))return SKIPPED_PASS;let targets=targetsOf(job.scope,host.tenants,host.mainSchema);return walkTargets(targets,(target2)=>{let options={db:host.db,schema:target2.schema,mainSchema:host.mainSchema,scope:host.scope??(()=>[]),tables:host.tables,relations:host.relations,logger:scoped2},ctx={job:job.name,schema:target2.schema,tenant:target2,logger:scoped2};return job.execute(options,ctx)},scoped2)})}function createJobRunner(options){let{host}=options,log4=host.logger??logger,clock=options.clock??systemClock,loops=new Map;for(let[index,job]of options.jobs.entries()){if(loops.has(job.name))throw Error(`Two jobs are named "${job.name}"`);loops.set(job.name,createJobLoop({job,index,clock,log:log4.scoped(`${JOBS_SCOPE}.${job.name}`),pass:()=>runPass(host,job,log4)}))}return{names:[...loops.keys()],start(){for(let loop of loops.values())loop.start()},async stop(){await Promise.allSettled([...loops.values()].map((loop)=>loop.stop()))},runNow(name2){let loop=loops.get(name2);if(loop===void 0)return Promise.reject(Error(`No job is named "${name2}"`));return loop.runNow()}}}function actionFlagsOf(resolved){let actions=resolved===null?void 0:Reflect.get(resolved,"actions");if(typeof actions!=="object"||actions===null)return{enabled:!1,purgeExpiredKeys:!0};return{enabled:Reflect.get(actions,"enabled")===!0,purgeExpiredKeys:Reflect.get(actions,"purgeExpiredKeys")!==!1}}function ownPool(data){if(data===void 0)throw Error("createNucleusServer: the job host names no database and nucleus has none to lend. Pass `jobHost: { db, mainSchema }`.");return data.db}function bootJobRunner(input){let jobs=[...input.actions.enabled&&input.actions.purgeExpiredKeys?IDEMPOTENCY_PURGE_JOBS:[],...input.jobs];if(jobs.length===0)return null;let base=input.jobHost??input.actionHost??(input.data===void 0?void 0:{mainSchema:input.data.mainSchema});if(base===void 0){if(input.jobs.length>0)throw Error("createNucleusServer: jobs need a database. Pass `jobHost: { db, mainSchema }` or `actions: { host }`.");return logger.scoped("jobs").warn("actions.enabled is on but no database was given for jobs: expired idempotency keys are not purged"),null}let host={db:base.db??ownPool(input.data),mainSchema:base.mainSchema,scope:input.jobHost?.scope,tables:base.tables,relations:base.relations,logger:base.logger,tenants:registrySource(currentRegistry)};return createJobRunner({host,jobs})}init_response();class BodyParseError extends Error{status=400;constructor(){super("Bad Request");this.name="BodyParseError"}}function looksStructured(value2){return value2.startsWith("{")||value2.startsWith("[")}function assignPath(target2,key2,value2){let steps=key2.replace(/\[(\w*)\]/g,".$1").split(".").filter((step)=>step!=="");if(steps.length<=1){mergeInto(target2,key2,value2);return}let cursor=target2;for(let index=0;index<steps.length-1;index++){let step=steps[index],next=steps[index+1],wanted=/^\d+$/.test(next)?[]:{},holder3=cursor;if(typeof holder3[step]!=="object"||holder3[step]===null)holder3[step]=wanted;cursor=holder3[step]}let last=steps[steps.length-1];if(Array.isArray(cursor))cursor[Number(last)]=value2;else mergeInto(cursor,last,value2)}function mergeInto(target2,key2,value2){if(key2 in target2){let existing=target2[key2];target2[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2];return}target2[key2]=value2}function fromFormData(form){let out={};for(let[key2,value2]of form.entries()){let parsed=value2;if(typeof value2==="string"&&looksStructured(value2))try{parsed=JSON.parse(value2)}catch{parsed=value2}assignPath(out,key2,parsed)}return out}async function parseBody(request,declared){let contentType=request.headers.get("content-type");if(!contentType&&!declared)return;let kind=(contentType?.includes("multipart/form-data")?"formdata":contentType?.includes("application/x-www-form-urlencoded")?"urlencoded":contentType?.includes("application/json")?"json":contentType?.startsWith("text/")?"text":contentType?.includes("octet-stream")?"binary":void 0)??declared;if(!kind)return;if(kind==="formdata")try{return fromFormData(await request.formData())}catch{throw new BodyParseError}if(kind==="urlencoded"){let params=new URLSearchParams(await request.text()),out={};for(let[key2,value2]of params)if(key2 in out){let existing=out[key2];out[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2]}else out[key2]=value2;return out}if(kind==="binary")return await request.arrayBuffer();if(kind==="text")return await request.text();let raw=await request.text();if(raw===""&&!request.body)return;try{return JSON.parse(raw)}catch{throw new BodyParseError}}init_response();init_esm3();init_esm3();var EMAIL2=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,UUID2=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,DATE_TIME=/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ANNOTATION_ONLY=["binary"],registered=!1;function registerStringFormats(){if(registered)return;registered=!0,exports_format.Set("email",(value2)=>EMAIL2.test(value2)),exports_format.Set("uuid",(value2)=>UUID2.test(value2)),exports_format.Set("date-time",(value2)=>DATE_TIME.test(value2));for(let name2 of ANNOTATION_ONLY)exports_format.Set(name2,()=>!0)}var REGISTERED_FORMATS=["email","uuid","date-time",...ANNOTATION_ONLY];var OPTIONAL_KIND=Symbol.for("TypeBox.Optional"),KIND=Symbol.for("TypeBox.Kind"),cleanable=new WeakMap;function honourOpenObjects(node){if(Array.isArray(node)){let changed2=!1,out2=node.map((entry)=>{let next=honourOpenObjects(entry);if(next!==entry)changed2=!0;return next});return changed2?out2:node}if(node===null||typeof node!=="object")return node;let source=node,isSchema=KIND in source,changed=!1,out={};for(let key2 of Object.keys(source)){let value2=source[key2];if(isSchema&&key2==="additionalProperties"&&value2===!0){out[key2]=Type.Any(),changed=!0;continue}let next=honourOpenObjects(value2);if(next!==value2)changed=!0;out[key2]=next}if(!changed)return node;for(let symbol3 of Object.getOwnPropertySymbols(source))out[symbol3]=source[symbol3];return out}function cleanSchemaFor(schema3){let cached=cleanable.get(schema3);if(cached)return cached;let rewritten=honourOpenObjects(schema3);return cleanable.set(schema3,rewritten),rewritten}function prepare(schema3,value2,on){if(!schema3)return value2;if(value2===void 0&&OPTIONAL_KIND in schema3)return;let prepared=value2;if(on==="query")try{prepared=exports_value2.Convert(schema3,prepared)}catch{}try{prepared=exports_value2.Default(schema3,prepared)}catch{}try{prepared=exports_value2.Clean(cleanSchemaFor(schema3),prepared)}catch{}return prepared}function sampleOf(schema3){try{return exports_value2.Create(schema3)}catch{return}}registerStringFormats();var REQUIRED_PROPERTY=45;function propertyName(path8){return path8.replace(/^\//,"").replace(/\//g,".")}function describe2(value2){if(value2===void 0)return"undefined";if(value2===null)return"null";if(typeof value2==="object")return JSON.stringify(value2);return String(value2)}function at(value2,path8){let current=value2;for(let segment of path8.split("/").filter(Boolean)){if(typeof current!=="object"||current===null)return;current=current[segment]}return current}function validate2(schema3,value2,on){if(!schema3)return null;if(exports_value2.Check(schema3,value2))return null;let all=[...exports_value2.Errors(schema3,value2)],errors2=all.filter((error3)=>error3.type!==REQUIRED_PROPERTY),primary=errors2[0]??all[0],path8=primary?.path??"",message=primary?.message??"Invalid value",atRoot=path8==="";return{isSuccess:!1,success:!1,type:"validation",on,property:atRoot?"root":path8,message,summary:atRoot?message:summarise(path8,message,at(value2,path8)),expected:sampleOf(schema3),found:redact(value2),errors:errors2.map((error3)=>({...error3,value:redact(error3.value),summary:summarise(error3.path,error3.message,at(value2,error3.path))}))}}function describeExpectation(message){return message.replace(/^Expected\s+/i,"")}function redact(value2){if(value2===null)return"null";if(Array.isArray(value2))return`array(${value2.length})`;if(value2 instanceof Date)return"Date";if(typeof value2==="object"){let shape={};for(let key2 of Object.keys(value2))shape[key2]=redact(value2[key2]);return shape}if(value2===void 0)return"undefined";return typeof value2}function summarise(path8,message,found){return`Expected property '${propertyName(path8)}' to be ${describeExpectation(message)} but found: ${describe2(redact(found))}`}class RouteCollisionError extends Error{constructor(method,path8){super(`${method} ${path8} is registered twice. Two groups claiming one path is a wiring mistake, not a fallback: which handler answers would depend on registration order.`);this.name="RouteCollisionError"}}function joinPath2(prefix,path8){if(!prefix)return path8;let left=prefix.endsWith("/")?prefix.slice(0,-1):prefix;if(path8==="/"||path8==="")return left||"/";let right=path8.startsWith("/")?path8:`/${path8}`;return`${left}${right}`||"/"}function buildRoutes(groups,options={}){let table2=new Map;for(let group of groups)for(let route of group.routes){let fullPath=joinPath2(group.prefix,route.path),method=route.method,byMethod=table2.get(fullPath);if(!byMethod)byMethod=new Map,table2.set(fullPath,byMethod);if(byMethod.has(method))throw new RouteCollisionError(method,fullPath);byMethod.set(method,{guards:[...group.guards??[],...route.guards??[]],route})}let out={},withSlashAlias=(path8)=>path8==="/"||path8.endsWith("/")?[path8]:[path8,`${path8}/`];for(let[path8,byMethod]of table2){let handlers={};for(let[method,registered2]of byMethod){handlers[method]=async(request,server)=>{let set2=createResponseSet(),response;try{response=await answer(request,server,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});response=finalizeResponse(answered,set2)}if(options.onAfter)try{set2.status=response.status,await options.onAfter({request,set:set2})}catch(error3){console.error("[router] after-handler failed",error3)}return response};let answer=async(request,server,set2)=>{let url=new URL(request.url),params=request.params??{},query=Object.fromEntries(url.searchParams);if(options.onRequest){let early=await options.onRequest({request,set:set2,body:void 0,params,query,server});if(early!==void 0)return finalizeResponse(early,set2)}let body;try{body=await parseBody(request.clone(),registered2.route.type)}catch(error3){if(error3 instanceof BodyParseError){let bodySchema=registered2.route.body;if(bodySchema&&OPTIONAL_KIND in bodySchema)body=void 0;else return new Response(error3.message,{status:error3.status})}else throw error3}body=prepare(registered2.route.body,body,"body"),query=prepare(registered2.route.query,query,"query"),params=prepare(registered2.route.params,params,"params");for(let[target2,schema3,value2]of[["body",registered2.route.body,body],["query",registered2.route.query,query],["params",registered2.route.params,params]]){if(value2===void 0&&schema3&&OPTIONAL_KIND in schema3)continue;let failure=validate2(schema3,value2,target2);if(failure){let headers=new Headers({"content-type":"application/json"});for(let[name2,value3]of Object.entries(set2.headers))if(value3!==void 0)headers.set(name2,String(value3));return new Response(JSON.stringify(failure,null,2),{status:422,headers})}}let guardContext={request,set:set2,body,params,query,server};if(options.beforeHandle){let early=await options.beforeHandle(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}for(let guard5 of registered2.guards){let early=await guard5(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}try{let result=await registered2.route.handler({...options.context,request,params,query,body,set:set2});return finalizeResponse(result,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}}for(let alias2 of withSlashAlias(path8))out[alias2]=handlers}return out}init_websocket();var NOT_FOUND=()=>new Response("NOT_FOUND",{status:404});async function staticAsset(request,assets){if(!assets)return null;if(request.method!=="GET"&&request.method!=="HEAD")return null;let{pathname}=new URL(request.url),prefix=assets.prefix.endsWith("/")?assets.prefix.slice(0,-1):assets.prefix;if(pathname!==prefix&&!pathname.startsWith(`${prefix}/`))return null;let relative;try{relative=decodeURIComponent(pathname.slice(prefix.length))}catch{return new Response("NOT_FOUND",{status:404})}let{join:join9,resolve:resolve2,sep}=await import("path"),root=resolve2(assets.directory),target2=resolve2(join9(root,relative));if(target2!==root&&!target2.startsWith(root+sep))return new Response("NOT_FOUND",{status:404});let file=Bun.file(target2);if(!await file.exists())return null;return new Response(request.method==="HEAD"?null:file)}function serve(options){let routes=buildRoutes(options.groups,{onRequest:options.onRequest,beforeHandle:options.beforeHandle,onError:options.onError,onAfter:options.onAfter,context:options.context}),notFound=options.notFound??NOT_FOUND,socket=options.socket,server=Bun.serve({port:options.port??0,hostname:options.hostname,idleTimeout:options.idleTimeout??30,reusePort:options.reusePort??!0,...options.maxRequestBodyBytes!==void 0?{maxRequestBodySize:options.maxRequestBodyBytes}:{},routes,fetch:async(request,self2)=>{let asset=await staticAsset(request,options.staticAssets);if(asset)return asset;let set2=createResponseSet();if(options.onRequest){let url=new URL(request.url);try{let early=await options.onRequest({request,set:set2,body:void 0,params:{},query:Object.fromEntries(url.searchParams),server:self2});if(early!==void 0)return finalizeResponse(early,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}if(socket){let upgraded=upgradeFor(socket,request,self2);if(upgraded)return upgraded}let missing=await notFound(request),headers=new Headers(missing.headers);for(let[name2,value2]of Object.entries(set2.headers))if(value2!==void 0&&!headers.has(name2))headers.set(name2,String(value2));let text4=await missing.text();return new Response(text4,{status:missing.status,headers})},websocket:socket?websocketHandlers(socket):void 0}),stopped=!1,runShutdown=async()=>{for(let step of options.onStop??[])try{await step()}catch(error3){console.error("[NucleusServer] shutdown step failed",error3)}},port=server.port??0,hostname=server.hostname??"localhost";return{port,hostname,url:`http://${hostname}:${port}`,stop:(closeActiveConnections=!1)=>{let stopping=Promise.resolve(server.stop(closeActiveConnections));if(stopped)return stopping;return stopped=!0,stopping.then(runShutdown)},raw:server}}function operationIdFor(method,path8){let tail2=path8.split("/").filter(Boolean).flatMap((segment)=>segment.startsWith(":")?["by",segment.slice(1)]:segment.split(/[-_]/)).filter(Boolean).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join("");return`${method.toLowerCase()}${tail2}`}function toOpenApiPath(path8){return path8.split("/").map((segment)=>segment.startsWith(":")?`{${segment.slice(1)}}`:segment).join("/")}function pathParametersOf(path8,schema3){let declared=schema3?.properties;return path8.split("/").filter((segment)=>segment.startsWith(":")).map((segment)=>{let name2=segment.slice(1);return{name:name2,in:"path",required:!0,schema:declared?.[name2]??{type:"string"}}})}function queryParametersOf(schema3){let object3=schema3;if(!object3?.properties)return[];return Object.entries(object3.properties).map(([name2,value2])=>({name:name2,in:"query",required:object3.required?.includes(name2)??!1,schema:value2}))}function buildOpenApiDocument(groups,config={}){let info=config.documentation?.info,exclude3=config.exclude??[],isExcluded=(path8)=>exclude3.some((rule)=>typeof rule==="string"?rule===path8:rule.test(path8)),paths={};for(let group of groups)for(let route of group.routes){let declared=route.path==="/"?"":route.path,joined=`${group.prefix??""}${declared}`||"/";if(isExcluded(joined))continue;let openApiPath=toOpenApiPath(joined),method=route.method.toLowerCase(),detail=route.detail,parameters4=[...pathParametersOf(joined,route.params),...queryParametersOf(route.query)],operation={operationId:operationIdFor(route.method,joined),responses:{"200":{}}};if(detail?.tags)operation.tags=detail.tags;if(detail?.summary)operation.summary=detail.summary;if(detail?.description)operation.description=detail.description;if(parameters4.length>0)operation.parameters=parameters4;if(route.body)operation.requestBody={content:{"application/json":{schema:route.body}}};if(paths[openApiPath]=paths[openApiPath]??{},!paths[openApiPath][method])paths[openApiPath][method]=operation}let document={openapi:"3.0.3",info:{title:info?.title??"Nucleus API",description:info?.description??"Auto-generated API documentation",version:info?.version??"1.0.0",...info?.contact?{contact:info.contact}:{},...info?.license?{license:info.license}:{}},tags:config.documentation?.tags??[],paths};if(config.documentation?.servers)document.servers=config.documentation.servers;return document}function viewerHtml(documentUrl,title,description,viewerConfig){let forHtml=(value2)=>value2.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;"),configuration=viewerConfig&&Object.keys(viewerConfig).length>0?` data-configuration="${forHtml(JSON.stringify(viewerConfig))}"`:"";return`<!doctype html>
632
+ `)}deliver(getEmailService(),{to:user.email,subject,html:emailHtml},"[AUTH] login notification").then((report)=>{if(report.level==="warn")logger2.warn(report.message,{userId:params.userId,trustScore,requiresApproval});else logger2.info(report.message,{userId:params.userId})})}}}if(logger2.info("[AUTH] Session saved to DB",{sessionId,userId:params.userId,isNewDevice,requiresApproval,deviceFingerprint,ipAddress:deviceInfo.ipAddress}),deviceTrustMint&&dtTable&&deviceTrustCfg?.enabled)try{let DT2=await Promise.resolve().then(() => (init_DeviceTrust(),exports_DeviceTrust)),DTStore2=await Promise.resolve().then(() => (init_store3(),exports_store)),{randomUUID:randomUUID12}=await import("crypto"),{raw,hash:hash2}=DT2.mintDeviceToken(),ttlSec=parseTimeToSeconds2(deviceTrustCfg.tokenExpiresIn??"30d");await DTStore2.insertDeviceRow(db,dtTable,{id:randomUUID12(),userId:params.userId,tokenHash:hash2,status:deviceTrustMint,originSessionId:sessionId,label:deviceInfo.deviceName||`${deviceInfo.browserName||"Unknown"} on ${deviceInfo.osName||"Unknown"}`,deviceFingerprint,firstSeenIp:deviceInfo.ipAddress,expiresAt:new Date(Date.now()+ttlSec*1000)});let rawDomainDT=authentication.cookieDomain,resolvedDomainDT=rawDomainDT?process.env[rawDomainDT]??rawDomainDT:void 0,domainDT=resolvedDomainDT==="localhost"||resolvedDomainDT===".localhost"?void 0:resolvedDomainDT;deviceTokenToSet=DT2.buildDeviceTokenCookie(raw,{cookieName:deviceTrustCfg.cookieName,cookiePrefix:deviceTrustCfg.cookiePrefix,sameSite:deviceTrustCfg.sameSite,maxAgeSeconds:ttlSec,domain:domainDT,secure:!!domainDT})}catch(dtErr){logger2.warn("[AUTH] Device-trust token mint failed \u2014 continuing",{userId:params.userId,error:dtErr instanceof Error?dtErr.message:String(dtErr)})}return{requiresApproval,sessionId,deviceTokenCookie:deviceTokenToSet??void 0}},storeResetToken:async(userId,token,expiresAt,reqSchemaName)=>{let resetTokensTable=resolveTableForTenant("passwordResetTokens",reqSchemaName);if(!resetTokensTable||!db)return;await db.insert(resetTokensTable).values({userId,tokenHash:createHash12("sha256").update(token).digest("hex"),expiresAt})},getResetToken:async(token,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),resetTokensTable=resolveTableForTenant("passwordResetTokens",reqSchemaName);if(!resetTokensTable||!db)return null;let tokenHash=createHash12("sha256").update(token).digest("hex"),row=(await db.select().from(resetTokensTable).where(eq84(resetTokensTable.tokenHash,tokenHash)).limit(1))[0];if(!row||row.usedAt)return null;return{userId:row.userId,expiresAt:row.expiresAt}},deleteResetToken:async(token,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),resetTokensTable=resolveTableForTenant("passwordResetTokens",reqSchemaName);if(!resetTokensTable||!db)return;let tokenHash=createHash12("sha256").update(token).digest("hex");await db.delete(resetTokensTable).where(eq84(resetTokensTable.tokenHash,tokenHash))},revokeSessionInDb:async(sessionId,reason,reqSchemaName)=>{let revokeTable=resolveTableForTenant("userSessions",reqSchemaName)||resolveTableForTenant("user_sessions",reqSchemaName)||resolveTableForTenant("sessions",reqSchemaName)||sessionsTable;if(!revokeTable||!db)return;await db.update(revokeTable).set({isActive:!1,revokedAt:new Date,revokedReason:reason}).where(eq83(revokeTable.id,sessionId)),logger2.info("[AUTH] Session revoked in DB",{sessionId,reason})},sendResetEmail:async(email,token,request,context)=>{if(isEmailExempt(email,authentication?.emailExemptDomains))return logger2.info("[AUTH] Skipping reset email \u2014 domain exempt",{email}),{sent:!1,reason:"exempt"};let mailer=getEmailService();if(!mailer?.isAvailable())return logger2.warn("[AUTH] Cannot send reset email \u2014 no email provider configured"),{sent:!1,reason:"no_provider"};let configuredResetUrl=authentication.passwordReset?.redirectUrl||"http://localhost:3000/reset-password",resetUrl=request?buildEmailActionLink({request,configuredUrl:configuredResetUrl,path:extractConfiguredPath(configuredResetUrl,"/reset-password"),query:{token},allowedOrigins:trustedAppOrigins()}):`${configuredResetUrl}?token=${token}`,content=renderPasswordResetEmail(authentication.passwordReset?.email,{link:resetUrl,locale:context?.locale,user:context?.user??{email}}),result=await mailer.sendEmail({to:email,subject:content.subject,html:content.html,...content.text===void 0?{}:{text:content.text}});if(result?.success===!1){let refused=result.rejected;return{sent:!1,reason:Array.isArray(refused)&&refused.length>0?"rejected":"error",detail:result.error}}return{sent:!0}},storeMagicToken:async(params,reqSchemaName)=>{let magicTokensTable=resolveTableForTenant("magicLinkTokens",reqSchemaName);if(!magicTokensTable||!db)return;await db.insert(magicTokensTable).values({userId:params.userId,email:params.email,tokenHash:params.tokenHash,expiresAt:params.expiresAt})},getMagicToken:async(tokenHash,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),magicTokensTable=resolveTableForTenant("magicLinkTokens",reqSchemaName);if(!magicTokensTable||!db)return null;let row=(await db.select().from(magicTokensTable).where(eq84(magicTokensTable.tokenHash,tokenHash)).limit(1))[0];if(!row||row.usedAt)return null;return{userId:row.userId,email:row.email,tokenHash:row.tokenHash,expiresAt:row.expiresAt}},deleteMagicToken:async(tokenHash,reqSchemaName)=>{let{eq:eq84}=__require("drizzle-orm"),magicTokensTable=resolveTableForTenant("magicLinkTokens",reqSchemaName);if(!magicTokensTable||!db)return;await db.delete(magicTokensTable).where(eq84(magicTokensTable.tokenHash,tokenHash))}}}),logger2.info("[AUTH] Routes registered")}}if(resolvedOptions.storage?.enabled&&resolvedOptions.storage?.cdn?.enabled){let{createCdnRoutes:createCdnRoutes2,mergeCdnConfig:mergeCdnConfig2,mergeStorageConfig:mergeStorageConfig2}=(init_storage2(),__toCommonJS(exports_storage)),cdnConfig=mergeCdnConfig2(resolvedOptions.storage.cdn),storageConfig=mergeStorageConfig2(resolvedOptions.storage),filesTable=schemaTables.files;if(useRoutes(plugin,createCdnRoutes2({cdn:cdnConfig,storagePath:storageConfig.basePath,logger:logger2,getStorageProvider:()=>storageProvider,buildStorageProvider,authorizeFile:db?async({id,request,schemaName:reqSchemaName})=>{let tables2=schemaTables;if(reqSchemaName&&tenantRegistry){let ctx=tenantRegistry.getSchemaContext(reqSchemaName);if(ctx?.schemaTables)tables2=ctx.schemaTables}if(await checkAttachmentFileAccess({db,schemaTables:tables2,fileId:id,userId:request.headers.get("x-user-id")})==="denied")return!1;if(await isVerificationSignatureFile({db,schemaTables:tables2,fileId:id}))return!1;return!0}:void 0,getFileRecord:filesTable&&db?async(id,reqSchemaName)=>{let tbl=filesTable;if(reqSchemaName&&tenantRegistry){let ctx=tenantRegistry.getSchemaContext(reqSchemaName);if(ctx?.schemaTables.files)tbl=ctx.schemaTables.files}let t=tbl,result=await db.select().from(t).where(eq83(t.id,id)).limit(1);if(result.length===0)return null;let record4=result[0];return{id:record4.id,name:record4.name,path:record4.path,mime_type:record4.mimeType||record4.mime_type,original_name:record4.originalName||record4.original_name,is_active:record4.isActive??record4.is_active}}:void 0})),logger2.info(`[Storage] CDN routes enabled at ${cdnConfig.basePath}`),filesTable&&db){let{createResumableRoutes:createResumableRoutes2}=(init_resumable(),__toCommonJS(exports_resumable)),resumable=createResumableRoutes2({basePath:storageConfig.basePath,storage:storageConfig,logger:logger2,getUserId:(request)=>request.headers.get("x-user-id"),canUpload:(request)=>{if(resolvedOptions.authorization?.enabled===!1)return!0;return checkAuthorizationFromJWT({userClaims:decodeHeaderList(request.headers.get("x-user-claims")),userRoles:decodeHeaderList(request.headers.get("x-user-roles")),claimScopes:decodeClaimScopesHeader(request.headers.get("x-user-claim-scopes")),method:"POST",entity:"files",logger:logger2,requireClaimSpecificity:resolvedOptions.authorization?.requireClaimSpecificity}).authorized},register:async(input)=>{let nodePath=__require("path"),{rename:rename6}=__require("fs/promises"),{randomUUID:randomUUID12}=__require("crypto"),id=randomUUID12(),extension2=nodePath.extname(input.originalName),storedName=`${id}${extension2}`,destination=nodePath.join(storageConfig.basePath,storedName);try{await rename6(input.partPath,destination)}catch(error3){return logger2.error("[Storage] A finished upload could not be moved into place",{error:error3}),null}let uploaded={id,name:storedName,originalName:input.originalName,path:storageConfig.basePath,mimeType:input.mimeType,size:input.size,createdAt:new Date},{buildFileRecordPayload:buildFileRecordPayload2,scheduleUploadMediaProcessing:scheduleUploadMediaProcessing2}=(init_storage2(),__toCommonJS(exports_storage)),t=filesTable,payload={...buildFileRecordPayload2(uploaded,input.userId),type:input.type},row=(await db.insert(t).values(payload).returning())[0];if(!row?.id)return null;return scheduleUploadMediaProcessing2([uploaded],{storagePath:storageConfig.basePath,media:{transform:mergeTransformConfig(resolvedOptions.storage?.cdn?.transform),video:mergeVideoConfig(resolvedOptions.storage?.cdn?.video),pdf:mergePdfConfig(resolvedOptions.storage?.cdn?.pdf)},logger:logger2}),{id:String(row.id)}}});useRoutes(plugin,resumable.plugin),setInterval(()=>{resumable.sweep(Date.now()).then((removed)=>{if(removed>0)logger2.info(`[Storage] Reclaimed ${removed} abandoned upload(s)`)}).catch(()=>{})},3600000).unref?.(),logger2.info("[Storage] Resumable uploads enabled at /uploads")}}if(resolvedOptions.notification?.enabled&&db){let notificationConfig=resolvedOptions.notification;if(notificationConfig.endpoints?.enabled!==!1){warnOnEntityBasePathCollision("Notification",notificationConfig.endpoints?.basePath||"/notifications",resolvedOptions.entities,logger2);let{routes:notificationRoutes}=createNotificationRoutes({db,schemaTables,config:notificationConfig,logger:logger2,getEmailService,tenantRegistry,getTenantRegistry:()=>tenantRegistry});useRoutes(plugin,notificationRoutes),logger2.info(`[Notification] Routes registered at ${notificationConfig.endpoints?.basePath||"/notifications"}`)}}if(resolvedOptions.verification?.enabled&&db){let{routes:verificationRoutes}=createVerificationRoutes({db,schemaTables,config:resolvedOptions.verification,notificationConfig:resolvedOptions.notification,logger:logger2,getEmailService,tenantRegistry,getTenantRegistry:()=>tenantRegistry});useRoutes(plugin,verificationRoutes)}if(resolvedOptions.backup?.enabled&&db){let{createBackupRoutes:createBackupRoutes2}=(init_backup(),__toCommonJS(exports_backup)),{routes:backupRoutes}=createBackupRoutes2({db,logger:logger2,config:{enabled:!0,basePath:resolvedOptions.backup.basePath||"/admin/backup",storagePath:resolvedOptions.backup.storagePath||"./backups",format:resolvedOptions.backup.format||"json",maxBackups:resolvedOptions.backup.maxBackups||50,allowRestore:resolvedOptions.backup.allowRestore??!0,excludeTables:resolvedOptions.backup.excludeTables||["audit_logs","backup_logs"],encryptionKey:resolvedOptions.backup.encryptionKey?process.env[resolvedOptions.backup.encryptionKey]||resolvedOptions.backup.encryptionKey:void 0,schedule:{enabled:resolvedOptions.backup.schedule?.enabled??!1,cron:resolvedOptions.backup.schedule?.cron||"0 2 * * *",retentionDays:resolvedOptions.backup.schedule?.retentionDays||30,timeZone:resolvedOptions.backup.schedule?.timeZone}},schemaTables,schemaName:targetSchemaName,getTenantRegistry:()=>tenantRegistry,lock:getRedisManager()});useRoutes(plugin,backupRoutes),logger2.info("[Backup] Routes registered",{basePath:resolvedOptions.backup.basePath||"/admin/backup",scheduleEnabled:resolvedOptions.backup.schedule?.enabled??!1})}if(resolvedOptions.authorization?.endpointDiscovery?.enabled&&db&&resolvedOptions.authentication?.mode!=="consumer"){let{createAuthorizationDiscoveryRoutes:createAuthorizationDiscoveryRoutes2}=(init_authorization(),__toCommonJS(exports_authorization));useRoutes(plugin,createAuthorizationDiscoveryRoutes2({db,schemaTables,logger:logger2,discovery:resolvedOptions.authorization.endpointDiscovery,readState:async(key2)=>{let rm3=getRedisManager();if(!rm3)return null;let res=await rm3.read(key2);return res?.success?res.data:null}})),logger2.info("[Authorization] Endpoint-discovery routes registered",{discover:"/authorization/discover",manifest:"/authorization/route-manifest"})}let pubsubClientManager=null;if(resolvedOptions.pubsub?.enabled){let redis=getRedisManager();if(redis){let pubsubConfig=resolvedOptions.pubsub,{routes:pubsubRoutes,socket:pubsubSocket,clientManager}=createPubSubRoutes({redis,logger:logger2,basePath:pubsubConfig.basePath||"/subs",wsPath:pubsubConfig.wsPath||"/api/events/subscribe",pubsubName:pubsubConfig.pubsubName||"pubsub-redis",maxClientsPerUser:pubsubConfig.maxClientsPerUser??10,maxTopicsPerClient:pubsubConfig.maxTopicsPerClient??DEFAULT_MAX_TOPICS_PER_CLIENT,wsIdleTimeout:pubsubConfig.wsIdleTimeout??120,ack:{enabled:pubsubConfig.ack?.enabled??!0,ttlSeconds:pubsubConfig.ack?.ttlSeconds??300,maxRetries:pubsubConfig.ack?.maxRetries??3,retryIntervalMs:pubsubConfig.ack?.retryIntervalMs??5000},presence:{enabled:pubsubConfig.presence?.enabled??!0,debounceMs:pubsubConfig.presence?.debounceMs??5000},cleanupIntervalMs:pubsubConfig.cleanupIntervalMs??60000,daprApiToken:pubsubConfig.daprApiToken,getLiveMonitoringService:()=>liveMonitoringService,authenticate:envResolved.accessTokenSecret?createHandshakeAuthenticator({accessTokenSecret:envResolved.accessTokenSecret,tokenNames,issuer:authentication?.accessToken?.issuer,audience:authentication?.accessToken?.audience,requireLiveSession:authentication?.mode!=="consumer",db,resolveSessionsTable:(tenant)=>{let tables2=schemaTables;if(tenant&&tenantRegistry){let ctx=tenantRegistry.getSchemaContext(tenant);if(ctx?.schemaTables)tables2=ctx.schemaTables}return tables2?.userSessions??null},logger:logger2}):void 0});useRoutes(plugin,pubsubRoutes),recordSocket(pubsubSocket),recordAdapterStep((app)=>{mountWebSocketRoute(app,pubsubSocket)}),pubsubClientManager=clientManager,logger2.info("[PubSub] Enabled",{basePath:pubsubConfig.basePath||"/subs",wsPath:pubsubConfig.wsPath||"/api/events/subscribe"})}else logger2.warn("[PubSub] pubsub is enabled but Redis is not configured. Disabling PubSub.")}if(resolvedOptions.chat?.enabled&&db){let chatConfig=mergeChatConfig(resolvedOptions.chat),chatStorageConfig=mergeStorageConfig(resolvedOptions.storage),attachmentsAvailable=resolvedOptions.storage?.enabled===!0&&resolvedOptions.storage?.cdn?.enabled===!0&&chatConfig.attachments.enabled,cdnBasePath=resolvedOptions.storage?.cdn?.basePath||"/cdn",cdnMedia={transform:mergeTransformConfig(resolvedOptions.storage?.cdn?.transform),video:mergeVideoConfig(resolvedOptions.storage?.cdn?.video),pdf:mergePdfConfig(resolvedOptions.storage?.cdn?.pdf)},{routes:chatRoutes}=createChatRoutes({db,schemaTables,config:chatConfig,logger:logger2,broadcaster:pubsubClientManager,getTenantRegistry:()=>tenantRegistry,storageConfig:chatStorageConfig,attachmentsAvailable,cdnBasePath,cdnMedia});useRoutes(plugin,chatRoutes),logger2.info("[Chat] Enabled",{basePath:chatConfig.basePath,attachmentsAvailable,realtime:pubsubClientManager!==null})}if(resolvedOptions.payment?.enabled&&db){let{createPaymentService:createPaymentService2}=(init_Payment(),__toCommonJS(exports_Payment)),{createPaymentRoutes:createPaymentRoutes2}=(init_payment(),__toCommonJS(exports_payment)),paymentService=createPaymentService2(resolvedOptions);if(paymentService){let paymentConfig=resolvedOptions.payment,marketplaceServices=null;if(paymentConfig?.marketplace?.enabled){let{createMarketplaceServices:createMarketplaceServices2}=(init_Payment(),__toCommonJS(exports_Payment));marketplaceServices=createMarketplaceServices2({options:resolvedOptions,logger:logger2,getDb:()=>db,provider:paymentService.providerInstance,schemaTables})}let paymentRoutes=createPaymentRoutes2({provider:paymentService.providerInstance,webhookSecret:paymentService.webhookSecret,getPayoutService:()=>marketplaceServices?.payoutService??null,basePath:paymentConfig?.basePath||"/payment",defaultCurrency:paymentConfig?.defaultCurrency||"TRY",defaultLocale:paymentConfig?.defaultLocale||"tr",successRedirectUrl:paymentConfig?.successRedirectUrl||"/payment/success",failedRedirectUrl:paymentConfig?.failedRedirectUrl||"/payment/failed",errorRedirectUrl:paymentConfig?.errorRedirectUrl||"/payment/error",callbackUrl:paymentConfig?.callbackUrl,savedMethodsEnabled:paymentConfig?.savedMethodsEnabled??!0,threeDSecureEnabled:paymentConfig?.threeDSecureEnabled??!0,subMerchantsEnabled:paymentConfig?.subMerchantsEnabled??!1,transactionsTable:schemaTables.paymentTransactions??schemaTables.payment_transactions,methodsTable:schemaTables.paymentMethods??schemaTables.payment_methods,webhookLogsTable:schemaTables.paymentWebhookLogs??schemaTables.payment_webhook_logs,subMerchantsTable:schemaTables.paymentSubMerchants??schemaTables.payment_sub_merchants,commissionSplitsTable:schemaTables.paymentCommissionSplits??schemaTables.payment_commission_splits,productsTable:schemaTables.paymentProducts??schemaTables.payment_products,pricesTable:schemaTables.paymentPrices??schemaTables.payment_prices,customersTable:schemaTables.paymentCustomers??schemaTables.payment_customers,subscriptionsTable:schemaTables.paymentSubscriptions??schemaTables.payment_subscriptions,invoicesTable:schemaTables.paymentInvoices??schemaTables.payment_invoices,db,logger:logger2});if(useRoutes(plugin,paymentRoutes),logger2.info("[Payment] Routes registered",{basePath:paymentConfig?.basePath||"/payment",provider:paymentService.provider}),marketplaceServices){let{createMarketplaceRoutes:createMarketplaceRoutes2}=(init_marketplace(),__toCommonJS(exports_marketplace)),services=marketplaceServices;createMarketplaceRoutes2(plugin,{getMarketplaceService:()=>services.marketplaceService,getPayoutService:()=>services.payoutService,basePath:paymentConfig?.basePath||"/payment",logger:logger2}),logger2.info("[Payment] Marketplace routes registered",{basePath:`${paymentConfig?.basePath||"/payment"}/marketplace`})}}}let cohortConfig=authentication?.cohorts;if(cohortConfig?.enabled!==!1&&!isConsumerMode&&db){let cohortBasePath=cohortConfig?.basePath||"/auth/admin/cohorts",resolveTable=(key2,fallback)=>schemaTables[key2]??(fallback?schemaTables[fallback]:null)??null,resolvedCohortsTable=resolveTable("userCohorts","user_cohorts");if(!resolvedCohortsTable)logger2.warn("[Cohort] user_cohorts table not found in schema \u2014 cohort routes will be inactive. Re-generate schema with nucleus-core >= 0.9.120");if(useRoutes(plugin,createCohortRoutes({db,logger:logger2,cohortsTable:resolvedCohortsTable,usersTable:resolveTable("users"),sessionsTable:resolveTable("userSessions","user_sessions"),rolesTable:resolveTable("roles"),userRolesTable:resolveTable("userRoles","user_roles"),profilesTable:resolveTable("profiles"),basePath:cohortBasePath,get defaultRole(){return resolvedOptions.authentication?.defaultRole},get defaultRoles(){return resolvedOptions.authentication?.defaultRoles},emailExemptDomains:authentication?.emailExemptDomains,passwordPolicy:authentication?.passwordPolicy})),resolvedCohortsTable)logger2.info("[Cohort] Routes registered",{basePath:cohortBasePath})}if(resolvedOptions.configManagement?.enabled){let configBasePath=resolvedOptions.configManagement.basePath||"/nucleus/config";useRoutes(plugin,createConfigRoutes({logger:logger2,resolvedOptions,configFilePath,basePath:configBasePath,db,schemaTables,getRedis:()=>{let redis=getRedisManager();if(!redis)return null;return{read:async(key2)=>{let r=await redis.read(key2);return{success:r.success,data:r.success?r.data:null}},create:async(key2,value2)=>{return{success:(await redis.create(key2,value2)).success}}}},onConfigUpdate:(section,_newValue)=>{logger2.info(`[ConfigManagement] Section "${section}" updated in-memory`,{section})}})),logger2.info(`[ConfigManagement] Routes enabled at ${configBasePath}`)}if(resolvedOptions.secrets?.enabled){let secretsBasePath=resolvedOptions.secrets.basePath||"/secrets";warnOnEntityBasePathCollision("Secrets",secretsBasePath,resolvedOptions.entities,logger2),useRoutes(plugin,createSecretsRoutes({logger:logger2,basePath:secretsBasePath,db,schemaTables,resolvedOptions,getService:()=>secretsService,getEmailService,getStorageProvider:()=>storageProvider,buildStorageProvider,adminRoles:resolvedOptions.secrets.adminRoles})),logger2.info(`[Secrets] Routes enabled at ${secretsBasePath}`)}if(resolvedOptions.integrations?.enabled){let integrationsBasePath=resolvedOptions.integrations.basePath||"/integrations";warnOnEntityBasePathCollision("Integrations",integrationsBasePath,resolvedOptions.entities,logger2),useRoutes(plugin,createIntegrationRoutes({logger:logger2,basePath:integrationsBasePath,db,schemaTables,resolvedOptions,getEncryptionKey:()=>resolveMasterKey(resolvedOptions.secrets?.encryptionKey)??null,getLockStore:()=>getRedisManager(),publish:(topic,payload)=>pubsubClientManager?.broadcastEvent(topic,payload),adminRoles:resolvedOptions.integrations.adminRoles}))}recordBootStep(()=>{let assignments=resolvedOptions.authorization?.seed?.roleClaimAssignments;if(!assignments?.length)return;let ownership=[];for(let entity of resolvedOptions.entities??[]){let table2=entity.table_name;if(!table2)continue;for(let column3 of entity.columns??[]){let hasDefault=column3.default!==void 0||!!column3.defaultRaw||!!column3.generatedAlwaysAs;if(column3.notNull&&!column3.nullable&&!hasDefault)ownership.push({table:table2,column:column3.name})}}for(let line of describeUnstamped(findUnstampedOwnership(assignments,ownership)))logger2.warn(line)}),recordBootStep((app)=>{let requiredBody=requiredBodyCeiling({storageEnabled:resolvedOptions.storage?.enabled,maxFileSizeBytes:resolvedOptions.storage?.maxFileSizeBytes,maxFiles:resolvedOptions.storage?.formData?.maxFiles}),complaint=bodyCeilingComplaint({configured:app?.config?.serve?.maxRequestBodySize,required:requiredBody});if(complaint)logger2.error(`[Storage] ${complaint}`);else if(requiredBody!==null){let configuredCeiling=app?.config?.serve?.maxRequestBodySize,mb2=(bytes)=>`${Math.round(bytes/1048576)} MB`;logger2.info(`[Storage] Uploads are configured up to ${mb2(requiredBody)}, and the server accepts ${configuredCeiling?mb2(configuredCeiling):"Bun's default"}.`)}let memoryComplaint=memoryCeilingComplaint({required:requiredBody,cgroupLimit:readCgroupLimitBytes()});if(memoryComplaint)logger2.error(`[Storage] ${memoryComplaint}`);let memoryAdvice=readRuntimeMemoryAdvice();if(memoryAdvice){let mib=(bytes)=>`${Math.round(bytes/1024/1024)} MiB`;logger2.warn(`[Runtime] The JS engine sizes its heap for ${mib(memoryAdvice.hostTotal)} but this container is capped at ${mib(memoryAdvice.cgroupLimit)} \u2014 it feels no memory `+"pressure and may grow past the limit and be OOM-killed. Raising the container memory limit delays this; no runtime option we have measured prevents it.")}let port=Number(process.env.PORT)||3000,appId=resolvedOptions.appId||"nucleus",mode=resolvedOptions.mode||"production";console.log(""),console.log(` \x1B[32m\uD83D\uDE80 ${appId}\x1B[0m \x1B[90mv${Date.now()}\x1B[0m`),console.log(` \x1B[36m\u279C\x1B[0m Local: \x1B[36mhttp://localhost:${port}\x1B[0m`),console.log(` \x1B[36m\u279C\x1B[0m Mode: \x1B[33m${mode}\x1B[0m`),console.log("")});let shuttingDown=!1,drainResources=async(trigger)=>{if(shuttingDown)return;shuttingDown=!0,logger2.info(`[Shutdown] ${trigger} \u2014 draining resources`);try{await lifecycleRecorder?.recordStop(trigger)}catch{}try{liveMonitoringService?.stop(),monitoringService?.stop(),secretsService?.stop(),storageProvider?.close()}catch(err){logger2.warn("[Shutdown] failed stopping monitoring",{error:err instanceof Error?err.message:String(err)})}try{let redisClient=getRedisManager()?.getDirectClient?.();if(redisClient)await redisClient.quit()}catch(err){logger2.warn("[Shutdown] failed closing Redis",{error:err instanceof Error?err.message:String(err)})}try{for(let timer of backgroundIntervals)clearInterval(timer);backgroundIntervals.length=0}catch(err){logger2.warn("[Shutdown] failed clearing background intervals",{error:err instanceof Error?err.message:String(err)})}try{let{destroyAckCleanup:destroyAckCleanup2}=await Promise.resolve().then(() => (init_ack_manager(),exports_ack_manager));destroyAckCleanup2()}catch{}try{if(dbPool)await dbPool.end()}catch(err){logger2.warn("[Shutdown] failed draining DB pool",{error:err instanceof Error?err.message:String(err)})}logger2.info("[Shutdown] complete")};if(recordShutdownStep(async()=>{await drainResources("server stop")}),resolvedOptions.gracefulShutdown!==!1){let onSignal=(signal)=>{drainResources(signal).finally(()=>process.exit(0))};process.once("SIGTERM",()=>onSignal("SIGTERM")),process.once("SIGINT",()=>onSignal("SIGINT"))}return recordAdapterStep((app)=>{for(let step of getRecordedBootSteps())app.onStart(step);for(let step of getRecordedShutdownSteps())app.onStop(step)}),lastMountedSocket=getRecordedSocket(),lastStaticAssets=getRecordedStaticAssets(),lastBootSteps=getRecordedBootSteps(),lastShutdownSteps=getRecordedShutdownSteps(),lastMountedGroups=resolveOverrides(endRouteRecording(),logger2),lastAuthMiddleware=authMiddleware,lastErrorHandler=errorResponder,lastAfterHandler=afterHandler,plugin}init_createUserAccount();init_utils6();function isNucleusRuntime(value2){return typeof value2==="object"&&value2!==null&&typeof Reflect.get(value2,"sendNotification")==="function"&&typeof Reflect.get(value2,"sendEmail")==="function"}init_Logger2();function actorOf2(request){let id=request.headers.get("x-user-id");return{id:id===null||id===""?null:id,roles:decodeHeaderList(request.headers.get("x-user-roles")),claims:decodeHeaderList(request.headers.get("x-user-claims"))}}function actorMaySee(actor,required3){let roleOk=required3.roles===void 0||required3.roles.some((role)=>actor.roles.includes(role)),claimOk=required3.claims===void 0||required3.claims.some((claim)=>actor.claims.includes(claim));return roleOk&&claimOk}var defaultEnvelope={success:(data)=>({success:!0,data:data??null}),failure:(failure)=>({success:!1,error:failure.code,message:failure.message,...failure.details===void 0?{}:{details:failure.details}})};function failureOf(error3){if(error3 instanceof ActionError)return{status:error3.status,code:error3.code,message:error3.message,details:error3.details};if(error3 instanceof IdempotencyConflictError)return{status:409,code:"idempotency_key_reused",message:error3.message};if(error3 instanceof ScopeViolationError)return{status:403,code:"scope_violation",message:"This write is outside your scope"};if(error3 instanceof Error){let constraint=toConstraintError(error3);if(constraint!==null)return{status:409,code:"constraint_violation",message:constraint.message,details:{kind:constraint.kind,constraint:constraint.constraint,columns:[...constraint.columns],table:constraint.table}}}if(isRetryable(error3))return{status:409,code:"serialization_failure",message:"The request conflicted with a concurrent one; repeat it"};return null}var ACTION_SCOPE="data.action",DEFAULT_IDEMPOTENCY_HEADER="Idempotency-Key",KEY_MAX_LENGTH=255;function schemaFor(host,action,request){if(action.scope==="main")return host.mainSchema;return host.schemaOf?.(request)??request.headers.get("x-tenant-schema")??host.mainSchema}function idempotencyOf(action,call,actorId){let settings=action.idempotency;if(settings===void 0)return null;let key2=call.request.headers.get(settings.header??DEFAULT_IDEMPOTENCY_HEADER)?.trim();if(key2===void 0||key2==="")return settings.required===!0?{status:400,code:"idempotency_key_required",message:"The Idempotency-Key header is required"}:null;if(key2.length>KEY_MAX_LENGTH)return{status:400,code:"idempotency_key_invalid",message:"The idempotency key is too long"};return{key:key2,action:action.name,actor:actorId??"",payloadHash:payloadHash({body:call.body,query:call.query,params:call.params}),ttlSeconds:settings.ttlSeconds??DEFAULT_IDEMPOTENCY_TTL_SECONDS}}function isFailure(value2){return value2!==null&&"status"in value2}function render(call,envelope,failure){return call.set.status=failure.status,envelope.failure(failure)}async function runAction(host,action,call){let log4=(host.logger??logger).scoped(ACTION_SCOPE),envelope=host.envelope??defaultEnvelope,actor=actorOf2(call.request),schema3=schemaFor(host,action,call.request),claim=idempotencyOf(action,call,actor.id);if(isFailure(claim))return render(call,envelope,claim);let nucleus=call.nucleus,ctx={request:call.request,actor,schema:schema3,set:call.set,nucleus:call.nucleus},db=host.db??nucleusDataOf(nucleus)?.db;if(db===void 0)throw new StoreError(`Action "${action.name}" has no database: the host gave no db and the server is not served by createNucleusServer`);let options={db,schema:schema3,mainSchema:host.mainSchema,scope:host.scopeFor(actor),tables:host.tables,relations:host.relations,logger:log4,retry:action.retry,isolationLevel:action.isolationLevel,readOnly:action.readOnly,notifier:nucleus===null?void 0:(params)=>nucleus.sendNotification(params)};try{let outcome=await runUnitOfWork(options,async(unit)=>{call.set.status=void 0;let keyRowId=null;if(claim!==null){let taken=await claimIdempotencyKey(executorOf2(unit),schema3,claim);if(taken.kind==="replay")return{status:taken.status,body:envelope.success(taken.body),replayed:!0};keyRowId=taken.id}let result=await action.handler({params:call.params,body:call.body,query:call.query},unit,ctx),status=call.set.status??200;if(claim!==null&&keyRowId!==null)await completeIdempotency(executorOf2(unit),schema3,keyRowId,status,result);return{status,body:envelope.success(result),replayed:!1}});if(call.set.status=outcome.status,outcome.replayed)call.set.headers["idempotent-replay"]="true";return outcome.body}catch(error3){let failure=failureOf(error3);if(failure===null)throw error3;return log4.warn("Action refused",{action:action.name,status:failure.status,code:failure.code}),render(call,envelope,failure)}}function accessGuard(spec,host){if(spec.public===!0&&spec.roles===void 0&&spec.claims===void 0)return null;let envelope=host.envelope??defaultEnvelope;return({request,set:set2})=>{let actor=actorOf2(request);if(actor.id===null&&spec.public!==!0)return set2.status=401,envelope.failure({status:401,code:"unauthorized",message:"Sign in first"});if(!actorMaySee(actor,spec))return set2.status=403,envelope.failure({status:403,code:"forbidden",message:"You may not do this"});return}}function defineActionFor(){return function(spec){return{name:spec.name,method:spec.method,path:spec.path,toRoute(host){let guard5=accessGuard(spec,host);return defineRoute({method:spec.method,path:spec.path,isPublic:spec.public,body:spec.body,query:spec.query,params:spec.params,response:spec.response,detail:{summary:spec.name,tags:["Actions"],...spec.detail},guards:guard5===null?[]:[guard5],handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,spec,{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}}var defineAction=defineActionFor();function actionGroup(host,actions){let names3=new Set;for(let action of actions){if(names3.has(action.name))throw Error(`Two actions are named "${action.name}"`);names3.add(action.name)}return{routes:actions.map((action)=>action.toRoute(host))}}function isPlain(value2){return!Array.isArray(value2)&&!(value2 instanceof Date)}function jsonOfValue(value2){if(value2===null||typeof value2==="string"||typeof value2==="boolean")return value2;if(typeof value2==="number")return Number.isFinite(value2)?value2:null;if(typeof value2==="bigint")return value2.toString();if(value2 instanceof Date)return value2.toISOString();if(Array.isArray(value2))return value2.map((item)=>jsonOfValue(item));let out={};if(!isPlain(value2))return out;for(let[key2,item]of Object.entries(value2))if(item!==void 0)out[key2]=jsonOfValue(item);return out}init_utils5();var RESERVED_QUERY_NAMES=["page","limit","after","filters","sort"],OPERATORS2=["eq","neq","gt","gte","lt","lte","like","ilike"],LISTS2=["in","notIn"];function isRecord8(value2){return typeof value2==="object"&&value2!==null&&!Array.isArray(value2)}function jsonOf2(name2,text4){try{return JSON.parse(text4)}catch{throw new ViewError(`"${name2}" is not valid JSON`)}}function scalarOf5(name2,value2){if(typeof value2==="string"||typeof value2==="number"||typeof value2==="boolean")return value2;throw new ViewError(`"${name2}": the value must be a string, a number or a boolean`)}function opsOf(entry){let{operator,field:field2}=entry;if(typeof operator!=="string")throw new ViewError('A filter needs an "operator"');let label2=`Filter on "${String(field2)}"`,one=OPERATORS2.find((o)=>o===operator);if(one!==void 0)return{[one]:scalarOf5(label2,entry.value)};let list3=LISTS2.find((o)=>o===operator);if(list3!==void 0){let values=entry.value;if(!Array.isArray(values))throw new ViewError(`${label2}: "${operator}" takes an array`);return{[list3]:values.map((v)=>scalarOf5(label2,v))}}if(operator==="isNull")return{isNull:!0};if(operator==="isNotNull")return{isNull:!1};throw new ViewError(`${label2}: unknown operator "${operator}"`)}function parseFilters(text4){if(text4===void 0||text4==="")return{};let list3=jsonOf2("filters",text4);if(!Array.isArray(list3))throw new ViewError('"filters" must be a JSON array');let out={};for(let entry of list3){if(!isRecord8(entry)||typeof entry.field!=="string")throw new ViewError('A filter is { "field", "operator", "value" }');let ops=opsOf(entry),known=out[entry.field]??{};for(let key2 of Object.keys(ops))if(Object.hasOwn(known,key2))throw new ViewError(`Two "${key2}" filters on "${entry.field}"`);out[entry.field]={...known,...ops}}return out}function directionOf(value2){if(value2==="asc"||value2==="desc")return value2;throw new ViewError('A sort direction is "asc" or "desc"')}function parseSort(text4){if(text4===void 0||text4.trim()==="")return;let trimmed=text4.trim();if(!trimmed.startsWith("["))return trimmed.split(",").map((part)=>{let name2=part.trim(),desc9=name2.startsWith("-"),field2=desc9?name2.slice(1):name2;if(field2==="")throw new ViewError("An empty sort field");return{field:field2,direction:desc9?"desc":"asc"}});let list3=jsonOf2("sort",trimmed);if(!Array.isArray(list3))throw new ViewError('"sort" must be a JSON array');return list3.map((entry)=>{if(!isRecord8(entry)||typeof entry.field!=="string")throw new ViewError('A sort is { "field", "direction" }');return{field:entry.field,direction:directionOf(entry.direction)}})}function positive2(name2,text4,fallback){if(text4===null||text4==="")return fallback;let value2=Number(text4);if(!Number.isInteger(value2)||value2<1)throw new ViewError(`"${name2}" must be a positive integer`);return value2}function parseViewQuery(url){let query=url.searchParams,params={};for(let name2 of new Set(query.keys())){if(RESERVED_QUERY_NAMES.includes(name2))continue;let values=query.getAll(name2);params[name2]=values.length===1&&values[0]!==void 0?values[0]:values}let after=query.get("after")??void 0;if(after!==void 0&&query.has("page"))throw new ViewError('Send "page" or "after", not both');return{params,filters:parseFilters(query.get("filters")??void 0),sort:parseSort(query.get("sort")??void 0),page:positive2("page",query.get("page"),1)??1,limit:positive2("limit",query.get("limit"),void 0),after:after===""?void 0:after}}function refusal(error3){if(error3 instanceof ViewParamError)return new ActionError(422,"invalid_view_params",error3.message,{param:error3.param});return new ActionError(422,"invalid_view_request",error3.message)}function requestOf(view,ctx,paging){let url=new URL(ctx.request.url),query=parseViewQuery(url);if(paging==="cursor"&&url.searchParams.has("page"))throw new ViewError('This view pages with "after", not "page"');let size=query.limit??view.plan.limit,offset=paging==="offset"?(query.page-1)*size:void 0;return{request:{params:view.parseParams(query.params),filters:query.filters,sort:query.sort,limit:query.limit,offset,after:query.after===void 0?void 0:decodeViewCursor(query.after,query.sort)},page:query.page,offset:offset??0,sort:query.sort}}async function runViewCall(view,paging,unit,ctx){try{let{request,page,offset,sort}=requestOf(view,ctx,paging),result=await unit.store.view(view,request),items=result.items.map((row)=>jsonOfValue(row));if(paging==="cursor"){let nextCursor=result.next===null?null:encodeViewCursor(sort,result.next);return{items,meta:{limit:result.limit,hasNextPage:result.hasNextPage,nextCursor}}}let total=await unit.store.countView(view,request);return{items,meta:{...buildPaginationMeta(page,result.limit,offset,total)}}}catch(error3){if(error3 instanceof ViewParamError||error3 instanceof ViewError)throw refusal(error3);throw error3}}function viewClaimOf(name2){return`get.view.${name2}`}function check2(spec){let name2=spec.view.plan.name;if(!spec.path.startsWith("/")||spec.path.includes(":"))throw Error(`View "${name2}": the path must be a literal starting with "/" ("${spec.path}")`);let clash=Object.keys(spec.view.plan.params).find((p)=>RESERVED_QUERY_NAMES.includes(p));if(clash!==void 0)throw Error(`View "${name2}": the param name "${clash}" is reserved by the view route`)}function guardsOf(spec,host){let name2=spec.view.plan.name,claims=spec.roles===void 0&&spec.claims===void 0&&spec.public!==!0?[viewClaimOf(name2)]:spec.claims,access2=accessGuard({public:spec.public,roles:spec.roles,claims},host),guards2=access2===null?[]:[access2];if(spec.tenantFeature!==void 0){let registry5=host.getTenantRegistry;if(registry5===void 0)throw Error(`View "${name2}" declares tenant_feature but the host has no getTenantRegistry`);guards2.push(createTenantFeatureGuard(spec.tenantFeature,()=>registry5.call(host)))}return guards2}function defineViewRoute(spec){check2(spec);let name2=spec.view.plan.name;return{name:name2,path:spec.path,toRoute(host){let paging=spec.paging??"offset";return defineRoute({method:"GET",path:spec.path,isPublic:spec.public,detail:{summary:`View ${name2}`,tags:["Views"],...spec.detail},guards:guardsOf(spec,host),handler:({request,set:set2,params,body,query,nucleus})=>runAction(host,{name:`view.${name2}`,scope:spec.scope,readOnly:!0,handler:(_input,unit,ctx)=>runViewCall(spec.view,paging,unit,ctx)},{request,set:set2,params,body,query,nucleus:isNucleusRuntime(nucleus)?nucleus:null})})}}}function viewGroup(host,views){let names3=new Set;for(let view of views){if(names3.has(view.name))throw Error(`Two views are named "${view.name}"`);names3.add(view.name)}return{routes:views.map((view)=>view.toRoute(host))}}function isViewConfig(entry){return typeof Reflect.get(entry,"name")==="string"&&typeof Reflect.get(entry,"from")==="string"}function viewsOfOptions(resolved){let list3=resolved===null?void 0:Reflect.get(resolved,"views");if(list3===void 0)return[];if(!Array.isArray(list3))throw Error("config.views must be an array of view declarations");return list3.map((entry,index)=>{if(typeof entry!=="object"||entry===null||!isViewConfig(entry))throw Error(`config.views[${index}] needs a "name" and a "from"`);return entry})}function configViewRoutes(configs){let routes=[];for(let config of configs??[]){if(config.path===void 0)continue;routes.push(defineViewRoute({view:buildConfigView(config),path:config.path,public:config.is_public,roles:config.roles,claims:config.claims,tenantFeature:config.tenant_feature,paging:config.paging,scope:config.scope}))}return routes}init_Logger2();var JOBS_SCOPE="jobs",jobLockKey=(name2)=>`jobs:${name2}`;var JOB_LOCKED={locked:!0},NAME3=/^[A-Za-z][A-Za-z0-9_.-]{0,99}$/,MAX_EVERY_SECONDS=86400;function validate(spec){if(!NAME3.test(spec.name))throw Error(`Job name "${spec.name}" must start with a letter and use letters, digits, ".", "_" or "-"`);if(!Number.isInteger(spec.everySeconds)||spec.everySeconds<1||spec.everySeconds>MAX_EVERY_SECONDS)throw Error(`Job "${spec.name}": everySeconds must be a whole number from 1 to ${MAX_EVERY_SECONDS}`);let first=spec.firstRunAfterSeconds;if(first!==void 0&&(!Number.isFinite(first)||first<0))throw Error(`Job "${spec.name}": firstRunAfterSeconds must be zero or more`)}function defineJobFor(){return function(spec){return validate(spec),{name:spec.name,everySeconds:spec.everySeconds,scope:spec.scope,firstRunAfterSeconds:spec.firstRunAfterSeconds,execute:(options,ctx,run)=>run({...options,retry:spec.retry},async(unit)=>{if(!await unit.lock.tryAdvisory(jobLockKey(spec.name)))return JOB_LOCKED;return spec.run(unit,ctx)})}}}var defineJob=defineJobFor();var PURGE_EVERY_SECONDS=3600;function purgeJob(name2,scope){return defineJob({name:name2,everySeconds:PURGE_EVERY_SECONDS,scope,run:async(unit,ctx)=>{let removed=await purgeExpiredIdempotencyKeys(executorOf2(unit),ctx.schema);if(removed>0)ctx.logger.info("Expired idempotency keys removed",{schema:ctx.schema,removed});return{handled:removed,failed:0}}})}var IDEMPOTENCY_PURGE_JOBS=[purgeJob("nucleus.purgeIdempotencyKeys","active"),purgeJob("nucleus.purgeIdempotencyKeys.main","main")];init_Logger2();var systemClock={now:()=>Date.now(),after(delayMs,callback){let timer=setTimeout(callback,delayMs);if(typeof timer==="object"&&typeof timer.unref==="function")timer.unref();return()=>clearTimeout(timer)}};function firstRunDelayMs(job,index){return((job.firstRunAfterSeconds??Math.min(job.everySeconds,20))+index*5)*1000}function nextDelayMs({everySeconds,failures}){let interval=everySeconds*1000;if(failures<=0)return interval;let base=Math.min(30000,interval);return Math.min(base*2**(failures-1),interval*8)}function createJobLoop(options){let{job,clock,log:log4}=options,cancel=null,running=null,active=!1,failures=0;function runNow(){return running??=options.pass().finally(()=>{running=null}),running}function schedule(delayMs){if(!active)return;cancel=clock.after(delayMs,()=>void cycle())}async function cycle(){cancel=null;let failed;try{let report=await runNow();if(failed=report.failed>0,report.skipped)log4.debug("Pass skipped: another replica holds the lock");else if(report.handled>0||report.failed>0)log4.info("Pass finished",{...report})}catch(error3){failed=!0,log4.error("Pass failed",error3)}failures=failed?failures+1:0;let delayMs=nextDelayMs({everySeconds:job.everySeconds,failures});if(failed)log4.warn("Retrying",{inSeconds:delayMs/1000,consecutiveFailures:failures});schedule(delayMs)}return{start(){active=!0,schedule(firstRunDelayMs(job,options.index))},async stop(){active=!1,cancel?.(),cancel=null,await running?.catch(()=>{return})},runNow}}var DEFAULT_MAX_CONCURRENT_PASSES=1;function createJobSlots(size){if(!Number.isInteger(size)||size<1)throw Error("jobs.maxConcurrentPasses must be a whole number of 1 or more");let busy=0,closed=!1,waiting=[];return{get busy(){return busy},acquire(){if(closed)return Promise.resolve(!1);if(busy<size)return busy+=1,Promise.resolve(!0);return new Promise((resolve2)=>waiting.push(resolve2))},release(){let next=waiting.shift();if(next!==void 0)next(!0);else busy-=1},close(){closed=!0;for(let resolve2 of waiting.splice(0))resolve2(!1)}}}function registrySource(registry5){return{list:()=>(registry5()?.getAllTenants()??[]).map((tenant)=>({id:tenant.id,schema:tenant.schemaName,status:tenant.status}))}}var PROVISIONED=["active","suspended","archived"];function targetsOf(scope,tenants,mainSchema){if(scope==="main")return[{id:null,schema:mainSchema,status:"active"}];let allowed=scope==="provisioned"?PROVISIONED:["active"];return tenants.list().filter((tenant)=>allowed.includes(tenant.status)).sort((a,b)=>a.schema<b.schema?-1:a.schema>b.schema?1:0)}var SKIPPED_PASS={tenants:0,handled:0,failed:0,skipped:!0};async function walkTargets(targets,visit,log4){let handled=0,failed=0,visited2=0;for(let target2 of targets)try{let result=await visit(target2);if("locked"in result){if(visited2===0)return SKIPPED_PASS;log4.debug("Another replica took over the job; this pass stops here",{schema:target2.schema});break}visited2+=1,handled+=result.handled,failed+=result.failed}catch(error3){visited2+=1,failed+=1,log4.error("Tenant failed; the others still run",error3,{schema:target2.schema})}return{tenants:visited2,handled,failed,skipped:!1}}async function runPass(host,job,log4){let scoped2=log4.scoped(`${JOBS_SCOPE}.${job.name}`),targets=targetsOf(job.scope,host.tenants,host.mainSchema);return walkTargets(targets,(target2)=>{let options={schema:target2.schema,mainSchema:host.mainSchema,scope:host.scope??(()=>[]),tables:host.tables,relations:host.relations,logger:scoped2},ctx={job:job.name,schema:target2.schema,tenant:target2,logger:scoped2};return job.execute(options,ctx,unitRunnerOf(host))},scoped2)}function unitRunnerOf(host){if(host.runUnit!==void 0)return host.runUnit;return(options,work)=>runUnitOfWork({...options,db:host.db,mainSchema:options.mainSchema??host.mainSchema},work)}async function runInSlot(slots,pass,skippedPass){if(!await slots.acquire())return skippedPass;try{return await pass()}finally{slots.release()}}function createJobRunner(options){let{host}=options,log4=host.logger??logger,clock=options.clock??systemClock,slots=createJobSlots(host.maxConcurrentPasses??DEFAULT_MAX_CONCURRENT_PASSES),loops=new Map;for(let[index,job]of options.jobs.entries()){if(loops.has(job.name))throw Error(`Two jobs are named "${job.name}"`);loops.set(job.name,createJobLoop({job,index,clock,log:log4.scoped(`${JOBS_SCOPE}.${job.name}`),pass:()=>runInSlot(slots,()=>runPass(host,job,log4),SKIPPED_PASS)}))}return{names:[...loops.keys()],start(){for(let loop of loops.values())loop.start()},async stop(){slots.close(),await Promise.allSettled([...loops.values()].map((loop)=>loop.stop()))},runNow(name2){let loop=loops.get(name2);if(loop===void 0)return Promise.reject(Error(`No job is named "${name2}"`));return loop.runNow()}}}function actionFlagsOf(resolved){let actions=resolved===null?void 0:Reflect.get(resolved,"actions");if(typeof actions!=="object"||actions===null)return{enabled:!1,purgeExpiredKeys:!0};return{enabled:Reflect.get(actions,"enabled")===!0,purgeExpiredKeys:Reflect.get(actions,"purgeExpiredKeys")!==!1}}function ownPool(data){if(data===void 0)throw Error("createNucleusServer: the job host names no database and nucleus has none to lend. Pass `jobHost: { db, mainSchema }`.");return data.db}function bootJobRunner(input){let jobs=[...input.actions.enabled&&input.actions.purgeExpiredKeys?IDEMPOTENCY_PURGE_JOBS:[],...input.jobs];if(jobs.length===0)return null;let base=input.jobHost??input.actionHost??(input.data===void 0?void 0:{mainSchema:input.data.mainSchema});if(base===void 0){if(input.jobs.length>0)throw Error("createNucleusServer: jobs need a database. Pass `jobHost: { db, mainSchema }` or `actions: { host }`.");return logger.scoped("jobs").warn("actions.enabled is on but no database was given for jobs: expired idempotency keys are not purged"),null}let host={db:base.db??ownPool(input.data),runUnit:base.db===void 0?input.data?.runUnitOfWork:void 0,mainSchema:base.mainSchema,scope:input.jobHost?.scope,tables:base.tables,relations:base.relations,logger:base.logger,maxConcurrentPasses:input.jobHost?.maxConcurrentPasses,tenants:registrySource(currentRegistry)};return createJobRunner({host,jobs})}init_response();class BodyParseError extends Error{status=400;constructor(){super("Bad Request");this.name="BodyParseError"}}function looksStructured(value2){return value2.startsWith("{")||value2.startsWith("[")}function assignPath(target2,key2,value2){let steps=key2.replace(/\[(\w*)\]/g,".$1").split(".").filter((step)=>step!=="");if(steps.length<=1){mergeInto(target2,key2,value2);return}let cursor=target2;for(let index=0;index<steps.length-1;index++){let step=steps[index],next=steps[index+1],wanted=/^\d+$/.test(next)?[]:{},holder3=cursor;if(typeof holder3[step]!=="object"||holder3[step]===null)holder3[step]=wanted;cursor=holder3[step]}let last=steps[steps.length-1];if(Array.isArray(cursor))cursor[Number(last)]=value2;else mergeInto(cursor,last,value2)}function mergeInto(target2,key2,value2){if(key2 in target2){let existing=target2[key2];target2[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2];return}target2[key2]=value2}function fromFormData(form){let out={};for(let[key2,value2]of form.entries()){let parsed=value2;if(typeof value2==="string"&&looksStructured(value2))try{parsed=JSON.parse(value2)}catch{parsed=value2}assignPath(out,key2,parsed)}return out}async function parseBody(request,declared){let contentType=request.headers.get("content-type");if(!contentType&&!declared)return;let kind=(contentType?.includes("multipart/form-data")?"formdata":contentType?.includes("application/x-www-form-urlencoded")?"urlencoded":contentType?.includes("application/json")?"json":contentType?.startsWith("text/")?"text":contentType?.includes("octet-stream")?"binary":void 0)??declared;if(!kind)return;if(kind==="formdata")try{return fromFormData(await request.formData())}catch{throw new BodyParseError}if(kind==="urlencoded"){let params=new URLSearchParams(await request.text()),out={};for(let[key2,value2]of params)if(key2 in out){let existing=out[key2];out[key2]=Array.isArray(existing)?[...existing,value2]:[existing,value2]}else out[key2]=value2;return out}if(kind==="binary")return await request.arrayBuffer();if(kind==="text")return await request.text();let raw=await request.text();if(raw===""&&!request.body)return;try{return JSON.parse(raw)}catch{throw new BodyParseError}}init_response();init_esm3();init_esm3();var EMAIL2=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,UUID2=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,DATE_TIME=/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ANNOTATION_ONLY=["binary"],registered=!1;function registerStringFormats(){if(registered)return;registered=!0,exports_format.Set("email",(value2)=>EMAIL2.test(value2)),exports_format.Set("uuid",(value2)=>UUID2.test(value2)),exports_format.Set("date-time",(value2)=>DATE_TIME.test(value2));for(let name2 of ANNOTATION_ONLY)exports_format.Set(name2,()=>!0)}var REGISTERED_FORMATS=["email","uuid","date-time",...ANNOTATION_ONLY];var OPTIONAL_KIND=Symbol.for("TypeBox.Optional"),KIND=Symbol.for("TypeBox.Kind"),cleanable=new WeakMap;function honourOpenObjects(node){if(Array.isArray(node)){let changed2=!1,out2=node.map((entry)=>{let next=honourOpenObjects(entry);if(next!==entry)changed2=!0;return next});return changed2?out2:node}if(node===null||typeof node!=="object")return node;let source=node,isSchema=KIND in source,changed=!1,out={};for(let key2 of Object.keys(source)){let value2=source[key2];if(isSchema&&key2==="additionalProperties"&&value2===!0){out[key2]=Type.Any(),changed=!0;continue}let next=honourOpenObjects(value2);if(next!==value2)changed=!0;out[key2]=next}if(!changed)return node;for(let symbol3 of Object.getOwnPropertySymbols(source))out[symbol3]=source[symbol3];return out}function cleanSchemaFor(schema3){let cached=cleanable.get(schema3);if(cached)return cached;let rewritten=honourOpenObjects(schema3);return cleanable.set(schema3,rewritten),rewritten}function prepare(schema3,value2,on){if(!schema3)return value2;if(value2===void 0&&OPTIONAL_KIND in schema3)return;let prepared=value2;if(on==="query")try{prepared=exports_value2.Convert(schema3,prepared)}catch{}try{prepared=exports_value2.Default(schema3,prepared)}catch{}try{prepared=exports_value2.Clean(cleanSchemaFor(schema3),prepared)}catch{}return prepared}function sampleOf(schema3){try{return exports_value2.Create(schema3)}catch{return}}registerStringFormats();var REQUIRED_PROPERTY=45;function propertyName(path8){return path8.replace(/^\//,"").replace(/\//g,".")}function describe2(value2){if(value2===void 0)return"undefined";if(value2===null)return"null";if(typeof value2==="object")return JSON.stringify(value2);return String(value2)}function at(value2,path8){let current=value2;for(let segment of path8.split("/").filter(Boolean)){if(typeof current!=="object"||current===null)return;current=current[segment]}return current}function validate2(schema3,value2,on){if(!schema3)return null;if(exports_value2.Check(schema3,value2))return null;let all=[...exports_value2.Errors(schema3,value2)],errors2=all.filter((error3)=>error3.type!==REQUIRED_PROPERTY),primary=errors2[0]??all[0],path8=primary?.path??"",message=primary?.message??"Invalid value",atRoot=path8==="";return{isSuccess:!1,success:!1,type:"validation",on,property:atRoot?"root":path8,message,summary:atRoot?message:summarise(path8,message,at(value2,path8)),expected:sampleOf(schema3),found:redact(value2),errors:errors2.map((error3)=>({...error3,value:redact(error3.value),summary:summarise(error3.path,error3.message,at(value2,error3.path))}))}}function describeExpectation(message){return message.replace(/^Expected\s+/i,"")}function redact(value2){if(value2===null)return"null";if(Array.isArray(value2))return`array(${value2.length})`;if(value2 instanceof Date)return"Date";if(typeof value2==="object"){let shape={};for(let key2 of Object.keys(value2))shape[key2]=redact(value2[key2]);return shape}if(value2===void 0)return"undefined";return typeof value2}function summarise(path8,message,found){return`Expected property '${propertyName(path8)}' to be ${describeExpectation(message)} but found: ${describe2(redact(found))}`}class RouteCollisionError extends Error{constructor(method,path8){super(`${method} ${path8} is registered twice. Two groups claiming one path is a wiring mistake, not a fallback: which handler answers would depend on registration order.`);this.name="RouteCollisionError"}}function joinPath2(prefix,path8){if(!prefix)return path8;let left=prefix.endsWith("/")?prefix.slice(0,-1):prefix;if(path8==="/"||path8==="")return left||"/";let right=path8.startsWith("/")?path8:`/${path8}`;return`${left}${right}`||"/"}function buildRoutes(groups,options={}){let table2=new Map;for(let group of groups)for(let route of group.routes){let fullPath=joinPath2(group.prefix,route.path),method=route.method,byMethod=table2.get(fullPath);if(!byMethod)byMethod=new Map,table2.set(fullPath,byMethod);if(byMethod.has(method))throw new RouteCollisionError(method,fullPath);byMethod.set(method,{guards:[...group.guards??[],...route.guards??[]],route})}let out={},withSlashAlias=(path8)=>path8==="/"||path8.endsWith("/")?[path8]:[path8,`${path8}/`];for(let[path8,byMethod]of table2){let handlers={};for(let[method,registered2]of byMethod){handlers[method]=async(request,server)=>{let set2=createResponseSet(),response;try{response=await answer(request,server,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});response=finalizeResponse(answered,set2)}if(options.onAfter)try{set2.status=response.status,await options.onAfter({request,set:set2})}catch(error3){console.error("[router] after-handler failed",error3)}return response};let answer=async(request,server,set2)=>{let url=new URL(request.url),params=request.params??{},query=Object.fromEntries(url.searchParams);if(options.onRequest){let early=await options.onRequest({request,set:set2,body:void 0,params,query,server});if(early!==void 0)return finalizeResponse(early,set2)}let body;try{body=await parseBody(request.clone(),registered2.route.type)}catch(error3){if(error3 instanceof BodyParseError){let bodySchema=registered2.route.body;if(bodySchema&&OPTIONAL_KIND in bodySchema)body=void 0;else return new Response(error3.message,{status:error3.status})}else throw error3}body=prepare(registered2.route.body,body,"body"),query=prepare(registered2.route.query,query,"query"),params=prepare(registered2.route.params,params,"params");for(let[target2,schema3,value2]of[["body",registered2.route.body,body],["query",registered2.route.query,query],["params",registered2.route.params,params]]){if(value2===void 0&&schema3&&OPTIONAL_KIND in schema3)continue;let failure=validate2(schema3,value2,target2);if(failure){let headers=new Headers({"content-type":"application/json"});for(let[name2,value3]of Object.entries(set2.headers))if(value3!==void 0)headers.set(name2,String(value3));return new Response(JSON.stringify(failure,null,2),{status:422,headers})}}let guardContext={request,set:set2,body,params,query,server};if(options.beforeHandle){let early=await options.beforeHandle(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}for(let guard5 of registered2.guards){let early=await guard5(guardContext);if(early!==void 0)return finalizeResponse(early,set2)}try{let result=await registered2.route.handler({...options.context,request,params,query,body,set:set2});return finalizeResponse(result,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}}for(let alias2 of withSlashAlias(path8))out[alias2]=handlers}return out}init_websocket();var NOT_FOUND=()=>new Response("NOT_FOUND",{status:404});async function staticAsset(request,assets){if(!assets)return null;if(request.method!=="GET"&&request.method!=="HEAD")return null;let{pathname}=new URL(request.url),prefix=assets.prefix.endsWith("/")?assets.prefix.slice(0,-1):assets.prefix;if(pathname!==prefix&&!pathname.startsWith(`${prefix}/`))return null;let relative;try{relative=decodeURIComponent(pathname.slice(prefix.length))}catch{return new Response("NOT_FOUND",{status:404})}let{join:join9,resolve:resolve2,sep}=await import("path"),root=resolve2(assets.directory),target2=resolve2(join9(root,relative));if(target2!==root&&!target2.startsWith(root+sep))return new Response("NOT_FOUND",{status:404});let file=Bun.file(target2);if(!await file.exists())return null;return new Response(request.method==="HEAD"?null:file)}function serve(options){let routes=buildRoutes(options.groups,{onRequest:options.onRequest,beforeHandle:options.beforeHandle,onError:options.onError,onAfter:options.onAfter,context:options.context}),notFound=options.notFound??NOT_FOUND,socket=options.socket,server=Bun.serve({port:options.port??0,hostname:options.hostname,idleTimeout:options.idleTimeout??30,reusePort:options.reusePort??!0,...options.maxRequestBodyBytes!==void 0?{maxRequestBodySize:options.maxRequestBodyBytes}:{},routes,fetch:async(request,self2)=>{let asset=await staticAsset(request,options.staticAssets);if(asset)return asset;let set2=createResponseSet();if(options.onRequest){let url=new URL(request.url);try{let early=await options.onRequest({request,set:set2,body:void 0,params:{},query:Object.fromEntries(url.searchParams),server:self2});if(early!==void 0)return finalizeResponse(early,set2)}catch(error3){if(!options.onError)throw error3;let answered=await options.onError({set:set2,code:"UNKNOWN",error:error3,request});return finalizeResponse(answered,set2)}}if(socket){let upgraded=upgradeFor(socket,request,self2);if(upgraded)return upgraded}let missing=await notFound(request),headers=new Headers(missing.headers);for(let[name2,value2]of Object.entries(set2.headers))if(value2!==void 0&&!headers.has(name2))headers.set(name2,String(value2));let text4=await missing.text();return new Response(text4,{status:missing.status,headers})},websocket:socket?websocketHandlers(socket):void 0}),stopped=!1,runShutdown=async()=>{for(let step of options.onStop??[])try{await step()}catch(error3){console.error("[NucleusServer] shutdown step failed",error3)}},port=server.port??0,hostname=server.hostname??"localhost";return{port,hostname,url:`http://${hostname}:${port}`,stop:(closeActiveConnections=!1)=>{let stopping=Promise.resolve(server.stop(closeActiveConnections));if(stopped)return stopping;return stopped=!0,stopping.then(runShutdown)},raw:server}}function operationIdFor(method,path8){let tail2=path8.split("/").filter(Boolean).flatMap((segment)=>segment.startsWith(":")?["by",segment.slice(1)]:segment.split(/[-_]/)).filter(Boolean).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join("");return`${method.toLowerCase()}${tail2}`}function toOpenApiPath(path8){return path8.split("/").map((segment)=>segment.startsWith(":")?`{${segment.slice(1)}}`:segment).join("/")}function pathParametersOf(path8,schema3){let declared=schema3?.properties;return path8.split("/").filter((segment)=>segment.startsWith(":")).map((segment)=>{let name2=segment.slice(1);return{name:name2,in:"path",required:!0,schema:declared?.[name2]??{type:"string"}}})}function queryParametersOf(schema3){let object3=schema3;if(!object3?.properties)return[];return Object.entries(object3.properties).map(([name2,value2])=>({name:name2,in:"query",required:object3.required?.includes(name2)??!1,schema:value2}))}function buildOpenApiDocument(groups,config={}){let info=config.documentation?.info,exclude3=config.exclude??[],isExcluded=(path8)=>exclude3.some((rule)=>typeof rule==="string"?rule===path8:rule.test(path8)),paths={};for(let group of groups)for(let route of group.routes){let declared=route.path==="/"?"":route.path,joined=`${group.prefix??""}${declared}`||"/";if(isExcluded(joined))continue;let openApiPath=toOpenApiPath(joined),method=route.method.toLowerCase(),detail=route.detail,parameters4=[...pathParametersOf(joined,route.params),...queryParametersOf(route.query)],operation={operationId:operationIdFor(route.method,joined),responses:{"200":{}}};if(detail?.tags)operation.tags=detail.tags;if(detail?.summary)operation.summary=detail.summary;if(detail?.description)operation.description=detail.description;if(parameters4.length>0)operation.parameters=parameters4;if(route.body)operation.requestBody={content:{"application/json":{schema:route.body}}};if(paths[openApiPath]=paths[openApiPath]??{},!paths[openApiPath][method])paths[openApiPath][method]=operation}let document={openapi:"3.0.3",info:{title:info?.title??"Nucleus API",description:info?.description??"Auto-generated API documentation",version:info?.version??"1.0.0",...info?.contact?{contact:info.contact}:{},...info?.license?{license:info.license}:{}},tags:config.documentation?.tags??[],paths};if(config.documentation?.servers)document.servers=config.documentation.servers;return document}function viewerHtml(documentUrl,title,description,viewerConfig){let forHtml=(value2)=>value2.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;"),configuration=viewerConfig&&Object.keys(viewerConfig).length>0?` data-configuration="${forHtml(JSON.stringify(viewerConfig))}"`:"";return`<!doctype html>
633
633
  <html>
634
634
  <head>
635
635
  <title>${forHtml(title)}</title>
@@ -644,8 +644,8 @@ ${content}
644
644
  <script id="api-reference" data-url="${forHtml(documentUrl)}"${configuration}></script>
645
645
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
646
646
  </body>
647
- </html>`}function chainGuards(...guards2){return async(context)=>{for(let guard5 of guards2){let early=await guard5(context);if(early!==void 0)return early}return}}function docsGroup(groups,config){let swagger=config.swagger;if(swagger?.enabled===!1)return null;let base=swagger?.path??"/swagger",info=swagger?.documentation?.info,title=info?.title??"Nucleus API",description=info?.description??"Auto-generated API documentation",document=buildOpenApiDocument(groups,swagger),page=viewerHtml(`${base}/json`,title,description,swagger?.scalarConfig);return{prefix:base,routes:[defineRoute({method:"GET",path:"/",detail:{summary:"API documentation",tags:["Documentation"]},handler:()=>new Response(page,{headers:{"content-type":"text/html; charset=utf8"}})}),defineRoute({method:"GET",path:"/json",detail:{summary:"OpenAPI document",tags:["Documentation"]},handler:()=>document})]}}async function createNucleusServer(options){await buildNucleus({...options.config,onTenantProvisioned:options.onTenantProvisioned??options.config.onTenantProvisioned,tenants:options.tenants??options.config.tenants,entityHooks:options.entityHooks??options.config.entityHooks});let groups=getMountedRouteGroups();if(groups.length===0)throw Error("createNucleusServer: the plugin mounted no route groups. That is a wiring "+"fault, not an empty install \u2014 refusing to serve rather than answering 404 to everything.");let resolved=getResolvedOptions2(),rawOptions=options.config.options,securityOf=(candidate)=>typeof candidate==="object"&&candidate!==null?candidate.security?.maxRequestBodyBytes:void 0,maxRequestBodyBytes=securityOf(resolved)??securityOf(rawOptions),storageCeiling=requiredBodyCeiling({storageEnabled:resolved?.storage?.enabled,maxFileSizeBytes:resolved?.storage?.maxFileSizeBytes,maxFiles:resolved?.storage?.formData?.maxFiles}),bunBodyCeiling=bunBodyCeilingFor({storageRequired:storageCeiling,guardCeiling:maxRequestBodyBytes});{let{containerMemoryLimitBytes:containerMemoryLimitBytes2,uploadMemoryAdvice:uploadMemoryAdvice2}=__toCommonJS(exports_bodyCeiling),advice=uploadMemoryAdvice2({storageEnabled:resolved?.storage?.enabled,maxFileSizeBytes:resolved?.storage?.maxFileSizeBytes,memoryLimitBytes:containerMemoryLimitBytes2((p)=>__require("fs").readFileSync(p,"utf8"))});if(advice)console.warn(advice)}for(let step of getBootSteps())await step({config:{serve:{maxRequestBodySize:bunBodyCeiling}}});let data=nucleusDataOf(getMountedRuntime2())??createNucleusData({getDb:()=>null,mainSchema:"public",relationsOf:()=>({}),getRules:()=>{return}}),jobRunner=bootJobRunner({data,jobs:options.jobs??[],jobHost:options.jobHost,actionHost:options.actions?.host,actions:actionFlagsOf(typeof resolved==="object"?resolved:null)}),hostRoutes=[...options.routes??[],...options.actions?[actionGroup(options.actions.host,options.actions.actions)]:[],...options.views?[viewGroup(options.views.host,[...options.views.views??[],...configViewRoutes(viewsOfOptions(typeof resolved==="object"?resolved:null))])]:[]],resolvedSwagger=resolved?.swagger,outerSwagger=options.config.swagger,docs=docsGroup([...groups,...hostRoutes],{swagger:outerSwagger??resolvedSwagger}),server=serve({groups:[...groups,...docs?[docs]:[],...hostRoutes],maxRequestBodyBytes:bunBodyCeiling,onStop:[...jobRunner?[()=>jobRunner.stop()]:[],...getShutdownSteps(),...options.onStop??[]],socket:options.socket??getMountedSocket()??void 0,staticAssets:(()=>{let directory=getMountedStaticAssets();return directory?{prefix:"/nucleus-core",directory}:void 0})(),onRequest:chainGuards(...options.onRequest?[options.onRequest]:[],createInboundGuard({maxRequestBodyBytes}),getAuthMiddleware()),beforeHandle:options.beforeHandle,onError:getErrorHandler(),onAfter:getAfterHandler()??void 0,context:(()=>{let runtime=getMountedRuntime2();return runtime?{nucleus:runtime}:void 0})(),port:options.port,hostname:options.hostname});return jobRunner?.start(),Object.assign(server,{data})}init_routeCollector();init_response();function compile(pattern2){let names3=[],source=pattern2.split("/").map((segment)=>{if(segment.startsWith(":"))return names3.push(segment.slice(1)),"([^/]+)";if(segment==="*")return names3.push("*"),"(.*)";return segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{regex:new RegExp(`^${source}/?$`),names:names3}}var DEFAULT_ERROR_RESPONDER=({set:set2,error:error3})=>{let carried=error3?.status,status=typeof carried==="number"&&carried>=100&&carried<=599?carried:500;set2.status=status;let message=status<500?String(error3?.message??""):"Internal Server Error";return Response.json(withEnvelopeFlags({isSuccess:!1,message,status,errors:[{message}],data:null}))};class NucleusTestApp{mountConfig;recorded=[];decorations={};sockets=[];globalGuard;beforeHandlers=[];listening=null;errorResponder;afterResponder;table=null;constructor(mountConfig={}){this.mountConfig=mountConfig;for(let method of["get","post","put","patch","delete","head","options"]){let register=(path8,handler,schema3)=>{return this.add(method.toUpperCase(),path8,handler,schema3),this};this[method]=register}}add(method,path8,handler,schema3={}){let prefix=this.mountConfig.prefix??"",joined=path8==="/"?prefix||"/":`${prefix}${path8}`;this.recorded.push({method,path:joined,route:{method,path:joined,handler,body:schema3.body,query:schema3.query,params:schema3.params,detail:schema3.detail,type:schema3.type}}),this.table=null}ws(path8,definition2){return this.sockets.push({path:path8,...definition2}),this}use(plugin){if(plugin instanceof NucleusTestApp){for(let one of plugin.recorded)this.recorded.push(one);for(let socket of plugin.sockets)this.sockets.push(socket);return this.table=null,this}let group=plugin;if(group&&Array.isArray(group.routes)){let prefix=typeof group.prefix==="string"?group.prefix:"";for(let route of group.routes){let declared=route.path==="/"?"":route.path,path8=`${prefix}${declared}`||"/";this.recorded.push({method:route.method,path:path8,route:{...route,path:path8}})}this.table=null}return this}onRequest(guard5){return this.globalGuard=guard5,this.table=null,this}onError(responder){return this.errorResponder=responder,this.table=null,this}onAfterHandle(responder){return this.afterResponder=responder,this.table=null,this}onBeforeHandle(guard5){return this.beforeHandlers.push(guard5),this.table=null,this}decorate(key2,value2){let entries=typeof key2==="string"?{[key2]:value2}:key2;return Object.assign(this,entries),Object.assign(this.decorations,entries),this.table=null,this}listen(port=0){return this.listening=serve({groups:[{routes:this.recorded.map((one)=>one.route)}],socket:this.sockets[0],port:Number(port)||0,reusePort:!1,onRequest:this.globalGuard,onError:this.errorResponder??DEFAULT_ERROR_RESPONDER,onAfter:this.afterResponder}),this}get server(){return this.listening??void 0}stop(closeActiveConnections){return this.listening?.stop(closeActiveConnections)}get socketRoutes(){return this.sockets}get routes(){return this.recorded.map((one)=>`${one.method} ${one.path}`)}build(){if(this.table)return this.table;let groups=[{guards:this.beforeHandlers,routes:this.recorded.map((one)=>one.route)}];return this.table=buildRoutes(groups,{context:this.decorations,onRequest:this.globalGuard,onError:this.errorResponder??DEFAULT_ERROR_RESPONDER,onAfter:this.afterResponder}),this.table}async handle(request){let table2=this.build(),{pathname}=new URL(request.url),method=request.method.toUpperCase(),exact=table2[pathname]??table2[pathname.replace(/\/$/,"")];if(exact?.[method])return exact[method](request);for(let[pattern2,byMethod]of Object.entries(table2)){if(!byMethod[method])continue;if(!pattern2.includes(":")&&!pattern2.includes("*"))continue;let{regex,names:names3}=compile(pattern2),matched=regex.exec(pathname);if(!matched)continue;let params={};return names3.forEach((name2,index)=>{params[name2]=decodeURIComponent(matched[index+1]??"")}),request.params=params,byMethod[method](request)}return new Response("NOT_FOUND",{status:404})}}init_websocket();import{sql as sql48}from"drizzle-orm";init_Logger2();import{sql as sql44}from"drizzle-orm";init_Logger2();init_Delete2();var log6=logger.scoped("auth.endUserSessions"),SESSION_TABLES=["user_sessions","sessions"];async function sessionTableOf(executor,schema3){for(let name2 of SESSION_TABLES){let found=await executor.execute(sql44`select to_regclass(format('%I.%I', ${schema3}::text, ${name2}::text)) is not null as present`);if(Reflect.get(rowsOfResult(found)[0]??{},"present")===!0)return name2}return null}async function endUserSessions(unit,userId){let executor=executorOf2(unit),table2=await sessionTableOf(executor,unit.schema);if(table2===null)return 0;let deleted=await executor.execute(sql44`delete from ${sql44.identifier(unit.schema)}.${sql44.identifier(table2)}
648
- where user_id = ${userId} returning id`),ids=rowsOfResult(deleted).map((row)=>String(Reflect.get(row,"id")));if(ids.length>0)unit.afterCommit(async()=>{await forgetSessionsInRedis(ids),log6.info("Redis session tokens cleared",{schema:unit.schema,sessions:ids.length})});return log6.info("User sessions ended",{schema:unit.schema,table:table2,sessions:ids.length}),ids.length}import{sql as sql45}from"drizzle-orm";class AccountErasureError extends Error{unhandled;constructor(message,unhandled=[]){super(message);this.unhandled=unhandled;this.name="AccountErasureError"}}var AUDIT_TABLE="audit_logs";async function userReferences(executor,schema3){let result=await executor.execute(sql45`
647
+ </html>`}function chainGuards(...guards2){return async(context)=>{for(let guard5 of guards2){let early=await guard5(context);if(early!==void 0)return early}return}}function docsGroup(groups,config){let swagger=config.swagger;if(swagger?.enabled===!1)return null;let base=swagger?.path??"/swagger",info=swagger?.documentation?.info,title=info?.title??"Nucleus API",description=info?.description??"Auto-generated API documentation",document=buildOpenApiDocument(groups,swagger),page=viewerHtml(`${base}/json`,title,description,swagger?.scalarConfig);return{prefix:base,routes:[defineRoute({method:"GET",path:"/",detail:{summary:"API documentation",tags:["Documentation"]},handler:()=>new Response(page,{headers:{"content-type":"text/html; charset=utf8"}})}),defineRoute({method:"GET",path:"/json",detail:{summary:"OpenAPI document",tags:["Documentation"]},handler:()=>document})]}}async function createNucleusServer(options){await buildNucleus({...options.config,onTenantProvisioned:options.onTenantProvisioned??options.config.onTenantProvisioned,tenants:options.tenants??options.config.tenants,entityHooks:options.entityHooks??options.config.entityHooks});let groups=getMountedRouteGroups();if(groups.length===0)throw Error("createNucleusServer: the plugin mounted no route groups. That is a wiring "+"fault, not an empty install \u2014 refusing to serve rather than answering 404 to everything.");let resolved=getResolvedOptions2(),rawOptions=options.config.options,securityOf=(candidate)=>typeof candidate==="object"&&candidate!==null?candidate.security?.maxRequestBodyBytes:void 0,maxRequestBodyBytes=securityOf(resolved)??securityOf(rawOptions),storageCeiling=requiredBodyCeiling({storageEnabled:resolved?.storage?.enabled,maxFileSizeBytes:resolved?.storage?.maxFileSizeBytes,maxFiles:resolved?.storage?.formData?.maxFiles}),bunBodyCeiling=bunBodyCeilingFor({storageRequired:storageCeiling,guardCeiling:maxRequestBodyBytes});{let{containerMemoryLimitBytes:containerMemoryLimitBytes2,uploadMemoryAdvice:uploadMemoryAdvice2}=__toCommonJS(exports_bodyCeiling),advice=uploadMemoryAdvice2({storageEnabled:resolved?.storage?.enabled,maxFileSizeBytes:resolved?.storage?.maxFileSizeBytes,memoryLimitBytes:containerMemoryLimitBytes2((p)=>__require("fs").readFileSync(p,"utf8"))});if(advice)console.warn(advice)}for(let step of getBootSteps())await step({config:{serve:{maxRequestBodySize:bunBodyCeiling}}});let data=nucleusDataOf(getMountedRuntime2())??createNucleusData({getDb:()=>null,mainSchema:"public",relationsOf:()=>({}),getRules:()=>{return}}),jobRunner=bootJobRunner({data,jobs:options.jobs??[],jobHost:options.jobHost,actionHost:options.actions?.host,actions:actionFlagsOf(typeof resolved==="object"?resolved:null)}),hostRoutes=[...options.routes??[],...options.actions?[actionGroup(options.actions.host,options.actions.actions)]:[],...options.views?[viewGroup(options.views.host,[...options.views.views??[],...configViewRoutes(viewsOfOptions(typeof resolved==="object"?resolved:null))])]:[]],resolvedSwagger=resolved?.swagger,outerSwagger=options.config.swagger,docs=docsGroup([...groups,...hostRoutes],{swagger:outerSwagger??resolvedSwagger}),server=serve({groups:[...groups,...docs?[docs]:[],...hostRoutes],maxRequestBodyBytes:bunBodyCeiling,onStop:[...jobRunner?[()=>jobRunner.stop()]:[],...getShutdownSteps(),...options.onStop??[]],socket:options.socket??getMountedSocket()??void 0,staticAssets:(()=>{let directory=getMountedStaticAssets();return directory?{prefix:"/nucleus-core",directory}:void 0})(),onRequest:chainGuards(...options.onRequest?[options.onRequest]:[],createInboundGuard({maxRequestBodyBytes}),getAuthMiddleware()),beforeHandle:options.beforeHandle,onError:getErrorHandler(),onAfter:getAfterHandler()??void 0,context:(()=>{let runtime=getMountedRuntime2();return runtime?{nucleus:runtime}:void 0})(),port:options.port,hostname:options.hostname});return jobRunner?.start(),Object.assign(server,{data})}init_routeCollector();init_response();function compile(pattern2){let names3=[],source=pattern2.split("/").map((segment)=>{if(segment.startsWith(":"))return names3.push(segment.slice(1)),"([^/]+)";if(segment==="*")return names3.push("*"),"(.*)";return segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{regex:new RegExp(`^${source}/?$`),names:names3}}var DEFAULT_ERROR_RESPONDER=({set:set2,error:error3})=>{let carried=error3?.status,status=typeof carried==="number"&&carried>=100&&carried<=599?carried:500;set2.status=status;let message=status<500?String(error3?.message??""):"Internal Server Error";return Response.json(withEnvelopeFlags({isSuccess:!1,message,status,errors:[{message}],data:null}))};class NucleusTestApp{mountConfig;recorded=[];decorations={};sockets=[];globalGuard;beforeHandlers=[];listening=null;errorResponder;afterResponder;table=null;constructor(mountConfig={}){this.mountConfig=mountConfig;for(let method of["get","post","put","patch","delete","head","options"]){let register=(path8,handler,schema3)=>{return this.add(method.toUpperCase(),path8,handler,schema3),this};this[method]=register}}add(method,path8,handler,schema3={}){let prefix=this.mountConfig.prefix??"",joined=path8==="/"?prefix||"/":`${prefix}${path8}`;this.recorded.push({method,path:joined,route:{method,path:joined,handler,body:schema3.body,query:schema3.query,params:schema3.params,detail:schema3.detail,type:schema3.type}}),this.table=null}ws(path8,definition2){return this.sockets.push({path:path8,...definition2}),this}use(plugin){if(plugin instanceof NucleusTestApp){for(let one of plugin.recorded)this.recorded.push(one);for(let socket of plugin.sockets)this.sockets.push(socket);return this.table=null,this}let group=plugin;if(group&&Array.isArray(group.routes)){let prefix=typeof group.prefix==="string"?group.prefix:"";for(let route of group.routes){let declared=route.path==="/"?"":route.path,path8=`${prefix}${declared}`||"/";this.recorded.push({method:route.method,path:path8,route:{...route,path:path8}})}this.table=null}return this}onRequest(guard5){return this.globalGuard=guard5,this.table=null,this}onError(responder){return this.errorResponder=responder,this.table=null,this}onAfterHandle(responder){return this.afterResponder=responder,this.table=null,this}onBeforeHandle(guard5){return this.beforeHandlers.push(guard5),this.table=null,this}decorate(key2,value2){let entries=typeof key2==="string"?{[key2]:value2}:key2;return Object.assign(this,entries),Object.assign(this.decorations,entries),this.table=null,this}listen(port=0){return this.listening=serve({groups:[{routes:this.recorded.map((one)=>one.route)}],socket:this.sockets[0],port:Number(port)||0,reusePort:!1,onRequest:this.globalGuard,onError:this.errorResponder??DEFAULT_ERROR_RESPONDER,onAfter:this.afterResponder}),this}get server(){return this.listening??void 0}stop(closeActiveConnections){return this.listening?.stop(closeActiveConnections)}get socketRoutes(){return this.sockets}get routes(){return this.recorded.map((one)=>`${one.method} ${one.path}`)}build(){if(this.table)return this.table;let groups=[{guards:this.beforeHandlers,routes:this.recorded.map((one)=>one.route)}];return this.table=buildRoutes(groups,{context:this.decorations,onRequest:this.globalGuard,onError:this.errorResponder??DEFAULT_ERROR_RESPONDER,onAfter:this.afterResponder}),this.table}async handle(request){let table2=this.build(),{pathname}=new URL(request.url),method=request.method.toUpperCase(),exact=table2[pathname]??table2[pathname.replace(/\/$/,"")];if(exact?.[method])return exact[method](request);for(let[pattern2,byMethod]of Object.entries(table2)){if(!byMethod[method])continue;if(!pattern2.includes(":")&&!pattern2.includes("*"))continue;let{regex,names:names3}=compile(pattern2),matched=regex.exec(pathname);if(!matched)continue;let params={};return names3.forEach((name2,index)=>{params[name2]=decodeURIComponent(matched[index+1]??"")}),request.params=params,byMethod[method](request)}return new Response("NOT_FOUND",{status:404})}}init_websocket();import{sql as sql47}from"drizzle-orm";init_Logger2();import{sql as sql43}from"drizzle-orm";init_Logger2();init_Delete2();var log6=logger.scoped("auth.endUserSessions"),SESSION_TABLES=["user_sessions","sessions"];async function sessionTableOf(executor,schema3){for(let name2 of SESSION_TABLES){let found=await executor.execute(sql43`select to_regclass(format('%I.%I', ${schema3}::text, ${name2}::text)) is not null as present`);if(Reflect.get(rowsOfResult(found)[0]??{},"present")===!0)return name2}return null}async function endUserSessions(unit,userId){let executor=executorOf2(unit),table2=await sessionTableOf(executor,unit.schema);if(table2===null)return 0;let deleted=await executor.execute(sql43`delete from ${sql43.identifier(unit.schema)}.${sql43.identifier(table2)}
648
+ where user_id = ${userId} returning id`),ids=rowsOfResult(deleted).map((row)=>String(Reflect.get(row,"id")));if(ids.length>0)unit.afterCommit(async()=>{await forgetSessionsInRedis(ids),log6.info("Redis session tokens cleared",{schema:unit.schema,sessions:ids.length})});return log6.info("User sessions ended",{schema:unit.schema,table:table2,sessions:ids.length}),ids.length}import{sql as sql44}from"drizzle-orm";class AccountErasureError extends Error{unhandled;constructor(message,unhandled=[]){super(message);this.unhandled=unhandled;this.name="AccountErasureError"}}var AUDIT_TABLE="audit_logs";async function userReferences(executor,schema3){let result=await executor.execute(sql44`
649
649
  select rel.relname as table_name, a.attname as column_name, a.attnotnull as required,
650
650
  c.confdeltype as on_delete, array_length(c.conkey, 1) as width,
651
651
  exists (select 1 from pg_attribute i
@@ -658,18 +658,18 @@ ${content}
658
658
  where c.contype = 'f' and ns.nspname = ${schema3}
659
659
  and c.confrelid = to_regclass(format('%I.%I', ${schema3}::text, 'users'::text))
660
660
  and target.attname = 'id'
661
- order by rel.relname, a.attname`);return rowsOfResult(result).map((row)=>{let table2=String(Reflect.get(row,"table_name")),column3=String(Reflect.get(row,"column_name"));if(Number(Reflect.get(row,"width"))>1)throw new AccountErasureError(`${table2}.${column3} is a composite key to users`,[`${table2}.${column3}`]);return{table:table2,column:column3,required:Reflect.get(row,"required")===!0,onDelete:String(Reflect.get(row,"on_delete")),hasId:Reflect.get(row,"has_id")===!0}})}async function countReferences(executor,schema3,ref3,userId){let own=ref3.table==="users"?sql45` and id <> ${userId}`:sql45``,result=await executor.execute(sql45`select count(*)::int as n from ${sql45.identifier(schema3)}.${sql45.identifier(ref3.table)}
662
- where ${sql45.identifier(ref3.column)} = ${userId}${own}`);return Number(Reflect.get(rowsOfResult(result)[0]??{},"n"))}function touchedOf(result,hasId){let rows=rowsOfResult(result);if(hasId)return{count:rows.length,ids:rows.map((r)=>String(Reflect.get(r,"id")))};let rowCount=typeof result==="object"&&result!==null?Reflect.get(result,"rowCount"):0;return{count:typeof rowCount==="number"?rowCount:0,ids:[]}}import{sql as sql46}from"drizzle-orm";function declaredColumns(options){let found=new Map,add2=(table2,column3)=>found.set(`${table2}.${column3}`,{table:table2,column:column3});for(let table2 of options.tables??[])for(let column3 of table2.columns??[])if(column3.references_user===!0)add2(table2.table_name,column3.name);for(let extra of options.extraReferences??[])add2(extra.table,extra.column);return[...found.values()]}async function declaredReferences(executor,schema3,declared,foreignKeys){let found=[];for(let{table:table2,column:column3}of declared){if(foreignKeys.some((ref3)=>ref3.table===table2&&ref3.column===column3))continue;let result=await executor.execute(sql46`
661
+ order by rel.relname, a.attname`);return rowsOfResult(result).map((row)=>{let table2=String(Reflect.get(row,"table_name")),column3=String(Reflect.get(row,"column_name"));if(Number(Reflect.get(row,"width"))>1)throw new AccountErasureError(`${table2}.${column3} is a composite key to users`,[`${table2}.${column3}`]);return{table:table2,column:column3,required:Reflect.get(row,"required")===!0,onDelete:String(Reflect.get(row,"on_delete")),hasId:Reflect.get(row,"has_id")===!0}})}async function countReferences(executor,schema3,ref3,userId){let own=ref3.table==="users"?sql44` and id <> ${userId}`:sql44``,result=await executor.execute(sql44`select count(*)::int as n from ${sql44.identifier(schema3)}.${sql44.identifier(ref3.table)}
662
+ where ${sql44.identifier(ref3.column)} = ${userId}${own}`);return Number(Reflect.get(rowsOfResult(result)[0]??{},"n"))}function touchedOf(result,hasId){let rows=rowsOfResult(result);if(hasId)return{count:rows.length,ids:rows.map((r)=>String(Reflect.get(r,"id")))};let rowCount=typeof result==="object"&&result!==null?Reflect.get(result,"rowCount"):0;return{count:typeof rowCount==="number"?rowCount:0,ids:[]}}import{sql as sql45}from"drizzle-orm";function declaredColumns(options){let found=new Map,add2=(table2,column3)=>found.set(`${table2}.${column3}`,{table:table2,column:column3});for(let table2 of options.tables??[])for(let column3 of table2.columns??[])if(column3.references_user===!0)add2(table2.table_name,column3.name);for(let extra of options.extraReferences??[])add2(extra.table,extra.column);return[...found.values()]}async function declaredReferences(executor,schema3,declared,foreignKeys){let found=[];for(let{table:table2,column:column3}of declared){if(foreignKeys.some((ref3)=>ref3.table===table2&&ref3.column===column3))continue;let result=await executor.execute(sql45`
663
663
  select a.attnotnull as required,
664
664
  exists (select 1 from pg_attribute i
665
665
  where i.attrelid = a.attrelid and i.attname = 'id' and not i.attisdropped) as has_id
666
666
  from pg_attribute a
667
667
  where a.attrelid = to_regclass(format('%I.%I', ${schema3}::text, ${table2}::text))
668
- and a.attname = ${column3} and not a.attisdropped`),row=rowsOfResult(result)[0];if(row===void 0)continue;found.push({table:table2,column:column3,required:Reflect.get(row,"required")===!0,onDelete:"a",hasId:Reflect.get(row,"has_id")===!0,declared:!0})}return found}function ruleFor(policy2,ref3){return policy2[`${ref3.table}.${ref3.column}`]??policy2[ref3.table]}function assertKeepReasons(policy2){for(let[entity,rule]of Object.entries(policy2))if(typeof rule==="object"&&rule.keep.trim()==="")throw new AccountErasureError(`Policy "${entity}": keep needs a reason`)}function problemOf(ref3,rule){if(rule==="nullify"&&ref3.required)return"nullify, but the column is NOT NULL";if(typeof rule==="object"&&ref3.declared!==!0&&ref3.onDelete!=="n"&&ref3.onDelete!=="d")return"keep, but the database does not release the reference when the user goes";return null}import{sql as sql47}from"drizzle-orm";var REDACTED2="Redacted by a data deletion request.";async function scrubAuditRows(executor,schema3,userId,rowIds){let present=await executor.execute(sql47`select to_regclass(format('%I.%I', ${schema3}::text, ${AUDIT_TABLE}::text)) is not null as p`);if(Reflect.get(rowsOfResult(present)[0]??{},"p")!==!0)return 0;let ids=`{${rowIds.join(",")}}`,result=await executor.execute(sql47`
669
- update ${sql47.identifier(schema3)}.${sql47.identifier(AUDIT_TABLE)}
668
+ and a.attname = ${column3} and not a.attisdropped`),row=rowsOfResult(result)[0];if(row===void 0)continue;found.push({table:table2,column:column3,required:Reflect.get(row,"required")===!0,onDelete:"a",hasId:Reflect.get(row,"has_id")===!0,declared:!0})}return found}function ruleFor(policy2,ref3){return policy2[`${ref3.table}.${ref3.column}`]??policy2[ref3.table]}function assertKeepReasons(policy2){for(let[entity,rule]of Object.entries(policy2))if(typeof rule==="object"&&rule.keep.trim()==="")throw new AccountErasureError(`Policy "${entity}": keep needs a reason`)}function problemOf(ref3,rule){if(rule==="nullify"&&ref3.required)return"nullify, but the column is NOT NULL";if(typeof rule==="object"&&ref3.declared!==!0&&ref3.onDelete!=="n"&&ref3.onDelete!=="d")return"keep, but the database does not release the reference when the user goes";return null}import{sql as sql46}from"drizzle-orm";var REDACTED2="Redacted by a data deletion request.";async function scrubAuditRows(executor,schema3,userId,rowIds){let present=await executor.execute(sql46`select to_regclass(format('%I.%I', ${schema3}::text, ${AUDIT_TABLE}::text)) is not null as p`);if(Reflect.get(rowsOfResult(present)[0]??{},"p")!==!0)return 0;let ids=`{${rowIds.join(",")}}`,result=await executor.execute(sql46`
669
+ update ${sql46.identifier(schema3)}.${sql46.identifier(AUDIT_TABLE)}
670
670
  set user_id = case when user_id::text = ${userId} then null else user_id end,
671
671
  entity_id = case when entity_id::text = ${userId} then null else entity_id end,
672
672
  ip_address = null, user_agent = null, query = null,
673
673
  old_values = '{}'::jsonb, new_values = '{}'::jsonb, summary = ${REDACTED2}
674
674
  where user_id::text = ${userId} or entity_id::text = ${userId}
675
- or entity_id::text = any (${ids}::text[])`),count6=typeof result==="object"&&result!==null?Reflect.get(result,"rowCount"):0;return typeof count6==="number"?count6:0}var log7=logger.scoped("auth.accountErasure"),ERASURE_REASON="Account erasure (KVKK/GDPR right to erasure)";async function plan(executor,schema3,userId,policy2,options){let planned=[],refused=[],foreignKeys=await userReferences(executor,schema3),declared=await declaredReferences(executor,schema3,declaredColumns(options),foreignKeys);for(let ref3 of[...foreignKeys,...declared]){if(ref3.table===AUDIT_TABLE)continue;let rows=await countReferences(executor,schema3,ref3,userId);if(rows===0)continue;let rule=ruleFor(policy2,ref3),name2=`${ref3.table}.${ref3.column}`;if(rule===void 0)refused.push(`${name2}: no rule`);else{let problem=problemOf(ref3,rule);if(problem===null)planned.push({ref:ref3,rule,rows});else refused.push(`${name2}: ${problem}`)}}if(refused.length>0)throw new AccountErasureError(`Erasure refused, references left unhandled: ${refused.join("; ")}`,refused.map((line)=>line.split(":")[0]??line));return planned}async function apply2(executor,schema3,userId,{ref:ref3,rule},summary){let table2=sql48`${sql48.identifier(schema3)}.${sql48.identifier(ref3.table)}`,column3=sql48.identifier(ref3.column),own=ref3.table==="users"?sql48` and id <> ${userId}`:sql48``,returning=ref3.hasId?sql48` returning id`:sql48``;if(rule==="delete"){let done=touchedOf(await executor.execute(sql48`delete from ${table2} where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.deleted[ref3.table]=(summary.deleted[ref3.table]??0)+done.count,done.ids}if(rule==="nullify"){let done=touchedOf(await executor.execute(sql48`update ${table2} set ${column3} = null where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.nullified[ref3.table]=(summary.nullified[ref3.table]??0)+done.count,[]}let rows=(summary.kept[ref3.table]?.rows??0)+await countReferences(executor,schema3,ref3,userId);return summary.kept[ref3.table]={rows,reason:rule.keep},[]}async function eraseUser(unit,userId,policy2,options={}){return assertKeepReasons(policy2),unit.withoutRules(ERASURE_REASON,()=>erase(unit,userId,policy2,options))}async function erase(unit,userId,policy2,options){let executor=executorOf2(unit),schema3=unit.schema,summary={sessions:await endUserSessions(unit,userId),deleted:{},nullified:{},kept:{},users:0,auditScrubbed:0},planned=await plan(executor,schema3,userId,policy2,options),deletedIds=[];for(let step of planned)deletedIds.push(...await apply2(executor,schema3,userId,step,summary));summary.auditScrubbed=await scrubAuditRows(executor,schema3,userId,deletedIds);let removed=await executor.execute(sql48`delete from ${sql48.identifier(schema3)}.users where id = ${userId}`);return summary.users=touchedOf(removed,!1).count,await unit.audit({entityName:"users",operation:"ERASE_USER",summary:"An account was erased.",severity:"info",category:"system",newValues:{...summary}}),log7.info("Account erased",{schema:schema3,...summary}),summary}init_hostPasswordCheck();init_hooks();init_linkAuthorization();init_profileSync();init_profileSyncHooks();import{sql as sql49}from"drizzle-orm";init_Logger2();init_schema();var log8=logger.scoped("tenant.purge"),PROTECTED_SCHEMAS=new Set(["public","information_schema"]);class TenantPurgeRefusedError extends Error{tenantId;status;constructor(tenantId,status){super(`Tenant ${tenantId} is ${status}: purging it needs force`);this.tenantId=tenantId;this.status=status;this.name="TenantPurgeRefusedError"}}function toRow(row){if(row===void 0)return null;return{subdomain:String(Reflect.get(row,"subdomain")),schemaName:String(Reflect.get(row,"schema_name")),status:String(Reflect.get(row,"status"))}}function assertDroppable(schemaName,mainSchema){if(validateIdentifier(schemaName),schemaName===mainSchema||PROTECTED_SCHEMAS.has(schemaName)||schemaName.startsWith("pg_"))throw Error(`Refusing to drop protected schema "${schemaName}"`)}async function purgeTenant(tenantId,options){let registry5=options.registry===void 0?currentRegistry():options.registry,main=sql49.identifier(validateIdentifier(options.mainSchema)),outcome=await options.db.transaction(async(tx)=>{await tx.execute(sql49`select pg_advisory_xact_lock(hashtext(${`tenant_purge:${tenantId}`}))`);let found=await tx.execute(sql49`select subdomain, schema_name, status from ${main}.tenants where id = ${tenantId} for update`),row=toRow(rowsOfResult(found)[0]);if(row===null){let leftover=registry5?.getTenantById(tenantId)?.schemaName;if(leftover!==void 0)assertDroppable(leftover,options.mainSchema),await tx.execute(sql49`drop schema if exists ${sql49.identifier(leftover)} cascade`);return{purged:!1,tenantId,alreadyPurged:!0}}if(row.status==="active"&&options.force!==!0)throw new TenantPurgeRefusedError(tenantId,row.status);return assertDroppable(row.schemaName,options.mainSchema),await writeTenantAudit(tx,options.mainSchema,{entityName:"tenants",entityId:tenantId,operation:"TENANT_PURGE",summary:`${row.subdomain} hard-deleted${options.reason?` (${options.reason})`:""}`,category:"admin",severity:"critical",oldValues:{subdomain:row.subdomain,schemaName:row.schemaName,status:row.status},newValues:{reason:options.reason??null,performedBy:options.performedBy??null}}),await tx.execute(sql49`drop schema if exists ${sql49.identifier(row.schemaName)} cascade`),await tx.execute(sql49`delete from ${main}.tenants where id = ${tenantId}`),{purged:!0,tenantId,subdomain:row.subdomain,schemaName:row.schemaName}});return await registry5?.forgetTenant(tenantId),log8.info(outcome.purged?"Tenant purged":"Tenant already purged",{tenantId}),outcome}function formErrors(rule,fields,context){let merged={...context.item,...context.entered},checked=validateFieldValues(fields,merged,{party:context.actor.side}).errors,errors2=new Map;for(let id of Object.keys(context.entered))if(!rule.form.includes(id))errors2.set(id,"unknown_field");for(let id of rule.form){let code=Object.hasOwn(checked,id)?checked[id]:void 0;if(code===void 0)continue;if(Object.hasOwn(context.entered,id)&&!isEmptyValue(context.entered[id])||code==="required")errors2.set(id,code)}return Object.fromEntries(errors2)}var holdsRole=(rule,context)=>context.actor.roles.some((role)=>rule.roles.includes(role)),onForm=(rule)=>rule.when!==null&&rule.form.includes(rule.when.field),conditionFails=(rule,context)=>rule.when!==null&&!evaluateCondition(rule.when,{...context.item,...context.entered});function ruleFailure(rule,fields,context){if(rule.side!==context.actor.side)return{code:"transition_side_forbidden"};if(!holdsRole(rule,context))return{code:"transition_role_forbidden"};if(rule.onlyCreator&&!context.isCreator)return{code:"transition_creator_only"};if(!onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(context.mode==="offer")return null;let fieldErrors=formErrors(rule,fields,context);if(Object.keys(fieldErrors).length>0)return{code:"transition_fields_invalid",fieldErrors};if(onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(rule.requireNote&&(context.note??"").trim()==="")return{code:"transition_note_required"};return null}var FLOW_FAILURE_CODES=["transition_unknown","transition_unknown_state","transition_source_mismatch","transition_from_final","transition_start_forbidden","transition_side_forbidden","transition_role_forbidden","transition_creator_only","transition_condition_not_met","transition_fields_invalid","transition_note_required"];function failureCodeOf(message){return FLOW_FAILURE_CODES.find((code)=>code===message)??null}function rulesOf(document){return document.transitions.flatMap((transition)=>{let common={key:transition.key,to:transition.to,side:transition.side,roles:transition.roles,form:transition.form,requireNote:transition.requireNote,onlyCreator:transition.onlyCreator===!0,when:transition.when??null};return(transition.from==="create"?[null]:transition.from).map((from)=>({...common,from}))})}function edgesOf(rules,fields){let grouped=new Map;for(let rule of rules){if(rule.from===null)continue;let targets=grouped.get(rule.from)??new Map;targets.set(rule.to,[...targets.get(rule.to)??[],rule]),grouped.set(rule.from,targets)}let edges=new Map;for(let[from,targets]of grouped)edges.set(from,[...targets].map(([to,edgeRules])=>({to,guard:(context)=>{let rule=edgeRules.find((candidate)=>candidate.key===context.key);if(rule===void 0)return"transition_source_mismatch";return ruleFailure(rule,fields,context)?.code??!0}})));return edges}function buildFlow(document,options={}){let rules=rulesOf(document),fields=document.fields??[],edges=edgesOf(rules,fields),transitions=Object.fromEntries(document.states.map((state)=>[state.key,edges.get(state.key)??[]])),terminal=document.states.filter((state)=>state.terminal===!0||options.isTerminal?.(state)===!0).map((state)=>state.key),declared=new Set(document.states.map((state)=>state.key));return{table:{initial:[...new Set(rules.filter((rule)=>rule.from===null&&declared.has(rule.to)).map((rule)=>rule.to))],terminal,transitions},rules,fields}}var REFUSALS={unknown_state:"transition_unknown_state",terminal_state:"transition_from_final",no_transition:"transition_source_mismatch"};function ruleOf(flow,key2,from){let found=flow.rules.find((rule)=>rule.key===key2&&rule.from===from);if(found!==void 0)return found;return flow.rules.some((rule)=>rule.key===key2)?"transition_source_mismatch":"transition_unknown"}function judge2(flow,rule,context){if(rule.from===null){if(!canStartIn(flow.table,rule.to))return{ok:!1,code:"transition_start_forbidden"};let failure2=ruleFailure(rule,flow.fields,context);return failure2===null?{ok:!0,rule}:{ok:!1,...failure2}}if(!Object.hasOwn(flow.table.transitions,rule.to))return{ok:!1,code:"transition_unknown_state"};let evaluation=evaluate(flow.table,rule.from,rule.to,context);if(evaluation.allowed)return{ok:!0,rule};if(evaluation.reason!=="guard_rejected")return{ok:!1,code:REFUSALS[evaluation.reason]};let failure=ruleFailure(rule,flow.fields,context),code=failure?.code??failureCodeOf(evaluation.message);return code===null?{ok:!1,code:"transition_source_mismatch"}:{ok:!1,code,...failure?.fieldErrors?{fieldErrors:failure.fieldErrors}:{}}}function decideTransition(flow,attempt3){let rule=ruleOf(flow,attempt3.key,attempt3.from);if(typeof rule==="string")return{ok:!1,code:rule};return judge2(flow,rule,{...attempt3,mode:"perform"})}function allowedTransitions(flow,offer){return flow.rules.filter((rule)=>rule.from===offer.state&&ruleOf(flow,rule.key,rule.from)===rule&&judge2(flow,rule,{...offer,from:offer.state,key:rule.key,entered:{},mode:"offer"}).ok)}function flowProblems(document,options={}){let problems=[],add2=(code,subject,message)=>problems.push({code,subject,message}),states=new Set;for(let state of document.states){if(states.has(state.key))add2("duplicate_state",state.key,`State "${state.key}" is declared twice`);states.add(state.key)}let defined=new Set((document.fields??[]).map((field2)=>field2.id)),keys=new Set;for(let transition of document.transitions){if(keys.has(transition.key))add2("duplicate_transition",transition.key,`Transition "${transition.key}" is declared twice`);keys.add(transition.key);let sources=transition.from==="create"?[]:transition.from;if(transition.roles.length===0)add2("no_roles",transition.key,`Transition "${transition.key}" lists no role: nobody could make it`);if(transition.from!=="create"&&sources.length===0)add2("no_source",transition.key,`Transition "${transition.key}" starts from no state`);for(let state of[...sources,transition.to])if(!states.has(state))add2("unknown_state",transition.key,`Transition "${transition.key}" names unknown state "${state}"`);for(let id of transition.form)if(!defined.has(id))add2("unknown_form_field",transition.key,`Transition "${transition.key}" asks for unknown field "${id}"`);if(transition.when!==void 0&&!defined.has(transition.when.field))add2("unknown_condition_field",transition.key,`Transition "${transition.key}" has a condition on unknown field "${transition.when.field}"`)}let flow=buildFlow(document,options);if(!flow.rules.some((rule)=>rule.from===null))add2("no_create_transition","","The flow has no transition that creates an item");for(let message of tableProblems(flow.table))add2("unusable_table","",message);return problems}function numberPeriod(format2,clock={}){if(!format2.yearly)return"";let year=new Intl.DateTimeFormat("en-US",{timeZone:clock.timeZone??"UTC",year:"numeric"}).formatToParts(clock.now??new Date).find((part)=>part.type==="year")?.value;if(year===void 0)throw RangeError("Could not read the year of the clock");return year.padStart(4,"0")}function formatNumber(format2,period,counter){if(!Number.isSafeInteger(counter)||counter<1)throw RangeError("A counter value is a positive integer");let separator=format2.separator??"-",padded=String(counter).padStart(format2.digits,"0");return[format2.prefix,period,padded].filter((part)=>part!=="").join(separator)}var NUMBER_COUNTER_TABLE="number_counters";function numberCounterTable(){return{table_name:NUMBER_COUNTER_TABLE,add_base_columns:!1,excluded_methods:["GET","POST","PUT","PATCH","DELETE","TOGGLE","VERIFICATION"],columns:[{name:"sequence",type:"varchar",length:128,notNull:!0},{name:"period",type:"varchar",length:16,notNull:!0,default:""},{name:"counter",type:"integer",notNull:!0,check:"counter >= 0"}],constraints:{unique:[{name:`${NUMBER_COUNTER_TABLE}_sequence_period_key`,columns:["sequence","period"]}]}}}var MAX_SEQUENCE_LENGTH=128;function assertSequenceKey(key2){if(key2===""||key2.length>MAX_SEQUENCE_LENGTH)throw RangeError(`A sequence key is 1 to ${MAX_SEQUENCE_LENGTH} characters`)}async function nextNumber(unit,sequence,clock={}){assertSequenceKey(sequence.key);let period=numberPeriod(sequence.format,clock),row=await unit.store.from(NUMBER_COUNTER_TABLE).upsert({conflict:{columns:["sequence","period"]},insert:{sequence:sequence.key,period,counter:1},set:{counter:{$inc:1}}});return{reference:formatNumber(sequence.format,period,row.counter),counter:row.counter,period}}async function raiseNumberCounter(unit,sequence,period,atLeast){if(!Number.isSafeInteger(atLeast)||atLeast<0)throw RangeError("A counter is raised to a non-negative integer");assertSequenceKey(sequence);let counters=unit.store.from(NUMBER_COUNTER_TABLE),row=await counters.upsert({conflict:{columns:["sequence","period"]},insert:{sequence,period,counter:atLeast},set:{counter:{$inc:0}}});if(row.counter>=atLeast)return row.counter;let[raised]=await counters.updateWhere({sequence,period,counter:{lt:atLeast}},{counter:atLeast});return raised?.counter??atLeast}export{writeTenantNotifications,writeTenantNotification,writeTenantAudit,visibleFieldIds,viewGroup,viewClaimOf,versionedDocumentTables,versionedDocumentImmutabilitySql,verifyUserPassword,validatePasswordStrength,validateNucleusConfig,validateFieldValues,validateFieldValue,validateFieldDefinitions,upper,unsafeExecutorOf,unitOfWorkFor,translate,toIndexEntries,tableProblems,tableExists,sum,sub,storeFromExecutor,statesOf,serve,safeRegExp,safeCast,runUnitOfWork,runRowView,runMigrations,runAggregateView,rulesOf,ruleFailure,round,resolveProfileSyncUpdates,replace,refreshTenantFeatures,refreshTenant,refreshAllTenants,readView,readMoney,readLedger,readDateRange,raiseNumberCounter,qualified,purgeTenant,purgeExpiredIdempotencyKeys,pruneFieldValues,provisionWithMigrations,profileSyncHooks,payloadHash,parseParams,parseFilterValue,param,ownedObjects,optionLabel,objectExists,numberPeriod,numberCounterTable,nucleusDataOf,now,nextNumber,min,migrationOwnedDropGuard,measure,max,lower,localize,lit,least,json,isTerminal,isTenantFeatureEnabled,isSystemActor,isStringList2 as isStringList,isRowView,isJsonObject2 as isJsonObject,isIndexed,isExpr,isEmptyValue,isCalendarDate,initialFieldValues,indexedFieldIds,indexColumnFor,hiddenFieldIds,hashPassword,hasEntityRules,greatest,getResolvedOptions2 as getResolvedOptions,formatNumber,formatConfigIssues,formErrors,flowProblems,fieldValuesSchema,fieldValueSchema,fieldDefinitionsSchema,fieldDefinitionSchema,failureCodeOf,evaluateCondition,evaluate,eraseUser,endUserSessions,encodeViewCursor,documentTransactionsOf,documentTableNames,documentLeaves,diffSeconds,diffDocuments,defineWebSocketRoute,defineViewRoute,defineRules,defineRoute,defineJobFor,defineJob,defineDocumentType,defineActionFor,defineAction,decodeViewCursor,decodeHeaderList,decideTransition,cursorValues,createViewBuilder,createUserAccount,createPgDocumentTransactions,createNucleusServer,createJobRunner,createEntityStore,createDocumentStore,createBootMigrations,countView,countRowView,countAggregateView,count,configureProfileSync,configureOAuthLinkAuthorization,configureAuthorizationDiscovery,concatWs,concat,computed,completeIdempotency,compileRowView,collectRoutes,col,codePointLength,coalesce,claimIdempotencyKey,checksumOf,caseWhen,canStartIn,canEnter,buildOpenApiDocument,buildNucleus,buildFlow,buildEntityRules,buildConfigViews,buildConfigView,bucket,bindDocumentStore,avg,allowedTransitions,allowedTargets,aggregateOf,add,actionGroup,WhereError,ViewParamError,ViewError,TenantPurgeRefusedError,StoreError,ScopeViolationError,SYSTEM_ACTOR_KINDS,RuleSet,RuleError,RESERVED_IDS,REFERENCE_PATTERN,NucleusTestApp,NUMBER_COUNTER_TABLE,MigrationFailedError,MigrationDefinitionError,MigrationChecksumError,MAX_VIEW_LIMIT,MAX_PREFIX_LENGTH,MAX_OPTIONS,MAX_FIELDS,LOCK_MODES,LENGTH_LIMITS,LEDGER_TABLE,IdempotencyConflictError,ID_PATTERN,IDEMPOTENCY_TABLE,FLOW_FAILURE_CODES,FIELD_PARTIES,FIELD_LOCALES,FIELD_KINDS,FIELD_ERROR_CODES,ExprError,EntityStore,EMAIL_PATTERN,DocumentUnreadableError,DEFINITION_ISSUE_CODES,DEFAULT_VIEW_LIMIT,DEFAULT_LOCK_TIMEOUT_MS,DEFAULT_ARRAY_IDENTITY,ConstraintError,CURRENCY_PATTERN,CONDITION_OPS,ActionError,AccountErasureError};
675
+ or entity_id::text = any (${ids}::text[])`),count6=typeof result==="object"&&result!==null?Reflect.get(result,"rowCount"):0;return typeof count6==="number"?count6:0}var log7=logger.scoped("auth.accountErasure"),ERASURE_REASON="Account erasure (KVKK/GDPR right to erasure)";async function plan(executor,schema3,userId,policy2,options){let planned=[],refused=[],foreignKeys=await userReferences(executor,schema3),declared=await declaredReferences(executor,schema3,declaredColumns(options),foreignKeys);for(let ref3 of[...foreignKeys,...declared]){if(ref3.table===AUDIT_TABLE)continue;let rows=await countReferences(executor,schema3,ref3,userId);if(rows===0)continue;let rule=ruleFor(policy2,ref3),name2=`${ref3.table}.${ref3.column}`;if(rule===void 0)refused.push(`${name2}: no rule`);else{let problem=problemOf(ref3,rule);if(problem===null)planned.push({ref:ref3,rule,rows});else refused.push(`${name2}: ${problem}`)}}if(refused.length>0)throw new AccountErasureError(`Erasure refused, references left unhandled: ${refused.join("; ")}`,refused.map((line)=>line.split(":")[0]??line));return planned}async function apply2(executor,schema3,userId,{ref:ref3,rule},summary){let table2=sql47`${sql47.identifier(schema3)}.${sql47.identifier(ref3.table)}`,column3=sql47.identifier(ref3.column),own=ref3.table==="users"?sql47` and id <> ${userId}`:sql47``,returning=ref3.hasId?sql47` returning id`:sql47``;if(rule==="delete"){let done=touchedOf(await executor.execute(sql47`delete from ${table2} where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.deleted[ref3.table]=(summary.deleted[ref3.table]??0)+done.count,done.ids}if(rule==="nullify"){let done=touchedOf(await executor.execute(sql47`update ${table2} set ${column3} = null where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.nullified[ref3.table]=(summary.nullified[ref3.table]??0)+done.count,[]}let rows=(summary.kept[ref3.table]?.rows??0)+await countReferences(executor,schema3,ref3,userId);return summary.kept[ref3.table]={rows,reason:rule.keep},[]}async function eraseUser(unit,userId,policy2,options={}){return assertKeepReasons(policy2),unit.withoutRules(ERASURE_REASON,()=>erase(unit,userId,policy2,options))}async function erase(unit,userId,policy2,options){let executor=executorOf2(unit),schema3=unit.schema,summary={sessions:await endUserSessions(unit,userId),deleted:{},nullified:{},kept:{},users:0,auditScrubbed:0},planned=await plan(executor,schema3,userId,policy2,options),deletedIds=[];for(let step of planned)deletedIds.push(...await apply2(executor,schema3,userId,step,summary));summary.auditScrubbed=await scrubAuditRows(executor,schema3,userId,deletedIds);let removed=await executor.execute(sql47`delete from ${sql47.identifier(schema3)}.users where id = ${userId}`);return summary.users=touchedOf(removed,!1).count,await unit.audit({entityName:"users",operation:"ERASE_USER",summary:"An account was erased.",severity:"info",category:"system",newValues:{...summary}}),log7.info("Account erased",{schema:schema3,...summary}),summary}init_hostPasswordCheck();init_hooks();init_linkAuthorization();init_profileSync();init_profileSyncHooks();import{sql as sql48}from"drizzle-orm";init_Logger2();init_schema();var log8=logger.scoped("tenant.purge"),PROTECTED_SCHEMAS=new Set(["public","information_schema"]);class TenantPurgeRefusedError extends Error{tenantId;status;constructor(tenantId,status){super(`Tenant ${tenantId} is ${status}: purging it needs force`);this.tenantId=tenantId;this.status=status;this.name="TenantPurgeRefusedError"}}function toRow(row){if(row===void 0)return null;return{subdomain:String(Reflect.get(row,"subdomain")),schemaName:String(Reflect.get(row,"schema_name")),status:String(Reflect.get(row,"status"))}}function assertDroppable(schemaName,mainSchema){if(validateIdentifier(schemaName),schemaName===mainSchema||PROTECTED_SCHEMAS.has(schemaName)||schemaName.startsWith("pg_"))throw Error(`Refusing to drop protected schema "${schemaName}"`)}async function purgeTenant(tenantId,options){let registry5=options.registry===void 0?currentRegistry():options.registry,main=sql48.identifier(validateIdentifier(options.mainSchema)),outcome=await options.db.transaction(async(tx)=>{await tx.execute(sql48`select pg_advisory_xact_lock(hashtext(${`tenant_purge:${tenantId}`}))`);let found=await tx.execute(sql48`select subdomain, schema_name, status from ${main}.tenants where id = ${tenantId} for update`),row=toRow(rowsOfResult(found)[0]);if(row===null){let leftover=registry5?.getTenantById(tenantId)?.schemaName;if(leftover!==void 0)assertDroppable(leftover,options.mainSchema),await tx.execute(sql48`drop schema if exists ${sql48.identifier(leftover)} cascade`);return{purged:!1,tenantId,alreadyPurged:!0}}if(row.status==="active"&&options.force!==!0)throw new TenantPurgeRefusedError(tenantId,row.status);return assertDroppable(row.schemaName,options.mainSchema),await writeTenantAudit(tx,options.mainSchema,{entityName:"tenants",entityId:tenantId,operation:"TENANT_PURGE",summary:`${row.subdomain} hard-deleted${options.reason?` (${options.reason})`:""}`,category:"admin",severity:"critical",oldValues:{subdomain:row.subdomain,schemaName:row.schemaName,status:row.status},newValues:{reason:options.reason??null,performedBy:options.performedBy??null}}),await tx.execute(sql48`drop schema if exists ${sql48.identifier(row.schemaName)} cascade`),await tx.execute(sql48`delete from ${main}.tenants where id = ${tenantId}`),{purged:!0,tenantId,subdomain:row.subdomain,schemaName:row.schemaName}});return await registry5?.forgetTenant(tenantId),log8.info(outcome.purged?"Tenant purged":"Tenant already purged",{tenantId}),outcome}function formErrors(rule,fields,context){let merged={...context.item,...context.entered},checked=validateFieldValues(fields,merged,{party:context.actor.side}).errors,errors2=new Map;for(let id of Object.keys(context.entered))if(!rule.form.includes(id))errors2.set(id,"unknown_field");for(let id of rule.form){let code=Object.hasOwn(checked,id)?checked[id]:void 0;if(code===void 0)continue;if(Object.hasOwn(context.entered,id)&&!isEmptyValue(context.entered[id])||code==="required")errors2.set(id,code)}return Object.fromEntries(errors2)}var holdsRole=(rule,context)=>context.actor.roles.some((role)=>rule.roles.includes(role)),onForm=(rule)=>rule.when!==null&&rule.form.includes(rule.when.field),conditionFails=(rule,context)=>rule.when!==null&&!evaluateCondition(rule.when,{...context.item,...context.entered});function ruleFailure(rule,fields,context){if(rule.side!==context.actor.side)return{code:"transition_side_forbidden"};if(!holdsRole(rule,context))return{code:"transition_role_forbidden"};if(rule.onlyCreator&&!context.isCreator)return{code:"transition_creator_only"};if(!onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(context.mode==="offer")return null;let fieldErrors=formErrors(rule,fields,context);if(Object.keys(fieldErrors).length>0)return{code:"transition_fields_invalid",fieldErrors};if(onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(rule.requireNote&&(context.note??"").trim()==="")return{code:"transition_note_required"};return null}var FLOW_FAILURE_CODES=["transition_unknown","transition_unknown_state","transition_source_mismatch","transition_from_final","transition_start_forbidden","transition_side_forbidden","transition_role_forbidden","transition_creator_only","transition_condition_not_met","transition_fields_invalid","transition_note_required"];function failureCodeOf(message){return FLOW_FAILURE_CODES.find((code)=>code===message)??null}function rulesOf(document){return document.transitions.flatMap((transition)=>{let common={key:transition.key,to:transition.to,side:transition.side,roles:transition.roles,form:transition.form,requireNote:transition.requireNote,onlyCreator:transition.onlyCreator===!0,when:transition.when??null};return(transition.from==="create"?[null]:transition.from).map((from)=>({...common,from}))})}function edgesOf(rules,fields){let grouped=new Map;for(let rule of rules){if(rule.from===null)continue;let targets=grouped.get(rule.from)??new Map;targets.set(rule.to,[...targets.get(rule.to)??[],rule]),grouped.set(rule.from,targets)}let edges=new Map;for(let[from,targets]of grouped)edges.set(from,[...targets].map(([to,edgeRules])=>({to,guard:(context)=>{let rule=edgeRules.find((candidate)=>candidate.key===context.key);if(rule===void 0)return"transition_source_mismatch";return ruleFailure(rule,fields,context)?.code??!0}})));return edges}function buildFlow(document,options={}){let rules=rulesOf(document),fields=document.fields??[],edges=edgesOf(rules,fields),transitions=Object.fromEntries(document.states.map((state)=>[state.key,edges.get(state.key)??[]])),terminal=document.states.filter((state)=>state.terminal===!0||options.isTerminal?.(state)===!0).map((state)=>state.key),declared=new Set(document.states.map((state)=>state.key));return{table:{initial:[...new Set(rules.filter((rule)=>rule.from===null&&declared.has(rule.to)).map((rule)=>rule.to))],terminal,transitions},rules,fields}}var REFUSALS={unknown_state:"transition_unknown_state",terminal_state:"transition_from_final",no_transition:"transition_source_mismatch"};function ruleOf(flow,key2,from){let found=flow.rules.find((rule)=>rule.key===key2&&rule.from===from);if(found!==void 0)return found;return flow.rules.some((rule)=>rule.key===key2)?"transition_source_mismatch":"transition_unknown"}function judge2(flow,rule,context){if(rule.from===null){if(!canStartIn(flow.table,rule.to))return{ok:!1,code:"transition_start_forbidden"};let failure2=ruleFailure(rule,flow.fields,context);return failure2===null?{ok:!0,rule}:{ok:!1,...failure2}}if(!Object.hasOwn(flow.table.transitions,rule.to))return{ok:!1,code:"transition_unknown_state"};let evaluation=evaluate(flow.table,rule.from,rule.to,context);if(evaluation.allowed)return{ok:!0,rule};if(evaluation.reason!=="guard_rejected")return{ok:!1,code:REFUSALS[evaluation.reason]};let failure=ruleFailure(rule,flow.fields,context),code=failure?.code??failureCodeOf(evaluation.message);return code===null?{ok:!1,code:"transition_source_mismatch"}:{ok:!1,code,...failure?.fieldErrors?{fieldErrors:failure.fieldErrors}:{}}}function decideTransition(flow,attempt3){let rule=ruleOf(flow,attempt3.key,attempt3.from);if(typeof rule==="string")return{ok:!1,code:rule};return judge2(flow,rule,{...attempt3,mode:"perform"})}function allowedTransitions(flow,offer){return flow.rules.filter((rule)=>rule.from===offer.state&&ruleOf(flow,rule.key,rule.from)===rule&&judge2(flow,rule,{...offer,from:offer.state,key:rule.key,entered:{},mode:"offer"}).ok)}function flowProblems(document,options={}){let problems=[],add2=(code,subject,message)=>problems.push({code,subject,message}),states=new Set;for(let state of document.states){if(states.has(state.key))add2("duplicate_state",state.key,`State "${state.key}" is declared twice`);states.add(state.key)}let defined=new Set((document.fields??[]).map((field2)=>field2.id)),keys=new Set;for(let transition of document.transitions){if(keys.has(transition.key))add2("duplicate_transition",transition.key,`Transition "${transition.key}" is declared twice`);keys.add(transition.key);let sources=transition.from==="create"?[]:transition.from;if(transition.roles.length===0)add2("no_roles",transition.key,`Transition "${transition.key}" lists no role: nobody could make it`);if(transition.from!=="create"&&sources.length===0)add2("no_source",transition.key,`Transition "${transition.key}" starts from no state`);for(let state of[...sources,transition.to])if(!states.has(state))add2("unknown_state",transition.key,`Transition "${transition.key}" names unknown state "${state}"`);for(let id of transition.form)if(!defined.has(id))add2("unknown_form_field",transition.key,`Transition "${transition.key}" asks for unknown field "${id}"`);if(transition.when!==void 0&&!defined.has(transition.when.field))add2("unknown_condition_field",transition.key,`Transition "${transition.key}" has a condition on unknown field "${transition.when.field}"`)}let flow=buildFlow(document,options);if(!flow.rules.some((rule)=>rule.from===null))add2("no_create_transition","","The flow has no transition that creates an item");for(let message of tableProblems(flow.table))add2("unusable_table","",message);return problems}function numberPeriod(format2,clock={}){if(!format2.yearly)return"";let year=new Intl.DateTimeFormat("en-US",{timeZone:clock.timeZone??"UTC",year:"numeric"}).formatToParts(clock.now??new Date).find((part)=>part.type==="year")?.value;if(year===void 0)throw RangeError("Could not read the year of the clock");return year.padStart(4,"0")}function formatNumber(format2,period,counter){if(!Number.isSafeInteger(counter)||counter<1)throw RangeError("A counter value is a positive integer");let separator=format2.separator??"-",padded=String(counter).padStart(format2.digits,"0");return[format2.prefix,period,padded].filter((part)=>part!=="").join(separator)}var NUMBER_COUNTER_TABLE="number_counters";function numberCounterTable(){return{table_name:NUMBER_COUNTER_TABLE,add_base_columns:!1,excluded_methods:["GET","POST","PUT","PATCH","DELETE","TOGGLE","VERIFICATION"],columns:[{name:"sequence",type:"varchar",length:128,notNull:!0},{name:"period",type:"varchar",length:16,notNull:!0,default:""},{name:"counter",type:"integer",notNull:!0,check:"counter >= 0"}],constraints:{unique:[{name:`${NUMBER_COUNTER_TABLE}_sequence_period_key`,columns:["sequence","period"]}]}}}var MAX_SEQUENCE_LENGTH=128;function assertSequenceKey(key2){if(key2===""||key2.length>MAX_SEQUENCE_LENGTH)throw RangeError(`A sequence key is 1 to ${MAX_SEQUENCE_LENGTH} characters`)}async function nextNumber(unit,sequence,clock={}){assertSequenceKey(sequence.key);let period=numberPeriod(sequence.format,clock),row=await unit.store.from(NUMBER_COUNTER_TABLE).upsert({conflict:{columns:["sequence","period"]},insert:{sequence:sequence.key,period,counter:1},set:{counter:{$inc:1}}});return{reference:formatNumber(sequence.format,period,row.counter),counter:row.counter,period}}async function raiseNumberCounter(unit,sequence,period,atLeast){if(!Number.isSafeInteger(atLeast)||atLeast<0)throw RangeError("A counter is raised to a non-negative integer");assertSequenceKey(sequence);let counters=unit.store.from(NUMBER_COUNTER_TABLE),row=await counters.upsert({conflict:{columns:["sequence","period"]},insert:{sequence,period,counter:atLeast},set:{counter:{$inc:0}}});if(row.counter>=atLeast)return row.counter;let[raised]=await counters.updateWhere({sequence,period,counter:{lt:atLeast}},{counter:atLeast});return raised?.counter??atLeast}export{writeTenantNotifications,writeTenantNotification,writeTenantAudit,visibleFieldIds,viewGroup,viewClaimOf,versionedDocumentTables,versionedDocumentImmutabilitySql,verifyUserPassword,validatePasswordStrength,validateNucleusConfig,validateFieldValues,validateFieldValue,validateFieldDefinitions,upper,unsafeExecutorOf,unitOfWorkFor,translate,toIndexEntries,tableProblems,tableExists,sum,sub,storeFromExecutor,statesOf,serve,safeRegExp,safeCast,runUnitOfWork,runRowView,runMigrations,runAggregateView,rulesOf,ruleFailure,round,resolveProfileSyncUpdates,replace,refreshTenantFeatures,refreshTenant,refreshAllTenants,readView,readMoney,readLedger,readDateRange,raiseNumberCounter,qualified,purgeTenant,purgeExpiredIdempotencyKeys,pruneFieldValues,provisionWithMigrations,profileSyncHooks,payloadHash,parseParams,parseFilterValue,param,ownedObjects,optionLabel,objectExists,numberPeriod,numberCounterTable,nucleusDataOf,now,nextNumber,min,migrationOwnedDropGuard,measure,max,lower,localize,lit,least,json,isTerminal,isTenantFeatureEnabled,isSystemActor,isStringList2 as isStringList,isRowView,isJsonObject2 as isJsonObject,isIndexed,isExpr,isEmptyValue,isCalendarDate,initialFieldValues,indexedFieldIds,indexColumnFor,hiddenFieldIds,hashPassword,hasEntityRules,greatest,getResolvedOptions2 as getResolvedOptions,formatNumber,formatConfigIssues,formErrors,flowProblems,fieldValuesSchema,fieldValueSchema,fieldDefinitionsSchema,fieldDefinitionSchema,failureCodeOf,evaluateCondition,evaluate,eraseUser,endUserSessions,encodeViewCursor,documentTransactionsOf,documentTableNames,documentLeaves,diffSeconds,diffDocuments,defineWebSocketRoute,defineViewRoute,defineRules,defineRoute,defineJobFor,defineJob,defineDocumentType,defineActionFor,defineAction,decodeViewCursor,decodeHeaderList,decideTransition,cursorValues,createViewBuilder,createUserAccount,createPgDocumentTransactions,createNucleusServer,createJobRunner,createEntityStore,createDocumentStore,createBootMigrations,countView,countRowView,countAggregateView,count,configureProfileSync,configureOAuthLinkAuthorization,configureAuthorizationDiscovery,concatWs,concat,computed,completeIdempotency,compileRowView,collectRoutes,col,codePointLength,coalesce,claimIdempotencyKey,checksumOf,caseWhen,canStartIn,canEnter,buildOpenApiDocument,buildNucleus,buildFlow,buildEntityRules,buildConfigViews,buildConfigView,bucket,bindDocumentStore,avg,allowedTransitions,allowedTargets,aggregateOf,add,actionGroup,WhereError,ViewParamError,ViewError,TenantPurgeRefusedError,StoreError,ScopeViolationError,SYSTEM_ACTOR_KINDS,RuleSet,RuleError,RESERVED_IDS,REFERENCE_PATTERN,NucleusTestApp,NUMBER_COUNTER_TABLE,MigrationFailedError,MigrationDefinitionError,MigrationChecksumError,MAX_VIEW_LIMIT,MAX_PREFIX_LENGTH,MAX_OPTIONS,MAX_FIELDS,LOCK_MODES,LENGTH_LIMITS,LEDGER_TABLE,IdempotencyConflictError,ID_PATTERN,IDEMPOTENCY_TABLE,FLOW_FAILURE_CODES,FIELD_PARTIES,FIELD_LOCALES,FIELD_KINDS,FIELD_ERROR_CODES,ExprError,EntityStore,EMAIL_PATTERN,DocumentUnreadableError,DEFINITION_ISSUE_CODES,DEFAULT_VIEW_LIMIT,DEFAULT_LOCK_TIMEOUT_MS,DEFAULT_ARRAY_IDENTITY,ConstraintError,CURRENCY_PATTERN,CONDITION_OPS,ActionError,AccountErasureError};
@@ -99,7 +99,9 @@ export interface CreateNucleusServerOptions {
99
99
  };
100
100
  /**
101
101
  * Recurring jobs (`defineJob`): nucleus runs each on its schedule, per tenant of its scope, in a
102
- * unit of work, under a transaction-level advisory lock so a second replica skips the pass. Passes
102
+ * unit of work that takes the job's transaction-level advisory lock first, so a second replica skips.
103
+ * A pass holds one pool connection at a time and at most `jobHost.maxConcurrentPasses` (default 1)
104
+ * passes run at once, so the jobs cannot starve the pool of the host's requests. Passes
103
105
  * start once the server listens; `stop()` waits for the pass in flight before the pool closes.
104
106
  * Needs a database: `jobHost`, or the one of `actions.host`; with neither, nucleus's own pool.
105
107
  */
@@ -1,14 +1,20 @@
1
1
  import type { EntityStoreOptions } from '../../Data/EntityStore';
2
2
  import type { UnitDatabase } from '../../Data/unitTypes';
3
3
  import { type Logger } from '../Logger';
4
- import type { JobDefinition } from './defineJob';
4
+ import type { JobDefinition, UnitRunner } from './defineJob';
5
5
  import { type JobClock } from './jobClock';
6
6
  import { type PassReport, type TenantSource } from './tenantWalk';
7
- export declare const JOBS_SCOPE = "jobs";
7
+ export { JOBS_SCOPE, jobLockKey } from './jobLock';
8
8
  /** What the host supplies ONCE for every job. */
9
9
  export interface JobHost {
10
10
  /** The drizzle database the units open their transactions on. */
11
11
  db: UnitDatabase;
12
+ /**
13
+ * Opens each tenant's unit. Default: `runUnitOfWork` on `db`. Nucleus's own pool passes its
14
+ * `data.runUnitOfWork`, so a job's unit gets the install's rules, relations and session limits
15
+ * (statement and idle-in-transaction timeouts) like a request's does.
16
+ */
17
+ runUnit?: UnitRunner;
12
18
  /** The main schema: the one `scope: 'main'` jobs run in. */
13
19
  mainSchema: string;
14
20
  /** The tenants to walk. */
@@ -22,6 +28,12 @@ export interface JobHost {
22
28
  tables?: EntityStoreOptions['tables'];
23
29
  relations?: EntityStoreOptions['relations'];
24
30
  logger?: Logger;
31
+ /**
32
+ * `jobs.maxConcurrentPasses`: how many passes of ALL jobs run at once in this process, default 1.
33
+ * A pass holds one pool connection at a time, so this is also the most connections the jobs take
34
+ * from the pool; the rest stays for the host's requests. Raise it only on a pool far larger than it.
35
+ */
36
+ maxConcurrentPasses?: number;
25
37
  }
26
38
  export interface JobRunnerOptions {
27
39
  host: JobHost;
@@ -39,10 +51,9 @@ export interface JobRunner {
39
51
  /** The declared job names, in registration order. */
40
52
  readonly names: readonly string[];
41
53
  }
42
- /** The job's lock name. The same string is the same lock on every replica. */
43
- export declare const jobLockKey: (name: string) => string;
44
54
  /**
45
- * Runs the declared jobs: staggered first passes, one pass at a time per job, a replica-safe lock
46
- * per pass, tenant isolation and quick capped retries (see `createJobLoop`).
55
+ * Runs the declared jobs: staggered first passes, one pass at a time per job and at most
56
+ * `maxConcurrentPasses` across all jobs, a replica-safe lock per tenant unit, tenant isolation and
57
+ * quick capped retries (see `createJobLoop`).
47
58
  */
48
59
  export declare function createJobRunner(options: JobRunnerOptions): JobRunner;
@@ -1,3 +1,4 @@
1
+ import type { NucleusData, NucleusUnitOptions } from '../../Data/nucleusData';
1
2
  import type { EntityMap } from '../../Data/storeTypes';
2
3
  import type { UnitOfWork, UnitOfWorkOptions } from '../../Data/unitTypes';
3
4
  import type { ScopedLogger } from '../Logger';
@@ -9,6 +10,14 @@ export interface JobResult {
9
10
  readonly handled: number;
10
11
  readonly failed: number;
11
12
  }
13
+ /** How a job's unit is opened: `runUnitOfWork` on the host's database, or nucleus's own `data.runUnitOfWork` (rules, relations, session limits bound). */
14
+ export type UnitRunner = NucleusData['runUnitOfWork'];
15
+ /** What `execute` returns when another replica holds the job's lock: nothing ran. */
16
+ export declare const JOB_LOCKED: {
17
+ readonly locked: true;
18
+ };
19
+ /** The result of one tenant's unit: the job's own, or "the lock was taken, nothing ran". */
20
+ export type JobOutcome = JobResult | typeof JOB_LOCKED;
12
21
  /** What a run knows besides its unit of work. */
13
22
  export interface JobContext {
14
23
  /** The job's name, as declared. */
@@ -21,9 +30,10 @@ export interface JobContext {
21
30
  readonly logger: ScopedLogger;
22
31
  }
23
32
  /**
24
- * A recurring job (N6). Nucleus owns the schedule: per pass it takes a transaction-level advisory
25
- * lock named after the job (a second replica skips), walks the tenants of `scope`, and runs `run`
26
- * in ONE unit of work per tenant (commit when it resolves, rollback when it throws).
33
+ * A recurring job (N6). Nucleus owns the schedule: a pass walks the tenants of `scope` and runs
34
+ * `run` in ONE unit of work per tenant (commit when it resolves, rollback when it throws). Each
35
+ * unit takes the job's transaction-level advisory lock as its first statement, on its own single
36
+ * connection: a second replica (or a second pass) finds it taken and skips that tenant.
27
37
  */
28
38
  export interface JobSpec<M extends EntityMap> {
29
39
  /** Unique, stable: the lock's name and the log scope (`floor.idleSessions` logs as `jobs.floor.idleSessions`). */
@@ -44,8 +54,8 @@ export interface JobDefinition {
44
54
  readonly everySeconds: number;
45
55
  readonly scope: JobScope;
46
56
  readonly firstRunAfterSeconds: number | undefined;
47
- /** Opens the unit of work for one tenant and runs the job in it. */
48
- execute(options: UnitOfWorkOptions, ctx: JobContext): Promise<JobResult>;
57
+ /** Opens the unit of work for one tenant, takes the job's lock in it, and runs the job. */
58
+ execute(options: NucleusUnitOptions, ctx: JobContext, run: UnitRunner): Promise<JobOutcome>;
49
59
  }
50
60
  /**
51
61
  * Declares a job over the entity map `M` (the generated `Entities`): `defineJobFor<Entities>()`
@@ -0,0 +1,3 @@
1
+ export declare const JOBS_SCOPE = "jobs";
2
+ /** The job's lock name. The same string is the same lock on every replica. */
3
+ export declare const jobLockKey: (name: string) => string;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A counting semaphore for job passes: at most `size` passes run at once in this process, so the
3
+ * jobs can never hold more than `size` pool connections and requests always keep the rest.
4
+ * Waiters are served in order; `close()` frees them with `false` so a stopping runner does not
5
+ * wait for a queue of passes that will never run.
6
+ */
7
+ export interface JobSlots {
8
+ /** Waits for a free slot. `false` when the slots were closed meanwhile: do not run. */
9
+ acquire(): Promise<boolean>;
10
+ release(): void;
11
+ close(): void;
12
+ /** Passes running right now. */
13
+ readonly busy: number;
14
+ }
15
+ export declare const DEFAULT_MAX_CONCURRENT_PASSES = 1;
16
+ export declare function createJobSlots(size: number): JobSlots;
@@ -1,6 +1,6 @@
1
1
  import type { ScopedLogger } from '../Logger';
2
2
  import type { TenantRecord, TenantStatus } from '../Tenant/types';
3
- import type { JobResult, JobScope } from './defineJob';
3
+ import type { JobOutcome, JobScope } from './defineJob';
4
4
  /** One schema a job can visit. `id` is null for the main schema. */
5
5
  export interface TenantRef {
6
6
  readonly id: string | null;
@@ -34,7 +34,9 @@ export interface PassReport {
34
34
  }
35
35
  export declare const SKIPPED_PASS: PassReport;
36
36
  /**
37
- * Visits every target in turn. A target that throws is logged and counted as one failure; the
38
- * others still run.
37
+ * Visits every target in turn, one connection at a time. A target that throws is logged and counted
38
+ * as one failure; the others still run. A target whose job lock another replica holds is not run:
39
+ * when it is the first, that replica is mid-pass and the whole pass is skipped; when it comes later,
40
+ * the walk stops, since the other replica is walking the same list.
39
41
  */
40
- export declare function walkTargets(targets: readonly TenantRef[], visit: (target: TenantRef) => Promise<JobResult>, log: ScopedLogger): Promise<PassReport>;
42
+ export declare function walkTargets(targets: readonly TenantRef[], visit: (target: TenantRef) => Promise<JobOutcome>, log: ScopedLogger): Promise<PassReport>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nucleus-core-ts",
3
- "version": "0.10.189",
3
+ "version": "0.10.190",
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",