@stacksjs/api 0.70.228 → 0.70.230
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/generate-openapi.d.ts +17 -1
- package/dist/index.js +9 -9
- package/package.json +9 -8
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { path } from '@stacksjs/path';
|
|
1
2
|
import type { SchemaObject } from './generate-types';
|
|
2
3
|
/**
|
|
3
4
|
* Build an OpenAPI 3.0 spec from the live route registry.
|
|
@@ -14,7 +15,22 @@ import type { SchemaObject } from './generate-types';
|
|
|
14
15
|
* but omits a request body schema — that's still useful for clients
|
|
15
16
|
* that just want to know what endpoints exist.
|
|
16
17
|
*/
|
|
17
|
-
export declare function generateOpenApi(options?: {
|
|
18
|
+
export declare function generateOpenApi(options?: {
|
|
19
|
+
write?: boolean
|
|
20
|
+
/**
|
|
21
|
+
* Produce the canonical, machine-independent document.
|
|
22
|
+
*
|
|
23
|
+
* The committed `storage/framework/api/openapi.json` is compared byte for
|
|
24
|
+
* byte against a fresh generation, so anything that varies by machine or by
|
|
25
|
+
* run makes the check either fail for everyone or pass for nobody. Portable
|
|
26
|
+
* mode pins those inputs and refuses to emit a document it cannot vouch for.
|
|
27
|
+
*
|
|
28
|
+
* Defaults to true, because every path that produces or verifies the shared
|
|
29
|
+
* artifact must agree. Only the live `GET /__openapi.json` route wants the
|
|
30
|
+
* app-flavoured variant, and it opts out explicitly.
|
|
31
|
+
*/
|
|
32
|
+
portable?: boolean
|
|
33
|
+
}): Promise<OpenApiSpec>;
|
|
18
34
|
declare interface OpenApiPathItem {
|
|
19
35
|
[method: string]: {
|
|
20
36
|
summary?: string
|
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var e$=Object.defineProperty;var $O=($)=>$;function OO($,O){this[$]=$O.bind(null,O)}var H$=($,O)=>{for(var J in O)e$($,J,{get:O[J],enumerable:!0,configurable:!0,set:OO.bind(O,J)})};var G$=($,O)=>()=>($&&(O=$($=0)),O);var m=import.meta.require;var D$;var W$=G$(()=>{D$={api:"api",v1:{path:"v1",prefix:"v1"}}});var E$={};H$(E$,{default:()=>D$});var I$=G$(()=>{W$();W$()});function JO($){let O=$;return O?.code==="SQLITE_CONSTRAINT_UNIQUE"||O?.code==="SQLITE_CONSTRAINT"||O?.code==="23505"||O?.errno===1062||/unique|duplicate/i.test(O?.message??"")}function X$($,O,J){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(JO($))return{status:409,body:{error:`${O} already exists`}};return{status:500,body:{error:`Failed to ${J} ${O}`,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 Y$($){let O={};for(let[J,G]of Object.entries($))O[V(J)]=G;return O}function B$($,O){if(!$||O.length===0)return{};let J={};for(let G of O){if(G in $){J[G]=$[G];continue}let Z=V(G);if(Z!==G&&Z in $)J[G]=$[Z]}return J}function T$($,O){if(!O.length)return $;let J={...$};for(let G of O)delete J[G],delete J[V(G)];return J}function o($,O){if(!$||O.length===0)return $;let J={...$};for(let G of O)delete J[G],delete J[V(G)];return J}function V$($,O){let J=new Map;for(let G of[...Object.keys($??{}),...GO]){let Z=V(G);if(!/^\w+$/.test(Z))continue;J.set(G,Z),J.set(Z,Z)}for(let G of O)J.delete(G),J.delete(V(G));return J}function M$($,O,J){if(!O)return $;let G=String(O).split(",").map((z)=>z.trim()).filter(Boolean),Z=$;for(let z of G){let L=z.startsWith("-"),Q=L?z.slice(1):z;if(!/^\w+$/.test(Q))continue;let B=J.get(Q);if(!B)continue;Z=Z.orderBy(B,L?"desc":"asc")}return Z}function zO($){try{return JSON.parse($)}catch{return $}}function LO($){try{return JSON.parse($)}catch{return[]}}function x$($,O,J){if(!$||typeof $!=="object"||!O||Object.keys(O).length===0)return $;let G={...$};for(let[Z,z]of Object.entries(O)){let L=typeof z==="string"?ZO[z]:z;if(!L||typeof L[J]!=="function")continue;if(Object.prototype.hasOwnProperty.call(G,Z))G[Z]=L[J](G[Z]);let Q=V(Z);if(Q!==Z&&Object.prototype.hasOwnProperty.call(G,Q))G[Q]=L[J](G[Q])}return G}function C$($){let O=typeof $==="object"&&$!==null&&"middleware"in $,J=$?.middleware,G=Array.isArray(J)?J.filter((Z)=>typeof Z==="string"&&Z.length>0):typeof J==="string"&&J?[J]:[];return{read:G,write:O?G:["auth"],declared:O}}function k$($){let O=Number.parseInt($.get("page")||String(1),10),J=Number.isFinite(O)?Math.max(1,O):1,G=Number.parseInt($.get("per_page")||String(F$),10),Z=Math.min(Number.isFinite(G)?Math.max(1,G):F$,KO);return{page:J,perPage:Z,offset:(J-1)*Z}}function Z$($,O){let J=new URL($.toString());return J.searchParams.set("page",String(O)),`${J.pathname}${J.search}`}function z$($,O,J,G,Z,z){let L=(O-1)*J,Q=G===0,B={page:O,per_page:J,from:Q?null:L+1,to:Q?null:L+G,has_more_pages:Z,prev_page_url:O>1?Z$($,O-1):null,next_page_url:Z?Z$($,O+1):null};if(z!==void 0&&!Number.isNaN(z)){let W=Math.max(1,Math.ceil(z/J));B.total=z,B.last_page=W,B.first_page_url=Z$($,1),B.last_page_url=Z$($,W)}return B}function j$($,O,J,G,Z,z){let{page:L,...Q}=z$($,O,J,G,Z,z);return{current_page:L,...Q}}var GO,ZO,F$=15,KO=100;var P$=G$(()=>{GO=["id","uuid","created_at","updated_at","deleted_at"];ZO={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"?zO($):$,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"?LO($):[],set:($)=>$==null?null:Array.isArray($)?JSON.stringify($):$}}});var u$={};H$(u$,{default:()=>TO});import{route as h}from"@stacksjs/router";import{env as u}from"@stacksjs/env";import{projectPath as h$}from"@stacksjs/path";import{createQueryBuilder as QO,defaultConfig as R$,setConfig as f$}from"@stacksjs/query-builder";import{HttpError as i}from"@stacksjs/error-handling";import{log as p$}from"@stacksjs/logging";function l($,O){return h.routes.some((J)=>J.method===$&&J.path===O)}function XO($){if(!$.attributes)return[];return Object.entries($.attributes).filter(([O,J])=>J.fillable===!0).map(([O])=>O)}function m$($){if(!$.attributes)return[];return Object.entries($.attributes).filter(([O,J])=>J.hidden===!0).map(([O])=>O)}function y$($,O,J){let G=$,Z=O,z=J,L=Z?.attributes??{},Q={};for(let[B,W]of Object.entries(L)){let D=W?.validation?.rule;if(!D||typeof D.validate!=="function")continue;let _=Object.prototype.hasOwnProperty.call(G,B);if(!_&&z==="updating")continue;let R=_?G[B]:void 0,S=D.validate(R);if(!S?.valid&&Array.isArray(S?.errors)&&S.errors.length>0)Q[B]=S.errors.map((b)=>W?.validation?.message?.[b?.code]??b?.message??"invalid")}return Object.keys(Q).length===0?{valid:!0}:{valid:!1,errors:Q}}function g$($){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 q$($,O,J,G){if(!$.length)return $;let Z=J.split(",").map((W)=>W.trim()).filter(Boolean);if(!Z.length)return $;let z=Array.isArray(O.belongsTo)?O.belongsTo:[],L=Array.isArray(O.hasMany)?O.hasMany:[],Q=Array.isArray(O.hasOne)?O.hasOne:[],B=new Map;for(let W of z)B.set(V(W),{kind:"belongsTo",modelName:W});for(let W of Q)B.set(V(W),{kind:"hasOne",modelName:W});for(let W of L)B.set(g$(V(W)),{kind:"hasMany",modelName:W});for(let W of Z){let D=B.get(W);if(!D)continue;let _=G[D.modelName];if(!_)continue;let R=_.table||g$(V(D.modelName)),S=m$(_),b=(M)=>o($$(M,_),S);if(D.kind==="belongsTo"||D.kind==="hasOne"){let M=`${V(D.modelName)}_id`,C=[...new Set($.map((Y)=>Y[M]).filter((Y)=>Y!=null))];if(!C.length){for(let Y of $)Y[W]=null;continue}let y=await f.selectFrom(R).whereIn("id",C).get(),q=new Map;for(let Y of y??[])q.set(String(Y.id),b(Y));for(let Y of $)Y[W]=q.get(String(Y[M]))??null}else{let M=String(O.name??""),C=`${V(M)}_id`,y=[...new Set($.map((K)=>K.id).filter((K)=>K!=null))];if(!y.length){for(let K of $)K[W]=[];continue}let q=await f.selectFrom(R).whereIn(C,y).get(),Y=new Map;for(let K of q??[]){let X=String(K[C]),T=Y.get(X)??[];T.push(b(K)),Y.set(X,T)}for(let K of $)K[W]=Y.get(String(K.id))??[]}}return $}async function w$($,O){let J=O?.set;if(!J||typeof J!=="object")return $;let G={...$};for(let[Z,z]of Object.entries(J)){if(typeof z!=="function"||!(Z in G))continue;try{G[Z]=await z(G)}catch{}}return G}function c$($,O){return x$($,O?.casts,"set")}function $$($,O){return x$($,O?.casts,"get")}function x($,O=200){return new Response(JSON.stringify($),{status:O,headers:{"Content-Type":"application/json"}})}async function A$($){if(Number($.headers?.get?.("content-length")??0)>L$)throw new i(413,`Request body exceeds ${L$}-byte limit`);if($.jsonBody&&typeof $.jsonBody==="object")return $.jsonBody;if($.formBody&&typeof $.formBody==="object")return $.formBody;try{let J=await $.clone().text();if(J.length>L$)throw new i(413,`Request body exceeds ${L$}-byte limit`);if(!J)return{};let G=JSON.parse(J);return G&&typeof G==="object"&&!Array.isArray(G)?G:{}}catch(J){if(J instanceof i)throw J;throw new i(400,`Invalid JSON body: ${J.message}`)}}function K$($){if($==null)return null;if(typeof $==="number")return Number.isFinite($)&&$>0?$:null;if(typeof $==="string"){let O=$.trim();if(!O)return null;if(/^\d+$/.test(O)){let J=Number(O);return Number.isFinite(J)&&J>0?J:null}return O}return null}function i$($){let O=$.bearerToken;if(typeof O==="function"){let G=O.call($);if(G)return G}let J=$.headers?.get?.("authorization")||$.headers?.get?.("Authorization")||"";if(typeof J==="string"&&J.startsWith("Bearer "))return J.substring(7);return null}async function d($){let O=$._authenticatedUser;if(O)return O;let J=i$($);if(!J)return null;try{let{Auth:G}=await import("@stacksjs/auth"),Z=await G.getUserFromToken(J);if(Z)$._authenticatedUser=Z;return Z||null}catch{return null}}function a($,O){if($==null||O==null)return!1;if(Array.isArray(O))return O.some((J)=>String(J)===String($));return String($)===String(O)}function YO($){let O=$?.attributes||{},J=(G)=>Object.prototype.hasOwnProperty.call(O,G);return J("teamId")||J("team_id")?"team_id":null}function BO($){let O=i$($),J=$.headers?.get?.("cookie")||"";return{bearerToken:()=>O,cookies:{get:(G)=>{for(let Z of J.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 n$($){if($?.ownership)return $.ownership;let O=YO($);if(!O)return null;return{field:O,resolve:async(J,G)=>{let{resolveAuthenticatedTeamId:Z}=await import("@stacksjs/auth");return Z(BO(G))}}}async function e($,O,J){let G=n$($);if(!G||!G.field||typeof G.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let Z=typeof G.bypass==="function"?!!G.bypass(O,J):!1,z=null;try{z=await G.resolve(O,J)}catch{z=null}return{enforced:!0,value:z,field:String(G.field),bypass:Z}}async function v$($,O,J,G){let Z=$?.authedFill?.[O];if(!Z)return{};if(typeof Z==="function")try{let z=await Z(J,G);return z&&typeof z==="object"?z:{}}catch{return{}}if(typeof Z==="object"){let z={};for(let[L,Q]of Object.entries(Z))try{z[L]=typeof Q==="function"?await Q(J,G):Q}catch{}return z}return{}}var WO,b$,Q$,f,L$=1048576,TO;var l$=G$(async()=>{P$();WO=h$("config/qb.ts");try{let $=(await import(WO)).default;f$($??R$)}catch{p$.debug("[orm] No config/qb.ts override found \u2014 deriving config from DB_CONNECTION");let $=u.DB_CONNECTION||"sqlite";f$({...R$,dialect:$,database:$==="sqlite"?{database:u.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:u.DB_DATABASE||"stacks",host:u.DB_HOST||"127.0.0.1",port:u.DB_PORT||($==="postgres"?5432:3306),username:u.DB_USERNAME||($==="postgres"?"postgres":"root"),password:u.DB_PASSWORD||""}})}b$=h$("app/Models"),Q$={};try{let{readdirSync:$,statSync:O}=await import("fs"),{extname:J,basename:G}=await import("path"),Z=$(b$);for(let z of Z){let L=`${b$}/${z}`;if(O(L).isDirectory())continue;let B=J(L);if(![".ts",".js"].includes(B))continue;try{let W=await import(`${L}?t=${Date.now()}`),D=W.default??W,_=D.name??G(z,B);Q$[_]={...D,name:_}}catch{}}}catch{}f=QO();for(let[$,O]of Object.entries(Q$)){let J=O.traits?.useApi;if(!J)continue;let G=typeof J==="object"?J:{},Z=G.uri||O.table||$.toLowerCase()+"s",z=G.routes||["index","show","store","update","destroy"],L=O.table||Z,Q=XO(O),B=m$(O),W=`/api/${Z}`,D=V$(O.attributes,B),{read:_,write:R,declared:S}=C$(J);if(["store","update","destroy"].some((Y)=>z.includes(Y))&&S&&R.length===0)p$.warn(`[orm] ${$}: registering UNAUTHENTICATED mutating routes at ${W} (explicit \`middleware: []\` opt-out)`);let M=!!n$(O),C=M&&!_.includes("auth")?["auth",..._]:_,y=(Y,K=C)=>{let X=Y;for(let T of K)if(X&&typeof X.middleware==="function")X=X.middleware(T);return X};if(z.includes("index")&&!l("GET",W))y(h.get(W,async(Y)=>{try{let K=new URL(Y.url),{page:X,perPage:T,offset:H}=k$(K.searchParams),A=K.searchParams.get("sort"),j=f.selectFrom(L);j=M$(j,A,D);let g=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[k,P]of K.searchParams.entries()){if(g.has(k)||!P)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(k))continue;let n=D.get(k);if(n)j=j.where(n,"=",P)}let U=K.searchParams.get("search");if(U&&Q.length>0){let k=Q.slice(0,5);j=j.where((P)=>{for(let n of k)P=P.orWhere(V(n),"like",`%${U}%`);return P})}let E=K.searchParams.get("fields");if(E){let k=E.split(",").map((P)=>P.trim()).filter((P)=>/^[a-z_][a-z0-9_]*$/i.test(P)).map((P)=>V(P));if(k.length>0)j=j.select(k)}let I=!!O.traits?.useSoftDeletes,F=K.searchParams.get("withTrashed")==="true",p=K.searchParams.get("onlyTrashed")==="true";if(I&&!F)j=p?j.whereNotNull("deleted_at"):j.whereNull("deleted_at");let N=M?await e(O,await d(Y),Y):{enforced:!1,value:null,field:"",bypass:!1};if(N.enforced&&!N.bypass){if(N.value==null||Array.isArray(N.value)&&N.value.length===0){let k=j$(K,X,T,0,!1,void 0);return new Response(JSON.stringify({data:[],...k,meta:z$(K,X,T,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}j=Array.isArray(N.value)?j.where(N.field,"in",N.value):j.where(N.field,"=",N.value)}let c=await j.limit(T+1).offset(H).get()||[],v=c.length>T,r=(v?c.slice(0,T):c).map((k)=>o($$(k,O),B)),N$=K.searchParams.get("include");if(N$)r=await q$(r,O,N$,Q$);let r$=K.searchParams.get("with_count")==="true",t;if(r$)try{let k=f.selectFrom(L);if(N.enforced&&!N.bypass&&N.value!=null)k=Array.isArray(N.value)?k.where(N.field,"in",N.value):k.where(N.field,"=",N.value);let P=await k.count(),n=typeof P==="number"?P:Number(P?.count??P);if(Number.isFinite(n))t=n}catch{}let J$={"Content-Type":"application/json"};if(t!==void 0&&!Number.isNaN(t))J$["X-Total-Count"]=String(t);J$["Cache-Control"]=N.enforced&&!N.bypass?"private, no-store":"public, max-age=15, must-revalidate",J$.Vary="Authorization";let a$=j$(K,X,T,r.length,v,t);return new Response(JSON.stringify({data:r,...a$,meta:z$(K,X,T,r.length,v,t)}),{status:200,headers:J$})}catch(K){if(K instanceof i){let X={error:K.message};if(K.details!==void 0)X.details=K.details;return x(X,K.status||400)}return x({error:`Failed to fetch ${Z}`,detail:String(K)},500)}}));if(z.includes("show")&&!l("GET",`${W}/{id}`))y(h.get(`${W}/{id}`,async(Y)=>{try{let K=K$(Y.params?.id);if(K==null)return x({error:"Invalid ID parameter"},400);let X=await f.selectFrom(L).where({id:K}).executeTakeFirst();if(!X)return x({error:`${$} not found`},404);let T=new URL(Y.url);if(O.traits?.useSoftDeletes&&X.deleted_at&&T.searchParams.get("withTrashed")!=="true")return x({error:`${$} not found`},404);let H=M?await e(O,await d(Y),Y):{enforced:!1,value:null,field:"",bypass:!1};if(H.enforced&&!H.bypass){if(H.value==null||!a(X[H.field],H.value))return x({error:`${$} not found`},404)}let A=o($$(X,O),B),j=T.searchParams.get("include");if(j){let[F]=await q$([A],O,j,Q$);A=F}let g=A?.updated_at||A?.created_at,U=g?`W/"${A.id}-${String(g)}"`:void 0,E=Y.headers?.get?.("if-none-match");if(U&&E&&E===U)return new Response(null,{status:304,headers:{ETag:U}});let I={"Content-Type":"application/json"};if(U)I.ETag=U;return I["Cache-Control"]=H.enforced&&!H.bypass?"private, no-store":"public, max-age=30, must-revalidate",I.Vary="Authorization",new Response(JSON.stringify({data:A}),{status:200,headers:I})}catch(K){if(K instanceof i){let X={error:K.message};if(K.details!==void 0)X.details=K.details;return x(X,K.status||400)}return x({error:`Failed to fetch ${$}`,detail:String(K)},500)}}));if(z.includes("store")&&!l("POST",W))y(h.post(W,async(Y)=>{try{let K=await A$(Y),X=T$(K,B),T=B$(X,Q),H=await d(Y);if(H){let I=await v$(O,"creating",H,Y);for(let[F,p]of Object.entries(I))if(p!==void 0&&p!==null&&T[F]===void 0)T[F]=p}if(Object.keys(T).length===0)return x({error:"No fillable fields provided"},422);let A=y$(T,O,"creating");if(!A.valid)return x({error:"Validation failed",errors:A.errors},422);if(O.traits?.useTimestamps!==!1){let I=new Date().toISOString();T.created_at=I,T.updated_at=I}let j=await w$(T,O),g=Y$(c$(j,O)),U=await f.insertInto(L).values(g).execute(),E=g;try{let I=U?.lastInsertRowid??U?.insertId??U;if(I){let F=await f.selectFrom(L).where({id:I}).executeTakeFirst();if(F)E=F}}catch{}return x({data:o($$(E,O),B)},201)}catch(K){let{status:X,body:T}=X$(K,$,"create");return x(T,X)}}),R);if(z.includes("update")){let Y=async(K)=>{try{let X=K$(K.params?.id);if(X==null)return x({error:"Invalid ID parameter"},400);let T=await A$(K),H=T$(T,B),A=B$(H,Q),j=await d(K);if(j){let N=await v$(O,"updating",j,K);for(let[c,v]of Object.entries(N))if(v!==void 0&&v!==null&&A[c]===void 0)A[c]=v}if(Object.keys(A).length===0)return x({error:"No fillable fields provided"},422);let g=y$(A,O,"updating");if(!g.valid)return x({error:"Validation failed",errors:g.errors},422);let U=await f.selectFrom(L).where({id:X}).executeTakeFirst();if(!U)return x({error:`${$} not found`},404);let E=await e(O,j,K);if(E.enforced&&!E.bypass){if(!j)return x({error:"Auth required"},401);let N=U[E.field];if(!a(N,E.value))return x({error:`Not your ${$}`},403);let c=Object.keys(A).find((v)=>V(v)===V(E.field));if(c!==void 0&&!a(A[c],E.value))return x({error:`Cannot reassign ${$} ownership`},403)}if(O.traits?.useTimestamps!==!1)A.updated_at=new Date().toISOString();let I=await w$(A,O),F=Y$(c$(I,O));await f.updateTable(L).set(F).where({id:X}).execute();let p={...U,...F};try{let N=await f.selectFrom(L).where({id:X}).executeTakeFirst();if(N)p=N}catch{}return x({data:o($$(p,O),B)})}catch(X){let{status:T,body:H}=X$(X,$,"update");return x(H,T)}};if(!l("PUT",`${W}/{id}`))y(h.put(`${W}/{id}`,Y),R);if(!l("PATCH",`${W}/{id}`))y(h.patch(`${W}/{id}`,Y),R)}let q=!!O.traits?.useSoftDeletes;if(z.includes("destroy")&&!l("DELETE",`${W}/{id}`))y(h.delete(`${W}/{id}`,async(Y)=>{try{let K=K$(Y.params?.id);if(K==null)return x({error:"Invalid ID parameter"},400);let X=await f.selectFrom(L).where({id:K}).executeTakeFirst();if(!X)return x({error:`${$} not found`},404);let T=await d(Y),H=await e(O,T,Y);if(H.enforced&&!H.bypass){if(!T)return x({error:"Auth required"},401);let A=X[H.field];if(!a(A,H.value))return x({error:`Not your ${$}`},403)}if(q){let A=new Date().toISOString();await f.updateTable(L).set({deleted_at:A,updated_at:A}).where({id:K}).execute()}else await f.deleteFrom(L).where({id:K}).execute();return new Response(null,{status:204})}catch(K){if(K instanceof i){let X={error:K.message};if(K.details!==void 0)X.details=K.details;return x(X,K.status||400)}return x({error:`Failed to delete ${$}`,detail:String(K)},500)}}),R);if(z.includes("destroy")&&!l("POST",`${W}/bulk-delete`))y(h.post(`${W}/bulk-delete`,async(Y)=>{try{let X=(await A$(Y))?.ids;if(!Array.isArray(X)||X.length===0)return x({error:"An array of IDs is required"},422);if(X.length>100)return x({error:"Cannot delete more than 100 records at once"},422);let T=[],H=[];for(let U of X){let E=K$(U);if(E!=null)T.push(E);else H.push(U)}if(H.length>0)return x({error:"Invalid IDs in batch",invalid:H},422);let A=await d(Y),j=await e(O,A,Y);if(j.enforced&&!j.bypass){if(!A)return x({error:"Auth required"},401);if(j.value==null)return x({error:"Caller has no ownership identity"},403);let U=await f.selectFrom(L).select(["id",j.field]).execute(),E=new Set(U.filter((F)=>a(F[j.field],j.value)).map((F)=>String(F.id))),I=T.filter((F)=>!E.has(String(F)));if(I.length>0)return x({error:`Cannot delete ${$} you don't own`,ids:I},403)}let g=new Date().toISOString();for(let U of T)if(q)await f.updateTable(L).set({deleted_at:g,updated_at:g}).where({id:U}).execute();else await f.deleteFrom(L).where({id:U}).execute();return x({message:`Successfully deleted ${T.length} ${Z}`})}catch(K){if(K instanceof i){let X={error:K.message};if(K.details!==void 0)X.details=K.details;return x(X,K.status||400)}return x({error:`Failed to bulk delete ${Z}`,detail:String(K)},500)}}),R)}TO=h});class U${data;status;headers;isOk;constructor($,O,J,G){this.data=$;this.status=O;this.headers=J;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 _${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($,O){let J=btoa(`${$}:${O}`);return this.customHeaders.Authorization=`Basic ${J}`,this}withDigestAuth($,O){return this.digestAuth={username:$,password:O},this}withBody($){return this.bodyData=$,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach($,O,J,G){let Z=typeof O==="string"?new Blob([O],{type:G?.["Content-Type"]||"text/plain"}):O;return this.attachments.push({name:$,content:Z,filename:J,headers:G}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams($){if(!this.queryParams)return $;let O=new URLSearchParams;Object.entries(this.queryParams).forEach(([Z,z])=>{if(z!=null)O.append(Z,String(z))});let J=O.toString();if(!J)return $;let G=$.includes("?");return $+(G?"&":"?")+J}async formatBody($){let O=$||this.bodyData;if(this.isMultipart){let J=new FormData;if(O)Object.entries(O).forEach(([G,Z])=>{J.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;J.append(G.name,Z,G.filename)}else J.append(G.name,G.content,G.filename);return J}if(this.isFormData&&O){let J=new URLSearchParams;return Object.entries(O).forEach(([G,Z])=>{if(Z!=null)J.append(G,String(Z))}),J.toString()}return O?JSON.stringify(O):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($,O,J,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((S,b)=>{let[M,C]=b.trim().split("=");if(M)S[M]=C?.replace(/["']/g,"")??"";return S},{}),L=await this.generateMD5(`${this.digestAuth.username}:${z.realm}:${this.digestAuth.password}`),Q=await this.generateMD5(`${J}:${O}`),B="00000001",W=await this.generateMD5(Date.now().toString()).then((S)=>S.substring(0,8)),D=await this.generateMD5(`${L}:${z.nonce}:${B}:${W}:${z.qop}:${Q}`),_={username:`"${this.digestAuth.username}"`,realm:`"${z.realm}"`,nonce:`"${z.nonce}"`,uri:`"${O}"`,algorithm:z.algorithm?`"${z.algorithm}"`:void 0,qop:`"${z.qop}"`,nc:B,cnonce:`"${W}"`,response:`"${D}"`,opaque:z.opaque?`"${z.opaque}"`:void 0},R=Object.entries(_).filter(([S,b])=>b!==void 0).map(([S,b])=>`${S}=${b}`).join(", ");return this.customHeaders.Authorization=`Digest ${R}`,fetch(O,{method:J,headers:this.getHeaders(),body:G?this.formatBody(G):void 0})}async generateMD5($){let J=new TextEncoder().encode($),G=await crypto.subtle.digest("SHA-256",J);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}async request($,O,J){let G=this.addQueryParams($),Z=await this.formatBody(J),z=await fetch(G,{method:O,headers:this.getHeaders(),body:Z});if(this.digestAuth)z=await this.handleDigestAuth(z,G,O,J);let L=await z.json();return this.resetState(),new U$(L,z.status,z.headers,z.ok)}async get($){return this.request($,"GET")}async post($,O){return this.request($,"POST",O)}async put($,O){return this.request($,"PUT",O)}async patch($,O){return this.request($,"PATCH",O)}async delete($){return this.request($,"DELETE")}}var EO=new _$;import{path as xO}from"@stacksjs/path";function jO($){if(!$||typeof $!=="object")return{type:"string"};let O=$,J=O._type??"string",G={type:J==="array"?"array":J};if(typeof O._min==="number")G[J==="string"?"minLength":"minimum"]=O._min;if(typeof O._max==="number")G[J==="string"?"maxLength":"maximum"]=O._max;if(O._email)G.format="email";if(O._url)G.format="uri";if(O._uuid)G.format="uuid";if(Array.isArray(O._enum))G.enum=O._enum;return G}async function AO($){if(typeof $!=="string"||!$.includes("Actions"))return null;try{let{path:O}=await import("@stacksjs/path"),J=[O.appPath(`${$}.ts`),O.storagePath(`framework/defaults/app/${$}.ts`)];for(let G of J)try{if(!await Bun.file(G).exists())continue;let L=(await import(G)).default;if(L&&typeof L==="object"&&"validations"in L){let Q=L.validations;return Q&&typeof Q==="object"?Q:null}return null}catch{}}catch{}return null}async function wO($={}){let{listRegisteredRoutes:O}=await import("@stacksjs/router");try{let{loadRoutes:L}=await import("@stacksjs/router"),{default:Q}=await Promise.resolve().then(() => (I$(),E$));await L(Q)}catch(L){let Q=L instanceof Error?L.message:String(L);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${Q}`)}try{await l$().then(() => u$)}catch(L){let Q=L instanceof Error?L.message:String(L);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${Q}`)}let J=O(),G="Stacks API";try{let{config:L}=await import("@stacksjs/config");if(L.app?.name)G=`${L.app.name} API`}catch{}let Z={openapi:"3.0.0",info:{title:G,version:"1.0.0"},paths:{},components:{schemas:{}}},z=new Set;for(let L of J){let Q=L.path.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}");if(!Z.paths[Q])Z.paths[Q]={};let B=[];for(let S of L.path.matchAll(/\{(\w+)\}/g))if(S[1])B.push(S[1]);for(let S of L.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(S[1])B.push(S[1]);let W=L.method.toLowerCase(),D=L.name??`${W}_${Q.replace(/[^a-z0-9]/gi,"_")}`,_=D;if(z.has(_)){_=`${D}_${W}`;let S=2;while(z.has(_))_=`${D}_${W}_${S++}`}z.add(_);let R={summary:L.name??L.path,operationId:_,parameters:B.map((S)=>({name:S,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"}}};if(W!=="get"&&W!=="head"&&L.name){let b=`Actions/${L.name.split(".").map((C)=>C.charAt(0).toUpperCase()+C.slice(1)).join("")}Action`,M=await AO(b);if(M&&Object.keys(M).length>0){let C={type:"object",properties:{},required:[]},y=C.properties,q=C.required;for(let[Y,K]of Object.entries(M)){let X=K?.rule;if(y[Y]=jO(X),X?._required)q.push(Y)}if(q.length===0)delete C.required;R.requestBody={required:q.length>0,content:{"application/json":{schema:C}}}}}Z.paths[Q][W]=R}if($.write!==!1){let Q=Bun.file(xO.frameworkPath("api/openapi.json")).writer();Q.write(JSON.stringify(Z,null,2)),await Q.end()}return Z}var SO=["get","put","post","delete","options","head","patch","trace"];function NO($){return typeof $==="string"?JSON.stringify($):String($)}function s($){if(!$)return"unknown";if($.enum?.length)return $.enum.map(NO).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<${s($.items)}>`;if($.type==="object"||$.properties||$.additionalProperties){let O=new Set($.required||[]),J=Object.entries($.properties||{}).map(([G,Z])=>`${JSON.stringify(G)}${O.has(G)?"":"?"}: ${s(Z)}`);if($.additionalProperties){let G=$.additionalProperties===!0?"unknown":s($.additionalProperties);J.push(`[key: string]: ${G}`)}return J.length?`{ ${J.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function HO($=[]){return` parameters: {
|
|
3
|
-
${["query","header","path","cookie"].map((J)=>{let G=$.filter((z)=>z.in===J);if(!G.length)return` ${J}?: never`;let Z=G.map((z)=>`${JSON.stringify(z.name)}${z.required?"":"?"}: ${
|
|
2
|
+
var ZO=Object.defineProperty;var zO=($)=>$;function LO($,O){this[$]=zO.bind(null,O)}var D$=($,O)=>{for(var J in O)ZO($,J,{get:O[J],enumerable:!0,configurable:!0,set:LO.bind(O,J)})};var a=($,O)=>()=>($&&(O=$($=0)),O);var o=import.meta.require;var E$;var Q$=a(()=>{E$={api:"api",v1:{path:"v1",prefix:"v1"}}});var I$={};D$(I$,{default:()=>E$});var F$=a(()=>{Q$();Q$()});function KO($){let O=$;return O?.code==="SQLITE_CONSTRAINT_UNIQUE"||O?.code==="SQLITE_CONSTRAINT"||O?.code==="23505"||O?.errno===1062||/unique|duplicate/i.test(O?.message??"")}function W$($,O,J){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(KO($))return{status:409,body:{error:`${O} already exists`}};return{status:500,body:{error:`Failed to ${J} ${O}`,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 X$($){let O={};for(let[J,G]of Object.entries($))O[F(J)]=G;return O}function M$($){if(!$)return[];let O=Object.entries($.attributes??{}).filter(([,J])=>J?.fillable===!0).map(([J])=>J);for(let J of $.belongsTo??[]){if(typeof J!=="string"||!J.trim())continue;let G=F(J.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`;O.push(Z)}return[...new Set(O)]}function Y$($,O){if(!$||O.length===0)return{};let J={};for(let G of O){if(G in $){J[G]=$[G];continue}let Z=F(G);if(Z!==G&&Z in $)J[G]=$[Z]}return J}function C$($,O){if($?.name!=="date"||O instanceof Date||typeof O!=="string")return O;let J=/^(\d{4})-(\d{2})-(\d{2})$/.exec(O);if(!J)return O;let G=Number(J[1]),Z=Number(J[2]),z=Number(J[3]),K=new Date(Date.UTC(G,Z-1,z));if(K.getUTCFullYear()!==G||K.getUTCMonth()!==Z-1||K.getUTCDate()!==z)return O;return K}function x$($,O){if(!O.length)return $;let J={...$};for(let G of O)delete J[G],delete J[F(G)];return J}function l($,O){if(!$||O.length===0)return $;let J={...$};for(let G of O)delete J[G],delete J[F(G)];return J}function k$($,O){let J=new Map;for(let G of[...Object.keys($??{}),...QO]){let Z=F(G);if(!/^\w+$/.test(Z))continue;J.set(G,Z),J.set(Z,Z)}for(let G of O)J.delete(G),J.delete(F(G));return J}function R$($,O,J){if(!O)return $;let G=String(O).split(",").map((z)=>z.trim()).filter(Boolean),Z=$;for(let z of G){let K=z.startsWith("-"),Y=K?z.slice(1):z;if(!/^\w+$/.test(Y))continue;let W=J.get(Y);if(!W)continue;Z=Z.orderBy(W,K?"desc":"asc")}return Z}function XO($){try{return JSON.parse($)}catch{return $}}function YO($){try{return JSON.parse($)}catch{return[]}}function T$($,O,J){if(!$||typeof $!=="object"||!O||Object.keys(O).length===0)return $;let G={...$};for(let[Z,z]of Object.entries(O)){let K=typeof z==="string"?WO[z]:z;if(!K||typeof K[J]!=="function")continue;if(Object.prototype.hasOwnProperty.call(G,Z))G[Z]=K[J](G[Z]);let Y=F(Z);if(Y!==Z&&Object.prototype.hasOwnProperty.call(G,Y))G[Y]=K[J](G[Y])}return G}function P$($){let O=typeof $==="object"&&$!==null&&"middleware"in $,J=$?.middleware,G=Array.isArray(J)?J.filter((Z)=>typeof Z==="string"&&Z.length>0):typeof J==="string"&&J?[J]:[];return{read:G,write:O?G:["auth"],declared:O}}function f$($){let O=Number.parseInt($.get("page")||String(1),10),J=Number.isFinite(O)?Math.max(1,O):1,G=Number.parseInt($.get("per_page")||String(V$),10),Z=Math.min(Number.isFinite(G)?Math.max(1,G):V$,xO);return{page:J,perPage:Z,offset:(J-1)*Z}}function Z$($,O){let J=new URL($.toString());return J.searchParams.set("page",String(O)),`${J.pathname}${J.search}`}function z$($,O,J,G,Z,z){let K=(O-1)*J,Y=G===0,W={page:O,per_page:J,from:Y?null:K+1,to:Y?null:K+G,has_more_pages:Z,prev_page_url:O>1?Z$($,O-1):null,next_page_url:Z?Z$($,O+1):null};if(z!==void 0&&!Number.isNaN(z)){let Q=Math.max(1,Math.ceil(z/J));W.total=z,W.last_page=Q,W.first_page_url=Z$($,1),W.last_page_url=Z$($,Q)}return W}function B$($,O,J,G,Z,z){let{page:K,...Y}=z$($,O,J,G,Z,z);return{current_page:K,...Y}}var QO,WO,V$=15,xO=100;var y$=a(()=>{QO=["id","uuid","created_at","updated_at","deleted_at"];WO={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"?XO($):$,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"?YO($):[],set:($)=>$==null?null:Array.isArray($)?JSON.stringify($):$}}});import{readdirSync as TO}from"fs";import{basename as BO,extname as b$,join as jO}from"path";function SO($){let O=[],J=(G)=>{let Z;try{Z=TO(G,{withFileTypes:!0})}catch{return}for(let z of Z){let K=jO(G,z.name);if(z.isDirectory()){J(K);continue}if(![".ts",".js"].includes(b$(z.name)))continue;if(z.name.startsWith(".")||z.name.startsWith("index"))continue;O.push(K)}};return J($),O.sort()}async function g$($,O,J){for(let G of SO($))try{let Z=b$(G),z=await import(`${G}?t=${Date.now()}`),K=z.default??z,Y=K.name??BO(G,Z);O[Y]={...K,name:Y}}catch(Z){J?.(G,Z)}}async function q$($){let O={};return await g$($.defaultsRoot,O,$.onImportError),await g$($.userRoot,O,$.onImportError),O}var c$=()=>{};var d$={};D$(d$,{default:()=>_O});import{route as h}from"@stacksjs/router";import{env as n}from"@stacksjs/env";import{projectPath as t$,storagePath as AO}from"@stacksjs/path";import{createQueryBuilder as NO,defaultConfig as w$,setConfig as v$}from"@stacksjs/query-builder";import{HttpError as m}from"@stacksjs/error-handling";import{log as A$}from"@stacksjs/logging";function u($,O){return h.routes.some((J)=>J.method===$&&J.path===O)}function o$($){if(!$.attributes)return[];return Object.entries($.attributes).filter(([O,J])=>J.hidden===!0).map(([O])=>O)}function h$($,O,J){let G=$,Z=O,z=J,K=Z?.attributes??{},Y={};for(let[W,Q]of Object.entries(K)){let U=Q?.validation?.rule;if(!U||typeof U.validate!=="function")continue;let M=Object.prototype.hasOwnProperty.call(G,W);if(!M&&z==="updating")continue;let C=C$(U,M?G[W]:void 0),_=U.validate(C);if(!_?.valid&&Array.isArray(_?.errors)&&_.errors.length>0)Y[W]=_.errors.map((y)=>Q?.validation?.message?.[y?.code]??y?.message??"invalid")}return Object.keys(Y).length===0?{valid:!0}:{valid:!1,errors:Y}}function p$($){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 m$($,O,J,G){if(!$.length)return $;let Z=J.split(",").map((Q)=>Q.trim()).filter(Boolean);if(!Z.length)return $;let z=Array.isArray(O.belongsTo)?O.belongsTo:[],K=Array.isArray(O.hasMany)?O.hasMany:[],Y=Array.isArray(O.hasOne)?O.hasOne:[],W=new Map;for(let Q of z)W.set(F(Q),{kind:"belongsTo",modelName:Q});for(let Q of Y)W.set(F(Q),{kind:"hasOne",modelName:Q});for(let Q of K)W.set(p$(F(Q)),{kind:"hasMany",modelName:Q});for(let Q of Z){let U=W.get(Q);if(!U)continue;let M=G[U.modelName];if(!M)continue;let C=M.table||p$(F(U.modelName)),_=o$(M),y=(H)=>l(O$(H,M),_);if(U.kind==="belongsTo"||U.kind==="hasOne"){let H=`${F(U.modelName)}_id`,q=[...new Set($.map((x)=>x[H]).filter((x)=>x!=null))];if(!q.length){for(let x of $)x[Q]=null;continue}let P=await f.selectFrom(C).whereIn("id",q).get(),g=new Map;for(let x of P??[])g.set(String(x.id),y(x));for(let x of $)x[Q]=g.get(String(x[H]))??null}else{let H=String(O.name??""),q=`${F(H)}_id`,P=[...new Set($.map((L)=>L.id).filter((L)=>L!=null))];if(!P.length){for(let L of $)L[Q]=[];continue}let g=await f.selectFrom(C).whereIn(q,P).get(),x=new Map;for(let L of g??[]){let X=String(L[q]),T=x.get(X)??[];T.push(y(L)),x.set(X,T)}for(let L of $)L[Q]=x.get(String(L.id))??[]}}return $}async function i$($,O){let J=O?.set;if(!J||typeof J!=="object")return $;let G={...$};for(let[Z,z]of Object.entries(J)){if(typeof z!=="function"||!(Z in G))continue;try{G[Z]=await z(G)}catch{}}return G}function n$($,O){return T$($,O?.casts,"set")}function O$($,O){return T$($,O?.casts,"get")}function B($,O=200){return new Response(JSON.stringify($),{status:O,headers:{"Content-Type":"application/json"}})}async function S$($){if(Number($.headers?.get?.("content-length")??0)>L$)throw new m(413,`Request body exceeds ${L$}-byte limit`);if($.jsonBody&&typeof $.jsonBody==="object")return $.jsonBody;if($.formBody&&typeof $.formBody==="object")return $.formBody;try{let J=await $.clone().text();if(J.length>L$)throw new m(413,`Request body exceeds ${L$}-byte limit`);if(!J)return{};let G=JSON.parse(J);return G&&typeof G==="object"&&!Array.isArray(G)?G:{}}catch(J){if(J instanceof m)throw J;throw new m(400,`Invalid JSON body: ${J.message}`)}}function K$($){if($==null)return null;if(typeof $==="number")return Number.isFinite($)&&$>0?$:null;if(typeof $==="string"){let O=$.trim();if(!O)return null;if(/^\d+$/.test(O)){let J=Number(O);return Number.isFinite(J)&&J>0?J:null}return O}return null}function l$($){let O=$.bearerToken;if(typeof O==="function"){let G=O.call($);if(G)return G}let J=$.headers?.get?.("authorization")||$.headers?.get?.("Authorization")||"";if(typeof J==="string"&&J.startsWith("Bearer "))return J.substring(7);return null}async function s($){let O=$._authenticatedUser;if(O)return O;let J=l$($);if(!J)return null;try{let{Auth:G}=await import("@stacksjs/auth"),Z=await G.getUserFromToken(J);if(Z)$._authenticatedUser=Z;return Z||null}catch{return null}}function e($,O){if($==null||O==null)return!1;if(Array.isArray(O))return O.some((J)=>String(J)===String($));return String($)===String(O)}function DO($){let O=$?.attributes||{},J=(G)=>Object.prototype.hasOwnProperty.call(O,G);return J("teamId")||J("team_id")?"team_id":null}function UO($){let O=l$($),J=$.headers?.get?.("cookie")||"";return{bearerToken:()=>O,cookies:{get:(G)=>{for(let Z of J.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 s$($){if($?.ownership)return $.ownership;let O=DO($);if(!O)return null;return{field:O,resolve:async(J,G)=>{let{resolveAuthenticatedTeamId:Z}=await import("@stacksjs/auth");return Z(UO(G))}}}async function $$($,O,J){let G=s$($);if(!G||!G.field||typeof G.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let Z=typeof G.bypass==="function"?!!G.bypass(O,J):!1,z=null;try{z=await G.resolve(O,J)}catch{z=null}return{enforced:!0,value:z,field:String(G.field),bypass:Z}}async function u$($,O,J,G){let Z=$?.authedFill?.[O];if(!Z)return{};if(typeof Z==="function")try{let z=await Z(J,G);return z&&typeof z==="object"?z:{}}catch{return{}}if(typeof Z==="object"){let z={};for(let[K,Y]of Object.entries(Z))try{z[K]=typeof Y==="function"?await Y(J,G):Y}catch{}return z}return{}}var HO,j$,f,L$=1048576,_O;var r$=a(async()=>{y$();c$();HO=t$("config/qb.ts");try{let $=(await import(HO)).default;v$($??w$)}catch{A$.debug("[orm] No config/qb.ts override found \u2014 deriving config from DB_CONNECTION");let $=n.DB_CONNECTION||"sqlite";v$({...w$,dialect:$,database:$==="sqlite"?{database:n.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:n.DB_DATABASE||"stacks",host:n.DB_HOST||"127.0.0.1",port:n.DB_PORT||($==="postgres"?5432:3306),username:n.DB_USERNAME||($==="postgres"?"postgres":"root"),password:n.DB_PASSWORD||""}})}j$=await q$({defaultsRoot:AO("framework/defaults/app/Models"),userRoot:t$("app/Models"),onImportError:($,O)=>A$.warn(`[orm] Could not load model ${$}: ${O.message}`)}),f=NO();for(let[$,O]of Object.entries(j$)){let J=O.traits?.useApi;if(!J)continue;let G=typeof J==="object"?J:{},Z=G.uri||O.table||$.toLowerCase()+"s",z=G.routes||["index","show","store","update","destroy"],K=O.table||Z,Y=M$(O),W=o$(O),Q=`/api/${Z}`,U=k$(O.attributes,W),{read:M,write:C,declared:_}=P$(J);if(["store","update","destroy"].some((x)=>z.includes(x))&&_&&C.length===0)A$.warn(`[orm] ${$}: registering UNAUTHENTICATED mutating routes at ${Q} (explicit \`middleware: []\` opt-out)`);let H=!!s$(O),q=H&&!M.includes("auth")?["auth",...M]:M,P=(x,L=q)=>{let X=x;for(let T of L)if(X&&typeof X.middleware==="function")X=X.middleware(T);return X};if(z.includes("index")&&!u("GET",Q))P(h.get(Q,async(x)=>{try{let L=new URL(x.url),{page:X,perPage:T,offset:S}=f$(L.searchParams),A=L.searchParams.get("sort"),j=f.selectFrom(K);j=R$(j,A,U);let b=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[k,R]of L.searchParams.entries()){if(b.has(k)||!R)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(k))continue;let i=U.get(k);if(i)j=j.where(i,"=",R)}let D=L.searchParams.get("search");if(D&&Y.length>0){let k=Y.slice(0,5);j=j.where((R)=>{for(let i of k)R=R.orWhere(F(i),"like",`%${D}%`);return R})}let E=L.searchParams.get("fields");if(E){let k=E.split(",").map((R)=>R.trim()).filter((R)=>/^[a-z_][a-z0-9_]*$/i.test(R)).map((R)=>F(R));if(k.length>0)j=j.select(k)}let I=!!O.traits?.useSoftDeletes,V=L.searchParams.get("withTrashed")==="true",p=L.searchParams.get("onlyTrashed")==="true";if(I&&!V)j=p?j.whereNotNull("deleted_at"):j.whereNull("deleted_at");let N=H?await $$(O,await s(x),x):{enforced:!1,value:null,field:"",bypass:!1};if(N.enforced&&!N.bypass){if(N.value==null||Array.isArray(N.value)&&N.value.length===0){let k=B$(L,X,T,0,!1,void 0);return new Response(JSON.stringify({data:[],...k,meta:z$(L,X,T,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}j=Array.isArray(N.value)?j.where(N.field,"in",N.value):j.where(N.field,"=",N.value)}let w=await j.limit(T+1).offset(S).get()||[],v=w.length>T,r=(v?w.slice(0,T):w).map((k)=>l(O$(k,O),W)),H$=L.searchParams.get("include");if(H$)r=await m$(r,O,H$,j$);let JO=L.searchParams.get("with_count")==="true",t;if(JO)try{let k=f.selectFrom(K);if(N.enforced&&!N.bypass&&N.value!=null)k=Array.isArray(N.value)?k.where(N.field,"in",N.value):k.where(N.field,"=",N.value);let R=await k.count(),i=typeof R==="number"?R:Number(R?.count??R);if(Number.isFinite(i))t=i}catch{}let G$={"Content-Type":"application/json"};if(t!==void 0&&!Number.isNaN(t))G$["X-Total-Count"]=String(t);G$["Cache-Control"]=N.enforced&&!N.bypass?"private, no-store":"public, max-age=15, must-revalidate",G$.Vary="Authorization";let GO=B$(L,X,T,r.length,v,t);return new Response(JSON.stringify({data:r,...GO,meta:z$(L,X,T,r.length,v,t)}),{status:200,headers:G$})}catch(L){if(L instanceof m){let X={error:L.message};if(L.details!==void 0)X.details=L.details;return B(X,L.status||400)}return B({error:`Failed to fetch ${Z}`,detail:String(L)},500)}}));if(z.includes("show")&&!u("GET",`${Q}/{id}`))P(h.get(`${Q}/{id}`,async(x)=>{try{let L=K$(x.params?.id);if(L==null)return B({error:"Invalid ID parameter"},400);let X=await f.selectFrom(K).where({id:L}).executeTakeFirst();if(!X)return B({error:`${$} not found`},404);let T=new URL(x.url);if(O.traits?.useSoftDeletes&&X.deleted_at&&T.searchParams.get("withTrashed")!=="true")return B({error:`${$} not found`},404);let S=H?await $$(O,await s(x),x):{enforced:!1,value:null,field:"",bypass:!1};if(S.enforced&&!S.bypass){if(S.value==null||!e(X[S.field],S.value))return B({error:`${$} not found`},404)}let A=l(O$(X,O),W),j=T.searchParams.get("include");if(j){let[V]=await m$([A],O,j,j$);A=V}let b=A?.updated_at||A?.created_at,D=b?`W/"${A.id}-${String(b)}"`:void 0,E=x.headers?.get?.("if-none-match");if(D&&E&&E===D)return new Response(null,{status:304,headers:{ETag:D}});let I={"Content-Type":"application/json"};if(D)I.ETag=D;return I["Cache-Control"]=S.enforced&&!S.bypass?"private, no-store":"public, max-age=30, must-revalidate",I.Vary="Authorization",new Response(JSON.stringify({data:A}),{status:200,headers:I})}catch(L){if(L instanceof m){let X={error:L.message};if(L.details!==void 0)X.details=L.details;return B(X,L.status||400)}return B({error:`Failed to fetch ${$}`,detail:String(L)},500)}}));if(z.includes("store")&&!u("POST",Q))P(h.post(Q,async(x)=>{try{let L=await S$(x),X=x$(L,W),T=Y$(X,Y),S=await s(x);if(S){let I=await u$(O,"creating",S,x);for(let[V,p]of Object.entries(I))if(p!==void 0&&p!==null&&T[V]===void 0)T[V]=p}if(Object.keys(T).length===0)return B({error:"No fillable fields provided"},422);let A=h$(T,O,"creating");if(!A.valid)return B({error:"Validation failed",errors:A.errors},422);if(O.traits?.useTimestamps!==!1){let I=new Date().toISOString();T.created_at=I,T.updated_at=I}let j=await i$(T,O),b=X$(n$(j,O)),D=await f.insertInto(K).values(b).execute(),E=b;try{let I=D?.lastInsertRowid??D?.insertId??D;if(I){let V=await f.selectFrom(K).where({id:I}).executeTakeFirst();if(V)E=V}}catch{}return B({data:l(O$(E,O),W)},201)}catch(L){let{status:X,body:T}=W$(L,$,"create");return B(T,X)}}),C);if(z.includes("update")){let x=async(L)=>{try{let X=K$(L.params?.id);if(X==null)return B({error:"Invalid ID parameter"},400);let T=await S$(L),S=x$(T,W),A=Y$(S,Y),j=await s(L);if(j){let N=await u$(O,"updating",j,L);for(let[w,v]of Object.entries(N))if(v!==void 0&&v!==null&&A[w]===void 0)A[w]=v}if(Object.keys(A).length===0)return B({error:"No fillable fields provided"},422);let b=h$(A,O,"updating");if(!b.valid)return B({error:"Validation failed",errors:b.errors},422);let D=await f.selectFrom(K).where({id:X}).executeTakeFirst();if(!D)return B({error:`${$} not found`},404);let E=await $$(O,j,L);if(E.enforced&&!E.bypass){if(!j)return B({error:"Auth required"},401);let N=D[E.field];if(!e(N,E.value))return B({error:`Not your ${$}`},403);let w=Object.keys(A).find((v)=>F(v)===F(E.field));if(w!==void 0&&!e(A[w],E.value))return B({error:`Cannot reassign ${$} ownership`},403)}if(O.traits?.useTimestamps!==!1)A.updated_at=new Date().toISOString();let I=await i$(A,O),V=X$(n$(I,O));await f.updateTable(K).set(V).where({id:X}).execute();let p={...D,...V};try{let N=await f.selectFrom(K).where({id:X}).executeTakeFirst();if(N)p=N}catch{}return B({data:l(O$(p,O),W)})}catch(X){let{status:T,body:S}=W$(X,$,"update");return B(S,T)}};if(!u("PUT",`${Q}/{id}`))P(h.put(`${Q}/{id}`,x),C);if(!u("PATCH",`${Q}/{id}`))P(h.patch(`${Q}/{id}`,x),C)}let g=!!O.traits?.useSoftDeletes;if(z.includes("destroy")&&!u("DELETE",`${Q}/{id}`))P(h.delete(`${Q}/{id}`,async(x)=>{try{let L=K$(x.params?.id);if(L==null)return B({error:"Invalid ID parameter"},400);let X=await f.selectFrom(K).where({id:L}).executeTakeFirst();if(!X)return B({error:`${$} not found`},404);let T=await s(x),S=await $$(O,T,x);if(S.enforced&&!S.bypass){if(!T)return B({error:"Auth required"},401);let A=X[S.field];if(!e(A,S.value))return B({error:`Not your ${$}`},403)}if(g){let A=new Date().toISOString();await f.updateTable(K).set({deleted_at:A,updated_at:A}).where({id:L}).execute()}else await f.deleteFrom(K).where({id:L}).execute();return new Response(null,{status:204})}catch(L){if(L instanceof m){let X={error:L.message};if(L.details!==void 0)X.details=L.details;return B(X,L.status||400)}return B({error:`Failed to delete ${$}`,detail:String(L)},500)}}),C);if(z.includes("destroy")&&!u("POST",`${Q}/bulk-delete`))P(h.post(`${Q}/bulk-delete`,async(x)=>{try{let X=(await S$(x))?.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=[],S=[];for(let D of X){let E=K$(D);if(E!=null)T.push(E);else S.push(D)}if(S.length>0)return B({error:"Invalid IDs in batch",invalid:S},422);let A=await s(x),j=await $$(O,A,x);if(j.enforced&&!j.bypass){if(!A)return B({error:"Auth required"},401);if(j.value==null)return B({error:"Caller has no ownership identity"},403);let D=await f.selectFrom(K).select(["id",j.field]).execute(),E=new Set(D.filter((V)=>e(V[j.field],j.value)).map((V)=>String(V.id))),I=T.filter((V)=>!E.has(String(V)));if(I.length>0)return B({error:`Cannot delete ${$} you don't own`,ids:I},403)}let b=new Date().toISOString();for(let D of T)if(g)await f.updateTable(K).set({deleted_at:b,updated_at:b}).where({id:D}).execute();else await f.deleteFrom(K).where({id:D}).execute();return B({message:`Successfully deleted ${T.length} ${Z}`})}catch(L){if(L instanceof m){let X={error:L.message};if(L.details!==void 0)X.details=L.details;return B(X,L.status||400)}return B({error:`Failed to bulk delete ${Z}`,detail:String(L)},500)}}),C)}_O=h});class U${data;status;headers;isOk;constructor($,O,J,G){this.data=$;this.status=O;this.headers=J;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 _${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($,O){let J=btoa(`${$}:${O}`);return this.customHeaders.Authorization=`Basic ${J}`,this}withDigestAuth($,O){return this.digestAuth={username:$,password:O},this}withBody($){return this.bodyData=$,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach($,O,J,G){let Z=typeof O==="string"?new Blob([O],{type:G?.["Content-Type"]||"text/plain"}):O;return this.attachments.push({name:$,content:Z,filename:J,headers:G}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams($){if(!this.queryParams)return $;let O=new URLSearchParams;Object.entries(this.queryParams).forEach(([Z,z])=>{if(z!=null)O.append(Z,String(z))});let J=O.toString();if(!J)return $;let G=$.includes("?");return $+(G?"&":"?")+J}async formatBody($){let O=$||this.bodyData;if(this.isMultipart){let J=new FormData;if(O)Object.entries(O).forEach(([G,Z])=>{J.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;J.append(G.name,Z,G.filename)}else J.append(G.name,G.content,G.filename);return J}if(this.isFormData&&O){let J=new URLSearchParams;return Object.entries(O).forEach(([G,Z])=>{if(Z!=null)J.append(G,String(Z))}),J.toString()}return O?JSON.stringify(O):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($,O,J,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((_,y)=>{let[H,q]=y.trim().split("=");if(H)_[H]=q?.replace(/["']/g,"")??"";return _},{}),K=await this.generateMD5(`${this.digestAuth.username}:${z.realm}:${this.digestAuth.password}`),Y=await this.generateMD5(`${J}:${O}`),W="00000001",Q=await this.generateMD5(Date.now().toString()).then((_)=>_.substring(0,8)),U=await this.generateMD5(`${K}:${z.nonce}:${W}:${Q}:${z.qop}:${Y}`),M={username:`"${this.digestAuth.username}"`,realm:`"${z.realm}"`,nonce:`"${z.nonce}"`,uri:`"${O}"`,algorithm:z.algorithm?`"${z.algorithm}"`:void 0,qop:`"${z.qop}"`,nc:W,cnonce:`"${Q}"`,response:`"${U}"`,opaque:z.opaque?`"${z.opaque}"`:void 0},C=Object.entries(M).filter(([_,y])=>y!==void 0).map(([_,y])=>`${_}=${y}`).join(", ");return this.customHeaders.Authorization=`Digest ${C}`,fetch(O,{method:J,headers:this.getHeaders(),body:G?this.formatBody(G):void 0})}async generateMD5($){let J=new TextEncoder().encode($),G=await crypto.subtle.digest("SHA-256",J);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}async request($,O,J){let G=this.addQueryParams($),Z=await this.formatBody(J),z=await fetch(G,{method:O,headers:this.getHeaders(),body:Z});if(this.digestAuth)z=await this.handleDigestAuth(z,G,O,J);let K=await z.json();return this.resetState(),new U$(K,z.status,z.headers,z.ok)}async get($){return this.request($,"GET")}async post($,O){return this.request($,"POST",O)}async put($,O){return this.request($,"PUT",O)}async patch($,O){return this.request($,"PATCH",O)}async delete($){return this.request($,"DELETE")}}var fO=new _$;import{path as EO}from"@stacksjs/path";function IO($){if(!$||typeof $!=="object")return{type:"string"};let O=$,J=O._type??"string",G={type:J==="array"?"array":J};if(typeof O._min==="number")G[J==="string"?"minLength":"minimum"]=O._min;if(typeof O._max==="number")G[J==="string"?"maxLength":"maximum"]=O._max;if(O._email)G.format="email";if(O._url)G.format="uri";if(O._uuid)G.format="uuid";if(Array.isArray(O._enum))G.enum=O._enum;return G}async function FO($){if(typeof $!=="string"||!$.includes("Actions"))return null;try{let{path:O}=await import("@stacksjs/path"),J=[O.appPath(`${$}.ts`),O.storagePath(`framework/defaults/app/${$}.ts`)];for(let G of J)try{if(!await Bun.file(G).exists())continue;let K=(await import(G)).default;if(K&&typeof K==="object"&&"validations"in K){let Y=K.validations;return Y&&typeof Y==="object"?Y:null}return null}catch{}}catch{}return null}async function dO($={}){let O=$.portable??!0,{listRegisteredRoutes:J}=await import("@stacksjs/router");try{let{loadRoutes:W}=await import("@stacksjs/router"),{default:Q}=await Promise.resolve().then(() => (F$(),I$));await W(Q)}catch(W){let Q=W instanceof Error?W.message:String(W);if(O)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${Q}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${Q}`)}try{await r$().then(() => d$)}catch(W){let Q=W instanceof Error?W.message:String(W);if(O)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${Q}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${Q}`)}let G=(W)=>W.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),Z=[...J()].map((W)=>({route:W,oasPath:G(W.path),method:W.method.toLowerCase()})).sort((W,Q)=>{if(W.oasPath!==Q.oasPath)return W.oasPath<Q.oasPath?-1:1;return W.method<Q.method?-1:W.method>Q.method?1:0});if(O&&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(!O)try{let{config:W}=await import("@stacksjs/config");if(W.app?.name)z=`${W.app.name} API`}catch{}let K={openapi:"3.0.0",info:{title:z,version:"1.0.0"},paths:{},components:{schemas:{}}},Y=new Set;for(let{route:W,oasPath:Q,method:U}of Z){if(!K.paths[Q])K.paths[Q]={};let M=[];for(let H of W.path.matchAll(/\{(\w+)\}/g))if(H[1])M.push(H[1]);for(let H of W.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(H[1])M.push(H[1]);let C=W.name??`${U}_${Q.replace(/[^a-z0-9]/gi,"_")}`,_=C;if(Y.has(_)){_=`${C}_${U}`;let H=2;while(Y.has(_))_=`${C}_${U}_${H++}`}Y.add(_);let y={summary:W.name??W.path,operationId:_,parameters:M.map((H)=>({name:H,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"}}};if(U!=="get"&&U!=="head"&&W.name){let q=`Actions/${W.name.split(".").map((g)=>g.charAt(0).toUpperCase()+g.slice(1)).join("")}Action`,P=await FO(q);if(P&&Object.keys(P).length>0){let g={type:"object",properties:{},required:[]},x=g.properties,L=g.required;for(let[X,T]of Object.entries(P)){let S=T?.rule;if(x[X]=IO(S),S?._required)L.push(X)}if(L.length===0)delete g.required;y.requestBody={required:L.length>0,content:{"application/json":{schema:g}}}}}K.paths[Q][U]=y}if($.write!==!1){let Q=Bun.file(EO.frameworkPath("api/openapi.json")).writer();Q.write(JSON.stringify(K,null,2)),await Q.end()}return K}var VO=["get","put","post","delete","options","head","patch","trace"];function MO($){return typeof $==="string"?JSON.stringify($):String($)}function d($){if(!$)return"unknown";if($.enum?.length)return $.enum.map(MO).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<${d($.items)}>`;if($.type==="object"||$.properties||$.additionalProperties){let O=new Set($.required||[]),J=Object.entries($.properties||{}).map(([G,Z])=>`${JSON.stringify(G)}${O.has(G)?"":"?"}: ${d(Z)}`);if($.additionalProperties){let G=$.additionalProperties===!0?"unknown":d($.additionalProperties);J.push(`[key: string]: ${G}`)}return J.length?`{ ${J.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function CO($=[]){return` parameters: {
|
|
3
|
+
${["query","header","path","cookie"].map((J)=>{let G=$.filter((z)=>z.in===J);if(!G.length)return` ${J}?: never`;let Z=G.map((z)=>`${JSON.stringify(z.name)}${z.required?"":"?"}: ${d(z.schema)}`);return` ${J}${G.every((z)=>!z.required)?"?":""}: { ${Z.join("; ")} }`}).join(`
|
|
4
4
|
`)}
|
|
5
|
-
}`}function
|
|
6
|
-
requestBody${$.requestBody.required?"":"?"}: { content: ${
|
|
7
|
-
requestBody?: never`,J=Object.entries($.responses||{}).map(([G,Z])=>` ${JSON.stringify(G)}: { content: ${
|
|
8
|
-
${
|
|
5
|
+
}`}function a$($){if(!$||!Object.keys($).length)return"never";return`{ ${Object.entries($).map(([O,J])=>`${JSON.stringify(O)}: ${d(J.schema)}`).join("; ")} }`}function kO($){let O=$.requestBody?`
|
|
6
|
+
requestBody${$.requestBody.required?"":"?"}: { content: ${a$($.requestBody.content)} }`:`
|
|
7
|
+
requestBody?: never`,J=Object.entries($.responses||{}).map(([G,Z])=>` ${JSON.stringify(G)}: { content: ${a$(Z.content)} }`);return`{
|
|
8
|
+
${CO($.parameters)}${O}
|
|
9
9
|
responses: {
|
|
10
10
|
${J.join(`
|
|
11
11
|
`)}
|
|
12
12
|
}
|
|
13
|
-
}`}function
|
|
13
|
+
}`}function aO($){let O=Object.entries($.paths||{}).map(([G,Z])=>{let z=VO.map((K)=>{let Y=Z[K];return Y?` ${K}: ${kO(Y)}`:` ${K}?: never`});return` ${JSON.stringify(G)}: {
|
|
14
14
|
${z.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}),J=Object.entries($.components?.schemas||{}).map(([G,Z])=>` ${JSON.stringify(G)}: ${
|
|
16
|
+
}`}),J=Object.entries($.components?.schemas||{}).map(([G,Z])=>` ${JSON.stringify(G)}: ${d(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
|
*/
|
|
@@ -29,4 +29,4 @@ ${J.join(`
|
|
|
29
29
|
`)}
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
-
`}class
|
|
32
|
+
`}class c{static instance=new c;isMissing(){return!0}}class J${data;constructor($){this.data=$}}class e${condition;value;defaultValue;constructor($,O,J=new c){this.condition=$;this.value=O;this.defaultValue=J}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class $O{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 O=this.toArray($||this.request);return this.filterAndResolve(O)}toResponse($){let O=this.resolve($),J=this.constructor.wrap;if(J)return{[J]:O,...this.additional};return{...O,...this.additional}}toJson($){return JSON.stringify(this.toResponse($))}toJSON(){return this.toResponse()}static collection($){return new N$($,this)}when($,O,J){if(typeof $==="function"?$():$)return typeof O==="function"?O():O;return J!==void 0?J:c.instance}whenNotNull($,O){if($===null||$===void 0)return c.instance;return O?O($):$}whenLoaded($,O,J){let G=this.resource;if(!(($ in G)&&G[$]!==void 0))return J!==void 0?J:c.instance;if(O!==void 0)return typeof O==="function"?O():O;return G[$]}whenCounted($,O){let J=this.resource,G=`${$}_count`;if(G in J)return J[G];return O!==void 0?O:c.instance}merge($){return new J$($)}mergeWhen($,O){if(!(typeof $==="function"?$():$))return c.instance;let G=typeof O==="function"?O():O;return new J$(G)}static MAX_RESOLVE_DEPTH=20;filterAndResolve($,O=0){if(O>=$O.MAX_RESOLVE_DEPTH)return $;let J={};for(let[G,Z]of Object.entries($)){if(Z instanceof c)continue;if(Z instanceof J$){Object.assign(J,this.filterAndResolve(Z.data,O+1));continue}if(Z instanceof e$){let z=Z.resolve();if(!(z instanceof c))J[G]=z;continue}if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)&&!(Z instanceof Date)){J[G]=this.filterAndResolve(Z,O+1);continue}if(Array.isArray(Z)){J[G]=Z.filter((z)=>!(z instanceof c)).map((z)=>{if(z instanceof J$)return z.data;if(z!==null&&typeof z==="object"&&!(z instanceof Date))return this.filterAndResolve(z,O+1);return z});continue}J[G]=Z}return J}static withoutWrapping(){this.wrap=null}static wrapWith($){this.wrap=$}}class N${resources;ResourceClass;additional={};request;static wrap="data";constructor($,O){this.resources=$,this.ResourceClass=O}withRequest($){return this.request=$,this}withAdditional($){return this.additional={...this.additional,...$},this}resolve($){let O=$||this.request;return this.resources.map((J)=>{let G=new this.ResourceClass(J);if(O)G.withRequest(O);return G.resolve(O)})}toResponse($){let O=this.resolve($),J=this.constructor.wrap;if(J)return{[J]:O,...this.additional};return{data:O,...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 OO extends N${meta;links;constructor($,O){super($.data,O);this.meta=$.meta,this.links=$.links}static fromPagination($,O,J){let{currentPage:G,perPage:Z,total:z,baseUrl:K=""}=J,Y=Math.ceil(z/Z),W=z>0?(G-1)*Z+1:null,Q=z>0?Math.min(G*Z,z):null;return new OO({data:$,meta:{current_page:G,from:W,last_page:Y,per_page:Z,to:Q,total:z},links:{first:`${K}?page=1`,last:`${K}?page=${Y}`,prev:G>1?`${K}?page=${G-1}`:null,next:G<Y?`${K}?page=${G+1}`:null}},O)}toResponse($){return{data:this.resolve($),meta:this.meta,links:this.links,...this.additional}}}function $J($,O){let J=O($);return{toResponse:()=>({data:J}),toJson:()=>JSON.stringify({data:J})}}function OJ($,O){let J=$.map(O);return{toResponse:()=>({data:J}),toJson:()=>JSON.stringify({data:J})}}export{d as schemaType,$J as resource,aO as renderOpenApiTypes,dO as generateOpenApi,fO as fetcher,OJ as collection,N$ as ResourceCollection,OO as PaginatedResourceCollection,c as MissingValue,J$ as MergeValue,$O as JsonResource,e$ as ConditionalValue};
|
package/package.json
CHANGED
|
@@ -2,27 +2,28 @@
|
|
|
2
2
|
"name": "@stacksjs/api",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.70.
|
|
6
|
-
"description": "The Stacks
|
|
5
|
+
"version": "0.70.230",
|
|
6
|
+
"description": "The Stacks API utilities.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
9
9
|
"Chris Breuer <chris@stacksjs.com>"
|
|
10
10
|
],
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"funding": "https://github.com/sponsors/chrisbbreuer",
|
|
13
|
-
"homepage": "https://github.com/stacksjs/stacks/tree/main/storage/framework/core/
|
|
13
|
+
"homepage": "https://github.com/stacksjs/stacks/tree/main/storage/framework/core/api#readme",
|
|
14
14
|
"repository": {
|
|
15
15
|
"type": "git",
|
|
16
16
|
"url": "git+https://github.com/stacksjs/stacks.git",
|
|
17
|
-
"directory": "./storage/framework/core/
|
|
17
|
+
"directory": "./storage/framework/core/api"
|
|
18
18
|
},
|
|
19
19
|
"bugs": {
|
|
20
20
|
"url": "https://github.com/stacksjs/stacks/issues"
|
|
21
21
|
},
|
|
22
22
|
"keywords": [
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"
|
|
23
|
+
"api",
|
|
24
|
+
"http",
|
|
25
|
+
"openapi",
|
|
26
|
+
"fetch",
|
|
26
27
|
"utilities",
|
|
27
28
|
"functions",
|
|
28
29
|
"stacks"
|
|
@@ -56,6 +57,6 @@
|
|
|
56
57
|
},
|
|
57
58
|
"devDependencies": {
|
|
58
59
|
"better-dx": "^0.2.17",
|
|
59
|
-
"@stacksjs/utils": "0.70.
|
|
60
|
+
"@stacksjs/utils": "0.70.230"
|
|
60
61
|
}
|
|
61
62
|
}
|