sonamu 0.5.0 → 0.5.2

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 (118) hide show
  1. package/dist/api/context.d.ts +4 -1
  2. package/dist/api/context.d.ts.map +1 -1
  3. package/dist/api/decorators.d.ts.map +1 -1
  4. package/dist/api/decorators.js +1 -1
  5. package/dist/api/decorators.js.map +1 -1
  6. package/dist/api/sonamu.d.ts +7 -6
  7. package/dist/api/sonamu.d.ts.map +1 -1
  8. package/dist/api/sonamu.js +1 -1
  9. package/dist/api/sonamu.js.map +1 -1
  10. package/dist/bin/build-config.d.ts +4 -0
  11. package/dist/bin/build-config.d.ts.map +1 -1
  12. package/dist/bin/build-config.js +1 -1
  13. package/dist/bin/build-config.js.map +1 -1
  14. package/dist/bin/cli-wrapper.js +1 -1
  15. package/dist/bin/cli-wrapper.js.map +1 -1
  16. package/dist/bin/cli.js +1 -1
  17. package/dist/bin/cli.js.map +1 -1
  18. package/dist/database/base-model.d.ts +8 -1
  19. package/dist/database/base-model.d.ts.map +1 -1
  20. package/dist/database/base-model.js +1 -1
  21. package/dist/database/base-model.js.map +1 -1
  22. package/dist/database/db.d.ts +1 -0
  23. package/dist/database/db.d.ts.map +1 -1
  24. package/dist/database/db.js +1 -1
  25. package/dist/database/db.js.map +1 -1
  26. package/dist/file-storage/driver.d.ts +3 -0
  27. package/dist/file-storage/driver.d.ts.map +1 -1
  28. package/dist/file-storage/driver.js +1 -1
  29. package/dist/file-storage/driver.js.map +1 -1
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +1 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/stream/index.d.ts +2 -0
  35. package/dist/stream/index.d.ts.map +1 -0
  36. package/dist/stream/index.js +2 -0
  37. package/dist/stream/index.js.map +1 -0
  38. package/dist/stream/sse.d.ts +13 -0
  39. package/dist/stream/sse.d.ts.map +1 -0
  40. package/dist/stream/sse.js +2 -0
  41. package/dist/stream/sse.js.map +1 -0
  42. package/dist/types/types.d.ts +5 -3
  43. package/dist/types/types.d.ts.map +1 -1
  44. package/dist/types/types.js.map +1 -1
  45. package/package.json +5 -3
  46. package/src/api/context.ts +10 -5
  47. package/src/api/decorators.ts +1 -3
  48. package/src/api/sonamu.ts +60 -26
  49. package/src/bin/build-config.ts +5 -0
  50. package/src/bin/cli-wrapper.ts +20 -6
  51. package/src/bin/cli.ts +16 -21
  52. package/src/database/base-model.ts +29 -3
  53. package/src/database/db.ts +3 -2
  54. package/src/file-storage/driver.ts +10 -0
  55. package/src/index.ts +1 -0
  56. package/src/stream/index.ts +1 -0
  57. package/src/stream/sse.ts +49 -0
  58. package/src/types/types.ts +10 -4
  59. package/tsconfig.json +4 -0
  60. package/dist/api/sonamu.types.d.ts +0 -30
  61. package/dist/api/sonamu.types.d.ts.map +0 -1
  62. package/dist/api/sonamu.types.js +0 -2
  63. package/dist/api/sonamu.types.js.map +0 -1
  64. package/dist/base-model-CEB0H0aO.d.mts +0 -43
  65. package/dist/base-model-CrqDMYhI.d.ts +0 -43
  66. package/dist/bin/cli-wrapper.d.mts +0 -1
  67. package/dist/bin/cli-wrapper.mjs +0 -43
  68. package/dist/bin/cli-wrapper.mjs.map +0 -1
  69. package/dist/bin/cli.d.mts +0 -2
  70. package/dist/bin/cli.mjs +0 -907
  71. package/dist/bin/cli.mjs.map +0 -1
  72. package/dist/chunk-2WAC2GER.js +0 -7625
  73. package/dist/chunk-2WAC2GER.js.map +0 -1
  74. package/dist/chunk-C3IPIF6O.mjs +0 -1581
  75. package/dist/chunk-C3IPIF6O.mjs.map +0 -1
  76. package/dist/chunk-EXHKSVTE.js +0 -280
  77. package/dist/chunk-EXHKSVTE.js.map +0 -1
  78. package/dist/chunk-FCERKIIF.mjs +0 -7623
  79. package/dist/chunk-FCERKIIF.mjs.map +0 -1
  80. package/dist/chunk-HGIBJYOU.mjs +0 -231
  81. package/dist/chunk-HGIBJYOU.mjs.map +0 -1
  82. package/dist/chunk-JKSOJRQA.mjs +0 -280
  83. package/dist/chunk-JKSOJRQA.mjs.map +0 -1
  84. package/dist/chunk-OTKKFP3Y.js +0 -1581
  85. package/dist/chunk-OTKKFP3Y.js.map +0 -1
  86. package/dist/chunk-PTFDTOJU.mjs +0 -19
  87. package/dist/chunk-PTFDTOJU.mjs.map +0 -1
  88. package/dist/chunk-UZ2IY5VE.js +0 -231
  89. package/dist/chunk-UZ2IY5VE.js.map +0 -1
  90. package/dist/database/drivers/knex/base-model.d.mts +0 -16
  91. package/dist/database/drivers/knex/base-model.d.ts +0 -16
  92. package/dist/database/drivers/knex/base-model.js +0 -55
  93. package/dist/database/drivers/knex/base-model.js.map +0 -1
  94. package/dist/database/drivers/knex/base-model.mjs +0 -56
  95. package/dist/database/drivers/knex/base-model.mjs.map +0 -1
  96. package/dist/database/drivers/kysely/base-model.d.mts +0 -22
  97. package/dist/database/drivers/kysely/base-model.d.ts +0 -22
  98. package/dist/database/drivers/kysely/base-model.js +0 -64
  99. package/dist/database/drivers/kysely/base-model.js.map +0 -1
  100. package/dist/database/drivers/kysely/base-model.mjs +0 -65
  101. package/dist/database/drivers/kysely/base-model.mjs.map +0 -1
  102. package/dist/database/types.d.ts +0 -39
  103. package/dist/database/types.d.ts.map +0 -1
  104. package/dist/database/types.js +0 -2
  105. package/dist/database/types.js.map +0 -1
  106. package/dist/index.d.mts +0 -813
  107. package/dist/index.mjs +0 -435
  108. package/dist/index.mjs.map +0 -1
  109. package/dist/model-aFgomcdc.d.mts +0 -1112
  110. package/dist/model-aFgomcdc.d.ts +0 -1112
  111. package/dist/smd/smd-manager.d.ts +0 -28
  112. package/dist/smd/smd-manager.d.ts.map +0 -1
  113. package/dist/smd/smd-manager.js +0 -2
  114. package/dist/smd/smd-manager.js.map +0 -1
  115. package/dist/smd/smd.d.ts +0 -40
  116. package/dist/smd/smd.d.ts.map +0 -1
  117. package/dist/smd/smd.js +0 -2
  118. package/dist/smd/smd.js.map +0 -1
