@clivly/core 0.8.0 → 0.9.1

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 (48) hide show
  1. package/README.md +182 -16
  2. package/dist/drizzle.cjs +82 -1
  3. package/dist/drizzle.d.cts +23 -2
  4. package/dist/drizzle.d.mts +23 -2
  5. package/dist/drizzle.mjs +81 -2
  6. package/dist/entity-config-8Fgr6IOH.mjs +666 -0
  7. package/dist/entity-config-CLxI8dVb.d.cts +556 -0
  8. package/dist/entity-config-CLxI8dVb.d.mts +556 -0
  9. package/dist/entity-config-Dh8aEcgj.cjs +779 -0
  10. package/dist/entity-config.cjs +13 -349
  11. package/dist/entity-config.d.cts +2 -295
  12. package/dist/entity-config.d.mts +2 -295
  13. package/dist/entity-config.mjs +2 -339
  14. package/dist/entity-heuristics.cjs +28 -8
  15. package/dist/entity-heuristics.d.cts +2 -12
  16. package/dist/entity-heuristics.d.mts +2 -12
  17. package/dist/entity-heuristics.mjs +28 -8
  18. package/dist/env-file.cjs +59 -0
  19. package/dist/env-file.d.cts +23 -0
  20. package/dist/env-file.d.mts +23 -0
  21. package/dist/env-file.mjs +55 -0
  22. package/dist/index.cjs +83 -2
  23. package/dist/index.d.cts +72 -2
  24. package/dist/index.d.mts +72 -2
  25. package/dist/index.mjs +69 -3
  26. package/dist/integration-state.cjs +242 -0
  27. package/dist/integration-state.d.cts +88 -0
  28. package/dist/integration-state.d.mts +88 -0
  29. package/dist/integration-state.mjs +232 -0
  30. package/dist/mapping-form.d.cts +1 -1
  31. package/dist/mapping-form.d.mts +1 -1
  32. package/dist/mappings-config.cjs +32 -6
  33. package/dist/mappings-config.d.cts +7 -1
  34. package/dist/mappings-config.d.mts +7 -1
  35. package/dist/mappings-config.mjs +32 -6
  36. package/dist/projection-BXBkh7qp.cjs +98 -0
  37. package/dist/projection-C_EMRmZ8.mjs +75 -0
  38. package/dist/sync-engine.cjs +9 -2
  39. package/dist/sync-engine.d.cts +1 -1
  40. package/dist/sync-engine.d.mts +1 -1
  41. package/dist/sync-engine.mjs +9 -2
  42. package/dist/view-compiler-BpNI8Ttw.cjs +299 -0
  43. package/dist/view-compiler-CcqsGxv4.mjs +270 -0
  44. package/dist/view-compiler.cjs +6 -188
  45. package/dist/view-compiler.d.cts +12 -2
  46. package/dist/view-compiler.d.mts +12 -2
  47. package/dist/view-compiler.mjs +2 -185
  48. package/package.json +21 -1
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_entity_config = require("./entity-config.cjs");
2
+ const require_entity_config = require("./entity-config-Dh8aEcgj.cjs");
3
3
  const require_mapping_score = require("./mapping-score.cjs");
4
4
  //#region src/entity-heuristics.ts
