@stacksjs/api 0.71.2 → 0.71.10

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.
@@ -12,6 +12,8 @@ import type { SchemaObject } from './generate-types';
12
12
  export declare function ruleToSchema(rule: unknown): Record<string, unknown>;
13
13
  /** Whether a rule says the field must be present. */
14
14
  export declare function ruleIsRequired(rule: unknown): boolean;
15
+ /** Convert a defineModel() definition into its public response schema. */
16
+ export declare function modelDefinitionToSchema(model: Record<string, any>): SchemaObject;
15
17
  /**
16
18
  * The answers an operation documents: the defaults, plus whatever the action
17
19
  * says about itself.
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  // @bun
2
- var BJ=Object.defineProperty;var TJ=($)=>$;function jJ($,J){this[$]=TJ.bind(null,J)}var x$=($,J)=>{for(var O in J)BJ($,O,{get:J[O],enumerable:!0,configurable:!0,set:jJ.bind(J,O)})};var d=($,J)=>()=>($&&(J=$($=0)),J);var l=import.meta.require;var k$={};x$(k$,{schemaType:()=>w,renderOpenApiTypes:()=>DJ});function _J($){return typeof $==="string"?JSON.stringify($):String($)}function w($){if(!$)return"unknown";if($.enum?.length)return $.enum.map(_J).join(" | ");if($.type==="string")return"string";if($.type==="number"||$.type==="integer")return"number";if($.type==="boolean")return"boolean";if($.type==="null")return"null";if($.type==="array")return`Array<${w($.items)}>`;if($.type==="object"||$.properties||$.additionalProperties){let J=new Set($.required||[]),O=Object.entries($.properties||{}).map(([G,Z])=>`${JSON.stringify(G)}${J.has(G)?"":"?"}: ${w(Z)}`);if($.additionalProperties){let G=$.additionalProperties===!0?"unknown":w($.additionalProperties);O.push(`[key: string]: ${G}`)}return O.length?`{ ${O.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function NJ($=[]){return` parameters: {
2
+ var NJ=Object.defineProperty;var HJ=($)=>$;function AJ($,J){this[$]=HJ.bind(null,J)}var Q$=($,J)=>{for(var O in J)NJ($,O,{get:J[O],enumerable:!0,configurable:!0,set:AJ.bind(J,O)})};var d=($,J)=>()=>($&&(J=$($=0)),J);var n=import.meta.require;var f$={};Q$(f$,{schemaType:()=>w,renderOpenApiTypes:()=>IJ});function UJ($){return typeof $==="string"?JSON.stringify($):String($)}function w($){if(!$)return"unknown";if($.enum?.length)return $.enum.map(UJ).join(" | ");if($.type==="string")return"string";if($.type==="number"||$.type==="integer")return"number";if($.type==="boolean")return"boolean";if($.type==="null")return"null";if($.type==="array")return`Array<${w($.items)}>`;if($.type==="object"||$.properties||$.additionalProperties){let J=new Set($.required||[]),O=Object.entries($.properties||{}).map(([G,Z])=>`${JSON.stringify(G)}${J.has(G)?"":"?"}: ${w(Z)}`);if($.additionalProperties){let G=$.additionalProperties===!0?"unknown":w($.additionalProperties);O.push(`[key: string]: ${G}`)}return O.length?`{ ${O.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function EJ($=[]){return` parameters: {
3
3
  ${["query","header","path","cookie"].map((O)=>{let G=$.filter((z)=>z.in===O);if(!G.length)return` ${O}?: never`;let Z=G.map((z)=>`${JSON.stringify(z.name)}${z.required?"":"?"}: ${w(z.schema)}`);return` ${O}${G.every((z)=>!z.required)?"?":""}: { ${Z.join("; ")} }`}).join(`
4
4
  `)}
5
- }`}function R$($){if(!$||!Object.keys($).length)return"never";return`{ ${Object.entries($).map(([J,O])=>`${JSON.stringify(J)}: ${w(O.schema)}`).join("; ")} }`}function HJ($){let J=$.requestBody?`
6
- requestBody${$.requestBody.required?"":"?"}: { content: ${R$($.requestBody.content)} }`:`
7
- requestBody?: never`,O=Object.entries($.responses||{}).map(([G,Z])=>` ${JSON.stringify(G)}: { content: ${R$(Z.content)} }`);return`{
8
- ${NJ($.parameters)}${J}
5
+ }`}function P$($){if(!$||!Object.keys($).length)return"never";return`{ ${Object.entries($).map(([J,O])=>`${JSON.stringify(J)}: ${w(O.schema)}`).join("; ")} }`}function SJ($){let J=$.requestBody?`
6
+ requestBody${$.requestBody.required?"":"?"}: { content: ${P$($.requestBody.content)} }`:`
7
+ requestBody?: never`,O=Object.entries($.responses||{}).map(([G,Z])=>` ${JSON.stringify(G)}: { content: ${P$(Z.content)} }`);return`{
8
+ ${EJ($.parameters)}${J}
9
9
  responses: {
10
10
  ${O.join(`
11
11
  `)}
12
12
  }
13
- }`}function DJ($){let J=Object.entries($.paths||{}).map(([G,Z])=>{let z=AJ.map((Q)=>{let X=Z[Q];return X?` ${Q}: ${HJ(X)}`:` ${Q}?: never`});return` ${JSON.stringify(G)}: {
13
+ }`}function IJ($){let J=Object.entries($.paths||{}).map(([G,Z])=>{let z=DJ.map((Q)=>{let L=Z[Q];return L?` ${Q}: ${SJ(L)}`:` ${Q}?: never`});return` ${JSON.stringify(G)}: {
14
14
  ${z.join(`
15
15
  `)}
16
16
  }`}),O=Object.entries($.components?.schemas||{}).map(([G,Z])=>` ${JSON.stringify(G)}: ${w(Z)}`);return`/**
@@ -29,13 +29,13 @@ ${O.join(`
29
29
  `)}
30
30
  }
31
31
  }
32
- `}var AJ;var z$=d(()=>{AJ=["get","put","post","delete","options","head","patch","trace"]});var f$={};x$(f$,{renderApiClient:()=>FJ,methodName:()=>P$});function P$($){let J=$.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean),O=J[0]?.toLowerCase()==="api"?J.slice(1):J[1]?.toLowerCase()==="api"?[J[0],...J.slice(2)]:J,[G,...Z]=O;if(!G)return"call";let z=G.charAt(0).toLowerCase()+G.slice(1),Q=Z.map((L)=>L.charAt(0).toUpperCase()+L.slice(1)),X=[z,...Q].join("");return/^[a-z_$]/i.test(X)?X:`call${X.charAt(0).toUpperCase()}${X.slice(1)}`}function UJ($){let J=$.responses??{},O=Object.keys(J).find((z)=>z.startsWith("2"));if(!O)return"unknown";let G=J[O]?.content,Z=G?.["application/json"]??Object.values(G??{})[0];return Z?.schema?w(Z.schema):"unknown"}function EJ($,J=" "){let O=$.filter(Boolean);if(!O.length)return"";return`${J}/**
32
+ `}var DJ;var L$=d(()=>{DJ=["get","put","post","delete","options","head","patch","trace"]});var g$={};Q$(g$,{renderApiClient:()=>RJ,methodName:()=>b$});function b$($){let J=$.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean),O=J[0]?.toLowerCase()==="api"?J.slice(1):J[1]?.toLowerCase()==="api"?[J[0],...J.slice(2)]:J,[G,...Z]=O;if(!G)return"call";let z=G.charAt(0).toLowerCase()+G.slice(1),Q=Z.map((T)=>T.charAt(0).toUpperCase()+T.slice(1)),L=[z,...Q].join("");return/^[a-z_$]/i.test(L)?L:`call${L.charAt(0).toUpperCase()}${L.slice(1)}`}function VJ($){let J=$.responses??{},O=Object.keys(J).find((z)=>z.startsWith("2"));if(!O)return"unknown";let G=J[O]?.content,Z=G?.["application/json"]??Object.values(G??{})[0];return Z?.schema?w(Z.schema):"unknown"}function MJ($,J=" "){let O=$.filter(Boolean);if(!O.length)return"";return`${J}/**
33
33
  ${O.map((G)=>`${J} * ${G}`).join(`
34
34
  `)}
35
35
  ${J} */