package/dist/bin/cli.mjs DELETED
@@ -1,907 +0,0 @@
1
- import {
2
- FixtureManager,
3
- Migrator
4
- } from "../chunk-C3IPIF6O.mjs";
5
- import {
6
- DB,
7
- EntityManager,
8
- KnexClient,
9
- KyselyClient,
10
- Sonamu,
11
- isBelongsToOneRelationProp,
12
- isEnumProp,
13
- isHasManyRelationProp,
14
- isManyToManyRelationProp,
15
- isOneToOneRelationProp,
16
- isRelationProp,
17
- isVirtualProp
18
- } from "../chunk-FCERKIIF.mjs";
19
- import {
20
- __dirname
21
- } from "../chunk-PTFDTOJU.mjs";
22
-
23
- // src/bin/cli.ts
24
- import chalk2 from "chalk";
25
- import dotenv from "dotenv";
26
- import path3 from "path";
27
- import { tsicli } from "tsicli";
28
- import { execSync } from "child_process";
29
- import fs2 from "fs-extra";
30
- import inflection3 from "inflection";
31
- import prettier from "prettier";
32
- import process from "process";
33
- import _2 from "lodash";
34
-
35
- // src/smd/smd-manager.ts
36
- import chalk from "chalk";
37
- import glob from "glob";
38
- import inflection2 from "inflection";
39
- import path2 from "path";
40
-
41
- // src/smd/smd.ts
42
- import _ from "lodash";
43
- import inflection from "inflection";
44
- import path from "path";
45
- import fs from "fs-extra";
46
- var SMD = class {
47
- id;
48
- parentId;
49
- table;
50
- title;
51
- names;
52
- props;
53
- propsDict;
54
- relations;
55
- indexes;
56
- subsets;
57
- types = {};
58
- enums = {};
59
- enumLabels = {};
60
- constructor({
61
- id,
62
- parentId,
63
- table,
64
- title,
65
- props,
66
- indexes,
67
- subsets
68
- }) {
69
- this.id = id;
70
- this.parentId = parentId;
71
- this.title = title ?? this.id;
72
- this.table = table ?? inflection.underscore(inflection.pluralize(id));
73
- if (props) {
74
- this.props = props.map((prop) => {
75
- if (isEnumProp(prop)) {
76
- if (prop.id.includes("$Model")) {
77
- prop.id = prop.id.replace("$Model", id);
78
- }
79
- }
80
- return prop;
81
- });
82
- this.propsDict = props.reduce((result, prop) => {
83
- return {
84
- ...result,
85
- [prop.name]: prop
86
- };
87
- }, {});
88
- this.relations = props.filter((prop) => isRelationProp(prop)).reduce((result, prop) => {
89
- return {
90
- ...result,
91
- [prop.name]: prop
92
- };
93
- }, {});
94
- } else {
95
- this.props = [];
96
- this.propsDict = {};
97
- this.relations = {};
98
- }
99
- this.indexes = indexes ?? [];
100
- this.subsets = subsets ?? {};
101
- this.names = {
102
- fs: parentId === void 0 ? inflection.dasherize(inflection.underscore(id)).toLowerCase() : inflection.dasherize(parentId).toLowerCase(),
103
- module: id
104
- };
105
- this.registerModulePaths();
106
- this.registerTableSpecs();
107
- }
108
- /*
109
- subset SELECT/JOIN/LOADER 결과 리턴
110
- */
111
- getSubsetQuery(subsetKey) {
112
- const subset = this.subsets[subsetKey];
113
- const result = this.resolveSubsetQuery("", subset);
114
- return result;
115
- }
116
- /*
117
- */
118
- resolveSubsetQuery(prefix, fields, isAlreadyOuterJoined = false) {
119
- prefix = prefix.replace(/\./g, "__");
120
- const subsetGroup = _.groupBy(fields, (field) => {
121
- if (field.includes(".")) {
122
- const [rel] = field.split(".");
123
- return rel;
124
- } else {
125
- return "";
126
- }
127
- });
128
- const result = Object.keys(subsetGroup).reduce(
129
- (r, groupKey) => {
130
- const fields2 = subsetGroup[groupKey];
131
- if (groupKey === "") {
132
- const realFields = fields2.filter(
133
- (field) => !isVirtualProp(this.propsDict[field])
134
- );
135
- const virtualFields = fields2.filter(
136
- (field) => isVirtualProp(this.propsDict[field])
137
- );
138
- if (prefix === "") {
139
- r.select = r.select.concat(
140
- realFields.map((field) => `${this.table}.${field}`)
141
- );
142
- r.virtual = r.virtual.concat(virtualFields);
143
- } else {
144
- r.select = r.select.concat(
145
- realFields.map(
146
- (field) => `${prefix}.${field} as ${prefix}__${field}`
147
- )
148
- );
149
- }
150
- return r;
151
- }
152
- const relation = this.relations[groupKey];
153
- if (relation === void 0) {
154
- throw new Error(`\uC874\uC7AC\uD558\uC9C0 \uC54A\uB294 relation \uCC38\uC870 ${groupKey}`);
155
- }
156
- const relSMD = SMDManager.get(relation.with);
157
- if (isOneToOneRelationProp(relation) || isBelongsToOneRelationProp(relation)) {
158
- const relFields = fields2.map(
159
- (field) => field.split(".").slice(1).join(".")
160
- );
161
- if (relFields.length === 1 && relFields[0] === "id") {
162
- if (prefix === "") {
163
- r.select = r.select.concat(`${this.table}.${groupKey}_id`);
164
- } else {
165
- r.select = r.select.concat(
166
- `${prefix}.${groupKey}_id as ${prefix}__${groupKey}_id`
167
- );
168
- }
169
- return r;
170
- }
171
- const innerOrOuter = (() => {
172
- if (isAlreadyOuterJoined) {
173
- return "outer";
174
- }
175
- if (isOneToOneRelationProp(relation)) {
176
- if (relation.hasJoinColumn === true && (relation.nullable ?? false) === false) {
177
- return "inner";
178
- } else {
179
- return "outer";
180
- }
181
- } else {
182
- if (relation.nullable) {
183
- return "outer";
184
- } else {
185
- return "inner";
186
- }
187
- }
188
- })();
189
- const relSubsetQuery = relSMD.resolveSubsetQuery(
190
- `${prefix !== "" ? prefix + "." : ""}${groupKey}`,
191
- relFields,
192
- innerOrOuter === "outer"
193
- );
194
- r.select = r.select.concat(relSubsetQuery.select);
195
- r.virtual = r.virtual.concat(relSubsetQuery.virtual);
196
- const joinAs = prefix === "" ? groupKey : prefix + "__" + groupKey;
197
- const fromTable = prefix === "" ? this.table : prefix;
198
- let joinClause;
199
- if (relation.customJoinClause) {
200
- joinClause = {
201
- custom: relation.customJoinClause
202
- };
203
- } else {
204
- let from, to;
205
- if (isOneToOneRelationProp(relation)) {
206
- if (relation.hasJoinColumn) {
207
- from = `${fromTable}.${relation.name}_id`;
208
- to = `${joinAs}.id`;
209
- } else {
210
- from = `${fromTable}.id`;
211
- to = `${joinAs}.${inflection.underscore(
212
- this.names.fs.replace(/\-/g, "_")
213
- )}_id`;
214
- }
215
- } else {
216
- from = `${fromTable}.${relation.name}_id`;
217
- to = `${joinAs}.id`;
218
- }
219
- joinClause = {
220
- from,
221
- to
222
- };
223
- }
224
- r.joins.push({
225
- as: joinAs,
226
- join: innerOrOuter,
227
- table: relSMD.table,
228
- ...joinClause
229
- });
230
- if (relSubsetQuery.loaders.length > 0) {
231
- const convertedLoaders = relSubsetQuery.loaders.map((loader) => {
232
- const newAs = [groupKey, loader.as].join("__");
233
- return {
234
- as: newAs,
235
- table: loader.table,
236
- manyJoin: loader.manyJoin,
237
- oneJoins: loader.oneJoins,
238
- select: loader.select
239
- };
240
- });
241
- r.loaders = [...r.loaders, ...convertedLoaders];
242
- }
243
- r.joins = r.joins.concat(relSubsetQuery.joins);
244
- } else if (isHasManyRelationProp(relation) || isManyToManyRelationProp(relation)) {
245
- const relFields = fields2.map(
246
- (field) => field.split(".").slice(1).join(".")
247
- );
248
- const relSubsetQuery = relSMD.resolveSubsetQuery("", relFields);
249
- let manyJoin;
250
- if (isHasManyRelationProp(relation)) {
251
- manyJoin = {
252
- fromTable: this.table,
253
- fromCol: "id",
254
- idField: prefix === "" ? `id` : `${prefix}__id`,
255
- toTable: relSMD.table,
256
- toCol: relation.joinColumn
257
- };
258
- } else if (isManyToManyRelationProp(relation)) {
259
- const [table1, table2] = relation.joinTable.split("__");
260
- manyJoin = {
261
- fromTable: this.table,
262
- fromCol: "id",
263
- idField: prefix === "" ? `id` : `${prefix}__id`,
264
- through: {
265
- table: relation.joinTable,
266
- fromCol: `${inflection.singularize(table1)}_id`,
267
- toCol: `${inflection.singularize(table2)}_id`
268
- },
269
- toTable: relSMD.table,
270
- toCol: "id"
271
- };
272
- } else {
273
- throw new Error();
274
- }
275
- r.loaders.push({
276
- as: groupKey,
277
- table: relSMD.table,
278
- manyJoin,
279
- oneJoins: relSubsetQuery.joins,
280
- select: relSubsetQuery.select,
281
- loaders: relSubsetQuery.loaders
282
- });
283
- }
284
- return r;
285
- },
286
- {
287
- select: [],
288
- virtual: [],
289
- joins: [],
290
- loaders: []
291
- }
292
- );
293
- return result;
294
- }
295
- /*
296
- FieldExpr[] 을 SMDPropNode[] 로 변환
297
- */
298
- fieldExprsToPropNodes(fieldExprs, smd = this) {
299
- const groups = fieldExprs.reduce(
300
- (result, fieldExpr) => {
301
- let key, value, elseExpr;
302
- if (fieldExpr.includes(".")) {
303
- [key, ...elseExpr] = fieldExpr.split(".");
304
- value = elseExpr.join(".");
305
- } else {
306
- key = "";
307
- value = fieldExpr;
308
- }
309
- result[key] = (result[key] ?? []).concat(value);
310
- return result;
311
- },
312
- {}
313
- );
314
- return Object.keys(groups).map((key) => {
315
- const group = groups[key];
316
- if (key === "") {
317
- return group.map((propName) => {
318
- if (propName === "uuid") {
319
- return {
320
- nodeType: "plain",
321
- prop: {
322
- type: "string",
323
- name: "uuid",
324
- length: 128
325
- },
326
- children: []
327
- };
328
- }
329
- const prop2 = smd.propsDict[propName];
330
- if (prop2 === void 0) {
331
- throw new Error(`${this.id} -- \uC798\uBABB\uB41C FieldExpr ${propName}`);
332
- }
333
- return {
334
- nodeType: "plain",
335
- prop: prop2,
336
- children: []
337
- };
338
- });
339
- }
340
- const prop = smd.propsDict[key];
341
- if (!isRelationProp(prop)) {
342
- throw new Error(`\uC798\uBABB\uB41C FieldExpr ${key}.${group[0]}`);
343
- }
344
- const relSMD = SMDManager.get(prop.with);
345
- if (isBelongsToOneRelationProp(prop) || isOneToOneRelationProp(prop)) {
346
- if (group.length == 1 && (group[0] === "id" || group[0] == "id?")) {
347
- const idProp = relSMD.propsDict.id;
348
- return {
349
- nodeType: "plain",
350
- prop: {
351
- ...idProp,
352
- name: key + "_id",
353
- nullable: prop.nullable
354
- },
355
- children: []
356
- };
357
- }
358
- }
359
- const children = this.fieldExprsToPropNodes(group, relSMD);
360
- const nodeType = isBelongsToOneRelationProp(prop) || isOneToOneRelationProp(prop) ? "object" : "array";
361
- return {
362
- prop,
363
- children,
364
- nodeType
365
- };
366
- }).flat();
367
- }
368
- getFieldExprs(prefix = "", maxDepth = 3, froms = []) {
369
- return this.props.map((prop) => {
370
- const propName = [prefix, prop.name].filter((v) => v !== "").join(".");
371
- if (propName === prefix) {
372
- return null;
373
- }
374
- if (isRelationProp(prop)) {
375
- if (maxDepth < 0) {
376
- return null;
377
- }
378
- if (froms.includes(prop.with)) {
379
- return null;
380
- }
381
- const relMd = SMDManager.get(prop.with);
382
- return relMd.getFieldExprs(propName, maxDepth - 1, [
383
- ...froms,
384
- this.id
385
- ]);
386
- }
387
- return propName;
388
- }).flat().filter((f) => f !== null);
389
- }
390
- registerModulePaths() {
391
- const basePath = `${this.names.fs}`;
392
- SMDManager.setModulePath(
393
- `${this.id}BaseSchema`,
394
- `${basePath}/${this.names.fs}.generated`
395
- );
396
- if (Object.keys(this.subsets).length > 0) {
397
- SMDManager.setModulePath(
398
- `${this.id}SubsetKey`,
399
- `${basePath}/${this.names.fs}.generated`
400
- );
401
- SMDManager.setModulePath(
402
- `${this.id}SubsetMapping`,
403
- `${basePath}/${this.names.fs}.generated`
404
- );
405
- Object.keys(this.subsets).map((subsetKey) => {
406
- SMDManager.setModulePath(
407
- `${this.id}Subset${subsetKey.toUpperCase()}`,
408
- `${basePath}/${this.names.fs}.generated`
409
- );
410
- });
411
- }
412
- const typesModulePath = `${basePath}/${this.names.fs}.types`;
413
- const typesFileDistPath = path.join(
414
- Sonamu.apiRootPath,
415
- `dist/application/${typesModulePath}.js`
416
- );
417
- if (fs.existsSync(typesFileDistPath)) {
418
- const importPath = path.relative(__dirname, typesFileDistPath);
419
- import(importPath).then((t) => {
420
- this.types = Object.keys(t).reduce((result, key) => {
421
- SMDManager.setModulePath(key, typesModulePath);
422
- return {
423
- ...result,
424
- [key]: t[key]
425
- };
426
- }, {});
427
- });
428
- }
429
- const enumsModulePath = `${basePath}/${this.names.fs}.enums`;
430
- const enumsFileDistPath = path.join(
431
- Sonamu.apiRootPath,
432
- `/dist/application/${enumsModulePath}.js`
433
- );
434
- if (fs.existsSync(enumsFileDistPath)) {
435
- const importPath = path.relative(__dirname, enumsFileDistPath);
436
- import(importPath).then((t) => {
437
- this.enums = Object.keys(t).reduce((result, key) => {
438
- SMDManager.setModulePath(key, enumsModulePath);
439
- if (key === inflection.underscore(this.id).toUpperCase()) {
440
- this.enumLabels = t[key];
441
- }
442
- return {
443
- ...result,
444
- [key]: t[key]
445
- };
446
- }, {});
447
- });
448
- }
449
- }
450
- registerTableSpecs() {
451
- const uniqueColumns = _.uniq(
452
- this.indexes.filter((idx) => idx.type === "unique").map((idx) => idx.columns).flat()
453
- );
454
- SMDManager.setTableSpec({
455
- name: this.table,
456
- uniqueColumns
457
- });
458
- }
459
- };
460
-
461
- // src/smd/smd-manager.ts
462
- var SMDManagerClass = class {
463
- SMDs = /* @__PURE__ */ new Map();
464
- modulePaths = /* @__PURE__ */ new Map();
465
- tableSpecs = /* @__PURE__ */ new Map();
466
- isAutoloaded = false;
467
- // 경로 전달받아 모든 SMD 파일 로드
468
- async autoload(doSilent = false) {
469
- if (this.isAutoloaded) {
470
- return;
471
- }
472
- const pathPattern = path2.join(
473
- Sonamu.apiRootPath,
474
- "/dist/application/**/*.smd.js"
475
- );
476
- !doSilent && console.log(chalk.yellow(`autoload ${pathPattern}`));
477
- return new Promise((resolve) => {
478
- glob.glob(path2.resolve(pathPattern), (_err, files) => {
479
- const importPaths = files.map(
480
- (filePath) => path2.relative(__dirname, filePath)
481
- );
482
- Promise.all(
483
- importPaths.map(async (importPath) => {
484
- const imported = await import(importPath);
485
- Object.values(imported).map(
486
- (smdInput) => this.register(smdInput)
487
- );
488
- return imported;
489
- })
490
- ).then(() => {
491
- resolve("ok");
492
- this.isAutoloaded = true;
493
- });
494
- });
495
- });
496
- }
497
- register(smdInput) {
498
- const smd = new SMD(smdInput);
499
- this.SMDs.set(smdInput.id, smd);
500
- }
501
- get(smdId) {
502
- const smd = this.SMDs.get(smdId);
503
- if (smd === void 0) {
504
- throw new Error(`\uC874\uC7AC\uD558\uC9C0 \uC54A\uB294 SMD \uC694\uCCAD ${smdId}`);
505
- }
506
- return smd;
507
- }
508
- exists(smdId) {
509
- const smd = this.SMDs.get(smdId);
510
- return smd !== void 0;
511
- }
512
- getAllIds() {
513
- return Array.from(SMDManager.SMDs.keys());
514
- }
515
- getAllParentIds() {
516
- return this.getAllIds().filter((smdId) => {
517
- const smd = this.get(smdId);
518
- return smd.parentId === void 0;
519
- });
520
- }
521
- getChildrenIds(parentId) {
522
- return this.getAllIds().filter((smdId) => {
523
- const smd = this.get(smdId);
524
- return smd.parentId === parentId;
525
- });
526
- }
527
- setModulePath(key, modulePath) {
528
- this.modulePaths.set(key, modulePath);
529
- }
530
- getModulePath(key) {
531
- const modulePath = this.modulePaths.get(key);
532
- if (modulePath === void 0) {
533
- throw new Error(`\uC874\uC7AC\uD558\uC9C0 \uC54A\uB294 \uBAA8\uB4C8 \uD328\uC2A4 \uC694\uCCAD ${key}`);
534
- }
535
- return modulePath;
536
- }
537
- setTableSpec(tableSpec) {
538
- this.tableSpecs.set(tableSpec.name, tableSpec);
539
- }
540
- getTableSpec(key) {
541
- const tableSpec = this.tableSpecs.get(key);
542
- if (tableSpec === void 0) {
543
- throw new Error(`\uC874\uC7AC\uD558\uC9C0 \uC54A\uB294 \uD14C\uC774\uBE14 \uC2A4\uD399 \uC694\uCCAD ${key}`);
544
- }
545
- return tableSpec;
546
- }
547
- getNamesFromId(smdId) {
548
- const pluralized = inflection2.pluralize(smdId) === smdId ? `${smdId}List` : inflection2.pluralize(smdId);
549
- return {
550
- fs: inflection2.dasherize(inflection2.underscore(smdId)).toLowerCase(),
551
- fsPlural: inflection2.dasherize(inflection2.underscore(pluralized)).toLowerCase(),
552
- camel: inflection2.camelize(smdId, true),
553
- camelPlural: inflection2.camelize(pluralized, true),
554
- capital: smdId,
555
- capitalPlural: pluralized,
556
- upper: smdId.toUpperCase(),
557
- constant: inflection2.underscore(smdId).toUpperCase()
558
- };
559
- }
560
- };
561
- var SMDManager = new SMDManagerClass();
562
-
563
- // src/bin/cli.ts
564
- console.log(chalk2.bgBlue(`BEGIN ${/* @__PURE__ */ new Date()}`));
565
- dotenv.config();
566
- var migrator;
567
- async function bootstrap() {
568
- await Sonamu.init(false, false);
569
- await tsicli(process.argv, {
570
- types: {
571
- "#entityId": {
572
- type: "autocomplete",
573
- name: "#entityId",
574
- message: "Please input #entityId",
575
- choices: EntityManager.getAllParentIds().map((entityId) => ({
576
- title: entityId,
577
- value: entityId
578
- }))
579
- },
580
- "#recordIds": "number[]",
581
- "#name": "string"
582
- },
583
- args: [
584
- ["fixture", "init"],
585
- ["fixture", "import", "#entityId", "#recordIds"],
586
- ["fixture", "sync"],
587
- ["migrate", "run"],
588
- ["migrate", "check"],
589
- ["migrate", "rollback"],
590
- ["migrate", "reset"],
591
- ["migrate", "clear"],
592
- ["migrate", "status"],
593
- ["stub", "practice", "#name"],
594
- ["stub", "entity", "#name"],
595
- ["scaffold", "model", "#entityId"],
596
- ["scaffold", "model_test", "#entityId"],
597
- ["scaffold", "view_list", "#entityId"],
598
- ["scaffold", "view_form", "#entityId"],
599
- ["ui"],
600
- ["smd_migration"]
601
- ],
602
- runners: {
603
- migrate_run,
604
- migrate_check,
605
- migrate_rollback,
606
- migrate_clear,
607
- migrate_reset,
608
- migrate_status,
609
- fixture_init,
610
- fixture_import,
611
- fixture_sync,
612
- stub_practice,
613
- stub_entity,
614
- scaffold_model,
615
- scaffold_model_test,
616
- ui,
617
- // scaffold_view_list,
618
- // scaffold_view_form,
619
- smd_migration
620
- }
621
- });
622
- }
623
- bootstrap().finally(async () => {
624
- if (migrator) {
625
- await migrator.destroy();
626
- }
627
- await FixtureManager.destory();
628
- console.log(chalk2.bgBlue(`END ${/* @__PURE__ */ new Date()}
629
- `));
630
- });
631
- async function setupMigrator() {
632
- migrator = new Migrator({
633
- mode: "dev"
634
- });
635
- }
636
- async function setupFixtureManager() {
637
- FixtureManager.init();
638
- }
639
- async function migrate_run() {
640
- await setupMigrator();
641
- await migrator.cleanUpDist();
642
- await migrator.run();
643
- }
644
- async function migrate_check() {
645
- await setupMigrator();
646
- await migrator.cleanUpDist();
647
- await migrator.check();
648
- }
649
- async function migrate_status() {
650
- await setupMigrator();
651
- const status = await migrator.getStatus();
652
- console.log(status);
653
- }
654
- async function migrate_rollback() {
655
- await setupMigrator();
656
- await migrator.rollback();
657
- }
658
- async function migrate_clear() {
659
- await setupMigrator();
660
- await migrator.clearPendingList();
661
- }
662
- async function migrate_reset() {
663
- await setupMigrator();
664
- await migrator.resetAll();
665
- }
666
- async function fixture_init() {
667
- const _db = DB.getClient("development_master");
668
- const srcConn = _db.connectionInfo;
669
- const targets = [
670
- {
671
- label: "(REMOTE) Fixture DB",
672
- connKey: "fixture_remote"
673
- },
674
- {
675
- label: "(LOCAL) Fixture DB",
676
- connKey: "fixture_local"
677
- },
678
- {
679
- label: "(LOCAL) Testing DB",
680
- connKey: "test"
681
- }
682
- ];
683
- console.log("DUMP...");
684
- const dumpFilename = `/tmp/sonamu-fixture-init-${Date.now()}.sql`;
685
- const migrationsDump = `/tmp/sonamu-fixture-init-migrations-${Date.now()}.sql`;
686
- execSync(
687
- `mysqldump -h${srcConn.host} -P${srcConn.port} -u${srcConn.user} -p${srcConn.password} --single-transaction -d --no-create-db --triggers ${srcConn.database} > ${dumpFilename}`
688
- );
689
- const dbClient = DB.baseConfig.client;
690
- const migrationTable = DB.migrationTable;
691
- const [migrations] = await _db.raw(
692
- "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = ? AND table_name = ?",
693
- [srcConn.database, migrationTable]
694
- );
695
- if (migrations.count > 0) {
696
- execSync(
697
- `mysqldump -h${srcConn.host} -P${srcConn.port} -u${srcConn.user} -p${srcConn.password} --single-transaction --no-create-db --triggers ${srcConn.database} ${migrationTable} ${migrationTable}_lock > ${migrationsDump}`
698
- );
699
- }
700
- for await (const { label, connKey } of targets) {
701
- const config = DB.connectionInfo[connKey];
702
- if (label === "(LOCAL) Fixture DB" && targets.find(
703
- (t) => t.label === "(REMOTE) Fixture DB" && DB.connectionInfo[t.connKey].host === config.host && DB.connectionInfo[t.connKey].database === config.database
704
- )) {
705
- console.log(chalk2.red(`${label}: Skipped!`));
706
- continue;
707
- }
708
- const db = (() => {
709
- if (dbClient === "knex") {
710
- const config2 = _2.cloneDeep(DB.fullConfig[connKey]);
711
- config2.connection.database = void 0;
712
- return new KnexClient(config2);
713
- } else {
714
- const config2 = _2.cloneDeep(DB.fullConfig[connKey]);
715
- config2.database = void 0;
716
- return new KyselyClient(config2);
717
- }
718
- })();
719
- const [row] = await db.raw(`SHOW DATABASES LIKE "${config.database}"`);
720
- if (row) {
721
- console.log(
722
- chalk2.yellow(`${label}: Database "${config.database}" Already exists`)
723
- );
724
- await db.destroy();
725
- continue;
726
- }
727
- console.log(`SYNC to ${label}...`);
728
- const mysqlCmd = `mysql -h${config.host} -P${srcConn.port} -u${config.user} -p${config.password}`;
729
- execSync(`${mysqlCmd} -e 'DROP DATABASE IF EXISTS \`${config.database}\`'`);
730
- execSync(`${mysqlCmd} -e 'CREATE DATABASE \`${config.database}\`'`);
731
- execSync(`${mysqlCmd} ${config.database} < ${dumpFilename}`);
732
- if (fs2.existsSync(migrationsDump)) {
733
- execSync(`${mysqlCmd} ${config.database} < ${migrationsDump}`);
734
- }
735
- await db.destroy();
736
- }
737
- }
738
- async function fixture_import(entityId, recordIds) {
739
- await setupFixtureManager();
740
- await FixtureManager.importFixture(entityId, recordIds);
741
- await FixtureManager.sync();
742
- }
743
- async function fixture_sync() {
744
- await setupFixtureManager();
745
- await FixtureManager.sync();
746
- }
747
- async function stub_practice(name) {
748
- const practiceDir = path3.join(Sonamu.apiRootPath, "src", "practices");
749
- const fileNames = fs2.readdirSync(practiceDir);
750
- const maxSeqNo = (() => {
751
- if (fs2.existsSync(practiceDir) === false) {
752
- fs2.mkdirSync(practiceDir, { recursive: true });
753
- }
754
- const filteredSeqs = fileNames.filter(
755
- (fileName2) => fileName2.startsWith("p") && fileName2.endsWith(".ts")
756
- ).map((fileName2) => {
757
- const [, seqNo] = fileName2.match(/^p([0-9]+)\-/) ?? ["0", "0"];
758
- return parseInt(seqNo);
759
- }).sort((a, b) => b - a);
760
- if (filteredSeqs.length > 0) {
761
- return filteredSeqs[0];
762
- }
763
- return 0;
764
- })();
765
- const currentSeqNo = maxSeqNo + 1;
766
- const fileName = `p${currentSeqNo}-${name}.ts`;
767
- const dstPath = path3.join(practiceDir, fileName);
768
- const code = [
769
- `import { BaseModel } from "sonamu";`,
770
- "",
771
- `console.clear();`,
772
- `console.log("${fileName}");`,
773
- "",
774
- `async function bootstrap() {`,
775
- ` // TODO`,
776
- `}`,
777
- `bootstrap().finally(async () => {`,
778
- `await BaseModel.destroy();`,
779
- `});`
780
- ].join("\n");
781
- fs2.writeFileSync(dstPath, code);
782
- execSync(`code ${dstPath}`);
783
- const runCode = `yarn node -r source-map-support/register dist/practices/${fileName.replace(
784
- ".ts",
785
- ".js"
786
- )}`;
787
- console.log(`${chalk2.blue(runCode)} copied to clipboard.`);
788
- execSync(`echo "${runCode}" | pbcopy`);
789
- }
790
- async function stub_entity(entityId) {
791
- await Sonamu.syncer.createEntity({ entityId });
792
- }
793
- async function scaffold_model(entityId) {
794
- await Sonamu.syncer.generateTemplate("model", {
795
- entityId
796
- });
797
- }
798
- async function scaffold_model_test(entityId) {
799
- await Sonamu.syncer.generateTemplate("model_test", {
800
- entityId
801
- });
802
- }
803
- async function ui() {
804
- try {
805
- const sonamuUI = await import("@sonamu-kit/ui");
806
- sonamuUI.startServers(Sonamu.apiRootPath);
807
- } catch (e) {
808
- if (e instanceof Error && e.message.includes("isn't declared")) {
809
- console.log(`You need to install ${chalk2.blue(`@sonamu-kit/ui`)} first.`);
810
- return;
811
- }
812
- throw e;
813
- }
814
- }
815
- async function smd_migration() {
816
- await SMDManager.autoload();
817
- const smdIds = SMDManager.getAllIds();
818
- function enumLabelsToEntityEnums(entityId, enumLabels) {
819
- return Object.fromEntries(
820
- Object.entries(enumLabels).map(([enumLabelName, enumLabel]) => {
821
- const enumName = entityId + inflection3.camelize(enumLabelName.toLowerCase(), false);
822
- return [
823
- enumName,
824
- Object.fromEntries(
825
- Object.entries(enumLabel).map(([name, { ko }]) => [name, ko])
826
- )
827
- ];
828
- })
829
- );
830
- }
831
- for await (const smdId of smdIds) {
832
- const smd = SMDManager.get(smdId);
833
- const entityJson = {
834
- id: smd.id,
835
- ...smd.parentId && { parentId: smd.parentId },
836
- title: smd.title,
837
- props: smd.props,
838
- indexes: smd.indexes,
839
- subsets: smd.subsets,
840
- enums: enumLabelsToEntityEnums(smd.id, smd.enumLabels)
841
- };
842
- const parentNames = SMDManager.getNamesFromId(smd.parentId ?? smd.id);
843
- const names = SMDManager.getNamesFromId(smd.id);
844
- const dstPath = path3.join(
845
- Sonamu.apiRootPath,
846
- "src",
847
- "application",
848
- parentNames.fs,
849
- `${names.fs}.entity.json`
850
- );
851
- const formatted = await prettier.format(JSON.stringify(entityJson), {
852
- parser: "json"
853
- });
854
- fs2.writeFileSync(dstPath, formatted);
855
- console.log(chalk2.blue(`CREATED: ${dstPath}`));
856
- const srcSmdPath = path3.join(
857
- Sonamu.apiRootPath,
858
- "src",
859
- "application",
860
- parentNames.fs,
861
- `${names.fs}.smd.ts`
862
- );
863
- const dstSmdPath = srcSmdPath.replace("/src/", "/dist/").replace(/\.ts$/, ".js");
864
- const srcEnumsPath = path3.join(
865
- Sonamu.apiRootPath,
866
- "src",
867
- "application",
868
- parentNames.fs,
869
- `${names.fs}.enums.ts`
870
- );
871
- const dstEnumsPath = srcEnumsPath.replace("/src/", "/dist/").replace(/\.ts$/, ".js");
872
- const srcGeneratedPath = path3.join(
873
- Sonamu.apiRootPath,
874
- "src",
875
- "application",
876
- parentNames.fs,
877
- `${names.fs}.generated.ts`
878
- );
879
- const dstGeneratedPath = srcGeneratedPath.replace("/src/", "/dist/").replace(/\.ts$/, ".js");
880
- [
881
- srcSmdPath,
882
- dstSmdPath,
883
- srcEnumsPath,
884
- dstEnumsPath,
885
- ...Sonamu.config.sync.targets.map(
886
- (target) => srcEnumsPath.replace(Sonamu.apiRootPath, path3.join(Sonamu.appRootPath, target)).replace("/src/application/", "/src/services/")
887
- ),
888
- srcGeneratedPath,
889
- dstGeneratedPath
890
- ].map((p) => {
891
- if (fs2.existsSync(p) === false) {
892
- console.log(chalk2.yellow(`NOT FOUND: ${p}`));
893
- return;
894
- }
895
- fs2.unlinkSync(p);
896
- console.log(chalk2.red(`DELETED: ${p}`));
897
- });
898
- }
899
- console.log("Entity\uB85C \uB2E4\uC2DC \uB85C\uB4DC\uD569\uB2C8\uB2E4.");
900
- EntityManager.isAutoloaded = false;
901
- await EntityManager.autoload();
902
- const entityIds = EntityManager.getAllParentIds();
903
- for await (const entityId of entityIds) {
904
- await Sonamu.syncer.generateTemplate("generated", { entityId });
905
- }
906
- }
907
- //# sourceMappingURL=cli.mjs.map