@stacksjs/api 0.72.56 → 0.72.57
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/index.js +15 -15
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
${["query","header","path","cookie"].map((
|
|
2
|
+
var jJ=Object.defineProperty;var HJ=($)=>$;function DJ($,J){this[$]=HJ.bind(null,J)}var Q$=($,J)=>{for(var G in J)jJ($,G,{get:J[G],enumerable:!0,configurable:!0,set:DJ.bind(J,G)})};var t=($,J)=>()=>($&&(J=$($=0)),J);var n=import.meta.require;var f$={};Q$(f$,{schemaType:()=>v,renderOpenApiTypes:()=>FJ});function AJ($){return typeof $==="string"?JSON.stringify($):String($)}function v($){if(!$)return"unknown";if($.enum?.length)return $.enum.map(AJ).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<${v($.items)}>`;if($.type==="object"||$.properties||$.additionalProperties){let J=new Set($.required||[]),G=Object.entries($.properties||{}).map(([O,Z])=>`${JSON.stringify(O)}${J.has(O)?"":"?"}: ${v(Z)}`);if($.additionalProperties){let O=$.additionalProperties===!0?"unknown":v($.additionalProperties);G.push(`[key: string]: ${O}`)}return G.length?`{ ${G.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function EJ($=[]){return` parameters: {
|
|
3
|
+
${["query","header","path","cookie"].map((G)=>{let O=$.filter((z)=>z.in===G);if(!O.length)return` ${G}?: never`;let Z=O.map((z)=>`${JSON.stringify(z.name)}${z.required?"":"?"}: ${v(z.schema)}`);return` ${G}${O.every((z)=>!z.required)?"?":""}: { ${Z.join("; ")} }`}).join(`
|
|
4
4
|
`)}
|
|
5
|
-
}`}function P$($){if(!$||!Object.keys($).length)return"never";return`{ ${Object.entries($).map(([J,
|
|
5
|
+
}`}function P$($){if(!$||!Object.keys($).length)return"never";return`{ ${Object.entries($).map(([J,G])=>`${JSON.stringify(J)}: ${v(G.schema)}`).join("; ")} }`}function SJ($){let J=$.requestBody?`
|
|
6
6
|
requestBody${$.requestBody.required?"":"?"}: { content: ${P$($.requestBody.content)} }`:`
|
|
7
|
-
requestBody?: never`,
|
|
7
|
+
requestBody?: never`,G=Object.entries($.responses||{}).map(([O,Z])=>` ${JSON.stringify(O)}: { content: ${P$(Z.content)} }`);return`{
|
|
8
8
|
${EJ($.parameters)}${J}
|
|
9
9
|
responses: {
|
|
10
|
-
${
|
|
10
|
+
${G.join(`
|
|
11
11
|
`)}
|
|
12
12
|
}
|
|
13
|
-
}`}function
|
|
13
|
+
}`}function FJ($){let J=Object.entries($.paths||{}).map(([O,Z])=>{let z=UJ.map((Q)=>{let W=Z[Q];return W?` ${Q}: ${SJ(W)}`:` ${Q}?: never`});return` ${JSON.stringify(O)}: {
|
|
14
14
|
${z.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}),
|
|
16
|
+
}`}),G=Object.entries($.components?.schemas||{}).map(([O,Z])=>` ${JSON.stringify(O)}: ${v(Z)}`);return`/**
|
|
17
17
|
* Generated from storage/framework/api/openapi.json by @stacksjs/api.
|
|
18
18
|
* Do not edit this file directly; run bun run docs:artifacts to regenerate it.
|
|
19
19
|
*/
|
|
@@ -25,19 +25,19 @@ ${J.join(`
|
|
|
25
25
|
|
|
26
26
|
export interface components {
|
|
27
27
|
schemas: {
|
|
28
|
-
${
|
|
28
|
+
${G.join(`
|
|
29
29
|
`)}
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
-
`}var
|
|
33
|
-
${
|
|
32
|
+
`}var UJ;var L$=t(()=>{UJ=["get","put","post","delete","options","head","patch","trace"]});var b$={};Q$(b$,{renderApiClient:()=>RJ,methodName:()=>g$});function g$($){let J=$.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean),G=J[0]?.toLowerCase()==="api"?J.slice(1):J[1]?.toLowerCase()==="api"?[J[0],...J.slice(2)]:J,[O,...Z]=G;if(!O)return"call";let z=O.charAt(0).toLowerCase()+O.slice(1),Q=Z.map((B)=>B.charAt(0).toUpperCase()+B.slice(1)),W=[z,...Q].join("");return/^[a-z_$]/i.test(W)?W:`call${W.charAt(0).toUpperCase()}${W.slice(1)}`}function VJ($){let J=$.responses??{},G=Object.keys(J).find((z)=>z.startsWith("2"));if(!G)return"unknown";let O=J[G]?.content,Z=O?.["application/json"]??Object.values(O??{})[0];return Z?.schema?v(Z.schema):"unknown"}function MJ($,J=" "){let G=$.filter(Boolean);if(!G.length)return"";return`${J}/**
|
|
33
|
+
${G.map((O)=>`${J} * ${O}`).join(`
|
|
34
34
|
`)}
|
|
35
35
|
${J} */
|
|
36
|
-
`}function CJ($,J,O
|
|
37
|
-
return request(config, ${JSON.stringify(J.toUpperCase())}, ${JSON.stringify($)}, ${X.length?"input ?? {}":"{}"}, ${
|
|
38
|
-
},`}function RJ($,J={}){let
|
|
36
|
+
`}function CJ($,J,G,O){let Z=G.parameters??[],z=Z.filter((E)=>E.in==="path"),Q=Z.filter((E)=>E.in==="query"),W=G.requestBody?.content?.["application/json"]?.schema,B=Boolean(G.requestBody?.required),X=[];for(let E of[...z,...Q]){let k=E.in==="path"||E.required;X.push(`${JSON.stringify(E.name)}${k?"":"?"}: ${v(E.schema)}`)}if(W)X.push(`body${B?"":"?"}: ${v(W)}`);let K=[...z,...Q].every((E)=>E.in!=="path"&&!E.required)&&(!W||!B),x=X.length?`input${K?"?":""}: { ${X.join("; ")} }, `:"",U=Q.length?`[${Q.map((E)=>JSON.stringify(E.name)).join(", ")}]`:"[]";return`${MJ([G.summary&&G.summary!==$?G.summary:`${J.toUpperCase()} ${$}`,G.description??""])} ${O}(${x}options?: RequestOptions): Promise<ApiResult<${VJ(G)}>> {
|
|
37
|
+
return request(config, ${JSON.stringify(J.toUpperCase())}, ${JSON.stringify($)}, ${X.length?"input ?? {}":"{}"}, ${U}, ${W?"true":"false"}, options)
|
|
38
|
+
},`}function RJ($,J={}){let G=J.name??"API",O=new Map,Z=[];for(let[z,Q]of Object.entries($.paths??{}))for(let W of IJ){let B=Q[W];if(!B)continue;let X=g$(B.operationId??`${W}_${z}`),K=O.get(X)??0;O.set(X,K+1),Z.push(CJ(z,W,B,K===0?X:`${X}${K+1}`))}return`/* eslint-disable */
|
|
39
39
|
/**
|
|
40
|
-
* ${
|
|
40
|
+
* ${G} client, generated from the OpenAPI document.
|
|
41
41
|
*
|
|
42
42
|
* Do not edit. Run \`buddy generate:openapi\` to rebuild it from the routes.
|
|
43
43
|
*
|
|
@@ -136,4 +136,4 @@ ${Z.join(`
|
|
|
136
136
|
}
|
|
137
137
|
|
|
138
138
|
export type Client = ReturnType<typeof createClient>
|
|
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 F($){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[F(O)]=G;return J}function q$($,J){let O=String(J||"").replace(/^\/+|\/+$/g,""),G=String($).replace(/^\/+/,"");return`/api/${O?`${O}/`:""}${G}`}function w$($){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 c$($,J,O){let G=Object.keys($).find((z)=>F(z)===F(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(F(z)===F(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=F(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=F(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[F(G)];return O}function r($,J){if(!$||J.length===0)return $;let O={...$};for(let G of J)delete O[G],delete O[F(G)];return O}function h$($,J){let O=new Map;for(let G of[...Object.keys($??{}),...fJ]){let Z=F(G);if(!/^\w+$/.test(Z))continue;O.set(G,Z),O.set(Z,Z)}for(let G of J)O.delete(G),O.delete(F(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("-"),W=Q?z.slice(1):z;if(!/^\w+$/.test(W))continue;let x=O.get(W);if(!x)continue;Z=Z.orderBy(x,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 W=F(Z);if(W!==Z&&Object.prototype.hasOwnProperty.call(G,W))G[W]=Q[O](G[W])}return G}function D$($,J,O){let G=J?.attributes??{},Z={};for(let[z,Q]of Object.entries(G)){let W=Q?.validation?.rule;if(!W||typeof W.validate!=="function")continue;let x=Object.prototype.hasOwnProperty.call($,z);if(!x&&O==="updating")continue;let X=Q!==null&&typeof Q==="object"&&Object.prototype.hasOwnProperty.call(Q,"default"),K=x?$[z]:X?Q.default:void 0,B=PJ(W,K),D=W.validate(B);if(!D?.valid&&Array.isArray(D?.errors)&&D.errors.length>0)Z[z]=D.errors.map((C)=>Q?.validation?.message?.[C?.code]??C?.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,W=G===0,x={page:J,per_page:O,from:W?null:Q+1,to:W?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));x.total=z,x.last_page=X,x.first_page_url=W$($,1),x.last_page_url=W$($,X)}return x}function E$($,J,O,G,Z,z){let{page:Q,...W}=K$($,J,O,G,Z,z);return{current_page:Q,...W}}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 t$={};Q$(t$,{modelFiles:()=>o$,loadModelRegistry:()=>S$});import{readdirSync as wJ}from"fs";import{basename as cJ,extname as l$,join as vJ}from"path";function o$($){let J=[],O=(G)=>{let Z;try{Z=wJ(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,W=Q.name??cJ(G,Z);J[W]={...Q,name:W}}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 s$,setConfig as d$}from"@stacksjs/query-builder";import{HttpError as u}from"@stacksjs/error-handling";import{log as x$}from"@stacksjs/logging";function t($,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:[],W=Array.isArray(J.hasOne)?J.hasOne:[],x=new Map;for(let X of z)x.set(F(X),{kind:"belongsTo",modelName:X});for(let X of W)x.set(F(X),{kind:"hasOne",modelName:X});for(let X of Q)x.set(r$(F(X)),{kind:"hasMany",modelName:X});for(let X of Z){let K=x.get(X);if(!K)continue;let B=G[K.modelName];if(!B)continue;let D=B.table||r$(F(K.modelName)),C=GJ(B),E=(k)=>r(G$(k,B),C);if(K.kind==="belongsTo"||K.kind==="hasOne"){let k=`${F(K.modelName)}_id`,V=[...new Set($.map((M)=>M[k]).filter((M)=>M!=null))];if(!V.length){for(let M of $)M[X]=null;continue}let q=await g.selectFrom(D).whereIn("id",V).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??""),V=`${F(k)}_id`,q=[...new Set($.map((_)=>_.id).filter((_)=>_!=null))];if(!q.length){for(let _ of $)_[X]=[];continue}let P=await g.selectFrom(D).whereIn(V,q).get(),M=new Map;for(let _ of P??[]){let L=String(_[V]),Y=M.get(L)??[];Y.push(E(_)),M.set(L,Y)}for(let _ of $)_[X]=M.get(String(_.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=w$($);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,W]of Object.entries(Z))try{z[Q]=typeof W==="function"?await W(O,G):W}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$($??s$)}catch{x$.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let $=o.DB_CONNECTION||"sqlite";d$({...s$,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,W=v$(J),x=GJ(J),X=q$(Z,G.prefix),K=h$(J.attributes,x),{read:B,write:D,declared:C}=m$(O);if(["store","update","destroy"].some((_)=>z.includes(_))&&C&&D.length===0)x$.warn(`[orm] ${$}: registering UNAUTHENTICATED mutating routes at ${X} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((_)=>z.includes(_))&&C&&B.length===0)x$.debug(`[orm] ${$}: registering public read routes at ${X} (declared \`middleware.read: []\`)`);let V=!!zJ(J),q=V&&!B.includes("auth")?["auth",...B]:B,P=(_,L=q)=>{let Y=_;for(let T of L)if(Y&&typeof Y.middleware==="function")Y=Y.middleware(T);return Y};if(z.includes("index")&&!t("GET",X))P(i.get(X,async(_)=>{try{let L=new URL(_.url),{page:Y,perPage:T,offset:H}=i$(L.searchParams),N=L.searchParams.get("sort"),A=g.selectFrom(Q);A=p$(A,N,K);let w=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[f,b]of L.searchParams.entries()){if(w.has(f)||!b)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(f))continue;let l=K.get(f);if(l)A=A.where(l,"=",b)}let I=L.searchParams.get("search");if(I&&W.length>0){let f=W.slice(0,5);A=A.where((b)=>{for(let l of f)b=b.orWhere(F(l),"like",`%${I}%`);return b})}let R=L.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)=>F(b));if(f.length>0)A=A.select(f)}let y=!!J.traits?.useSoftDeletes,S=L.searchParams.get("withTrashed")==="true",h=L.searchParams.get("onlyTrashed")==="true";if(y&&!S)A=h?A.whereNotNull("deleted_at"):A.whereNull("deleted_at");let U=V?await e(J,await a(_),_):{enforced:!1,value:null,field:"",bypass:!1};if(U.enforced&&!U.bypass){if(U.value==null||Array.isArray(U.value)&&U.value.length===0){let f=E$(L,Y,T,0,!1,void 0);return new Response(JSON.stringify({data:[],...f,meta:K$(L,Y,T,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}A=Array.isArray(U.value)?A.where(U.field,"in",U.value):A.where(U.field,"=",U.value)}let p=await A.limit(T+1).offset(H).get()||[],m=p.length>T,J$=(m?p.slice(0,T):p).map((f)=>r(G$(f,J),x)),C$=L.searchParams.get("include");if(C$)J$=await a$(J$,J,C$,F$);let _J=L.searchParams.get("with_count")==="true",s;if(_J)try{let f=g.selectFrom(Q);if(U.enforced&&!U.bypass&&U.value!=null)f=Array.isArray(U.value)?f.where(U.field,"in",U.value):f.where(U.field,"=",U.value);let b=await f.count(),l=typeof b==="number"?b:Number(b?.count??b);if(Number.isFinite(l))s=l}catch{}let z$={"Content-Type":"application/json"};if(s!==void 0&&!Number.isNaN(s))z$["X-Total-Count"]=String(s);z$["Cache-Control"]=U.enforced&&!U.bypass?"private, no-store":"public, max-age=15, must-revalidate",z$.Vary="Authorization";let jJ=E$(L,Y,T,J$.length,m,s);return new Response(JSON.stringify({data:J$,...jJ,meta:K$(L,Y,T,J$.length,m,s)}),{status:200,headers:z$})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to fetch ${Z}`,detail:String(L)},500)}}));if(z.includes("show")&&!t("GET",`${X}/{id}`))P(i.get(`${X}/{id}`,async(_)=>{try{let L=Y$(_.params?.id);if(L==null)return j({error:"Invalid ID parameter"},400);let Y=await g.selectFrom(Q).where({id:L}).executeTakeFirst();if(!Y)return j({error:`${$} not found`},404);let T=new URL(_.url);if(J.traits?.useSoftDeletes&&Y.deleted_at&&T.searchParams.get("withTrashed")!=="true")return j({error:`${$} not found`},404);let H=V?await e(J,await a(_),_):{enforced:!1,value:null,field:"",bypass:!1};if(H.enforced&&!H.bypass){if(H.value==null||!O$(Y[H.field],H.value))return j({error:`${$} not found`},404)}let N=r(G$(Y,J),x),A=T.searchParams.get("include");if(A){let[S]=await a$([N],J,A,F$);N=S}let w=N?.updated_at||N?.created_at,I=w?`W/"${N.id}-${String(w)}"`:void 0,R=_.headers?.get?.("if-none-match");if(I&&R&&R===I)return new Response(null,{status:304,headers:{ETag:I}});let y={"Content-Type":"application/json"};if(I)y.ETag=I;return y["Cache-Control"]=H.enforced&&!H.bypass?"private, no-store":"public, max-age=30, must-revalidate",y.Vary="Authorization",new Response(JSON.stringify({data:N}),{status:200,headers:y})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to fetch ${$}`,detail:String(L)},500)}}));if(z.includes("store")&&!t("POST",X))P(i.post(X,async(_)=>{try{let L=await V$(_),Y=H$(L,x),T=N$(Y,W),H=await a(_);if(H){let S=await JJ(J,"creating",H,_);for(let[h,U]of Object.entries(S))if(U!==void 0&&U!==null&&T[h]===void 0)T[h]=U}let N=await e(J,H,_);if(N.enforced&&!N.bypass){if(!H)return j({error:"Auth required"},401);let S=c$(T,N.field,N.value);if(S.error)return j({error:S.error},403);T=S.data}if(Object.keys(T).length===0)return j({error:"No fillable fields provided"},422);let A=D$(T,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();T.created_at=S,T.updated_at=S}let w=await e$(T,J),I=j$($J(w,J)),R=await g.insertInto(Q).values(I).execute(),y=I;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),x)},201)}catch(L){let{status:Y,body:T}=_$(L,$,"create");return j(T,Y)}}),D);if(z.includes("update")){let _=async(L)=>{try{let Y=Y$(L.params?.id);if(Y==null)return j({error:"Invalid ID parameter"},400);let T=await V$(L),H=H$(T,x),N=N$(H,W),A=await a(L);if(A){let U=await JJ(J,"updating",A,L);for(let[p,m]of Object.entries(U))if(m!==void 0&&m!==null&&N[p]===void 0)N[p]=m}if(Object.keys(N).length===0)return j({error:"No fillable fields provided"},422);let w=D$(N,J,"updating");if(!w.valid)return j({success:!1,message:"Validation failed",errors:w.errors},422);let I=await g.selectFrom(Q).where({id:Y}).executeTakeFirst();if(!I)return j({error:`${$} not found`},404);let R=await e(J,A,L);if(R.enforced&&!R.bypass){if(!A)return j({error:"Auth required"},401);let U=I[R.field];if(!O$(U,R.value))return j({error:`Not your ${$}`},403);let p=Object.keys(N).find((m)=>F(m)===F(R.field));if(p!==void 0&&!O$(N[p],R.value))return j({error:`Cannot reassign ${$} ownership`},403)}if(J.traits?.useTimestamps!==!1)N.updated_at=new Date().toISOString();let y=await e$(N,J),S=j$($J(y,J));await g.updateTable(Q).set(S).where({id:Y}).execute();let h={...I,...S};try{let U=await g.selectFrom(Q).where({id:Y}).executeTakeFirst();if(U)h=U}catch{}return j({data:r(G$(h,J),x)})}catch(Y){let{status:T,body:H}=_$(Y,$,"update");return j(H,T)}};if(!t("PUT",`${X}/{id}`))P(i.put(`${X}/{id}`,_),D);if(!t("PATCH",`${X}/{id}`))P(i.patch(`${X}/{id}`,_),D)}let M=!!J.traits?.useSoftDeletes;if(z.includes("destroy")&&!t("DELETE",`${X}/{id}`))P(i.delete(`${X}/{id}`,async(_)=>{try{let L=Y$(_.params?.id);if(L==null)return j({error:"Invalid ID parameter"},400);let Y=await g.selectFrom(Q).where({id:L}).executeTakeFirst();if(!Y)return j({error:`${$} not found`},404);let T=await a(_),H=await e(J,T,_);if(H.enforced&&!H.bypass){if(!T)return j({error:"Auth required"},401);let N=Y[H.field];if(!O$(N,H.value))return j({error:`Not your ${$}`},403)}if(M){let N=new Date().toISOString();await g.updateTable(Q).set({deleted_at:N,updated_at:N}).where({id:L}).execute()}else await g.deleteFrom(Q).where({id:L}).execute();return new Response(null,{status:204})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to delete ${$}`,detail:String(L)},500)}}),D);if(z.includes("destroy")&&!t("POST",`${X}/bulk-delete`))P(i.post(`${X}/bulk-delete`,async(_)=>{try{let Y=(await V$(_))?.ids;if(!Array.isArray(Y)||Y.length===0)return j({error:"An array of IDs is required"},422);if(Y.length>100)return j({error:"Cannot delete more than 100 records at once"},422);let T=[],H=[];for(let I of Y){let R=Y$(I);if(R!=null)T.push(R);else H.push(I)}if(H.length>0)return j({error:"Invalid IDs in batch",invalid:H},422);let N=await a(_),A=await e(J,N,_);if(A.enforced&&!A.bypass){if(!N)return j({error:"Auth required"},401);if(A.value==null)return j({error:"Caller has no ownership identity"},403);let I=await g.selectFrom(Q).select(["id",A.field]).execute(),R=new Set(I.filter((S)=>O$(S[A.field],A.value)).map((S)=>String(S.id))),y=T.filter((S)=>!R.has(String(S)));if(y.length>0)return j({error:`Cannot delete ${$} you don't own`,ids:y},403)}let w=new Date().toISOString();for(let I of T)if(M)await g.updateTable(Q).set({deleted_at:w,updated_at:w}).where({id:I}).execute();else await g.deleteFrom(Q).where({id:I}).execute();return j({message:`Successfully deleted ${T.length} ${Z}`})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return j(Y,L.status||400)}return j({error:`Failed to bulk delete ${Z}`,detail:String(L)},500)}}),D)}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((C,E)=>{let[k,V]=E.trim().split("=");if(k)C[k]=V?.replace(/["']/g,"")??"";return C},{}),Q=await this.generateMD5(`${this.digestAuth.username}:${z.realm}:${this.digestAuth.password}`),W=await this.generateMD5(`${O}:${J}`),x="00000001",X=await this.generateMD5(Date.now().toString()).then((C)=>C.substring(0,8)),K=await this.generateMD5(`${Q}:${z.nonce}:${x}:${X}:${z.qop}:${W}`),B={username:`"${this.digestAuth.username}"`,realm:`"${z.realm}"`,nonce:`"${z.nonce}"`,uri:`"${J}"`,algorithm:z.algorithm?`"${z.algorithm}"`:void 0,qop:`"${z.qop}"`,nc:x,cnonce:`"${X}"`,response:`"${K}"`,opaque:z.opaque?`"${z.opaque}"`:void 0},D=Object.entries(B).filter(([C,E])=>E!==void 0).map(([C,E])=>`${C}=${E}`).join(", ");return this.customHeaders.Authorization=`Digest ${D}`,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=(K)=>O.find((B)=>B.name===K),Z=(K,B)=>{let D=G(K)?.params?.[B];return typeof D==="number"?D:void 0},z=J.name??J._type??"string",Q={type:z==="enum"?"string":z},W=Z("min","min")??(typeof J._min==="number"?J._min:void 0),x=Z("max","max")??(typeof J._max==="number"?J._max:void 0);if(W!==void 0)Q[z==="string"?"minLength":"minimum"]=W;if(x!==void 0)Q[z==="string"?"maxLength":"maximum"]=x;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 W=Q;if(!W||typeof W!=="object"||typeof W.description!=="string")continue;O[String(z)]={description:W.description,...W.schema&&typeof W.schema==="object"?{content:{"application/json":{schema:W.schema}}}:{}}}let Z=$?.responseHeaders;if(Z&&typeof Z==="object"){let z={};for(let[Q,W]of Object.entries(Z)){let x=W;if(!x||typeof x!=="object"||typeof x.description!=="string")continue;z[Q]={description:x.description,...x.schema&&typeof x.schema==="object"?{schema:x.schema}:{}}}if(Object.keys(z).length>0)for(let Q of Object.keys(O))O[Q]={...O[Q],headers:z}}return O}async function tJ($){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:K}=await import("@stacksjs/router"),{default:B}=await import($$.appPath("Routes.ts"));await K(B)}catch(K){let B=K instanceof Error?K.message:String(K);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(K){let B=K instanceof Error?K.message:String(K);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$(),t$))}G=await B.loadModelRegistry({defaultsRoot:$$.storagePath("framework/defaults/app/Models"),userRoot:$$.projectPath("app/Models")})}catch(K){let B=K instanceof Error?K.message:String(K);if(J)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${B}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${B}`)}let Z=(K)=>K.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),z=[...O()].map((K)=>({route:K,oasPath:Z(K.path),method:K.method.toLowerCase()})).sort((K,B)=>{if(K.oasPath!==B.oasPath)return K.oasPath<B.oasPath?-1:1;return K.method<B.method?-1:K.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:K}=await import("@stacksjs/config");if(K.app?.name)Q=`${K.app.name} API`}catch{}let W={openapi:"3.0.0",info:{title:Q,version:"1.0.0"},paths:{},components:{schemas:{}}},x=Object.values(G).map((K)=>({name:String(K.name),path:lJ(K),schema:uJ(K)})).filter((K)=>K.path!==null).sort((K,B)=>K.name<B.name?-1:K.name>B.name?1:0);for(let K of x)W.components.schemas[K.name]=K.schema;let X=new Set;for(let{route:K,oasPath:B,method:D}of z){if(!W.paths[B])W.paths[B]={};let C=[];for(let L of K.path.matchAll(/\{(\w+)\}/g))if(L[1])C.push(L[1]);for(let L of K.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(L[1])C.push(L[1]);let E=K.name??`${D}_${B.replace(/[^a-z0-9]/gi,"_")}`,k=E;if(X.has(k)){k=`${E}_${D}`;let L=2;while(X.has(k))k=`${E}_${D}_${L++}`}X.add(k);let V={summary:K.name??K.path,operationId:k,parameters:C.map((L)=>({name:L,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=x.find((L)=>B===L.path||B===`${L.path}/{id}`);if(q){let L=B===q.path&&D==="get"?{type:"array",items:q.schema}:q.schema;if(V.responses[200].content={"application/json":{schema:{type:"object",properties:{data:L},required:["data"]}}},D==="post"&&B===q.path)V.responses[201]={...V.responses[200],description:"Created"},delete V.responses[200]}let P=K.handler?await tJ(K.handler):null,M=P&&typeof P.validations==="object"&&P.validations!==null?P.validations:null;V.responses=oJ(P,V.responses);let _=P?.requestHeaders;if(_&&typeof _==="object")for(let[L,Y]of Object.entries(_)){let T=Y;if(!T||typeof T!=="object"||typeof T.description!=="string")continue;V.parameters?.push({name:L,in:"header",description:T.description,required:T.required===!0,schema:T.schema&&typeof T.schema==="object"?T.schema:{type:"string"}})}if(M&&Object.keys(M).length>0){let L=Object.entries(M).map(([Y,T])=>{let H=T?.rule;return{field:Y,schema:YJ(H),required:nJ(H)}});if(D==="get"||D==="head"||D==="delete"){let Y=new Set(C);for(let{field:T,schema:H,required:N}of L){if(Y.has(T))continue;V.parameters?.push({name:T,in:"query",required:N,schema:H})}}else{let Y={type:"object",properties:{},required:[]},T=Y.properties,H=Y.required;for(let N of L)if(T[N.field]=N.schema,N.required)H.push(N.field);if(H.length===0)delete Y.required;V.requestBody={required:H.length>0,content:{"application/json":{schema:Y}}}}}W.paths[B][D]=V}if($.write!==!1){await Bun.write($$.frameworkPath("api/openapi.json"),JSON.stringify(W,null,2));let{renderOpenApiTypes:K}=await Promise.resolve().then(() => (L$(),f$)),{renderApiClient:B}=await Promise.resolve().then(() => (B$(),g$));await Bun.write($$.frameworkPath("api/api-types.ts"),K(W)),await Bun.write($$.frameworkPath("api/client.ts"),B(W,{name:W.info.title}))}return W}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,W=Math.ceil(z/Z),x=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:x,last_page:W,per_page:Z,to:X,total:z},links:{first:`${Q}?page=1`,last:`${Q}?page=${W}`,prev:G>1?`${Q}?page=${G-1}`:null,next:G<W?`${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{c 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};
|
|
139
|
+
`}var IJ;var x$=t(()=>{L$();IJ=["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 T$($,J,G){let O=$;if($ instanceof Error&&typeof O.status==="number"&&Number.isInteger(O.status)&&O.status>=400&&O.status<600){let Z={error:$.message};if(O.details!==void 0)Z.details=O.details;return{status:O.status,body:Z}}if(kJ($))return{status:409,body:{error:`${J} already exists`}};return{status:500,body:{error:`Failed to ${G} ${J}`,detail:String($)}}}function I($){return $.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function N$($){let J={};for(let[G,O]of Object.entries($))J[I(G)]=O;return J}function q$($,J){let G=String(J||"").replace(/^\/+|\/+$/g,""),O=String($).replace(/^\/+/,"");return`/api/${G?`${G}/`:""}${O}`}function w$($){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((G)=>G==="Team")?"team_id":null}function v$($,J,G){let O=Object.keys($).find((z)=>I(z)===I(J));if(Array.isArray(G)){if(O===void 0)return{data:$,error:"Ownership value is required"};if(!G.some((z)=>String(z)===String($[O])))return{data:$,error:"Ownership value is not available to this caller"};return{data:{...$,[J]:$[O]}}}if(G===null||G===void 0)return{data:$,error:"Caller has no ownership identity"};let Z={...$};for(let z of Object.keys(Z))if(I(z)===I(J))delete Z[z];return Z[J]=G,{data:Z}}function c$($){if(!$)return[];let J=Object.entries($.attributes??{}).filter(([,G])=>G?.fillable===!0).map(([G])=>G);for(let G of $.belongsTo??[]){if(typeof G!=="string"||!G.trim())continue;let O=I(G.trim()).split("_").filter(Boolean);if(O.length===0)continue;let Z=`${O[0]}${O.slice(1).map((z)=>`${z[0]?.toUpperCase()}${z.slice(1)}`).join("")}Id`;J.push(Z)}return[...new Set(J)]}function j$($,J){if(!$||J.length===0)return{};let G={};for(let O of J){if(O in $){G[O]=$[O];continue}let Z=I(O);if(Z!==O&&Z in $)G[O]=$[Z]}return G}function PJ($,J){if($?.name!=="date"||J instanceof Date||typeof J!=="string")return J;let G=/^(\d{4})-(\d{2})-(\d{2})$/.exec(J);if(!G)return J;let O=Number(G[1]),Z=Number(G[2]),z=Number(G[3]),Q=new Date(Date.UTC(O,Z-1,z));if(Q.getUTCFullYear()!==O||Q.getUTCMonth()!==Z-1||Q.getUTCDate()!==z)return J;return Q}function H$($,J){if(!J.length)return $;let G={...$};for(let O of J)delete G[O],delete G[I(O)];return G}function r($,J){if(!$||J.length===0)return $;let G={...$};for(let O of J)delete G[O],delete G[I(O)];return G}function h$($,J){let G=new Map;for(let O of[...Object.keys($??{}),...fJ]){let Z=I(O);if(!/^\w+$/.test(Z))continue;G.set(O,Z),G.set(Z,Z)}for(let O of J)G.delete(O),G.delete(I(O));return G}function p$($,J,G){if(!J)return $;let O=String(J).split(",").map((z)=>z.trim()).filter(Boolean),Z=$;for(let z of O){let Q=z.startsWith("-"),W=Q?z.slice(1):z;if(!/^\w+$/.test(W))continue;let B=G.get(W);if(!B)continue;Z=Z.orderBy(B,Q?"desc":"asc")}return Z}function bJ($){try{return JSON.parse($)}catch{return $}}function yJ($){try{return JSON.parse($)}catch{return[]}}function D$($,J,G){if(!$||typeof $!=="object"||!J||Object.keys(J).length===0)return $;let O={...$};for(let[Z,z]of Object.entries(J)){let Q=typeof z==="string"?gJ[z]:z;if(!Q||typeof Q[G]!=="function")continue;if(Object.prototype.hasOwnProperty.call(O,Z))O[Z]=Q[G](O[Z]);let W=I(Z);if(W!==Z&&Object.prototype.hasOwnProperty.call(O,W))O[W]=Q[G](O[W])}return O}function U$($,J,G){let O=J?.attributes??{},Z={};for(let[z,Q]of Object.entries(O)){let W=Q?.validation?.rule;if(!W||typeof W.validate!=="function")continue;let B=Object.prototype.hasOwnProperty.call($,z);if(!B&&G==="updating")continue;let X=Q!==null&&typeof Q==="object"&&Object.prototype.hasOwnProperty.call(Q,"default"),K=B?$[z]:X?Q.default:void 0,x=PJ(W,K),U=W.validate(x);if(!U?.valid&&Array.isArray(U?.errors)&&U.errors.length>0)Z[z]=U.errors.map((C)=>Q?.validation?.message?.[C?.code]??C?.message??"invalid")}return Object.keys(Z).length===0?{valid:!0}:{valid:!1,errors:Z}}function A$($){return $.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function _$($){if(Array.isArray($))return $.filter((J)=>typeof J==="string"&&J.length>0);return typeof $==="string"&&$?[$]:[]}function m$($){let J=typeof $==="object"&&$!==null&&"middleware"in $,G=$?.middleware;if(!J)return{read:["auth"],write:["auth"],declared:!1};if(G&&typeof G==="object"&&!Array.isArray(G)){let Z=G;return{read:"read"in Z?_$(Z.read):["auth"],write:"write"in Z?_$(Z.write):["auth"],declared:!0}}let O=_$(G);return{read:O,write:O,declared:!0}}function i$($){let J=Number.parseInt($.get("page")||String(1),10),G=Number.isFinite(J)?Math.max(1,J):1,O=Number.parseInt($.get("per_page")||String(y$),10),Z=Math.min(Number.isFinite(O)?Math.max(1,O):y$,qJ);return{page:G,perPage:Z,offset:(G-1)*Z}}function W$($,J){let G=new URL($.toString());return G.searchParams.set("page",String(J)),`${G.pathname}${G.search}`}function K$($,J,G,O,Z,z){let Q=(J-1)*G,W=O===0,B={page:J,per_page:G,from:W?null:Q+1,to:W?null:Q+O,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/G));B.total=z,B.last_page=X,B.first_page_url=W$($,1),B.last_page_url=W$($,X)}return B}function E$($,J,G,O,Z,z){let{page:Q,...W}=K$($,J,G,O,Z,z);return{current_page:Q,...W}}var fJ,gJ,y$=15,qJ=100;var n$=t(()=>{fJ=["id","uuid","created_at","updated_at","deleted_at"];gJ={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"?bJ($):$,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 d$={};Q$(d$,{modelFiles:()=>o$,loadModelRegistry:()=>S$});import{readdirSync as wJ}from"fs";import{basename as vJ,extname as l$,join as cJ}from"path";function o$($){let J=[],G=(O)=>{let Z;try{Z=wJ(O,{withFileTypes:!0})}catch{return}for(let z of Z){let Q=cJ(O,z.name);if(z.isDirectory()){G(Q);continue}if(![".ts",".js"].includes(l$(z.name)))continue;if(z.name.startsWith(".")||z.name.startsWith("index"))continue;J.push(Q)}};return G($),J.sort()}async function u$($,J,G){for(let O of o$($))try{let Z=l$(O),z=await import(`${O}?t=${Date.now()}`),Q=z.default??z,W=Q.name??vJ(O,Z);J[W]={...Q,name:W}}catch(Z){G?.(O,Z)}}async function S$($){let J={};return await u$($.defaultsRoot,J,$.onImportError),await u$($.userRoot,J,$.onImportError),J}var F$=()=>{};import{route as i}from"@stacksjs/router";import{env as o}from"@stacksjs/env";import{projectPath as GJ,storagePath as hJ}from"@stacksjs/path";import{createQueryBuilder as pJ,defaultConfig as s$,setConfig as t$}from"@stacksjs/query-builder";import{HttpError as u}from"@stacksjs/error-handling";import{log as B$}from"@stacksjs/logging";function d($,J){let G=A$(J);return i.routes.some((O)=>O.method===$&&A$(String(O.path??""))===G)}function OJ($){if(!$.attributes)return[];return Object.entries($.attributes).filter(([J,G])=>G.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,G,O){if(!$.length)return $;let Z=G.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:[],W=Array.isArray(J.hasOne)?J.hasOne:[],B=new Map;for(let X of z)B.set(I(X),{kind:"belongsTo",modelName:X});for(let X of W)B.set(I(X),{kind:"hasOne",modelName:X});for(let X of Q)B.set(r$(I(X)),{kind:"hasMany",modelName:X});for(let X of Z){let K=B.get(X);if(!K)continue;let x=O[K.modelName];if(!x)continue;let U=x.table||r$(I(K.modelName)),C=OJ(x),E=(k)=>r(O$(k,x),C);if(K.kind==="belongsTo"||K.kind==="hasOne"){let k=`${I(K.modelName)}_id`,V=[...new Set($.map((M)=>M[k]).filter((M)=>M!=null))];if(!V.length){for(let M of $)M[X]=null;continue}let q=await b.selectFrom(U).whereIn("id",V).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??""),V=`${I(k)}_id`,q=[...new Set($.map((T)=>T.id).filter((T)=>T!=null))];if(!q.length){for(let T of $)T[X]=[];continue}let P=await b.selectFrom(U).whereIn(V,q).get(),M=new Map;for(let T of P??[]){let L=String(T[V]),Y=M.get(L)??[];Y.push(E(T)),M.set(L,Y)}for(let T of $)T[X]=M.get(String(T.id))??[]}}return $}async function e$($,J){let G=J?.set;if(!G||typeof G!=="object")return $;let O={...$};for(let[Z,z]of Object.entries(G)){if(typeof z!=="function"||!(Z in O))continue;try{O[Z]=await z(O)}catch{}}return O}function $J($,J){return D$($,J?.casts,"set")}function O$($,J){return D$($,J?.casts,"get")}function N($,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 G=await $.clone().text();if(G.length>X$)throw new u(413,`Request body exceeds ${X$}-byte limit`);if(!G)return{};let O=JSON.parse(G);return O&&typeof O==="object"&&!Array.isArray(O)?O:{}}catch(G){if(G instanceof u)throw G;throw new u(400,`Invalid JSON body: ${G.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 G=Number(J);return Number.isFinite(G)&&G>0?G:null}return J}return null}function ZJ($){let J=$.bearerToken;if(typeof J==="function"){let O=J.call($);if(O)return O}let G=$.headers?.get?.("authorization")||$.headers?.get?.("Authorization")||"";if(typeof G==="string"&&G.startsWith("Bearer "))return G.substring(7);return null}async function a($){let J=$._authenticatedUser;if(J)return J;let G=ZJ($);if(!G)return null;try{let{Auth:O}=await import("@stacksjs/auth"),Z=await O.getUserFromToken(G);if(Z)$._authenticatedUser=Z;return Z||null}catch{return null}}function G$($,J){if($==null||J==null)return!1;if(Array.isArray(J))return J.some((G)=>String(G)===String($));return String($)===String(J)}function iJ($){let J=ZJ($),G=$.headers?.get?.("cookie")||"";return{bearerToken:()=>J,cookies:{get:(O)=>{for(let Z of G.split(";")){let z=Z.indexOf("=");if(z===-1)continue;if(Z.slice(0,z).trim()===O)return decodeURIComponent(Z.slice(z+1).trim())}return null}}}}function zJ($){if($?.ownership)return $.ownership;let J=w$($);if(!J)return null;return{field:J,resolve:async(G,O)=>{let{resolveAuthenticatedTeamId:Z}=await import("@stacksjs/auth");return Z(iJ(O))}}}async function e($,J,G){let O=zJ($);if(!O||!O.field||typeof O.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let Z=typeof O.bypass==="function"?!!O.bypass(J,G):!1,z=null;try{z=await O.resolve(J,G)}catch{z=null}return{enforced:!0,value:z,field:String(O.field),bypass:Z}}async function JJ($,J,G,O){let Z=$?.authedFill?.[J];if(!Z)return{};if(typeof Z==="function")try{let z=await Z(G,O);return z&&typeof z==="object"?z:{}}catch{return{}}if(typeof Z==="object"){let z={};for(let[Q,W]of Object.entries(Z))try{z[Q]=typeof W==="function"?await W(G,O):W}catch{}return z}return{}}var mJ,I$,b,X$=1048576,QJ;var LJ=t(async()=>{n$();F$();mJ=GJ("config/qb.ts");try{let $=(await import(mJ)).default;t$($??s$)}catch{B$.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let $=o.DB_CONNECTION||"sqlite";t$({...s$,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||""}})}I$=await S$({defaultsRoot:hJ("framework/defaults/app/Models"),userRoot:GJ("app/Models"),onImportError:($,J)=>B$.warn(`[orm] Could not load model ${$}: ${J.message}`)}),b=pJ();for(let[$,J]of Object.entries(I$)){let G=J.traits?.useApi;if(!G)continue;let O=typeof G==="object"?G:{},Z=O.uri||J.table||$.toLowerCase()+"s",z=O.routes||["index","show","store","update","destroy"],Q=J.table||Z,W=c$(J),B=OJ(J),X=q$(Z,O.prefix),K=h$(J.attributes,B),{read:x,write:U,declared:C}=m$(G);if(["store","update","destroy"].some((T)=>z.includes(T))&&C&&U.length===0)B$.warn(`[orm] ${$}: registering UNAUTHENTICATED mutating routes at ${X} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((T)=>z.includes(T))&&C&&x.length===0)B$.debug(`[orm] ${$}: registering public read routes at ${X} (declared \`middleware.read: []\`)`);let V=!!zJ(J),q=V&&!x.includes("auth")?["auth",...x]:x,P=(T,L=q)=>{let Y=T;for(let _ of L)if(Y&&typeof Y.middleware==="function")Y=Y.middleware(_);return Y};if(z.includes("index")&&!d("GET",X))P(i.get(X,async(T)=>{try{let L=new URL(T.url),{page:Y,perPage:_,offset:H}=i$(L.searchParams),j=L.searchParams.get("sort"),D=b.selectFrom(Q);D=p$(D,j,K);let w=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[f,g]of L.searchParams.entries()){if(w.has(f)||!g)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(f))continue;let l=K.get(f);if(l)D=D.where(l,"=",g)}let F=L.searchParams.get("search");if(F&&W.length>0){let f=W.slice(0,5);D=D.where((g)=>{for(let l of f)g=g.orWhere(I(l),"like",`%${F}%`);return g})}let R=L.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)=>I(g));if(f.length>0)D=D.select(f)}let y=!!J.traits?.useSoftDeletes,S=L.searchParams.get("withTrashed")==="true",h=L.searchParams.get("onlyTrashed")==="true";if(y&&!S)D=h?D.whereNotNull("deleted_at"):D.whereNull("deleted_at");let A=V?await e(J,await a(T),T):{enforced:!1,value:null,field:"",bypass:!1};if(A.enforced&&!A.bypass){if(A.value==null||Array.isArray(A.value)&&A.value.length===0){let f=E$(L,Y,_,0,!1,void 0);return new Response(JSON.stringify({data:[],...f,meta:K$(L,Y,_,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}D=Array.isArray(A.value)?D.where(A.field,"in",A.value):D.where(A.field,"=",A.value)}let p=await D.limit(_+1).offset(H).get()||[],m=p.length>_,J$=(m?p.slice(0,_):p).map((f)=>r(O$(f,J),B)),C$=L.searchParams.get("include");if(C$)J$=await a$(J$,J,C$,I$);let TJ=L.searchParams.get("with_count")==="true",s;if(TJ)try{let f=b.selectFrom(Q);if(A.enforced&&!A.bypass&&A.value!=null)f=Array.isArray(A.value)?f.where(A.field,"in",A.value):f.where(A.field,"=",A.value);let g=await f.count(),l=typeof g==="number"?g:Number(g?.count??g);if(Number.isFinite(l))s=l}catch{}let z$={"Content-Type":"application/json"};if(s!==void 0&&!Number.isNaN(s))z$["X-Total-Count"]=String(s);z$["Cache-Control"]=A.enforced&&!A.bypass?"private, no-store":"public, max-age=15, must-revalidate",z$.Vary="Authorization";let NJ=E$(L,Y,_,J$.length,m,s);return new Response(JSON.stringify({data:J$,...NJ,meta:K$(L,Y,_,J$.length,m,s)}),{status:200,headers:z$})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return N(Y,L.status||400)}return N({error:`Failed to fetch ${Z}`,detail:String(L)},500)}}));if(z.includes("show")&&!d("GET",`${X}/{id}`))P(i.get(`${X}/{id}`,async(T)=>{try{let L=Y$(T.params?.id);if(L==null)return N({error:"Invalid ID parameter"},400);let Y=await b.selectFrom(Q).where({id:L}).executeTakeFirst();if(!Y)return N({error:`${$} not found`},404);let _=new URL(T.url);if(J.traits?.useSoftDeletes&&Y.deleted_at&&_.searchParams.get("withTrashed")!=="true")return N({error:`${$} not found`},404);let H=V?await e(J,await a(T),T):{enforced:!1,value:null,field:"",bypass:!1};if(H.enforced&&!H.bypass){if(H.value==null||!G$(Y[H.field],H.value))return N({error:`${$} not found`},404)}let j=r(O$(Y,J),B),D=_.searchParams.get("include");if(D){let[S]=await a$([j],J,D,I$);j=S}let w=j?.updated_at||j?.created_at,F=w?`W/"${j.id}-${String(w)}"`:void 0,R=T.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"]=H.enforced&&!H.bypass?"private, no-store":"public, max-age=30, must-revalidate",y.Vary="Authorization",new Response(JSON.stringify({data:j}),{status:200,headers:y})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return N(Y,L.status||400)}return N({error:`Failed to fetch ${$}`,detail:String(L)},500)}}));if(z.includes("store")&&!d("POST",X))P(i.post(X,async(T)=>{try{let L=await V$(T),Y=H$(L,B),_=j$(Y,W),H=await a(T);if(H){let S=await JJ(J,"creating",H,T);for(let[h,A]of Object.entries(S))if(A!==void 0&&A!==null&&_[h]===void 0)_[h]=A}let j=await e(J,H,T);if(j.enforced&&!j.bypass){if(!H)return N({error:"Auth required"},401);let S=v$(_,j.field,j.value);if(S.error)return N({error:S.error},403);_=S.data}if(Object.keys(_).length===0)return N({error:"No fillable fields provided"},422);let D=U$(_,J,"creating");if(!D.valid)return N({success:!1,message:"Validation failed",errors:D.errors},422);if(J.traits?.useTimestamps!==!1){let S=new Date().toISOString();_.created_at=S,_.updated_at=S}let w=await e$(_,J),F=N$($J(w,J)),R=await b.insertInto(Q).values(F).execute(),y=F;try{let S=R?.lastInsertRowid??R?.insertId??R;if(S){let h=await b.selectFrom(Q).where({id:S}).executeTakeFirst();if(h)y=h}}catch{}return N({data:r(O$(y,J),B)},201)}catch(L){let{status:Y,body:_}=T$(L,$,"create");return N(_,Y)}}),U);if(z.includes("update")){let T=async(L)=>{try{let Y=Y$(L.params?.id);if(Y==null)return N({error:"Invalid ID parameter"},400);let _=await V$(L),H=H$(_,B),j=j$(H,W),D=await a(L);if(D){let A=await JJ(J,"updating",D,L);for(let[p,m]of Object.entries(A))if(m!==void 0&&m!==null&&j[p]===void 0)j[p]=m}if(Object.keys(j).length===0)return N({error:"No fillable fields provided"},422);let w=U$(j,J,"updating");if(!w.valid)return N({success:!1,message:"Validation failed",errors:w.errors},422);let F=await b.selectFrom(Q).where({id:Y}).executeTakeFirst();if(!F)return N({error:`${$} not found`},404);let R=await e(J,D,L);if(R.enforced&&!R.bypass){if(!D)return N({error:"Auth required"},401);let A=F[R.field];if(!G$(A,R.value))return N({error:`Not your ${$}`},403);let p=Object.keys(j).find((m)=>I(m)===I(R.field));if(p!==void 0&&!G$(j[p],R.value))return N({error:`Cannot reassign ${$} ownership`},403)}if(J.traits?.useTimestamps!==!1)j.updated_at=new Date().toISOString();let y=await e$(j,J),S=N$($J(y,J));await b.updateTable(Q).set(S).where({id:Y}).execute();let h={...F,...S};try{let A=await b.selectFrom(Q).where({id:Y}).executeTakeFirst();if(A)h=A}catch{}return N({data:r(O$(h,J),B)})}catch(Y){let{status:_,body:H}=T$(Y,$,"update");return N(H,_)}};if(!d("PUT",`${X}/{id}`))P(i.put(`${X}/{id}`,T),U);if(!d("PATCH",`${X}/{id}`))P(i.patch(`${X}/{id}`,T),U)}let M=!!J.traits?.useSoftDeletes;if(z.includes("destroy")&&!d("DELETE",`${X}/{id}`))P(i.delete(`${X}/{id}`,async(T)=>{try{let L=Y$(T.params?.id);if(L==null)return N({error:"Invalid ID parameter"},400);let Y=await b.selectFrom(Q).where({id:L}).executeTakeFirst();if(!Y)return N({error:`${$} not found`},404);let _=await a(T),H=await e(J,_,T);if(H.enforced&&!H.bypass){if(!_)return N({error:"Auth required"},401);let j=Y[H.field];if(!G$(j,H.value))return N({error:`Not your ${$}`},403)}if(M){let j=new Date().toISOString();await b.updateTable(Q).set({deleted_at:j,updated_at:j}).where({id:L}).execute()}else await b.deleteFrom(Q).where({id:L}).execute();return new Response(null,{status:204})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return N(Y,L.status||400)}return N({error:`Failed to delete ${$}`,detail:String(L)},500)}}),U);if(z.includes("destroy")&&!d("POST",`${X}/bulk-delete`))P(i.post(`${X}/bulk-delete`,async(T)=>{try{let Y=(await V$(T))?.ids;if(!Array.isArray(Y)||Y.length===0)return N({error:"An array of IDs is required"},422);if(Y.length>100)return N({error:"Cannot delete more than 100 records at once"},422);let _=[],H=[];for(let F of Y){let R=Y$(F);if(R!=null)_.push(R);else H.push(F)}if(H.length>0)return N({error:"Invalid IDs in batch",invalid:H},422);let j=await a(T),D=await e(J,j,T);if(D.enforced&&!D.bypass){if(!j)return N({error:"Auth required"},401);if(D.value==null)return N({error:"Caller has no ownership identity"},403);let F=await b.selectFrom(Q).select(["id",D.field]).execute(),R=new Set(F.filter((S)=>G$(S[D.field],D.value)).map((S)=>String(S.id))),y=_.filter((S)=>!R.has(String(S)));if(y.length>0)return N({error:`Cannot delete ${$} you don't own`,ids:y},403)}let w=new Date().toISOString();for(let F of _)if(M)await b.updateTable(Q).set({deleted_at:w,updated_at:w}).where({id:F}).execute();else await b.deleteFrom(Q).where({id:F}).execute();return N({message:`Successfully deleted ${_.length} ${Z}`})}catch(L){if(L instanceof u){let Y={error:L.message};if(L.details!==void 0)Y.details=L.details;return N(Y,L.status||400)}return N({error:`Failed to bulk delete ${Z}`,detail:String(L)},500)}}),U)}QJ=i});var WJ={};Q$(WJ,{default:()=>QJ});var KJ=t(async()=>{await LJ()});class R${data;status;headers;isOk;constructor($,J,G,O){this.data=$;this.status=J;this.headers=G;this.isOk=O}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 G=btoa(`${$}:${J}`);return this.customHeaders.Authorization=`Basic ${G}`,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,G,O){let Z=typeof J==="string"?new Blob([J],{type:O?.["Content-Type"]||"text/plain"}):J;return this.attachments.push({name:$,content:Z,filename:G,headers:O}),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 G=J.toString();if(!G)return $;let O=$.includes("?");return $+(O?"&":"?")+G}async formatBody($){let J=$||this.bodyData;if(this.isMultipart){let G=new FormData;if(J)Object.entries(J).forEach(([O,Z])=>{G.append(O,String(Z))});for(let O of this.attachments)if(O.headers){let Z=O.content instanceof Blob?new Blob([O.content],{type:O.headers["Content-Type"]}):O.content;G.append(O.name,Z,O.filename)}else G.append(O.name,O.content,O.filename);return G}if(this.isFormData&&J){let G=new URLSearchParams;return Object.entries(J).forEach(([O,Z])=>{if(Z!=null)G.append(O,String(Z))}),G.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,G,O){if($.status!==401||!this.digestAuth)return $;let Z=$.headers.get("WWW-Authenticate");if(!Z?.startsWith("Digest "))return $;let z=Z.substring(7).split(",").reduce((C,E)=>{let[k,V]=E.trim().split("=");if(k)C[k]=V?.replace(/["']/g,"")??"";return C},{}),Q=await this.generateMD5(`${this.digestAuth.username}:${z.realm}:${this.digestAuth.password}`),W=await this.generateMD5(`${G}:${J}`),B="00000001",X=await this.generateMD5(Date.now().toString()).then((C)=>C.substring(0,8)),K=await this.generateMD5(`${Q}:${z.nonce}:${B}:${X}:${z.qop}:${W}`),x={username:`"${this.digestAuth.username}"`,realm:`"${z.realm}"`,nonce:`"${z.nonce}"`,uri:`"${J}"`,algorithm:z.algorithm?`"${z.algorithm}"`:void 0,qop:`"${z.qop}"`,nc:B,cnonce:`"${X}"`,response:`"${K}"`,opaque:z.opaque?`"${z.opaque}"`:void 0},U=Object.entries(x).filter(([C,E])=>E!==void 0).map(([C,E])=>`${C}=${E}`).join(", ");return this.customHeaders.Authorization=`Digest ${U}`,fetch(J,{method:G,headers:this.getHeaders(),body:O?this.formatBody(O):void 0})}async generateMD5($){let G=new TextEncoder().encode($),O=await crypto.subtle.digest("SHA-256",G);return Array.from(new Uint8Array(O)).map((z)=>z.toString(16).padStart(2,"0")).join("")}async request($,J,G){let O=this.addQueryParams($),Z=await this.formatBody(G),z=await fetch(O,{method:J,headers:this.getHeaders(),body:Z});if(this.digestAuth)z=await this.handleDigestAuth(z,O,J,G);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$;x$();import{path as $$}from"@stacksjs/path";function YJ($){if(!$||typeof $!=="object")return{type:"string"};let J=$,G=Array.isArray(J.rules)?J.rules:[],O=(K)=>G.find((x)=>x.name===K),Z=(K,x)=>{let U=O(K)?.params?.[x];return typeof U==="number"?U:void 0},z=J.name??J._type??"string",Q={type:z==="enum"?"string":z},W=Z("min","min")??(typeof J._min==="number"?J._min:void 0),B=Z("max","max")??(typeof J._max==="number"?J._max:void 0);if(W!==void 0)Q[z==="string"?"minLength":"minimum"]=W;if(B!==void 0)Q[z==="string"?"maxLength":"maximum"]=B;if(O("email")||J._email)Q.format="email";if(O("url")||J._url)Q.format="uri";if(O("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"}},G=["id"];if($.traits?.useUuid)J.uuid={type:"string",format:"uuid"},G.push("uuid");for(let[O,Z]of Object.entries($.attributes??{})){if(Z.hidden===!0)continue;let z=XJ(O);if(J[z]=YJ(Z.validation?.rule),Z.required===!0)G.push(z)}for(let O of $.belongsTo??[]){if(typeof O!=="string"||!O.trim())continue;let Z=`${XJ(O.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(G)]}}function lJ($){let J=$.traits?.useApi;if(!J||typeof J!=="object"||!J.uri)return null;let G=String(J.prefix||"").replace(/^\/+|\/+$/g,""),O=String(J.uri).replace(/^\/+|\/+$/g,"");return`/api/${G?`${G}/`:""}${O}`}function oJ($,J){let G={...J},O=$?.responses;if(O&&typeof O==="object")for(let[z,Q]of Object.entries(O)){let W=Q;if(!W||typeof W!=="object"||typeof W.description!=="string")continue;G[String(z)]={description:W.description,...W.schema&&typeof W.schema==="object"?{content:{"application/json":{schema:W.schema}}}:{}}}let Z=$?.responseHeaders;if(Z&&typeof Z==="object"){let z={};for(let[Q,W]of Object.entries(Z)){let B=W;if(!B||typeof B!=="object"||typeof B.description!=="string")continue;z[Q]={description:B.description,...B.schema&&typeof B.schema==="object"?{schema:B.schema}:{}}}if(Object.keys(z).length>0)for(let Q of Object.keys(G))G[Q]={...G[Q],headers:z}}return G}async function dJ($){if(typeof $!=="string"||!$||$.includes(".."))return null;try{let{path:J}=await import("@stacksjs/path"),G=[J.appPath(`${$}.ts`),J.storagePath(`framework/defaults/app/${$}.ts`)];for(let O of G)try{if(!await Bun.file(O).exists())continue;let Q=(await import(O)).default;return Q&&typeof Q==="object"?Q:null}catch{}}catch{}return null}async function T8($={}){let J=$.portable??!0,{listRegisteredRoutes:G}=await import("@stacksjs/router");try{let{loadRoutes:K}=await import("@stacksjs/router"),{default:x}=await import($$.appPath("Routes.ts"));await K(x)}catch(K){let x=K instanceof Error?K.message:String(K);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${x}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${x}`)}try{try{await import("@stacksjs/orm/routes")}catch{await KJ().then(() => WJ)}}catch(K){let x=K instanceof Error?K.message:String(K);if(J)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${x}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${x}`)}let O={};try{let x;try{x=await import("@stacksjs/orm/model-registry")}catch{x=await Promise.resolve().then(() => (F$(),d$))}O=await x.loadModelRegistry({defaultsRoot:$$.storagePath("framework/defaults/app/Models"),userRoot:$$.projectPath("app/Models")})}catch(K){let x=K instanceof Error?K.message:String(K);if(J)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${x}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${x}`)}let Z=(K)=>K.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),z=[...G()].map((K)=>({route:K,oasPath:Z(K.path),method:K.method.toLowerCase()})).sort((K,x)=>{if(K.oasPath!==x.oasPath)return K.oasPath<x.oasPath?-1:1;return K.method<x.method?-1:K.method>x.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:K}=await import("@stacksjs/config");if(K.app?.name)Q=`${K.app.name} API`}catch{}let W={openapi:"3.0.0",info:{title:Q,version:"1.0.0"},paths:{},components:{schemas:{}}},B=Object.values(O).map((K)=>({name:String(K.name),path:lJ(K),schema:uJ(K)})).filter((K)=>K.path!==null).sort((K,x)=>K.name<x.name?-1:K.name>x.name?1:0);for(let K of B)W.components.schemas[K.name]=K.schema;let X=new Set;for(let{route:K,oasPath:x,method:U}of z){if(!W.paths[x])W.paths[x]={};let C=[];for(let L of K.path.matchAll(/\{(\w+)\}/g))if(L[1])C.push(L[1]);for(let L of K.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(L[1])C.push(L[1]);let E=K.name??`${U}_${x.replace(/[^a-z0-9]/gi,"_")}`,k=E;if(X.has(k)){k=`${E}_${U}`;let L=2;while(X.has(k))k=`${E}_${U}_${L++}`}X.add(k);let V={summary:K.name??K.path,operationId:k,parameters:C.map((L)=>({name:L,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=B.find((L)=>x===L.path||x===`${L.path}/{id}`);if(q){let L=x===q.path&&U==="get"?{type:"array",items:q.schema}:q.schema;if(V.responses[200].content={"application/json":{schema:{type:"object",properties:{data:L},required:["data"]}}},U==="post"&&x===q.path)V.responses[201]={...V.responses[200],description:"Created"},delete V.responses[200]}let P=K.action??(K.handler?await dJ(K.handler):null),M=P&&typeof P.validations==="object"&&P.validations!==null?P.validations:null;V.responses=oJ(P,V.responses);let T=P?.requestHeaders;if(T&&typeof T==="object")for(let[L,Y]of Object.entries(T)){let _=Y;if(!_||typeof _!=="object"||typeof _.description!=="string")continue;V.parameters?.push({name:L,in:"header",description:_.description,required:_.required===!0,schema:_.schema&&typeof _.schema==="object"?_.schema:{type:"string"}})}if(M&&Object.keys(M).length>0){let L=Object.entries(M).map(([Y,_])=>{let H=_?.rule;return{field:Y,schema:YJ(H),required:nJ(H)}});if(U==="get"||U==="head"||U==="delete"){let Y=new Set(C);for(let{field:_,schema:H,required:j}of L){if(Y.has(_))continue;V.parameters?.push({name:_,in:"query",required:j,schema:H})}}else{let Y={type:"object",properties:{},required:[]},_=Y.properties,H=Y.required;for(let j of L)if(_[j.field]=j.schema,j.required)H.push(j.field);if(H.length===0)delete Y.required;V.requestBody={required:H.length>0,content:{"application/json":{schema:Y}}}}}W.paths[x][U]=V}if($.write!==!1){await Bun.write($$.frameworkPath("api/openapi.json"),JSON.stringify(W,null,2));let{renderOpenApiTypes:K}=await Promise.resolve().then(() => (L$(),f$)),{renderApiClient:x}=await Promise.resolve().then(() => (x$(),b$));await Bun.write($$.frameworkPath("api/api-types.ts"),K(W)),await Bun.write($$.frameworkPath("api/client.ts"),x(W,{name:W.info.title}))}return W}L$();class c{static instance=new c;isMissing(){return!0}}class Z${data;constructor($){this.data=$}}class BJ{condition;value;defaultValue;constructor($,J,G=new c){this.condition=$;this.value=J;this.defaultValue=G}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class xJ{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($),G=this.constructor.wrap;if(G)return{[G]: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,G){if(typeof $==="function"?$():$)return typeof J==="function"?J():J;return G!==void 0?G:c.instance}whenNotNull($,J){if($===null||$===void 0)return c.instance;return J?J($):$}whenLoaded($,J,G){let O=this.resource;if(!(($ in O)&&O[$]!==void 0))return G!==void 0?G:c.instance;if(J!==void 0)return typeof J==="function"?J():J;return O[$]}whenCounted($,J){let G=this.resource,O=`${$}_count`;if(O in G)return G[O];return J!==void 0?J:c.instance}merge($){return new Z$($)}mergeWhen($,J){if(!(typeof $==="function"?$():$))return c.instance;let O=typeof J==="function"?J():J;return new Z$(O)}static MAX_RESOLVE_DEPTH=20;filterAndResolve($,J=0){if(J>=xJ.MAX_RESOLVE_DEPTH)return $;let G={};for(let[O,Z]of Object.entries($)){if(Z instanceof c)continue;if(Z instanceof Z$){Object.assign(G,this.filterAndResolve(Z.data,J+1));continue}if(Z instanceof BJ){let z=Z.resolve();if(!(z instanceof c))G[O]=z;continue}if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)&&!(Z instanceof Date)){G[O]=this.filterAndResolve(Z,J+1);continue}if(Array.isArray(Z)){G[O]=Z.filter((z)=>!(z instanceof c)).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}G[O]=Z}return G}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((G)=>{let O=new this.ResourceClass(G);if(J)O.withRequest(J);return O.resolve(J)})}toResponse($){let J=this.resolve($),G=this.constructor.wrap;if(G)return{[G]: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 _J extends M${meta;links;constructor($,J){super($.data,J);this.meta=$.meta,this.links=$.links}static fromPagination($,J,G){let{currentPage:O,perPage:Z,total:z,baseUrl:Q=""}=G,W=Math.ceil(z/Z),B=z>0?(O-1)*Z+1:null,X=z>0?Math.min(O*Z,z):null;return new _J({data:$,meta:{current_page:O,from:B,last_page:W,per_page:Z,to:X,total:z},links:{first:`${Q}?page=1`,last:`${Q}?page=${W}`,prev:O>1?`${Q}?page=${O-1}`:null,next:O<W?`${Q}?page=${O+1}`:null}},J)}toResponse($){return{data:this.resolve($),meta:this.meta,links:this.links,...this.additional}}}function j8($,J){let G=J($);return{toResponse:()=>({data:G}),toJson:()=>JSON.stringify({data:G})}}function H8($,J){let G=$.map(J);return{toResponse:()=>({data:G}),toJson:()=>JSON.stringify({data:G})}}export{v as schemaType,YJ as ruleToSchema,nJ as ruleIsRequired,j8 as resource,FJ as renderOpenApiTypes,RJ as renderApiClient,uJ as modelDefinitionToSchema,g$ as methodName,T8 as generateOpenApi,rJ as fetcher,oJ as describedResponses,H8 as collection,M$ as ResourceCollection,_J as PaginatedResourceCollection,c as MissingValue,Z$ as MergeValue,xJ as JsonResource,BJ 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.72.
|
|
5
|
+
"version": "0.72.57",
|
|
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.24",
|
|
65
|
-
"@stacksjs/utils": "0.72.
|
|
65
|
+
"@stacksjs/utils": "0.72.57"
|
|
66
66
|
}
|
|
67
67
|
}
|