@stonyx/orm 0.2.1-beta.83 → 0.2.1-beta.84

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.
Files changed (149) hide show
  1. package/dist/aggregates.d.ts +21 -0
  2. package/dist/aggregates.js +90 -0
  3. package/dist/attr.d.ts +2 -0
  4. package/dist/attr.js +22 -0
  5. package/dist/belongs-to.d.ts +11 -0
  6. package/dist/belongs-to.js +58 -0
  7. package/dist/cli.d.ts +22 -0
  8. package/dist/cli.js +148 -0
  9. package/dist/commands.d.ts +7 -0
  10. package/dist/commands.js +146 -0
  11. package/dist/db.d.ts +21 -0
  12. package/dist/db.js +174 -0
  13. package/dist/exports/db.d.ts +7 -0
  14. package/{src → dist}/exports/db.js +2 -4
  15. package/dist/has-many.d.ts +11 -0
  16. package/dist/has-many.js +57 -0
  17. package/dist/hooks.d.ts +47 -0
  18. package/dist/hooks.js +106 -0
  19. package/dist/index.d.ts +14 -0
  20. package/dist/index.js +34 -0
  21. package/dist/main.d.ts +46 -0
  22. package/dist/main.js +178 -0
  23. package/dist/manage-record.d.ts +13 -0
  24. package/dist/manage-record.js +113 -0
  25. package/dist/meta-request.d.ts +6 -0
  26. package/dist/meta-request.js +52 -0
  27. package/dist/migrate.d.ts +2 -0
  28. package/dist/migrate.js +57 -0
  29. package/dist/model-property.d.ts +9 -0
  30. package/dist/model-property.js +29 -0
  31. package/dist/model.d.ts +15 -0
  32. package/dist/model.js +18 -0
  33. package/dist/mysql/connection.d.ts +14 -0
  34. package/dist/mysql/connection.js +24 -0
  35. package/dist/mysql/migration-generator.d.ts +45 -0
  36. package/dist/mysql/migration-generator.js +245 -0
  37. package/dist/mysql/migration-runner.d.ts +12 -0
  38. package/dist/mysql/migration-runner.js +83 -0
  39. package/dist/mysql/mysql-db.d.ts +100 -0
  40. package/dist/mysql/mysql-db.js +411 -0
  41. package/dist/mysql/query-builder.d.ts +10 -0
  42. package/dist/mysql/query-builder.js +44 -0
  43. package/dist/mysql/schema-introspector.d.ts +19 -0
  44. package/dist/mysql/schema-introspector.js +286 -0
  45. package/dist/mysql/type-map.d.ts +21 -0
  46. package/dist/mysql/type-map.js +36 -0
  47. package/dist/orm-request.d.ts +38 -0
  48. package/dist/orm-request.js +453 -0
  49. package/dist/plural-registry.d.ts +4 -0
  50. package/{src → dist}/plural-registry.js +3 -6
  51. package/dist/postgres/connection.d.ts +15 -0
  52. package/dist/postgres/connection.js +30 -0
  53. package/dist/postgres/migration-generator.d.ts +45 -0
  54. package/dist/postgres/migration-generator.js +257 -0
  55. package/dist/postgres/migration-runner.d.ts +10 -0
  56. package/dist/postgres/migration-runner.js +82 -0
  57. package/dist/postgres/postgres-db.d.ts +119 -0
  58. package/dist/postgres/postgres-db.js +473 -0
  59. package/dist/postgres/query-builder.d.ts +27 -0
  60. package/dist/postgres/query-builder.js +98 -0
  61. package/dist/postgres/schema-introspector.d.ts +29 -0
  62. package/dist/postgres/schema-introspector.js +309 -0
  63. package/dist/postgres/type-map.d.ts +23 -0
  64. package/dist/postgres/type-map.js +53 -0
  65. package/dist/record.d.ts +75 -0
  66. package/dist/record.js +115 -0
  67. package/dist/relationships.d.ts +10 -0
  68. package/dist/relationships.js +35 -0
  69. package/dist/serializer.d.ts +17 -0
  70. package/dist/serializer.js +130 -0
  71. package/dist/setup-rest-server.d.ts +1 -0
  72. package/dist/setup-rest-server.js +54 -0
  73. package/dist/standalone-db.d.ts +58 -0
  74. package/dist/standalone-db.js +142 -0
  75. package/dist/store.d.ts +62 -0
  76. package/dist/store.js +271 -0
  77. package/dist/timescale/query-builder.d.ts +41 -0
  78. package/dist/timescale/query-builder.js +87 -0
  79. package/dist/timescale/timescale-db.d.ts +44 -0
  80. package/dist/timescale/timescale-db.js +81 -0
  81. package/dist/transforms.d.ts +2 -0
  82. package/dist/transforms.js +17 -0
  83. package/dist/types/orm-types.d.ts +142 -0
  84. package/dist/types/orm-types.js +1 -0
  85. package/dist/utils.d.ts +5 -0
  86. package/dist/utils.js +13 -0
  87. package/dist/view-resolver.d.ts +8 -0
  88. package/dist/view-resolver.js +165 -0
  89. package/dist/view.d.ts +11 -0
  90. package/dist/view.js +18 -0
  91. package/package.json +34 -11
  92. package/src/{aggregates.js → aggregates.ts} +27 -13
  93. package/src/{attr.js → attr.ts} +2 -2
  94. package/src/{belongs-to.js → belongs-to.ts} +36 -17
  95. package/src/{cli.js → cli.ts} +17 -11
  96. package/src/{commands.js → commands.ts} +179 -170
  97. package/src/{db.js → db.ts} +35 -26
  98. package/src/exports/db.ts +7 -0
  99. package/src/has-many.ts +91 -0
  100. package/src/{hooks.js → hooks.ts} +23 -27
  101. package/src/{index.js → index.ts} +4 -4
  102. package/src/{main.js → main.ts} +59 -34
  103. package/src/{manage-record.js → manage-record.ts} +41 -22
  104. package/src/{meta-request.js → meta-request.ts} +17 -14
  105. package/src/{migrate.js → migrate.ts} +9 -9
  106. package/src/{model-property.js → model-property.ts} +12 -6
  107. package/src/{model.js → model.ts} +5 -4
  108. package/src/mysql/{connection.js → connection.ts} +43 -28
  109. package/src/mysql/{migration-generator.js → migration-generator.ts} +332 -286
  110. package/src/mysql/{migration-runner.js → migration-runner.ts} +116 -110
  111. package/src/mysql/{mysql-db.js → mysql-db.ts} +533 -473
  112. package/src/mysql/{query-builder.js → query-builder.ts} +69 -64
  113. package/src/mysql/{schema-introspector.js → schema-introspector.ts} +355 -325
  114. package/src/mysql/{type-map.js → type-map.ts} +42 -37
  115. package/src/{orm-request.js → orm-request.ts} +165 -95
  116. package/src/plural-registry.ts +12 -0
  117. package/src/postgres/{connection.js → connection.ts} +14 -5
  118. package/src/postgres/{migration-generator.js → migration-generator.ts} +82 -38
  119. package/src/postgres/{migration-runner.js → migration-runner.ts} +11 -10
  120. package/src/postgres/{postgres-db.js → postgres-db.ts} +195 -114
  121. package/src/postgres/{query-builder.js → query-builder.ts} +27 -28
  122. package/src/postgres/{schema-introspector.js → schema-introspector.ts} +87 -58
  123. package/src/postgres/{type-map.js → type-map.ts} +10 -6
  124. package/src/{record.js → record.ts} +73 -34
  125. package/src/relationships.ts +48 -0
  126. package/src/{serializer.js → serializer.ts} +44 -36
  127. package/src/{setup-rest-server.js → setup-rest-server.ts} +18 -13
  128. package/src/{standalone-db.js → standalone-db.ts} +33 -24
  129. package/src/{store.js → store.ts} +90 -68
  130. package/src/timescale/{query-builder.js → query-builder.ts} +33 -38
  131. package/src/timescale/timescale-db.ts +107 -0
  132. package/src/transforms.ts +20 -0
  133. package/src/types/mysql2.d.ts +30 -0
  134. package/src/types/orm-types.ts +146 -0
  135. package/src/types/pg.d.ts +28 -0
  136. package/src/types/stonyx-cron.d.ts +5 -0
  137. package/src/types/stonyx-events.d.ts +4 -0
  138. package/src/types/stonyx-rest-server.d.ts +11 -0
  139. package/src/types/stonyx-utils.d.ts +33 -0
  140. package/src/types/stonyx.d.ts +21 -0
  141. package/src/utils.ts +16 -0
  142. package/src/{view-resolver.js → view-resolver.ts} +53 -28
  143. package/src/view.ts +22 -0
  144. package/src/has-many.js +0 -68
  145. package/src/relationships.js +0 -43
  146. package/src/timescale/timescale-db.js +0 -111
  147. package/src/transforms.js +0 -20
  148. package/src/utils.js +0 -12
  149. package/src/view.js +0 -21
