@stacksjs/api 0.72.103 → 0.73.0
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 +11 -11
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var bt=Object.defineProperty;var Rt=(e)=>e;function
|
|
3
|
-
${["query","header","path","cookie"].map((n)=>{let r=e.filter((o)=>o.in===n);if(!r.length)return` ${n}?: never`;let s=r.map((o)=>`${JSON.stringify(o.name)}${o.required?"":"?"}: ${
|
|
2
|
+
var bt=Object.defineProperty;var Rt=(e)=>e;function kt(e,t){this[e]=Rt.bind(null,t)}var ce=(e,t)=>{for(var n in t)bt(e,n,{get:t[n],enumerable:!0,configurable:!0,set:kt.bind(t,n)})};var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=import.meta.require;var ve={};ce(ve,{renderOpenApiTypes:()=>Tt,schemaType:()=>F});function St(e){return typeof e==="string"?JSON.stringify(e):String(e)}function F(e){if(!e)return"unknown";if(e.enum?.length)return e.enum.map(St).join(" | ");if(e.type==="string")return"string";if(e.type==="number"||e.type==="integer")return"number";if(e.type==="boolean")return"boolean";if(e.type==="null")return"null";if(e.type==="array")return`Array<${F(e.items)}>`;if(e.type==="object"||e.properties||e.additionalProperties){let t=new Set(e.required||[]),n=Object.entries(e.properties||{}).map(([r,s])=>`${JSON.stringify(r)}${t.has(r)?"":"?"}: ${F(s)}`);if(e.additionalProperties){let r=e.additionalProperties===!0?"unknown":F(e.additionalProperties);n.push(`[key: string]: ${r}`)}return n.length?`{ ${n.join("; ")} }`:"Record<string, unknown>"}return"unknown"}function $t(e=[]){return` parameters: {
|
|
3
|
+
${["query","header","path","cookie"].map((n)=>{let r=e.filter((o)=>o.in===n);if(!r.length)return` ${n}?: never`;let s=r.map((o)=>`${JSON.stringify(o.name)}${o.required?"":"?"}: ${F(o.schema)}`);return` ${n}${r.every((o)=>!o.required)?"?":""}: { ${s.join("; ")} }`}).join(`
|
|
4
4
|
`)}
|
|
5
|
-
}`}function
|
|
6
|
-
requestBody${e.requestBody.required?"":"?"}: { content: ${
|
|
7
|
-
requestBody?: never`,n=Object.entries(e.responses||{}).map(([r,s])=>` ${JSON.stringify(r)}: { content: ${
|
|
5
|
+
}`}function De(e){if(!e||!Object.keys(e).length)return"never";return`{ ${Object.entries(e).map(([t,n])=>`${JSON.stringify(t)}: ${F(n.schema)}`).join("; ")} }`}function At(e){let t=e.requestBody?`
|
|
6
|
+
requestBody${e.requestBody.required?"":"?"}: { content: ${De(e.requestBody.content)} }`:`
|
|
7
|
+
requestBody?: never`,n=Object.entries(e.responses||{}).map(([r,s])=>` ${JSON.stringify(r)}: { content: ${De(s.content)} }`);return`{
|
|
8
8
|
${$t(e.parameters)}${t}
|
|
9
9
|
responses: {
|
|
10
10
|
${n.join(`
|
|
11
11
|
`)}
|
|
12
12
|
}
|
|
13
|
-
}`}function Tt(e){let t=Object.entries(e.paths||{}).map(([r,s])=>{let o=
|
|
13
|
+
}`}function Tt(e){let t=Object.entries(e.paths||{}).map(([r,s])=>{let o=Ot.map((i)=>{let c=s[i];return c?` ${i}: ${At(c)}`:` ${i}?: never`});return` ${JSON.stringify(r)}: {
|
|
14
14
|
${o.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}),n=Object.entries(e.components?.schemas||{}).map(([r,s])=>` ${JSON.stringify(r)}: ${
|
|
16
|
+
}`}),n=Object.entries(e.components?.schemas||{}).map(([r,s])=>` ${JSON.stringify(r)}: ${F(s)}`);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,13 +29,13 @@ ${n.join(`
|
|
|
29
29
|
`)}
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
-
`}var
|
|
32
|
+
`}var Ot;var ue=Z(()=>{Ot=["get","put","post","delete","options","head","patch","trace"]});var Ne={};ce(Ne,{methodName:()=>qe,renderApiClient:()=>Dt});function qe(e){let t=e.replace(/[{}]/g,"").split(/[^a-z0-9]+/i).filter(Boolean),n=t[0]?.toLowerCase()==="api"?t.slice(1):t[1]?.toLowerCase()==="api"?[t[0],...t.slice(2)]:t,[r,...s]=n;if(!r)return"call";let o=r.charAt(0).toLowerCase()+r.slice(1),i=s.map((p)=>p.charAt(0).toUpperCase()+p.slice(1)),c=[o,...i].join("");return/^[a-z_$]/i.test(c)?c:`call${c.charAt(0).toUpperCase()}${c.slice(1)}`}function xt(e){let t=e.responses??{},n=Object.keys(t).find((o)=>o.startsWith("2"));if(!n)return"unknown";let r=t[n]?.content,s=r?.["application/json"]??Object.values(r??{})[0];return s?.schema?F(s.schema):"unknown"}function _t(e,t=" "){let n=e.filter(Boolean);if(!n.length)return"";return`${t}/**
|
|
33
33
|
${n.map((r)=>`${t} * ${r}`).join(`
|
|
34
34
|
`)}
|
|
35
35
|
${t} */
|
|
36
|
-
`}function
|
|
36
|
+
`}function Pt(e,t,n,r){let s=n.parameters??[],o=s.filter((O)=>O.in==="path"),i=s.filter((O)=>O.in==="query"),c=n.requestBody?.content?.["application/json"]?.schema,p=Boolean(n.requestBody?.required),d=[];for(let O of[...o,...i]){let D=O.in==="path"||O.required;d.push(`${JSON.stringify(O.name)}${D?"":"?"}: ${F(O.schema)}`)}if(c)d.push(`body${p?"":"?"}: ${F(c)}`);let u=[...o,...i].every((O)=>O.in!=="path"&&!O.required)&&(!c||!p),f=d.length?`input${u?"?":""}: { ${d.join("; ")} }, `:"",R=i.length?`[${i.map((O)=>JSON.stringify(O.name)).join(", ")}]`:"[]";return`${_t([n.summary&&n.summary!==e?n.summary:`${t.toUpperCase()} ${e}`,n.description??""])} ${r}(${f}options?: RequestOptions): Promise<ApiResult<${xt(n)}>> {
|
|
37
37
|
return request(config, ${JSON.stringify(t.toUpperCase())}, ${JSON.stringify(e)}, ${d.length?"input ?? {}":"{}"}, ${R}, ${c?"true":"false"}, options)
|
|
38
|
-
},`}function
|
|
38
|
+
},`}function Dt(e,t={}){let n=t.name??"API",r=new Map,s=[];for(let[o,i]of Object.entries(e.paths??{}))for(let c of jt){let p=i[c];if(!p)continue;let d=qe(p.operationId??`${c}_${o}`),u=r.get(d)??0;r.set(d,u+1),s.push(Pt(o,c,p,u===0?d:`${d}${u+1}`))}return`/* eslint-disable */
|
|
39
39
|
/**
|
|
40
40
|
* ${n} client, generated from the OpenAPI document.
|
|
41
41
|
*
|
|
@@ -136,4 +136,4 @@ ${s.join(`
|
|
|
136
136
|
}
|
|
137
137
|
|
|
138
138
|
export type Client = ReturnType<typeof createClient>
|
|
139
|
-
`}var jt;var ge=Z(()=>{ue();jt=["get","put","post","delete","options","head","patch"]});function qt(e){let t=e;return t?.code==="SQLITE_CONSTRAINT_UNIQUE"||t?.code==="SQLITE_CONSTRAINT"||t?.code==="23505"||t?.errno===1062||/unique|duplicate/i.test(t?.message??"")}function me(e,t,n){let r=e;if(e instanceof Error&&typeof r.status==="number"&&Number.isInteger(r.status)&&r.status>=400&&r.status<600){let s={error:e.message};if(r.details!==void 0)s.details=r.details;return{status:r.status,body:s}}if(qt(e))return{status:409,body:{error:`${t} already exists`}};return{status:500,body:{error:`Failed to ${n} ${t}`,detail:String(e)}}}function T(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function ye(e){let t={};for(let[n,r]of Object.entries(e))t[T(n)]=r;return t}function Ee(e,t){let n=String(t||"").replace(/^\/+|\/+$/g,""),r=String(e).replace(/^\/+/,"");return`/api/${n?`${n}/`:""}${r}`}function Be(e){if(!e)return null;let t=e.attributes??{};if(Object.prototype.hasOwnProperty.call(t,"teamId")||Object.prototype.hasOwnProperty.call(t,"team_id"))return"team_id";return e.belongsTo?.some((n)=>n==="Team")?"team_id":null}function Me(e,t,n){let r=Object.keys(e).find((o)=>T(o)===T(t));if(Array.isArray(n)){if(r===void 0)return{data:e,error:"Ownership value is required"};if(!n.some((o)=>String(o)===String(e[r])))return{data:e,error:"Ownership value is not available to this caller"};return{data:{...e,[t]:e[r]}}}if(n===null||n===void 0)return{data:e,error:"Caller has no ownership identity"};let s={...e};for(let o of Object.keys(s))if(T(o)===T(t))delete s[o];return s[t]=n,{data:s}}function Fe(e){if(!e)return[];let t=Object.entries(e.attributes??{}).filter(([,n])=>n?.fillable===!0).map(([n])=>n);for(let n of e.belongsTo??[]){if(typeof n!=="string"||!n.trim())continue;let r=T(n.trim()).split("_").filter(Boolean);if(r.length===0)continue;let s=`${r[0]}${r.slice(1).map((o)=>`${o[0]?.toUpperCase()}${o.slice(1)}`).join("")}Id`;t.push(s)}return[...new Set(t)]}function we(e,t){if(!e||t.length===0)return{};let n={};for(let r of t){if(r in e){n[r]=e[r];continue}let s=T(r);if(s!==r&&s in e)n[r]=e[s]}return n}function Dt(e,t){if(e?.name!=="date"||t instanceof Date||typeof t!=="string")return t;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return t;let r=Number(n[1]),s=Number(n[2]),o=Number(n[3]),i=new Date(Date.UTC(r,s-1,o));if(i.getUTCFullYear()!==r||i.getUTCMonth()!==s-1||i.getUTCDate()!==o)return t;return i}function be(e,t){if(!t.length)return e;let n={...e};for(let r of t)delete n[r],delete n[T(r)];return n}function K(e,t){if(!e||t.length===0)return e;let n={...e};for(let r of t)delete n[r],delete n[T(r)];return n}function Ue(e,t){let n=new Map;for(let r of[...Object.keys(e??{}),...Nt]){let s=T(r);if(!/^\w+$/.test(s))continue;n.set(r,s),n.set(s,s)}for(let r of t)n.delete(r),n.delete(T(r));return n}function Je(e,t,n){if(!t)return e;let r=String(t).split(",").map((o)=>o.trim()).filter(Boolean),s=e;for(let o of r){let i=o.startsWith("-"),c=i?o.slice(1):o;if(!/^\w+$/.test(c))continue;let p=n.get(c);if(!p)continue;s=s.orderBy(p,i?"desc":"asc")}return s}function It(e){try{return JSON.parse(e)}catch{return e}}function Et(e){try{return JSON.parse(e)}catch{return[]}}function Re(e,t,n){if(!e||typeof e!=="object"||!t||Object.keys(t).length===0)return e;let r={...e};for(let[s,o]of Object.entries(t)){let i=typeof o==="string"?Ct[o]:o;if(!i||typeof i[n]!=="function")continue;if(Object.prototype.hasOwnProperty.call(r,s))r[s]=i[n](r[s]);let c=T(s);if(c!==s&&Object.prototype.hasOwnProperty.call(r,c))r[c]=i[n](r[c])}return r}function Oe(e,t,n){let r=t?.attributes??{},s={};for(let[o,i]of Object.entries(r)){let c=i?.validation?.rule;if(!c||typeof c.validate!=="function")continue;let p=Object.prototype.hasOwnProperty.call(e,o);if(!p&&n==="updating")continue;let d=i!==null&&typeof i==="object"&&Object.prototype.hasOwnProperty.call(i,"default"),u=p?e[o]:d?i.default:void 0,f=Dt(c,u),R=c.validate(f);if(!R?.valid&&Array.isArray(R?.errors)&&R.errors.length>0)s[o]=R.errors.map((P)=>i?.validation?.message?.[P?.code]??P?.message??"invalid")}return Object.keys(s).length===0?{valid:!0}:{valid:!1,errors:s}}function He(e,t,n){let r=Ce(n);return e.find((s)=>s.method===t&&Ce(String(s.path??""))===r)}function Ce(e){return e.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function he(e){if(Array.isArray(e))return e.filter((t)=>typeof t==="string"&&t.length>0);return typeof e==="string"&&e?[e]:[]}function Le(e){let t=typeof e==="object"&&e!==null&&"middleware"in e,n=e?.middleware;if(!t)return{read:["auth"],write:["auth"],declared:!1};if(n&&typeof n==="object"&&!Array.isArray(n)){let s=n;return{read:"read"in s?he(s.read):["auth"],write:"write"in s?he(s.write):["auth"],declared:!0}}let r=he(n);return{read:r,write:r,declared:!0}}function We(e){let t=Number.parseInt(e.get("page")||String(1),10),n=Number.isFinite(t)?Math.max(1,t):1,r=Number.parseInt(e.get("per_page")||String(Ie),10),s=Math.min(Number.isFinite(r)?Math.max(1,r):Ie,Bt);return{page:n,perPage:s,offset:(n-1)*s}}function de(e,t){let n=new URL(e.toString());return n.searchParams.set("page",String(t)),`${n.pathname}${n.search}`}function le(e,t,n,r,s,o){let i=(t-1)*n,c=r===0,p={page:t,per_page:n,from:c?null:i+1,to:c?null:i+r,has_more_pages:s,prev_page_url:t>1?de(e,t-1):null,next_page_url:s?de(e,t+1):null};if(o!==void 0&&!Number.isNaN(o)){let d=Math.max(1,Math.ceil(o/n));p.total=o,p.last_page=d,p.first_page_url=de(e,1),p.last_page_url=de(e,d)}return p}function Se(e,t,n,r,s,o){let{page:i,...c}=le(e,t,n,r,s,o);return{current_page:i,...c}}var Nt,Ct,Ie=15,Bt=100;var ze=Z(()=>{Nt=["id","uuid","created_at","updated_at","deleted_at"];Ct={string:{get:(e)=>e!=null?String(e):null,set:(e)=>e!=null?String(e):null},number:{get:(e)=>e!=null?Number(e):null,set:(e)=>e!=null?Number(e):null},integer:{get:(e)=>e!=null?Math.trunc(Number(e)):null,set:(e)=>e!=null?Math.trunc(Number(e)):null},float:{get:(e)=>e!=null?Number.parseFloat(String(e)):null,set:(e)=>e!=null?Number.parseFloat(String(e)):null},boolean:{get:(e)=>e===1||e==="1"||e===!0||e==="true",set:(e)=>e===!0||e===1||e==="1"||e==="true"?1:0},json:{get:(e)=>e==null?null:typeof e==="string"?It(e):e,set:(e)=>e==null?null:typeof e==="string"?e:JSON.stringify(e)},datetime:{get:(e)=>e?new Date(e):null,set:(e)=>e instanceof Date?e.toISOString():e},date:{get:(e)=>e?new Date(e):null,set:(e)=>e instanceof Date?e.toISOString().split("T")[0]:e},array:{get:(e)=>e==null?[]:Array.isArray(e)?e:typeof e==="string"?Et(e):[],set:(e)=>e==null?null:Array.isArray(e)?JSON.stringify(e):e}}});var Xe={};ce(Xe,{loadModelRegistry:()=>ke,modelFiles:()=>Ge});import{readdirSync as Mt}from"fs";import{basename as Ft,extname as Qe,join as Ut}from"path";function Ge(e){let t=[],n=(r)=>{let s;try{s=Mt(r,{withFileTypes:!0})}catch{return}for(let o of s){let i=Ut(r,o.name);if(o.isDirectory()){n(i);continue}if(![".ts",".js"].includes(Qe(o.name)))continue;if(o.name.startsWith(".")||o.name.startsWith("index"))continue;t.push(i)}};return n(e),t.sort()}async function Ve(e,t,n){for(let r of Ge(e))try{let s=Qe(r),o=await import(`${r}?t=${Date.now()}`),i=o.default??o,c=i.name??Ft(r,s);t[c]={...i,name:c}}catch(s){n?.(r,s)}}async function ke(e){let t={};return await Ve(e.defaultsRoot,t,e.onImportError),await Ve(e.userRoot,t,e.onImportError),t}var $e=()=>{};import{route as L}from"@stacksjs/router";import{env as Q}from"@stacksjs/env";import{projectPath as st,storagePath as Jt}from"@stacksjs/path";import{createQueryBuilder as Ht,defaultConfig as Ze,setConfig as Ke}from"@stacksjs/query-builder";import{HttpError as z}from"@stacksjs/error-handling";import{log as oe}from"@stacksjs/logging";function G(e,t){let n=He(L.routes,e,t);if(!n)return!1;let r=String(n.path??"");return oe.info(`[orm] Skipping generated ${e} ${t} - already defined${r&&r!==t?` as ${r}`:""}.`),!0}function ot(e){if(!e.attributes)return[];return Object.entries(e.attributes).filter(([t,n])=>n.hidden===!0).map(([t])=>t)}function Ye(e){if(e.endsWith("y")&&!/[aeiou]y$/i.test(e))return`${e.slice(0,-1)}ies`;if(/(?:s|x|z|ch|sh)$/i.test(e))return`${e}es`;return`${e}s`}async function et(e,t,n,r){if(!e.length)return e;let s=n.split(",").map((d)=>d.trim()).filter(Boolean);if(!s.length)return e;let o=Array.isArray(t.belongsTo)?t.belongsTo:[],i=Array.isArray(t.hasMany)?t.hasMany:[],c=Array.isArray(t.hasOne)?t.hasOne:[],p=new Map;for(let d of o)p.set(T(d),{kind:"belongsTo",modelName:d});for(let d of c)p.set(T(d),{kind:"hasOne",modelName:d});for(let d of i)p.set(Ye(T(d)),{kind:"hasMany",modelName:d});for(let d of s){let u=p.get(d);if(!u)continue;let f=r[u.modelName];if(!f)continue;let R=f.table||Ye(T(u.modelName)),P=ot(f),S=(v)=>K(se(v,f),P);if(u.kind==="belongsTo"||u.kind==="hasOne"){let v=`${T(u.modelName)}_id`,j=[...new Set(e.map((x)=>x[v]).filter((x)=>x!=null))];if(!j.length){for(let x of e)x[d]=null;continue}let E=await C.selectFrom(R).whereIn("id",j).get(),q=new Map;for(let x of E??[])q.set(String(x.id),S(x));for(let x of e)x[d]=q.get(String(x[v]))??null}else{let v=String(t.name??""),j=`${T(v)}_id`,E=[...new Set(e.map((h)=>h.id).filter((h)=>h!=null))];if(!E.length){for(let h of e)h[d]=[];continue}let q=await C.selectFrom(R).whereIn(j,E).get(),x=new Map;for(let h of q??[]){let a=String(h[j]),l=x.get(a)??[];l.push(S(h)),x.set(a,l)}for(let h of e)h[d]=x.get(String(h.id))??[]}}return e}async function tt(e,t){let n=t?.set;if(!n||typeof n!=="object")return e;let r={...e};for(let[s,o]of Object.entries(n)){if(typeof o!=="function"||!(s in r))continue;try{r[s]=await o(r)}catch{}}return r}function nt(e,t){return Re(e,t?.casts,"set")}function se(e,t){return Re(e,t?.casts,"get")}function m(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})}async function Te(e){if(Number(e.headers?.get?.("content-length")??0)>pe)throw new z(413,`Request body exceeds ${pe}-byte limit`);if(e.jsonBody&&typeof e.jsonBody==="object")return e.jsonBody;if(e.formBody&&typeof e.formBody==="object")return e.formBody;try{let n=await e.clone().text();if(n.length>pe)throw new z(413,`Request body exceeds ${pe}-byte limit`);if(!n)return{};let r=JSON.parse(n);return r&&typeof r==="object"&&!Array.isArray(r)?r:{}}catch(n){if(n instanceof z)throw n;throw new z(400,`Invalid JSON body: ${n.message}`)}}function fe(e){if(e==null)return null;if(typeof e==="number")return Number.isFinite(e)&&e>0?e:null;if(typeof e==="string"){let t=e.trim();if(!t)return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)&&n>0?n:null}return t}return null}function it(e){let t=e.bearerToken;if(typeof t==="function"){let r=t.call(e);if(r)return r}let n=e.headers?.get?.("authorization")||e.headers?.get?.("Authorization")||"";if(typeof n==="string"&&n.startsWith("Bearer "))return n.substring(7);return null}async function Y(e){let t=e._authenticatedUser;if(t)return t;let n=it(e);if(!n)return null;try{let{Auth:r}=await import("@stacksjs/auth"),s=await r.getUserFromToken(n);if(s)e._authenticatedUser=s;return s||null}catch{return null}}function re(e,t){if(e==null||t==null)return!1;if(Array.isArray(t))return t.some((n)=>String(n)===String(e));return String(e)===String(t)}function Wt(e){let t=it(e),n=e.headers?.get?.("cookie")||"";return{bearerToken:()=>t,cookies:{get:(r)=>{for(let s of n.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()===r)return decodeURIComponent(s.slice(o+1).trim())}return null}}}}function at(e){if(e?.ownership)return e.ownership;let t=Be(e);if(!t)return null;return{field:t,resolve:async(n,r)=>{let{resolveAuthenticatedTeamId:s}=await import("@stacksjs/auth");return s(Wt(r))}}}async function ee(e,t,n){let r=at(e);if(!r||!r.field||typeof r.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let s=typeof r.bypass==="function"?!!r.bypass(t,n):!1,o=null;try{o=await r.resolve(t,n)}catch{o=null}return{enforced:!0,value:o,field:String(r.field),bypass:s}}async function rt(e,t,n,r){let s=e?.authedFill?.[t];if(!s)return{};if(typeof s==="function")try{let o=await s(n,r);return o&&typeof o==="object"?o:{}}catch{return{}}if(typeof s==="object"){let o={};for(let[i,c]of Object.entries(s))try{o[i]=typeof c==="function"?await c(n,r):c}catch{}return o}return{}}var Lt,Ae,C,pe=1048576,ct;var ut=Z(async()=>{ze();$e();Lt=st("config/qb.ts");try{let e=(await import(Lt)).default;Ke(e??Ze)}catch{oe.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let e=Q.DB_CONNECTION||"sqlite";Ke({...Ze,dialect:e,database:e==="sqlite"?{database:Q.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:Q.DB_DATABASE||"stacks",host:Q.DB_HOST||"127.0.0.1",port:Q.DB_PORT||(e==="postgres"?5432:3306),username:Q.DB_USERNAME||(e==="postgres"?"postgres":"root"),password:Q.DB_PASSWORD||""}})}Ae=await ke({defaultsRoot:Jt("framework/defaults/app/Models"),userRoot:st("app/Models"),onImportError:(e,t)=>oe.warn(`[orm] Could not load model ${e}: ${t.message}`)}),C=Ht();for(let[e,t]of Object.entries(Ae)){let n=t.traits?.useApi;if(!n)continue;let r=typeof n==="object"?n:{},s=r.uri||t.table||e.toLowerCase()+"s",o=r.routes||["index","show","store","update","destroy"],i=t.table||s,c=Fe(t),p=ot(t),d=Ee(s,r.prefix),u=Ue(t.attributes,p),{read:f,write:R,declared:P}=Le(n);if(["store","update","destroy"].some((h)=>o.includes(h))&&P&&R.length===0)oe.warn(`[orm] ${e}: registering UNAUTHENTICATED mutating routes at ${d} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((h)=>o.includes(h))&&P&&f.length===0)oe.debug(`[orm] ${e}: registering public read routes at ${d} (declared \`middleware.read: []\`)`);let j=!!at(t),E=j&&!f.includes("auth")?["auth",...f]:f,q=(h,a=E)=>{let l=h;for(let g of a)if(l&&typeof l.middleware==="function")l=l.middleware(g);return l};if(o.includes("index")&&!G("GET",d))q(L.get(d,async(h)=>{try{let a=new URL(h.url),{page:l,perPage:g,offset:w}=We(a.searchParams),y=a.searchParams.get("sort"),b=C.selectFrom(i);b=Je(b,y,u);let B=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[D,N]of a.searchParams.entries()){if(B.has(D)||!N)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(D))continue;let V=u.get(D);if(V)b=b.where(V,"=",N)}let A=a.searchParams.get("search");if(A&&c.length>0){let D=c.slice(0,5);b=b.where((N)=>{for(let V of D)N=N.orWhere(T(V),"like",`%${A}%`);return N})}let _=a.searchParams.get("fields");if(_){let D=_.split(",").map((N)=>N.trim()).filter((N)=>/^[a-z_][a-z0-9_]*$/i.test(N)).map((N)=>T(N));if(D.length>0)b=b.select(D)}let I=!!t.traits?.useSoftDeletes,k=a.searchParams.get("withTrashed")==="true",U=a.searchParams.get("onlyTrashed")==="true";if(I&&!k)b=U?b.whereNotNull("deleted_at"):b.whereNull("deleted_at");let O=j?await ee(t,await Y(h),h):{enforced:!1,value:null,field:"",bypass:!1};if(O.enforced&&!O.bypass){if(O.value==null||Array.isArray(O.value)&&O.value.length===0){let D=Se(a,l,g,0,!1,void 0);return new Response(JSON.stringify({data:[],...D,meta:le(a,l,g,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}b=Array.isArray(O.value)?b.where(O.field,"in",O.value):b.where(O.field,"=",O.value)}let J=await b.limit(g+1).offset(w).get()||[],H=J.length>g,ne=(H?J.slice(0,g):J).map((D)=>K(se(D,t),p)),xe=a.searchParams.get("include");if(xe)ne=await et(ne,t,xe,Ae);let yt=a.searchParams.get("with_count")==="true",X;if(yt)try{let D=C.selectFrom(i);if(O.enforced&&!O.bypass&&O.value!=null)D=Array.isArray(O.value)?D.where(O.field,"in",O.value):D.where(O.field,"=",O.value);let N=await D.count(),V=typeof N==="number"?N:Number(N?.count??N);if(Number.isFinite(V))X=V}catch{}let ae={"Content-Type":"application/json"};if(X!==void 0&&!Number.isNaN(X))ae["X-Total-Count"]=String(X);ae["Cache-Control"]=O.enforced&&!O.bypass?"private, no-store":"public, max-age=15, must-revalidate",ae.Vary="Authorization";let wt=Se(a,l,g,ne.length,H,X);return new Response(JSON.stringify({data:ne,...wt,meta:le(a,l,g,ne.length,H,X)}),{status:200,headers:ae})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to fetch ${s}`,detail:String(a)},500)}}));if(o.includes("show")&&!G("GET",`${d}/{id}`))q(L.get(`${d}/{id}`,async(h)=>{try{let a=fe(h.params?.id);if(a==null)return m({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return m({error:`${e} not found`},404);let g=new URL(h.url);if(t.traits?.useSoftDeletes&&l.deleted_at&&g.searchParams.get("withTrashed")!=="true")return m({error:`${e} not found`},404);let w=j?await ee(t,await Y(h),h):{enforced:!1,value:null,field:"",bypass:!1};if(w.enforced&&!w.bypass){if(w.value==null||!re(l[w.field],w.value))return m({error:`${e} not found`},404)}let y=K(se(l,t),p),b=g.searchParams.get("include");if(b){let[k]=await et([y],t,b,Ae);y=k}let B=y?.updated_at||y?.created_at,A=B?`W/"${y.id}-${String(B)}"`:void 0,_=h.headers?.get?.("if-none-match");if(A&&_&&_===A)return new Response(null,{status:304,headers:{ETag:A}});let I={"Content-Type":"application/json"};if(A)I.ETag=A;return I["Cache-Control"]=w.enforced&&!w.bypass?"private, no-store":"public, max-age=30, must-revalidate",I.Vary="Authorization",new Response(JSON.stringify({data:y}),{status:200,headers:I})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to fetch ${e}`,detail:String(a)},500)}}));if(o.includes("store")&&!G("POST",d))q(L.post(d,async(h)=>{try{let a=await Te(h),l=be(a,p),g=we(l,c),w=await Y(h);if(w){let k=await rt(t,"creating",w,h);for(let[U,O]of Object.entries(k))if(O!==void 0&&O!==null&&g[U]===void 0)g[U]=O}let y=await ee(t,w,h);if(y.enforced&&!y.bypass){if(!w)return m({error:"Auth required"},401);let k=Me(g,y.field,y.value);if(k.error)return m({error:k.error},403);g=k.data}if(Object.keys(g).length===0)return m({error:"No fillable fields provided"},422);let b=Oe(g,t,"creating");if(!b.valid)return m({success:!1,message:"Validation failed",errors:b.errors},422);if(t.traits?.useTimestamps!==!1){let k=new Date().toISOString();g.created_at=k,g.updated_at=k}let B=await tt(g,t),A=ye(nt(B,t)),_=await C.insertInto(i).values(A).execute(),I=A;try{let k=_?.lastInsertRowid??_?.insertId??_;if(k){let U=await C.selectFrom(i).where({id:k}).executeTakeFirst();if(U)I=U}}catch{}return m({data:K(se(I,t),p)},201)}catch(a){let{status:l,body:g}=me(a,e,"create");return m(g,l)}}),R);if(o.includes("update")){let h=async(a)=>{try{let l=fe(a.params?.id);if(l==null)return m({error:"Invalid ID parameter"},400);let g=await Te(a),w=be(g,p),y=we(w,c),b=await Y(a);if(b){let O=await rt(t,"updating",b,a);for(let[J,H]of Object.entries(O))if(H!==void 0&&H!==null&&y[J]===void 0)y[J]=H}if(Object.keys(y).length===0)return m({error:"No fillable fields provided"},422);let B=Oe(y,t,"updating");if(!B.valid)return m({success:!1,message:"Validation failed",errors:B.errors},422);let A=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(!A)return m({error:`${e} not found`},404);let _=await ee(t,b,a);if(_.enforced&&!_.bypass){if(!b)return m({error:"Auth required"},401);let O=A[_.field];if(!re(O,_.value))return m({error:`Not your ${e}`},403);let J=Object.keys(y).find((H)=>T(H)===T(_.field));if(J!==void 0&&!re(y[J],_.value))return m({error:`Cannot reassign ${e} ownership`},403)}if(t.traits?.useTimestamps!==!1)y.updated_at=new Date().toISOString();let I=await tt(y,t),k=ye(nt(I,t));await C.updateTable(i).set(k).where({id:l}).execute();let U={...A,...k};try{let O=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(O)U=O}catch{}return m({data:K(se(U,t),p)})}catch(l){let{status:g,body:w}=me(l,e,"update");return m(w,g)}};if(!G("PUT",`${d}/{id}`))q(L.put(`${d}/{id}`,h),R);if(!G("PATCH",`${d}/{id}`))q(L.patch(`${d}/{id}`,h),R)}let x=!!t.traits?.useSoftDeletes;if(o.includes("destroy")&&!G("DELETE",`${d}/{id}`))q(L.delete(`${d}/{id}`,async(h)=>{try{let a=fe(h.params?.id);if(a==null)return m({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return m({error:`${e} not found`},404);let g=await Y(h),w=await ee(t,g,h);if(w.enforced&&!w.bypass){if(!g)return m({error:"Auth required"},401);let y=l[w.field];if(!re(y,w.value))return m({error:`Not your ${e}`},403)}if(x){let y=new Date().toISOString();await C.updateTable(i).set({deleted_at:y,updated_at:y}).where({id:a}).execute()}else await C.deleteFrom(i).where({id:a}).execute();return new Response(null,{status:204})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to delete ${e}`,detail:String(a)},500)}}),R);if(o.includes("destroy")&&!G("POST",`${d}/bulk-delete`))q(L.post(`${d}/bulk-delete`,async(h)=>{try{let l=(await Te(h))?.ids;if(!Array.isArray(l)||l.length===0)return m({error:"An array of IDs is required"},422);if(l.length>100)return m({error:"Cannot delete more than 100 records at once"},422);let g=[],w=[];for(let A of l){let _=fe(A);if(_!=null)g.push(_);else w.push(A)}if(w.length>0)return m({error:"Invalid IDs in batch",invalid:w},422);let y=await Y(h),b=await ee(t,y,h);if(b.enforced&&!b.bypass){if(!y)return m({error:"Auth required"},401);if(b.value==null)return m({error:"Caller has no ownership identity"},403);let A=await C.selectFrom(i).select(["id",b.field]).execute(),_=new Set(A.filter((k)=>re(k[b.field],b.value)).map((k)=>String(k.id))),I=g.filter((k)=>!_.has(String(k)));if(I.length>0)return m({error:`Cannot delete ${e} you don't own`,ids:I},403)}let B=new Date().toISOString();for(let A of g)if(x)await C.updateTable(i).set({deleted_at:B,updated_at:B}).where({id:A}).execute();else await C.deleteFrom(i).where({id:A}).execute();return m({message:`Successfully deleted ${g.length} ${s}`})}catch(a){if(a instanceof z){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return m(l,a.status||400)}return m({error:`Failed to bulk delete ${s}`,detail:String(a)},500)}}),R)}ct=L});var dt={};ce(dt,{default:()=>ct});var lt=Z(async()=>{await ut()});class Pe{data;status;headers;isOk;constructor(e,t,n,r){this.data=e;this.status=t;this.headers=n;this.isOk=r}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 _e{defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData=!1;customHeaders={};attachments=[];isMultipart=!1;digestAuth;withQueryParams(e){return this.queryParams=e,this}withHeaders(e){return this.customHeaders={...this.customHeaders,...e},this}accept(e){return this.defaultHeaders.Accept=e,this}acceptJson(){return this.accept("application/json")}withToken(e){return this.customHeaders.Authorization=`Bearer ${e}`,this}withBasicAuth(e,t){let n=btoa(`${e}:${t}`);return this.customHeaders.Authorization=`Basic ${n}`,this}withDigestAuth(e,t){return this.digestAuth={username:e,password:t},this}withBody(e){return this.bodyData=e,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach(e,t,n,r){let s=typeof t==="string"?new Blob([t],{type:r?.["Content-Type"]||"text/plain"}):t;return this.attachments.push({name:e,content:s,filename:n,headers:r}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams(e){if(!this.queryParams)return e;let t=new URLSearchParams;Object.entries(this.queryParams).forEach(([s,o])=>{if(o!=null)t.append(s,String(o))});let n=t.toString();if(!n)return e;let r=e.includes("?");return e+(r?"&":"?")+n}async formatBody(e){let t=e||this.bodyData;if(this.isMultipart){let n=new FormData;if(t)Object.entries(t).forEach(([r,s])=>{n.append(r,String(s))});for(let r of this.attachments)if(r.headers){let s=r.content instanceof Blob?new Blob([r.content],{type:r.headers["Content-Type"]}):r.content;n.append(r.name,s,r.filename)}else n.append(r.name,r.content,r.filename);return n}if(this.isFormData&&t){let n=new URLSearchParams;return Object.entries(t).forEach(([r,s])=>{if(s!=null)n.append(r,String(s))}),n.toString()}return t?JSON.stringify(t):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(e,t,n,r){if(e.status!==401||!this.digestAuth)return e;let s=e.headers.get("WWW-Authenticate");if(!s?.startsWith("Digest "))return e;let o=s.substring(7).split(",").reduce((P,S)=>{let[v,j]=S.trim().split("=");if(v)P[v]=j?.replace(/["']/g,"")??"";return P},{}),i=await this.generateMD5(`${this.digestAuth.username}:${o.realm}:${this.digestAuth.password}`),c=await this.generateMD5(`${n}:${t}`),p="00000001",d=await this.generateMD5(Date.now().toString()).then((P)=>P.substring(0,8)),u=await this.generateMD5(`${i}:${o.nonce}:${p}:${d}:${o.qop}:${c}`),f={username:`"${this.digestAuth.username}"`,realm:`"${o.realm}"`,nonce:`"${o.nonce}"`,uri:`"${t}"`,algorithm:o.algorithm?`"${o.algorithm}"`:void 0,qop:`"${o.qop}"`,nc:p,cnonce:`"${d}"`,response:`"${u}"`,opaque:o.opaque?`"${o.opaque}"`:void 0},R=Object.entries(f).filter(([P,S])=>S!==void 0).map(([P,S])=>`${P}=${S}`).join(", ");return this.customHeaders.Authorization=`Digest ${R}`,fetch(t,{method:n,headers:this.getHeaders(),body:r?this.formatBody(r):void 0})}async generateMD5(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map((o)=>o.toString(16).padStart(2,"0")).join("")}async request(e,t,n){let r=this.addQueryParams(e),s=await this.formatBody(n),o=await fetch(r,{method:t,headers:this.getHeaders(),body:s});if(this.digestAuth)o=await this.handleDigestAuth(o,r,t,n);let i=await o.json();return this.resetState(),new Pe(i,o.status,o.headers,o.ok)}async get(e){return this.request(e,"GET")}async post(e,t){return this.request(e,"POST",t)}async put(e,t){return this.request(e,"PUT",t)}async patch(e,t){return this.request(e,"PATCH",t)}async delete(e){return this.request(e,"DELETE")}}var Yt=new _e;ge();import{path as te}from"@stacksjs/path";function ft(e){if(!e||typeof e!=="object")return{type:"string"};let t=e,n=Array.isArray(t.rules)?t.rules:[],r=(u)=>n.find((f)=>f.name===u),s=(u,f)=>{let R=r(u)?.params?.[f];return typeof R==="number"?R:void 0},o=t.name??t._type??"string",i={type:o==="enum"?"string":o},c=s("min","min")??(typeof t._min==="number"?t._min:void 0),p=s("max","max")??(typeof t._max==="number"?t._max:void 0);if(c!==void 0)i[o==="string"?"minLength":"minimum"]=c;if(p!==void 0)i[o==="string"?"maxLength":"maximum"]=p;if(r("email")||t._email)i.format="email";if(r("url")||t._url)i.format="uri";if(r("uuid")||t._uuid)i.format="uuid";let d=Array.isArray(t.allowedValues)?t.allowedValues:Array.isArray(t._enum)?t._enum:null;if(d)i.enum=d;return i}function zt(e){if(!e||typeof e!=="object")return!1;let t=e;return Boolean(t.isRequired??t._required)}function pt(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Vt(e){let t={id:{type:"integer"}},n=["id"];if(e.traits?.useUuid)t.uuid={type:"string",format:"uuid"},n.push("uuid");for(let[r,s]of Object.entries(e.attributes??{})){if(s.hidden===!0)continue;let o=pt(r);if(t[o]=ft(s.validation?.rule),s.required===!0)n.push(o)}for(let r of e.belongsTo??[]){if(typeof r!=="string"||!r.trim())continue;let s=`${pt(r.trim())}_id`;t[s]??={type:"integer"}}if(e.traits?.useTimestamps!==!1)t.created_at={type:"string",format:"date-time"},t.updated_at={type:"string",format:"date-time"};if(e.traits?.useSoftDeletes)t.deleted_at={type:"string",format:"date-time",nullable:!0};return{type:"object",properties:t,required:[...new Set(n)]}}function Qt(e){let t=e.traits?.useApi;if(!t||typeof t!=="object"||!t.uri)return null;let n=String(t.prefix||"").replace(/^\/+|\/+$/g,""),r=String(t.uri).replace(/^\/+|\/+$/g,"");return`/api/${n?`${n}/`:""}${r}`}function Gt(e,t){let n={...t},r=e?.responses;if(r&&typeof r==="object")for(let[o,i]of Object.entries(r)){let c=i;if(!c||typeof c!=="object"||typeof c.description!=="string")continue;n[String(o)]={description:c.description,...c.schema&&typeof c.schema==="object"?{content:{"application/json":{schema:c.schema}}}:{}}}let s=e?.responseHeaders;if(s&&typeof s==="object"){let o={};for(let[i,c]of Object.entries(s)){let p=c;if(!p||typeof p!=="object"||typeof p.description!=="string")continue;o[i]={description:p.description,...p.schema&&typeof p.schema==="object"?{schema:p.schema}:{}}}if(Object.keys(o).length>0)for(let i of Object.keys(n))n[i]={...n[i],headers:o}}return n}async function Xt(e){if(typeof e!=="string"||!e||e.includes(".."))return null;try{let{path:t}=await import("@stacksjs/path"),n=[t.appPath(`${e}.ts`),t.storagePath(`framework/defaults/app/${e}.ts`)];for(let r of n)try{if(!await Bun.file(r).exists())continue;let i=(await import(r)).default;return i&&typeof i==="object"?i:null}catch{}}catch{}return null}async function yn(e={}){let t=e.portable??!0,{listRegisteredRoutes:n}=await import("@stacksjs/router");try{let{loadRoutes:u}=await import("@stacksjs/router"),{default:f}=await import(te.appPath("Routes.ts"));await u(f)}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${f}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${f}`)}try{try{await import("@stacksjs/orm/routes")}catch{await lt().then(() => dt)}}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${f}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${f}`)}let r={};try{let f;try{f=await import("@stacksjs/orm/model-registry")}catch{f=await Promise.resolve().then(() => ($e(),Xe))}r=await f.loadModelRegistry({defaultsRoot:te.storagePath("framework/defaults/app/Models"),userRoot:te.projectPath("app/Models")})}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${f}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${f}`)}let s=(u)=>u.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),o=[...n()].map((u)=>({route:u,oasPath:s(u.path),method:u.method.toLowerCase()})).sort((u,f)=>{if(u.oasPath!==f.oasPath)return u.oasPath<f.oasPath?-1:1;return u.method<f.method?-1:u.method>f.method?1:0});if(t&&o.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 i="Stacks API";if(!t)try{let{config:u}=await import("@stacksjs/config");if(u.app?.name)i=`${u.app.name} API`}catch{}let c={openapi:"3.0.0",info:{title:i,version:"1.0.0"},paths:{},components:{schemas:{}}},p=Object.values(r).map((u)=>({name:String(u.name),path:Qt(u),schema:Vt(u)})).filter((u)=>u.path!==null).sort((u,f)=>u.name<f.name?-1:u.name>f.name?1:0);for(let u of p)c.components.schemas[u.name]=u.schema;let d=new Set;for(let{route:u,oasPath:f,method:R}of o){if(!c.paths[f])c.paths[f]={};let P=[];for(let a of u.path.matchAll(/\{(\w+)\}/g))if(a[1])P.push(a[1]);for(let a of u.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(a[1])P.push(a[1]);let S=u.name??`${R}_${f.replace(/[^a-z0-9]/gi,"_")}`,v=S;if(d.has(v)){v=`${S}_${R}`;let a=2;while(d.has(v))v=`${S}_${R}_${a++}`}d.add(v);let j={summary:u.name??u.path,operationId:v,parameters:P.map((a)=>({name:a,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"}}},E=p.find((a)=>f===a.path||f===`${a.path}/{id}`);if(E){let a=f===E.path&&R==="get"?{type:"array",items:E.schema}:E.schema;if(j.responses[200].content={"application/json":{schema:{type:"object",properties:{data:a},required:["data"]}}},R==="post"&&f===E.path)j.responses[201]={...j.responses[200],description:"Created"},delete j.responses[200]}let q=u.action??(u.handler?await Xt(u.handler):null),x=q&&typeof q.validations==="object"&&q.validations!==null?q.validations:null;j.responses=Gt(q,j.responses);let h=q?.requestHeaders;if(h&&typeof h==="object")for(let[a,l]of Object.entries(h)){let g=l;if(!g||typeof g!=="object"||typeof g.description!=="string")continue;j.parameters?.push({name:a,in:"header",description:g.description,required:g.required===!0,schema:g.schema&&typeof g.schema==="object"?g.schema:{type:"string"}})}if(x&&Object.keys(x).length>0){let a=Object.entries(x).map(([l,g])=>{let w=g?.rule;return{field:l,schema:ft(w),required:zt(w)}});if(R==="get"||R==="head"||R==="delete"){let l=new Set(P);for(let{field:g,schema:w,required:y}of a){if(l.has(g))continue;j.parameters?.push({name:g,in:"query",required:y,schema:w})}}else{let l={type:"object",properties:{},required:[]},g=l.properties,w=l.required;for(let y of a)if(g[y.field]=y.schema,y.required)w.push(y.field);if(w.length===0)delete l.required;j.requestBody={required:w.length>0,content:{"application/json":{schema:l}}}}}c.paths[f][R]=j}if(e.write!==!1){await Bun.write(te.frameworkPath("api/openapi.json"),JSON.stringify(c,null,2));let{renderOpenApiTypes:u}=await Promise.resolve().then(() => (ue(),qe)),{renderApiClient:f}=await Promise.resolve().then(() => (ge(),Ne));await Bun.write(te.frameworkPath("api/api-types.ts"),u(c)),await Bun.write(te.frameworkPath("api/client.ts"),f(c,{name:c.info.title}))}return c}ue();class F{static instance=new F;isMissing(){return!0}}class ie{data;constructor(e){this.data=e}}class gt{condition;value;defaultValue;constructor(e,t,n=new F){this.condition=e;this.value=t;this.defaultValue=n}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class ht{resource;additional={};request;static wrap="data";static additionalMeta={};constructor(e){this.resource=e}withRequest(e){return this.request=e,this}withAdditional(e){return this.additional={...this.additional,...e},this}resolve(e){let t=this.toArray(e||this.request);return this.filterAndResolve(t)}toResponse(e){let t=this.resolve(e),n=this.constructor.wrap;if(n)return{[n]:t,...this.additional};return{...t,...this.additional}}toJson(e){return JSON.stringify(this.toResponse(e))}toJSON(){return this.toResponse()}static collection(e){return new je(e,this)}when(e,t,n){if(typeof e==="function"?e():e)return typeof t==="function"?t():t;return n!==void 0?n:F.instance}whenNotNull(e,t){if(e===null||e===void 0)return F.instance;return t?t(e):e}whenLoaded(e,t,n){let r=this.resource;if(!((e in r)&&r[e]!==void 0))return n!==void 0?n:F.instance;if(t!==void 0)return typeof t==="function"?t():t;return r[e]}whenCounted(e,t){let n=this.resource,r=`${e}_count`;if(r in n)return n[r];return t!==void 0?t:F.instance}merge(e){return new ie(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return F.instance;let r=typeof t==="function"?t():t;return new ie(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=ht.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,s]of Object.entries(e)){if(s instanceof F)continue;if(s instanceof ie){Object.assign(n,this.filterAndResolve(s.data,t+1));continue}if(s instanceof gt){let o=s.resolve();if(!(o instanceof F))n[r]=o;continue}if(s!==null&&typeof s==="object"&&!Array.isArray(s)&&!(s instanceof Date)){n[r]=this.filterAndResolve(s,t+1);continue}if(Array.isArray(s)){n[r]=s.filter((o)=>!(o instanceof F)).map((o)=>{if(o instanceof ie)return o.data;if(o!==null&&typeof o==="object"&&!(o instanceof Date))return this.filterAndResolve(o,t+1);return o});continue}n[r]=s}return n}static withoutWrapping(){this.wrap=null}static wrapWith(e){this.wrap=e}}class je{resources;ResourceClass;additional={};request;static wrap="data";constructor(e,t){this.resources=e,this.ResourceClass=t}withRequest(e){return this.request=e,this}withAdditional(e){return this.additional={...this.additional,...e},this}resolve(e){let t=e||this.request;return this.resources.map((n)=>{let r=new this.ResourceClass(n);if(t)r.withRequest(t);return r.resolve(t)})}toResponse(e){let t=this.resolve(e),n=this.constructor.wrap;if(n)return{[n]:t,...this.additional};return{data:t,...this.additional}}toJson(e){return JSON.stringify(this.toResponse(e))}count(){return this.resources.length}isEmpty(){return this.resources.length===0}isNotEmpty(){return this.resources.length>0}}class mt extends je{meta;links;constructor(e,t){super(e.data,t);this.meta=e.meta,this.links=e.links}static fromPagination(e,t,n){let{currentPage:r,perPage:s,total:o,baseUrl:i=""}=n,c=Math.ceil(o/s),p=o>0?(r-1)*s+1:null,d=o>0?Math.min(r*s,o):null;return new mt({data:e,meta:{current_page:r,from:p,last_page:c,per_page:s,to:d,total:o},links:{first:`${i}?page=1`,last:`${i}?page=${c}`,prev:r>1?`${i}?page=${r-1}`:null,next:r<c?`${i}?page=${r+1}`:null}},t)}toResponse(e){return{data:this.resolve(e),meta:this.meta,links:this.links,...this.additional}}}function bn(e,t){let n=t(e);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}function Rn(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{gt as ConditionalValue,ht as JsonResource,ie as MergeValue,F as MissingValue,mt as PaginatedResourceCollection,je as ResourceCollection,Rn as collection,Gt as describedResponses,Yt as fetcher,yn as generateOpenApi,De as methodName,Vt as modelDefinitionToSchema,vt as renderApiClient,Tt as renderOpenApiTypes,bn as resource,zt as ruleIsRequired,ft as ruleToSchema,M as schemaType};
|
|
139
|
+
`}var jt;var ge=Z(()=>{ue();jt=["get","put","post","delete","options","head","patch"]});function vt(e){let t=e;return t?.code==="SQLITE_CONSTRAINT_UNIQUE"||t?.code==="SQLITE_CONSTRAINT"||t?.code==="23505"||t?.errno===1062||/unique|duplicate/i.test(t?.message??"")}function he(e,t,n){let r=e;if(e instanceof Error&&typeof r.status==="number"&&Number.isInteger(r.status)&&r.status>=400&&r.status<600){let s={error:e.message};if(r.details!==void 0)s.details=r.details;return{status:r.status,body:s}}if(vt(e))return{status:409,body:{error:`${t} already exists`}};return{status:500,body:{error:`Failed to ${n} ${t}`,detail:String(e)}}}function T(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function ye(e){let t={};for(let[n,r]of Object.entries(e))t[T(n)]=r;return t}function Ee(e,t){let n=String(t||"").replace(/^\/+|\/+$/g,""),r=String(e).replace(/^\/+/,"");return`/api/${n?`${n}/`:""}${r}`}function Be(e){if(!e)return null;let t=e.attributes??{};if(Object.prototype.hasOwnProperty.call(t,"teamId")||Object.prototype.hasOwnProperty.call(t,"team_id"))return"team_id";return e.belongsTo?.some((n)=>n==="Team")?"team_id":null}function Fe(e,t,n){let r=Object.keys(e).find((o)=>T(o)===T(t));if(Array.isArray(n)){if(r===void 0)return{data:e,error:"Ownership value is required"};if(!n.some((o)=>String(o)===String(e[r])))return{data:e,error:"Ownership value is not available to this caller"};return{data:{...e,[t]:e[r]}}}if(n===null||n===void 0)return{data:e,error:"Caller has no ownership identity"};let s={...e};for(let o of Object.keys(s))if(T(o)===T(t))delete s[o];return s[t]=n,{data:s}}function Me(e){if(!e)return[];let t=Object.entries(e.attributes??{}).filter(([,n])=>n?.fillable===!0).map(([n])=>n);for(let n of e.belongsTo??[]){if(typeof n!=="string"||!n.trim())continue;let r=T(n.trim()).split("_").filter(Boolean);if(r.length===0)continue;let s=`${r[0]}${r.slice(1).map((o)=>`${o[0]?.toUpperCase()}${o.slice(1)}`).join("")}Id`;t.push(s)}return[...new Set(t)]}function we(e,t){if(!e||t.length===0)return{};let n={};for(let r of t){if(r in e){n[r]=e[r];continue}let s=T(r);if(s!==r&&s in e)n[r]=e[s]}return n}function qt(e,t){if(e?.name!=="date"||t instanceof Date||typeof t!=="string")return t;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return t;let r=Number(n[1]),s=Number(n[2]),o=Number(n[3]),i=new Date(Date.UTC(r,s-1,o));if(i.getUTCFullYear()!==r||i.getUTCMonth()!==s-1||i.getUTCDate()!==o)return t;return i}function be(e,t){if(!t.length)return e;let n={...e};for(let r of t)delete n[r],delete n[T(r)];return n}function K(e,t){if(!e||t.length===0)return e;let n={...e};for(let r of t)delete n[r],delete n[T(r)];return n}function Ue(e,t){let n=new Map;for(let r of[...Object.keys(e??{}),...Nt]){let s=T(r);if(!/^\w+$/.test(s))continue;n.set(r,s),n.set(s,s)}for(let r of t)n.delete(r),n.delete(T(r));return n}function Je(e,t,n){if(!t)return e;let r=String(t).split(",").map((o)=>o.trim()).filter(Boolean),s=e;for(let o of r){let i=o.startsWith("-"),c=i?o.slice(1):o;if(!/^\w+$/.test(c))continue;let p=n.get(c);if(!p)continue;s=s.orderBy(p,i?"desc":"asc")}return s}function It(e){try{return JSON.parse(e)}catch{return e}}function Et(e){try{return JSON.parse(e)}catch{return[]}}function Re(e,t,n){if(!e||typeof e!=="object"||!t||Object.keys(t).length===0)return e;let r={...e};for(let[s,o]of Object.entries(t)){let i=typeof o==="string"?Ct[o]:o;if(!i||typeof i[n]!=="function")continue;if(Object.prototype.hasOwnProperty.call(r,s))r[s]=i[n](r[s]);let c=T(s);if(c!==s&&Object.prototype.hasOwnProperty.call(r,c))r[c]=i[n](r[c])}return r}function ke(e,t,n){let r=t?.attributes??{},s={};for(let[o,i]of Object.entries(r)){let c=i?.validation?.rule;if(!c||typeof c.validate!=="function")continue;let p=Object.prototype.hasOwnProperty.call(e,o);if(!p&&n==="updating")continue;let d=i!==null&&typeof i==="object"&&Object.prototype.hasOwnProperty.call(i,"default"),u=p?e[o]:d?i.default:void 0,f=qt(c,u),R=c.validate(f);if(!R?.valid&&Array.isArray(R?.errors)&&R.errors.length>0)s[o]=R.errors.map((_)=>i?.validation?.message?.[_?.code]??_?.message??"invalid")}return Object.keys(s).length===0?{valid:!0}:{valid:!1,errors:s}}function He(e,t,n){let r=Ce(n);return e.find((s)=>s.method===t&&Ce(String(s.path??""))===r)}function Ce(e){return e.replace(/\{[^}]*\}/g,"{}").replace(/:[^/]+/g,"{}")}function me(e){if(Array.isArray(e))return e.filter((t)=>typeof t==="string"&&t.length>0);return typeof e==="string"&&e?[e]:[]}function Le(e){let t=typeof e==="object"&&e!==null&&"middleware"in e,n=e?.middleware;if(!t)return{read:["auth"],write:["auth"],declared:!1};if(n&&typeof n==="object"&&!Array.isArray(n)){let s=n;return{read:"read"in s?me(s.read):["auth"],write:"write"in s?me(s.write):["auth"],declared:!0}}let r=me(n);return{read:r,write:r,declared:!0}}function Qe(e){let t=Number.parseInt(e.get("page")||String(1),10),n=Number.isFinite(t)?Math.max(1,t):1,r=Number.parseInt(e.get("per_page")||String(Ie),10),s=Math.min(Number.isFinite(r)?Math.max(1,r):Ie,Bt);return{page:n,perPage:s,offset:(n-1)*s}}function de(e,t){let n=new URL(e.toString());return n.searchParams.set("page",String(t)),`${n.pathname}${n.search}`}function le(e,t,n,r,s,o){let i=(t-1)*n,c=r===0,p={page:t,per_page:n,from:c?null:i+1,to:c?null:i+r,has_more_pages:s,prev_page_url:t>1?de(e,t-1):null,next_page_url:s?de(e,t+1):null};if(o!==void 0&&!Number.isNaN(o)){let d=Math.max(1,Math.ceil(o/n));p.total=o,p.last_page=d,p.first_page_url=de(e,1),p.last_page_url=de(e,d)}return p}function Oe(e,t,n,r,s,o){let{page:i,...c}=le(e,t,n,r,s,o);return{current_page:i,...c}}var Nt,Ct,Ie=15,Bt=100;var We=Z(()=>{Nt=["id","uuid","created_at","updated_at","deleted_at"];Ct={string:{get:(e)=>e!=null?String(e):null,set:(e)=>e!=null?String(e):null},number:{get:(e)=>e!=null?Number(e):null,set:(e)=>e!=null?Number(e):null},integer:{get:(e)=>e!=null?Math.trunc(Number(e)):null,set:(e)=>e!=null?Math.trunc(Number(e)):null},float:{get:(e)=>e!=null?Number.parseFloat(String(e)):null,set:(e)=>e!=null?Number.parseFloat(String(e)):null},boolean:{get:(e)=>e===1||e==="1"||e===!0||e==="true",set:(e)=>e===!0||e===1||e==="1"||e==="true"?1:0},json:{get:(e)=>e==null?null:typeof e==="string"?It(e):e,set:(e)=>e==null?null:typeof e==="string"?e:JSON.stringify(e)},datetime:{get:(e)=>e?new Date(e):null,set:(e)=>e instanceof Date?e.toISOString():e},date:{get:(e)=>e?new Date(e):null,set:(e)=>e instanceof Date?e.toISOString().split("T")[0]:e},array:{get:(e)=>e==null?[]:Array.isArray(e)?e:typeof e==="string"?Et(e):[],set:(e)=>e==null?null:Array.isArray(e)?JSON.stringify(e):e}}});var Xe={};ce(Xe,{loadModelRegistry:()=>Se,modelFiles:()=>Ge});import{readdirSync as Ft}from"fs";import{basename as Mt,extname as Ve,join as Ut}from"path";function Ge(e){let t=[],n=(r)=>{let s;try{s=Ft(r,{withFileTypes:!0})}catch{return}for(let o of s){let i=Ut(r,o.name);if(o.isDirectory()){n(i);continue}if(![".ts",".js"].includes(Ve(o.name)))continue;if(o.name.startsWith(".")||o.name.startsWith("index"))continue;t.push(i)}};return n(e),t.sort()}async function ze(e,t,n){for(let r of Ge(e))try{let s=Ve(r),o=await import(`${r}?t=${Date.now()}`),i=o.default??o,c=i.name??Mt(r,s);t[c]={...i,name:c}}catch(s){n?.(r,s)}}async function Se(e){let t={};return await ze(e.defaultsRoot,t,e.onImportError),await ze(e.userRoot,t,e.onImportError),t}var $e=()=>{};import{route as L}from"@stacksjs/router";import{env as V}from"@stacksjs/env";import{projectPath as st,storagePath as Jt}from"@stacksjs/path";import{createQueryBuilder as Ht,defaultConfig as Ze,setConfig as Ke}from"@stacksjs/query-builder";import{HttpError as W}from"@stacksjs/error-handling";import{log as oe}from"@stacksjs/logging";function G(e,t){let n=He(L.routes,e,t);if(!n)return!1;let r=String(n.path??"");return oe.info(`[orm] Skipping generated ${e} ${t} - already defined${r&&r!==t?` as ${r}`:""}.`),!0}function ot(e){if(!e.attributes)return[];return Object.entries(e.attributes).filter(([t,n])=>n.hidden===!0).map(([t])=>t)}function Ye(e){if(e.endsWith("y")&&!/[aeiou]y$/i.test(e))return`${e.slice(0,-1)}ies`;if(/(?:s|x|z|ch|sh)$/i.test(e))return`${e}es`;return`${e}s`}async function et(e,t,n,r){if(!e.length)return e;let s=n.split(",").map((d)=>d.trim()).filter(Boolean);if(!s.length)return e;let o=Array.isArray(t.belongsTo)?t.belongsTo:[],i=Array.isArray(t.hasMany)?t.hasMany:[],c=Array.isArray(t.hasOne)?t.hasOne:[],p=new Map;for(let d of o)p.set(T(d),{kind:"belongsTo",modelName:d});for(let d of c)p.set(T(d),{kind:"hasOne",modelName:d});for(let d of i)p.set(Ye(T(d)),{kind:"hasMany",modelName:d});for(let d of s){let u=p.get(d);if(!u)continue;let f=r[u.modelName];if(!f)continue;let R=f.table||Ye(T(u.modelName)),_=ot(f),O=(D)=>K(se(D,f),_);if(u.kind==="belongsTo"||u.kind==="hasOne"){let D=`${T(u.modelName)}_id`,j=[...new Set(e.map((x)=>x[D]).filter((x)=>x!=null))];if(!j.length){for(let x of e)x[d]=null;continue}let E=await C.selectFrom(R).whereIn("id",j).get(),v=new Map;for(let x of E??[])v.set(String(x.id),O(x));for(let x of e)x[d]=v.get(String(x[D]))??null}else{let D=String(t.name??""),j=`${T(D)}_id`,E=[...new Set(e.map((m)=>m.id).filter((m)=>m!=null))];if(!E.length){for(let m of e)m[d]=[];continue}let v=await C.selectFrom(R).whereIn(j,E).get(),x=new Map;for(let m of v??[]){let a=String(m[j]),l=x.get(a)??[];l.push(O(m)),x.set(a,l)}for(let m of e)m[d]=x.get(String(m.id))??[]}}return e}async function tt(e,t){let n=t?.set;if(!n||typeof n!=="object")return e;let r={...e};for(let[s,o]of Object.entries(n)){if(typeof o!=="function"||!(s in r))continue;try{r[s]=await o(r)}catch{}}return r}function nt(e,t){return Re(e,t?.casts,"set")}function se(e,t){return Re(e,t?.casts,"get")}function h(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})}async function Te(e){if(Number(e.headers?.get?.("content-length")??0)>pe)throw new W(413,`Request body exceeds ${pe}-byte limit`);if(e.jsonBody&&typeof e.jsonBody==="object")return e.jsonBody;if(e.formBody&&typeof e.formBody==="object")return e.formBody;try{let n=await e.clone().text();if(n.length>pe)throw new W(413,`Request body exceeds ${pe}-byte limit`);if(!n)return{};let r=JSON.parse(n);return r&&typeof r==="object"&&!Array.isArray(r)?r:{}}catch(n){if(n instanceof W)throw n;throw new W(400,`Invalid JSON body: ${n.message}`)}}function fe(e){if(e==null)return null;if(typeof e==="number")return Number.isFinite(e)&&e>0?e:null;if(typeof e==="string"){let t=e.trim();if(!t)return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)&&n>0?n:null}return t}return null}function it(e){let t=e.bearerToken;if(typeof t==="function"){let r=t.call(e);if(r)return r}let n=e.headers?.get?.("authorization")||e.headers?.get?.("Authorization")||"";if(typeof n==="string"&&n.startsWith("Bearer "))return n.substring(7);return null}async function Y(e){let t=e._authenticatedUser;if(t)return t;let n=it(e);if(!n)return null;try{let{Auth:r}=await import("@stacksjs/auth"),s=await r.getUserFromToken(n);if(s)e._authenticatedUser=s;return s||null}catch{return null}}function re(e,t){if(e==null||t==null)return!1;if(Array.isArray(t))return t.some((n)=>String(n)===String(e));return String(e)===String(t)}function Wt(e){let t=it(e),n=e.headers?.get?.("cookie")||"";return{bearerToken:()=>t,cookies:{get:(r)=>{for(let s of n.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()===r)return decodeURIComponent(s.slice(o+1).trim())}return null}}}}function at(e){if(e?.ownership)return e.ownership;let t=Be(e);if(!t)return null;return{field:t,resolve:async(n,r)=>{let{resolveAuthenticatedTeamId:s}=await import("@stacksjs/auth");return s(Wt(r))}}}async function ee(e,t,n){let r=at(e);if(!r||!r.field||typeof r.resolve!=="function")return{enforced:!1,value:null,field:"",bypass:!1};let s=typeof r.bypass==="function"?!!r.bypass(t,n):!1,o=null;try{o=await r.resolve(t,n)}catch{o=null}return{enforced:!0,value:o,field:String(r.field),bypass:s}}async function rt(e,t,n,r){let s=e?.authedFill?.[t];if(!s)return{};if(typeof s==="function")try{let o=await s(n,r);return o&&typeof o==="object"?o:{}}catch{return{}}if(typeof s==="object"){let o={};for(let[i,c]of Object.entries(s))try{o[i]=typeof c==="function"?await c(n,r):c}catch{}return o}return{}}var Lt,Ae,Qt,C,pe=1048576,ct;var ut=Z(async()=>{We();$e();Lt=st("config/qb.ts");try{let e=(await import(Lt)).default;Ke(e??Ze)}catch{oe.debug("[orm] No config/qb.ts override found - deriving config from DB_CONNECTION");let e=V.DB_CONNECTION||"sqlite";Ke({...Ze,dialect:e,database:e==="sqlite"?{database:V.DB_DATABASE_PATH||"database/stacks.sqlite"}:{database:V.DB_DATABASE||"stacks",host:V.DB_HOST||"127.0.0.1",port:V.DB_PORT||(e==="postgres"?5432:3306),username:V.DB_USERNAME||(e==="postgres"?"postgres":"root"),password:V.DB_PASSWORD||""}})}Ae=await Se({defaultsRoot:Jt("framework/defaults/app/Models"),userRoot:st("app/Models"),onImportError:(e,t)=>oe.warn(`[orm] Could not load model ${e}: ${t.message}`)}),Qt=Ht(),C=Qt;for(let[e,t]of Object.entries(Ae)){let n=t.traits?.useApi;if(!n)continue;let r=typeof n==="object"?n:{},s=r.uri||t.table||e.toLowerCase()+"s",o=r.routes||["index","show","store","update","destroy"],i=t.table||s,c=Me(t),p=ot(t),d=Ee(s,r.prefix),u=Ue(t.attributes,p),{read:f,write:R,declared:_}=Le(n);if(["store","update","destroy"].some((m)=>o.includes(m))&&_&&R.length===0)oe.warn(`[orm] ${e}: registering UNAUTHENTICATED mutating routes at ${d} (explicit \`middleware: []\` opt-out)`);if(["index","show"].some((m)=>o.includes(m))&&_&&f.length===0)oe.debug(`[orm] ${e}: registering public read routes at ${d} (declared \`middleware.read: []\`)`);let j=!!at(t),E=j&&!f.includes("auth")?["auth",...f]:f,v=(m,a=E)=>{let l=m;for(let g of a)if(l&&typeof l.middleware==="function")l=l.middleware(g);return l};if(o.includes("index")&&!G("GET",d))v(L.get(d,async(m)=>{try{let a=new URL(m.url),{page:l,perPage:g,offset:w}=Qe(a.searchParams),y=a.searchParams.get("sort"),b=C.selectFrom(i);b=Je(b,y,u);let B=new Set(["page","per_page","sort","fields","search","include","limit","offset","with_count","withTrashed","onlyTrashed"]);for(let[q,N]of a.searchParams.entries()){if(B.has(q)||!N)continue;if(!/^[a-z_][a-z0-9_]*$/i.test(q))continue;let z=u.get(q);if(z)b=b.where(z,"=",N)}let A=a.searchParams.get("search");if(A&&c.length>0){let q=c.slice(0,5);b=b.where((N)=>{for(let z of q)N=N.orWhere(T(z),"like",`%${A}%`);return N})}let P=a.searchParams.get("fields");if(P){let q=P.split(",").map((N)=>N.trim()).filter((N)=>/^[a-z_][a-z0-9_]*$/i.test(N)).map((N)=>T(N));if(q.length>0)b=b.select(q)}let I=!!t.traits?.useSoftDeletes,S=a.searchParams.get("withTrashed")==="true",U=a.searchParams.get("onlyTrashed")==="true";if(I&&!S)b=U?b.whereNotNull("deleted_at"):b.whereNull("deleted_at");let k=j?await ee(t,await Y(m),m):{enforced:!1,value:null,field:"",bypass:!1};if(k.enforced&&!k.bypass){if(k.value==null||Array.isArray(k.value)&&k.value.length===0){let q=Oe(a,l,g,0,!1,void 0);return new Response(JSON.stringify({data:[],...q,meta:le(a,l,g,0,!1,void 0)}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}b=Array.isArray(k.value)?b.where(k.field,"in",k.value):b.where(k.field,"=",k.value)}let J=await b.limit(g+1).offset(w).get()||[],H=J.length>g,ne=(H?J.slice(0,g):J).map((q)=>K(se(q,t),p)),xe=a.searchParams.get("include");if(xe)ne=await et(ne,t,xe,Ae);let yt=a.searchParams.get("with_count")==="true",X;if(yt)try{let q=C.selectFrom(i);if(k.enforced&&!k.bypass&&k.value!=null)q=Array.isArray(k.value)?q.where(k.field,"in",k.value):q.where(k.field,"=",k.value);let N=await q.count(),z=typeof N==="number"?N:Number(N?.count??N);if(Number.isFinite(z))X=z}catch{}let ae={"Content-Type":"application/json"};if(X!==void 0&&!Number.isNaN(X))ae["X-Total-Count"]=String(X);ae["Cache-Control"]=k.enforced&&!k.bypass?"private, no-store":"public, max-age=15, must-revalidate",ae.Vary="Authorization";let wt=Oe(a,l,g,ne.length,H,X);return new Response(JSON.stringify({data:ne,...wt,meta:le(a,l,g,ne.length,H,X)}),{status:200,headers:ae})}catch(a){if(a instanceof W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({error:`Failed to fetch ${s}`,detail:String(a)},500)}}));if(o.includes("show")&&!G("GET",`${d}/{id}`))v(L.get(`${d}/{id}`,async(m)=>{try{let a=fe(m.params?.id);if(a==null)return h({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return h({error:`${e} not found`},404);let g=new URL(m.url);if(t.traits?.useSoftDeletes&&l.deleted_at&&g.searchParams.get("withTrashed")!=="true")return h({error:`${e} not found`},404);let w=j?await ee(t,await Y(m),m):{enforced:!1,value:null,field:"",bypass:!1};if(w.enforced&&!w.bypass){if(w.value==null||!re(l[w.field],w.value))return h({error:`${e} not found`},404)}let y=K(se(l,t),p),b=g.searchParams.get("include");if(b){let[S]=await et([y],t,b,Ae);y=S}let B=y?.updated_at||y?.created_at,A=B?`W/"${y.id}-${String(B)}"`:void 0,P=m.headers?.get?.("if-none-match");if(A&&P&&P===A)return new Response(null,{status:304,headers:{ETag:A}});let I={"Content-Type":"application/json"};if(A)I.ETag=A;return I["Cache-Control"]=w.enforced&&!w.bypass?"private, no-store":"public, max-age=30, must-revalidate",I.Vary="Authorization",new Response(JSON.stringify({data:y}),{status:200,headers:I})}catch(a){if(a instanceof W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({error:`Failed to fetch ${e}`,detail:String(a)},500)}}));if(o.includes("store")&&!G("POST",d))v(L.post(d,async(m)=>{try{let a=await Te(m),l=be(a,p),g=we(l,c),w=await Y(m);if(w){let S=await rt(t,"creating",w,m);for(let[U,k]of Object.entries(S))if(k!==void 0&&k!==null&&g[U]===void 0)g[U]=k}let y=await ee(t,w,m);if(y.enforced&&!y.bypass){if(!w)return h({error:"Auth required"},401);let S=Fe(g,y.field,y.value);if(S.error)return h({error:S.error},403);g=S.data}if(Object.keys(g).length===0)return h({error:"No fillable fields provided"},422);let b=ke(g,t,"creating");if(!b.valid)return h({success:!1,message:"Validation failed",errors:b.errors},422);if(t.traits?.useTimestamps!==!1){let S=new Date().toISOString();g.created_at=S,g.updated_at=S}let B=await tt(g,t),A=ye(nt(B,t)),P=await C.insertInto(i).values(A).execute(),I=A;try{let S=P?.lastInsertRowid??P?.insertId??P;if(S){let U=await C.selectFrom(i).where({id:S}).executeTakeFirst();if(U)I=U}}catch{}return h({data:K(se(I,t),p)},201)}catch(a){let{status:l,body:g}=he(a,e,"create");return h(g,l)}}),R);if(o.includes("update")){let m=async(a)=>{try{let l=fe(a.params?.id);if(l==null)return h({error:"Invalid ID parameter"},400);let g=await Te(a),w=be(g,p),y=we(w,c),b=await Y(a);if(b){let k=await rt(t,"updating",b,a);for(let[J,H]of Object.entries(k))if(H!==void 0&&H!==null&&y[J]===void 0)y[J]=H}if(Object.keys(y).length===0)return h({error:"No fillable fields provided"},422);let B=ke(y,t,"updating");if(!B.valid)return h({success:!1,message:"Validation failed",errors:B.errors},422);let A=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(!A)return h({error:`${e} not found`},404);let P=await ee(t,b,a);if(P.enforced&&!P.bypass){if(!b)return h({error:"Auth required"},401);let k=A[P.field];if(!re(k,P.value))return h({error:`Not your ${e}`},403);let J=Object.keys(y).find((H)=>T(H)===T(P.field));if(J!==void 0&&!re(y[J],P.value))return h({error:`Cannot reassign ${e} ownership`},403)}if(t.traits?.useTimestamps!==!1)y.updated_at=new Date().toISOString();let I=await tt(y,t),S=ye(nt(I,t));await C.updateTable(i).set(S).where({id:l}).execute();let U={...A,...S};try{let k=await C.selectFrom(i).where({id:l}).executeTakeFirst();if(k)U=k}catch{}return h({data:K(se(U,t),p)})}catch(l){let{status:g,body:w}=he(l,e,"update");return h(w,g)}};if(!G("PUT",`${d}/{id}`))v(L.put(`${d}/{id}`,m),R);if(!G("PATCH",`${d}/{id}`))v(L.patch(`${d}/{id}`,m),R)}let x=!!t.traits?.useSoftDeletes;if(o.includes("destroy")&&!G("DELETE",`${d}/{id}`))v(L.delete(`${d}/{id}`,async(m)=>{try{let a=fe(m.params?.id);if(a==null)return h({error:"Invalid ID parameter"},400);let l=await C.selectFrom(i).where({id:a}).executeTakeFirst();if(!l)return h({error:`${e} not found`},404);let g=await Y(m),w=await ee(t,g,m);if(w.enforced&&!w.bypass){if(!g)return h({error:"Auth required"},401);let y=l[w.field];if(!re(y,w.value))return h({error:`Not your ${e}`},403)}if(x){let y=new Date().toISOString();await C.updateTable(i).set({deleted_at:y,updated_at:y}).where({id:a}).execute()}else await C.deleteFrom(i).where({id:a}).execute();return new Response(null,{status:204})}catch(a){if(a instanceof W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({error:`Failed to delete ${e}`,detail:String(a)},500)}}),R);if(o.includes("destroy")&&!G("POST",`${d}/bulk-delete`))v(L.post(`${d}/bulk-delete`,async(m)=>{try{let l=(await Te(m))?.ids;if(!Array.isArray(l)||l.length===0)return h({error:"An array of IDs is required"},422);if(l.length>100)return h({error:"Cannot delete more than 100 records at once"},422);let g=[],w=[];for(let A of l){let P=fe(A);if(P!=null)g.push(P);else w.push(A)}if(w.length>0)return h({error:"Invalid IDs in batch",invalid:w},422);let y=await Y(m),b=await ee(t,y,m);if(b.enforced&&!b.bypass){if(!y)return h({error:"Auth required"},401);if(b.value==null)return h({error:"Caller has no ownership identity"},403);let A=await C.selectFrom(i).select(["id",b.field]).execute(),P=new Set(A.filter((S)=>re(S[b.field],b.value)).map((S)=>String(S.id))),I=g.filter((S)=>!P.has(String(S)));if(I.length>0)return h({error:`Cannot delete ${e} you don't own`,ids:I},403)}let B=new Date().toISOString();for(let A of g)if(x)await C.updateTable(i).set({deleted_at:B,updated_at:B}).where({id:A}).execute();else await C.deleteFrom(i).where({id:A}).execute();return h({message:`Successfully deleted ${g.length} ${s}`})}catch(a){if(a instanceof W){let l={error:a.message};if(a.details!==void 0)l.details=a.details;return h(l,a.status||400)}return h({error:`Failed to bulk delete ${s}`,detail:String(a)},500)}}),R)}ct=L});var dt={};ce(dt,{default:()=>ct});var lt=Z(async()=>{await ut()});class _e{data;status;headers;isOk;constructor(e,t,n,r){this.data=e;this.status=t;this.headers=n;this.isOk=r}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 Pe{defaultHeaders={Accept:"application/json","Content-Type":"application/json"};queryParams;bodyData;isFormData=!1;customHeaders={};attachments=[];isMultipart=!1;digestAuth;withQueryParams(e){return this.queryParams=e,this}withHeaders(e){return this.customHeaders={...this.customHeaders,...e},this}accept(e){return this.defaultHeaders.Accept=e,this}acceptJson(){return this.accept("application/json")}withToken(e){return this.customHeaders.Authorization=`Bearer ${e}`,this}withBasicAuth(e,t){let n=btoa(`${e}:${t}`);return this.customHeaders.Authorization=`Basic ${n}`,this}withDigestAuth(e,t){return this.digestAuth={username:e,password:t},this}withBody(e){return this.bodyData=e,this}asForm(){return this.isFormData=!0,this.defaultHeaders["Content-Type"]="application/x-www-form-urlencoded",this}attach(e,t,n,r){let s=typeof t==="string"?new Blob([t],{type:r?.["Content-Type"]||"text/plain"}):t;return this.attachments.push({name:e,content:s,filename:n,headers:r}),this.isMultipart=!0,delete this.defaultHeaders["Content-Type"],this}getHeaders(){return{...this.defaultHeaders,...this.customHeaders}}addQueryParams(e){if(!this.queryParams)return e;let t=new URLSearchParams;Object.entries(this.queryParams).forEach(([s,o])=>{if(o!=null)t.append(s,String(o))});let n=t.toString();if(!n)return e;let r=e.includes("?");return e+(r?"&":"?")+n}async formatBody(e){let t=e||this.bodyData;if(this.isMultipart){let n=new FormData;if(t)Object.entries(t).forEach(([r,s])=>{n.append(r,String(s))});for(let r of this.attachments)if(r.headers){let s=r.content instanceof Blob?new Blob([r.content],{type:r.headers["Content-Type"]}):r.content;n.append(r.name,s,r.filename)}else n.append(r.name,r.content,r.filename);return n}if(this.isFormData&&t){let n=new URLSearchParams;return Object.entries(t).forEach(([r,s])=>{if(s!=null)n.append(r,String(s))}),n.toString()}return t?JSON.stringify(t):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(e,t,n,r){if(e.status!==401||!this.digestAuth)return e;let s=e.headers.get("WWW-Authenticate");if(!s?.startsWith("Digest "))return e;let o=s.substring(7).split(",").reduce((_,O)=>{let[D,j]=O.trim().split("=");if(D)_[D]=j?.replace(/["']/g,"")??"";return _},{}),i=await this.generateMD5(`${this.digestAuth.username}:${o.realm}:${this.digestAuth.password}`),c=await this.generateMD5(`${n}:${t}`),p="00000001",d=await this.generateMD5(Date.now().toString()).then((_)=>_.substring(0,8)),u=await this.generateMD5(`${i}:${o.nonce}:${p}:${d}:${o.qop}:${c}`),f={username:`"${this.digestAuth.username}"`,realm:`"${o.realm}"`,nonce:`"${o.nonce}"`,uri:`"${t}"`,algorithm:o.algorithm?`"${o.algorithm}"`:void 0,qop:`"${o.qop}"`,nc:p,cnonce:`"${d}"`,response:`"${u}"`,opaque:o.opaque?`"${o.opaque}"`:void 0},R=Object.entries(f).filter(([_,O])=>O!==void 0).map(([_,O])=>`${_}=${O}`).join(", ");return this.customHeaders.Authorization=`Digest ${R}`,fetch(t,{method:n,headers:this.getHeaders(),body:r?await this.formatBody(r):void 0})}async generateMD5(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map((o)=>o.toString(16).padStart(2,"0")).join("")}async request(e,t,n){let r=this.addQueryParams(e),s=await this.formatBody(n),o=await fetch(r,{method:t,headers:this.getHeaders(),body:s});if(this.digestAuth)o=await this.handleDigestAuth(o,r,t,n);let i=await o.json();return this.resetState(),new _e(i,o.status,o.headers,o.ok)}async get(e){return this.request(e,"GET")}async post(e,t){return this.request(e,"POST",t)}async put(e,t){return this.request(e,"PUT",t)}async patch(e,t){return this.request(e,"PATCH",t)}async delete(e){return this.request(e,"DELETE")}}var en=new Pe;ge();import{path as te}from"@stacksjs/path";function ft(e){if(!e||typeof e!=="object")return{type:"string"};let t=e,n=Array.isArray(t.rules)?t.rules:[],r=(u)=>n.find((f)=>f.name===u),s=(u,f)=>{let R=r(u)?.params?.[f];return typeof R==="number"?R:void 0},o=t.name??t._type??"string",i={type:o==="enum"?"string":o},c=s("min","min")??(typeof t._min==="number"?t._min:void 0),p=s("max","max")??(typeof t._max==="number"?t._max:void 0);if(c!==void 0)i[o==="string"?"minLength":"minimum"]=c;if(p!==void 0)i[o==="string"?"maxLength":"maximum"]=p;if(r("email")||t._email)i.format="email";if(r("url")||t._url)i.format="uri";if(r("uuid")||t._uuid)i.format="uuid";let d=Array.isArray(t.allowedValues)?t.allowedValues:Array.isArray(t._enum)?t._enum:null;if(d)i.enum=d;return i}function zt(e){if(!e||typeof e!=="object")return!1;let t=e;return Boolean(t.isRequired??t._required)}function pt(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Vt(e){let t={id:{type:"integer"}},n=["id"];if(e.traits?.useUuid)t.uuid={type:"string",format:"uuid"},n.push("uuid");for(let[r,s]of Object.entries(e.attributes??{})){if(s.hidden===!0)continue;let o=pt(r);if(t[o]=ft(s.validation?.rule),s.required===!0)n.push(o)}for(let r of e.belongsTo??[]){if(typeof r!=="string"||!r.trim())continue;let s=`${pt(r.trim())}_id`;t[s]??={type:"integer"}}if(e.traits?.useTimestamps!==!1)t.created_at={type:"string",format:"date-time"},t.updated_at={type:"string",format:"date-time"};if(e.traits?.useSoftDeletes)t.deleted_at={type:"string",format:"date-time",nullable:!0};return{type:"object",properties:t,required:[...new Set(n)]}}function Gt(e){let t=e.traits?.useApi;if(!t||typeof t!=="object"||!t.uri)return null;let n=String(t.prefix||"").replace(/^\/+|\/+$/g,""),r=String(t.uri).replace(/^\/+|\/+$/g,"");return`/api/${n?`${n}/`:""}${r}`}function Xt(e,t){let n={...t},r=e?.responses;if(r&&typeof r==="object")for(let[o,i]of Object.entries(r)){let c=i;if(!c||typeof c!=="object"||typeof c.description!=="string")continue;n[String(o)]={description:c.description,...c.schema&&typeof c.schema==="object"?{content:{"application/json":{schema:c.schema}}}:{}}}let s=e?.responseHeaders;if(s&&typeof s==="object"){let o={};for(let[i,c]of Object.entries(s)){let p=c;if(!p||typeof p!=="object"||typeof p.description!=="string")continue;o[i]={description:p.description,...p.schema&&typeof p.schema==="object"?{schema:p.schema}:{}}}if(Object.keys(o).length>0)for(let i of Object.keys(n))n[i]={...n[i],headers:o}}return n}async function Zt(e){if(typeof e!=="string"||!e||e.includes(".."))return null;try{let{path:t}=await import("@stacksjs/path"),n=[t.appPath(`${e}.ts`),t.storagePath(`framework/defaults/app/${e}.ts`)];for(let r of n)try{if(!await Bun.file(r).exists())continue;let i=(await import(r)).default;return i&&typeof i==="object"?i:null}catch{}}catch{}return null}async function wn(e={}){let t=e.portable??!0,{listRegisteredRoutes:n}=await import("@stacksjs/router");try{let{loadRoutes:u}=await import("@stacksjs/router"),{default:f}=await import(te.appPath("Routes.ts"));await u(f)}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load routes/api.ts + framework routes: ${f}`);console.warn(`[generateOpenApi] Failed to load routes/api.ts + framework routes: ${f}`)}try{try{await import("@stacksjs/orm/routes")}catch{await lt().then(() => dt)}}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit a partial spec: failed to load useApi-generated ORM routes: ${f}`);console.warn(`[generateOpenApi] Failed to load useApi-generated ORM routes: ${f}`)}let r={};try{let f;try{f=await import("@stacksjs/orm/model-registry")}catch{f=await Promise.resolve().then(() => ($e(),Xe))}r=await f.loadModelRegistry({defaultsRoot:te.storagePath("framework/defaults/app/Models"),userRoot:te.projectPath("app/Models")})}catch(u){let f=u instanceof Error?u.message:String(u);if(t)throw Error(`[generateOpenApi] Refusing to emit model-free schemas: ${f}`);console.warn(`[generateOpenApi] Failed to load model schemas: ${f}`)}let s=(u)=>u.replace(/(^|\/):(\w+)(?=$|\/)/g,"$1{$2}"),o=[...n()].map((u)=>({route:u,oasPath:s(u.path),method:u.method.toLowerCase()})).sort((u,f)=>{if(u.oasPath!==f.oasPath)return u.oasPath<f.oasPath?-1:1;return u.method<f.method?-1:u.method>f.method?1:0});if(t&&o.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 i="Stacks API";if(!t)try{let{config:u}=await import("@stacksjs/config");if(u.app?.name)i=`${u.app.name} API`}catch{}let c={openapi:"3.0.0",info:{title:i,version:"1.0.0"},paths:{},components:{schemas:{}}},p=Object.values(r).map((u)=>({name:String(u.name),path:Gt(u),schema:Vt(u)})).filter((u)=>u.path!==null).sort((u,f)=>u.name<f.name?-1:u.name>f.name?1:0);for(let u of p)c.components.schemas[u.name]=u.schema;let d=new Set;for(let{route:u,oasPath:f,method:R}of o){if(!c.paths[f])c.paths[f]={};let _=[];for(let a of u.path.matchAll(/\{(\w+)\}/g))if(a[1])_.push(a[1]);for(let a of u.path.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(a[1])_.push(a[1]);let O=u.name??`${R}_${f.replace(/[^a-z0-9]/gi,"_")}`,D=O;if(d.has(D)){D=`${O}_${R}`;let a=2;while(d.has(D))D=`${O}_${R}_${a++}`}d.add(D);let j={summary:u.name??u.path,operationId:D,parameters:_.map((a)=>({name:a,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"}}},E=p.find((a)=>f===a.path||f===`${a.path}/{id}`);if(E){let a=f===E.path&&R==="get"?{type:"array",items:E.schema}:E.schema;if(j.responses[200].content={"application/json":{schema:{type:"object",properties:{data:a},required:["data"]}}},R==="post"&&f===E.path)j.responses[201]={...j.responses[200],description:"Created"},delete j.responses[200]}let v=u.action??(u.handler?await Zt(u.handler):null),x=v&&typeof v.validations==="object"&&v.validations!==null?v.validations:null;j.responses=Xt(v,j.responses);let m=v?.requestHeaders;if(m&&typeof m==="object")for(let[a,l]of Object.entries(m)){let g=l;if(!g||typeof g!=="object"||typeof g.description!=="string")continue;j.parameters?.push({name:a,in:"header",description:g.description,required:g.required===!0,schema:g.schema&&typeof g.schema==="object"?g.schema:{type:"string"}})}if(x&&Object.keys(x).length>0){let a=Object.entries(x).map(([l,g])=>{let w=g?.rule;return{field:l,schema:ft(w),required:zt(w)}});if(R==="get"||R==="head"||R==="delete"){let l=new Set(_);for(let{field:g,schema:w,required:y}of a){if(l.has(g))continue;j.parameters?.push({name:g,in:"query",required:y,schema:w})}}else{let l={type:"object",properties:{},required:[]},g=l.properties,w=l.required;for(let y of a)if(g[y.field]=y.schema,y.required)w.push(y.field);if(w.length===0)delete l.required;j.requestBody={required:w.length>0,content:{"application/json":{schema:l}}}}}c.paths[f][R]=j}if(e.write!==!1){await Bun.write(te.frameworkPath("api/openapi.json"),JSON.stringify(c,null,2));let{renderOpenApiTypes:u}=await Promise.resolve().then(() => (ue(),ve)),{renderApiClient:f}=await Promise.resolve().then(() => (ge(),Ne));await Bun.write(te.frameworkPath("api/api-types.ts"),u(c)),await Bun.write(te.frameworkPath("api/client.ts"),f(c,{name:c.info.title}))}return c}ue();class M{static instance=new M;isMissing(){return!0}}class ie{data;constructor(e){this.data=e}}class gt{condition;value;defaultValue;constructor(e,t,n=new M){this.condition=e;this.value=t;this.defaultValue=n}resolve(){return(typeof this.condition==="function"?this.condition():this.condition)?this.value:this.defaultValue}}class mt{resource;additional={};request;static wrap="data";static additionalMeta={};constructor(e){this.resource=e}withRequest(e){return this.request=e,this}withAdditional(e){return this.additional={...this.additional,...e},this}resolve(e){let t=this.toArray(e||this.request);return this.filterAndResolve(t)}toResponse(e){let t=this.resolve(e),n=this.constructor.wrap;if(n)return{[n]:t,...this.additional};return{...t,...this.additional}}toJson(e){return JSON.stringify(this.toResponse(e))}toJSON(){return this.toResponse()}static collection(e){return new je(e,this)}when(e,t,n){if(typeof e==="function"?e():e)return typeof t==="function"?t():t;return n!==void 0?n:M.instance}whenNotNull(e,t){if(e===null||e===void 0)return M.instance;return t?t(e):e}whenLoaded(e,t,n){let r=this.resource;if(!((e in r)&&r[e]!==void 0))return n!==void 0?n:M.instance;if(t!==void 0)return typeof t==="function"?t():t;return r[e]}whenCounted(e,t){let n=this.resource,r=`${e}_count`;if(r in n)return Number(n[r]);return t!==void 0?t:M.instance}merge(e){return new ie(e)}mergeWhen(e,t){if(!(typeof e==="function"?e():e))return M.instance;let r=typeof t==="function"?t():t;return new ie(r)}static MAX_RESOLVE_DEPTH=20;filterAndResolve(e,t=0){if(t>=mt.MAX_RESOLVE_DEPTH)return e;let n={};for(let[r,s]of Object.entries(e)){if(s instanceof M)continue;if(s instanceof ie){Object.assign(n,this.filterAndResolve(s.data,t+1));continue}if(s instanceof gt){let o=s.resolve();if(!(o instanceof M))n[r]=o;continue}if(s!==null&&typeof s==="object"&&!Array.isArray(s)&&!(s instanceof Date)){n[r]=this.filterAndResolve(s,t+1);continue}if(Array.isArray(s)){n[r]=s.filter((o)=>!(o instanceof M)).map((o)=>{if(o instanceof ie)return o.data;if(o!==null&&typeof o==="object"&&!(o instanceof Date))return this.filterAndResolve(o,t+1);return o});continue}n[r]=s}return n}static withoutWrapping(){this.wrap=null}static wrapWith(e){this.wrap=e}}class je{resources;ResourceClass;additional={};request;static wrap="data";constructor(e,t){this.resources=e,this.ResourceClass=t}withRequest(e){return this.request=e,this}withAdditional(e){return this.additional={...this.additional,...e},this}resolve(e){let t=e||this.request;return this.resources.map((n)=>{let r=new this.ResourceClass(n);if(t)r.withRequest(t);return r.resolve(t)})}toResponse(e){let t=this.resolve(e),n=this.constructor.wrap;if(n)return{[n]:t,...this.additional};return{data:t,...this.additional}}toJson(e){return JSON.stringify(this.toResponse(e))}count(){return this.resources.length}isEmpty(){return this.resources.length===0}isNotEmpty(){return this.resources.length>0}}class ht extends je{meta;links;constructor(e,t){super(e.data,t);this.meta=e.meta,this.links=e.links}static fromPagination(e,t,n){let{currentPage:r,perPage:s,total:o,baseUrl:i=""}=n,c=Math.ceil(o/s),p=o>0?(r-1)*s+1:null,d=o>0?Math.min(r*s,o):null;return new ht({data:e,meta:{current_page:r,from:p,last_page:c,per_page:s,to:d,total:o},links:{first:`${i}?page=1`,last:`${i}?page=${c}`,prev:r>1?`${i}?page=${r-1}`:null,next:r<c?`${i}?page=${r+1}`:null}},t)}toResponse(e){return{data:this.resolve(e),meta:this.meta,links:this.links,...this.additional}}}function Rn(e,t){let n=t(e);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}function kn(e,t){let n=e.map(t);return{toResponse:()=>({data:n}),toJson:()=>JSON.stringify({data:n})}}export{gt as ConditionalValue,mt as JsonResource,ie as MergeValue,M as MissingValue,ht as PaginatedResourceCollection,je as ResourceCollection,kn as collection,Xt as describedResponses,en as fetcher,wn as generateOpenApi,qe as methodName,Vt as modelDefinitionToSchema,Dt as renderApiClient,Tt as renderOpenApiTypes,Rn as resource,zt as ruleIsRequired,ft as ruleToSchema,F as schemaType};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/api",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.73.0",
|
|
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.
|
|
65
|
+
"@stacksjs/utils": "0.73.0"
|
|
66
66
|
}
|
|
67
67
|
}
|