36
- `}function IJ($,J,O,G){let Z=O.parameters??[],z=Z.filter((H)=>H.in==="path"),Q=Z.filter((H)=>H.in==="query"),X=O.requestBody?.content?.["application/json"]?.schema,L=Boolean(O.requestBody?.required),W=[];for(let H of[...z,...Q]){let P=H.in==="path"||H.required;W.push(`${JSON.stringify(H.name)}${P?"":"?"}: ${w(H.schema)}`)}if(X)W.push(`body${L?"":"?"}: ${w(X)}`);let j=[...z,...Q].every((H)=>H.in!=="path"&&!H.required)&&(!X||!L),S=W.length?`input${j?"?":""}: { ${W.join("; ")} }, `:"",U=Q.length?`[${Q.map((H)=>JSON.stringify(H.name)).join(", ")}]`:"[]";return`${EJ([O.summary&&O.summary!==$?O.summary:`${J.toUpperCase()} ${$}`,O.description??""])} ${G}(${S}options?: RequestOptions): Promise<ApiResult<${UJ(O)}>> {
37
- return request(config, ${JSON.stringify(J.toUpperCase())}, ${JSON.stringify($)}, ${W.length?"input ?? {}":"{}"}, ${U}, ${X?"true":"false"}, options)
38
- },`}function FJ($,J={}){let O=J.name??"API",G=new Map,Z=[];for(let[z,Q]of Object.entries($.paths??{}))for(let X of SJ){let L=Q[X];if(!L)continue;let W=P$(L.operationId??`${X}_${z}`),j=G.get(W)??0;G.set(W,j+1),Z.push(IJ(z,X,L,j===0?W:`${W}${j+1}`))}return`/* eslint-disable */
36
+ `}function CJ($,J,O,G){let Z=O.parameters??[],z=Z.filter((E)=>E.in==="path"),Q=Z.filter((E)=>E.in==="query"),L=O.requestBody?.content?.["application/json"]?.schema,T=Boolean(O.requestBody?.required),X=[];for(let E of[...z,...Q]){let k=E.in==="path"||E.required;X.push(`${JSON.stringify(E.name)}${k?"":"?"}: ${w(E.schema)}`)}if(L)X.push(`body${T?"":"?"}: ${w(L)}`);let W=[...z,...Q].every((E)=>E.in!=="path"&&!E.required)&&(!L||!T),B=X.length?`input${W?"?":""}: { ${X.join("; ")} }, `:"",H=Q.length?`[${Q.map((E)=>JSON.stringify(E.name)).join(", ")}]`:"[]";return`${MJ([O.summary&&O.summary!==$?O.summary:`${J.toUpperCase()} ${$}`,O.description??""])} ${G}(${B}options?: RequestOptions): Promise<ApiResult<${VJ(O)}>> {
37
+ return request(config, ${JSON.stringify(J.toUpperCase())}, ${JSON.stringify($)}, ${X.length?"input ?? {}":"{}"}, ${H}, ${L?"true":"false"}, options)
38
+ },`}function RJ($,J={}){let O=J.name??"API",G=new Map,Z=[];for(let[z,Q]of Object.entries($.paths??{}))for(let L of FJ){let T=Q[L];if(!T)continue;let X=b$(T.operationId??`${L}_${z}`),W=G.get(X)??0;G.set(X,W+1),Z.push(CJ(z,L,T,W===0?X:`${X}${W+1}`))}return`/* eslint-disable */
39
39
  /**
40
40
  * ${O} client, generated from the OpenAPI document.
41
41
  *
@@ -136,4 +136,4 @@ ${Z.join(`
136
136
  }
137
137
 
138
138
  export type Client = ReturnType<typeof createClient>
139
- `}var SJ;var B$=d(()=>{z$();SJ=["get","put","post","delete","options","head","patch"]});function VJ($){let J=$;return J?.code==="SQLITE_CONSTRAINT_UNIQUE"||J?.code==="SQLITE_CONSTRAINT"||J?.code==="23505"||J?.errno===1062||/unique|duplicate/i.test(J?.message??"")}function j$($,J,O){let G=$;if($ instanceof Error&&typeof G.status==="number"&&Number.isInteger(G.status)&&G.status>=400&&G.status<600){let Z={error:$.message};if(G.details!==void 0)Z.details=G.details;return{status:G.status,body:Z}}if(VJ($))return{status:409,body:{error:`${J} already exists`}};return{status:500,body:{error:`Failed to ${O} ${J}`,detail:String($)}}}function M($){return $.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function A$($){let J={};for(let[O,G]of Object.entries($))J[M(O)]=G;return J}function y$($,J){let O=String(J||"").replace(/^\/+|\/+$/g,""),G=String($).replace(/^\/+/,"");return`/api/${O?`${O}/`:""}${G}`}function b$($){if(!$)return null;let J=$.attributes??{};if(Object.prototype.hasOwnProperty.call(J,"teamId")||Object.prototype.hasOwnProperty.call(J,"team_id"))return"team_id";return $.belongsTo?.some((O)=>O==="Team")?"team_id":null}function q$($,J,O){let G=Object.keys($).find((z)=>M(z)===M(J));if(Array.isArray(O)){if(G===void 0)return{data:$,error:"Ownership value is required"};if(!O.some((z)=>String(z)===String($[G])))return{data:$,error:"Ownership value is not available to this caller"};return{data:{...$,[J]:$[G]}}}if(O===null||O===void 0)return{data:$,error:"Caller has no ownership identity"};let Z={...$};for(let z of Object.keys(Z))if(M(z)===M(J))delete Z[z];return Z[J]=O,{data:Z}}function c$($){if(!$)return[];let J=Object.entries($.attributes??{}).filter(([,O])=>O?.fillable===!0).map(([O])=>O);for(let O of $.belongsTo??[]){if(typeof O!=="string"||!O.trim())continue;let G=M(O.trim()).split("_").filter(Boolean);if(G.length===0)continue;let Z=`${G[0]}${G.slice(1).map((z)=>`${z[0]?.toUpperCase()}${z.slice(1)}`).join("")}Id`;J.push(Z)}return[...new Set(J)]}function _$($,J){if(!$||J.length===0)return{};let O={};for(let G of J){if(G in $){O[G]=$[G];continue}let Z=M(G);if(Z!==G&&Z in $)O[G]=$[Z]}return O}function MJ($,J){if($?.name!=="date"||J instanceof Date||typeof J!=="string")return J;let O=/^(\d{4})-(\d{2})-(\d{2})$/.exec(J);if(!O)return J;let G=Number(O[1]),Z=Number(O[2]),z=Number(O[3]),Q=new Date(Date.UTC(G,Z-1,z));if(Q.getUTCFullYear()!==G||Q.getUTCMonth()!==Z-1||Q.getUTCDate()!==z)return J;return Q}function N$($,J){if(!J.length)return $;let O={...$};for(let G of J)delete O[G],delete O[M(G)];return O}function r($,J){if(!$||J.length===0)return $;let O={...$};for(let G of J)delete O[G],delete O[M(G)];return O}function w$($,J){let O=new Map;for(let G of[...Object.keys($??{}),...CJ]){let Z=M(G);if(!/^\w+$/.test(Z))continue;O.set(G,Z),O.set(Z,Z)}for(let G of J)O.delete(G),O.delete(M(G));return O}function v$($,J,O){if(!J)return $;let G=String(J).split(",").map((z)=>z.trim()).filter(Boolean),Z=$;for(let z of G){let Q=z.startsWith("-"),X=Q?z.slice(1):z;if(!/^\w+$/.test(X))continue;let L=O.get(X);if(!L)continue;Z=Z.orderBy(L,Q?"desc":"asc")}return Z}function kJ($){try{return JSON.parse($)}catch{return $}}function PJ($){try{return JSON.parse($)}catch{return[]}}function H$($,J,O){if(!$||typeof $!=="object"||!J||Object.keys(J).length===0)return $;let G={...$};for(let[Z,z]of Object.entries(J)){let Q=typeof z==="string"?RJ[z]:z;if(!Q||typeof Q[O]!=="function")continue;if(Object.prototype.hasOwnProperty.call(G,Z))G[Z]=Q[O](G[Z]);let X=M(Z);if(X!==Z&&Object.prototype.hasOwnProperty.call(G,X))G[X]=Q[O](G[X])}return G}function D$($,J,O){let G=J?.attributes??{},Z={};for(let[z,Q]of Object.entries(G)){let X=Q?.validation?.rule;if(!X||typeof X.validate!=="function")continue;let L=Object.prototype.hasOwnProperty.call($,z);if(!L&&O==="updating")continue;let W=Q!==null&&typeof Q==="object"&&Object.prototype.hasOwnProperty.call(Q,"default"),j=L?$[z]:W?Q.default:void 0,S=MJ(X,j),U=X.validate(S);if(!U?.valid&&Array.isArray(U?.errors)&&U.errors.length>0)Z[z]=U.errors.map((F)=>Q?.validation?.message?.[F?.code]??F?.message??"invalid")}return Object.keys(Z).length===0?{valid:!0}:{valid:!1,errors:Z}}function S$($){return $.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function T$($){if(Array.isArray($))return $.filter((J)=>typeof J==="string"&&J.length>0);return typeof $==="string"&&$?[$]:[]}function h$($){let J=typeof $==="object"&&$!==null&&"middleware"in $,O=$?.middleware;if(!J)return{read:["auth"],write:["auth"],declared:!1};if(O&&typeof O==="object"&&!Array.isArray(O)){let Z=O;return{read:"read"in Z?T$(Z.read):["auth"],write:"write"in Z?T$(Z.write):["auth"],declared:!0}}let G=T$(O);return{read:G,write:G,declared:!0}}function p$($){let J=Number.parseInt($.get("page")||String(1),10),O=Number.isFinite(J)?Math.max(1,J):1,G=Number.parseInt($.get("per_page")||String(g$),10),Z=Math.min(Number.isFinite(G)?Math.max(1,G):g$,fJ);return{page:O,perPage:Z,offset:(O-1)*Z}}function Q$($,J){let O=new URL($.toString());return O.searchParams.set("page",String(J)),`${O.pathname}${O.search}`}function L$($,J,O,G,Z,z){let Q=(J-1)*O,X=G===0,L={page:J,per_page:O,from:X?null:Q+1,to:X?null:Q+G,has_more_pages:Z,prev_page_url:J>1?Q$($,J-1):null,next_page_url:Z?Q$($,J+1):null};if(z!==void 0&&!Number.isNaN(z)){let W=Math.max(1,Math.ceil(z/O));L.total=z,L.last_page=W,L.first_page_url=Q$($,1),L.last_page_url=Q$($,W)}return L}function U$($,J,O,G,Z,z){let{page:Q,...X}=L$($,J,O,G,Z,z);return{current_page:Q,...X}}var CJ,RJ,g$=15,fJ=100;var m$=d(()=>{CJ=["id","uuid","created_at","updated_at","deleted_at"];RJ={string:{get:($)=>$!=null?String($):null,set:($)=>$!=null?String($):null},number:{get:($)=>$!=null?Number($):null,set:($)=>$!=null?Number($):null},integer:{get:($)=>$!=null?Math.trunc(Number($)):null,set:($)=>$!=null?Math.trunc(Number($)):null},float:{get:($)=>$!=null?Number.parseFloat(String($)):null,set:($)=>$!=null?Number.parseFloat(String($)):null},boolean:{get:($)=>$===1||$==="1"||$===!0||$==="true",set:($)=>$===!0||$===1||$==="1"||$==="true"?1:0},json:{get:($)=>$==null?null:typeof $==="string"?kJ($):$,set:($)=>$==null?null:typeof $==="string"?$:JSON.stringify($)},datetime:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString():$},date:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString().split("T")[0]:$},array:{get:($)=>$==null?[]:Array.isArray($)?$:typeof $==="string"?PJ($):[],set:($)=>$==null?null:Array.isArray($)?JSON.stringify($):$}}});import{readdirSync as gJ}from"fs";import{basename as yJ,extname as n$,join as bJ}from"path";function qJ($){let J=[],O=(G)=>{let Z;try{Z=gJ(G,{withFileTypes:!0})}catch{return}for(let z of Z){let Q=bJ(G,z.name);if(z.isDirectory()){O(Q);continue}if(![".ts",".js"].includes(n$(z.name)))continue;if(z.name.startsWith(".")||z.name.startsWith("index"))continue;J.push(Q)}};return O($),J.sort()}async function i$($,J,O){for(let G of qJ($))try{let Z=n$(G),z=await import(`${G}?t=${Date.now()}`),Q=z.default??z,X=Q.name??yJ(G,Z);J[X]={...Q,name:X}}catch(Z){O?.(G,Z)}}async function u$($){let J={};return await i$($.defaultsRoot,J,$.onImportError),await i$($.userRoot,J,$.onImportError),J}var l$=()=>{};import{route as i}from"@stacksjs/router";import{env as o}from"@stacksjs/env";import{projectPath as $J,storagePath as cJ}from"@stacksjs/path";import{createQueryBuilder as wJ,defaultConfig as o$,setConfig as t$}from"@stacksjs/query-builder";import{HttpError as n}from"@stacksjs/error-handling";import{log as X$}from"@stacksjs/logging";function t($,J){let O=S$(J);return i.routes.some((G)=>G.method===$&&S$(String(G.path??""))===O)}function JJ($){if(!$.attributes)return[];return Object.entries($.attributes).filter(([J,O])=>O.hidden===!0).map(([J])=>J)}function s$($){if($.endsWith("y")&&!/[aeiou]y$/i.test($))return`${$.slice(0,-1)}ies`;if(/(?:s|x|z|ch|sh)$/i.test($))return`${$}es`;return`${$}s`}async function d$($,J,O,G){if(!$.length)return $;let Z=O.split(",").map((W)=>W.trim()).filter(Boolean);if(!Z.length)return $;let z=Array.isArray(J.belongsTo)?J.belongsTo:[],Q=Array.isArray(J.hasMany)?J.hasMany:[],X=Array.isArray(J.hasOne)?J.hasOne:[],L=new Map;for(let W of z)L.set(M(W),{kind:"belongsTo",modelName:W});for(let W of X)L.set(M(W),{kind:"hasOne",modelName:W});for(let W of Q)L.set(s$(M(W)),{kind:"hasMany",modelName:W});for(let W of Z){let j=L.get(W);if(!j)continue;let S=G[j.modelName];if(!S)continue;let U=S.table||s$(M(j.modelName)),F=JJ(S),H=(P)=>r(O$(P,S),F);if(j.kind==="belongsTo"||j.kind==="hasOne"){let P=`${M(j.modelName)}_id`,b=[...new Set($.map((E)=>E[P]).filter((E)=>E!=null))];if(!b.length){for(let E of $)E[W]=null;continue}let k=await y.selectFrom(U).whereIn("id",b).get(),C=new Map;for(let E of k??[])C.set(String(E.id),H(E));for(let E of $)E[W]=C.get(String(E[P]))??null}else{let P=String(J.name??""),b=`${M(P)}_id`,k=[...new Set($.map((Y)=>Y.id).filter((Y)=>Y!=null))];if(!k.length){for(let Y of $)Y[W]=[];continue}let C=await y.selectFrom(U).whereIn(b,k).get(),E=new Map;for(let Y of C??[]){let K=String(Y[b]),x=E.get(K)??[];x.push(H(Y)),E.set(K,x)}for(let Y of $)Y[W]=E.get(String(Y.id))??[]}}return $}async function r$($,J){let O=J?.set;if(!O||typeof O!=="object")return $;let G={...$};for(let[Z,z]of Object.entries(O)){if(typeof z!=="function"||!(Z in G))continue;try{G[Z]=await z(G)}catch{}}return G}function a$($,J){return H$($,J?.casts,"set")}function O$($,J){return H$($,J?.casts,"get")}function B($,J=200){return new Response(JSON.stringify($),{status:J,headers:{"Content-Type":"application/json"}})}async function I$($){if(Number($.headers?.get?.("content-length")??0)>W$)throw new n(413,`Request body exceeds ${W$}-byte limit`);if($.jsonBody&&typeof $.jsonBody==="object")return $.jsonBody;if($.formBody&&typeof $.formBody==="object")return $.formBody;try{let O=await $.clone().text();if(O.length>W$)throw new n(413,`Request body exceeds ${W$}-byte limit`);if(!O)return{};let G=JSON.parse(O);return G&&typeof G==="object"&&!Array.isArray(G)?G:{}}catch(O){if(O instanceof n)throw O;throw new n(400,`Invalid JSON body: ${O.message}`)}}function K$($){if($==null)return null;if(typeof $==="number")return Number.isFinite($)&&$>0?$:null;if(typeof $==="string"){let J=$.trim();if(!J)return null;if(/^\d+$/.test(J)){let O=Number(J);return Number.isFinite(O)&&O>0?O:null}return J}return null}function OJ($){let J=$.bearerToken;if(typeof J==="function"){let G=J.call($);if(G)return G}let O=$.headers?.get?.("authorization")||$.headers?.get?.("Authorization")||"";if(typeof O==="string"&&O.startsWith("Bearer "))return O.substring(7);return null}async function a($){let J=$._authenticatedUser;if(J)return J;let O=OJ($);if(!O)return null;try{let{Auth:G}=await import("@stacksjs/auth"),Z=await G.getUserFromToken(O);if(Z)$._authenticatedUser=Z;return Z||null}catch{return null}}function J$($,J){if($==null||J==null)return!1;if(Array.isArray(J))return J.some((O)=>String(O)===String($));return String($)===String(J)}function hJ($){let J=OJ($),O=$.headers?.get?.("cookie")||"";return{bearerToken:()=>J,cookies:{get:(G)=>{for(let Z of O.split(";")){let z=Z.indexOf("=");if(z===-1)continue;if(Z.slice(0,z).trim()===G)return decodeURIComponent(Z.slice(z+1).trim())}return null}}}}function GJ($){if($?.ownership)return $.ownership;let J=b$($);if(!J)return null;return{field:J,resolve:async(O,G)=>{let{resolveAuthenticatedTeamId:Z}=await import("@stacksjs/auth");return Z(hJ(G))}}}async function e($,J,O){let G=GJ($);if(!G||!G.field||typeof G.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let Z=typeof G.bypass==="function"?!!G.bypass(J,O):!1,z=null;try{z=await G.resolve(J,O)}catch{z=null}return{enforced:!0,value:z,field:String(G.field),bypass:Z}}async function e$($,J,O,G){let Z=$?.authedFill?.[J];if(!Z)return{};if(typeof Z==="function")try{let z=await Z(O,G);return z&&typeof z==="object"?z:{}}catch{return{}}if(typeof Z==="object"){let z={};for(let[Q,X]of Object.entries(Z))try{z[Q]=typeof X==="function"?await X(O,G):X}catch{}return z}return{}}var vJ,E$,y,W$=1048576,ZJ;var zJ=d(async()=>{m$();l$();vJ=$J("config/qb.ts");try{let $=(await import(vJ)).default;t$($??o$)}catch{X$.debug("[orm] No config/qb.ts override found \u2014 deriving config from DB_CONNECTION");let $=o.DB_CONNECTION||"sqlite";t$({...o$,dialect:$,database:$==="sqlite"?{database:o.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:o.DB_DATABASE||"stacks",host:o.DB_HOST||"127.0.0.1",port:o.DB_PORT||($==="postgres"?5432:3306),username:o.DB_USERNAME||($==="postgres"?"postgres":"root"),password:o.DB_PASSWORD||""}})}E$=await u$({defaultsRoot:cJ("framework/defaults/app/Models"),userRoot:$J("app/Models"),onImportError:($,J)=>X$.warn(`[orm] Could not load model ${$}: ${J.message}`)}),y=wJ();for(let[$,J]of Object.entries(E$)){let O=J.traits?.useApi;if(!O)continue;let G=typeof O==="object"?O:{},Z=G.uri||J.table||$.toLowerCase()+"s",z=G.routes||["index","show","store","update","destroy"],Q=J.table||Z,X=c$(J),L=JJ(J),W=y$(Z,G.prefix),j=w$(J.attributes,L),{read:S,write:U,declared:F}=h$(O);if(["store","update","destroy"].some((Y)=>z.includes(Y))&&F&&U.length===0)X$.warn(`[orm] ${$}: registering UNAUTHENTICATED mutating routes at ${W} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((Y)=>z.includes(Y))&&F&&S.length===0)X$.debug(`[orm] ${$}: registering public read routes at ${W} (declared \`middleware.read: []\`)`);let b=!!GJ(J),k=b&&!S.includes("auth")?["auth",...S]:S,C=(Y,K=k)=>{let x=Y;for(let T of K)if(x&&typeof x.middleware==="function")x=x.middleware(T);return x};if(z.includes("index")&&!t("GET",W))C(i.get(W,async(Y)=>{try{let K=new URL(Y.url),{page:x,perPage:T,offset:D}=p$(K.searchParams),N=K.searchParams.get("sort"),A=y.selectFrom(Q);A=v$(A,N,j);let c=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[f,g]of K.searchParams.entries()){if(c.has(f)||!g)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(f))continue;let u=j.get(f);if(u)A=A.where(u,"=",g)}let V=K.searchParams.get("search");if(V&&X.length>0){let f=X.slice(0,5);A=A.where((g)=>{for(let u of f)g=g.orWhere(M(u),"like",`%${V}%`);return g})}let R=K.searchParams.get("fields");if(R){let f=R.split(",").map((g)=>g.trim()).filter((g)=>/^[a-z_][a-z0-9_]*$/i.test(g)).map((g)=>M(g));if(f.length>0)A=A.select(f)}let q=!!J.traits?.useSoftDeletes,I=K.searchParams.get("withTrashed")==="true",h=K.searchParams.get("onlyTrashed")==="true";if(q&&!I)A=h?A.whereNotNull("deleted_at"):A.whereNull("deleted_at");let _=b?await e(J,await a(Y),Y):{enforced:!1,value:null,field:"",bypass:!1};if(_.enforced&&!_.bypass){if(_.value==null||Array.isArray(_.value)&&_.value.length===0){let f=U$(K,x,T,0,!1,void 0);return new Response(JSON.stringify({data:[],...f,meta:L$(K,x,T,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}A=Array.isArray(_.value)?A.where(_.field,"in",_.value):A.where(_.field,"=",_.value)}let p=await A.limit(T+1).offset(D).get()||[],m=p.length>T,$$=(m?p.slice(0,T):p).map((f)=>r(O$(f,J),L)),V$=K.searchParams.get("include");if(V$)$$=await d$($$,J,V$,E$);let YJ=K.searchParams.get("with_count")==="true",s;if(YJ)try{let f=y.selectFrom(Q);if(_.enforced&&!_.bypass&&_.value!=null)f=Array.isArray(_.value)?f.where(_.field,"in",_.value):f.where(_.field,"=",_.value);let g=await f.count(),u=typeof g==="number"?g:Number(g?.count??g);if(Number.isFinite(u))s=u}catch{}let Z$={"Content-Type":"application/json"};if(s!==void 0&&!Number.isNaN(s))Z$["X-Total-Count"]=String(s);Z$["Cache-Control"]=_.enforced&&!_.bypass?"private, no-store":"public, max-age=15, must-revalidate",Z$.Vary="Authorization";let xJ=U$(K,x,T,$$.length,m,s);return new Response(JSON.stringify({data:$$,...xJ,meta:L$(K,x,T,$$.length,m,s)}),{status:200,headers:Z$})}catch(K){if(K instanceof n){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return B(x,K.status||400)}return B({error:`Failed to fetch ${Z}`,detail:String(K)},500)}}));if(z.includes("show")&&!t("GET",`${W}/{id}`))C(i.get(`${W}/{id}`,async(Y)=>{try{let K=K$(Y.params?.id);if(K==null)return B({error:"Invalid ID parameter"},400);let x=await y.selectFrom(Q).where({id:K}).executeTakeFirst();if(!x)return B({error:`${$} not found`},404);let T=new URL(Y.url);if(J.traits?.useSoftDeletes&&x.deleted_at&&T.searchParams.get("withTrashed")!=="true")return B({error:`${$} not found`},404);let D=b?await e(J,await a(Y),Y):{enforced:!1,value:null,field:"",bypass:!1};if(D.enforced&&!D.bypass){if(D.value==null||!J$(x[D.field],D.value))return B({error:`${$} not found`},404)}let N=r(O$(x,J),L),A=T.searchParams.get("include");if(A){let[I]=await d$([N],J,A,E$);N=I}let c=N?.updated_at||N?.created_at,V=c?`W/"${N.id}-${String(c)}"`:void 0,R=Y.headers?.get?.("if-none-match");if(V&&R&&R===V)return new Response(null,{status:304,headers:{ETag:V}});let q={"Content-Type":"application/json"};if(V)q.ETag=V;return q["Cache-Control"]=D.enforced&&!D.bypass?"private, no-store":"public, max-age=30, must-revalidate",q.Vary="Authorization",new Response(JSON.stringify({data:N}),{status:200,headers:q})}catch(K){if(K instanceof n){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return B(x,K.status||400)}return B({error:`Failed to fetch ${$}`,detail:String(K)},500)}}));if(z.includes("store")&&!t("POST",W))C(i.post(W,async(Y)=>{try{let K=await I$(Y),x=N$(K,L),T=_$(x,X),D=await a(Y);if(D){let I=await e$(J,"creating",D,Y);for(let[h,_]of Object.entries(I))if(_!==void 0&&_!==null&&T[h]===void 0)T[h]=_}let N=await e(J,D,Y);if(N.enforced&&!N.bypass){if(!D)return B({error:"Auth required"},401);let I=q$(T,N.field,N.value);if(I.error)return B({error:I.error},403);T=I.data}if(Object.keys(T).length===0)return B({error:"No fillable fields provided"},422);let A=D$(T,J,"creating");if(!A.valid)return B({success:!1,message:"Validation failed",errors:A.errors},422);if(J.traits?.useTimestamps!==!1){let I=new Date().toISOString();T.created_at=I,T.updated_at=I}let c=await r$(T,J),V=A$(a$(c,J)),R=await y.insertInto(Q).values(V).execute(),q=V;try{let I=R?.lastInsertRowid??R?.insertId??R;if(I){let h=await y.selectFrom(Q).where({id:I}).executeTakeFirst();if(h)q=h}}catch{}return B({data:r(O$(q,J),L)},201)}catch(K){let{status:x,body:T}=j$(K,$,"create");return B(T,x)}}),U);if(z.includes("update")){let Y=async(K)=>{try{let x=K$(K.params?.id);if(x==null)return B({error:"Invalid ID parameter"},400);let T=await I$(K),D=N$(T,L),N=_$(D,X),A=await a(K);if(A){let _=await e$(J,"updating",A,K);for(let[p,m]of Object.entries(_))if(m!==void 0&&m!==null&&N[p]===void 0)N[p]=m}if(Object.keys(N).length===0)return B({error:"No fillable fields provided"},422);let c=D$(N,J,"updating");if(!c.valid)return B({success:!1,message:"Validation failed",errors:c.errors},422);let V=await y.selectFrom(Q).where({id:x}).executeTakeFirst();if(!V)return B({error:`${$} not found`},404);let R=await e(J,A,K);if(R.enforced&&!R.bypass){if(!A)return B({error:"Auth required"},401);let _=V[R.field];if(!J$(_,R.value))return B({error:`Not your ${$}`},403);let p=Object.keys(N).find((m)=>M(m)===M(R.field));if(p!==void 0&&!J$(N[p],R.value))return B({error:`Cannot reassign ${$} ownership`},403)}if(J.traits?.useTimestamps!==!1)N.updated_at=new Date().toISOString();let q=await r$(N,J),I=A$(a$(q,J));await y.updateTable(Q).set(I).where({id:x}).execute();let h={...V,...I};try{let _=await y.selectFrom(Q).where({id:x}).executeTakeFirst();if(_)h=_}catch{}return B({data:r(O$(h,J),L)})}catch(x){let{status:T,body:D}=j$(x,$,"update");return B(D,T)}};if(!t("PUT",`${W}/{id}`))C(i.put(`${W}/{id}`,Y),U);if(!t("PATCH",`${W}/{id}`))C(i.patch(`${W}/{id}`,Y),U)}let E=!!J.traits?.useSoftDeletes;if(z.includes("destroy")&&!t("DELETE",`${W}/{id}`))C(i.delete(`${W}/{id}`,async(Y)=>{try{let K=K$(Y.params?.id);if(K==null)return B({error:"Invalid ID parameter"},400);let x=await y.selectFrom(Q).where({id:K}).executeTakeFirst();if(!x)return B({error:`${$} not found`},404);let T=await a(Y),D=await e(J,T,Y);if(D.enforced&&!D.bypass){if(!T)return B({error:"Auth required"},401);let N=x[D.field];if(!J$(N,D.value))return B({error:`Not your ${$}`},403)}if(E){let N=new Date().toISOString();await y.updateTable(Q).set({deleted_at:N,updated_at:N}).where({id:K}).execute()}else await y.deleteFrom(Q).where({id:K}).execute();return new Response(null,{status:204})}catch(K){if(K instanceof n){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return B(x,K.status||400)}return B({error:`Failed to delete ${$}`,detail:String(K)},500)}}),U);if(z.includes("destroy")&&!t("POST",`${W}/bulk-delete`))C(i.post(`${W}/bulk-delete`,async(Y)=>{try{let x=(await I$(Y))?.ids;if(!Array.isArray(x)||x.length===0)return B({error:"An array of IDs is required"},422);if(x.length>100)return B({error:"Cannot delete more than 100 records at once"},422);let T=[],D=[];for(let V of x){let R=K$(V);if(R!=null)T.push(R);else D.push(V)}if(D.length>0)return B({error:"Invalid IDs in batch",invalid:D},422);let N=await a(Y),A=await e(J,N,Y);if(A.enforced&&!A.bypass){if(!N)return B({error:"Auth required"},401);if(A.value==null)return B({error:"Caller has no ownership identity"},403);let V=await y.selectFrom(Q).select(["id",A.field]).execute(),R=new Set(V.filter((I)=>J$(I[A.field],A.value)).map((I)=>String(I.id))),q=T.filter((I)=>!R.has(String(I)));if(q.length>0)return B({error:`Cannot delete ${$} you don't own`,ids:q},403)}let c=new Date().toISOString();for(let V of T)if(E)await y.updateTable(Q).set({deleted_at:c,updated_at:c}).where({id:V}).execute();else await y.deleteFrom(Q).where({id:V}).execute();return B({message:`Successfully deleted ${T.length} ${Z}`})}catch(K){if(K instanceof n){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return B(x,K.status||400)}return B({error:`Failed to bulk delete ${Z}`,detail:String(K)},500)}}),U)}ZJ=i});var QJ={};x$(QJ,{default:()=>ZJ});var LJ=d(async()=>{await zJ()});class M${data;status;headers;isOk;constructor($,J,O,G){this.data=$;this.status=J;this.headers=O;this.isOk=G}ok(){return this.status===200}created(){return this.status===201}accepted(){return this.status===202}noContent(){return this.status===204}movedPermanently(){return this.status===301}found(){return this.status===302}badRequest(){return this.status===400}unauthorized(){return this.status===401}paymentRequired(){return this.status===402}forbidden(){return this.status===403}notFound(){return this.status===404}requestTimeout(){return this.status===408}conflict(){return this.status===409}unprocessableEntity(){return this.status===422}tooManyRequests(){return this.status===429}serverError(){return this.status===500}}class C${defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData=!1;customHeaders={};attachments=[];isMultipart=!1;digestAuth;withQueryParams($){return this.queryParams=$,this}withHeaders($){return this.customHeaders={...this.customHeaders,...$},this}accept($){return this.defaultHeaders.Accept=$,this}acceptJson(){return this.accept("application/json")}withToken($){return this.customHeaders.Authorization=`Bearer ${$}`,this}withBasicAuth($,J){let O=btoa(`${$}:${J}`);return this.customHeaders.Authorization=`Basic ${O}`,this}withDigestAuth($,J){return this.digestAuth={username:$,password:J},this}withBody($){return this.bodyData=$,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach($,J,O,G){let Z=typeof J==="string"?new Blob([J],{type:G?.["Content-Type"]||"text/plain"}):J;return this.attachments.push({name:$,content:Z,filename:O,headers:G}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams($){if(!this.queryParams)return $;let J=new URLSearchParams;Object.entries(this.queryParams).forEach(([Z,z])=>{if(z!=null)J.append(Z,String(z))});let O=J.toString();if(!O)return $;let G=$.includes("?");return $+(G?"&":"?")+O}async formatBody($){let J=$||this.bodyData;if(this.isMultipart){let O=new FormData;if(J)Object.entries(J).forEach(([G,Z])=>{O.append(G,String(Z))});for(let G of this.attachments)if(G.headers){let Z=G.content instanceof Blob?new Blob([G.content],{type:G.headers["Content-Type"]}):G.content;O.append(G.name,Z,G.filename)}else O.append(G.name,G.content,G.filename);return O}if(this.isFormData&&J){let O=new URLSearchParams;return Object.entries(J).forEach(([G,Z])=>{if(Z!=null)O.append(G,String(Z))}),O.toString()}return J?JSON.stringify(J):void 0}resetState(){this.queryParams=void 0,this.bodyData=void 0,this.isFormData=!1,this.isMultipart=!1,this.customHeaders={},this.attachments=[],this.digestAuth=void 0,this.defaultHeaders["Content-Type"]="application/json"}async handleDigestAuth($,J,O,G){if($.status!==401||!this.digestAuth)return $;let Z=$.headers.get("WWW-Authenticate");if(!Z?.startsWith("Digest "))return $;let z=Z.substring(7).split(",").reduce((F,H)=>{let[P,b]=H.trim().split("=");if(P)F[P]=b?.replace(/["']/g,"")??"";return F},{}),Q=await this.generateMD5(`${this.digestAuth.username}:${z.realm}:${this.digestAuth.password}`),X=await this.generateMD5(`${O}:${J}`),L="00000001",W=await this.generateMD5(Date.now().toString()).then((F)=>F.substring(0,8)),j=await this.generateMD5(`${Q}:${z.nonce}:${L}:${W}:${z.qop}:${X}`),S={username:`"${this.digestAuth.username}"`,realm:`"${z.realm}"`,nonce:`"${z.nonce}"`,uri:`"${J}"`,algorithm:z.algorithm?`"${z.algorithm}"`:void 0,qop:`"${z.qop}"`,nc:L,cnonce:`"${W}"`,response:`"${j}"`,opaque:z.opaque?`"${z.opaque}"`:void 0},U=Object.entries(S).filter(([F,H])=>H!==void 0).map(([F,H])=>`${F}=${H}`).join(", ");return this.customHeaders.Authorization=`Digest ${U}`,fetch(J,{method:O,headers:this.getHeaders(),body:G?this.formatBody(G):void 0})}async generateMD5($){let O=new TextEncoder().encode($),G=await crypto.subtle.digest("SHA-256",O);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}async request($,J,O){let G=this.addQueryParams($),Z=await this.formatBody(O),z=await fetch(G,{method:J,headers:this.getHeaders(),body:Z});if(this.digestAuth)z=await this.handleDigestAuth(z,G,J,O);let Q=await z.json();return this.resetState(),new M$(Q,z.status,z.headers,z.ok)}async get($){return this.request($,"GET")}async post($,J){return this.request($,"POST",J)}async put($,J){return this.request($,"PUT",J)}async patch($,J){return this.request($,"PATCH",J)}async delete($){return this.request($,"DELETE")}}var oJ=new C$;B$();import{path as Y$}from"@stacksjs/path";function pJ($){if(!$||typeof $!=="object")return{type:"string"};let J=$,O=Array.isArray(J.rules)?J.rules:[],G=(j)=>O.find((S)=>S.name===j),Z=(j,S)=>{let U=G(j)?.params?.[S];return typeof U==="number"?U:void 0},z=J.name??J._type??"string",Q={type:z==="enum"?"string":z},X=Z("min","min")??(typeof J._min==="number"?J._min:void 0),L=Z("max","max")??(typeof J._max==="number"?J._max:void 0);if(X!==void 0)Q[z==="string"?"minLength":"minimum"]=X;if(L!==void 0)Q[z==="string"?"maxLength":"maximum"]=L;if(G("email")||J._email)Q.format="email";if(G("url")||J._url)Q.format="uri";if(G("uuid")||J._uuid)Q.format="uuid";let W=Array.isArray(J.allowedValues)?J.allowedValues:Array.isArray(J._enum)?J._enum:null;if(W)Q.enum=W;return Q}function mJ($){if(!$||typeof $!=="object")return!1;let J=$;return Boolean(J.isRequired??J._required)}function iJ($,J){let O={...J},G=$?.responses;if(G&&typeof G==="object")for(let[z,Q]of Object.entries(G)){let X=Q;if(!X||typeof X!=="object"||typeof X.description!=="string")continue;O[String(z)]={description:X.description,...X.schema&&typeof X.schema==="object"?{content:{"application/json":{schema:X.schema}}}:{}}}let Z=$?.responseHeaders;if(Z&&typeof Z==="object"){let z={};for(let[Q,X]of Object.entries(Z)){let L=X;if(!L||typeof L!=="object"||typeof L.description!=="string")continue;z[Q]={description:L.description,...L.schema&&typeof L.schema==="object"?{schema:L.schema}:{}}}if(Object.keys(z).length>0)for(let Q of Object.keys(O))O[Q]={...O[Q],headers:z}}return O}async function nJ($){if(typeof $!=="string"||!$||$.includes(".."))return null;try{let{path:J}=await import("@stacksjs/path"),O=[J.appPath(`${$}.ts`),J.storagePath(`framework/defaults/app/${$}.ts`)];for(let G of O)try{if(!await Bun.file(G).exists())continue;let Q=(await import(G)).default;return Q&&typeof Q==="object"?Q:null}catch{}}catch{}return null}async function xO($={}){let J=$.portable??!0,{listRegisteredRoutes:O}=await import("@stacksjs/router");try{let{loadRoutes:L}=await import("@stacksjs/router"),{default:W}=await import(Y$.appPath("Routes.ts"));await L(W)}catch(L){let W=L instanceof Error?L.message:String(L);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${W}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${W}`)}try{try{await import("@stacksjs/orm/routes")}catch{await LJ().then(() => QJ)}}catch(L){let W=L instanceof Error?L.message:String(L);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${W}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${W}`)}let G=(L)=>L.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),Z=[...O()].map((L)=>({route:L,oasPath:G(L.path),method:L.method.toLowerCase()})).sort((L,W)=>{if(L.oasPath!==W.oasPath)return L.oasPath<W.oasPath?-1:1;return L.method<W.method?-1:L.method>W.method?1:0});if(J&&Z.length===0)throw Error("[generateOpenApi] Refusing to emit an empty spec: no routes were registered. This usually means route loading failed silently rather than that the app has no API.");let z="Stacks API";if(!J)try{let{config:L}=await import("@stacksjs/config");if(L.app?.name)z=`${L.app.name} API`}catch{}let Q={openapi:"3.0.0",info:{title:z,version:"1.0.0"},paths:{},components:{schemas:{}}},X=new Set;for(let{route:L,oasPath:W,method:j}of Z){if(!Q.paths[W])Q.paths[W]={};let S=[];for(let k of L.path.matchAll(/\{(\w+)\}/g))if(k[1])S.push(k[1]);for(let k of L.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(k[1])S.push(k[1]);let U=L.name??`${j}_${W.replace(/[^a-z0-9]/gi,"_")}`,F=U;if(X.has(F)){F=`${U}_${j}`;let k=2;while(X.has(F))F=`${U}_${j}_${k++}`}X.add(F);let H={summary:L.name??L.path,operationId:F,parameters:S.map((k)=>({name:k,in:"path",required:!0,schema:{type:"string"}})),responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object"}}}},422:{description:"Validation failed"},500:{description:"Server error"}}},P=L.handler?await nJ(L.handler):null,b=P&&typeof P.validations==="object"&&P.validations!==null?P.validations:null;if(H.responses=iJ(P,H.responses),b&&Object.keys(b).length>0){let k=Object.entries(b).map(([C,E])=>{let Y=E?.rule;return{field:C,schema:pJ(Y),required:mJ(Y)}});if(j==="get"||j==="head"||j==="delete"){let C=new Set(S);for(let{field:E,schema:Y,required:K}of k){if(C.has(E))continue;H.parameters?.push({name:E,in:"query",required:K,schema:Y})}}else{let C={type:"object",properties:{},required:[]},E=C.properties,Y=C.required;for(let K of k)if(E[K.field]=K.schema,K.required)Y.push(K.field);if(Y.length===0)delete C.required;H.requestBody={required:Y.length>0,content:{"application/json":{schema:C}}}}}Q.paths[W][j]=H}if($.write!==!1){let W=Bun.file(Y$.frameworkPath("api/openapi.json")).writer();W.write(JSON.stringify(Q,null,2)),await W.end();let{renderOpenApiTypes:j}=await Promise.resolve().then(() => (z$(),k$)),{renderApiClient:S}=await Promise.resolve().then(() => (B$(),f$));await Bun.write(Y$.frameworkPath("api/api-types.ts"),j(Q)),await Bun.write(Y$.frameworkPath("api/client.ts"),S(Q,{name:Q.info.title}))}return Q}z$();class v{static instance=new v;isMissing(){return!0}}class G${data;constructor($){this.data=$}}class WJ{condition;value;defaultValue;constructor($,J,O=new v){this.condition=$;this.value=J;this.defaultValue=O}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class KJ{resource;additional={};request;static wrap="data";static additionalMeta={};constructor($){this.resource=$}withRequest($){return this.request=$,this}withAdditional($){return this.additional={...this.additional,...$},this}resolve($){let J=this.toArray($||this.request);return this.filterAndResolve(J)}toResponse($){let J=this.resolve($),O=this.constructor.wrap;if(O)return{[O]:J,...this.additional};return{...J,...this.additional}}toJson($){return JSON.stringify(this.toResponse($))}toJSON(){return this.toResponse()}static collection($){return new F$($,this)}when($,J,O){if(typeof $==="function"?$():$)return typeof J==="function"?J():J;return O!==void 0?O:v.instance}whenNotNull($,J){if($===null||$===void 0)return v.instance;return J?J($):$}whenLoaded($,J,O){let G=this.resource;if(!(($ in G)&&G[$]!==void 0))return O!==void 0?O:v.instance;if(J!==void 0)return typeof J==="function"?J():J;return G[$]}whenCounted($,J){let O=this.resource,G=`${$}_count`;if(G in O)return O[G];return J!==void 0?J:v.instance}merge($){return new G$($)}mergeWhen($,J){if(!(typeof $==="function"?$():$))return v.instance;let G=typeof J==="function"?J():J;return new G$(G)}static MAX_RESOLVE_DEPTH=20;filterAndResolve($,J=0){if(J>=KJ.MAX_RESOLVE_DEPTH)return $;let O={};for(let[G,Z]of Object.entries($)){if(Z instanceof v)continue;if(Z instanceof G$){Object.assign(O,this.filterAndResolve(Z.data,J+1));continue}if(Z instanceof WJ){let z=Z.resolve();if(!(z instanceof v))O[G]=z;continue}if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)&&!(Z instanceof Date)){O[G]=this.filterAndResolve(Z,J+1);continue}if(Array.isArray(Z)){O[G]=Z.filter((z)=>!(z instanceof v)).map((z)=>{if(z instanceof G$)return z.data;if(z!==null&&typeof z==="object"&&!(z instanceof Date))return this.filterAndResolve(z,J+1);return z});continue}O[G]=Z}return O}static withoutWrapping(){this.wrap=null}static wrapWith($){this.wrap=$}}class F${resources;ResourceClass;additional={};request;static wrap="data";constructor($,J){this.resources=$,this.ResourceClass=J}withRequest($){return this.request=$,this}withAdditional($){return this.additional={...this.additional,...$},this}resolve($){let J=$||this.request;return this.resources.map((O)=>{let G=new this.ResourceClass(O);if(J)G.withRequest(J);return G.resolve(J)})}toResponse($){let J=this.resolve($),O=this.constructor.wrap;if(O)return{[O]:J,...this.additional};return{data:J,...this.additional}}toJson($){return JSON.stringify(this.toResponse($))}count(){return this.resources.length}isEmpty(){return this.resources.length===0}isNotEmpty(){return this.resources.length>0}}class XJ extends F${meta;links;constructor($,J){super($.data,J);this.meta=$.meta,this.links=$.links}static fromPagination($,J,O){let{currentPage:G,perPage:Z,total:z,baseUrl:Q=""}=O,X=Math.ceil(z/Z),L=z>0?(G-1)*Z+1:null,W=z>0?Math.min(G*Z,z):null;return new XJ({data:$,meta:{current_page:G,from:L,last_page:X,per_page:Z,to:W,total:z},links:{first:`${Q}?page=1`,last:`${Q}?page=${X}`,prev:G>1?`${Q}?page=${G-1}`:null,next:G<X?`${Q}?page=${G+1}`:null}},J)}toResponse($){return{data:this.resolve($),meta:this.meta,links:this.links,...this.additional}}}function TO($,J){let O=J($);return{toResponse:()=>({data:O}),toJson:()=>JSON.stringify({data:O})}}function jO($,J){let O=$.map(J);return{toResponse:()=>({data:O}),toJson:()=>JSON.stringify({data:O})}}export{w as schemaType,pJ as ruleToSchema,mJ as ruleIsRequired,TO as resource,DJ as renderOpenApiTypes,FJ as renderApiClient,P$ as methodName,xO as generateOpenApi,oJ as fetcher,iJ as describedResponses,jO as collection,F$ as ResourceCollection,XJ as PaginatedResourceCollection,v as MissingValue,G$ as MergeValue,KJ as JsonResource,WJ as ConditionalValue};
139
+ `}var FJ;var B$=d(()=>{L$();FJ=["get","put","post","delete","options","head","patch"]});function kJ($){let J=$;return J?.code==="SQLITE_CONSTRAINT_UNIQUE"||J?.code==="SQLITE_CONSTRAINT"||J?.code==="23505"||J?.errno===1062||/unique|duplicate/i.test(J?.message??"")}function _$($,J,O){let G=$;if($ instanceof Error&&typeof G.status==="number"&&Number.isInteger(G.status)&&G.status>=400&&G.status<600){let Z={error:$.message};if(G.details!==void 0)Z.details=G.details;return{status:G.status,body:Z}}if(kJ($))return{status:409,body:{error:`${J} already exists`}};return{status:500,body:{error:`Failed to ${O} ${J}`,detail:String($)}}}function V($){return $.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function j$($){let J={};for(let[O,G]of Object.entries($))J[V(O)]=G;return J}function q$($,J){let O=String(J||"").replace(/^\/+|\/+$/g,""),G=String($).replace(/^\/+/,"");return`/api/${O?`${O}/`:""}${G}`}function c$($){if(!$)return null;let J=$.attributes??{};if(Object.prototype.hasOwnProperty.call(J,"teamId")||Object.prototype.hasOwnProperty.call(J,"team_id"))return"team_id";return $.belongsTo?.some((O)=>O==="Team")?"team_id":null}function w$($,J,O){let G=Object.keys($).find((z)=>V(z)===V(J));if(Array.isArray(O)){if(G===void 0)return{data:$,error:"Ownership value is required"};if(!O.some((z)=>String(z)===String($[G])))return{data:$,error:"Ownership value is not available to this caller"};return{data:{...$,[J]:$[G]}}}if(O===null||O===void 0)return{data:$,error:"Caller has no ownership identity"};let Z={...$};for(let z of Object.keys(Z))if(V(z)===V(J))delete Z[z];return Z[J]=O,{data:Z}}function v$($){if(!$)return[];let J=Object.entries($.attributes??{}).filter(([,O])=>O?.fillable===!0).map(([O])=>O);for(let O of $.belongsTo??[]){if(typeof O!=="string"||!O.trim())continue;let G=V(O.trim()).split("_").filter(Boolean);if(G.length===0)continue;let Z=`${G[0]}${G.slice(1).map((z)=>`${z[0]?.toUpperCase()}${z.slice(1)}`).join("")}Id`;J.push(Z)}return[...new Set(J)]}function N$($,J){if(!$||J.length===0)return{};let O={};for(let G of J){if(G in $){O[G]=$[G];continue}let Z=V(G);if(Z!==G&&Z in $)O[G]=$[Z]}return O}function PJ($,J){if($?.name!=="date"||J instanceof Date||typeof J!=="string")return J;let O=/^(\d{4})-(\d{2})-(\d{2})$/.exec(J);if(!O)return J;let G=Number(O[1]),Z=Number(O[2]),z=Number(O[3]),Q=new Date(Date.UTC(G,Z-1,z));if(Q.getUTCFullYear()!==G||Q.getUTCMonth()!==Z-1||Q.getUTCDate()!==z)return J;return Q}function H$($,J){if(!J.length)return $;let O={...$};for(let G of J)delete O[G],delete O[V(G)];return O}function r($,J){if(!$||J.length===0)return $;let O={...$};for(let G of J)delete O[G],delete O[V(G)];return O}function h$($,J){let O=new Map;for(let G of[...Object.keys($??{}),...fJ]){let Z=V(G);if(!/^\w+$/.test(Z))continue;O.set(G,Z),O.set(Z,Z)}for(let G of J)O.delete(G),O.delete(V(G));return O}function p$($,J,O){if(!J)return $;let G=String(J).split(",").map((z)=>z.trim()).filter(Boolean),Z=$;for(let z of G){let Q=z.startsWith("-"),L=Q?z.slice(1):z;if(!/^\w+$/.test(L))continue;let T=O.get(L);if(!T)continue;Z=Z.orderBy(T,Q?"desc":"asc")}return Z}function gJ($){try{return JSON.parse($)}catch{return $}}function yJ($){try{return JSON.parse($)}catch{return[]}}function A$($,J,O){if(!$||typeof $!=="object"||!J||Object.keys(J).length===0)return $;let G={...$};for(let[Z,z]of Object.entries(J)){let Q=typeof z==="string"?bJ[z]:z;if(!Q||typeof Q[O]!=="function")continue;if(Object.prototype.hasOwnProperty.call(G,Z))G[Z]=Q[O](G[Z]);let L=V(Z);if(L!==Z&&Object.prototype.hasOwnProperty.call(G,L))G[L]=Q[O](G[L])}return G}function D$($,J,O){let G=J?.attributes??{},Z={};for(let[z,Q]of Object.entries(G)){let L=Q?.validation?.rule;if(!L||typeof L.validate!=="function")continue;let T=Object.prototype.hasOwnProperty.call($,z);if(!T&&O==="updating")continue;let X=Q!==null&&typeof Q==="object"&&Object.prototype.hasOwnProperty.call(Q,"default"),W=T?$[z]:X?Q.default:void 0,B=PJ(L,W),H=L.validate(B);if(!H?.valid&&Array.isArray(H?.errors)&&H.errors.length>0)Z[z]=H.errors.map((I)=>Q?.validation?.message?.[I?.code]??I?.message??"invalid")}return Object.keys(Z).length===0?{valid:!0}:{valid:!1,errors:Z}}function U$($){return $.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function T$($){if(Array.isArray($))return $.filter((J)=>typeof J==="string"&&J.length>0);return typeof $==="string"&&$?[$]:[]}function m$($){let J=typeof $==="object"&&$!==null&&"middleware"in $,O=$?.middleware;if(!J)return{read:["auth"],write:["auth"],declared:!1};if(O&&typeof O==="object"&&!Array.isArray(O)){let Z=O;return{read:"read"in Z?T$(Z.read):["auth"],write:"write"in Z?T$(Z.write):["auth"],declared:!0}}let G=T$(O);return{read:G,write:G,declared:!0}}function i$($){let J=Number.parseInt($.get("page")||String(1),10),O=Number.isFinite(J)?Math.max(1,J):1,G=Number.parseInt($.get("per_page")||String(y$),10),Z=Math.min(Number.isFinite(G)?Math.max(1,G):y$,qJ);return{page:O,perPage:Z,offset:(O-1)*Z}}function W$($,J){let O=new URL($.toString());return O.searchParams.set("page",String(J)),`${O.pathname}${O.search}`}function K$($,J,O,G,Z,z){let Q=(J-1)*O,L=G===0,T={page:J,per_page:O,from:L?null:Q+1,to:L?null:Q+G,has_more_pages:Z,prev_page_url:J>1?W$($,J-1):null,next_page_url:Z?W$($,J+1):null};if(z!==void 0&&!Number.isNaN(z)){let X=Math.max(1,Math.ceil(z/O));T.total=z,T.last_page=X,T.first_page_url=W$($,1),T.last_page_url=W$($,X)}return T}function E$($,J,O,G,Z,z){let{page:Q,...L}=K$($,J,O,G,Z,z);return{current_page:Q,...L}}var fJ,bJ,y$=15,qJ=100;var n$=d(()=>{fJ=["id","uuid","created_at","updated_at","deleted_at"];bJ={string:{get:($)=>$!=null?String($):null,set:($)=>$!=null?String($):null},number:{get:($)=>$!=null?Number($):null,set:($)=>$!=null?Number($):null},integer:{get:($)=>$!=null?Math.trunc(Number($)):null,set:($)=>$!=null?Math.trunc(Number($)):null},float:{get:($)=>$!=null?Number.parseFloat(String($)):null,set:($)=>$!=null?Number.parseFloat(String($)):null},boolean:{get:($)=>$===1||$==="1"||$===!0||$==="true",set:($)=>$===!0||$===1||$==="1"||$==="true"?1:0},json:{get:($)=>$==null?null:typeof $==="string"?gJ($):$,set:($)=>$==null?null:typeof $==="string"?$:JSON.stringify($)},datetime:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString():$},date:{get:($)=>$?new Date($):null,set:($)=>$ instanceof Date?$.toISOString().split("T")[0]:$},array:{get:($)=>$==null?[]:Array.isArray($)?$:typeof $==="string"?yJ($):[],set:($)=>$==null?null:Array.isArray($)?JSON.stringify($):$}}});var s$={};Q$(s$,{modelFiles:()=>o$,loadModelRegistry:()=>S$});import{readdirSync as cJ}from"fs";import{basename as wJ,extname as l$,join as vJ}from"path";function o$($){let J=[],O=(G)=>{let Z;try{Z=cJ(G,{withFileTypes:!0})}catch{return}for(let z of Z){let Q=vJ(G,z.name);if(z.isDirectory()){O(Q);continue}if(![".ts",".js"].includes(l$(z.name)))continue;if(z.name.startsWith(".")||z.name.startsWith("index"))continue;J.push(Q)}};return O($),J.sort()}async function u$($,J,O){for(let G of o$($))try{let Z=l$(G),z=await import(`${G}?t=${Date.now()}`),Q=z.default??z,L=Q.name??wJ(G,Z);J[L]={...Q,name:L}}catch(Z){O?.(G,Z)}}async function S$($){let J={};return await u$($.defaultsRoot,J,$.onImportError),await u$($.userRoot,J,$.onImportError),J}var I$=()=>{};import{route as i}from"@stacksjs/router";import{env as o}from"@stacksjs/env";import{projectPath as OJ,storagePath as hJ}from"@stacksjs/path";import{createQueryBuilder as pJ,defaultConfig as t$,setConfig as d$}from"@stacksjs/query-builder";import{HttpError as u}from"@stacksjs/error-handling";import{log as x$}from"@stacksjs/logging";function s($,J){let O=U$(J);return i.routes.some((G)=>G.method===$&&U$(String(G.path??""))===O)}function GJ($){if(!$.attributes)return[];return Object.entries($.attributes).filter(([J,O])=>O.hidden===!0).map(([J])=>J)}function r$($){if($.endsWith("y")&&!/[aeiou]y$/i.test($))return`${$.slice(0,-1)}ies`;if(/(?:s|x|z|ch|sh)$/i.test($))return`${$}es`;return`${$}s`}async function a$($,J,O,G){if(!$.length)return $;let Z=O.split(",").map((X)=>X.trim()).filter(Boolean);if(!Z.length)return $;let z=Array.isArray(J.belongsTo)?J.belongsTo:[],Q=Array.isArray(J.hasMany)?J.hasMany:[],L=Array.isArray(J.hasOne)?J.hasOne:[],T=new Map;for(let X of z)T.set(V(X),{kind:"belongsTo",modelName:X});for(let X of L)T.set(V(X),{kind:"hasOne",modelName:X});for(let X of Q)T.set(r$(V(X)),{kind:"hasMany",modelName:X});for(let X of Z){let W=T.get(X);if(!W)continue;let B=G[W.modelName];if(!B)continue;let H=B.table||r$(V(W.modelName)),I=GJ(B),E=(k)=>r(G$(k,B),I);if(W.kind==="belongsTo"||W.kind==="hasOne"){let k=`${V(W.modelName)}_id`,C=[...new Set($.map((M)=>M[k]).filter((M)=>M!=null))];if(!C.length){for(let M of $)M[X]=null;continue}let q=await g.selectFrom(H).whereIn("id",C).get(),P=new Map;for(let M of q??[])P.set(String(M.id),E(M));for(let M of $)M[X]=P.get(String(M[k]))??null}else{let k=String(J.name??""),C=`${V(k)}_id`,q=[...new Set($.map((Y)=>Y.id).filter((Y)=>Y!=null))];if(!q.length){for(let Y of $)Y[X]=[];continue}let P=await g.selectFrom(H).whereIn(C,q).get(),M=new Map;for(let Y of P??[]){let K=String(Y[C]),x=M.get(K)??[];x.push(E(Y)),M.set(K,x)}for(let Y of $)Y[X]=M.get(String(Y.id))??[]}}return $}async function e$($,J){let O=J?.set;if(!O||typeof O!=="object")return $;let G={...$};for(let[Z,z]of Object.entries(O)){if(typeof z!=="function"||!(Z in G))continue;try{G[Z]=await z(G)}catch{}}return G}function $J($,J){return A$($,J?.casts,"set")}function G$($,J){return A$($,J?.casts,"get")}function j($,J=200){return new Response(JSON.stringify($),{status:J,headers:{"Content-Type":"application/json"}})}async function V$($){if(Number($.headers?.get?.("content-length")??0)>X$)throw new u(413,`Request body exceeds ${X$}-byte limit`);if($.jsonBody&&typeof $.jsonBody==="object")return $.jsonBody;if($.formBody&&typeof $.formBody==="object")return $.formBody;try{let O=await $.clone().text();if(O.length>X$)throw new u(413,`Request body exceeds ${X$}-byte limit`);if(!O)return{};let G=JSON.parse(O);return G&&typeof G==="object"&&!Array.isArray(G)?G:{}}catch(O){if(O instanceof u)throw O;throw new u(400,`Invalid JSON body: ${O.message}`)}}function Y$($){if($==null)return null;if(typeof $==="number")return Number.isFinite($)&&$>0?$:null;if(typeof $==="string"){let J=$.trim();if(!J)return null;if(/^\d+$/.test(J)){let O=Number(J);return Number.isFinite(O)&&O>0?O:null}return J}return null}function ZJ($){let J=$.bearerToken;if(typeof J==="function"){let G=J.call($);if(G)return G}let O=$.headers?.get?.("authorization")||$.headers?.get?.("Authorization")||"";if(typeof O==="string"&&O.startsWith("Bearer "))return O.substring(7);return null}async function a($){let J=$._authenticatedUser;if(J)return J;let O=ZJ($);if(!O)return null;try{let{Auth:G}=await import("@stacksjs/auth"),Z=await G.getUserFromToken(O);if(Z)$._authenticatedUser=Z;return Z||null}catch{return null}}function O$($,J){if($==null||J==null)return!1;if(Array.isArray(J))return J.some((O)=>String(O)===String($));return String($)===String(J)}function iJ($){let J=ZJ($),O=$.headers?.get?.("cookie")||"";return{bearerToken:()=>J,cookies:{get:(G)=>{for(let Z of O.split(";")){let z=Z.indexOf("=");if(z===-1)continue;if(Z.slice(0,z).trim()===G)return decodeURIComponent(Z.slice(z+1).trim())}return null}}}}function zJ($){if($?.ownership)return $.ownership;let J=c$($);if(!J)return null;return{field:J,resolve:async(O,G)=>{let{resolveAuthenticatedTeamId:Z}=await import("@stacksjs/auth");return Z(iJ(G))}}}async function e($,J,O){let G=zJ($);if(!G||!G.field||typeof G.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let Z=typeof G.bypass==="function"?!!G.bypass(J,O):!1,z=null;try{z=await G.resolve(J,O)}catch{z=null}return{enforced:!0,value:z,field:String(G.field),bypass:Z}}async function JJ($,J,O,G){let Z=$?.authedFill?.[J];if(!Z)return{};if(typeof Z==="function")try{let z=await Z(O,G);return z&&typeof z==="object"?z:{}}catch{return{}}if(typeof Z==="object"){let z={};for(let[Q,L]of Object.entries(Z))try{z[Q]=typeof L==="function"?await L(O,G):L}catch{}return z}return{}}var mJ,F$,g,X$=1048576,QJ;var LJ=d(async()=>{n$();I$();mJ=OJ("config/qb.ts");try{let $=(await import(mJ)).default;d$($??t$)}catch{x$.debug("[orm] No config/qb.ts override found \u2014 deriving config from DB_CONNECTION");let $=o.DB_CONNECTION||"sqlite";d$({...t$,dialect:$,database:$==="sqlite"?{database:o.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:o.DB_DATABASE||"stacks",host:o.DB_HOST||"127.0.0.1",port:o.DB_PORT||($==="postgres"?5432:3306),username:o.DB_USERNAME||($==="postgres"?"postgres":"root"),password:o.DB_PASSWORD||""}})}F$=await S$({defaultsRoot:hJ("framework/defaults/app/Models"),userRoot:OJ("app/Models"),onImportError:($,J)=>x$.warn(`[orm] Could not load model ${$}: ${J.message}`)}),g=pJ();for(let[$,J]of Object.entries(F$)){let O=J.traits?.useApi;if(!O)continue;let G=typeof O==="object"?O:{},Z=G.uri||J.table||$.toLowerCase()+"s",z=G.routes||["index","show","store","update","destroy"],Q=J.table||Z,L=v$(J),T=GJ(J),X=q$(Z,G.prefix),W=h$(J.attributes,T),{read:B,write:H,declared:I}=m$(O);if(["store","update","destroy"].some((Y)=>z.includes(Y))&&I&&H.length===0)x$.warn(`[orm] ${$}: registering UNAUTHENTICATED mutating routes at ${X} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((Y)=>z.includes(Y))&&I&&B.length===0)x$.debug(`[orm] ${$}: registering public read routes at ${X} (declared \`middleware.read: []\`)`);let C=!!zJ(J),q=C&&!B.includes("auth")?["auth",...B]:B,P=(Y,K=q)=>{let x=Y;for(let _ of K)if(x&&typeof x.middleware==="function")x=x.middleware(_);return x};if(z.includes("index")&&!s("GET",X))P(i.get(X,async(Y)=>{try{let K=new URL(Y.url),{page:x,perPage:_,offset:N}=i$(K.searchParams),U=K.searchParams.get("sort"),A=g.selectFrom(Q);A=p$(A,U,W);let c=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[f,b]of K.searchParams.entries()){if(c.has(f)||!b)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(f))continue;let l=W.get(f);if(l)A=A.where(l,"=",b)}let F=K.searchParams.get("search");if(F&&L.length>0){let f=L.slice(0,5);A=A.where((b)=>{for(let l of f)b=b.orWhere(V(l),"like",`%${F}%`);return b})}let R=K.searchParams.get("fields");if(R){let f=R.split(",").map((b)=>b.trim()).filter((b)=>/^[a-z_][a-z0-9_]*$/i.test(b)).map((b)=>V(b));if(f.length>0)A=A.select(f)}let y=!!J.traits?.useSoftDeletes,S=K.searchParams.get("withTrashed")==="true",h=K.searchParams.get("onlyTrashed")==="true";if(y&&!S)A=h?A.whereNotNull("deleted_at"):A.whereNull("deleted_at");let D=C?await e(J,await a(Y),Y):{enforced:!1,value:null,field:"",bypass:!1};if(D.enforced&&!D.bypass){if(D.value==null||Array.isArray(D.value)&&D.value.length===0){let f=E$(K,x,_,0,!1,void 0);return new Response(JSON.stringify({data:[],...f,meta:K$(K,x,_,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}A=Array.isArray(D.value)?A.where(D.field,"in",D.value):A.where(D.field,"=",D.value)}let p=await A.limit(_+1).offset(N).get()||[],m=p.length>_,J$=(m?p.slice(0,_):p).map((f)=>r(G$(f,J),T)),C$=K.searchParams.get("include");if(C$)J$=await a$(J$,J,C$,F$);let _J=K.searchParams.get("with_count")==="true",t;if(_J)try{let f=g.selectFrom(Q);if(D.enforced&&!D.bypass&&D.value!=null)f=Array.isArray(D.value)?f.where(D.field,"in",D.value):f.where(D.field,"=",D.value);let b=await f.count(),l=typeof b==="number"?b:Number(b?.count??b);if(Number.isFinite(l))t=l}catch{}let z$={"Content-Type":"application/json"};if(t!==void 0&&!Number.isNaN(t))z$["X-Total-Count"]=String(t);z$["Cache-Control"]=D.enforced&&!D.bypass?"private, no-store":"public, max-age=15, must-revalidate",z$.Vary="Authorization";let jJ=E$(K,x,_,J$.length,m,t);return new Response(JSON.stringify({data:J$,...jJ,meta:K$(K,x,_,J$.length,m,t)}),{status:200,headers:z$})}catch(K){if(K instanceof u){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return j(x,K.status||400)}return j({error:`Failed to fetch ${Z}`,detail:String(K)},500)}}));if(z.includes("show")&&!s("GET",`${X}/{id}`))P(i.get(`${X}/{id}`,async(Y)=>{try{let K=Y$(Y.params?.id);if(K==null)return j({error:"Invalid ID parameter"},400);let x=await g.selectFrom(Q).where({id:K}).executeTakeFirst();if(!x)return j({error:`${$} not found`},404);let _=new URL(Y.url);if(J.traits?.useSoftDeletes&&x.deleted_at&&_.searchParams.get("withTrashed")!=="true")return j({error:`${$} not found`},404);let N=C?await e(J,await a(Y),Y):{enforced:!1,value:null,field:"",bypass:!1};if(N.enforced&&!N.bypass){if(N.value==null||!O$(x[N.field],N.value))return j({error:`${$} not found`},404)}let U=r(G$(x,J),T),A=_.searchParams.get("include");if(A){let[S]=await a$([U],J,A,F$);U=S}let c=U?.updated_at||U?.created_at,F=c?`W/"${U.id}-${String(c)}"`:void 0,R=Y.headers?.get?.("if-none-match");if(F&&R&&R===F)return new Response(null,{status:304,headers:{ETag:F}});let y={"Content-Type":"application/json"};if(F)y.ETag=F;return y["Cache-Control"]=N.enforced&&!N.bypass?"private, no-store":"public, max-age=30, must-revalidate",y.Vary="Authorization",new Response(JSON.stringify({data:U}),{status:200,headers:y})}catch(K){if(K instanceof u){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return j(x,K.status||400)}return j({error:`Failed to fetch ${$}`,detail:String(K)},500)}}));if(z.includes("store")&&!s("POST",X))P(i.post(X,async(Y)=>{try{let K=await V$(Y),x=H$(K,T),_=N$(x,L),N=await a(Y);if(N){let S=await JJ(J,"creating",N,Y);for(let[h,D]of Object.entries(S))if(D!==void 0&&D!==null&&_[h]===void 0)_[h]=D}let U=await e(J,N,Y);if(U.enforced&&!U.bypass){if(!N)return j({error:"Auth required"},401);let S=w$(_,U.field,U.value);if(S.error)return j({error:S.error},403);_=S.data}if(Object.keys(_).length===0)return j({error:"No fillable fields provided"},422);let A=D$(_,J,"creating");if(!A.valid)return j({success:!1,message:"Validation failed",errors:A.errors},422);if(J.traits?.useTimestamps!==!1){let S=new Date().toISOString();_.created_at=S,_.updated_at=S}let c=await e$(_,J),F=j$($J(c,J)),R=await g.insertInto(Q).values(F).execute(),y=F;try{let S=R?.lastInsertRowid??R?.insertId??R;if(S){let h=await g.selectFrom(Q).where({id:S}).executeTakeFirst();if(h)y=h}}catch{}return j({data:r(G$(y,J),T)},201)}catch(K){let{status:x,body:_}=_$(K,$,"create");return j(_,x)}}),H);if(z.includes("update")){let Y=async(K)=>{try{let x=Y$(K.params?.id);if(x==null)return j({error:"Invalid ID parameter"},400);let _=await V$(K),N=H$(_,T),U=N$(N,L),A=await a(K);if(A){let D=await JJ(J,"updating",A,K);for(let[p,m]of Object.entries(D))if(m!==void 0&&m!==null&&U[p]===void 0)U[p]=m}if(Object.keys(U).length===0)return j({error:"No fillable fields provided"},422);let c=D$(U,J,"updating");if(!c.valid)return j({success:!1,message:"Validation failed",errors:c.errors},422);let F=await g.selectFrom(Q).where({id:x}).executeTakeFirst();if(!F)return j({error:`${$} not found`},404);let R=await e(J,A,K);if(R.enforced&&!R.bypass){if(!A)return j({error:"Auth required"},401);let D=F[R.field];if(!O$(D,R.value))return j({error:`Not your ${$}`},403);let p=Object.keys(U).find((m)=>V(m)===V(R.field));if(p!==void 0&&!O$(U[p],R.value))return j({error:`Cannot reassign ${$} ownership`},403)}if(J.traits?.useTimestamps!==!1)U.updated_at=new Date().toISOString();let y=await e$(U,J),S=j$($J(y,J));await g.updateTable(Q).set(S).where({id:x}).execute();let h={...F,...S};try{let D=await g.selectFrom(Q).where({id:x}).executeTakeFirst();if(D)h=D}catch{}return j({data:r(G$(h,J),T)})}catch(x){let{status:_,body:N}=_$(x,$,"update");return j(N,_)}};if(!s("PUT",`${X}/{id}`))P(i.put(`${X}/{id}`,Y),H);if(!s("PATCH",`${X}/{id}`))P(i.patch(`${X}/{id}`,Y),H)}let M=!!J.traits?.useSoftDeletes;if(z.includes("destroy")&&!s("DELETE",`${X}/{id}`))P(i.delete(`${X}/{id}`,async(Y)=>{try{let K=Y$(Y.params?.id);if(K==null)return j({error:"Invalid ID parameter"},400);let x=await g.selectFrom(Q).where({id:K}).executeTakeFirst();if(!x)return j({error:`${$} not found`},404);let _=await a(Y),N=await e(J,_,Y);if(N.enforced&&!N.bypass){if(!_)return j({error:"Auth required"},401);let U=x[N.field];if(!O$(U,N.value))return j({error:`Not your ${$}`},403)}if(M){let U=new Date().toISOString();await g.updateTable(Q).set({deleted_at:U,updated_at:U}).where({id:K}).execute()}else await g.deleteFrom(Q).where({id:K}).execute();return new Response(null,{status:204})}catch(K){if(K instanceof u){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return j(x,K.status||400)}return j({error:`Failed to delete ${$}`,detail:String(K)},500)}}),H);if(z.includes("destroy")&&!s("POST",`${X}/bulk-delete`))P(i.post(`${X}/bulk-delete`,async(Y)=>{try{let x=(await V$(Y))?.ids;if(!Array.isArray(x)||x.length===0)return j({error:"An array of IDs is required"},422);if(x.length>100)return j({error:"Cannot delete more than 100 records at once"},422);let _=[],N=[];for(let F of x){let R=Y$(F);if(R!=null)_.push(R);else N.push(F)}if(N.length>0)return j({error:"Invalid IDs in batch",invalid:N},422);let U=await a(Y),A=await e(J,U,Y);if(A.enforced&&!A.bypass){if(!U)return j({error:"Auth required"},401);if(A.value==null)return j({error:"Caller has no ownership identity"},403);let F=await g.selectFrom(Q).select(["id",A.field]).execute(),R=new Set(F.filter((S)=>O$(S[A.field],A.value)).map((S)=>String(S.id))),y=_.filter((S)=>!R.has(String(S)));if(y.length>0)return j({error:`Cannot delete ${$} you don't own`,ids:y},403)}let c=new Date().toISOString();for(let F of _)if(M)await g.updateTable(Q).set({deleted_at:c,updated_at:c}).where({id:F}).execute();else await g.deleteFrom(Q).where({id:F}).execute();return j({message:`Successfully deleted ${_.length} ${Z}`})}catch(K){if(K instanceof u){let x={error:K.message};if(K.details!==void 0)x.details=K.details;return j(x,K.status||400)}return j({error:`Failed to bulk delete ${Z}`,detail:String(K)},500)}}),H)}QJ=i});var WJ={};Q$(WJ,{default:()=>QJ});var KJ=d(async()=>{await LJ()});class R${data;status;headers;isOk;constructor($,J,O,G){this.data=$;this.status=J;this.headers=O;this.isOk=G}ok(){return this.status===200}created(){return this.status===201}accepted(){return this.status===202}noContent(){return this.status===204}movedPermanently(){return this.status===301}found(){return this.status===302}badRequest(){return this.status===400}unauthorized(){return this.status===401}paymentRequired(){return this.status===402}forbidden(){return this.status===403}notFound(){return this.status===404}requestTimeout(){return this.status===408}conflict(){return this.status===409}unprocessableEntity(){return this.status===422}tooManyRequests(){return this.status===429}serverError(){return this.status===500}}class k${defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData=!1;customHeaders={};attachments=[];isMultipart=!1;digestAuth;withQueryParams($){return this.queryParams=$,this}withHeaders($){return this.customHeaders={...this.customHeaders,...$},this}accept($){return this.defaultHeaders.Accept=$,this}acceptJson(){return this.accept("application/json")}withToken($){return this.customHeaders.Authorization=`Bearer ${$}`,this}withBasicAuth($,J){let O=btoa(`${$}:${J}`);return this.customHeaders.Authorization=`Basic ${O}`,this}withDigestAuth($,J){return this.digestAuth={username:$,password:J},this}withBody($){return this.bodyData=$,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach($,J,O,G){let Z=typeof J==="string"?new Blob([J],{type:G?.["Content-Type"]||"text/plain"}):J;return this.attachments.push({name:$,content:Z,filename:O,headers:G}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams($){if(!this.queryParams)return $;let J=new URLSearchParams;Object.entries(this.queryParams).forEach(([Z,z])=>{if(z!=null)J.append(Z,String(z))});let O=J.toString();if(!O)return $;let G=$.includes("?");return $+(G?"&":"?")+O}async formatBody($){let J=$||this.bodyData;if(this.isMultipart){let O=new FormData;if(J)Object.entries(J).forEach(([G,Z])=>{O.append(G,String(Z))});for(let G of this.attachments)if(G.headers){let Z=G.content instanceof Blob?new Blob([G.content],{type:G.headers["Content-Type"]}):G.content;O.append(G.name,Z,G.filename)}else O.append(G.name,G.content,G.filename);return O}if(this.isFormData&&J){let O=new URLSearchParams;return Object.entries(J).forEach(([G,Z])=>{if(Z!=null)O.append(G,String(Z))}),O.toString()}return J?JSON.stringify(J):void 0}resetState(){this.queryParams=void 0,this.bodyData=void 0,this.isFormData=!1,this.isMultipart=!1,this.customHeaders={},this.attachments=[],this.digestAuth=void 0,this.defaultHeaders["Content-Type"]="application/json"}async handleDigestAuth($,J,O,G){if($.status!==401||!this.digestAuth)return $;let Z=$.headers.get("WWW-Authenticate");if(!Z?.startsWith("Digest "))return $;let z=Z.substring(7).split(",").reduce((I,E)=>{let[k,C]=E.trim().split("=");if(k)I[k]=C?.replace(/["']/g,"")??"";return I},{}),Q=await this.generateMD5(`${this.digestAuth.username}:${z.realm}:${this.digestAuth.password}`),L=await this.generateMD5(`${O}:${J}`),T="00000001",X=await this.generateMD5(Date.now().toString()).then((I)=>I.substring(0,8)),W=await this.generateMD5(`${Q}:${z.nonce}:${T}:${X}:${z.qop}:${L}`),B={username:`"${this.digestAuth.username}"`,realm:`"${z.realm}"`,nonce:`"${z.nonce}"`,uri:`"${J}"`,algorithm:z.algorithm?`"${z.algorithm}"`:void 0,qop:`"${z.qop}"`,nc:T,cnonce:`"${X}"`,response:`"${W}"`,opaque:z.opaque?`"${z.opaque}"`:void 0},H=Object.entries(B).filter(([I,E])=>E!==void 0).map(([I,E])=>`${I}=${E}`).join(", ");return this.customHeaders.Authorization=`Digest ${H}`,fetch(J,{method:O,headers:this.getHeaders(),body:G?this.formatBody(G):void 0})}async generateMD5($){let O=new TextEncoder().encode($),G=await crypto.subtle.digest("SHA-256",O);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}async request($,J,O){let G=this.addQueryParams($),Z=await this.formatBody(O),z=await fetch(G,{method:J,headers:this.getHeaders(),body:Z});if(this.digestAuth)z=await this.handleDigestAuth(z,G,J,O);let Q=await z.json();return this.resetState(),new R$(Q,z.status,z.headers,z.ok)}async get($){return this.request($,"GET")}async post($,J){return this.request($,"POST",J)}async put($,J){return this.request($,"PUT",J)}async patch($,J){return this.request($,"PATCH",J)}async delete($){return this.request($,"DELETE")}}var rJ=new k$;B$();import{path as $$}from"@stacksjs/path";function YJ($){if(!$||typeof $!=="object")return{type:"string"};let J=$,O=Array.isArray(J.rules)?J.rules:[],G=(W)=>O.find((B)=>B.name===W),Z=(W,B)=>{let H=G(W)?.params?.[B];return typeof H==="number"?H:void 0},z=J.name??J._type??"string",Q={type:z==="enum"?"string":z},L=Z("min","min")??(typeof J._min==="number"?J._min:void 0),T=Z("max","max")??(typeof J._max==="number"?J._max:void 0);if(L!==void 0)Q[z==="string"?"minLength":"minimum"]=L;if(T!==void 0)Q[z==="string"?"maxLength":"maximum"]=T;if(G("email")||J._email)Q.format="email";if(G("url")||J._url)Q.format="uri";if(G("uuid")||J._uuid)Q.format="uuid";let X=Array.isArray(J.allowedValues)?J.allowedValues:Array.isArray(J._enum)?J._enum:null;if(X)Q.enum=X;return Q}function nJ($){if(!$||typeof $!=="object")return!1;let J=$;return Boolean(J.isRequired??J._required)}function XJ($){return $.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function uJ($){let J={id:{type:"integer"}},O=["id"];if($.traits?.useUuid)J.uuid={type:"string",format:"uuid"},O.push("uuid");for(let[G,Z]of Object.entries($.attributes??{})){if(Z.hidden===!0)continue;let z=XJ(G);if(J[z]=YJ(Z.validation?.rule),Z.required===!0)O.push(z)}for(let G of $.belongsTo??[]){if(typeof G!=="string"||!G.trim())continue;let Z=`${XJ(G.trim())}_id`;J[Z]??={type:"integer"}}if($.traits?.useTimestamps!==!1)J.created_at={type:"string",format:"date-time"},J.updated_at={type:"string",format:"date-time"};if($.traits?.useSoftDeletes)J.deleted_at={type:"string",format:"date-time",nullable:!0};return{type:"object",properties:J,required:[...new Set(O)]}}function lJ($){let J=$.traits?.useApi;if(!J||typeof J!=="object"||!J.uri)return null;let O=String(J.prefix||"").replace(/^\/+|\/+$/g,""),G=String(J.uri).replace(/^\/+|\/+$/g,"");return`/api/${O?`${O}/`:""}${G}`}function oJ($,J){let O={...J},G=$?.responses;if(G&&typeof G==="object")for(let[z,Q]of Object.entries(G)){let L=Q;if(!L||typeof L!=="object"||typeof L.description!=="string")continue;O[String(z)]={description:L.description,...L.schema&&typeof L.schema==="object"?{content:{"application/json":{schema:L.schema}}}:{}}}let Z=$?.responseHeaders;if(Z&&typeof Z==="object"){let z={};for(let[Q,L]of Object.entries(Z)){let T=L;if(!T||typeof T!=="object"||typeof T.description!=="string")continue;z[Q]={description:T.description,...T.schema&&typeof T.schema==="object"?{schema:T.schema}:{}}}if(Object.keys(z).length>0)for(let Q of Object.keys(O))O[Q]={...O[Q],headers:z}}return O}async function sJ($){if(typeof $!=="string"||!$||$.includes(".."))return null;try{let{path:J}=await import("@stacksjs/path"),O=[J.appPath(`${$}.ts`),J.storagePath(`framework/defaults/app/${$}.ts`)];for(let G of O)try{if(!await Bun.file(G).exists())continue;let Q=(await import(G)).default;return Q&&typeof Q==="object"?Q:null}catch{}}catch{}return null}async function _O($={}){let J=$.portable??!0,{listRegisteredRoutes:O}=await import("@stacksjs/router");try{let{loadRoutes:W}=await import("@stacksjs/router"),{default:B}=await import($$.appPath("Routes.ts"));await W(B)}catch(W){let B=W instanceof Error?W.message:String(W);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${B}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${B}`)}try{try{await import("@stacksjs/orm/routes")}catch{await KJ().then(() => WJ)}}catch(W){let B=W instanceof Error?W.message:String(W);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${B}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${B}`)}let G={};try{let B;try{B=await import("@stacksjs/orm/model-registry")}catch{B=await Promise.resolve().then(() => (I$(),s$))}G=await B.loadModelRegistry({defaultsRoot:$$.storagePath("framework/defaults/app/Models"),userRoot:$$.projectPath("app/Models")})}catch(W){let B=W instanceof Error?W.message:String(W);if(J)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${B}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${B}`)}let Z=(W)=>W.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),z=[...O()].map((W)=>({route:W,oasPath:Z(W.path),method:W.method.toLowerCase()})).sort((W,B)=>{if(W.oasPath!==B.oasPath)return W.oasPath<B.oasPath?-1:1;return W.method<B.method?-1:W.method>B.method?1:0});if(J&&z.length===0)throw Error("[generateOpenApi] Refusing to emit an empty spec: no routes were registered. This usually means route loading failed silently rather than that the app has no API.");let Q="Stacks API";if(!J)try{let{config:W}=await import("@stacksjs/config");if(W.app?.name)Q=`${W.app.name} API`}catch{}let L={openapi:"3.0.0",info:{title:Q,version:"1.0.0"},paths:{},components:{schemas:{}}},T=Object.values(G).map((W)=>({name:String(W.name),path:lJ(W),schema:uJ(W)})).filter((W)=>W.path!==null).sort((W,B)=>W.name<B.name?-1:W.name>B.name?1:0);for(let W of T)L.components.schemas[W.name]=W.schema;let X=new Set;for(let{route:W,oasPath:B,method:H}of z){if(!L.paths[B])L.paths[B]={};let I=[];for(let Y of W.path.matchAll(/\{(\w+)\}/g))if(Y[1])I.push(Y[1]);for(let Y of W.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(Y[1])I.push(Y[1]);let E=W.name??`${H}_${B.replace(/[^a-z0-9]/gi,"_")}`,k=E;if(X.has(k)){k=`${E}_${H}`;let Y=2;while(X.has(k))k=`${E}_${H}_${Y++}`}X.add(k);let C={summary:W.name??W.path,operationId:k,parameters:I.map((Y)=>({name:Y,in:"path",required:!0,schema:{type:"string"}})),responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object"}}}},422:{description:"Validation failed"},500:{description:"Server error"}}},q=T.find((Y)=>B===Y.path||B===`${Y.path}/{id}`);if(q){let Y=B===q.path&&H==="get"?{type:"array",items:q.schema}:q.schema;if(C.responses[200].content={"application/json":{schema:{type:"object",properties:{data:Y},required:["data"]}}},H==="post"&&B===q.path)C.responses[201]={...C.responses[200],description:"Created"},delete C.responses[200]}let P=W.handler?await sJ(W.handler):null,M=P&&typeof P.validations==="object"&&P.validations!==null?P.validations:null;if(C.responses=oJ(P,C.responses),M&&Object.keys(M).length>0){let Y=Object.entries(M).map(([K,x])=>{let _=x?.rule;return{field:K,schema:YJ(_),required:nJ(_)}});if(H==="get"||H==="head"||H==="delete"){let K=new Set(I);for(let{field:x,schema:_,required:N}of Y){if(K.has(x))continue;C.parameters?.push({name:x,in:"query",required:N,schema:_})}}else{let K={type:"object",properties:{},required:[]},x=K.properties,_=K.required;for(let N of Y)if(x[N.field]=N.schema,N.required)_.push(N.field);if(_.length===0)delete K.required;C.requestBody={required:_.length>0,content:{"application/json":{schema:K}}}}}L.paths[B][H]=C}if($.write!==!1){let B=Bun.file($$.frameworkPath("api/openapi.json")).writer();B.write(JSON.stringify(L,null,2)),await B.end();let{renderOpenApiTypes:H}=await Promise.resolve().then(() => (L$(),f$)),{renderApiClient:I}=await Promise.resolve().then(() => (B$(),g$));await Bun.write($$.frameworkPath("api/api-types.ts"),H(L)),await Bun.write($$.frameworkPath("api/client.ts"),I(L,{name:L.info.title}))}return L}L$();class v{static instance=new v;isMissing(){return!0}}class Z${data;constructor($){this.data=$}}class xJ{condition;value;defaultValue;constructor($,J,O=new v){this.condition=$;this.value=J;this.defaultValue=O}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class BJ{resource;additional={};request;static wrap="data";static additionalMeta={};constructor($){this.resource=$}withRequest($){return this.request=$,this}withAdditional($){return this.additional={...this.additional,...$},this}resolve($){let J=this.toArray($||this.request);return this.filterAndResolve(J)}toResponse($){let J=this.resolve($),O=this.constructor.wrap;if(O)return{[O]:J,...this.additional};return{...J,...this.additional}}toJson($){return JSON.stringify(this.toResponse($))}toJSON(){return this.toResponse()}static collection($){return new M$($,this)}when($,J,O){if(typeof $==="function"?$():$)return typeof J==="function"?J():J;return O!==void 0?O:v.instance}whenNotNull($,J){if($===null||$===void 0)return v.instance;return J?J($):$}whenLoaded($,J,O){let G=this.resource;if(!(($ in G)&&G[$]!==void 0))return O!==void 0?O:v.instance;if(J!==void 0)return typeof J==="function"?J():J;return G[$]}whenCounted($,J){let O=this.resource,G=`${$}_count`;if(G in O)return O[G];return J!==void 0?J:v.instance}merge($){return new Z$($)}mergeWhen($,J){if(!(typeof $==="function"?$():$))return v.instance;let G=typeof J==="function"?J():J;return new Z$(G)}static MAX_RESOLVE_DEPTH=20;filterAndResolve($,J=0){if(J>=BJ.MAX_RESOLVE_DEPTH)return $;let O={};for(let[G,Z]of Object.entries($)){if(Z instanceof v)continue;if(Z instanceof Z$){Object.assign(O,this.filterAndResolve(Z.data,J+1));continue}if(Z instanceof xJ){let z=Z.resolve();if(!(z instanceof v))O[G]=z;continue}if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)&&!(Z instanceof Date)){O[G]=this.filterAndResolve(Z,J+1);continue}if(Array.isArray(Z)){O[G]=Z.filter((z)=>!(z instanceof v)).map((z)=>{if(z instanceof Z$)return z.data;if(z!==null&&typeof z==="object"&&!(z instanceof Date))return this.filterAndResolve(z,J+1);return z});continue}O[G]=Z}return O}static withoutWrapping(){this.wrap=null}static wrapWith($){this.wrap=$}}class M${resources;ResourceClass;additional={};request;static wrap="data";constructor($,J){this.resources=$,this.ResourceClass=J}withRequest($){return this.request=$,this}withAdditional($){return this.additional={...this.additional,...$},this}resolve($){let J=$||this.request;return this.resources.map((O)=>{let G=new this.ResourceClass(O);if(J)G.withRequest(J);return G.resolve(J)})}toResponse($){let J=this.resolve($),O=this.constructor.wrap;if(O)return{[O]:J,...this.additional};return{data:J,...this.additional}}toJson($){return JSON.stringify(this.toResponse($))}count(){return this.resources.length}isEmpty(){return this.resources.length===0}isNotEmpty(){return this.resources.length>0}}class TJ extends M${meta;links;constructor($,J){super($.data,J);this.meta=$.meta,this.links=$.links}static fromPagination($,J,O){let{currentPage:G,perPage:Z,total:z,baseUrl:Q=""}=O,L=Math.ceil(z/Z),T=z>0?(G-1)*Z+1:null,X=z>0?Math.min(G*Z,z):null;return new TJ({data:$,meta:{current_page:G,from:T,last_page:L,per_page:Z,to:X,total:z},links:{first:`${Q}?page=1`,last:`${Q}?page=${L}`,prev:G>1?`${Q}?page=${G-1}`:null,next:G<L?`${Q}?page=${G+1}`:null}},J)}toResponse($){return{data:this.resolve($),meta:this.meta,links:this.links,...this.additional}}}function NO($,J){let O=J($);return{toResponse:()=>({data:O}),toJson:()=>JSON.stringify({data:O})}}function HO($,J){let O=$.map(J);return{toResponse:()=>({data:O}),toJson:()=>JSON.stringify({data:O})}}export{w as schemaType,YJ as ruleToSchema,nJ as ruleIsRequired,NO as resource,IJ as renderOpenApiTypes,RJ as renderApiClient,uJ as modelDefinitionToSchema,b$ as methodName,_O as generateOpenApi,rJ as fetcher,oJ as describedResponses,HO as collection,M$ as ResourceCollection,TJ as PaginatedResourceCollection,v as MissingValue,Z$ as MergeValue,BJ as JsonResource,xJ as ConditionalValue};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/api",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.71.2",
5
+ "version": "0.71.10",
6
6
  "description": "The Stacks API utilities.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -62,6 +62,6 @@
62
62
  },
63
63
  "devDependencies": {
64
64
  "better-dx": "^0.2.23",
65
- "@stacksjs/utils": "0.71.2"
65
+ "@stacksjs/utils": "0.71.10"
66
66
  }
67
67
  }