@@ -0,0 +1,309 @@
1
+ import Orm from '@stonyx/orm';
2
+ import { getPgType, getVectorType } from './type-map.js';
3
+ import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
+ import { getPluralName } from '../plural-registry.js';
5
+ import { dbKey } from '../db.js';
6
+ import { AggregateProperty } from '../aggregates.js';
7
+ import ModelProperty from '../model-property.js';
8
+ function getRelationshipInfo(property) {
9
+ if (typeof property !== 'function')
10
+ return null;
11
+ const relType = property.__relationshipType;
12
+ const modelName = property.__relatedModelName || null;
13
+ if (relType === 'belongsTo')
14
+ return { type: 'belongsTo', modelName };
15
+ if (relType === 'hasMany')
16
+ return { type: 'hasMany', modelName };
17
+ return null;
18
+ }
19
+ function sanitizeTableName(name) {
20
+ return name.replace(/[-/]/g, '_');
21
+ }
22
+ export function introspectModels() {
23
+ const { models } = Orm.instance;
24
+ const schemas = {};
25
+ for (const [modelKey, modelClass] of Object.entries(models)) {
26
+ const name = camelCaseToKebabCase(modelKey.slice(0, -5));
27
+ if (name === dbKey)
28
+ continue;
29
+ const model = new modelClass(modelKey);
30
+ const columns = {};
31
+ const foreignKeys = {};
32
+ const relationships = { belongsTo: {}, hasMany: {} };
33
+ const vectorColumns = {};
34
+ let idType = 'number';
35
+ const transforms = Orm.instance.transforms;
36
+ for (const [key, property] of Object.entries(model)) {
37
+ if (key.startsWith('__'))
38
+ continue;
39
+ const relInfo = getRelationshipInfo(property);
40
+ if (relInfo?.type === 'belongsTo') {
41
+ relationships.belongsTo[key] = relInfo.modelName;
42
+ }
43
+ else if (relInfo?.type === 'hasMany') {
44
+ relationships.hasMany[key] = relInfo.modelName;
45
+ }
46
+ else if (property instanceof ModelProperty) {
47
+ const prop = property;
48
+ if (key === 'id') {
49
+ idType = prop.type;
50
+ }
51
+ else if (prop.type === 'vector') {
52
+ const dimensions = prop.dimensions || 1536;
53
+ columns[key] = getVectorType(dimensions);
54
+ vectorColumns[key] = dimensions;
55
+ }
56
+ else {
57
+ columns[key] = getPgType(prop.type, transforms[prop.type]);
58
+ }
59
+ }
60
+ }
61
+ // Build foreign keys from belongsTo relationships
62
+ for (const [relName, targetModelName] of Object.entries(relationships.belongsTo)) {
63
+ const fkColumn = `${relName}_id`;
64
+ foreignKeys[fkColumn] = {
65
+ references: sanitizeTableName(getPluralName(targetModelName)),
66
+ column: 'id',
67
+ };
68
+ }
69
+ schemas[name] = {
70
+ table: sanitizeTableName(getPluralName(name)),
71
+ idType,
72
+ columns,
73
+ foreignKeys,
74
+ relationships,
75
+ vectorColumns,
76
+ memory: modelClass.memory === true,
77
+ };
78
+ }
79
+ return schemas;
80
+ }
81
+ export function buildTableDDL(name, schema, allSchemas = {}) {
82
+ const { idType, columns, foreignKeys } = schema;
83
+ const table = sanitizeTableName(schema.table);
84
+ const lines = [];
85
+ // Primary key
86
+ if (idType === 'string') {
87
+ lines.push(' "id" VARCHAR(255) PRIMARY KEY');
88
+ }
89
+ else {
90
+ lines.push(' "id" INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY');
91
+ }
92
+ // Attribute columns
93
+ for (const [col, pgType] of Object.entries(columns)) {
94
+ lines.push(` "${col}" ${pgType}`);
95
+ }
96
+ // Foreign key columns
97
+ for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
98
+ const refIdType = getReferencedIdType(fkDef.references, allSchemas);
99
+ lines.push(` "${fkCol}" ${refIdType}`);
100
+ }
101
+ // Timestamps
102
+ lines.push(' "created_at" TIMESTAMPTZ DEFAULT NOW()');
103
+ lines.push(' "updated_at" TIMESTAMPTZ DEFAULT NOW()');
104
+ // Foreign key constraints
105
+ for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
106
+ const refTable = sanitizeTableName(fkDef.references);
107
+ lines.push(` FOREIGN KEY ("${fkCol}") REFERENCES "${refTable}"("${fkDef.column}") ON DELETE SET NULL`);
108
+ }
109
+ return `CREATE TABLE IF NOT EXISTS "${table}" (\n${lines.join(',\n')}\n)`;
110
+ }
111
+ /**
112
+ * Build HNSW index DDL for vector columns on a model.
113
+ */
114
+ export function buildVectorIndexDDL(name, schema) {
115
+ const table = sanitizeTableName(schema.table);
116
+ const statements = [];
117
+ for (const [col] of Object.entries(schema.vectorColumns || {})) {
118
+ statements.push(`CREATE INDEX IF NOT EXISTS "idx_${table}_${col}_hnsw" ON "${table}" USING hnsw ("${col}" vector_cosine_ops) WITH (m = 16, ef_construction = 200)`);
119
+ }
120
+ return statements;
121
+ }
122
+ function getReferencedIdType(tableName, allSchemas) {
123
+ for (const schema of Object.values(allSchemas)) {
124
+ if (schema.table === tableName) {
125
+ return schema.idType === 'string' ? 'VARCHAR(255)' : 'INTEGER';
126
+ }
127
+ }
128
+ return 'INTEGER';
129
+ }
130
+ export function getTopologicalOrder(schemas) {
131
+ const visited = new Set();
132
+ const order = [];
133
+ function visit(name) {
134
+ if (visited.has(name))
135
+ return;
136
+ visited.add(name);
137
+ const schema = schemas[name];
138
+ if (!schema)
139
+ return;
140
+ // Visit dependencies (belongsTo targets) first
141
+ for (const targetModelName of Object.values(schema.relationships.belongsTo)) {
142
+ visit(targetModelName);
143
+ }
144
+ order.push(name);
145
+ }
146
+ for (const name of Object.keys(schemas)) {
147
+ visit(name);
148
+ }
149
+ return order;
150
+ }
151
+ export function introspectViews() {
152
+ const orm = Orm.instance;
153
+ if (!orm.views)
154
+ return {};
155
+ const schemas = {};
156
+ for (const [viewKey, viewClass] of Object.entries(orm.views)) {
157
+ const name = camelCaseToKebabCase(viewKey.slice(0, -4)); // Remove 'View' suffix
158
+ const source = viewClass.source;
159
+ if (!source)
160
+ continue;
161
+ const model = new viewClass(name);
162
+ const columns = {};
163
+ const foreignKeys = {};
164
+ const aggregates = {};
165
+ const relationships = { belongsTo: {}, hasMany: {} };
166
+ for (const [key, property] of Object.entries(model)) {
167
+ if (key.startsWith('__'))
168
+ continue;
169
+ if (key === 'id')
170
+ continue;
171
+ if (property instanceof AggregateProperty) {
172
+ aggregates[key] = property;
173
+ continue;
174
+ }
175
+ const relInfo = getRelationshipInfo(property);
176
+ if (relInfo?.type === 'belongsTo') {
177
+ relationships.belongsTo[key] = relInfo.modelName;
178
+ const fkColumn = `${key}_id`;
179
+ foreignKeys[fkColumn] = {
180
+ references: sanitizeTableName(getPluralName(relInfo.modelName)),
181
+ column: 'id',
182
+ };
183
+ }
184
+ else if (relInfo?.type === 'hasMany') {
185
+ relationships.hasMany[key] = relInfo.modelName;
186
+ }
187
+ else if (property instanceof ModelProperty) {
188
+ const transforms = Orm.instance.transforms;
189
+ const prop = property;
190
+ columns[key] = getPgType(prop.type, transforms[prop.type]);
191
+ }
192
+ }
193
+ schemas[name] = {
194
+ viewName: sanitizeTableName(getPluralName(name)),
195
+ source,
196
+ groupBy: viewClass.groupBy || undefined,
197
+ columns,
198
+ foreignKeys,
199
+ aggregates,
200
+ relationships,
201
+ isView: true,
202
+ memory: false, // Views default to memory:false
203
+ };
204
+ }
205
+ return schemas;
206
+ }
207
+ export function buildViewDDL(name, viewSchema, modelSchemas = {}) {
208
+ if (!viewSchema.source) {
209
+ throw new Error(`View '${name}' must define a source model`);
210
+ }
211
+ const sourceModelName = viewSchema.source;
212
+ const sourceSchema = modelSchemas[sourceModelName];
213
+ const sourceTable = sanitizeTableName(sourceSchema
214
+ ? sourceSchema.table
215
+ : getPluralName(sourceModelName));
216
+ const selectColumns = [];
217
+ const joins = [];
218
+ const hasAggregates = Object.keys(viewSchema.aggregates || {}).length > 0;
219
+ const groupByField = viewSchema.groupBy;
220
+ // ID column: groupBy field or source table PK
221
+ if (groupByField) {
222
+ selectColumns.push(`"${sourceTable}"."${groupByField}" AS "id"`);
223
+ }
224
+ else {
225
+ selectColumns.push(`"${sourceTable}"."id" AS "id"`);
226
+ }
227
+ // Aggregate columns
228
+ for (const [key, aggProp] of Object.entries(viewSchema.aggregates || {})) {
229
+ // Use pgFunction if available, fall back to mysqlFunction
230
+ const fn = aggProp.pgFunction || aggProp.mysqlFunction;
231
+ if (aggProp.relationship === undefined) {
232
+ // Field-level aggregate (groupBy views)
233
+ if (aggProp.aggregateType === 'count') {
234
+ selectColumns.push(`COUNT(*) AS "${key}"`);
235
+ }
236
+ else {
237
+ selectColumns.push(`${fn}("${sourceTable}"."${aggProp.field}") AS "${key}"`);
238
+ }
239
+ }
240
+ else {
241
+ // Relationship aggregate
242
+ const relName = aggProp.relationship;
243
+ const relTable = sanitizeTableName(getPluralName(relName));
244
+ if (aggProp.aggregateType === 'count') {
245
+ selectColumns.push(`${fn}("${relTable}"."id") AS "${key}"`);
246
+ }
247
+ else {
248
+ const field = aggProp.field;
249
+ selectColumns.push(`${fn}("${relTable}"."${field}") AS "${key}"`);
250
+ }
251
+ // Add LEFT JOIN for the relationship if not already added
252
+ const joinKey = `${relTable}`;
253
+ if (!joins.find(j => j.table === joinKey)) {
254
+ const fkColumn = `${sourceModelName}_id`;
255
+ joins.push({
256
+ table: relTable,
257
+ condition: `"${relTable}"."${fkColumn}" = "${sourceTable}"."id"`
258
+ });
259
+ }
260
+ }
261
+ }
262
+ // Regular columns
263
+ for (const [key] of Object.entries(viewSchema.columns || {})) {
264
+ selectColumns.push(`"${sourceTable}"."${key}" AS "${key}"`);
265
+ }
266
+ // Build JOIN clauses
267
+ const joinClauses = joins.map(j => `LEFT JOIN "${j.table}" ON ${j.condition}`).join('\n ');
268
+ // Build GROUP BY
269
+ let groupBy = '';
270
+ if (groupByField) {
271
+ groupBy = `\nGROUP BY "${sourceTable}"."${groupByField}"`;
272
+ }
273
+ else if (hasAggregates) {
274
+ groupBy = `\nGROUP BY "${sourceTable}"."id"`;
275
+ }
276
+ const viewName = sanitizeTableName(viewSchema.viewName);
277
+ const sql = `CREATE OR REPLACE VIEW "${viewName}" AS\nSELECT\n ${selectColumns.join(',\n ')}\nFROM "${sourceTable}"${joinClauses ? '\n ' + joinClauses : ''}${groupBy}`;
278
+ return sql;
279
+ }
280
+ export function viewSchemasToSnapshot(viewSchemas) {
281
+ const snapshot = {};
282
+ for (const [name, schema] of Object.entries(viewSchemas)) {
283
+ snapshot[name] = {
284
+ viewName: schema.viewName,
285
+ source: schema.source,
286
+ ...(schema.groupBy ? { groupBy: schema.groupBy } : {}),
287
+ columns: { ...schema.columns },
288
+ foreignKeys: { ...schema.foreignKeys },
289
+ isView: true,
290
+ viewQuery: buildViewDDL(name, schema),
291
+ };
292
+ }
293
+ return snapshot;
294
+ }
295
+ export function schemasToSnapshot(schemas) {
296
+ const snapshot = {};
297
+ for (const [name, schema] of Object.entries(schemas)) {
298
+ snapshot[name] = {
299
+ table: schema.table,
300
+ idType: schema.idType,
301
+ columns: { ...schema.columns },
302
+ foreignKeys: { ...schema.foreignKeys },
303
+ ...(schema.vectorColumns && Object.keys(schema.vectorColumns).length > 0
304
+ ? { vectorColumns: { ...schema.vectorColumns } }
305
+ : {}),
306
+ };
307
+ }
308
+ return snapshot;
309
+ }
@@ -0,0 +1,23 @@
1
+ interface TransformFn {
2
+ pgType?: string;
3
+ mysqlType?: string;
4
+ (...args: unknown[]): unknown;
5
+ }
6
+ declare const typeMap: Record<string, string>;
7
+ /**
8
+ * Resolves a Stonyx ORM attribute type to a PostgreSQL column type.
9
+ *
10
+ * For built-in types, returns the mapped PostgreSQL type directly.
11
+ *
12
+ * For custom transforms (e.g. an `animal` transform that maps strings to ints):
13
+ * - If the transform function exports a `pgType` property, that value is used.
14
+ * - Otherwise, if `mysqlType` is defined, it is mapped to a PG equivalent.
15
+ * - Otherwise, defaults to JSONB. Values are JSON-stringified on write and
16
+ * JSON-parsed on read by PostgreSQL natively.
17
+ */
18
+ export declare function getPgType(attrType: string, transformFn?: TransformFn): string;
19
+ /**
20
+ * Returns a vector column type for the given dimensions.
21
+ */
22
+ export declare function getVectorType(dimensions: number): string;
23
+ export default typeMap;
@@ -0,0 +1,53 @@
1
+ const typeMap = {
2
+ string: 'VARCHAR(255)',
3
+ number: 'INTEGER',
4
+ float: 'REAL',
5
+ boolean: 'BOOLEAN',
6
+ date: 'TIMESTAMPTZ',
7
+ timestamp: 'BIGINT',
8
+ passthrough: 'TEXT',
9
+ trim: 'VARCHAR(255)',
10
+ uppercase: 'VARCHAR(255)',
11
+ ceil: 'INTEGER',
12
+ floor: 'INTEGER',
13
+ round: 'INTEGER',
14
+ };
15
+ /**
16
+ * Resolves a Stonyx ORM attribute type to a PostgreSQL column type.
17
+ *
18
+ * For built-in types, returns the mapped PostgreSQL type directly.
19
+ *
20
+ * For custom transforms (e.g. an `animal` transform that maps strings to ints):
21
+ * - If the transform function exports a `pgType` property, that value is used.
22
+ * - Otherwise, if `mysqlType` is defined, it is mapped to a PG equivalent.
23
+ * - Otherwise, defaults to JSONB. Values are JSON-stringified on write and
24
+ * JSON-parsed on read by PostgreSQL natively.
25
+ */
26
+ export function getPgType(attrType, transformFn) {
27
+ if (typeMap[attrType])
28
+ return typeMap[attrType];
29
+ if (transformFn?.pgType)
30
+ return transformFn.pgType;
31
+ if (transformFn?.mysqlType)
32
+ return mysqlTypeToPg(transformFn.mysqlType);
33
+ return 'JSONB';
34
+ }
35
+ /**
36
+ * Returns a vector column type for the given dimensions.
37
+ */
38
+ export function getVectorType(dimensions) {
39
+ return `vector(${dimensions})`;
40
+ }
41
+ function mysqlTypeToPg(mysqlType) {
42
+ const upper = mysqlType.toUpperCase();
43
+ if (upper === 'TINYINT(1)')
44
+ return 'BOOLEAN';
45
+ if (upper === 'INT' || upper === 'INT AUTO_INCREMENT')
46
+ return 'INTEGER';
47
+ if (upper === 'DATETIME')
48
+ return 'TIMESTAMPTZ';
49
+ if (upper === 'JSON')
50
+ return 'JSONB';
51
+ return mysqlType;
52
+ }
53
+ export default typeMap;
@@ -0,0 +1,75 @@
1
+ import type Serializer from './serializer.js';
2
+ interface ToJSONOptions {
3
+ fields?: Set<string>;
4
+ baseUrl?: string;
5
+ }
6
+ interface SerializeOptions {
7
+ update?: boolean;
8
+ serialize?: boolean;
9
+ transform?: boolean;
10
+ [key: string]: unknown;
11
+ }
12
+ interface UnloadOptions {
13
+ [key: string]: unknown;
14
+ }
15
+ interface RelationshipLinks {
16
+ self: string;
17
+ related: string;
18
+ }
19
+ interface RelationshipEntry {
20
+ data: {
21
+ type: string;
22
+ id: unknown;
23
+ } | {
24
+ type: string;
25
+ id: unknown;
26
+ }[] | null;
27
+ links?: RelationshipLinks;
28
+ }
29
+ interface JSONAPIResult {
30
+ attributes: {
31
+ [key: string]: unknown;
32
+ };
33
+ relationships: {
34
+ [key: string]: RelationshipEntry;
35
+ };
36
+ id: unknown;
37
+ type: string;
38
+ links?: {
39
+ self: string;
40
+ };
41
+ }
42
+ export default class Record {
43
+ /** @private */
44
+ __data: {
45
+ [key: string]: unknown;
46
+ };
47
+ /** @private */
48
+ __relationships: {
49
+ [key: string]: unknown;
50
+ };
51
+ /** @private */
52
+ __serialized: boolean;
53
+ /** @private */
54
+ __model: {
55
+ __name: string;
56
+ [key: string]: unknown;
57
+ };
58
+ /** @private */
59
+ __serializer: Serializer;
60
+ [key: string]: unknown;
61
+ constructor(model: {
62
+ __name: string;
63
+ [key: string]: unknown;
64
+ }, serializer: Serializer);
65
+ serialize(rawData?: unknown, options?: SerializeOptions): {
66
+ [key: string]: unknown;
67
+ };
68
+ format(): {
69
+ [key: string]: unknown;
70
+ };
71
+ toJSON(options?: ToJSONOptions): JSONAPIResult;
72
+ unload(options?: UnloadOptions): void;
73
+ clean(): void;
74
+ }
75
+ export {};
package/dist/record.js ADDED
@@ -0,0 +1,115 @@
1
+ import { store } from '@stonyx/orm';
2
+ import { getComputedProperties } from "./serializer.js";
3
+ import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
+ import { getPluralName } from './plural-registry.js';
5
+ export default class Record {
6
+ /** @private */
7
+ __data = {};
8
+ /** @private */
9
+ __relationships = {};
10
+ /** @private */
11
+ __serialized = false;
12
+ /** @private */
13
+ __model;
14
+ /** @private */
15
+ __serializer;
16
+ constructor(model, serializer) {
17
+ this.__model = model;
18
+ this.__serializer = serializer;
19
+ }
20
+ serialize(rawData, options = {}) {
21
+ const { __data: data } = this;
22
+ if (this.__serialized && !options.update) {
23
+ const relatedIds = {};
24
+ for (const [key, childRecord] of Object.entries(this.__relationships)) {
25
+ relatedIds[key] = Array.isArray(childRecord)
26
+ ? childRecord.map((r) => r.id)
27
+ : childRecord?.id ?? null;
28
+ }
29
+ return { ...data, ...relatedIds };
30
+ }
31
+ const normalizedData = this.__serializer.normalize(rawData);
32
+ this.__serializer.setProperties(normalizedData, this, options);
33
+ return data;
34
+ }
35
+ // Similar to serialize, but preserves top level relationship records
36
+ format() {
37
+ if (!this.__serialized)
38
+ throw new Error('Record must be serialized before being converted to JSON');
39
+ const { __data: data } = this;
40
+ const records = {};
41
+ for (const [key, childRecord] of Object.entries(this.__relationships)) {
42
+ records[key] = Array.isArray(childRecord)
43
+ ? childRecord.map((r) => r.serialize())
44
+ : childRecord?.serialize() ?? null;
45
+ }
46
+ return { ...data, ...records };
47
+ }
48
+ // Formats record for JSON API output
49
+ toJSON(options = {}) {
50
+ if (!this.__serialized)
51
+ throw new Error('Record must be serialized before being converted to JSON');
52
+ const { fields, baseUrl } = options;
53
+ const { __data: data } = this;
54
+ const modelName = this.__model.__name;
55
+ const pluralizedModelName = getPluralName(modelName);
56
+ const recordId = data.id;
57
+ const relationships = {};
58
+ const attributes = {};
59
+ for (const [key, value] of Object.entries(data)) {
60
+ if (key === 'id')
61
+ continue;
62
+ if (fields && !fields.has(key))
63
+ continue;
64
+ attributes[key] = value;
65
+ }
66
+ for (const [key, getter] of getComputedProperties(this.__model)) {
67
+ if (fields && !fields.has(key))
68
+ continue;
69
+ attributes[key] = getter.call(this);
70
+ }
71
+ for (const [key, childRecord] of Object.entries(this.__relationships)) {
72
+ if (fields && !fields.has(key))
73
+ continue;
74
+ const relationshipData = Array.isArray(childRecord)
75
+ ? childRecord.map((r) => ({ type: r.__model.__name, id: r.id }))
76
+ : childRecord ? { type: childRecord.__model.__name, id: childRecord.id } : null;
77
+ // Dasherize the key for URL paths (e.g., accessLinks -> access-links)
78
+ const dasherizedKey = camelCaseToKebabCase(key);
79
+ relationships[dasherizedKey] = { data: relationshipData };
80
+ // Add links to relationship if baseUrl provided
81
+ if (baseUrl) {
82
+ relationships[dasherizedKey].links = {
83
+ self: `${baseUrl}/${pluralizedModelName}/${recordId}/relationships/${dasherizedKey}`,
84
+ related: `${baseUrl}/${pluralizedModelName}/${recordId}/${dasherizedKey}`
85
+ };
86
+ }
87
+ }
88
+ const result = {
89
+ attributes,
90
+ relationships,
91
+ id: recordId,
92
+ type: modelName,
93
+ };
94
+ // Add resource links if baseUrl provided
95
+ if (baseUrl) {
96
+ result.links = {
97
+ self: `${baseUrl}/${pluralizedModelName}/${recordId}`
98
+ };
99
+ }
100
+ return result;
101
+ }
102
+ unload(options = {}) {
103
+ store.unloadRecord(this.__model.__name, this.id, options);
104
+ }
105
+ clean() {
106
+ try {
107
+ for (const key of Object.keys(this)) {
108
+ delete this[key];
109
+ }
110
+ }
111
+ catch {
112
+ // Ignore errors during cleanup, as some keys may not be deletable
113
+ }
114
+ }
115
+ }
@@ -0,0 +1,10 @@
1
+ import type { HasManyMap, BelongsToMap, GlobalMap, PendingMap, PendingBelongsToMap } from './types/orm-types.js';
2
+ export declare function getRelationships(type: string, sourceModel: string, targetModel: string, relationshipId?: string): Map<unknown, unknown> | undefined;
3
+ export declare function getHasManyRelationships(sourceModel: string, targetModel: string): Map<unknown, unknown> | undefined;
4
+ /** Typed accessors for the relationship registry */
5
+ export declare function getHasManyRegistry(): HasManyMap;
6
+ export declare function getBelongsToRegistry(): BelongsToMap;
7
+ export declare function getGlobalRegistry(): GlobalMap;
8
+ export declare function getPendingRegistry(): PendingMap;
9
+ export declare function getPendingBelongsToRegistry(): PendingBelongsToMap;
10
+ export declare const TYPES: string[];
@@ -0,0 +1,35 @@
1
+ import { relationships } from '@stonyx/orm';
2
+ // TODO: Refactor mapping to remove a level of iteration
3
+ export function getRelationships(type, sourceModel, targetModel, relationshipId) {
4
+ const allRelationships = relationships.get(type);
5
+ // create relationship map for this type of it doesn't already exist
6
+ if (!allRelationships.has(sourceModel))
7
+ allRelationships.set(sourceModel, new Map());
8
+ const modelRelationship = allRelationships.get(sourceModel);
9
+ if (!modelRelationship.has(targetModel))
10
+ modelRelationship.set(targetModel, new Map());
11
+ const relationship = modelRelationship.get(targetModel);
12
+ // TODO: Determine whether already having id should be handled differently
13
+ //if (relationship.has(relationshipId)) return;
14
+ return relationship;
15
+ }
16
+ export function getHasManyRelationships(sourceModel, targetModel) {
17
+ return relationships.get('hasMany')?.get(sourceModel)?.get(targetModel);
18
+ }
19
+ /** Typed accessors for the relationship registry */
20
+ export function getHasManyRegistry() {
21
+ return relationships.get('hasMany');
22
+ }
23
+ export function getBelongsToRegistry() {
24
+ return relationships.get('belongsTo');
25
+ }
26
+ export function getGlobalRegistry() {
27
+ return relationships.get('global');
28
+ }
29
+ export function getPendingRegistry() {
30
+ return relationships.get('pending');
31
+ }
32
+ export function getPendingBelongsToRegistry() {
33
+ return relationships.get('pendingBelongsTo');
34
+ }
35
+ export const TYPES = ['global', 'hasMany', 'belongsTo', 'pending'];
@@ -0,0 +1,17 @@
1
+ export default class Serializer {
2
+ map: Record<string, unknown>;
3
+ path: string;
4
+ model: Record<string, unknown>;
5
+ constructor(model: Record<string, unknown>);
6
+ /**
7
+ * This method populates the record's instance with instances of
8
+ * the ModelProperty object, while setting parsed values to the record's
9
+ * __data property, which represents the serialized version of the data
10
+ */
11
+ setProperties(rawData: unknown, record: unknown, options: Record<string, unknown>): void;
12
+ /**
13
+ * OVERRIDE: This hook allows for data manipulation prior to serialization logic
14
+ */
15
+ normalize(data: unknown): unknown;
16
+ }
17
+ export declare function getComputedProperties(classInstance: Record<string, unknown>): [string, PropertyDescriptor['get']][];