tina4-nodejs 3.9.4 → 3.10.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.
package/CLAUDE.md CHANGED
@@ -1,10 +1,10 @@
1
- # CLAUDE.md — AI Developer Guide for tina4-nodejs (v3.9.2)
1
+ # CLAUDE.md — AI Developer Guide for tina4-nodejs (v3.10.2)
2
2
 
3
3
  > This file helps AI assistants (Claude, Copilot, Cursor, etc.) understand and work on this codebase effectively.
4
4
 
5
5
  ## What This Project Is
6
6
 
7
- Tina4 for Node.js/TypeScript v3.9.2 — a convention-over-configuration structural paradigm. **Not a framework.** The developer writes TypeScript; Tina4 is invisible infrastructure.
7
+ Tina4 for Node.js/TypeScript v3.10.2 — a convention-over-configuration structural paradigm. **Not a framework.** The developer writes TypeScript; Tina4 is invisible infrastructure.
8
8
 
9
9
  The philosophy: zero ceremony, batteries included, file system as source of truth.
10
10
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tina4-nodejs",
3
- "version": "3.9.4",
3
+ "version": "3.10.2",
4
4
  "type": "module",
5
5
  "description": "This is not a framework. Tina4 for Node.js/TypeScript — zero deps, 38 built-in features.",
6
6
  "keywords": ["tina4", "framework", "web", "api", "orm", "graphql", "websocket", "typescript"],
@@ -31,6 +31,9 @@ const BUILTIN_PUBLIC_DIR = resolve(__dirname, "..", "public");
31
31
 
32
32
  const TINA4_VERSION = "3.0.0";
33
33
 
34
+ /** Cache Frond instances by template directory to avoid repeated instantiation. */
35
+ const frondCache = new Map<string, InstanceType<any>>();
36
+
34
37
  /**
35
38
  * Test-bind each port in a subprocess to find one that is available.
36
39
  * Falls back to `start` if none of the candidates work.
@@ -94,18 +97,26 @@ async function renderErrorPage(
94
97
  const { Frond } = await import("@tina4/frond");
95
98
  const templateFile = `errors/${code}.twig`;
96
99
 
100
+ // Helper: get-or-create a cached Frond instance for a directory
101
+ const getCachedFrond = (dir: string) => {
102
+ let instance = frondCache.get(dir);
103
+ if (!instance) {
104
+ instance = new Frond(dir);
105
+ frondCache.set(dir, instance);
106
+ }
107
+ return instance;
108
+ };
109
+
97
110
  // 1. Try user override in the project's templates directory
98
111
  const userTemplatePath = join(templatesDir, templateFile);
99
112
  if (existsSync(userTemplatePath)) {
100
- const frond = new Frond(templatesDir);
101
- return frond.render(templateFile, data);
113
+ return getCachedFrond(templatesDir).render(templateFile, data);
102
114
  }
103
115
 
104
116
  // 2. Try built-in framework default
105
117
  const builtinTemplatePath = join(BUILTIN_ERROR_TEMPLATES_DIR, templateFile);
106
118
  if (existsSync(builtinTemplatePath)) {
107
- const frond = new Frond(BUILTIN_ERROR_TEMPLATES_DIR);
108
- return frond.render(templateFile, data);
119
+ return getCachedFrond(BUILTIN_ERROR_TEMPLATES_DIR).render(templateFile, data);
109
120
  }
110
121
 
111
122
  // 3. No template found
@@ -135,13 +135,67 @@ function resolveVar(expr: string, context: Record<string, unknown>): unknown {
135
135
  return items.map(item => evalExpr(item.trim(), context));
136
136
  }
137
137
 
138
- // Dotted path with bracket access
139
- const parts = expr.split(/\.|\[([^\]]+)\]/g).filter(p => p !== undefined && p !== "");
138
+ // Dotted path with bracket access — split on . and [...] but not . inside parentheses
139
+ const parts: string[] = [];
140
+ {
141
+ let current = "";
142
+ let depth = 0;
143
+ let inQuote: string | null = null;
144
+ for (let i = 0; i < expr.length; i++) {
145
+ const ch = expr[i];
146
+ if (inQuote) {
147
+ current += ch;
148
+ if (ch === inQuote) inQuote = null;
149
+ continue;
150
+ }
151
+ if (ch === '"' || ch === "'") { inQuote = ch; current += ch; continue; }
152
+ if (ch === '(') { depth++; current += ch; continue; }
153
+ if (ch === ')') { depth--; current += ch; continue; }
154
+ if (ch === '.' && depth === 0) {
155
+ if (current) parts.push(current);
156
+ current = "";
157
+ continue;
158
+ }
159
+ if (ch === '[' && depth === 0) {
160
+ if (current) parts.push(current);
161
+ current = "";
162
+ const end = expr.indexOf(']', i + 1);
163
+ if (end !== -1) {
164
+ parts.push(expr.slice(i + 1, end));
165
+ i = end;
166
+ }
167
+ continue;
168
+ }
169
+ current += ch;
170
+ }
171
+ if (current) parts.push(current);
172
+ }
140
173
 
141
174
  let value: unknown = context;
142
175
  for (const part of parts) {
143
176
  if (value === null || value === undefined) return null;
144
177
 
178
+ // Check for method call: name(args)
179
+ const methodMatch = part.match(/^(\w+)\s*\(([\s\S]*)?\)$/);
180
+ if (methodMatch) {
181
+ const methodName = methodMatch[1];
182
+ const rawArgs = methodMatch[2] || "";
183
+ if (typeof value === "object" && value !== null && methodName in (value as Record<string, unknown>)) {
184
+ const fn = (value as Record<string, unknown>)[methodName];
185
+ if (typeof fn === "function") {
186
+ if (rawArgs.trim()) {
187
+ const argParts = splitArgs(rawArgs);
188
+ const evalArgs = argParts.map(a => evalExpr(a.trim(), context));
189
+ value = fn.apply(value, evalArgs);
190
+ } else {
191
+ value = fn.call(value);
192
+ }
193
+ continue;
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+
145
199
  let key: string | number = part.replace(/^['"]|['"]$/g, "");
146
200
  const asNum = parseInt(key, 10);
147
201
  if (!isNaN(asNum) && String(asNum) === key) {
@@ -3,6 +3,20 @@ import { validate as validateFields } from "./validation.js";
3
3
  import { QueryBuilder } from "./queryBuilder.js";
4
4
  import type { DatabaseAdapter, FieldDefinition, RelationshipDefinition } from "./types.js";
5
5
 
6
+ /**
7
+ * Convert a snake_case name to camelCase.
8
+ */
9
+ export function snakeToCamel(name: string): string {
10
+ return name.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
11
+ }
12
+
13
+ /**
14
+ * Convert a camelCase name to snake_case.
15
+ */
16
+ export function camelToSnake(name: string): string {
17
+ return name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
18
+ }
19
+
6
20
  /**
7
21
  * BaseModel provides instance methods for ORM models.
8
22
  * Models extend this class and define static properties.
@@ -17,6 +31,7 @@ import type { DatabaseAdapter, FieldDefinition, RelationshipDefinition } from ".
17
31
  * static hasMany = [{ model: "Post", foreignKey: "author_id" }];
18
32
  * static _db = "secondary";
19
33
  * static fieldMapping = { firstName: "first_name", lastName: "last_name" };
34
+ * static autoMap = true; // auto-generate fieldMapping from camelCase → snake_case
20
35
  * }
21
36
  */
