@snowtop/ent 0.1.0-alpha → 0.1.0-alpha6

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.
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ const glob_1 = require("glob");
26
+ const typescript_1 = __importDefault(require("typescript"));
27
+ const fs = __importStar(require("fs"));
28
+ const compilerOptions_1 = require("../tsc/compilerOptions");
29
+ const child_process_1 = require("child_process");
30
+ function getTarget(target) {
31
+ switch (target.toLowerCase()) {
32
+ case "es2015":
33
+ return typescript_1.default.ScriptTarget.ES2015;
34
+ case "es2016":
35
+ return typescript_1.default.ScriptTarget.ES2016;
36
+ case "es2017":
37
+ return typescript_1.default.ScriptTarget.ES2017;
38
+ case "es2018":
39
+ return typescript_1.default.ScriptTarget.ES2018;
40
+ case "es2019":
41
+ return typescript_1.default.ScriptTarget.ES2019;
42
+ case "es2020":
43
+ return typescript_1.default.ScriptTarget.ES2020;
44
+ case "es2021":
45
+ return typescript_1.default.ScriptTarget.ES2021;
46
+ case "es3":
47
+ return typescript_1.default.ScriptTarget.ES3;
48
+ case "es5":
49
+ return typescript_1.default.ScriptTarget.ES5;
50
+ case "esnext":
51
+ return typescript_1.default.ScriptTarget.ESNext;
52
+ default:
53
+ return typescript_1.default.ScriptTarget.ESNext;
54
+ }
55
+ }
56
+ async function main() {
57
+ // this assumes this is being run from root of directory
58
+ const options = (0, compilerOptions_1.readCompilerOptions)(".");
59
+ let files = glob_1.glob.sync("src/schema/*.ts");
60
+ const target = options.target
61
+ ? // @ts-ignore
62
+ getTarget(options.target)
63
+ : typescript_1.default.ScriptTarget.ESNext;
64
+ // filter to only event.ts e.g. for comments and whitespace...
65
+ // files = files.filter((f) => f.endsWith("event.ts"));
66
+ files.forEach((file) => {
67
+ // assume valid file since we do glob above
68
+ const idx = file.lastIndexOf(".ts");
69
+ const writeFile = file.substring(0, idx) + "2" + ".ts";
70
+ let contents = fs.readFileSync(file).toString();
71
+ // go through the file and print everything back if not starting immediately after other position
72
+ const sourceFile = typescript_1.default.createSourceFile(file, contents, target, false, typescript_1.default.ScriptKind.TS);
73
+ const nodes = [];
74
+ let updateImport = false;
75
+ const f = {
76
+ trackNode: function (tni) {
77
+ nodes.push({
78
+ node: tni.node,
79
+ importNode: tni.node && typescript_1.default.isImportDeclaration(tni.node),
80
+ rawString: tni.rawString,
81
+ });
82
+ },
83
+ flagUpdateImport() {
84
+ updateImport = true;
85
+ },
86
+ };
87
+ if (!traverse(contents, sourceFile, f)) {
88
+ return;
89
+ }
90
+ let newContents = "";
91
+ for (const node of nodes) {
92
+ if (updateImport && node.importNode) {
93
+ const importNode = node.node;
94
+ const transformedImport = transformImport(importNode, sourceFile);
95
+ if (transformedImport) {
96
+ newContents += transformedImport;
97
+ continue;
98
+ }
99
+ }
100
+ if (node.node) {
101
+ newContents += node.node.getFullText(sourceFile);
102
+ }
103
+ else if (node.rawString) {
104
+ newContents += node.rawString;
105
+ }
106
+ else {
107
+ console.error("invalid node");
108
+ }
109
+ }
110
+ // console.debug(newContents);
111
+ // ideally there's a flag that indicates if we write
112
+ fs.writeFileSync(writeFile, newContents);
113
+ });
114
+ (0, child_process_1.execSync)("prettier src/schema/*.ts --write");
115
+ }
116
+ function traverse(fileContents, sourceFile, f) {
117
+ let traversed = false;
118
+ typescript_1.default.forEachChild(sourceFile, function (node) {
119
+ if (typescript_1.default.isClassDeclaration(node)) {
120
+ traversed = true;
121
+ // TODO address implicit schema doesn't work here...
122
+ // console.debug(sourceFile.fileName, node.kind);
123
+ if (traverseClass(fileContents, sourceFile, node, f)) {
124
+ f.flagUpdateImport();
125
+ return;
126
+ }
127
+ }
128
+ f.trackNode({ node });
129
+ });
130
+ return traversed;
131
+ }
132
+ // TODO need to replace class field member, print that and see what happens
133
+ function traverseClass(fileContents, sourceFile, node, f) {
134
+ let updated = false;
135
+ // beginning of class...
136
+ // including comment
137
+ let klassContents = fileContents.substring(node.getFullStart(), node.members[0].getFullStart());
138
+ for (let member of node.members) {
139
+ if (!isFieldElement(member, sourceFile)) {
140
+ klassContents += member.getFullText(sourceFile);
141
+ continue;
142
+ }
143
+ // intentionally doesn't parse decorators since we don't need it
144
+ let fieldMap = "";
145
+ // fieldMapComment...
146
+ const comment = getPreText(fileContents, member, sourceFile);
147
+ if (comment) {
148
+ fieldMap += comment;
149
+ }
150
+ updated = true;
151
+ // need to change to fields: FieldMap = {code: StringType()};
152
+ const property = member;
153
+ const initializer = property.initializer;
154
+ fieldMap += "fields: FieldMap = {";
155
+ for (const element of initializer.elements) {
156
+ const parsed = parseFieldElement(element, sourceFile, fileContents);
157
+ if (parsed === null) {
158
+ return false;
159
+ }
160
+ const { callEx, name, nameComment, properties } = parsed;
161
+ let property = "";
162
+ const fieldComment = getPreText(fileContents, element, sourceFile).trim();
163
+ if (fieldComment) {
164
+ property += "\n" + fieldComment + "\n";
165
+ }
166
+ if (nameComment) {
167
+ property += nameComment + "\n";
168
+ }
169
+ // e.g. UUIDType, StringType etc
170
+ let call = callEx.expression.getText(sourceFile);
171
+ let fnCall = "";
172
+ if (properties.length) {
173
+ fnCall = `{${properties.join(",")}}`;
174
+ }
175
+ property += `${name}:${call}(${fnCall}),`;
176
+ fieldMap += property;
177
+ }
178
+ fieldMap += "}";
179
+ klassContents += fieldMap;
180
+ }
181
+ klassContents += "\n}";
182
+ // console.debug(klassContents);
183
+ if (!updated) {
184
+ return updated;
185
+ }
186
+ f.trackNode({ rawString: klassContents });
187
+ return updated;
188
+ }
189
+ function isFieldElement(member, sourceFile) {
190
+ if (member.kind !== typescript_1.default.SyntaxKind.PropertyDeclaration) {
191
+ return false;
192
+ }
193
+ const property = member;
194
+ const token = property.name;
195
+ if (token.escapedText !== "fields") {
196
+ return false;
197
+ }
198
+ const propertytype = property.type?.getText(sourceFile);
199
+ if (propertytype !== "Field[]") {
200
+ return false;
201
+ }
202
+ if (property.initializer?.kind !== typescript_1.default.SyntaxKind.ArrayLiteralExpression) {
203
+ console.error("invalid array type");
204
+ return false;
205
+ }
206
+ return true;
207
+ }
208
+ function parseFieldElement(element, sourceFile, fileContents) {
209
+ if (element.kind !== typescript_1.default.SyntaxKind.CallExpression) {
210
+ console.error("skipped non-call expression");
211
+ return null;
212
+ }
213
+ let callEx = element;
214
+ if (callEx.arguments.length !== 1) {
215
+ console.error("callExpression with arguments not of length 1");
216
+ return null;
217
+ }
218
+ let arg = callEx.arguments[0];
219
+ if (arg.kind !== typescript_1.default.SyntaxKind.ObjectLiteralExpression) {
220
+ console.error("not objectLiteralExpression");
221
+ return null;
222
+ }
223
+ let expr = arg;
224
+ let name = "";
225
+ let propertyComment;
226
+ let properties = [];
227
+ for (const p of expr.properties) {
228
+ const p2 = p;
229
+ // found name property
230
+ if (p2.name.escapedText === "name") {
231
+ name = p2.initializer.getText(sourceFile);
232
+ // check for any comment associated with name: "fooo"
233
+ propertyComment = getPreText(fileContents, p, sourceFile).trim();
234
+ }
235
+ else {
236
+ properties.push(p.getFullText(sourceFile));
237
+ }
238
+ }
239
+ if (!name) {
240
+ console.error(`couldn't find name property`);
241
+ return null;
242
+ }
243
+ // remove quotes
244
+ name = name.slice(1, -1);
245
+ return {
246
+ callEx,
247
+ name,
248
+ properties,
249
+ nameComment: propertyComment,
250
+ };
251
+ }
252
+ function transformImport(importNode, sourceFile) {
253
+ // remove quotes too
254
+ const text = importNode.moduleSpecifier.getText(sourceFile).slice(1, -1);
255
+ if (text !== "@snowtop/ent" &&
256
+ text !== "@snowtop/ent/schema" &&
257
+ text !== "@snowtop/ent/schema/") {
258
+ return;
259
+ }
260
+ const importText = importNode.importClause?.getText(sourceFile) || "";
261
+ const start = importText.indexOf("{");
262
+ const end = importText.lastIndexOf("}");
263
+ if (start === -1 || end === -1) {
264
+ return;
265
+ }
266
+ const imports = importText
267
+ .substring(start + 1, end)
268
+ // .trim()
269
+ .split(",");
270
+ for (let i = 0; i < imports.length; i++) {
271
+ const imp = imports[i].trim();
272
+ if (imp === "Field") {
273
+ imports[i] = "FieldMap";
274
+ }
275
+ }
276
+ // TODO better to update node instead of doing this but this works for now
277
+ return ("import " +
278
+ importText.substring(0, start + 1) +
279
+ imports.join(", ") +
280
+ importText.substring(end) +
281
+ ' from "' +
282
+ text +
283
+ '"');
284
+ }
285
+ function getPreText(fileContents, node, sourceFile) {
286
+ return fileContents.substring(node.getFullStart(), node.getStart(sourceFile));
287
+ }
288
+ Promise.resolve(main());
@@ -479,8 +479,8 @@ exports.setupSqlite = setupSqlite;
479
479
  function getSchemaTable(schema, dialect) {
480
480
  const fields = (0, schema_1.getFields)(schema);
481
481
  const columns = [];
482
- for (const [_, field] of fields) {
483
- columns.push(getColumnFromField(field, dialect));
482
+ for (const [fieldName, field] of fields) {
483
+ columns.push(getColumnFromField(fieldName, field, dialect));
484
484
  }
485
485
  return table((0, builder_1.getTableName)(schema), ...columns);
486
486
  }
@@ -520,7 +520,7 @@ function getColumnForDbType(t, dialect) {
520
520
  return undefined;
521
521
  }
522
522
  }
