resora 0.2.3 → 0.2.5
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/README.md +7 -7
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +39 -8
- package/dist/index.d.mts +39 -8
- package/dist/index.mjs +4 -4
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/resora)
|
|
4
4
|
[](https://www.npmjs.com/package/resora)
|
|
5
|
-
[](https://github.com/
|
|
6
|
-
[](https://github.com/arkstack-hq/resora/blob/main/LICENSE)
|
|
6
|
+
[](https://github.com/arkstack-hq/resora/actions/workflows/ci.yml)
|
|
7
|
+
[](https://github.com/arkstack-hq/resora/actions/workflows/deploy-docs.yml)
|
|
8
8
|
|
|
9
9
|
Resora is a structured API response layer for Node.js and TypeScript backends.
|
|
10
10
|
|
|
@@ -207,10 +207,10 @@ It is intentionally not opinionated about routing, validation, or persistence.
|
|
|
207
207
|
|
|
208
208
|
## Documentation
|
|
209
209
|
|
|
210
|
-
- Getting Started: https://
|
|
211
|
-
- Configuration: https://
|
|
212
|
-
- Conditional Rendering: https://
|
|
213
|
-
- Pagination & Cursor Recipes: https://
|
|
210
|
+
- Getting Started: https://arkstack-hq.github.io/resora/guide/getting-started
|
|
211
|
+
- Configuration: https://arkstack-hq.github.io/resora/guide/configuration
|
|
212
|
+
- Conditional Rendering: https://arkstack-hq.github.io/resora/guide/conditional-attributes
|
|
213
|
+
- Pagination & Cursor Recipes: https://arkstack-hq.github.io/resora/guide/pagination-cursor-recipes
|
|
214
214
|
|
|
215
215
|
---
|
|
216
216
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`fs`),l=require(`path`);l=s(l);let u=require(`module`),d=require(`url`),f=require(`@h3ravel/musket`);function ee(e){return e}let p,m,
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`fs`),l=require(`path`);l=s(l);let u=require(`module`),d=require(`url`),f=require(`@h3ravel/musket`);function ee(e){return e}let p,m,te=[`meta`,`links`],h={first:`first`,last:`last`,prev:`prev`,next:`next`},g=`https://localhost`,_=`page`,v={to:`to`,from:`from`,links:`links`,path:`path`,total:`total`,per_page:`per_page`,last_page:`last_page`,current_page:`current_page`},y={previous:`previous`,next:`next`};const ne=e=>{p=e},b=()=>p,x=e=>{m=e},S=()=>m,re=e=>{m={...m||{},rootKey:e}},ie=e=>{m={...m||{},wrap:e}},ae=()=>m?.wrap,oe=()=>m?.rootKey,se=e=>{m={...m||{},factory:e}},ce=()=>m?.factory,C=e=>{te=e},w=()=>te,T=e=>{h={...h,...e}},E=()=>h,D=e=>{g=e},le=()=>g,ue=e=>{_=e},de=()=>_,fe=e=>{v={...v,...e}},pe=()=>v,me=e=>{y={...y,...e}},he=()=>y,O=e=>{if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Date||e instanceof RegExp)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},k=(e,t,n=`data`)=>!t||Object.keys(t).length===0?e:Array.isArray(e)?{[n]:e,...t}:O(e)?{...e,...t}:{[n]:e,...t},A=(e,t)=>{if(!t)return e;if(!e)return t;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];O(t)&&O(r)?n[e]=A(t,r):n[e]=r}return n},j=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.toObject==`function`&&typeof t.getRawAttributes==`function`},M=e=>!e||typeof e!=`object`?!1:typeof e.all==`function`,N=e=>{if(Array.isArray(e))return e.map(e=>N(e));if(j(e))return N(e.toObject());if(M(e)){let t=e.all();return Array.isArray(t)?t.map(e=>N(e)):N(t)}return O(e)?Object.entries(e).reduce((e,[t,n])=>(e[t]=N(n),e),{}):e},P=()=>{let e=w();return Array.isArray(e)?{metaKey:e.includes(`meta`)?`meta`:void 0,linksKey:e.includes(`links`)?`links`:void 0,cursorKey:e.includes(`cursor`)?`cursor`:void 0}:{metaKey:e.meta,linksKey:e.links,cursorKey:e.cursor}},F=(e,t)=>{if(e===void 0)return;let n=t||``,r=le()||``,i=/^https?:\/\//i.test(n),a=r.replace(/\/$/,``),o=n.replace(/^\//,``),s=i?n:a?o?`${a}/${o}`:a:``;if(!s)return;let c=new URL(s);return c.searchParams.set(de()||`page`,String(e)),c.toString()},I=e=>{let{metaKey:t,linksKey:n,cursorKey:r}=P(),i={},a=!!e&&typeof e==`object`&&!!e.meta&&typeof e.meta==`object`&&(Array.isArray(e.data)||M(e.data)),o=a?{first:typeof e.firstPageUrl==`function`?e.firstPageUrl():void 0,last:typeof e.lastPageUrl==`function`?e.lastPageUrl():void 0,prev:typeof e.previousPageUrl==`function`?e.previousPageUrl():void 0,next:typeof e.nextPageUrl==`function`?e.nextPageUrl():void 0}:void 0,s=o?Object.entries(o).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),{}):void 0,c=e?.pagination||(a?{...e.meta,links:e.links||s}:void 0),l=e?.cursor,u={},d={};if(c){let e={to:c.to,from:c.from,links:c.links,path:c.path,total:c.total,per_page:c.perPage,last_page:c.lastPage,current_page:c.currentPage};for(let[t,n]of Object.entries(pe())){if(!n)continue;let r=e[t];r!==void 0&&(u[n]=r)}let t={first:c.links&&Object.prototype.hasOwnProperty.call(c.links,`first`)?c.links.first:F(c.firstPage,c.path),last:c.links&&Object.prototype.hasOwnProperty.call(c.links,`last`)?c.links.last:F(c.lastPage,c.path),prev:c.links&&Object.prototype.hasOwnProperty.call(c.links,`prev`)?c.links.prev:F(c.prevPage,c.path),next:c.links&&Object.prototype.hasOwnProperty.call(c.links,`next`)?c.links.next:F(c.nextPage,c.path)};for(let[e,n]of Object.entries(E())){if(!n)continue;let r=t[e];r!==void 0&&(d[n]=r)}}if(l){let e={},t={previous:l.previous,next:l.next};for(let[n,r]of Object.entries(he())){if(!r)continue;let i=t[n];i!==void 0&&(e[r]=i)}r&&Object.keys(e).length>0?i[r]=e:Object.keys(e).length>0&&(u.cursor=e)}return t&&Object.keys(u).length>0&&(i[t]=u),n&&Object.keys(d).length>0&&(i[n]=d),i},L=({payload:e,meta:t,metaKey:n=`meta`,wrap:r=!0,rootKey:i=`data`,factory:a,context:o})=>{if(a)return a(e,{...o,rootKey:i,meta:t});if(!r)return t===void 0?e:O(e)?{...e,[n]:t}:{[i]:e,[n]:t};let s={[i]:e};return t!==void 0&&(s[n]=t),s},R=(e,t)=>{let n=e?.with;if(typeof n!=`function`||n===t||n.length>0)return;let r=n.call(e);return O(r)?r:void 0},z=Symbol(`resora.conditional.missing`),B=(e,t)=>e?typeof t==`function`?t():t:z,V=e=>e??z,H=(e,t)=>{if(!e)return{};let n=typeof t==`function`?t():t;return O(n)?n:{}},U=e=>{if(e===z)return z;if(Array.isArray(e))return e.map(e=>U(e)).filter(e=>e!==z);if(O(e)){let t={};for(let[n,r]of Object.entries(e)){let e=U(r);e!==z&&(t[n]=e)}return t}return e},W=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/[-_\s]+/g,` `).trim().toLowerCase().split(` `).filter(Boolean),G=e=>W(e).map((e,t)=>t===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(``),ge=e=>W(e).join(`_`),_e=e=>W(e).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``),ve=e=>W(e).join(`-`),K=e=>{if(typeof e==`function`)return e;switch(e){case`camel`:return G;case`snake`:return ge;case`pascal`:return _e;case`kebab`:return ve}},q=(e,t)=>e==null?e:Array.isArray(e)?e.map(e=>q(e,t)):e instanceof Date||e instanceof RegExp?e:typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[t(e),q(n,t)])):e;let J=l.default.resolve(process.cwd(),`node_modules/resora/stubs`);(0,c.existsSync)(J)||(J=l.default.resolve(process.cwd(),`stubs`));const ye=()=>({stubsDir:J,preferredCase:`camel`,responseStructure:{wrap:!0,rootKey:`data`},paginatedExtras:[`meta`,`links`],baseUrl:`https://localhost`,pageName:`page`,paginatedLinks:{first:`first`,last:`last`,prev:`prev`,next:`next`},paginatedMeta:{to:`to`,from:`from`,links:`links`,path:`path`,total:`total`,per_page:`per_page`,last_page:`last_page`,current_page:`current_page`},cursorMeta:{previous:`previous`,next:`next`},resourcesDir:`src/resources`,stubs:{config:`resora.config.stub`,resource:`resource.stub`,collection:`resource.collection.stub`}}),Y=e=>{let t=ye();return Object.assign(t,e,{stubs:Object.assign(t.stubs,e.stubs||{})},{cursorMeta:Object.assign(t.cursorMeta,e.cursorMeta||{})},{paginatedMeta:Object.assign(t.paginatedMeta,e.paginatedMeta||{})},{paginatedLinks:Object.assign(t.paginatedLinks,e.paginatedLinks||{})},{responseStructure:Object.assign(t.responseStructure,e.responseStructure||{})})};let X=!1,Z;const be=()=>{X=!1,Z=void 0},xe=e=>{e.preferredCase!==`camel`&&ne(e.preferredCase),x(e.responseStructure),C(e.paginatedExtras),T(e.paginatedLinks),fe(e.paginatedMeta),me(e.cursorMeta),D(e.baseUrl),ue(e.pageName)},Se=async e=>await import(`${(0,d.pathToFileURL)(e).href}?resora_runtime=${Date.now()}`),Q=e=>{xe(Y((e?.default??e)||{})),X=!0},Ce=()=>{let e=(0,u.createRequire)(e(`url`).pathToFileURL(__filename).href),t=[l.default.join(process.cwd(),`resora.config.cjs`)];for(let n of t)if((0,c.existsSync)(n))try{return Q(e(n)),!0}catch{continue}return!1},we=async()=>{if(!X){if(Z)return await Z;Ce()||(Z=(async()=>{let e=[l.default.join(process.cwd(),`resora.config.js`),l.default.join(process.cwd(),`resora.config.ts`)];for(let t of e)if((0,c.existsSync)(t))try{Q(await Se(t));return}catch{continue}X=!0})(),await Z)}};we();var Te=class{command;config={};constructor(e={}){this.config=Y(e)}async loadConfig(e={}){this.config=Y(e);let t=[(0,l.join)(process.cwd(),`resora.config.ts`),(0,l.join)(process.cwd(),`resora.config.js`),(0,l.join)(process.cwd(),`resora.config.cjs`)];for(let e of t)if((0,c.existsSync)(e))try{let{default:t}=await import(e);Object.assign(this.config,t);break}catch(t){console.error(`Error loading config file at ${e}:`,t)}return this}getConfig(){return this.config}init(){let e=(0,l.join)(process.cwd(),`resora.config.js`),t=(0,l.join)(this.config.stubsDir,this.config.stubs.config);return(0,c.existsSync)(e)&&!this.command.option(`force`)&&(this.command.error(`Error: ${e} already exists.`),process.exit(1)),this.ensureDirectory(e),(0,c.existsSync)(e)&&this.command.option(`force`)&&(0,c.copyFileSync)(e,e.replace(/\.js$/,`.backup.${Date.now()}.js`)),(0,c.writeFileSync)(e,(0,c.readFileSync)(t,`utf-8`)),{path:e}}ensureDirectory(e){let t=(0,l.dirname)(e);(0,c.existsSync)(t)||(0,c.mkdirSync)(t,{recursive:!0})}generateFile(e,t,n,r){(0,c.existsSync)(t)&&!r?.force?(this.command.error(`Error: ${t} already exists.`),process.exit(1)):(0,c.existsSync)(t)&&r?.force&&(0,c.rmSync)(t);let i=(0,c.readFileSync)(e,`utf-8`);for(let[e,t]of Object.entries(n))i=i.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(t),(0,c.writeFileSync)(t,i),t}makeResource(e,t){let n=e;t?.collection&&!e.endsWith(`Collection`)&&!e.endsWith(`Resource`)?n+=`Collection`:!t?.collection&&!e.endsWith(`Resource`)&&!e.endsWith(`Collection`)&&(n+=`Resource`);let r=`${n}.ts`,i=(0,l.join)(this.config.resourcesDir,r),a=(0,l.join)(this.config.stubsDir,t?.collection||e.endsWith(`Collection`)?this.config.stubs.collection:this.config.stubs.resource);(0,c.existsSync)(a)||(this.command.error(`Error: Stub file ${a} not found.`),process.exit(1));let o=n.replace(/(Resource|Collection)$/,``)+`Resource`,s=`/**
|
|
2
2
|
* The resource that this collection collects.
|
|
3
3
|
*/
|
|
4
4
|
collects = ${o}
|
|
5
|
-
`,u=`import ${o} from './${o}'\n`,d=(!!t?.collection||e.endsWith(`Collection`))&&(0,c.existsSync)((0,l.join)(this.config.resourcesDir,`${o}.ts`)),f=this.generateFile(a,i,{ResourceName:n,CollectionResourceName:n.replace(/(Resource|Collection)$/,``)+`Resource`,"collects = Resource":d?s:``,"import = Resource":d?u:``},t);return{name:n,path:f}}},
|
|
5
|
+
`,u=`import ${o} from './${o}'\n`,d=(!!t?.collection||e.endsWith(`Collection`))&&(0,c.existsSync)((0,l.join)(this.config.resourcesDir,`${o}.ts`)),f=this.generateFile(a,i,{ResourceName:n,CollectionResourceName:n.replace(/(Resource|Collection)$/,``)+`Resource`,"collects = Resource":d?s:``,"import = Resource":d?u:``},t);return{name:n,path:f}}},Ee=class extends f.Command{signature=`init
|
|
6
6
|
{--force : Force overwrite if config file already exists (existing file will be backed up) }
|
|
7
|
-
`;description=`Initialize Resora`;async handle(){this.app.command=this,this.app.init(),this.success(`Resora initialized`)}},
|
|
7
|
+
`;description=`Initialize Resora`;async handle(){this.app.command=this,this.app.init(),this.success(`Resora initialized`)}},De=class extends f.Command{signature=`#create:
|
|
8
8
|
{resource : Generates a new resource file.
|
|
9
9
|
| {name : Name of the resource to create}
|
|
10
10
|
| {--c|collection : Make a resource collection}
|
|
@@ -25,4 +25,4 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
25
25
|
| _ // _ \/ __|/ _ \| '__/ _, |
|
|
26
26
|
| | \ \ __/\__ \ (_) | | | (_| |
|
|
27
27
|
|_| \_\___||___/\___/|_| \__,_|
|
|
28
|
-
`;var $=class{_status=200;headers={};constructor(e,t){this.response=e,this.body=t}setStatusCode(e){return this._status=e,`status`in this.response&&typeof this.response.status==`function`?this.response.status(e):`status`in this.response&&(this.response.status=e),this}status(){return this._status}statusText(){if(`statusMessage`in this.response)return this.response.statusMessage;if(`statusText`in this.response)return this.response.statusText}setCookie(e,t,n){return this.#e(`Set-Cookie`,`${e}=${t}; ${Object.entries(n||{}).map(([e,t])=>`${e}=${t}`).join(`; `)}`),this}setHeaders(e){for(let[t,n]of Object.entries(e))this.#e(t,n);return this}header(e,t){return this.#e(e,t),this}#e(e,t){this.headers[e]=t,`headers`in this.response?this.response.headers.set(e,t):`setHeader`in this.response&&this.response.setHeader(e,t)}then(e,t){let n=Promise.resolve(this.body).then(e,t);return`send`in this.response&&this.response.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},Te=class e{body={data:{}};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){if(this.res=t,this.resource=e,!Array.isArray(this.resource.data??this.resource))for(let e of Object.keys(this.resource.data??this.resource))e in this||Object.defineProperty(this,e,{enumerable:!0,configurable:!0,get:()=>this.resource.data?.[e]??this.resource[e],set:t=>{this.resource.data&&this.resource.data[e]?this.resource.data[e]=t:this.resource[e]=t}})}data(){return this.resource}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data(),n=Array.isArray(t)?[...t]:{...t};Array.isArray(n)&&this.collects&&(n=n.map(e=>new this.collects(e).data()),this.resource=n),n.data!==void 0&&(n=n.data),n=V(n);let r=j(this.resource),{metaKey:i}=k(),a=i?r[i]:void 0;i&&delete r[i];let o=this.constructor.preferredCase??x();if(o){let e=q(o);n=J(n,e)}let s=P(I(this,e.prototype.with),this.additionalMeta),{wrap:c,rootKey:l,factory:u}=this.resolveResponseStructure();this.body=F({payload:n,meta:a,metaKey:i,wrap:c,rootKey:l,factory:u,context:{type:`generic`,resource:this.resource}}),this.body=N(this.body,{...r,...s||{}},l)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=Array.isArray(this.resource)?[...this.resource]:{...this.resource};return e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=e.data;delete e.data,delete e.pagination;let n=this.getPayloadKey();return t&&n&&this.body[n]!==void 0&&(this.body[n]=Array.isArray(this.body[n])?[...this.body[n],...t]:{...this.body[n],...t}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}},Ee=class e{body={data:[]};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data();this.collects&&(t=t.map(e=>new this.collects(e).data())),t=V(t);let n=Array.isArray(this.resource)?{}:j(this.resource),{metaKey:r}=k(),i=r?n[r]:void 0;r&&delete n[r];let a=this.constructor.preferredCase??this.collects?.preferredCase??x();if(a){let e=q(a);t=J(t,e)}let o=P(I(this,e.prototype.with),this.additionalMeta),{wrap:s,rootKey:c,factory:l}=this.resolveResponseStructure();this.body=F({payload:t,meta:i,metaKey:r,wrap:s,rootKey:c,factory:l,context:{type:`collection`,resource:this.resource}}),this.body=N(this.body,{...n,...o||{}},c)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){return this.called.toArray=!0,this.json(),Array.isArray(this.resource)?[...this.resource]:[...this.resource.data]}additional(e){this.called.additional=!0,this.json(),delete e.cursor,delete e.pagination;let t=this.getPayloadKey();return e.data&&t&&Array.isArray(this.body[t])&&(this.body[t]=[...this.body[t],...e.data]),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}setCollects(e){return this.collects=e,this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},De=class e{body={data:{}};resource;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){if(this.res=t,this.resource=e,!Array.isArray(this.resource.data??this.resource))for(let e of Object.keys(this.resource.data??this.resource))e in this||Object.defineProperty(this,e,{enumerable:!0,configurable:!0,get:()=>this.resource.data?.[e]??this.resource[e],set:t=>{this.resource.data&&this.resource.data[e]?this.resource.data[e]=t:this.resource[e]=t}})}static collection(e){return new Ee(e).setCollects(this)}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=C();return{wrap:e?.wrap??t?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??`data`,factory:e?.factory??t?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data(),n=Array.isArray(t)?[...t]:{...t};n.data!==void 0&&(n=n.data),n=V(n);let r=this.constructor.preferredCase??x();if(r){let e=q(r);n=J(n,e)}let i=P(I(this,e.prototype.with),this.additionalMeta),{wrap:a,rootKey:o,factory:s}=this.resolveResponseStructure();this.body=F({payload:n,wrap:a,rootKey:o,factory:s,context:{type:`resource`,resource:this.resource}}),this.body=N(this.body,i,o)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=Array.isArray(this.resource)?[...this.resource]:{...this.resource};return!Array.isArray(e)&&e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=this.getPayloadKey();return e.data&&t&&this.body[t]!==void 0&&(this.body[t]=Array.isArray(this.body[t])?[...this.body[t],...e.data]:{...this.body[t],...e.data}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}};exports.ApiResource=ee,exports.CONDITIONAL_ATTRIBUTE_MISSING=L,exports.CliApp=Se,exports.GenericResource=Te,exports.InitCommand=Ce,exports.MakeResource=we,exports.Resource=De,exports.ResourceCollection=Ee,exports.ServerResponse=$,exports.appendRootProperties=N,exports.applyRuntimeConfig=_e,exports.buildPaginationExtras=j,exports.buildResponseEnvelope=F,exports.defineConfig=X,exports.getCaseTransformer=q,exports.getDefaultConfig=he,exports.getGlobalBaseUrl=ue,exports.getGlobalCase=x,exports.getGlobalCursorMeta=O,exports.getGlobalPageName=fe,exports.getGlobalPaginatedExtras=T,exports.getGlobalPaginatedLinks=ce,exports.getGlobalPaginatedMeta=me,exports.getGlobalResponseFactory=se,exports.getGlobalResponseRootKey=ae,exports.getGlobalResponseStructure=C,exports.getGlobalResponseWrap=ie,exports.getPaginationExtraKeys=k,exports.isPlainObject=M,exports.loadRuntimeConfig=xe,exports.mergeMetadata=P,exports.resetRuntimeConfigForTests=ge,exports.resolveMergeWhen=B,exports.resolveWhen=R,exports.resolveWhenNotNull=z,exports.resolveWithHookMetadata=I,exports.sanitizeConditionalAttributes=V,exports.setGlobalBaseUrl=le,exports.setGlobalCase=b,exports.setGlobalCursorMeta=D,exports.setGlobalPageName=de,exports.setGlobalPaginatedExtras=w,exports.setGlobalPaginatedLinks=E,exports.setGlobalPaginatedMeta=pe,exports.setGlobalResponseFactory=oe,exports.setGlobalResponseRootKey=ne,exports.setGlobalResponseStructure=S,exports.setGlobalResponseWrap=re,exports.splitWords=H,exports.toCamelCase=U,exports.toKebabCase=K,exports.toPascalCase=G,exports.toSnakeCase=W,exports.transformKeys=J;
|
|
28
|
+
`;var $=class{_status=200;headers={};constructor(e,t){this.response=e,this.body=t}setStatusCode(e){return this._status=e,`status`in this.response&&typeof this.response.status==`function`?this.response.status(e):`status`in this.response&&(this.response.status=e),this}status(){return this._status}statusText(){if(`statusMessage`in this.response)return this.response.statusMessage;if(`statusText`in this.response)return this.response.statusText}setCookie(e,t,n){return this.#e(`Set-Cookie`,`${e}=${t}; ${Object.entries(n||{}).map(([e,t])=>`${e}=${t}`).join(`; `)}`),this}setHeaders(e){for(let[t,n]of Object.entries(e))this.#e(t,n);return this}header(e,t){return this.#e(e,t),this}#e(e,t){this.headers[e]=t,`headers`in this.response?this.response.headers.set(e,t):`setHeader`in this.response&&this.response.setHeader(e,t)}then(e,t){let n=Promise.resolve(this.body).then(e,t);return`send`in this.response&&this.response.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},Oe=class e{body={data:{}};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e;let n=!!this.resource&&typeof this.resource==`object`&&`data`in this.resource,r=n?this.resource.data:void 0,i=!!r&&!Array.isArray(r),a=n?r:this.resource;if(a&&typeof a==`object`&&!Array.isArray(a)&&!M(a)){let e=j(a)?Object.keys(a.toObject()):Object.keys(a);for(let t of e)t in this||Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>j(a)&&typeof a.getAttribute==`function`?a.getAttribute(t):i?r[t]:this.resource[t],set:e=>{if(j(a)&&typeof a.setAttribute==`function`){a.setAttribute(t,e);return}if(i){r[t]=e;return}this.resource[t]=e}})}}data(){return this.resource}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return B(e,t)}whenNotNull(e){return V(e)}mergeWhen(e,t){return H(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=S();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=N(this.data());Array.isArray(t)&&this.collects&&(t=t.map(e=>new this.collects(e).data())),!Array.isArray(t)&&t&&t.data!==void 0&&(t=t.data),t=U(t);let n=I(this.resource),{metaKey:r}=P(),i=r?n[r]:void 0;r&&delete n[r];let a=this.constructor.preferredCase??b();if(a){let e=K(a);t=q(t,e)}let o=A(R(this,e.prototype.with),this.additionalMeta),{wrap:s,rootKey:c,factory:l}=this.resolveResponseStructure();this.body=L({payload:t,meta:i,metaKey:r,wrap:s,rootKey:c,factory:l,context:{type:`generic`,resource:this.resource}}),this.body=k(this.body,{...n,...o||{}},c)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=A(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=k(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=N(this.resource);return!Array.isArray(e)&&e&&e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=e.data;delete e.data,delete e.pagination;let n=this.getPayloadKey();return t&&n&&this.body[n]!==void 0&&(this.body[n]=Array.isArray(this.body[n])?[...this.body[n],...t]:{...this.body[n],...t}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}},ke=class e{body={data:[]};resource;collects;additionalMeta;withResponseContext;isPaginatedCollectible(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.pagination&&Array.isArray(t.data)?!0:t.meta&&typeof t.meta==`object`&&`currentPage`in t.meta?Array.isArray(t.data)||M(t.data):!1}static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return B(e,t)}whenNotNull(e){return V(e)}mergeWhen(e,t){return H(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=S();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data();this.collects&&(t=t.map(e=>new this.collects(e).data())),t=N(t),t=U(t);let n=Array.isArray(this.resource)?{}:I(this.resource),{metaKey:r}=P(),i=r?n[r]:void 0;r&&delete n[r];let a=this.constructor.preferredCase??this.collects?.preferredCase??b();if(a){let e=K(a);t=q(t,e)}let o=A(R(this,e.prototype.with),this.additionalMeta),{wrap:s,rootKey:c,factory:l}=this.resolveResponseStructure();this.body=L({payload:t,meta:i,metaKey:r,wrap:s,rootKey:c,factory:l,context:{type:`collection`,resource:this.resource}}),this.body=k(this.body,{...n,...o||{}},c)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=A(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=k(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){return this.called.toArray=!0,this.json(),N(Array.isArray(this.resource)?this.resource:M(this.resource)?this.resource.all():this.resource.data)}additional(e){this.called.additional=!0,this.json(),delete e.cursor,delete e.pagination;let t=this.getPayloadKey();return e.data&&t&&Array.isArray(this.body[t])&&(this.body[t]=[...this.body[t],...e.data]),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}setCollects(e){return this.collects=e,this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},Ae=class e{body={data:{}};resource;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e;let n=this.resource.data??this.resource;if(!Array.isArray(n)){let e=j(n)?Object.keys(n.toObject()):Object.keys(n);for(let t of e)t in this||Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>j(n)&&typeof n.getAttribute==`function`?n.getAttribute(t):this.resource.data?.[t]??this.resource[t],set:e=>{if(j(n)&&typeof n.setAttribute==`function`){n.setAttribute(t,e);return}this.resource.data&&this.resource.data[t]?this.resource.data[t]=e:this.resource[t]=e}})}}static collection(e){return new ke(e).setCollects(this)}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return B(e,t)}whenNotNull(e){return V(e)}mergeWhen(e,t){return H(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=S();return{wrap:e?.wrap??t?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??`data`,factory:e?.factory??t?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=N(this.data());!Array.isArray(t)&&t&&t.data!==void 0&&(t=t.data),t=U(t);let n=this.constructor.preferredCase??b();if(n){let e=K(n);t=q(t,e)}let r=A(R(this,e.prototype.with),this.additionalMeta),{wrap:i,rootKey:a,factory:o}=this.resolveResponseStructure();this.body=L({payload:t,wrap:i,rootKey:a,factory:o,context:{type:`resource`,resource:this.resource}}),this.body=k(this.body,r,a)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=A(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=k(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=N(this.resource);return!Array.isArray(e)&&e&&e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=this.getPayloadKey();return e.data&&t&&this.body[t]!==void 0&&(this.body[t]=Array.isArray(this.body[t])?[...this.body[t],...e.data]:{...this.body[t],...e.data}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}};exports.ApiResource=ee,exports.CONDITIONAL_ATTRIBUTE_MISSING=z,exports.CliApp=Te,exports.GenericResource=Oe,exports.InitCommand=Ee,exports.MakeResource=De,exports.Resource=Ae,exports.ResourceCollection=ke,exports.ServerResponse=$,exports.appendRootProperties=k,exports.applyRuntimeConfig=xe,exports.buildPaginationExtras=I,exports.buildResponseEnvelope=L,exports.defineConfig=Y,exports.getCaseTransformer=K,exports.getDefaultConfig=ye,exports.getGlobalBaseUrl=le,exports.getGlobalCase=b,exports.getGlobalCursorMeta=he,exports.getGlobalPageName=de,exports.getGlobalPaginatedExtras=w,exports.getGlobalPaginatedLinks=E,exports.getGlobalPaginatedMeta=pe,exports.getGlobalResponseFactory=ce,exports.getGlobalResponseRootKey=oe,exports.getGlobalResponseStructure=S,exports.getGlobalResponseWrap=ae,exports.getPaginationExtraKeys=P,exports.isArkormLikeCollection=M,exports.isArkormLikeModel=j,exports.isPlainObject=O,exports.loadRuntimeConfig=we,exports.mergeMetadata=A,exports.normalizeSerializableData=N,exports.resetRuntimeConfigForTests=be,exports.resolveMergeWhen=H,exports.resolveWhen=B,exports.resolveWhenNotNull=V,exports.resolveWithHookMetadata=R,exports.sanitizeConditionalAttributes=U,exports.setGlobalBaseUrl=D,exports.setGlobalCase=ne,exports.setGlobalCursorMeta=me,exports.setGlobalPageName=ue,exports.setGlobalPaginatedExtras=C,exports.setGlobalPaginatedLinks=T,exports.setGlobalPaginatedMeta=fe,exports.setGlobalResponseFactory=se,exports.setGlobalResponseRootKey=re,exports.setGlobalResponseStructure=x,exports.setGlobalResponseWrap=ie,exports.splitWords=W,exports.toCamelCase=G,exports.toKebabCase=ve,exports.toPascalCase=_e,exports.toSnakeCase=ge,exports.transformKeys=q;
|
package/dist/index.d.cts
CHANGED
|
@@ -99,6 +99,14 @@ interface Collectible {
|
|
|
99
99
|
cursor?: Cursor | undefined;
|
|
100
100
|
pagination?: Pagination | undefined;
|
|
101
101
|
}
|
|
102
|
+
interface CollectionLike<T = any> {
|
|
103
|
+
all: () => T[];
|
|
104
|
+
}
|
|
105
|
+
interface PaginatorLike<T = any> {
|
|
106
|
+
data: CollectionLike<T> | T[] | unknown;
|
|
107
|
+
meta: Record<string, any>;
|
|
108
|
+
links?: Record<string, any>;
|
|
109
|
+
}
|
|
102
110
|
interface ResponseData<R extends ResourceData = any> extends ResourceDef {
|
|
103
111
|
data: R;
|
|
104
112
|
meta?: MetaData | undefined;
|
|
@@ -114,13 +122,21 @@ interface ResponseDataCollection<R extends Collectible | undefined = undefined>
|
|
|
114
122
|
data: R extends Collectible ? R['data'] : R;
|
|
115
123
|
meta?: R extends Collectible ? PaginatedMetaData<R> | undefined : undefined;
|
|
116
124
|
}
|
|
117
|
-
type CollectionBody<R extends ResourceData[] | Collectible = ResourceData[]> = ResponseDataCollection<R extends Collectible ? R : {
|
|
125
|
+
type CollectionBody<R extends ResourceData[] | Collectible | CollectionLike | PaginatorLike = ResourceData[]> = ResponseDataCollection<R extends Collectible ? R : R extends PaginatorLike<infer TPaginatorData> ? {
|
|
126
|
+
data: TPaginatorData[];
|
|
127
|
+
} : R extends CollectionLike<infer T> ? {
|
|
128
|
+
data: T[];
|
|
129
|
+
} : {
|
|
118
130
|
data: R;
|
|
119
131
|
}>;
|
|
120
132
|
type ResourceBody<R extends ResourceData | NonCollectible = ResourceData> = ResponseData<R extends NonCollectible ? R : {
|
|
121
133
|
data: R;
|
|
122
134
|
}>;
|
|
123
|
-
type GenericBody<R extends NonCollectible | Collectible | ResourceData = ResourceData> = ResponseData<R
|
|
135
|
+
type GenericBody<R extends NonCollectible | Collectible | CollectionLike | PaginatorLike | ResourceData = ResourceData> = ResponseData<R extends PaginatorLike<infer TPaginatorData> ? {
|
|
136
|
+
data: TPaginatorData[];
|
|
137
|
+
} : R extends CollectionLike<infer T> ? {
|
|
138
|
+
data: T[];
|
|
139
|
+
} : R>;
|
|
124
140
|
//#endregion
|
|
125
141
|
//#region src/types/config.d.ts
|
|
126
142
|
interface Config {
|
|
@@ -400,7 +416,7 @@ declare class ServerResponse<R extends NonCollectible | Collectible | ResourceDa
|
|
|
400
416
|
/**
|
|
401
417
|
* ResourceCollection class to handle API resource transformation and response building for collections
|
|
402
418
|
*/
|
|
403
|
-
declare class ResourceCollection<R extends ResourceData[] | Collectible = ResourceData[], T extends ResourceData = any> {
|
|
419
|
+
declare class ResourceCollection<R extends ResourceData[] | Collectible | CollectionLike | PaginatorLike = ResourceData[], T extends ResourceData = any> {
|
|
404
420
|
private res?;
|
|
405
421
|
[key: string]: any;
|
|
406
422
|
private body;
|
|
@@ -411,6 +427,7 @@ declare class ResourceCollection<R extends ResourceData[] | Collectible = Resour
|
|
|
411
427
|
response: ServerResponse<CollectionBody<R>>;
|
|
412
428
|
raw: Response | H3Event['res'];
|
|
413
429
|
};
|
|
430
|
+
private isPaginatedCollectible;
|
|
414
431
|
/**
|
|
415
432
|
* Preferred case style for this collection's output keys.
|
|
416
433
|
* Set on a subclass to override the global default.
|
|
@@ -426,7 +443,7 @@ declare class ResourceCollection<R extends ResourceData[] | Collectible = Resour
|
|
|
426
443
|
/**
|
|
427
444
|
* Get the original resource data
|
|
428
445
|
*/
|
|
429
|
-
data(): (R extends Collectible ? R["data"][number] : R extends ResourceData[] ? R[number] : never)[];
|
|
446
|
+
data(): (R extends Collectible ? R["data"][number] : R extends PaginatorLike<infer TPaginatorData> ? TPaginatorData : R extends CollectionLike<infer TCollectionData> ? TCollectionData : R extends ResourceData[] ? R[number] : never)[];
|
|
430
447
|
/**
|
|
431
448
|
* Get the current serialized output body.
|
|
432
449
|
*/
|
|
@@ -474,7 +491,7 @@ declare class ResourceCollection<R extends ResourceData[] | Collectible = Resour
|
|
|
474
491
|
*
|
|
475
492
|
* @returns
|
|
476
493
|
*/
|
|
477
|
-
toArray(): (R extends Collectible ? R['data'][number] : R extends ResourceData[] ? R[number] : never)[];
|
|
494
|
+
toArray(): (R extends Collectible ? R['data'][number] : R extends PaginatorLike<infer TPaginatorData> ? TPaginatorData : R extends CollectionLike<infer TCollectionData> ? TCollectionData : R extends ResourceData[] ? R[number] : never)[];
|
|
478
495
|
/**
|
|
479
496
|
* Add additional properties to the response body
|
|
480
497
|
*
|
|
@@ -546,7 +563,7 @@ declare class Resource<R extends ResourceData | NonCollectible = ResourceData> {
|
|
|
546
563
|
* @param data
|
|
547
564
|
* @returns
|
|
548
565
|
*/
|
|
549
|
-
static collection<C extends ResourceData[] | Collectible = ResourceData[], T extends ResourceData = any>(data: C): ResourceCollection<C, T>;
|
|
566
|
+
static collection<C extends ResourceData[] | Collectible | CollectionLike | PaginatorLike = ResourceData[], T extends ResourceData = any>(data: C): ResourceCollection<C, T>;
|
|
550
567
|
/**
|
|
551
568
|
* Get the original resource data
|
|
552
569
|
*/
|
|
@@ -642,7 +659,7 @@ declare class Resource<R extends ResourceData | NonCollectible = ResourceData> {
|
|
|
642
659
|
/**
|
|
643
660
|
* GenericResource class to handle API resource transformation and response building
|
|
644
661
|
*/
|
|
645
|
-
declare class GenericResource<R extends NonCollectible | Collectible | ResourceData = ResourceData, T extends ResourceData = any> {
|
|
662
|
+
declare class GenericResource<R extends NonCollectible | Collectible | CollectionLike | PaginatorLike | ResourceData = ResourceData, T extends ResourceData = any> {
|
|
646
663
|
private res?;
|
|
647
664
|
[key: string]: any;
|
|
648
665
|
private body;
|
|
@@ -839,6 +856,20 @@ declare const getDefaultConfig: () => Config;
|
|
|
839
856
|
*/
|
|
840
857
|
declare const defineConfig: (config: ResoraConfig) => Config;
|
|
841
858
|
//#endregion
|
|
859
|
+
//#region src/utilities/arkorm.d.ts
|
|
860
|
+
type ArkormLikeModel = {
|
|
861
|
+
toObject: () => Record<string, any>;
|
|
862
|
+
getRawAttributes?: () => Record<string, any>;
|
|
863
|
+
getAttribute?: (key: string) => unknown;
|
|
864
|
+
setAttribute?: (key: string, value: unknown) => unknown;
|
|
865
|
+
};
|
|
866
|
+
type ArkormLikeCollection = {
|
|
867
|
+
all: () => unknown;
|
|
868
|
+
};
|
|
869
|
+
declare const isArkormLikeModel: (value: unknown) => value is ArkormLikeModel;
|
|
870
|
+
declare const isArkormLikeCollection: (value: unknown) => value is ArkormLikeCollection;
|
|
871
|
+
declare const normalizeSerializableData: (value: unknown) => unknown;
|
|
872
|
+
//#endregion
|
|
842
873
|
//#region src/utilities/metadata.d.ts
|
|
843
874
|
/**
|
|
844
875
|
* Resolves metadata from a resource instance by checking for a custom `with` method.
|
|
@@ -1095,4 +1126,4 @@ declare const setGlobalCursorMeta: (meta: Config["cursorMeta"]) => void;
|
|
|
1095
1126
|
*/
|
|
1096
1127
|
declare const getGlobalCursorMeta: () => Config["cursorMeta"];
|
|
1097
1128
|
//#endregion
|
|
1098
|
-
export { ApiResource, CONDITIONAL_ATTRIBUTE_MISSING, CaseStyle, CliApp, Collectible, CollectionBody, Config, Cursor, GenericBody, GenericResource, InitCommand, MakeResource, MetaData, NonCollectible, PaginatedMetaData, Pagination, ResoraConfig, Resource, ResourceBody, ResourceCollection, ResourceData, ResourceDef, ResponseData, ResponseDataCollection, ResponseFactory, ResponseFactoryContext, ResponseKind, ResponseStructureConfig, ServerResponse, appendRootProperties, applyRuntimeConfig, buildPaginationExtras, buildResponseEnvelope, defineConfig, getCaseTransformer, getDefaultConfig, getGlobalBaseUrl, getGlobalCase, getGlobalCursorMeta, getGlobalPageName, getGlobalPaginatedExtras, getGlobalPaginatedLinks, getGlobalPaginatedMeta, getGlobalResponseFactory, getGlobalResponseRootKey, getGlobalResponseStructure, getGlobalResponseWrap, getPaginationExtraKeys, isPlainObject, loadRuntimeConfig, mergeMetadata, resetRuntimeConfigForTests, resolveMergeWhen, resolveWhen, resolveWhenNotNull, resolveWithHookMetadata, sanitizeConditionalAttributes, setGlobalBaseUrl, setGlobalCase, setGlobalCursorMeta, setGlobalPageName, setGlobalPaginatedExtras, setGlobalPaginatedLinks, setGlobalPaginatedMeta, setGlobalResponseFactory, setGlobalResponseRootKey, setGlobalResponseStructure, setGlobalResponseWrap, splitWords, toCamelCase, toKebabCase, toPascalCase, toSnakeCase, transformKeys };
|
|
1129
|
+
export { ApiResource, CONDITIONAL_ATTRIBUTE_MISSING, CaseStyle, CliApp, Collectible, CollectionBody, CollectionLike, Config, Cursor, GenericBody, GenericResource, InitCommand, MakeResource, MetaData, NonCollectible, PaginatedMetaData, Pagination, PaginatorLike, ResoraConfig, Resource, ResourceBody, ResourceCollection, ResourceData, ResourceDef, ResponseData, ResponseDataCollection, ResponseFactory, ResponseFactoryContext, ResponseKind, ResponseStructureConfig, ServerResponse, appendRootProperties, applyRuntimeConfig, buildPaginationExtras, buildResponseEnvelope, defineConfig, getCaseTransformer, getDefaultConfig, getGlobalBaseUrl, getGlobalCase, getGlobalCursorMeta, getGlobalPageName, getGlobalPaginatedExtras, getGlobalPaginatedLinks, getGlobalPaginatedMeta, getGlobalResponseFactory, getGlobalResponseRootKey, getGlobalResponseStructure, getGlobalResponseWrap, getPaginationExtraKeys, isArkormLikeCollection, isArkormLikeModel, isPlainObject, loadRuntimeConfig, mergeMetadata, normalizeSerializableData, resetRuntimeConfigForTests, resolveMergeWhen, resolveWhen, resolveWhenNotNull, resolveWithHookMetadata, sanitizeConditionalAttributes, setGlobalBaseUrl, setGlobalCase, setGlobalCursorMeta, setGlobalPageName, setGlobalPaginatedExtras, setGlobalPaginatedLinks, setGlobalPaginatedMeta, setGlobalResponseFactory, setGlobalResponseRootKey, setGlobalResponseStructure, setGlobalResponseWrap, splitWords, toCamelCase, toKebabCase, toPascalCase, toSnakeCase, transformKeys };
|
package/dist/index.d.mts
CHANGED
|
@@ -99,6 +99,14 @@ interface Collectible {
|
|
|
99
99
|
cursor?: Cursor | undefined;
|
|
100
100
|
pagination?: Pagination | undefined;
|
|
101
101
|
}
|
|
102
|
+
interface CollectionLike<T = any> {
|
|
103
|
+
all: () => T[];
|
|
104
|
+
}
|
|
105
|
+
interface PaginatorLike<T = any> {
|
|
106
|
+
data: CollectionLike<T> | T[] | unknown;
|
|
107
|
+
meta: Record<string, any>;
|
|
108
|
+
links?: Record<string, any>;
|
|
109
|
+
}
|
|
102
110
|
interface ResponseData<R extends ResourceData = any> extends ResourceDef {
|
|
103
111
|
data: R;
|
|
104
112
|
meta?: MetaData | undefined;
|
|
@@ -114,13 +122,21 @@ interface ResponseDataCollection<R extends Collectible | undefined = undefined>
|
|
|
114
122
|
data: R extends Collectible ? R['data'] : R;
|
|
115
123
|
meta?: R extends Collectible ? PaginatedMetaData<R> | undefined : undefined;
|
|
116
124
|
}
|
|
117
|
-
type CollectionBody<R extends ResourceData[] | Collectible = ResourceData[]> = ResponseDataCollection<R extends Collectible ? R : {
|
|
125
|
+
type CollectionBody<R extends ResourceData[] | Collectible | CollectionLike | PaginatorLike = ResourceData[]> = ResponseDataCollection<R extends Collectible ? R : R extends PaginatorLike<infer TPaginatorData> ? {
|
|
126
|
+
data: TPaginatorData[];
|
|
127
|
+
} : R extends CollectionLike<infer T> ? {
|
|
128
|
+
data: T[];
|
|
129
|
+
} : {
|
|
118
130
|
data: R;
|
|
119
131
|
}>;
|
|
120
132
|
type ResourceBody<R extends ResourceData | NonCollectible = ResourceData> = ResponseData<R extends NonCollectible ? R : {
|
|
121
133
|
data: R;
|
|
122
134
|
}>;
|
|
123
|
-
type GenericBody<R extends NonCollectible | Collectible | ResourceData = ResourceData> = ResponseData<R
|
|
135
|
+
type GenericBody<R extends NonCollectible | Collectible | CollectionLike | PaginatorLike | ResourceData = ResourceData> = ResponseData<R extends PaginatorLike<infer TPaginatorData> ? {
|
|
136
|
+
data: TPaginatorData[];
|
|
137
|
+
} : R extends CollectionLike<infer T> ? {
|
|
138
|
+
data: T[];
|
|
139
|
+
} : R>;
|
|
124
140
|
//#endregion
|
|
125
141
|
//#region src/types/config.d.ts
|
|
126
142
|
interface Config {
|
|
@@ -400,7 +416,7 @@ declare class ServerResponse<R extends NonCollectible | Collectible | ResourceDa
|
|
|
400
416
|
/**
|
|
401
417
|
* ResourceCollection class to handle API resource transformation and response building for collections
|
|
402
418
|
*/
|
|
403
|
-
declare class ResourceCollection<R extends ResourceData[] | Collectible = ResourceData[], T extends ResourceData = any> {
|
|
419
|
+
declare class ResourceCollection<R extends ResourceData[] | Collectible | CollectionLike | PaginatorLike = ResourceData[], T extends ResourceData = any> {
|
|
404
420
|
private res?;
|
|
405
421
|
[key: string]: any;
|
|
406
422
|
private body;
|
|
@@ -411,6 +427,7 @@ declare class ResourceCollection<R extends ResourceData[] | Collectible = Resour
|
|
|
411
427
|
response: ServerResponse<CollectionBody<R>>;
|
|
412
428
|
raw: Response | H3Event['res'];
|
|
413
429
|
};
|
|
430
|
+
private isPaginatedCollectible;
|
|
414
431
|
/**
|
|
415
432
|
* Preferred case style for this collection's output keys.
|
|
416
433
|
* Set on a subclass to override the global default.
|
|
@@ -426,7 +443,7 @@ declare class ResourceCollection<R extends ResourceData[] | Collectible = Resour
|
|
|
426
443
|
/**
|
|
427
444
|
* Get the original resource data
|
|
428
445
|
*/
|
|
429
|
-
data(): (R extends Collectible ? R["data"][number] : R extends ResourceData[] ? R[number] : never)[];
|
|
446
|
+
data(): (R extends Collectible ? R["data"][number] : R extends PaginatorLike<infer TPaginatorData> ? TPaginatorData : R extends CollectionLike<infer TCollectionData> ? TCollectionData : R extends ResourceData[] ? R[number] : never)[];
|
|
430
447
|
/**
|
|
431
448
|
* Get the current serialized output body.
|
|
432
449
|
*/
|
|
@@ -474,7 +491,7 @@ declare class ResourceCollection<R extends ResourceData[] | Collectible = Resour
|
|
|
474
491
|
*
|
|
475
492
|
* @returns
|
|
476
493
|
*/
|
|
477
|
-
toArray(): (R extends Collectible ? R['data'][number] : R extends ResourceData[] ? R[number] : never)[];
|
|
494
|
+
toArray(): (R extends Collectible ? R['data'][number] : R extends PaginatorLike<infer TPaginatorData> ? TPaginatorData : R extends CollectionLike<infer TCollectionData> ? TCollectionData : R extends ResourceData[] ? R[number] : never)[];
|
|
478
495
|
/**
|
|
479
496
|
* Add additional properties to the response body
|
|
480
497
|
*
|
|
@@ -546,7 +563,7 @@ declare class Resource<R extends ResourceData | NonCollectible = ResourceData> {
|
|
|
546
563
|
* @param data
|
|
547
564
|
* @returns
|
|
548
565
|
*/
|
|
549
|
-
static collection<C extends ResourceData[] | Collectible = ResourceData[], T extends ResourceData = any>(data: C): ResourceCollection<C, T>;
|
|
566
|
+
static collection<C extends ResourceData[] | Collectible | CollectionLike | PaginatorLike = ResourceData[], T extends ResourceData = any>(data: C): ResourceCollection<C, T>;
|
|
550
567
|
/**
|
|
551
568
|
* Get the original resource data
|
|
552
569
|
*/
|
|
@@ -642,7 +659,7 @@ declare class Resource<R extends ResourceData | NonCollectible = ResourceData> {
|
|
|
642
659
|
/**
|
|
643
660
|
* GenericResource class to handle API resource transformation and response building
|
|
644
661
|
*/
|
|
645
|
-
declare class GenericResource<R extends NonCollectible | Collectible | ResourceData = ResourceData, T extends ResourceData = any> {
|
|
662
|
+
declare class GenericResource<R extends NonCollectible | Collectible | CollectionLike | PaginatorLike | ResourceData = ResourceData, T extends ResourceData = any> {
|
|
646
663
|
private res?;
|
|
647
664
|
[key: string]: any;
|
|
648
665
|
private body;
|
|
@@ -839,6 +856,20 @@ declare const getDefaultConfig: () => Config;
|
|
|
839
856
|
*/
|
|
840
857
|
declare const defineConfig: (config: ResoraConfig) => Config;
|
|
841
858
|
//#endregion
|
|
859
|
+
//#region src/utilities/arkorm.d.ts
|
|
860
|
+
type ArkormLikeModel = {
|
|
861
|
+
toObject: () => Record<string, any>;
|
|
862
|
+
getRawAttributes?: () => Record<string, any>;
|
|
863
|
+
getAttribute?: (key: string) => unknown;
|
|
864
|
+
setAttribute?: (key: string, value: unknown) => unknown;
|
|
865
|
+
};
|
|
866
|
+
type ArkormLikeCollection = {
|
|
867
|
+
all: () => unknown;
|
|
868
|
+
};
|
|
869
|
+
declare const isArkormLikeModel: (value: unknown) => value is ArkormLikeModel;
|
|
870
|
+
declare const isArkormLikeCollection: (value: unknown) => value is ArkormLikeCollection;
|
|
871
|
+
declare const normalizeSerializableData: (value: unknown) => unknown;
|
|
872
|
+
//#endregion
|
|
842
873
|
//#region src/utilities/metadata.d.ts
|
|
843
874
|
/**
|
|
844
875
|
* Resolves metadata from a resource instance by checking for a custom `with` method.
|
|
@@ -1095,4 +1126,4 @@ declare const setGlobalCursorMeta: (meta: Config["cursorMeta"]) => void;
|
|
|
1095
1126
|
*/
|
|
1096
1127
|
declare const getGlobalCursorMeta: () => Config["cursorMeta"];
|
|
1097
1128
|
//#endregion
|
|
1098
|
-
export { ApiResource, CONDITIONAL_ATTRIBUTE_MISSING, CaseStyle, CliApp, Collectible, CollectionBody, Config, Cursor, GenericBody, GenericResource, InitCommand, MakeResource, MetaData, NonCollectible, PaginatedMetaData, Pagination, ResoraConfig, Resource, ResourceBody, ResourceCollection, ResourceData, ResourceDef, ResponseData, ResponseDataCollection, ResponseFactory, ResponseFactoryContext, ResponseKind, ResponseStructureConfig, ServerResponse, appendRootProperties, applyRuntimeConfig, buildPaginationExtras, buildResponseEnvelope, defineConfig, getCaseTransformer, getDefaultConfig, getGlobalBaseUrl, getGlobalCase, getGlobalCursorMeta, getGlobalPageName, getGlobalPaginatedExtras, getGlobalPaginatedLinks, getGlobalPaginatedMeta, getGlobalResponseFactory, getGlobalResponseRootKey, getGlobalResponseStructure, getGlobalResponseWrap, getPaginationExtraKeys, isPlainObject, loadRuntimeConfig, mergeMetadata, resetRuntimeConfigForTests, resolveMergeWhen, resolveWhen, resolveWhenNotNull, resolveWithHookMetadata, sanitizeConditionalAttributes, setGlobalBaseUrl, setGlobalCase, setGlobalCursorMeta, setGlobalPageName, setGlobalPaginatedExtras, setGlobalPaginatedLinks, setGlobalPaginatedMeta, setGlobalResponseFactory, setGlobalResponseRootKey, setGlobalResponseStructure, setGlobalResponseWrap, splitWords, toCamelCase, toKebabCase, toPascalCase, toSnakeCase, transformKeys };
|
|
1129
|
+
export { ApiResource, CONDITIONAL_ATTRIBUTE_MISSING, CaseStyle, CliApp, Collectible, CollectionBody, CollectionLike, Config, Cursor, GenericBody, GenericResource, InitCommand, MakeResource, MetaData, NonCollectible, PaginatedMetaData, Pagination, PaginatorLike, ResoraConfig, Resource, ResourceBody, ResourceCollection, ResourceData, ResourceDef, ResponseData, ResponseDataCollection, ResponseFactory, ResponseFactoryContext, ResponseKind, ResponseStructureConfig, ServerResponse, appendRootProperties, applyRuntimeConfig, buildPaginationExtras, buildResponseEnvelope, defineConfig, getCaseTransformer, getDefaultConfig, getGlobalBaseUrl, getGlobalCase, getGlobalCursorMeta, getGlobalPageName, getGlobalPaginatedExtras, getGlobalPaginatedLinks, getGlobalPaginatedMeta, getGlobalResponseFactory, getGlobalResponseRootKey, getGlobalResponseStructure, getGlobalResponseWrap, getPaginationExtraKeys, isArkormLikeCollection, isArkormLikeModel, isPlainObject, loadRuntimeConfig, mergeMetadata, normalizeSerializableData, resetRuntimeConfigForTests, resolveMergeWhen, resolveWhen, resolveWhenNotNull, resolveWithHookMetadata, sanitizeConditionalAttributes, setGlobalBaseUrl, setGlobalCase, setGlobalCursorMeta, setGlobalPageName, setGlobalPaginatedExtras, setGlobalPaginatedLinks, setGlobalPaginatedMeta, setGlobalResponseFactory, setGlobalResponseRootKey, setGlobalResponseStructure, setGlobalResponseWrap, splitWords, toCamelCase, toKebabCase, toPascalCase, toSnakeCase, transformKeys };
|
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,rmSync as i,writeFileSync as a}from"fs";import o,{dirname as s,join as c}from"path";import{createRequire as l}from"module";import{pathToFileURL as u}from"url";import{Command as d}from"@h3ravel/musket";function
|
|
1
|
+
import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,rmSync as i,writeFileSync as a}from"fs";import o,{dirname as s,join as c}from"path";import{createRequire as l}from"module";import{pathToFileURL as u}from"url";import{Command as d}from"@h3ravel/musket";function ee(e){return e}let f,p,m=[`meta`,`links`],h={first:`first`,last:`last`,prev:`prev`,next:`next`},g=`https://localhost`,_=`page`,v={to:`to`,from:`from`,links:`links`,path:`path`,total:`total`,per_page:`per_page`,last_page:`last_page`,current_page:`current_page`},y={previous:`previous`,next:`next`};const b=e=>{f=e},x=()=>f,S=e=>{p=e},C=()=>p,te=e=>{p={...p||{},rootKey:e}},ne=e=>{p={...p||{},wrap:e}},re=()=>p?.wrap,ie=()=>p?.rootKey,ae=e=>{p={...p||{},factory:e}},oe=()=>p?.factory,w=e=>{m=e},T=()=>m,E=e=>{h={...h,...e}},se=()=>h,ce=e=>{g=e},le=()=>g,ue=e=>{_=e},de=()=>_,fe=e=>{v={...v,...e}},D=()=>v,O=e=>{y={...y,...e}},pe=()=>y,k=e=>{if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Date||e instanceof RegExp)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},A=(e,t,n=`data`)=>!t||Object.keys(t).length===0?e:Array.isArray(e)?{[n]:e,...t}:k(e)?{...e,...t}:{[n]:e,...t},j=(e,t)=>{if(!t)return e;if(!e)return t;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];k(t)&&k(r)?n[e]=j(t,r):n[e]=r}return n},M=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.toObject==`function`&&typeof t.getRawAttributes==`function`},N=e=>!e||typeof e!=`object`?!1:typeof e.all==`function`,P=e=>{if(Array.isArray(e))return e.map(e=>P(e));if(M(e))return P(e.toObject());if(N(e)){let t=e.all();return Array.isArray(t)?t.map(e=>P(e)):P(t)}return k(e)?Object.entries(e).reduce((e,[t,n])=>(e[t]=P(n),e),{}):e},F=()=>{let e=T();return Array.isArray(e)?{metaKey:e.includes(`meta`)?`meta`:void 0,linksKey:e.includes(`links`)?`links`:void 0,cursorKey:e.includes(`cursor`)?`cursor`:void 0}:{metaKey:e.meta,linksKey:e.links,cursorKey:e.cursor}},I=(e,t)=>{if(e===void 0)return;let n=t||``,r=le()||``,i=/^https?:\/\//i.test(n),a=r.replace(/\/$/,``),o=n.replace(/^\//,``),s=i?n:a?o?`${a}/${o}`:a:``;if(!s)return;let c=new URL(s);return c.searchParams.set(de()||`page`,String(e)),c.toString()},L=e=>{let{metaKey:t,linksKey:n,cursorKey:r}=F(),i={},a=!!e&&typeof e==`object`&&!!e.meta&&typeof e.meta==`object`&&(Array.isArray(e.data)||N(e.data)),o=a?{first:typeof e.firstPageUrl==`function`?e.firstPageUrl():void 0,last:typeof e.lastPageUrl==`function`?e.lastPageUrl():void 0,prev:typeof e.previousPageUrl==`function`?e.previousPageUrl():void 0,next:typeof e.nextPageUrl==`function`?e.nextPageUrl():void 0}:void 0,s=o?Object.entries(o).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),{}):void 0,c=e?.pagination||(a?{...e.meta,links:e.links||s}:void 0),l=e?.cursor,u={},d={};if(c){let e={to:c.to,from:c.from,links:c.links,path:c.path,total:c.total,per_page:c.perPage,last_page:c.lastPage,current_page:c.currentPage};for(let[t,n]of Object.entries(D())){if(!n)continue;let r=e[t];r!==void 0&&(u[n]=r)}let t={first:c.links&&Object.prototype.hasOwnProperty.call(c.links,`first`)?c.links.first:I(c.firstPage,c.path),last:c.links&&Object.prototype.hasOwnProperty.call(c.links,`last`)?c.links.last:I(c.lastPage,c.path),prev:c.links&&Object.prototype.hasOwnProperty.call(c.links,`prev`)?c.links.prev:I(c.prevPage,c.path),next:c.links&&Object.prototype.hasOwnProperty.call(c.links,`next`)?c.links.next:I(c.nextPage,c.path)};for(let[e,n]of Object.entries(se())){if(!n)continue;let r=t[e];r!==void 0&&(d[n]=r)}}if(l){let e={},t={previous:l.previous,next:l.next};for(let[n,r]of Object.entries(pe())){if(!r)continue;let i=t[n];i!==void 0&&(e[r]=i)}r&&Object.keys(e).length>0?i[r]=e:Object.keys(e).length>0&&(u.cursor=e)}return t&&Object.keys(u).length>0&&(i[t]=u),n&&Object.keys(d).length>0&&(i[n]=d),i},R=({payload:e,meta:t,metaKey:n=`meta`,wrap:r=!0,rootKey:i=`data`,factory:a,context:o})=>{if(a)return a(e,{...o,rootKey:i,meta:t});if(!r)return t===void 0?e:k(e)?{...e,[n]:t}:{[i]:e,[n]:t};let s={[i]:e};return t!==void 0&&(s[n]=t),s},z=(e,t)=>{let n=e?.with;if(typeof n!=`function`||n===t||n.length>0)return;let r=n.call(e);return k(r)?r:void 0},B=Symbol(`resora.conditional.missing`),V=(e,t)=>e?typeof t==`function`?t():t:B,H=e=>e??B,U=(e,t)=>{if(!e)return{};let n=typeof t==`function`?t():t;return k(n)?n:{}},W=e=>{if(e===B)return B;if(Array.isArray(e))return e.map(e=>W(e)).filter(e=>e!==B);if(k(e)){let t={};for(let[n,r]of Object.entries(e)){let e=W(r);e!==B&&(t[n]=e)}return t}return e},G=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/[-_\s]+/g,` `).trim().toLowerCase().split(` `).filter(Boolean),K=e=>G(e).map((e,t)=>t===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(``),me=e=>G(e).join(`_`),he=e=>G(e).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``),ge=e=>G(e).join(`-`),q=e=>{if(typeof e==`function`)return e;switch(e){case`camel`:return K;case`snake`:return me;case`pascal`:return he;case`kebab`:return ge}},J=(e,t)=>e==null?e:Array.isArray(e)?e.map(e=>J(e,t)):e instanceof Date||e instanceof RegExp?e:typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[t(e),J(n,t)])):e;let Y=o.resolve(process.cwd(),`node_modules/resora/stubs`);t(Y)||(Y=o.resolve(process.cwd(),`stubs`));const _e=()=>({stubsDir:Y,preferredCase:`camel`,responseStructure:{wrap:!0,rootKey:`data`},paginatedExtras:[`meta`,`links`],baseUrl:`https://localhost`,pageName:`page`,paginatedLinks:{first:`first`,last:`last`,prev:`prev`,next:`next`},paginatedMeta:{to:`to`,from:`from`,links:`links`,path:`path`,total:`total`,per_page:`per_page`,last_page:`last_page`,current_page:`current_page`},cursorMeta:{previous:`previous`,next:`next`},resourcesDir:`src/resources`,stubs:{config:`resora.config.stub`,resource:`resource.stub`,collection:`resource.collection.stub`}}),X=e=>{let t=_e();return Object.assign(t,e,{stubs:Object.assign(t.stubs,e.stubs||{})},{cursorMeta:Object.assign(t.cursorMeta,e.cursorMeta||{})},{paginatedMeta:Object.assign(t.paginatedMeta,e.paginatedMeta||{})},{paginatedLinks:Object.assign(t.paginatedLinks,e.paginatedLinks||{})},{responseStructure:Object.assign(t.responseStructure,e.responseStructure||{})})};let Z=!1,Q;const ve=()=>{Z=!1,Q=void 0},ye=e=>{e.preferredCase!==`camel`&&b(e.preferredCase),S(e.responseStructure),w(e.paginatedExtras),E(e.paginatedLinks),fe(e.paginatedMeta),O(e.cursorMeta),ce(e.baseUrl),ue(e.pageName)},be=async e=>await import(`${u(e).href}?resora_runtime=${Date.now()}`),xe=e=>{ye(X((e?.default??e)||{})),Z=!0},Se=()=>{let e=l(import.meta.url),n=[o.join(process.cwd(),`resora.config.cjs`)];for(let r of n)if(t(r))try{return xe(e(r)),!0}catch{continue}return!1},Ce=async()=>{if(!Z){if(Q)return await Q;Se()||(Q=(async()=>{let e=[o.join(process.cwd(),`resora.config.js`),o.join(process.cwd(),`resora.config.ts`)];for(let n of e)if(t(n))try{xe(await be(n));return}catch{continue}Z=!0})(),await Q)}};Ce();var we=class{command;config={};constructor(e={}){this.config=X(e)}async loadConfig(e={}){this.config=X(e);let n=[c(process.cwd(),`resora.config.ts`),c(process.cwd(),`resora.config.js`),c(process.cwd(),`resora.config.cjs`)];for(let e of n)if(t(e))try{let{default:t}=await import(e);Object.assign(this.config,t);break}catch(t){console.error(`Error loading config file at ${e}:`,t)}return this}getConfig(){return this.config}init(){let n=c(process.cwd(),`resora.config.js`),i=c(this.config.stubsDir,this.config.stubs.config);return t(n)&&!this.command.option(`force`)&&(this.command.error(`Error: ${n} already exists.`),process.exit(1)),this.ensureDirectory(n),t(n)&&this.command.option(`force`)&&e(n,n.replace(/\.js$/,`.backup.${Date.now()}.js`)),a(n,r(i,`utf-8`)),{path:n}}ensureDirectory(e){let r=s(e);t(r)||n(r,{recursive:!0})}generateFile(e,n,o,s){t(n)&&!s?.force?(this.command.error(`Error: ${n} already exists.`),process.exit(1)):t(n)&&s?.force&&i(n);let c=r(e,`utf-8`);for(let[e,t]of Object.entries(o))c=c.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(n),a(n,c),n}makeResource(e,n){let r=e;n?.collection&&!e.endsWith(`Collection`)&&!e.endsWith(`Resource`)?r+=`Collection`:!n?.collection&&!e.endsWith(`Resource`)&&!e.endsWith(`Collection`)&&(r+=`Resource`);let i=`${r}.ts`,a=c(this.config.resourcesDir,i),o=c(this.config.stubsDir,n?.collection||e.endsWith(`Collection`)?this.config.stubs.collection:this.config.stubs.resource);t(o)||(this.command.error(`Error: Stub file ${o} not found.`),process.exit(1));let s=r.replace(/(Resource|Collection)$/,``)+`Resource`,l=`/**
|
|
2
2
|
* The resource that this collection collects.
|
|
3
3
|
*/
|
|
4
4
|
collects = ${s}
|
|
5
|
-
`,u=`import ${s} from './${s}'\n`,d=(!!n?.collection||e.endsWith(`Collection`))&&t(c(this.config.resourcesDir,`${s}.ts`)),
|
|
5
|
+
`,u=`import ${s} from './${s}'\n`,d=(!!n?.collection||e.endsWith(`Collection`))&&t(c(this.config.resourcesDir,`${s}.ts`)),ee=this.generateFile(o,a,{ResourceName:r,CollectionResourceName:r.replace(/(Resource|Collection)$/,``)+`Resource`,"collects = Resource":d?l:``,"import = Resource":d?u:``},n);return{name:r,path:ee}}},Te=class extends d{signature=`init
|
|
6
6
|
{--force : Force overwrite if config file already exists (existing file will be backed up) }
|
|
7
|
-
`;description=`Initialize Resora`;async handle(){this.app.command=this,this.app.init(),this.success(`Resora initialized`)}},
|
|
7
|
+
`;description=`Initialize Resora`;async handle(){this.app.command=this,this.app.init(),this.success(`Resora initialized`)}},Ee=class extends d{signature=`#create:
|
|
8
8
|
{resource : Generates a new resource file.
|
|
9
9
|
| {name : Name of the resource to create}
|
|
10
10
|
| {--c|collection : Make a resource collection}
|
|
@@ -25,4 +25,4 @@ import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,rmSync
|
|
|
25
25
|
| _ // _ \/ __|/ _ \| '__/ _, |
|
|
26
26
|
| | \ \ __/\__ \ (_) | | | (_| |
|
|
27
27
|
|_| \_\___||___/\___/|_| \__,_|
|
|
28
|
-
`;var $=class{_status=200;headers={};constructor(e,t){this.response=e,this.body=t}setStatusCode(e){return this._status=e,`status`in this.response&&typeof this.response.status==`function`?this.response.status(e):`status`in this.response&&(this.response.status=e),this}status(){return this._status}statusText(){if(`statusMessage`in this.response)return this.response.statusMessage;if(`statusText`in this.response)return this.response.statusText}setCookie(e,t,n){return this.#e(`Set-Cookie`,`${e}=${t}; ${Object.entries(n||{}).map(([e,t])=>`${e}=${t}`).join(`; `)}`),this}setHeaders(e){for(let[t,n]of Object.entries(e))this.#e(t,n);return this}header(e,t){return this.#e(e,t),this}#e(e,t){this.headers[e]=t,`headers`in this.response?this.response.headers.set(e,t):`setHeader`in this.response&&this.response.setHeader(e,t)}then(e,t){let n=Promise.resolve(this.body).then(e,t);return`send`in this.response&&this.response.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},we=class e{body={data:{}};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){if(this.res=t,this.resource=e,!Array.isArray(this.resource.data??this.resource))for(let e of Object.keys(this.resource.data??this.resource))e in this||Object.defineProperty(this,e,{enumerable:!0,configurable:!0,get:()=>this.resource.data?.[e]??this.resource[e],set:t=>{this.resource.data&&this.resource.data[e]?this.resource.data[e]=t:this.resource[e]=t}})}data(){return this.resource}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data(),n=Array.isArray(t)?[...t]:{...t};Array.isArray(n)&&this.collects&&(n=n.map(e=>new this.collects(e).data()),this.resource=n),n.data!==void 0&&(n=n.data),n=V(n);let r=j(this.resource),{metaKey:i}=k(),a=i?r[i]:void 0;i&&delete r[i];let o=this.constructor.preferredCase??x();if(o){let e=q(o);n=J(n,e)}let s=P(I(this,e.prototype.with),this.additionalMeta),{wrap:c,rootKey:l,factory:u}=this.resolveResponseStructure();this.body=F({payload:n,meta:a,metaKey:i,wrap:c,rootKey:l,factory:u,context:{type:`generic`,resource:this.resource}}),this.body=N(this.body,{...r,...s||{}},l)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=Array.isArray(this.resource)?[...this.resource]:{...this.resource};return e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=e.data;delete e.data,delete e.pagination;let n=this.getPayloadKey();return t&&n&&this.body[n]!==void 0&&(this.body[n]=Array.isArray(this.body[n])?[...this.body[n],...t]:{...this.body[n],...t}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}},Te=class e{body={data:[]};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data();this.collects&&(t=t.map(e=>new this.collects(e).data())),t=V(t);let n=Array.isArray(this.resource)?{}:j(this.resource),{metaKey:r}=k(),i=r?n[r]:void 0;r&&delete n[r];let a=this.constructor.preferredCase??this.collects?.preferredCase??x();if(a){let e=q(a);t=J(t,e)}let o=P(I(this,e.prototype.with),this.additionalMeta),{wrap:s,rootKey:c,factory:l}=this.resolveResponseStructure();this.body=F({payload:t,meta:i,metaKey:r,wrap:s,rootKey:c,factory:l,context:{type:`collection`,resource:this.resource}}),this.body=N(this.body,{...n,...o||{}},c)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){return this.called.toArray=!0,this.json(),Array.isArray(this.resource)?[...this.resource]:[...this.resource.data]}additional(e){this.called.additional=!0,this.json(),delete e.cursor,delete e.pagination;let t=this.getPayloadKey();return e.data&&t&&Array.isArray(this.body[t])&&(this.body[t]=[...this.body[t],...e.data]),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}setCollects(e){return this.collects=e,this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},Ee=class e{body={data:{}};resource;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){if(this.res=t,this.resource=e,!Array.isArray(this.resource.data??this.resource))for(let e of Object.keys(this.resource.data??this.resource))e in this||Object.defineProperty(this,e,{enumerable:!0,configurable:!0,get:()=>this.resource.data?.[e]??this.resource[e],set:t=>{this.resource.data&&this.resource.data[e]?this.resource.data[e]=t:this.resource[e]=t}})}static collection(e){return new Te(e).setCollects(this)}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return R(e,t)}whenNotNull(e){return z(e)}mergeWhen(e,t){return B(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=C();return{wrap:e?.wrap??t?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??`data`,factory:e?.factory??t?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data(),n=Array.isArray(t)?[...t]:{...t};n.data!==void 0&&(n=n.data),n=V(n);let r=this.constructor.preferredCase??x();if(r){let e=q(r);n=J(n,e)}let i=P(I(this,e.prototype.with),this.additionalMeta),{wrap:a,rootKey:o,factory:s}=this.resolveResponseStructure();this.body=F({payload:n,wrap:a,rootKey:o,factory:s,context:{type:`resource`,resource:this.resource}}),this.body=N(this.body,i,o)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=P(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=N(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=Array.isArray(this.resource)?[...this.resource]:{...this.resource};return!Array.isArray(e)&&e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=this.getPayloadKey();return e.data&&t&&this.body[t]!==void 0&&(this.body[t]=Array.isArray(this.body[t])?[...this.body[t],...e.data]:{...this.body[t],...e.data}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}};export{f as ApiResource,L as CONDITIONAL_ATTRIBUTE_MISSING,xe as CliApp,we as GenericResource,Se as InitCommand,Ce as MakeResource,Ee as Resource,Te as ResourceCollection,$ as ServerResponse,N as appendRootProperties,ge as applyRuntimeConfig,j as buildPaginationExtras,F as buildResponseEnvelope,X as defineConfig,q as getCaseTransformer,me as getDefaultConfig,le as getGlobalBaseUrl,x as getGlobalCase,O as getGlobalCursorMeta,de as getGlobalPageName,T as getGlobalPaginatedExtras,se as getGlobalPaginatedLinks,pe as getGlobalPaginatedMeta,oe as getGlobalResponseFactory,ie as getGlobalResponseRootKey,C as getGlobalResponseStructure,re as getGlobalResponseWrap,k as getPaginationExtraKeys,M as isPlainObject,be as loadRuntimeConfig,P as mergeMetadata,he as resetRuntimeConfigForTests,B as resolveMergeWhen,R as resolveWhen,z as resolveWhenNotNull,I as resolveWithHookMetadata,V as sanitizeConditionalAttributes,ce as setGlobalBaseUrl,b as setGlobalCase,D as setGlobalCursorMeta,ue as setGlobalPageName,w as setGlobalPaginatedExtras,E as setGlobalPaginatedLinks,fe as setGlobalPaginatedMeta,ae as setGlobalResponseFactory,te as setGlobalResponseRootKey,S as setGlobalResponseStructure,ne as setGlobalResponseWrap,H as splitWords,U as toCamelCase,K as toKebabCase,G as toPascalCase,W as toSnakeCase,J as transformKeys};
|
|
28
|
+
`;var $=class{_status=200;headers={};constructor(e,t){this.response=e,this.body=t}setStatusCode(e){return this._status=e,`status`in this.response&&typeof this.response.status==`function`?this.response.status(e):`status`in this.response&&(this.response.status=e),this}status(){return this._status}statusText(){if(`statusMessage`in this.response)return this.response.statusMessage;if(`statusText`in this.response)return this.response.statusText}setCookie(e,t,n){return this.#e(`Set-Cookie`,`${e}=${t}; ${Object.entries(n||{}).map(([e,t])=>`${e}=${t}`).join(`; `)}`),this}setHeaders(e){for(let[t,n]of Object.entries(e))this.#e(t,n);return this}header(e,t){return this.#e(e,t),this}#e(e,t){this.headers[e]=t,`headers`in this.response?this.response.headers.set(e,t):`setHeader`in this.response&&this.response.setHeader(e,t)}then(e,t){let n=Promise.resolve(this.body).then(e,t);return`send`in this.response&&this.response.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},De=class e{body={data:{}};resource;collects;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e;let n=!!this.resource&&typeof this.resource==`object`&&`data`in this.resource,r=n?this.resource.data:void 0,i=!!r&&!Array.isArray(r),a=n?r:this.resource;if(a&&typeof a==`object`&&!Array.isArray(a)&&!N(a)){let e=M(a)?Object.keys(a.toObject()):Object.keys(a);for(let t of e)t in this||Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>M(a)&&typeof a.getAttribute==`function`?a.getAttribute(t):i?r[t]:this.resource[t],set:e=>{if(M(a)&&typeof a.setAttribute==`function`){a.setAttribute(t,e);return}if(i){r[t]=e;return}this.resource[t]=e}})}}data(){return this.resource}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return V(e,t)}whenNotNull(e){return H(e)}mergeWhen(e,t){return U(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=P(this.data());Array.isArray(t)&&this.collects&&(t=t.map(e=>new this.collects(e).data())),!Array.isArray(t)&&t&&t.data!==void 0&&(t=t.data),t=W(t);let n=L(this.resource),{metaKey:r}=F(),i=r?n[r]:void 0;r&&delete n[r];let a=this.constructor.preferredCase??x();if(a){let e=q(a);t=J(t,e)}let o=j(z(this,e.prototype.with),this.additionalMeta),{wrap:s,rootKey:c,factory:l}=this.resolveResponseStructure();this.body=R({payload:t,meta:i,metaKey:r,wrap:s,rootKey:c,factory:l,context:{type:`generic`,resource:this.resource}}),this.body=A(this.body,{...n,...o||{}},c)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=j(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=A(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=P(this.resource);return!Array.isArray(e)&&e&&e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=e.data;delete e.data,delete e.pagination;let n=this.getPayloadKey();return t&&n&&this.body[n]!==void 0&&(this.body[n]=Array.isArray(this.body[n])?[...this.body[n],...t]:{...this.body[n],...t}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}},Oe=class e{body={data:[]};resource;collects;additionalMeta;withResponseContext;isPaginatedCollectible(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.pagination&&Array.isArray(t.data)?!0:t.meta&&typeof t.meta==`object`&&`currentPage`in t.meta?Array.isArray(t.data)||N(t.data):!1}static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return V(e,t)}whenNotNull(e){return H(e)}mergeWhen(e,t){return U(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=this.collects?.responseStructure,n=C();return{wrap:e?.wrap??t?.wrap??n?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??n?.rootKey??`data`,factory:e?.factory??t?.factory??n?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=this.data();this.collects&&(t=t.map(e=>new this.collects(e).data())),t=P(t),t=W(t);let n=Array.isArray(this.resource)?{}:L(this.resource),{metaKey:r}=F(),i=r?n[r]:void 0;r&&delete n[r];let a=this.constructor.preferredCase??this.collects?.preferredCase??x();if(a){let e=q(a);t=J(t,e)}let o=j(z(this,e.prototype.with),this.additionalMeta),{wrap:s,rootKey:c,factory:l}=this.resolveResponseStructure();this.body=R({payload:t,meta:i,metaKey:r,wrap:s,rootKey:c,factory:l,context:{type:`collection`,resource:this.resource}}),this.body=A(this.body,{...n,...o||{}},c)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=j(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=A(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){return this.called.toArray=!0,this.json(),P(Array.isArray(this.resource)?this.resource:N(this.resource)?this.resource.all():this.resource.data)}additional(e){this.called.additional=!0,this.json(),delete e.cursor,delete e.pagination;let t=this.getPayloadKey();return e.data&&t&&Array.isArray(this.body[t])&&(this.body[t]=[...this.body[t],...e.data]),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}setCollects(e){return this.collects=e,this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}},ke=class e{body={data:{}};resource;additionalMeta;withResponseContext;static preferredCase;static responseStructure;called={};constructor(e,t){this.res=t,this.resource=e;let n=this.resource.data??this.resource;if(!Array.isArray(n)){let e=M(n)?Object.keys(n.toObject()):Object.keys(n);for(let t of e)t in this||Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>M(n)&&typeof n.getAttribute==`function`?n.getAttribute(t):this.resource.data?.[t]??this.resource[t],set:e=>{if(M(n)&&typeof n.setAttribute==`function`){n.setAttribute(t,e);return}this.resource.data&&this.resource.data[t]?this.resource.data[t]=e:this.resource[t]=e}})}}static collection(e){return new Oe(e).setCollects(this)}data(){return this.toArray()}getBody(){return this.json(),this.body}setBody(e){return this.body=e,this}when(e,t){return V(e,t)}whenNotNull(e){return H(e)}mergeWhen(e,t){return U(e,t)}resolveResponseStructure(){let e=this.constructor.responseStructure,t=C();return{wrap:e?.wrap??t?.wrap??!0,rootKey:e?.rootKey??t?.rootKey??`data`,factory:e?.factory??t?.factory}}getPayloadKey(){let{wrap:e,rootKey:t,factory:n}=this.resolveResponseStructure();return n||!e?void 0:t}json(){if(!this.called.json){this.called.json=!0;let t=P(this.data());!Array.isArray(t)&&t&&t.data!==void 0&&(t=t.data),t=W(t);let n=this.constructor.preferredCase??x();if(n){let e=q(n);t=J(t,e)}let r=j(z(this,e.prototype.with),this.additionalMeta),{wrap:i,rootKey:a,factory:o}=this.resolveResponseStructure();this.body=R({payload:t,wrap:i,rootKey:a,factory:o,context:{type:`resource`,resource:this.resource}}),this.body=A(this.body,r,a)}return this}with(e){if(this.called.with=!0,e===void 0)return this.additionalMeta||{};let t=typeof e==`function`?e(this.resource):e;if(this.additionalMeta=j(this.additionalMeta,t),this.called.json){let{rootKey:e}=this.resolveResponseStructure();this.body=A(this.body,t,e)}return this}withMeta(e){return this.with(e),this}toArray(){this.called.toArray=!0,this.json();let e=P(this.resource);return!Array.isArray(e)&&e&&e.data!==void 0&&(e=e.data),e}additional(e){this.called.additional=!0,this.json();let t=this.getPayloadKey();return e.data&&t&&this.body[t]!==void 0&&(this.body[t]=Array.isArray(this.body[t])?[...this.body[t],...e.data]:{...this.body[t],...e.data}),this.body={...this.body,...e},this}response(e){this.called.toResponse=!0,this.json();let t=e??this.res,n=new $(t,this.body);return this.withResponseContext={response:n,raw:t},this.called.withResponse=!0,this.withResponse(n,t),n}withResponse(e,t){return this}then(e,t){if(this.called.then=!0,this.json(),this.res){let e=new $(this.res,this.body);this.withResponseContext={response:e,raw:this.res},this.called.withResponse=!0,this.withResponse(e,this.res)}else this.called.withResponse=!0,this.withResponse();let n=Promise.resolve(this.body).then(e,t);return this.res&&this.res.send(this.body),n}catch(e){return this.then(void 0,e)}finally(e){return this.then(e,e)}};export{ee as ApiResource,B as CONDITIONAL_ATTRIBUTE_MISSING,we as CliApp,De as GenericResource,Te as InitCommand,Ee as MakeResource,ke as Resource,Oe as ResourceCollection,$ as ServerResponse,A as appendRootProperties,ye as applyRuntimeConfig,L as buildPaginationExtras,R as buildResponseEnvelope,X as defineConfig,q as getCaseTransformer,_e as getDefaultConfig,le as getGlobalBaseUrl,x as getGlobalCase,pe as getGlobalCursorMeta,de as getGlobalPageName,T as getGlobalPaginatedExtras,se as getGlobalPaginatedLinks,D as getGlobalPaginatedMeta,oe as getGlobalResponseFactory,ie as getGlobalResponseRootKey,C as getGlobalResponseStructure,re as getGlobalResponseWrap,F as getPaginationExtraKeys,N as isArkormLikeCollection,M as isArkormLikeModel,k as isPlainObject,Ce as loadRuntimeConfig,j as mergeMetadata,P as normalizeSerializableData,ve as resetRuntimeConfigForTests,U as resolveMergeWhen,V as resolveWhen,H as resolveWhenNotNull,z as resolveWithHookMetadata,W as sanitizeConditionalAttributes,ce as setGlobalBaseUrl,b as setGlobalCase,O as setGlobalCursorMeta,ue as setGlobalPageName,w as setGlobalPaginatedExtras,E as setGlobalPaginatedLinks,fe as setGlobalPaginatedMeta,ae as setGlobalResponseFactory,te as setGlobalResponseRootKey,S as setGlobalResponseStructure,ne as setGlobalResponseWrap,G as splitWords,K as toCamelCase,ge as toKebabCase,he as toPascalCase,me as toSnakeCase,J as transformKeys};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "resora",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "A structured API response layer for Node.js and TypeScript with automatic JSON responses, collection support, and pagination handling.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"api",
|
|
@@ -14,13 +14,13 @@
|
|
|
14
14
|
"json",
|
|
15
15
|
"response"
|
|
16
16
|
],
|
|
17
|
-
"homepage": "https://
|
|
17
|
+
"homepage": "https://arkstack-hq.github.io/resora",
|
|
18
18
|
"bugs": {
|
|
19
|
-
"url": "https://github.com/
|
|
19
|
+
"url": "https://github.com/arkstack-hq/resora/issues"
|
|
20
20
|
},
|
|
21
21
|
"repository": {
|
|
22
22
|
"type": "git",
|
|
23
|
-
"url": "git+https://github.com/
|
|
23
|
+
"url": "git+https://github.com/arkstack-hq/resora.git"
|
|
24
24
|
},
|
|
25
25
|
"license": "MIT",
|
|
26
26
|
"author": "3m1n1nce <3m1n1nce@toneflix.net>",
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"@types/node": "^20.10.6",
|
|
53
53
|
"@types/supertest": "^6.0.3",
|
|
54
54
|
"@vitest/coverage-v8": "4.0.18",
|
|
55
|
+
"arkormx": "^0.1.11",
|
|
55
56
|
"barrelize": "^1.7.3",
|
|
56
57
|
"eslint": "^10.0.0",
|
|
57
58
|
"express": "^5.1.0",
|