@stacksjs/model-meta 0.74.4
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/LICENSE.md +21 -0
- package/README.md +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +2 -0
- package/package.json +56 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Open Web Foundation
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# @stacksjs/model-meta
|
|
2
|
+
|
|
3
|
+
Model metadata derived from a model definition: table names, pivot tables,
|
|
4
|
+
relations, and the attribute helpers that read them.
|
|
5
|
+
|
|
6
|
+
This is a leaf. It reads a `Model` and returns facts about it, and it depends on
|
|
7
|
+
nothing that can lead back to the ORM or the database layer.
|
|
8
|
+
|
|
9
|
+
That independence is the point. `@stacksjs/database` needs to know what table a
|
|
10
|
+
model maps to, but it has no business importing the ORM to find out — and when
|
|
11
|
+
it did, `orm → database → drivers/helpers → orm` deadlocked bun's module loader.
|
|
12
|
+
The import had to be held at a deep path inside `@stacksjs/orm` to step around
|
|
13
|
+
the cycle. Extracting these helpers removes the cycle instead.
|
|
14
|
+
|
|
15
|
+
`@stacksjs/orm` re-exports everything here, so `import { getTableName } from
|
|
16
|
+
'@stacksjs/orm'` keeps working.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { getPivotTables, getTableName } from '@stacksjs/model-meta'
|
|
20
|
+
|
|
21
|
+
getTableName(model, modelPath) // 'users'
|
|
22
|
+
await getPivotTables(model, modelPath) // [{ table: 'role_user', ... }]
|
|
23
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { AttributesElements, BaseBelongsToMany, Model, ModelElement, ModelNames, RelationConfig, TableNames } from '@stacksjs/types';
|
|
2
|
+
export declare function modelTableName(model: Model | ModelPath): Promise<string>;
|
|
3
|
+
export declare function getModelName(model: Model, modelPath: string): string;
|
|
4
|
+
export declare function getTableName(model: Model, modelPath: string): TableNames;
|
|
5
|
+
export declare function getPivotTableName(formattedModelName: string, modelRelationTable: string): string;
|
|
6
|
+
export declare function hasRelations(obj: object, key: string): boolean;
|
|
7
|
+
export declare function getRelations(model: Model, modelName: string): Promise<RelationConfig[]>;
|
|
8
|
+
export declare function getRelationType(relation: string): string;
|
|
9
|
+
export declare function getRelationCount(relation: string): string;
|
|
10
|
+
export declare function getPivotTables(model: Model, modelPath: string): Promise<{ table: string, firstForeignKey?: string, secondForeignKey?: string }[]>;
|
|
11
|
+
export declare function fetchOtherModelRelations(modelName?: string): Promise<RelationConfig[]>;
|
|
12
|
+
export declare function getHiddenAttributes(attributes: AttributesElements | undefined): string[];
|
|
13
|
+
export declare function getGuardedAttributes(model: Model): string[];
|
|
14
|
+
export declare function getFillableAttributes(model: Model, otherModelRelations: RelationConfig[]): string[];
|
|
15
|
+
export declare function extractFields(model: Model, modelFile: string): Promise<ModelElement[]>;
|
|
16
|
+
export declare function mapEntity(attribute: ModelElement): string | undefined;
|
|
17
|
+
export declare function findCoreModel(modelName: string): string;
|
|
18
|
+
export declare function findUserModel(modelName: string): string;
|
|
19
|
+
export declare function formatDate(date: Date | number | string): string;
|
|
20
|
+
export declare function extractDate(date: Date): string;
|
|
21
|
+
export declare function toTimestamp(date: Date): number;
|
|
22
|
+
declare type ModelPath = string;
|
|
23
|
+
declare type LegacyBelongsToMany = ModelNames | BaseBelongsToMany<ModelNames>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{path as m}from"@stacksjs/path";import{fs as b,globSync as w}from"@stacksjs/storage";import{plural as C,singular as _,snakeCase as p}from"@stacksjs/strings";import{isString as R}from"@stacksjs/validation";function B(e){let n=e.belongsToMany;if(!n)return[];if(Array.isArray(n))return n.map((t)=>({relationName:typeof t==="string"?p(t):p(String(t.model)),relation:t}));return Object.entries(n).map(([t,o])=>{if(typeof o==="string")return{relationName:t,relation:o};return{relationName:t,relation:{model:o.model,pivotTable:o.table,firstForeignKey:o.foreignKey,secondForeignKey:o.relatedKey}}})}async function G(e){if(typeof e==="string")e=(await import(e)).default;return e.table??p(C(e?.name||""))}function M(e,n){if(e.name)return e.name;return m.basename(n).replace(/\.ts$/,"")}function d(e,n){if(e.table)return e.table;return p(C(M(e,n)))}function E(e,n){let t=[e,n];return t.sort(),t.join("_")}function J(e,n){return n in e}async function D(e,n){let t=[];if(e.hasOne)for(let o of e.hasOne)t.push(await P(o,e,n,"hasOne"));if(e.hasMany)for(let o of e.hasMany)t.push(await P(o,e,n,"hasMany"));if(e.belongsTo)for(let o of e.belongsTo)t.push(await P(o,e,n,"belongsTo"));if(e.hasOneThrough)for(let o of e.hasOneThrough)t.push(await O(o,e,n,"hasOneThrough"));if(e.hasManyThrough)for(let o of e.hasManyThrough)t.push(await O(o,e,n,"hasManyThrough"));if(e.belongsToMany)for(let{relationName:o,relation:r}of B(e))t.push(await V(r,e,n,"belongsToMany",o));if(e.morphOne)t.push(await j(e.morphOne,e,n,"morphOne"));if(e.morphMany){let o=Array.isArray(e.morphMany)?e.morphMany:[e.morphMany];for(let r of o)t.push(await j(r,e,n,"morphMany"))}if(e.morphTo){let o=e.morphTo,r=Array.isArray(o)?o:typeof o==="object"&&o!==null?[o]:[];for(let i of r)t.push(k(i,e,n))}if(e.morphToMany){let o=Array.isArray(e.morphToMany)?e.morphToMany:[e.morphToMany];for(let r of o)t.push(A(r,e,n,"morphToMany"))}if(e.morphedByMany){let o=Array.isArray(e.morphedByMany)?e.morphedByMany:[e.morphedByMany];for(let r of o)t.push(A(r,e,n,"morphedByMany"))}return t}function k(e,n,t){let o=e&&typeof e==="object"&&e.name?String(e.name):`${p(t)}able`,r=e?.type||`${o}_type`;return{relationship:"morphTo",model:"",table:"",relationTable:"",foreignKey:e?.id||`${o}_id`,modelKey:r,relationName:o,relationModel:t,throughModel:"",throughForeignKey:"",pivotForeign:"",pivotKey:"",pivotTable:""}}function A(e,n,t,o){let r=typeof e==="object"&&e!==null,i=r?String(e.model||""):String(e),a=r&&e.morphName?String(e.morphName):`${p(t)}able`,l=r&&e.pivotTable?String(e.pivotTable):a,s=r&&e.id||`${a}_id`,u=r&&e.type||`${a}_type`;return{relationship:o,model:i,table:"",relationTable:"",foreignKey:s,modelKey:u,relationName:a,relationModel:t,throughModel:"",throughForeignKey:"",pivotForeign:s,pivotKey:u,pivotTable:l}}async function K(e,n){let t=x(`${n}.ts`),o=x(`${e}.ts`),r=N(`${e}.ts`),i=N(`${n}.ts`);if(!t&&!i)throw Error(`Model not found: ${n}`);if(!o&&!r)throw Error(`Model not found: ${e}`);let a;try{if(b.existsSync(t))a=(await import(t)).default;else a=(await import(i)).default}catch(s){throw Error(`Failed to load model: ${n}. Error: ${s?.message||"Unknown error"}`)}let l=b.existsSync(o)?o:r;return{modelRelation:a,modelPath:l,modelRelationPath:b.existsSync(t)?t:i}}async function O(e,n,t,o){let r="",i="",a="",l="";if(R(e))r=e;else r=e.model,i=e.relationName||"",a=e.through,l=e.throughForeignKey||"";let{modelRelation:s,modelPath:u,modelRelationPath:c}=await K(t,r),g=d(s,c),f=d(n,u),h=p(M(s,c)),y=p(t);return{relationship:o,model:r,table:g,relationTable:f,foreignKey:`${y}_id`,modelKey:`${h}_id`,relationName:i,relationModel:t,throughModel:a,throughForeignKey:l,pivotForeign:`${y}_id`,pivotKey:`${h}_id`,pivotTable:f}}async function V(e,n,t,o,r){let i="",a="",l="",s=p(t);if(R(e))i=e;else i=e.model,a=e.pivotTable||"",l=e.firstForeignKey||`${s}_id`;let{modelRelation:u,modelPath:c,modelRelationPath:g}=await K(t,i),f=d(u,g),h=d(n,c),y=p(M(u,g));return{relationship:o,model:i,table:f,relationTable:h,foreignKey:typeof e==="string"?`${s}_id`:e.firstForeignKey||`${s}_id`,modelKey:typeof e==="string"?`${y}_id`:e.secondForeignKey||`${y}_id`,relationName:r,relationModel:t,throughModel:"",throughForeignKey:"",pivotForeign:l,pivotKey:`${y}_id`,pivotTable:a}}async function j(e,n,t,o){let r="",i="",a="",l="";if(R(e))r=e,i=`${p(t)}able`;else r=e.model,i=e.morphName||`${p(t)}able`,a=e.type||`${i}_type`,l=e.id||`${i}_id`;let{modelRelation:s,modelPath:u,modelRelationPath:c}=await K(t,r),g=d(s,c),f=d(n,u);return{relationship:o,model:r,table:g,relationTable:f,foreignKey:l||`${i}_id`,modelKey:a||`${i}_type`,relationName:i,relationModel:t,throughModel:"",throughForeignKey:"",pivotForeign:"",pivotKey:"",pivotTable:f}}async function P(e,n,t,o){let r="",i="";if(R(e))r=e;else r=e.model,i=e.relationName||"";let{modelRelation:a,modelPath:l,modelRelationPath:s}=await K(t,r),u=d(a,s),c=d(n,l),g=p(M(a,s)),f=p(t),h=typeof e==="string"?"":e.foreignKey||"",y={relationship:o,model:r,table:u,relationTable:c,foreignKey:h||`${f}_id`,modelKey:`${g}_id`,relationName:i,relationModel:t,throughModel:"",throughForeignKey:"",pivotForeign:`${f}_id`,pivotKey:`${g}_id`,pivotTable:c};if(o==="belongsTo"){if(y.foreignKey="",h)y.modelKey=h}return y}function Q(e){let n=/belongs/,t=/has/,o=/Through/,r=/morph/;if(o.test(e))return"throughType";if(n.test(e))return"belongsType";if(t.test(e))return"hasType";if(r.test(e))return"morphType";return""}function W(e){let n=/One/;if(/Many/.test(e))return"many";if(n.test(e))return"one";return""}async function X(e,n){let t=[];if("belongsToMany"in e){for(let{relation:o}of B(e)){let r,i;if(typeof o==="string")i=o;else i=o.model;let a=x(`${i}.ts`),l=N(`${i}.ts`);if(b.existsSync(a))r=(await import(a)).default;else r=(await import(l)).default;let s=d(r,a),u=d(e,n),c=typeof o==="object"&&"firstForeignKey"in o?o.firstForeignKey:`${_(u)}_${e.primaryKey}`,g=typeof o==="object"&&"secondForeignKey"in o?o.secondForeignKey:`${_(s)}_${e.primaryKey}`;t.push({table:(typeof o==="object"&&"pivotTable"in o?o.pivotTable:void 0)??E(u,s),firstForeignKey:c,secondForeignKey:g})}return t}return[]}async function Y(e){let n=w([m.userModelsPath("*.ts"),m.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),t=[];for(let o=0;o<n.length;o++){let r=n[o],i=await import(r);if(e===i.default.name)continue;let a=M(i,r),l=await D(i.default,a);if(!l.length)continue;let s=l.find((u)=>u.model===e);if(s)t.push(s)}return t}function Z(e){if(e===void 0)return[];return Object.keys(e).filter((n)=>e[n]?.hidden===!0)}function I(e){let n=e.attributes;if(n===void 0)return[];return Object.keys(n).filter((t)=>n[t]?.guarded===!0).map((t)=>p(t))}function ee(e,n){let t=e.attributes,o=[];if(t===void 0)return[];let r=typeof e.traits?.billable==="object"||typeof e.traits?.billable==="boolean",i=typeof e.traits?.useAuth==="object"?e.traits?.useAuth.usePasskey:!1,a=e.traits?.useUuid||!1;if(r)o.push("stripe_id");if(a)o.push("uuid");if(i)o.push(...["two_factor_secret","public_key"]);let l=n.map((s)=>s.foreignKey).filter((s)=>s);return[...Object.keys(t).filter((s)=>{if(t===void 0)return!1;return t[s]?.fillable===!0}).map((s)=>p(s)),...o,...l]}async function te(e,n){let t=e.attributes;if(!t)t={};let o=Object.keys(t),r=[],i=Bun.file(n),a="";try{if(await i.exists())a=await i.text()}catch{a=""}let l=/rule:.*$/gm,s;s=l.exec(a);while(s!==null)r.push(s[0]),s=l.exec(a);return o.map((c,g)=>{let f=t[c],h=null,y=!1,T=!1,v=!1,F=!1;if(f)h=f||null,y=f.unique||!1,T=f.hidden||!1,v=f.fillable||!1;let S=r[g]??"";return F=(f.validation?.rule).isRequired??!1,{field:c,default:h,unique:y,hidden:T,fillable:v,required:F,fieldArray:q(S)}})}function q(e){let n=e.split("rule: schema.");if(n.length!==2)return null;if(!n[1])n[1]="";let t=n[1].replace(/,/g,"");if(!t)return null;let o=t.split("."),r=/\(([^)]+)\)/;return o.map((i)=>{let a=r.exec(i),l=a?a[1]:null;return{entity:i.replace(r,"").replace(/\(|\)/g,""),charValue:l}})[0]||null}function oe(e){let n=e.fieldArray?.entity;switch(n){case"enum":return"string | string[]";case"date":return"Date | string";case"timestamp":return"Date | string";case"datetime":return"Date | string";case"float":return"number";case"double":return"number";case"decimal":return"number";case"integer":return"number";case"bigint":return"number";default:return n}}function N(e){let n=m.join(m.storagePath("framework/defaults/app/Models"),"/"),t=m.join(n,e);if(b.existsSync(t))return t;return w(`${n}**/${e}`,{absolute:!0})[0]??""}function x(e){let n=m.join(m.userModelsPath("/"),"/"),t=m.join(n,e);if(b.existsSync(t))return t;return w(`${n}**/${e}`,{absolute:!0})[0]??""}function ne(e){let n=typeof e==="number"?new Date(e):typeof e==="string"?new Date(e):e;if(Number.isNaN(n.getTime()))throw Error(`Invalid date value: ${String(e)}`);return n.toISOString().replace("T"," ").split(".")[0]??""}function re(e){return e.toISOString().split("T")[0]??""}function ie(e){return e.getTime()}export{re as extractDate,te as extractFields,Y as fetchOtherModelRelations,N as findCoreModel,x as findUserModel,ne as formatDate,ee as getFillableAttributes,I as getGuardedAttributes,Z as getHiddenAttributes,M as getModelName,E as getPivotTableName,X as getPivotTables,W as getRelationCount,Q as getRelationType,D as getRelations,d as getTableName,J as hasRelations,oe as mapEntity,G as modelTableName,ie as toTimestamp};
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@stacksjs/model-meta",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.74.4",
|
|
5
|
+
"description": "Model metadata the ORM declares and the database layer reads: table names, pivot tables, relations.",
|
|
6
|
+
"author": "Chris Breuer",
|
|
7
|
+
"contributors": [
|
|
8
|
+
"Chris Breuer <chris@stacksjs.com>"
|
|
9
|
+
],
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"funding": "https://github.com/sponsors/chrisbbreuer",
|
|
12
|
+
"homepage": "https://github.com/stacksjs/stacks/tree/main/storage/framework/core/model-meta#readme",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/stacksjs/stacks.git",
|
|
16
|
+
"directory": "./storage/framework/core/model-meta"
|
|
17
|
+
},
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/stacksjs/stacks/issues"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"model",
|
|
23
|
+
"metadata",
|
|
24
|
+
"table",
|
|
25
|
+
"relations",
|
|
26
|
+
"stacks"
|
|
27
|
+
],
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"bun": "./dist/index.js",
|
|
32
|
+
"import": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./*": {
|
|
35
|
+
"import": "./dist/*"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"module": "./dist/index.js",
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"files": [
|
|
41
|
+
"README.md",
|
|
42
|
+
"dist"
|
|
43
|
+
],
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "bun build.ts",
|
|
46
|
+
"typecheck": "bun --bun tsc --noEmit"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@stacksjs/path": "0.74.4",
|
|
50
|
+
"@stacksjs/storage": "0.74.4",
|
|
51
|
+
"@stacksjs/strings": "0.74.4",
|
|
52
|
+
"@stacksjs/ts-validation": "^0.5.6",
|
|
53
|
+
"@stacksjs/types": "0.74.4",
|
|
54
|
+
"@stacksjs/validation": "0.74.4"
|
|
55
|
+
}
|
|
56
|
+
}
|