523
- function getColumnFromField(f, dialect) {
523
+ function getColumnFromField(fieldName, f, dialect) {
524
524
  switch (f.type.dbType) {
525
525
  case schema_1.DBType.List:
526
526
  const elemType = f.type.listElemType;
@@ -531,17 +531,17 @@ function getColumnFromField(f, dialect) {
531
531
  if (elemFn === undefined) {
532
532
  throw new Error(`unsupported type for ${elemType}`);
533
533
  }
534
- return list(storageKey(f), elemFn("ignore"), buildOpts(f));
534
+ return list(storageKey(fieldName, f), elemFn("ignore"), buildOpts(f));
535
535
  default:
536
536
  const fn = getColumnForDbType(f.type.dbType, dialect);
537
537
  if (fn === undefined) {
538
538
  throw new Error(`unsupported type ${f.type.dbType}`);
539
539
  }
540
- return getColumn(f, fn);
540
+ return getColumn(fieldName, f, fn);
541
541
  }
542
542
  }
543
- function getColumn(f, col) {
544
- return col(storageKey(f), buildOpts(f));
543
+ function getColumn(fieldName, f, col) {
544
+ return col(storageKey(fieldName, f), buildOpts(f));
545
545
  }
546
546
  function buildOpts(f) {
547
547
  let ret = {};
@@ -560,11 +560,11 @@ function buildOpts(f) {
560
560
  }
561
561
  return ret;
562
562
  }
563
- function storageKey(f) {
563
+ function storageKey(fieldName, f) {
564
564
  if (f.storageKey) {
565
565
  return f.storageKey;
566
566
  }
567
- return (0, snake_case_1.snakeCase)(f.name);
567
+ return (0, snake_case_1.snakeCase)(fieldName);
568
568
  }
569
569
  function isSyncClient(client) {
570
570
  return client.execSync !== undefined;
@@ -1,6 +1,6 @@
1
1
  import { ID, Ent, Viewer, Data, LoadEntOptions, PrivacyPolicy } from "../../core/base";
2
2
  import { BuilderSchema, SimpleBuilder } from "../builder";
3
- import { Field, BaseEntSchema } from "../../schema";
3
+ import { BaseEntSchema, FieldMap } from "../../schema";
4
4
  import { NodeType } from "./const";
5
5
  import { ObjectLoaderFactory } from "../../core/loaders";
6
6
  export declare class FakeContact implements Ent {
@@ -24,7 +24,7 @@ export declare class FakeContact implements Ent {
24
24
  }
25
25
  export declare class FakeContactSchema extends BaseEntSchema implements BuilderSchema<FakeContact> {
26
26
  ent: typeof FakeContact;
27
- fields: Field[];
27
+ fields: FieldMap;
28
28
  }
29
29
  export interface ContactCreateInput {
30
30
  firstName: string;
@@ -63,21 +63,14 @@ class FakeContactSchema extends schema_1.BaseEntSchema {
63
63
  constructor() {
64
64
  super(...arguments);
65
65
  this.ent = FakeContact;
66
- this.fields = [
67
- (0, schema_1.StringType)({
68
- name: "firstName",
69
- }),
70
- (0, schema_1.StringType)({
71
- name: "lastName",
72
- }),
73
- (0, schema_1.StringType)({
74
- name: "emailAddress",
75
- }),
76
- (0, schema_1.UUIDType)({
77
- name: "userID",
66
+ this.fields = {
67
+ firstName: (0, schema_1.StringType)(),
68
+ lastName: (0, schema_1.StringType)(),
69
+ emailAddress: (0, schema_1.StringType)(),
70
+ userID: (0, schema_1.UUIDType)({
78
71
  foreignKey: { schema: "User", column: "ID" },
79
72
  }),
80
- ];
73
+ };
81
74
  }
82
75
  }
83
76
  exports.FakeContactSchema = FakeContactSchema;
@@ -1,6 +1,6 @@
1
1
  import { ID, Ent, Viewer, Data, LoadEntOptions, PrivacyPolicy } from "../../core/base";
2
2
  import { BuilderSchema, SimpleBuilder } from "../builder";
3
- import { Field, BaseEntSchema } from "../../schema";
3
+ import { BaseEntSchema, FieldMap } from "../../schema";
4
4
  import { NodeType } from "./const";
5
5
  export declare class FakeEvent implements Ent {
6
6
  viewer: Viewer;
@@ -25,7 +25,7 @@ export declare class FakeEvent implements Ent {
25
25
  }
26
26
  export declare class FakeEventSchema extends BaseEntSchema implements BuilderSchema<FakeEvent> {
27
27
  ent: typeof FakeEvent;
28
- fields: Field[];
28
+ fields: FieldMap;
29
29
  }
30
30
  export interface EventCreateInput {
31
31
  startTime: Date;
@@ -67,30 +67,22 @@ class FakeEventSchema extends schema_1.BaseEntSchema {
67
67
  constructor() {
68
68
  super(...arguments);
69
69
  this.ent = FakeEvent;
70
- this.fields = [
71
- (0, schema_1.TimestampType)({
72
- name: "startTime",
70
+ this.fields = {
71
+ startTime: (0, schema_1.TimestampType)({
73
72
  index: true,
74
73
  }),
75
- (0, schema_1.TimestampType)({
76
- name: "endTime",
74
+ endTime: (0, schema_1.TimestampType)({
77
75
  nullable: true,
78
76
  }),
79
- (0, schema_1.StringType)({
80
- name: "title",
81
- }),
82
- (0, schema_1.StringType)({
83
- name: "location",
84
- }),
85
- (0, schema_1.StringType)({
86
- name: "description",
77
+ title: (0, schema_1.StringType)(),
78
+ location: (0, schema_1.StringType)(),
79
+ description: (0, schema_1.StringType)({
87
80
  nullable: true,
88
81
  }),
89
- (0, schema_1.UUIDType)({
90
- name: "userID",
82
+ userID: (0, schema_1.UUIDType)({
91
83
  foreignKey: { schema: "User", column: "ID" },
92
84
  }),
93
- ];
85
+ };
94
86
  }
95
87
  }
96
88
  exports.FakeEventSchema = FakeEventSchema;
@@ -1,6 +1,6 @@
1
1
  import { ID, Ent, Viewer, Data, LoadEntOptions, PrivacyPolicy } from "../../core/base";
2
2
  import { BuilderSchema, SimpleAction } from "../builder";
3
- import { Field, BaseEntSchema } from "../../schema";
3
+ import { BaseEntSchema, FieldMap } from "../../schema";
4
4
  import { NodeType } from "./const";
5
5
  import { IDViewer, IDViewerOptions } from "../../core/viewer";
6
6
  import { ObjectLoaderFactory } from "../../core/loaders";
@@ -34,7 +34,7 @@ export declare class FakeUser implements Ent {
34
34
  }
35
35
  export declare class FakeUserSchema extends BaseEntSchema implements BuilderSchema<FakeUser> {
36
36
  ent: typeof FakeUser;
37
- fields: Field[];
37
+ fields: FieldMap;
38
38
  }
39
39
  export interface UserCreateInput {
40
40
  firstName: string;
@@ -93,24 +93,15 @@ class FakeUserSchema extends schema_1.BaseEntSchema {
93
93
  constructor() {
94
94
  super(...arguments);
95
95
  this.ent = FakeUser;
96
- this.fields = [
97
- (0, schema_1.StringType)({
98
- name: "firstName",
99
- }),
100
- (0, schema_1.StringType)({
101
- name: "lastName",
102
- }),
103
- (0, schema_1.StringType)({
104
- name: "emailAddress",
105
- }),
106
- (0, schema_1.StringType)({
107
- name: "phoneNumber",
108
- }),
109
- (0, schema_1.StringType)({
110
- name: "password",
96
+ this.fields = {
97
+ firstName: (0, schema_1.StringType)(),
98
+ lastName: (0, schema_1.StringType)(),
99
+ emailAddress: (0, schema_1.StringType)(),
100
+ phoneNumber: (0, schema_1.StringType)(),
101
+ password: (0, schema_1.StringType)({
111
102
  nullable: true,
112
103
  }),
113
- ];
104
+ };
114
105
  }
115
106
  }
116
107
  exports.FakeUserSchema = FakeUserSchema;
@@ -0,0 +1,2 @@
1
+ import ts from "typescript";
2
+ export declare function readCompilerOptions(filePath: string): ts.CompilerOptions;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.readCompilerOptions = void 0;
26
+ const fs = __importStar(require("fs"));
27
+ const json5_1 = __importDefault(require("json5"));
28
+ const typescript_1 = __importDefault(require("typescript"));
29
+ const path = __importStar(require("path"));
30
+ function findTSConfigFile(filePath) {
31
+ while (filePath != "/") {
32
+ let configPath = `${filePath}/tsconfig.json`;
33
+ if (fs.existsSync(configPath)) {
34
+ return configPath;
35
+ }
36
+ filePath = path.join(filePath, "..");
37
+ }
38
+ return null;
39
+ }
40
+ function readCompilerOptions(filePath) {
41
+ let configPath = findTSConfigFile(filePath);
42
+ if (!configPath) {
43
+ return {};
44
+ }
45
+ let json = {};
46
+ try {
47
+ json = json5_1.default.parse(fs.readFileSync(configPath, {
48
+ encoding: "utf8",
49
+ }));
50
+ }
51
+ catch (e) {
52
+ console.error("couldn't read tsconfig.json file");
53
+ }
54
+ let options = json["compilerOptions"] || {};
55
+ // @ts-ignore
56
+ if (options.moduleResolution === "node") {
57
+ options.moduleResolution = typescript_1.default.ModuleResolutionKind.NodeJs;
58
+ }
59
+ return options;
60
+ }
61
+ exports.readCompilerOptions = readCompilerOptions;