@clivly/core 0.1.0 → 0.2.0

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,188 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/view-compiler.ts
3
+ /**
4
+ * View compiler (Phase 2) — turns a validated entity config into read-only
5
+ * Postgres view DDL.
6
+ *
7
+ * Each entity compiles to `crm_src_<entity>`: a projection over the host table
8
+ * that (a) selects the source primary key as `id` (the sync engine's
9
+ * `source_ref`), (b) aliases mapped columns to their Clivly field names,
10
+ * (c) resolves each relationship to a `<relationship>_ref` column carrying the
11
+ * host-side key, and (d) applies the entity's filter as a WHERE clause.
12
+ *
13
+ * The view is the security boundary: it exposes only allow-listed columns, and
14
+ * the sync engine (Phase 3) reads exclusively from it — never the raw table.
15
+ * Relationship refs stay host-side keys here; Phase 3 maps `<rel>_ref` onto the
16
+ * corresponding `crm_companies.id` mirror row.
17
+ *
18
+ * Pure string generation — no DB access. Config is developer-authored, but all
19
+ * identifiers and literals are still escaped so output is deterministic and
20
+ * injection-safe.
21
+ */
22
+ /** The source primary-key column. Assumed `id`; the sync engine reads it as `source_ref`. */
23
+ const SOURCE_KEY = "id";
24
+ const DEFAULT_VIEW_PREFIX = "crm_src_";
25
+ const DEFAULT_ROLE = "primary";
26
+ /** Quote a single identifier part, escaping embedded double-quotes. */
27
+ function quoteIdent(name) {
28
+ return `"${name.replace(/"/g, "\"\"")}"`;
29
+ }
30
+ /** Emit a SQL literal for a scalar filter value. */
31
+ function quoteLiteral(value) {
32
+ if (typeof value === "number") return String(value);
33
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
34
+ return `'${value.replace(/'/g, "''")}'`;
35
+ }
36
+ function quoteList(values) {
37
+ return `(${values.map((v) => quoteLiteral(v)).join(", ")})`;
38
+ }
39
+ /** Compile one column predicate into a SQL boolean expression. */
40
+ function compilePredicate(table, column, value) {
41
+ const col = `${quoteIdent(table)}.${quoteIdent(column)}`;
42
+ if (value === null || typeof value !== "object") return `${col} = ${quoteLiteral(value)}`;
43
+ if ("eq" in value) return `${col} = ${quoteLiteral(value.eq)}`;
44
+ if ("ne" in value) return `${col} <> ${quoteLiteral(value.ne)}`;
45
+ if ("in" in value) return `${col} IN ${quoteList(value.in)}`;
46
+ if ("notIn" in value) return `${col} NOT IN ${quoteList(value.notIn)}`;
47
+ if ("isNull" in value) return `${col} IS NULL`;
48
+ if ("isNotNull" in value) return `${col} IS NOT NULL`;
49
+ throw new Error(`unsupported filter predicate on ${table}.${column}`);
50
+ }
51
+ /**
52
+ * Build the WHERE conditions for an entity. Returns an array of SQL fragments
53
+ * (ANDed by the caller). `$raw` filters pass through verbatim.
54
+ */
55
+ function compileFilterConditions(table, filter) {
56
+ if (!filter) return [];
57
+ if ("$raw" in filter) return [`(${filter.$raw})`];
58
+ return Object.entries(filter).map(([column, value]) => compilePredicate(table, column, value));
59
+ }
60
+ /** Split a `table.column` ref, defaulting the table when unqualified. */
61
+ function refParts(ref, defaultTable) {
62
+ const dot = ref.indexOf(".");
63
+ if (dot === -1) return {
64
+ table: defaultTable,
65
+ column: ref
66
+ };
67
+ return {
68
+ table: ref.slice(0, dot),
69
+ column: ref.slice(dot + 1)
70
+ };
71
+ }
72
+ function compileRelationship(relName, rel, source, related) {
73
+ const refCol = `${relName}_ref`;
74
+ const refAlias = quoteIdent(refCol);
75
+ const { via } = rel;
76
+ if ("fkOn" in via) {
77
+ const relatedTable = related?.source ?? "";
78
+ if (via.fkOn === "company") {
79
+ const { table, column } = refParts(via.column, relatedTable);
80
+ const relatedFilter = compileFilterConditions(table, related?.filter);
81
+ const on = [`${quoteIdent(table)}.${quoteIdent(column)} = ${quoteIdent(source.source)}.${quoteIdent(SOURCE_KEY)}`, ...relatedFilter].join(" AND ");
82
+ return {
83
+ clause: `LEFT JOIN ${quoteIdent(table)} ON ${on}`,
84
+ refSelect: `${quoteIdent(table)}.${quoteIdent(SOURCE_KEY)} AS ${refAlias}`,
85
+ refColumn: refCol
86
+ };
87
+ }
88
+ const { table, column } = refParts(via.column, source.source);
89
+ const on = [`${quoteIdent(relatedTable)}.${quoteIdent(SOURCE_KEY)} = ${quoteIdent(table)}.${quoteIdent(column)}`, ...compileFilterConditions(relatedTable, related?.filter)].join(" AND ");
90
+ return {
91
+ clause: `LEFT JOIN ${quoteIdent(relatedTable)} ON ${on}`,
92
+ refSelect: `${quoteIdent(relatedTable)}.${quoteIdent(SOURCE_KEY)} AS ${refAlias}`,
93
+ refColumn: refCol
94
+ };
95
+ }
96
+ if ("through" in via) {
97
+ const on = `${quoteIdent(via.through)}.${quoteIdent(via.localKey)} = ${quoteIdent(source.source)}.${quoteIdent(SOURCE_KEY)}`;
98
+ return {
99
+ clause: `LEFT JOIN ${quoteIdent(via.through)} ON ${on}`,
100
+ refSelect: `${quoteIdent(via.through)}.${quoteIdent(via.foreignKey)} AS ${refAlias}`,
101
+ refColumn: refCol
102
+ };
103
+ }
104
+ return {
105
+ clause: via.$raw,
106
+ refSelect: null,
107
+ refColumn: refCol
108
+ };
109
+ }
110
+ function compileEntityView(config, entityKey, options = {}) {
111
+ const entity = config.entities[entityKey];
112
+ if (!entity) throw new Error(`entity "${entityKey}" is not defined`);
113
+ const viewName = `${options.viewPrefix ?? DEFAULT_VIEW_PREFIX}${entityKey}`;
114
+ const src = entity.source;
115
+ const selectItems = [`${quoteIdent(src)}.${quoteIdent(SOURCE_KEY)} AS ${quoteIdent("id")}`];
116
+ const columns = ["id"];
117
+ for (const [field, column] of Object.entries(entity.fields)) {
118
+ selectItems.push(`${quoteIdent(src)}.${quoteIdent(column)} AS ${quoteIdent(field)}`);
119
+ columns.push(field);
120
+ }
121
+ const joins = [];
122
+ for (const [relName, rel] of Object.entries(entity.relationships ?? {})) {
123
+ const compiled = compileRelationship(relName, rel, entity, config.entities[rel.entity]);
124
+ joins.push(compiled.clause);
125
+ if (compiled.refSelect) {
126
+ selectItems.push(compiled.refSelect);
127
+ columns.push(compiled.refColumn);
128
+ }
129
+ }
130
+ const conditions = compileFilterConditions(src, entity.filter);
131
+ if (options.orgScope) conditions.push(`${quoteIdent(src)}.${quoteIdent(options.orgScope.column)} = ${quoteLiteral(options.orgScope.value)}`);
132
+ const lines = [
133
+ options.securityInvoker ?? true ? `CREATE OR REPLACE VIEW ${quoteIdent(viewName)} WITH (security_invoker = true) AS` : `CREATE OR REPLACE VIEW ${quoteIdent(viewName)} AS`,
134
+ `SELECT ${selectItems.join(", ")}`,
135
+ `FROM ${quoteIdent(src)}`,
136
+ ...joins
137
+ ];
138
+ if (conditions.length > 0) lines.push(`WHERE ${conditions.join(" AND ")}`);
139
+ const sql = `${lines.join("\n")};`;
140
+ return {
141
+ entityKey,
142
+ viewName,
143
+ concept: entity.concept,
144
+ role: entity.role ?? DEFAULT_ROLE,
145
+ sourceTable: src,
146
+ columns,
147
+ sql,
148
+ dropSql: `DROP VIEW IF EXISTS ${quoteIdent(viewName)};`
149
+ };
150
+ }
151
+ /** Compile every entity in the config into its view, in declaration order. */
152
+ function compileEntityViews(config, options = {}) {
153
+ return Object.keys(config.entities).map((key) => compileEntityView(config, key, options));
154
+ }
155
+ /**
156
+ * Dry-run each entity's compiled view against the host DB via a caller-provided
157
+ * `run` function, so `$raw` filter/join fragments — which skip schema validation
158
+ * (see `validateEntitiesConfig`) — fail loudly *before* the first sync instead of
159
+ * at sync time. Never throws: each view's outcome is collected into an
160
+ * `ExplainResult`, so a mapping UI or CLI can show every problem at once.
161
+ *
162
+ * `run` should execute the SQL somewhere side-effect-free — e.g. inside a
163
+ * transaction it rolls back, or by `EXPLAIN`-ing the statement — since the
164
+ * compiled SQL is a `CREATE OR REPLACE VIEW`.
165
+ */
166
+ async function explainEntitiesConfig(config, run, options = {}) {
167
+ const results = [];
168
+ for (const view of compileEntityViews(config, options)) try {
169
+ await run(view.sql);
170
+ results.push({
171
+ entityKey: view.entityKey,
172
+ ok: true,
173
+ sql: view.sql
174
+ });
175
+ } catch (error) {
176
+ results.push({
177
+ entityKey: view.entityKey,
178
+ ok: false,
179
+ sql: view.sql,
180
+ error: error instanceof Error ? error.message : String(error)
181
+ });
182
+ }
183
+ return results;
184
+ }
185
+ //#endregion
186
+ exports.compileEntityView = compileEntityView;
187
+ exports.compileEntityViews = compileEntityViews;
188
+ exports.explainEntitiesConfig = explainEntitiesConfig;
@@ -0,0 +1,64 @@
1
+ import { ClivlyEntitiesConfig } from "./entity-config.cjs";
2
+
3
+ //#region src/view-compiler.d.ts
4
+ interface CompileOptions {
5
+ /**
6
+ * Optional tenant-scoping predicate ANDed into every view's WHERE, e.g.
7
+ * `{ column: "workspace_id", value: "ws_123" }`. Column must exist on the
8
+ * entity's source table (the compiler does not verify that — validate first).
9
+ */
10
+ orgScope?: {
11
+ column: string;
12
+ value: string | number;
13
+ };
14
+ /**
15
+ * Emit views `WITH (security_invoker = true)` so they run with the querying
16
+ * role's privileges instead of the (owner's) definer privileges — the
17
+ * default Postgres behaviour, which bypasses the caller's RLS. Defaults to
18
+ * `true`: the security boundary the product promises. Set `false` only for
19
+ * hosts on Postgres < 15, which lacks the option.
20
+ */
21
+ securityInvoker?: boolean;
22
+ /** View name prefix. Defaults to `crm_src_`. */
23
+ viewPrefix?: string;
24
+ }
25
+ interface CompiledView {
26
+ /** Output column names in SELECT order (`id`, mapped fields, then `<rel>_ref`s). */
27
+ columns: string[];
28
+ concept: string;
29
+ /** `DROP VIEW IF EXISTS …` statement (for teardown / reconfiguration). */
30
+ dropSql: string;
31
+ entityKey: string;
32
+ /** Resolved role — the entity's `role` or `"primary"`. */
33
+ role: string;
34
+ sourceTable: string;
35
+ /** `CREATE OR REPLACE VIEW … AS …` statement. */
36
+ sql: string;
37
+ viewName: string;
38
+ }
39
+ declare function compileEntityView(config: ClivlyEntitiesConfig, entityKey: string, options?: CompileOptions): CompiledView;
40
+ /** Compile every entity in the config into its view, in declaration order. */
41
+ declare function compileEntityViews(config: ClivlyEntitiesConfig, options?: CompileOptions): CompiledView[];
42
+ /** The outcome of dry-running one entity's compiled view against the host. */
43
+ interface ExplainResult {
44
+ entityKey: string;
45
+ /** The runner's error message when `ok` is false. */
46
+ error?: string;
47
+ ok: boolean;
48
+ /** The compiled view SQL that was run. */
49
+ sql: string;
50
+ }
51
+ /**
52
+ * Dry-run each entity's compiled view against the host DB via a caller-provided
53
+ * `run` function, so `$raw` filter/join fragments — which skip schema validation
54
+ * (see `validateEntitiesConfig`) — fail loudly *before* the first sync instead of
55
+ * at sync time. Never throws: each view's outcome is collected into an
56
+ * `ExplainResult`, so a mapping UI or CLI can show every problem at once.
57
+ *
58
+ * `run` should execute the SQL somewhere side-effect-free — e.g. inside a
59
+ * transaction it rolls back, or by `EXPLAIN`-ing the statement — since the
60
+ * compiled SQL is a `CREATE OR REPLACE VIEW`.
61
+ */
62
+ declare function explainEntitiesConfig(config: ClivlyEntitiesConfig, run: (sql: string) => Promise<unknown>, options?: CompileOptions): Promise<ExplainResult[]>;
63
+ //#endregion
64
+ export { CompileOptions, CompiledView, ExplainResult, compileEntityView, compileEntityViews, explainEntitiesConfig };
@@ -39,5 +39,26 @@ interface CompiledView {
39
39
  declare function compileEntityView(config: ClivlyEntitiesConfig, entityKey: string, options?: CompileOptions): CompiledView;
40
40
  /** Compile every entity in the config into its view, in declaration order. */
41
41
  declare function compileEntityViews(config: ClivlyEntitiesConfig, options?: CompileOptions): CompiledView[];
42
+ /** The outcome of dry-running one entity's compiled view against the host. */
43
+ interface ExplainResult {
44
+ entityKey: string;
45
+ /** The runner's error message when `ok` is false. */
46
+ error?: string;
47
+ ok: boolean;
48
+ /** The compiled view SQL that was run. */
49
+ sql: string;
50
+ }
51
+ /**
52
+ * Dry-run each entity's compiled view against the host DB via a caller-provided
53
+ * `run` function, so `$raw` filter/join fragments — which skip schema validation
54
+ * (see `validateEntitiesConfig`) — fail loudly *before* the first sync instead of
55
+ * at sync time. Never throws: each view's outcome is collected into an
56
+ * `ExplainResult`, so a mapping UI or CLI can show every problem at once.
57
+ *
58
+ * `run` should execute the SQL somewhere side-effect-free — e.g. inside a
59
+ * transaction it rolls back, or by `EXPLAIN`-ing the statement — since the
60
+ * compiled SQL is a `CREATE OR REPLACE VIEW`.
61
+ */
62
+ declare function explainEntitiesConfig(config: ClivlyEntitiesConfig, run: (sql: string) => Promise<unknown>, options?: CompileOptions): Promise<ExplainResult[]>;
42
63
  //#endregion
43
- export { CompileOptions, CompiledView, compileEntityView, compileEntityViews };
64
+ export { CompileOptions, CompiledView, ExplainResult, compileEntityView, compileEntityViews, explainEntitiesConfig };
@@ -151,5 +151,35 @@ function compileEntityView(config, entityKey, options = {}) {
151
151
  function compileEntityViews(config, options = {}) {
152
152
  return Object.keys(config.entities).map((key) => compileEntityView(config, key, options));
153
153
  }
154
+ /**
155
+ * Dry-run each entity's compiled view against the host DB via a caller-provided
156
+ * `run` function, so `$raw` filter/join fragments — which skip schema validation
157
+ * (see `validateEntitiesConfig`) — fail loudly *before* the first sync instead of
158
+ * at sync time. Never throws: each view's outcome is collected into an
159
+ * `ExplainResult`, so a mapping UI or CLI can show every problem at once.
160
+ *
161
+ * `run` should execute the SQL somewhere side-effect-free — e.g. inside a
162
+ * transaction it rolls back, or by `EXPLAIN`-ing the statement — since the
163
+ * compiled SQL is a `CREATE OR REPLACE VIEW`.
164
+ */
165
+ async function explainEntitiesConfig(config, run, options = {}) {
166
+ const results = [];
167
+ for (const view of compileEntityViews(config, options)) try {
168
+ await run(view.sql);
169
+ results.push({
170
+ entityKey: view.entityKey,
171
+ ok: true,
172
+ sql: view.sql
173
+ });
174
+ } catch (error) {
175
+ results.push({
176
+ entityKey: view.entityKey,
177
+ ok: false,
178
+ sql: view.sql,
179
+ error: error instanceof Error ? error.message : String(error)
180
+ });
181
+ }
182
+ return results;
183
+ }
154
184
  //#endregion
155
- export { compileEntityView, compileEntityViews };
185
+ export { compileEntityView, compileEntityViews, explainEntitiesConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clivly/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "ORM/auth-agnostic CRM adapter contracts and shared domain types for Clivly.",
@@ -8,40 +8,114 @@
8
8
  "sideEffects": false,
9
9
  "exports": {
10
10
  ".": {
11
- "types": "./dist/index.d.mts",
12
- "import": "./dist/index.mjs"
11
+ "import": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
13
19
  },
14
20
  "./adapter": {
15
- "types": "./dist/adapter.d.mts",
16
- "import": "./dist/adapter.mjs"
21
+ "import": {
22
+ "types": "./dist/adapter.d.mts",
23
+ "default": "./dist/adapter.mjs"
24
+ },
25
+ "require": {
26
+ "types": "./dist/adapter.d.cts",
27
+ "default": "./dist/adapter.cjs"
28
+ }
29
+ },
30
+ "./entity-heuristics": {
31
+ "import": {
32
+ "types": "./dist/entity-heuristics.d.mts",
33
+ "default": "./dist/entity-heuristics.mjs"
34
+ },
35
+ "require": {
36
+ "types": "./dist/entity-heuristics.d.cts",
37
+ "default": "./dist/entity-heuristics.cjs"
38
+ }
17
39
  },
18
40
  "./auth-adapter": {
19
- "types": "./dist/auth-adapter.d.mts",
20
- "import": "./dist/auth-adapter.mjs"
41
+ "import": {
42
+ "types": "./dist/auth-adapter.d.mts",
43
+ "default": "./dist/auth-adapter.mjs"
44
+ },
45
+ "require": {
46
+ "types": "./dist/auth-adapter.d.cts",
47
+ "default": "./dist/auth-adapter.cjs"
48
+ }
21
49
  },
22
50
  "./entity-config": {
23
- "types": "./dist/entity-config.d.mts",
24
- "import": "./dist/entity-config.mjs"
51
+ "import": {
52
+ "types": "./dist/entity-config.d.mts",
53
+ "default": "./dist/entity-config.mjs"
54
+ },
55
+ "require": {
56
+ "types": "./dist/entity-config.d.cts",
57
+ "default": "./dist/entity-config.cjs"
58
+ }
25
59
  },
26
60
  "./mappings-config": {
27
- "types": "./dist/mappings-config.d.mts",
28
- "import": "./dist/mappings-config.mjs"
61
+ "import": {
62
+ "types": "./dist/mappings-config.d.mts",
63
+ "default": "./dist/mappings-config.mjs"
64
+ },
65
+ "require": {
66
+ "types": "./dist/mappings-config.d.cts",
67
+ "default": "./dist/mappings-config.cjs"
68
+ }
29
69
  },
30
70
  "./mapping-form": {
31
- "types": "./dist/mapping-form.d.mts",
32
- "import": "./dist/mapping-form.mjs"
71
+ "import": {
72
+ "types": "./dist/mapping-form.d.mts",
73
+ "default": "./dist/mapping-form.mjs"
74
+ },
75
+ "require": {
76
+ "types": "./dist/mapping-form.d.cts",
77
+ "default": "./dist/mapping-form.cjs"
78
+ }
33
79
  },
34
80
  "./view-compiler": {
35
- "types": "./dist/view-compiler.d.mts",
36
- "import": "./dist/view-compiler.mjs"
81
+ "import": {
82
+ "types": "./dist/view-compiler.d.mts",
83
+ "default": "./dist/view-compiler.mjs"
84
+ },
85
+ "require": {
86
+ "types": "./dist/view-compiler.d.cts",
87
+ "default": "./dist/view-compiler.cjs"
88
+ }
37
89
  },
38
90
  "./sync-engine": {
39
- "types": "./dist/sync-engine.d.mts",
40
- "import": "./dist/sync-engine.mjs"
91
+ "import": {
92
+ "types": "./dist/sync-engine.d.mts",
93
+ "default": "./dist/sync-engine.mjs"
94
+ },
95
+ "require": {
96
+ "types": "./dist/sync-engine.d.cts",
97
+ "default": "./dist/sync-engine.cjs"
98
+ }
99
+ },
100
+ "./drizzle": {
101
+ "import": {
102
+ "types": "./dist/drizzle.d.mts",
103
+ "default": "./dist/drizzle.mjs"
104
+ },
105
+ "require": {
106
+ "types": "./dist/drizzle.d.cts",
107
+ "default": "./dist/drizzle.cjs"
108
+ }
41
109
  },
42
110
  "./types": {
43
- "types": "./dist/types.d.mts",
44
- "import": "./dist/types.mjs"
111
+ "import": {
112
+ "types": "./dist/types.d.mts",
113
+ "default": "./dist/types.mjs"
114
+ },
115
+ "require": {
116
+ "types": "./dist/types.d.cts",
117
+ "default": "./dist/types.cjs"
118
+ }
45
119
  }
46
120
  },
47
121
  "files": [
@@ -53,17 +127,26 @@
53
127
  "dependencies": {
54
128
  "zod": "^4.1.13"
55
129
  },
130
+ "peerDependencies": {
131
+ "drizzle-orm": ">=0.30"
132
+ },
133
+ "peerDependenciesMeta": {
134
+ "drizzle-orm": {
135
+ "optional": true
136
+ }
137
+ },
56
138
  "devDependencies": {
139
+ "drizzle-orm": "^0.45.1",
57
140
  "tsdown": "^0.21.9",
58
141
  "typescript": "^6",
59
- "vitest": "^3.2.4",
60
- "@clivly.com/config": "0.0.0"
142
+ "vitest": "^3.2.4"
61
143
  },
62
144
  "scripts": {
63
145
  "build": "tsdown",
64
146
  "check-types": "tsc --noEmit",
65
147
  "test": "vitest run"
66
148
  },
67
- "main": "./dist/index.mjs",
68
- "types": "./dist/index.d.mts"
149
+ "main": "./dist/index.cjs",
150
+ "types": "./dist/index.d.cts",
151
+ "module": "./dist/index.mjs"
69
152
  }