5
5
  const TARGET_CONCEPTS = [
@@ -101,7 +101,10 @@ const CONCEPT_FIELDS = {
101
101
  "name",
102
102
  "full_name",
103
103
  "fullname",
104
- "display_name"
104
+ "display_name",
105
+ "first_name",
106
+ "firstname",
107
+ "given_name"
105
108
  ],
106
109
  required: false
107
110
  }, {
@@ -224,12 +227,28 @@ function suggestCursorField(columnKeys) {
224
227
  return null;
225
228
  }
226
229
  const MATERIALIZING = new Set(require_entity_config.MATERIALIZING_CONCEPTS);
230
+ const ENDS_IN_CONSONANT_Y = /[^aeiou]y$/;
231
+ const NEEDS_ES = /(s|x|z|ch|sh)$/;
232
+ const IRREGULAR_PLURALS = {
233
+ person: "people",
234
+ child: "children",
235
+ man: "men",
236
+ woman: "women"
237
+ };
238
+ function pluralize(name) {
239
+ const irregular = IRREGULAR_PLURALS[name];
240
+ if (irregular) return irregular;
241
+ if (ENDS_IN_CONSONANT_Y.test(name)) return `${name.slice(0, -1)}ies`;
242
+ if (NEEDS_ES.test(name)) return `${name}es`;
243
+ return `${name}s`;
244
+ }
227
245
  function matchesConcept(tableName, concept) {
228
246
  const normalized = tableName.toLowerCase();
229
247
  const entry = TABLE_PATTERNS.find((p) => p.concept === concept);
230
248
  if (!entry) return null;
231
- if (entry.names.includes(normalized)) return { exact: true };
232
- if (entry.names.some((name) => normalized.includes(name))) return { exact: false };
249
+ const candidates = [normalized, pluralize(normalized)];
250
+ if (candidates.some((candidate) => entry.names.includes(candidate))) return { exact: true };
251
+ if (entry.names.some((name) => candidates.some((candidate) => candidate.includes(name)))) return { exact: false };
233
252
  return null;
234
253
  }
235
254
  function metaFor(table, column) {
@@ -245,17 +264,18 @@ function scoreConcepts(table) {
245
264
  for (const concept of TARGET_CONCEPTS) {
246
265
  if (!MATERIALIZING.has(concept)) continue;
247
266
  const nameMatch = matchesConcept(table.name, concept);
248
- if (!nameMatch) continue;
267
+ const definingColumns = hasDefiningColumn(concept, table.columns);
268
+ if (!(nameMatch || definingColumns)) continue;
249
269
  let score = 0;
250
270
  const reasons = [];
251
- if (nameMatch.exact) {
271
+ if (nameMatch?.exact) {
252
272
  score += require_mapping_score.W.nameExact;
253
273
  reasons.push(`name matches "${table.name}"`);
254
- } else {
274
+ } else if (nameMatch) {
255
275
  score += require_mapping_score.W.nameSubstring;
256
276
  reasons.push(`name looks like ${concept}`);
257
277
  }
258
- if (hasDefiningColumn(concept, table.columns)) {
278
+ if (definingColumns) {
259
279
  score += require_mapping_score.W.definingColumn;
260
280
  reasons.push(`has the columns a ${concept} needs`);
261
281
  }
@@ -1,3 +1,4 @@
1
+ import { f as DiscoveredColumnMeta } from "./entity-config-CLxI8dVb.cjs";
1
2
  import { Scored } from "./mapping-score.cjs";
2
3
  //#region src/entity-heuristics.d.ts
3
4
  declare const TARGET_CONCEPTS: readonly ["contact", "company", "deal", "activity", "conversation", "note"];
@@ -6,17 +7,6 @@ declare function suggestCursorField(columnKeys: string[]): string | null;
6
7
  declare function matchesConcept(tableName: string, concept: TargetConcept): {
7
8
  exact: boolean;
8
9
  } | null;
9
- interface DiscoveredColumnMeta {
10
- isForeignKey?: boolean;
11
- isPrimaryKey?: boolean;
12
- name: string;
13
- nullable?: boolean;
14
- references?: {
15
- table: string;
16
- column: string;
17
- };
18
- type?: string;
19
- }
20
10
  interface ScoredTable {
21
11
  columns: string[];
22
12
  columnsMeta?: DiscoveredColumnMeta[];
@@ -64,4 +54,4 @@ interface FieldSuggestion {
64
54
  declare function scoreFieldMap(concept: TargetConcept, table: ScoredTable): Scored<FieldSuggestion>[];
65
55
  declare function toFieldMap(scored: Scored<FieldSuggestion>[]): Record<string, string>;
66
56
  //#endregion
67
- export { DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
57
+ export { type DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
@@ -1,3 +1,4 @@
1
+ import { f as DiscoveredColumnMeta } from "./entity-config-CLxI8dVb.mjs";
1
2
  import { Scored } from "./mapping-score.mjs";
2
3
  //#region src/entity-heuristics.d.ts
3
4
  declare const TARGET_CONCEPTS: readonly ["contact", "company", "deal", "activity", "conversation", "note"];
@@ -6,17 +7,6 @@ declare function suggestCursorField(columnKeys: string[]): string | null;
6
7
  declare function matchesConcept(tableName: string, concept: TargetConcept): {
7
8
  exact: boolean;
8
9
  } | null;
9
- interface DiscoveredColumnMeta {
10
- isForeignKey?: boolean;
11
- isPrimaryKey?: boolean;
12
- name: string;
13
- nullable?: boolean;
14
- references?: {
15
- table: string;
16
- column: string;
17
- };
18
- type?: string;
19
- }
20
10
  interface ScoredTable {
21
11
  columns: string[];
22
12
  columnsMeta?: DiscoveredColumnMeta[];
@@ -64,4 +54,4 @@ interface FieldSuggestion {
64
54
  declare function scoreFieldMap(concept: TargetConcept, table: ScoredTable): Scored<FieldSuggestion>[];
65
55
  declare function toFieldMap(scored: Scored<FieldSuggestion>[]): Record<string, string>;
66
56
  //#endregion
67
- export { DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
57
+ export { type DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
@@ -1,4 +1,4 @@
1
- import { MATERIALIZING_CONCEPTS } from "./entity-config.mjs";
1
+ import { a as MATERIALIZING_CONCEPTS } from "./entity-config-8Fgr6IOH.mjs";
2
2
  import { CONCEPT_TIERS, FIELD_TIERS, RELATIONSHIP_TIERS, W, isAmbiguous, isNumericLike, isTextLike, isTimestampLike, tierFor } from "./mapping-score.mjs";
3
3
  //#region src/entity-heuristics.ts
4
4
  const TARGET_CONCEPTS = [
@@ -100,7 +100,10 @@ const CONCEPT_FIELDS = {
100
100
  "name",
101
101
  "full_name",
102
102
  "fullname",
103
- "display_name"
103
+ "display_name",
104
+ "first_name",
105
+ "firstname",
106
+ "given_name"
104
107
  ],
105
108
  required: false
106
109
  }, {
@@ -223,12 +226,28 @@ function suggestCursorField(columnKeys) {
223
226
  return null;
224
227
  }
225
228
  const MATERIALIZING = new Set(MATERIALIZING_CONCEPTS);
229
+ const ENDS_IN_CONSONANT_Y = /[^aeiou]y$/;
230
+ const NEEDS_ES = /(s|x|z|ch|sh)$/;
231
+ const IRREGULAR_PLURALS = {
232
+ person: "people",
233
+ child: "children",
234
+ man: "men",
235
+ woman: "women"
236
+ };
237
+ function pluralize(name) {
238
+ const irregular = IRREGULAR_PLURALS[name];
239
+ if (irregular) return irregular;
240
+ if (ENDS_IN_CONSONANT_Y.test(name)) return `${name.slice(0, -1)}ies`;
241
+ if (NEEDS_ES.test(name)) return `${name}es`;
242
+ return `${name}s`;
243
+ }
226
244
  function matchesConcept(tableName, concept) {
227
245
  const normalized = tableName.toLowerCase();
228
246
  const entry = TABLE_PATTERNS.find((p) => p.concept === concept);
229
247
  if (!entry) return null;
230
- if (entry.names.includes(normalized)) return { exact: true };
231
- if (entry.names.some((name) => normalized.includes(name))) return { exact: false };
248
+ const candidates = [normalized, pluralize(normalized)];
249
+ if (candidates.some((candidate) => entry.names.includes(candidate))) return { exact: true };
250
+ if (entry.names.some((name) => candidates.some((candidate) => candidate.includes(name)))) return { exact: false };
232
251
  return null;
233
252
  }
234
253
  function metaFor(table, column) {
@@ -244,17 +263,18 @@ function scoreConcepts(table) {
244
263
  for (const concept of TARGET_CONCEPTS) {
245
264
  if (!MATERIALIZING.has(concept)) continue;
246
265
  const nameMatch = matchesConcept(table.name, concept);
247
- if (!nameMatch) continue;
266
+ const definingColumns = hasDefiningColumn(concept, table.columns);
267
+ if (!(nameMatch || definingColumns)) continue;
248
268
  let score = 0;
249
269
  const reasons = [];
250
- if (nameMatch.exact) {
270
+ if (nameMatch?.exact) {
251
271
  score += W.nameExact;
252
272
  reasons.push(`name matches "${table.name}"`);
253
- } else {
273
+ } else if (nameMatch) {
254
274
  score += W.nameSubstring;
255
275
  reasons.push(`name looks like ${concept}`);
256
276
  }
257
- if (hasDefiningColumn(concept, table.columns)) {
277
+ if (definingColumns) {
258
278
  score += W.definingColumn;
259
279
  reasons.push(`has the columns a ${concept} needs`);
260
280
  }
@@ -0,0 +1,59 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/env-file.ts
3
+ const ENV_FRAMEWORKS = [
4
+ "next",
5
+ "tanstack-start",
6
+ "sveltekit",
7
+ "remix",
8
+ "nuxt",
9
+ "hono-workers"
10
+ ];
11
+ const ENV_FILES = {
12
+ next: ".env.local",
13
+ "tanstack-start": ".env",
14
+ sveltekit: ".env",
15
+ remix: ".env",
16
+ nuxt: ".env",
17
+ "hono-workers": ".dev.vars"
18
+ };
19
+ /** The conventional env file for a framework. `.env` when we do not know. */
20
+ function envFileFor(framework) {
21
+ return ENV_FILES[normalizeFramework(framework)] ?? ".env";
22
+ }
23
+ const ALIASES = {
24
+ next: "next",
25
+ nextjs: "next",
26
+ "next.js": "next",
27
+ "tanstack-start": "tanstack-start",
28
+ tanstack: "tanstack-start",
29
+ sveltekit: "sveltekit",
30
+ remix: "remix",
31
+ nuxt: "nuxt",
32
+ "hono-workers": "hono-workers",
33
+ hono: "hono-workers",
34
+ workers: "hono-workers"
35
+ };
36
+ /** The canonical id for a framework name, or null when unrecognised. */
37
+ function normalizeFramework(framework) {
38
+ if (!framework) return null;
39
+ return ALIASES[framework.toLowerCase()] ?? null;
40
+ }
41
+ /**
42
+ * Which env file to actually write to.
43
+ *
44
+ * Prefers a file that already holds the key over the conventional one: a
45
+ * project that has been running with credentials in `.env` must not suddenly
46
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
47
+ * stale one still loading. Convention applies to new setups, not to a working
48
+ * one someone already has.
49
+ */
50
+ function resolveEnvFile(input) {
51
+ const conventional = envFileFor(input.framework);
52
+ if (input.existing.includes(conventional)) return conventional;
53
+ return input.existing[0] ?? conventional;
54
+ }
55
+ //#endregion
56
+ exports.ENV_FRAMEWORKS = ENV_FRAMEWORKS;
57
+ exports.envFileFor = envFileFor;
58
+ exports.normalizeFramework = normalizeFramework;
59
+ exports.resolveEnvFile = resolveEnvFile;
@@ -0,0 +1,23 @@
1
+ //#region src/env-file.d.ts
2
+ declare const ENV_FRAMEWORKS: readonly ["next", "tanstack-start", "sveltekit", "remix", "nuxt", "hono-workers"];
3
+ type EnvFramework = (typeof ENV_FRAMEWORKS)[number];
4
+ /** The conventional env file for a framework. `.env` when we do not know. */
5
+ declare function envFileFor(framework: string | null | undefined): string;
6
+ /** The canonical id for a framework name, or null when unrecognised. */
7
+ declare function normalizeFramework(framework: string | null | undefined): EnvFramework | null;
8
+ /**
9
+ * Which env file to actually write to.
10
+ *
11
+ * Prefers a file that already holds the key over the conventional one: a
12
+ * project that has been running with credentials in `.env` must not suddenly
13
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
14
+ * stale one still loading. Convention applies to new setups, not to a working
15
+ * one someone already has.
16
+ */
17
+ declare function resolveEnvFile(input: {
18
+ /** Candidate filenames that already contain the credential, if any. */
19
+ existing: string[];
20
+ framework: string | null | undefined;
21
+ }): string;
22
+ //#endregion
23
+ export { ENV_FRAMEWORKS, EnvFramework, envFileFor, normalizeFramework, resolveEnvFile };
@@ -0,0 +1,23 @@
1
+ //#region src/env-file.d.ts
2
+ declare const ENV_FRAMEWORKS: readonly ["next", "tanstack-start", "sveltekit", "remix", "nuxt", "hono-workers"];
3
+ type EnvFramework = (typeof ENV_FRAMEWORKS)[number];
4
+ /** The conventional env file for a framework. `.env` when we do not know. */
5
+ declare function envFileFor(framework: string | null | undefined): string;
6
+ /** The canonical id for a framework name, or null when unrecognised. */
7
+ declare function normalizeFramework(framework: string | null | undefined): EnvFramework | null;
8
+ /**
9
+ * Which env file to actually write to.
10
+ *
11
+ * Prefers a file that already holds the key over the conventional one: a
12
+ * project that has been running with credentials in `.env` must not suddenly
13
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
14
+ * stale one still loading. Convention applies to new setups, not to a working
15
+ * one someone already has.
16
+ */
17
+ declare function resolveEnvFile(input: {
18
+ /** Candidate filenames that already contain the credential, if any. */
19
+ existing: string[];
20
+ framework: string | null | undefined;
21
+ }): string;
22
+ //#endregion
23
+ export { ENV_FRAMEWORKS, EnvFramework, envFileFor, normalizeFramework, resolveEnvFile };
@@ -0,0 +1,55 @@
1
+ //#region src/env-file.ts
2
+ const ENV_FRAMEWORKS = [
3
+ "next",
4
+ "tanstack-start",
5
+ "sveltekit",
6
+ "remix",
7
+ "nuxt",
8
+ "hono-workers"
9
+ ];
10
+ const ENV_FILES = {
11
+ next: ".env.local",
12
+ "tanstack-start": ".env",
13
+ sveltekit: ".env",
14
+ remix: ".env",
15
+ nuxt: ".env",
16
+ "hono-workers": ".dev.vars"
17
+ };
18
+ /** The conventional env file for a framework. `.env` when we do not know. */
19
+ function envFileFor(framework) {
20
+ return ENV_FILES[normalizeFramework(framework)] ?? ".env";
21
+ }
22
+ const ALIASES = {
23
+ next: "next",
24
+ nextjs: "next",
25
+ "next.js": "next",
26
+ "tanstack-start": "tanstack-start",
27
+ tanstack: "tanstack-start",
28
+ sveltekit: "sveltekit",
29
+ remix: "remix",
30
+ nuxt: "nuxt",
31
+ "hono-workers": "hono-workers",
32
+ hono: "hono-workers",
33
+ workers: "hono-workers"
34
+ };
35
+ /** The canonical id for a framework name, or null when unrecognised. */
36
+ function normalizeFramework(framework) {
37
+ if (!framework) return null;
38
+ return ALIASES[framework.toLowerCase()] ?? null;
39
+ }
40
+ /**
41
+ * Which env file to actually write to.
42
+ *
43
+ * Prefers a file that already holds the key over the conventional one: a
44
+ * project that has been running with credentials in `.env` must not suddenly
45
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
46
+ * stale one still loading. Convention applies to new setups, not to a working
47
+ * one someone already has.
48
+ */
49
+ function resolveEnvFile(input) {
50
+ const conventional = envFileFor(input.framework);
51
+ if (input.existing.includes(conventional)) return conventional;
52
+ return input.existing[0] ?? conventional;
53
+ }
54
+ //#endregion
55
+ export { ENV_FRAMEWORKS, envFileFor, normalizeFramework, resolveEnvFile };
package/dist/index.cjs CHANGED
@@ -1,10 +1,77 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_auth_adapter = require("./auth-adapter.cjs");
3
- const require_entity_config = require("./entity-config.cjs");
3
+ const require_projection = require("./projection-BXBkh7qp.cjs");
4
+ const require_entity_config = require("./entity-config-Dh8aEcgj.cjs");
4
5
  const require_mapping_form = require("./mapping-form.cjs");
5
6
  const require_mappings_config = require("./mappings-config.cjs");
6
- const require_view_compiler = require("./view-compiler.cjs");
7
+ const require_view_compiler = require("./view-compiler-BpNI8Ttw.cjs");
7
8
  const require_sync_engine = require("./sync-engine.cjs");
9
+ //#region src/projection-draft.ts
10
+ function emptyProjectionDraft(baseTable) {
11
+ return {
12
+ baseTable,
13
+ entityKey: "",
14
+ fieldBindings: {},
15
+ identity: { kind: "base_pk" },
16
+ joins: []
17
+ };
18
+ }
19
+ /**
20
+ * The ON conditions implied by a foreign key between the two tables, so the
21
+ * builder can pre-fill a join instead of making the user hand-pick columns.
22
+ * Returns [] when no FK relates them — the user then picks manually.
23
+ */
24
+ function suggestJoinConditions(baseTable, joinTable, schema, joinKey) {
25
+ const join = schema.find((t) => t.name === joinTable);
26
+ const conditions = [];
27
+ for (const column of join?.columnsMeta ?? []) if (column.references?.table === baseTable) conditions.push({
28
+ left: {
29
+ table: joinKey,
30
+ column: column.name
31
+ },
32
+ op: "eq",
33
+ right: {
34
+ table: require_projection.BASE_REF,
35
+ column: column.references.column
36
+ }
37
+ });
38
+ return conditions;
39
+ }
40
+ /** A draft becomes a projection once it has a valid key and ≥1 binding. */
41
+ function draftToProjection(draft) {
42
+ if (!require_projection.PROJECTION_KEY_PATTERN.test(draft.entityKey)) return null;
43
+ if (Object.keys(draft.fieldBindings).length === 0) return null;
44
+ return {
45
+ version: 1,
46
+ kind: "projection",
47
+ entityKey: draft.entityKey,
48
+ baseTable: draft.baseTable,
49
+ joins: draft.joins,
50
+ fieldBindings: draft.fieldBindings,
51
+ identity: draft.identity
52
+ };
53
+ }
54
+ function draftErrors(draft, schema) {
55
+ const projection = draftToProjection(draft);
56
+ if (!projection) return [{
57
+ path: "projection",
58
+ message: "Name the object and map a field."
59
+ }];
60
+ return require_entity_config.validateProjection(projection, schema, "projection");
61
+ }
62
+ /** Per-join fan-out, for the builder's inline cardinality hints. */
63
+ function describeCardinality(draft, schema) {
64
+ const projection = draftToProjection(draft);
65
+ if (!projection) return [];
66
+ const tablesByName = new Map(schema.map((t) => [t.name, t]));
67
+ const fanning = new Set(require_entity_config.fanOutJoins(projection, tablesByName).map((j) => j.key));
68
+ return projection.joins.map((join) => ({
69
+ joinKey: join.key,
70
+ fansOut: fanning.has(join.key)
71
+ }));
72
+ }
73
+ //#endregion
74
+ exports.BASE_REF = require_projection.BASE_REF;
8
75
  exports.CANONICAL_FIELDS = require_entity_config.CANONICAL_FIELDS;
9
76
  exports.CRM_CONCEPTS = require_entity_config.CRM_CONCEPTS;
10
77
  exports.ClivlyConfigError = require_entity_config.ClivlyConfigError;
@@ -13,16 +80,30 @@ exports.MATERIALIZING_CONCEPTS = require_entity_config.MATERIALIZING_CONCEPTS;
13
80
  exports.authCustom = require_auth_adapter.authCustom;
14
81
  exports.buildFilterFromDiscriminator = require_mapping_form.buildFilterFromDiscriminator;
15
82
  exports.buildRelationships = require_mapping_form.buildRelationships;
83
+ exports.columnMetaFor = require_entity_config.columnMetaFor;
16
84
  exports.compileEntityView = require_view_compiler.compileEntityView;
17
85
  exports.compileEntityViews = require_view_compiler.compileEntityViews;
86
+ exports.coversUniqueKey = require_entity_config.coversUniqueKey;
18
87
  exports.defineClivlyConfig = require_entity_config.defineClivlyConfig;
88
+ exports.describeCardinality = describeCardinality;
89
+ exports.draftErrors = draftErrors;
90
+ exports.draftToProjection = draftToProjection;
91
+ exports.emptyProjectionDraft = emptyProjectionDraft;
19
92
  exports.entitiesConfigSchema = require_entity_config.entitiesConfigSchema;
20
93
  exports.explainEntitiesConfig = require_view_compiler.explainEntitiesConfig;
94
+ exports.fanOutJoins = require_entity_config.fanOutJoins;
21
95
  exports.filterSchema = require_entity_config.filterSchema;
96
+ exports.hasRichMeta = require_entity_config.hasRichMeta;
97
+ exports.identityRefs = require_projection.identityRefs;
98
+ exports.joinFansOut = require_entity_config.joinFansOut;
22
99
  exports.mappingsToEntitiesConfig = require_mappings_config.mappingsToEntitiesConfig;
100
+ exports.primaryKeyColumns = require_entity_config.primaryKeyColumns;
101
+ exports.projectionSchema = require_projection.projectionSchema;
23
102
  exports.reconcile = require_sync_engine.reconcile;
24
103
  exports.relationshipSchema = require_entity_config.relationshipSchema;
25
104
  exports.relationshipViaSignature = require_mapping_form.relationshipViaSignature;
26
105
  exports.relationshipsSchema = require_entity_config.relationshipsSchema;
27
106
  exports.runSync = require_sync_engine.runSync;
107
+ exports.suggestJoinConditions = suggestJoinConditions;
28
108
  exports.validateEntitiesConfig = require_entity_config.validateEntitiesConfig;
109
+ exports.validateProjection = require_entity_config.validateProjection;
package/dist/index.d.cts CHANGED
@@ -1,9 +1,79 @@
1
1
  import { Activity, ActivityType, Company, Contact, ContactFilters, ContactStatus, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, CrmRole, Deal, DealStage, Note, RecordSource, Task, TaskEntityType, TaskFilters, TaskPriority, TaskStatus, UpdateContactInput, UpdateDealInput, UpdateTaskInput } from "./types.cjs";
2
2
  import { CRMAdapter } from "./adapter.cjs";
3
3
  import { ClivlyAuthAdapter, ClivlyUser, CrmMembership, MembershipResolver, authCustom } from "./auth-adapter.cjs";
4
- import { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyConfigError, ClivlyEntitiesConfig, ClivlyEntityConfig, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredSchemaTable, FilterExpr, FilterValue, MATERIALIZING_CONCEPTS, MaterializingConcept, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig } from "./entity-config.cjs";
4
+ import { A as ProjectionIdentity, C as filterSchema, D as validateEntitiesConfig, E as relationshipsSchema, F as projectionSchema, M as ProjectionMapping, N as ProjectionRef, O as BASE_REF, P as identityRefs, S as entitiesConfigSchema, T as relationshipSchema, _ as MaterializingConcept, a as ClivlyEntitiesConfig, b as RelationshipsMap, d as CrmConcept, f as DiscoveredColumnMeta, g as MATERIALIZING_CONCEPTS, h as FilterValue, i as ClivlyConfigError, j as ProjectionJoin, k as ProjectionFieldBinding, l as ConfigValidationError, m as FilterExpr, n as CRM_CONCEPTS, p as DiscoveredSchemaTable, s as ClivlyEntityConfig, t as CANONICAL_FIELDS, u as ConfigValidationResult, v as RelationshipSpec, x as defineClivlyConfig, y as RelationshipVia } from "./entity-config-CLxI8dVb.cjs";
5
5
  import { RelationshipCandidate, buildFilterFromDiscriminator, buildRelationships, relationshipViaSignature } from "./mapping-form.cjs";
6
6
  import { EntityMappingRow, mappingsToEntitiesConfig } from "./mappings-config.cjs";
7
7
  import { CompileOptions, CompiledView, DEFAULT_VIEW_PREFIX, ExplainResult, compileEntityView, compileEntityViews, explainEntitiesConfig } from "./view-compiler.cjs";
8
8
  import { EntitySyncResult, MirrorRecord, PersistAction, SourceRow, SyncAction, SyncResult, SyncStore, reconcile, runSync } from "./sync-engine.cjs";
9
- export { type Activity, type ActivityType, CANONICAL_FIELDS, type CRMAdapter, CRM_CONCEPTS, type ClivlyAuthAdapter, ClivlyConfigError, type ClivlyEntitiesConfig, type ClivlyEntityConfig, type ClivlyUser, type Company, type CompileOptions, type CompiledView, type ConfigValidationError, type ConfigValidationResult, type Contact, type ContactFilters, type ContactStatus, type CreateActivityInput, type CreateCompanyInput, type CreateContactInput, type CreateDealInput, type CreateTaskInput, type CrmConcept, type CrmMembership, type CrmRole, DEFAULT_VIEW_PREFIX, type Deal, type DealStage, type DiscoveredSchemaTable, type EntityMappingRow, type EntitySyncResult, type ExplainResult, type FilterExpr, type FilterValue, MATERIALIZING_CONCEPTS, type MaterializingConcept, type MembershipResolver, type MirrorRecord, type Note, type PersistAction, type RecordSource, type RelationshipCandidate, type RelationshipSpec, type RelationshipVia, type RelationshipsMap, type SourceRow, type SyncAction, type SyncResult, type SyncStore, type Task, type TaskEntityType, type TaskFilters, type TaskPriority, type TaskStatus, type UpdateContactInput, type UpdateDealInput, type UpdateTaskInput, authCustom, buildFilterFromDiscriminator, buildRelationships, compileEntityView, compileEntityViews, defineClivlyConfig, entitiesConfigSchema, explainEntitiesConfig, filterSchema, mappingsToEntitiesConfig, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, validateEntitiesConfig };
9
+ //#region src/projection-cardinality.d.ts
10
+ declare function joinFansOut(join: ProjectionJoin, joinTable: DiscoveredSchemaTable): boolean;
11
+ /** Every join in the projection that can multiply rows. */
12
+ declare function fanOutJoins(projection: ProjectionMapping, tablesByName: Map<string, DiscoveredSchemaTable>): ProjectionJoin[];
13
+ //#endregion
14
+ //#region src/projection-draft.d.ts
15
+ /**
16
+ * The builder's in-progress shape.
17
+ *
18
+ * A draft is deliberately looser than a `ProjectionMapping`: it exists while
19
+ * the user is still choosing things, so every field can be empty. All of the
20
+ * builder's rules live here as pure functions, which keeps the React components
21
+ * presentational and lets the rules be tested without a DOM.
22
+ */
23
+ interface ProjectionDraft {
24
+ baseTable: string;
25
+ entityKey: string;
26
+ fieldBindings: Record<string, ProjectionFieldBinding>;
27
+ identity: ProjectionIdentity;
28
+ joins: ProjectionJoin[];
29
+ }
30
+ declare function emptyProjectionDraft(baseTable: string): ProjectionDraft;
31
+ /**
32
+ * The ON conditions implied by a foreign key between the two tables, so the
33
+ * builder can pre-fill a join instead of making the user hand-pick columns.
34
+ * Returns [] when no FK relates them — the user then picks manually.
35
+ */
36
+ declare function suggestJoinConditions(baseTable: string, joinTable: string, schema: DiscoveredSchemaTable[], joinKey: string): ProjectionJoin["on"];
37
+ /** A draft becomes a projection once it has a valid key and ≥1 binding. */
38
+ declare function draftToProjection(draft: ProjectionDraft): ProjectionMapping | null;
39
+ declare function draftErrors(draft: ProjectionDraft, schema: DiscoveredSchemaTable[]): ConfigValidationError[];
40
+ /** Per-join fan-out, for the builder's inline cardinality hints. */
41
+ declare function describeCardinality(draft: ProjectionDraft, schema: DiscoveredSchemaTable[]): Array<{
42
+ fansOut: boolean;
43
+ joinKey: string;
44
+ }>;
45
+ //#endregion
46
+ //#region src/projection-validate.d.ts
47
+ /**
48
+ * Validate a projection against the discovered schema. Returns every error
49
+ * found (not just the first) so a builder UI can show them all at once.
50
+ */
51
+ declare function validateProjection(projection: ProjectionMapping, schema: DiscoveredSchemaTable[], base: string): ConfigValidationError[];
52
+ //#endregion
53
+ //#region src/schema-meta.d.ts
54
+ /**
55
+ * Accessors over a discovered table's schema-v2 metadata.
56
+ *
57
+ * Every helper treats *absent* metadata as **unknown**, never as a negative
58
+ * fact. `coversUniqueKey` returning false on a v1 payload is what makes
59
+ * projection validation fail closed: we cannot prove a join is many-to-one, so
60
+ * we refuse to compile it rather than guess.
61
+ */
62
+ declare function columnMetaFor(table: DiscoveredSchemaTable, column: string): DiscoveredColumnMeta | undefined;
63
+ /**
64
+ * Every primary-key column. More than one entry means a composite PK, which is
65
+ * why `base_pk` identity is rejected for such tables.
66
+ */
67
+ declare function primaryKeyColumns(table: DiscoveredSchemaTable): string[];
68
+ /**
69
+ * Do `columns` contain every column of at least one unique key on `table`?
70
+ *
71
+ * This is the fan-out test. A join whose ON columns cover a unique key of the
72
+ * joined table matches at most one row per base row; one that does not can
73
+ * match many.
74
+ */
75
+ declare function coversUniqueKey(table: DiscoveredSchemaTable, columns: string[]): boolean;
76
+ /** Is this table's payload rich enough to validate a projection against? */
77
+ declare function hasRichMeta(table: DiscoveredSchemaTable): boolean;
78
+ //#endregion
79
+ export { type Activity, type ActivityType, BASE_REF, CANONICAL_FIELDS, type CRMAdapter, CRM_CONCEPTS, type ClivlyAuthAdapter, ClivlyConfigError, type ClivlyEntitiesConfig, type ClivlyEntityConfig, type ClivlyUser, type Company, type CompileOptions, type CompiledView, type ConfigValidationError, type ConfigValidationResult, type Contact, type ContactFilters, type ContactStatus, type CreateActivityInput, type CreateCompanyInput, type CreateContactInput, type CreateDealInput, type CreateTaskInput, type CrmConcept, type CrmMembership, type CrmRole, DEFAULT_VIEW_PREFIX, type Deal, type DealStage, type DiscoveredColumnMeta, type DiscoveredSchemaTable, type EntityMappingRow, type EntitySyncResult, type ExplainResult, type FilterExpr, type FilterValue, MATERIALIZING_CONCEPTS, type MaterializingConcept, type MembershipResolver, type MirrorRecord, type Note, type PersistAction, type ProjectionDraft, type ProjectionFieldBinding, type ProjectionIdentity, type ProjectionJoin, type ProjectionMapping, type ProjectionRef, type RecordSource, type RelationshipCandidate, type RelationshipSpec, type RelationshipVia, type RelationshipsMap, type SourceRow, type SyncAction, type SyncResult, type SyncStore, type Task, type TaskEntityType, type TaskFilters, type TaskPriority, type TaskStatus, type UpdateContactInput, type UpdateDealInput, type UpdateTaskInput, authCustom, buildFilterFromDiscriminator, buildRelationships, columnMetaFor, compileEntityView, compileEntityViews, coversUniqueKey, defineClivlyConfig, describeCardinality, draftErrors, draftToProjection, emptyProjectionDraft, entitiesConfigSchema, explainEntitiesConfig, fanOutJoins, filterSchema, hasRichMeta, identityRefs, joinFansOut, mappingsToEntitiesConfig, primaryKeyColumns, projectionSchema, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, suggestJoinConditions, validateEntitiesConfig, validateProjection };
package/dist/index.d.mts CHANGED
@@ -1,9 +1,79 @@
1
1
  import { Activity, ActivityType, Company, Contact, ContactFilters, ContactStatus, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, CrmRole, Deal, DealStage, Note, RecordSource, Task, TaskEntityType, TaskFilters, TaskPriority, TaskStatus, UpdateContactInput, UpdateDealInput, UpdateTaskInput } from "./types.mjs";
2
2
  import { CRMAdapter } from "./adapter.mjs";
3
3
  import { ClivlyAuthAdapter, ClivlyUser, CrmMembership, MembershipResolver, authCustom } from "./auth-adapter.mjs";
4
- import { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyConfigError, ClivlyEntitiesConfig, ClivlyEntityConfig, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredSchemaTable, FilterExpr, FilterValue, MATERIALIZING_CONCEPTS, MaterializingConcept, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig } from "./entity-config.mjs";
4
+ import { A as ProjectionIdentity, C as filterSchema, D as validateEntitiesConfig, E as relationshipsSchema, F as projectionSchema, M as ProjectionMapping, N as ProjectionRef, O as BASE_REF, P as identityRefs, S as entitiesConfigSchema, T as relationshipSchema, _ as MaterializingConcept, a as ClivlyEntitiesConfig, b as RelationshipsMap, d as CrmConcept, f as DiscoveredColumnMeta, g as MATERIALIZING_CONCEPTS, h as FilterValue, i as ClivlyConfigError, j as ProjectionJoin, k as ProjectionFieldBinding, l as ConfigValidationError, m as FilterExpr, n as CRM_CONCEPTS, p as DiscoveredSchemaTable, s as ClivlyEntityConfig, t as CANONICAL_FIELDS, u as ConfigValidationResult, v as RelationshipSpec, x as defineClivlyConfig, y as RelationshipVia } from "./entity-config-CLxI8dVb.mjs";
5
5
  import { RelationshipCandidate, buildFilterFromDiscriminator, buildRelationships, relationshipViaSignature } from "./mapping-form.mjs";
6
6
  import { EntityMappingRow, mappingsToEntitiesConfig } from "./mappings-config.mjs";
7
7
  import { CompileOptions, CompiledView, DEFAULT_VIEW_PREFIX, ExplainResult, compileEntityView, compileEntityViews, explainEntitiesConfig } from "./view-compiler.mjs";
8
8
  import { EntitySyncResult, MirrorRecord, PersistAction, SourceRow, SyncAction, SyncResult, SyncStore, reconcile, runSync } from "./sync-engine.mjs";
9
- export { type Activity, type ActivityType, CANONICAL_FIELDS, type CRMAdapter, CRM_CONCEPTS, type ClivlyAuthAdapter, ClivlyConfigError, type ClivlyEntitiesConfig, type ClivlyEntityConfig, type ClivlyUser, type Company, type CompileOptions, type CompiledView, type ConfigValidationError, type ConfigValidationResult, type Contact, type ContactFilters, type ContactStatus, type CreateActivityInput, type CreateCompanyInput, type CreateContactInput, type CreateDealInput, type CreateTaskInput, type CrmConcept, type CrmMembership, type CrmRole, DEFAULT_VIEW_PREFIX, type Deal, type DealStage, type DiscoveredSchemaTable, type EntityMappingRow, type EntitySyncResult, type ExplainResult, type FilterExpr, type FilterValue, MATERIALIZING_CONCEPTS, type MaterializingConcept, type MembershipResolver, type MirrorRecord, type Note, type PersistAction, type RecordSource, type RelationshipCandidate, type RelationshipSpec, type RelationshipVia, type RelationshipsMap, type SourceRow, type SyncAction, type SyncResult, type SyncStore, type Task, type TaskEntityType, type TaskFilters, type TaskPriority, type TaskStatus, type UpdateContactInput, type UpdateDealInput, type UpdateTaskInput, authCustom, buildFilterFromDiscriminator, buildRelationships, compileEntityView, compileEntityViews, defineClivlyConfig, entitiesConfigSchema, explainEntitiesConfig, filterSchema, mappingsToEntitiesConfig, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, validateEntitiesConfig };
9
+ //#region src/projection-cardinality.d.ts
10
+ declare function joinFansOut(join: ProjectionJoin, joinTable: DiscoveredSchemaTable): boolean;
11
+ /** Every join in the projection that can multiply rows. */
12
+ declare function fanOutJoins(projection: ProjectionMapping, tablesByName: Map<string, DiscoveredSchemaTable>): ProjectionJoin[];
13
+ //#endregion
14
+ //#region src/projection-draft.d.ts
15
+ /**
16
+ * The builder's in-progress shape.
17
+ *
18
+ * A draft is deliberately looser than a `ProjectionMapping`: it exists while
19
+ * the user is still choosing things, so every field can be empty. All of the
20
+ * builder's rules live here as pure functions, which keeps the React components
21
+ * presentational and lets the rules be tested without a DOM.
22
+ */
23
+ interface ProjectionDraft {
24
+ baseTable: string;
25
+ entityKey: string;
26
+ fieldBindings: Record<string, ProjectionFieldBinding>;
27
+ identity: ProjectionIdentity;
28
+ joins: ProjectionJoin[];
29
+ }
30
+ declare function emptyProjectionDraft(baseTable: string): ProjectionDraft;
31
+ /**
32
+ * The ON conditions implied by a foreign key between the two tables, so the
33
+ * builder can pre-fill a join instead of making the user hand-pick columns.
34
+ * Returns [] when no FK relates them — the user then picks manually.
35
+ */
36
+ declare function suggestJoinConditions(baseTable: string, joinTable: string, schema: DiscoveredSchemaTable[], joinKey: string): ProjectionJoin["on"];
37
+ /** A draft becomes a projection once it has a valid key and ≥1 binding. */
38
+ declare function draftToProjection(draft: ProjectionDraft): ProjectionMapping | null;
39
+ declare function draftErrors(draft: ProjectionDraft, schema: DiscoveredSchemaTable[]): ConfigValidationError[];
40
+ /** Per-join fan-out, for the builder's inline cardinality hints. */
41
+ declare function describeCardinality(draft: ProjectionDraft, schema: DiscoveredSchemaTable[]): Array<{
42
+ fansOut: boolean;
43
+ joinKey: string;
44
+ }>;
45
+ //#endregion
46
+ //#region src/projection-validate.d.ts
47
+ /**
48
+ * Validate a projection against the discovered schema. Returns every error
49
+ * found (not just the first) so a builder UI can show them all at once.
50
+ */
51
+ declare function validateProjection(projection: ProjectionMapping, schema: DiscoveredSchemaTable[], base: string): ConfigValidationError[];
52
+ //#endregion
53
+ //#region src/schema-meta.d.ts
54
+ /**
55
+ * Accessors over a discovered table's schema-v2 metadata.
56
+ *
57
+ * Every helper treats *absent* metadata as **unknown**, never as a negative
58
+ * fact. `coversUniqueKey` returning false on a v1 payload is what makes
59
+ * projection validation fail closed: we cannot prove a join is many-to-one, so
60
+ * we refuse to compile it rather than guess.
61
+ */
62
+ declare function columnMetaFor(table: DiscoveredSchemaTable, column: string): DiscoveredColumnMeta | undefined;
63
+ /**
64
+ * Every primary-key column. More than one entry means a composite PK, which is
65
+ * why `base_pk` identity is rejected for such tables.
66
+ */
67
+ declare function primaryKeyColumns(table: DiscoveredSchemaTable): string[];
68
+ /**
69
+ * Do `columns` contain every column of at least one unique key on `table`?
70
+ *
71
+ * This is the fan-out test. A join whose ON columns cover a unique key of the
72
+ * joined table matches at most one row per base row; one that does not can
73
+ * match many.
74
+ */
75
+ declare function coversUniqueKey(table: DiscoveredSchemaTable, columns: string[]): boolean;
76
+ /** Is this table's payload rich enough to validate a projection against? */
77
+ declare function hasRichMeta(table: DiscoveredSchemaTable): boolean;
78
+ //#endregion
79
+ export { type Activity, type ActivityType, BASE_REF, CANONICAL_FIELDS, type CRMAdapter, CRM_CONCEPTS, type ClivlyAuthAdapter, ClivlyConfigError, type ClivlyEntitiesConfig, type ClivlyEntityConfig, type ClivlyUser, type Company, type CompileOptions, type CompiledView, type ConfigValidationError, type ConfigValidationResult, type Contact, type ContactFilters, type ContactStatus, type CreateActivityInput, type CreateCompanyInput, type CreateContactInput, type CreateDealInput, type CreateTaskInput, type CrmConcept, type CrmMembership, type CrmRole, DEFAULT_VIEW_PREFIX, type Deal, type DealStage, type DiscoveredColumnMeta, type DiscoveredSchemaTable, type EntityMappingRow, type EntitySyncResult, type ExplainResult, type FilterExpr, type FilterValue, MATERIALIZING_CONCEPTS, type MaterializingConcept, type MembershipResolver, type MirrorRecord, type Note, type PersistAction, type ProjectionDraft, type ProjectionFieldBinding, type ProjectionIdentity, type ProjectionJoin, type ProjectionMapping, type ProjectionRef, type RecordSource, type RelationshipCandidate, type RelationshipSpec, type RelationshipVia, type RelationshipsMap, type SourceRow, type SyncAction, type SyncResult, type SyncStore, type Task, type TaskEntityType, type TaskFilters, type TaskPriority, type TaskStatus, type UpdateContactInput, type UpdateDealInput, type UpdateTaskInput, authCustom, buildFilterFromDiscriminator, buildRelationships, columnMetaFor, compileEntityView, compileEntityViews, coversUniqueKey, defineClivlyConfig, describeCardinality, draftErrors, draftToProjection, emptyProjectionDraft, entitiesConfigSchema, explainEntitiesConfig, fanOutJoins, filterSchema, hasRichMeta, identityRefs, joinFansOut, mappingsToEntitiesConfig, primaryKeyColumns, projectionSchema, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, suggestJoinConditions, validateEntitiesConfig, validateProjection };