22
37
  export class BaseModel {
@@ -29,6 +44,12 @@ export class BaseModel {
29
44
  static belongsTo?: RelationshipDefinition[];
30
45
  static _db?: string;
31
46
 
47
+ /**
48
+ * When true, auto-generates fieldMapping entries from camelCase field names
49
+ * to snake_case DB column names. Explicit fieldMapping entries always win.
50
+ */
51
+ static autoMap: boolean = false;
52
+
32
53
  /**
33
54
  * Maps JS property names to database column names.
34
55
  * Example: { firstName: "first_name" } means the JS property `firstName`
@@ -46,6 +67,18 @@ export class BaseModel {
46
67
  constructor(data?: Record<string, unknown>) {
47
68
  if (data) {
48
69
  const ModelClass = this.constructor as typeof BaseModel;
70
+ // If autoMap is on, auto-generate fieldMapping from camelCase fields
71
+ if (ModelClass.autoMap) {
72
+ const fields = ModelClass.fields || {};
73
+ for (const key of Object.keys(fields)) {
74
+ if (!ModelClass.fieldMapping[key]) {
75
+ const snaked = camelToSnake(key);
76
+ if (snaked !== key) {
77
+ ModelClass.fieldMapping[key] = snaked;
78
+ }
79
+ }
80
+ }
81
+ }
49
82
  const reverseMapping = ModelClass.getReverseMapping();
50
83
  for (const [key, value] of Object.entries(data)) {
51
84
  // If this DB column has a mapping, use the JS property name instead
@@ -38,7 +38,7 @@ export { generateCrudRoutes } from "./autoCrud.js";
38
38
  export { buildQuery, parseQueryString } from "./query.js";
39
39
  export { validate } from "./validation.js";
40
40
  export type { ValidationError } from "./validation.js";
41
- export { BaseModel } from "./baseModel.js";
41
+ export { BaseModel, snakeToCamel, camelToSnake } from "./baseModel.js";
42
42
  export { QueryBuilder } from "./queryBuilder.js";
43
43
  export { SQLTranslator, QueryCache } from "./sqlTranslation.js";
44
44
  export { CachedDatabaseAdapter } from "./cachedDatabase.js";