monorise 1.14.1 → 1.15.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.
- package/dist/base/index.d.ts +126 -1
- package/dist/base/index.js +168 -1
- package/dist/base/index.js.map +1 -1
- package/dist/cli/cli.js +224 -117
- package/dist/cli/cli.js.map +1 -1
- package/dist/core/index.d.ts +108 -19
- package/dist/core/index.js +512 -66
- package/dist/core/index.js.map +1 -1
- package/dist/index.d.ts +18 -0
- package/dist/react/actions/core.action.d.ts.map +1 -1
- package/dist/react/actions/websocket.action.d.ts.map +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +110 -22
- package/dist/react/index.js.map +1 -1
- package/dist/react/lib/search.d.ts +29 -0
- package/dist/react/lib/search.d.ts.map +1 -0
- package/dist/react/services/core.service.d.ts.map +1 -1
- package/dist/react/types/monorise.type.d.ts +1 -0
- package/dist/react/types/monorise.type.d.ts.map +1 -1
- package/dist/sst/components/monorise-core.d.ts +1 -0
- package/dist/sst/components/monorise-core.d.ts.map +1 -1
- package/dist/sst/index.js +66 -1
- package/dist/sst/index.js.map +1 -1
- package/package.json +1 -1
package/dist/base/index.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ declare const createEntityConfig: <T extends Entity, B extends z.ZodRawShape, C
|
|
|
26
26
|
baseSchema: z.ZodObject<B, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<B>, any> extends infer T_33 ? { [k_6 in keyof T_33]: T_33[k_6]; } : never, z.baseObjectInputType<B> extends infer T_34 ? { [k_7 in keyof T_34]: T_34[k_7]; } : never>;
|
|
27
27
|
createSchema?: CO | undefined;
|
|
28
28
|
searchableFields?: (keyof B)[] | undefined;
|
|
29
|
+
search?: SearchConfig<keyof B> | undefined;
|
|
29
30
|
uniqueFields?: (keyof B)[] | undefined;
|
|
30
31
|
mutual?: {
|
|
31
32
|
subscribes?: {
|
|
@@ -121,6 +122,41 @@ declare enum Entity {
|
|
|
121
122
|
interface EntitySchemaMap {
|
|
122
123
|
[key: string]: Record<string, any>;
|
|
123
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* @description How a field's value is matched. `words`: split on spaces and
|
|
127
|
+
* symbols, and each word is matched from its start ("jo" finds "John").
|
|
128
|
+
*/
|
|
129
|
+
type SearchMatch = 'words';
|
|
130
|
+
/**
|
|
131
|
+
* @description Search settings shared by an entity's `search` config and the
|
|
132
|
+
* `search` key of `monorise.config.ts`. An entity's value replaces the
|
|
133
|
+
* global one.
|
|
134
|
+
*/
|
|
135
|
+
interface SearchSettings {
|
|
136
|
+
/**
|
|
137
|
+
* @description Most words indexed per entity, counted across `fields` in
|
|
138
|
+
* order after duplicates and `ignoreWords` are dropped. Words past it can't
|
|
139
|
+
* be searched. Each word is a copy of the entity that every update of the
|
|
140
|
+
* entity rewrites. Defaults to `DEFAULT_MAX_WORDS` (8).
|
|
141
|
+
*/
|
|
142
|
+
maxWords?: number;
|
|
143
|
+
/**
|
|
144
|
+
* @description Words that are never indexed and are skipped in queries
|
|
145
|
+
* (also known as stop words). Replaces the default list: spread
|
|
146
|
+
* `DEFAULT_IGNORE_WORDS` to extend it, or pass `[]` to ignore nothing.
|
|
147
|
+
*/
|
|
148
|
+
ignoreWords?: readonly string[];
|
|
149
|
+
}
|
|
150
|
+
interface SearchConfig<K extends PropertyKey = string> extends SearchSettings {
|
|
151
|
+
/**
|
|
152
|
+
* @description Fields to index, most-searched first: earlier fields fill
|
|
153
|
+
* `maxWords` first.
|
|
154
|
+
*/
|
|
155
|
+
fields: {
|
|
156
|
+
field: K;
|
|
157
|
+
match?: SearchMatch;
|
|
158
|
+
}[];
|
|
159
|
+
}
|
|
124
160
|
/**
|
|
125
161
|
* @description Configuration for a mutual relationship between two entities.
|
|
126
162
|
* Defines the schema for mutualData validation. Define once, reference from both entity configs.
|
|
@@ -284,7 +320,28 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
|
|
|
284
320
|
* @description Minimal schema required to create an entity
|
|
285
321
|
*/
|
|
286
322
|
createSchema?: CO;
|
|
323
|
+
/**
|
|
324
|
+
* @description (Optional) Fields `?query=` matches against, by scanning every
|
|
325
|
+
* entity of this type. Use `search` instead to look matches up by word
|
|
326
|
+
* without the scan. Can't be combined with `search`.
|
|
327
|
+
*/
|
|
287
328
|
searchableFields?: (keyof B)[];
|
|
329
|
+
/**
|
|
330
|
+
* @description (Optional) Index these fields by word, so `?query=` reads
|
|
331
|
+
* only the entities that contain the words searched for. Can't be combined
|
|
332
|
+
* with `searchableFields`.
|
|
333
|
+
*
|
|
334
|
+
* `maxWords` and `ignoreWords` fall back to the `search` settings in
|
|
335
|
+
* `monorise.config.ts`, then to the built-in defaults.
|
|
336
|
+
*
|
|
337
|
+
* @example
|
|
338
|
+
* ```ts
|
|
339
|
+
* search: {
|
|
340
|
+
* fields: [{ field: 'displayName' }, { field: 'email' }],
|
|
341
|
+
* },
|
|
342
|
+
* ```
|
|
343
|
+
*/
|
|
344
|
+
search?: SearchConfig<keyof B>;
|
|
288
345
|
uniqueFields?: (keyof B)[];
|
|
289
346
|
/**
|
|
290
347
|
* @description Define mutual relationship of this entity with other entities
|
|
@@ -590,4 +647,72 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
|
|
|
590
647
|
allowLegacyWhere?: boolean;
|
|
591
648
|
}
|
|
592
649
|
|
|
593
|
-
|
|
650
|
+
declare const DEFAULT_MAX_WORDS = 8;
|
|
651
|
+
/**
|
|
652
|
+
* @description Words ignored unless an entity or `monorise.config.ts` sets
|
|
653
|
+
* its own list. Deliberately short: an ignored word can never be found on its
|
|
654
|
+
* own, so words that are also names ("an", "will", "may") are left out.
|
|
655
|
+
*/
|
|
656
|
+
declare const DEFAULT_IGNORE_WORDS: readonly string[];
|
|
657
|
+
type ResolvedSearchConfig = {
|
|
658
|
+
fields: {
|
|
659
|
+
field: string;
|
|
660
|
+
match: SearchMatch;
|
|
661
|
+
}[];
|
|
662
|
+
maxWords: number;
|
|
663
|
+
ignoreWords: string[];
|
|
664
|
+
};
|
|
665
|
+
/**
|
|
666
|
+
* @description Lowercases and strips accents, so "José" and "jose" match.
|
|
667
|
+
*/
|
|
668
|
+
declare function foldText(text: string): string;
|
|
669
|
+
/**
|
|
670
|
+
* @description Splits on anything that isn't a letter or digit:
|
|
671
|
+
* "example@mail.com" becomes ["example", "mail", "com"].
|
|
672
|
+
*/
|
|
673
|
+
declare function splitWords(text: string): string[];
|
|
674
|
+
/**
|
|
675
|
+
* @description An entity's `search` config with the `monorise.config.ts`
|
|
676
|
+
* settings and built-in defaults filled in.
|
|
677
|
+
*/
|
|
678
|
+
declare function resolveSearchConfig(search: SearchConfig<PropertyKey>, defaults?: SearchSettings): ResolvedSearchConfig;
|
|
679
|
+
/**
|
|
680
|
+
* @description Throws on settings the index can't use. `where` names the
|
|
681
|
+
* config in the message.
|
|
682
|
+
*/
|
|
683
|
+
declare function validateSearchSettings(settings: SearchSettings, where: string): void;
|
|
684
|
+
/**
|
|
685
|
+
* @description Changes whenever the words an entity is indexed by would.
|
|
686
|
+
* Only used to notice that, so it doesn't need to be cryptographic (cyrb53).
|
|
687
|
+
*/
|
|
688
|
+
declare function searchConfigHash(config: ResolvedSearchConfig): string;
|
|
689
|
+
/**
|
|
690
|
+
* @description The words an entity can be found by: fields in config order,
|
|
691
|
+
* without one-letter words, ignored words and duplicates, up to `maxWords`.
|
|
692
|
+
* Writing the index and checking a match both use this, so a word past the
|
|
693
|
+
* cap is never found, whichever word a query is looked up by.
|
|
694
|
+
*/
|
|
695
|
+
declare function indexedWords(data: Record<string, unknown> | undefined, config: ResolvedSearchConfig): string[];
|
|
696
|
+
type SearchTerm = {
|
|
697
|
+
/** Each must be the start of one of the entity's indexed words. */
|
|
698
|
+
words: string[];
|
|
699
|
+
/** Must also appear as typed in one field: quoted, or joined by symbols. */
|
|
700
|
+
phrase?: string;
|
|
701
|
+
};
|
|
702
|
+
type SearchPlan = {
|
|
703
|
+
/** The word whose index rows are read. Without one, nothing matches. */
|
|
704
|
+
anchor?: string;
|
|
705
|
+
terms: SearchTerm[];
|
|
706
|
+
};
|
|
707
|
+
/**
|
|
708
|
+
* @description Parses a query. Plain words match from the start of a word,
|
|
709
|
+
* in any order. Quoted text and text joined by symbols ("example@mail.com")
|
|
710
|
+
* must also appear exactly. The anchor is the longest word.
|
|
711
|
+
*/
|
|
712
|
+
declare function planSearch(query: string, ignoreWords: readonly string[]): SearchPlan;
|
|
713
|
+
/**
|
|
714
|
+
* @description Whether an entity's data matches a planned query.
|
|
715
|
+
*/
|
|
716
|
+
declare function matchesSearch(data: Record<string, unknown> | undefined, plan: SearchPlan, config: ResolvedSearchConfig): boolean;
|
|
717
|
+
|
|
718
|
+
export { type AdjustmentCondition, type AdjustmentConditionFn, type CreatedEntity, DEFAULT_IGNORE_WORDS, DEFAULT_MAX_WORDS, type DraftEntity, Entity, type EntitySchemaMap, type MonoriseEntityConfig, type MutualConfig, type MutualConfigInput, type NumericFields, type ResolvedSearchConfig, type SearchConfig, type SearchMatch, type SearchPlan, type SearchSettings, type SearchTerm, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, createEntityConfig, createMutualConfig, foldText, indexedWords, matchesSearch, planSearch, resolveEffectiveMutualSchema, resolveSearchConfig, searchConfigHash, splitWords, validateSearchSettings };
|
package/dist/base/index.js
CHANGED
|
@@ -25,6 +25,144 @@ var Entity = /* @__PURE__ */ ((Entity2) => {
|
|
|
25
25
|
|
|
26
26
|
// utils/index.ts
|
|
27
27
|
import { z } from "zod";
|
|
28
|
+
|
|
29
|
+
// utils/search.ts
|
|
30
|
+
var DEFAULT_MAX_WORDS = 8;
|
|
31
|
+
var DEFAULT_IGNORE_WORDS = [
|
|
32
|
+
"the",
|
|
33
|
+
"and",
|
|
34
|
+
"of",
|
|
35
|
+
"in",
|
|
36
|
+
"to",
|
|
37
|
+
"for",
|
|
38
|
+
"with",
|
|
39
|
+
"on",
|
|
40
|
+
"at",
|
|
41
|
+
"by",
|
|
42
|
+
"from",
|
|
43
|
+
"or",
|
|
44
|
+
"is",
|
|
45
|
+
"are",
|
|
46
|
+
"was",
|
|
47
|
+
"be",
|
|
48
|
+
"as",
|
|
49
|
+
"it",
|
|
50
|
+
"this",
|
|
51
|
+
"that"
|
|
52
|
+
];
|
|
53
|
+
var MIN_WORD_LENGTH = 2;
|
|
54
|
+
var NON_WORD = /[^\p{L}\p{N}]+/u;
|
|
55
|
+
var MARKS = new RegExp("\\p{M}", "gu");
|
|
56
|
+
function foldText(text) {
|
|
57
|
+
return text.normalize("NFKD").replace(MARKS, "").toLowerCase();
|
|
58
|
+
}
|
|
59
|
+
function splitWords(text) {
|
|
60
|
+
return foldText(text).split(NON_WORD).filter(Boolean);
|
|
61
|
+
}
|
|
62
|
+
var collapseSpaces = (text) => text.trim().replace(/\s+/g, " ");
|
|
63
|
+
function resolveSearchConfig(search, defaults) {
|
|
64
|
+
var _a, _b, _c, _d;
|
|
65
|
+
const ignoreWords = (_b = (_a = search.ignoreWords) != null ? _a : defaults == null ? void 0 : defaults.ignoreWords) != null ? _b : DEFAULT_IGNORE_WORDS;
|
|
66
|
+
return {
|
|
67
|
+
fields: search.fields.map(({ field, match }) => ({
|
|
68
|
+
field: String(field),
|
|
69
|
+
match: match != null ? match : "words"
|
|
70
|
+
})),
|
|
71
|
+
maxWords: (_d = (_c = search.maxWords) != null ? _c : defaults == null ? void 0 : defaults.maxWords) != null ? _d : DEFAULT_MAX_WORDS,
|
|
72
|
+
ignoreWords: [...new Set(ignoreWords.map(foldText))].sort()
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function validateSearchSettings(settings, where) {
|
|
76
|
+
const { maxWords, ignoreWords } = settings;
|
|
77
|
+
if (maxWords !== void 0 && (!Number.isInteger(maxWords) || maxWords < 1)) {
|
|
78
|
+
throw new Error(`${where}: 'search.maxWords' must be a positive integer.`);
|
|
79
|
+
}
|
|
80
|
+
if (ignoreWords !== void 0 && (!Array.isArray(ignoreWords) || ignoreWords.some((word) => typeof word !== "string"))) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`${where}: 'search.ignoreWords' must be an array of strings.`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function searchConfigHash(config) {
|
|
87
|
+
const input = JSON.stringify(config);
|
|
88
|
+
let h1 = 3735928559;
|
|
89
|
+
let h2 = 1103547991;
|
|
90
|
+
for (let i = 0; i < input.length; i++) {
|
|
91
|
+
const char = input.charCodeAt(i);
|
|
92
|
+
h1 = Math.imul(h1 ^ char, 2654435761);
|
|
93
|
+
h2 = Math.imul(h2 ^ char, 1597334677);
|
|
94
|
+
}
|
|
95
|
+
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
|
|
96
|
+
h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
97
|
+
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
|
|
98
|
+
h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
99
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
|
|
100
|
+
}
|
|
101
|
+
function fieldValues(data, field) {
|
|
102
|
+
const value = data == null ? void 0 : data[field];
|
|
103
|
+
const values = Array.isArray(value) ? value : [value];
|
|
104
|
+
return values.filter((v) => typeof v === "string" || typeof v === "number").map(String);
|
|
105
|
+
}
|
|
106
|
+
function indexedWords(data, config) {
|
|
107
|
+
const ignore = new Set(config.ignoreWords);
|
|
108
|
+
const words = /* @__PURE__ */ new Set();
|
|
109
|
+
for (const { field } of config.fields) {
|
|
110
|
+
for (const value of fieldValues(data, field)) {
|
|
111
|
+
for (const word of splitWords(value)) {
|
|
112
|
+
if (word.length < MIN_WORD_LENGTH || ignore.has(word)) continue;
|
|
113
|
+
words.add(word);
|
|
114
|
+
if (words.size === config.maxWords) return [...words];
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return [...words];
|
|
119
|
+
}
|
|
120
|
+
function planSearch(query, ignoreWords) {
|
|
121
|
+
var _a;
|
|
122
|
+
const ignore = new Set(ignoreWords);
|
|
123
|
+
const parsed = [];
|
|
124
|
+
const termPattern = /"([^"]+)"|(\S+)/g;
|
|
125
|
+
for (let match = termPattern.exec(query); match; match = termPattern.exec(query)) {
|
|
126
|
+
parsed.push({ text: (_a = match[1]) != null ? _a : match[2], quoted: match[1] !== void 0 });
|
|
127
|
+
}
|
|
128
|
+
const terms = [];
|
|
129
|
+
let trailing;
|
|
130
|
+
parsed.forEach(({ text, quoted }, i) => {
|
|
131
|
+
var _a2, _b;
|
|
132
|
+
const parts = splitWords(text);
|
|
133
|
+
const words = parts.filter(
|
|
134
|
+
(word) => word.length >= MIN_WORD_LENGTH && !ignore.has(word)
|
|
135
|
+
);
|
|
136
|
+
if (quoted || parts.length > 1) {
|
|
137
|
+
terms.push({ words, phrase: collapseSpaces(foldText(text)) });
|
|
138
|
+
} else if (words.length) {
|
|
139
|
+
terms.push({ words });
|
|
140
|
+
} else if (i === parsed.length - 1 && ((_b = (_a2 = parts[0]) == null ? void 0 : _a2.length) != null ? _b : 0) >= MIN_WORD_LENGTH) {
|
|
141
|
+
trailing = parts[0];
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
const required = terms.flatMap((term) => term.words);
|
|
145
|
+
if (!required.length && trailing) {
|
|
146
|
+
return { anchor: trailing, terms: [...terms, { words: [trailing] }] };
|
|
147
|
+
}
|
|
148
|
+
const anchor = required.reduce(
|
|
149
|
+
(longest, word) => !longest || word.length > longest.length ? word : longest,
|
|
150
|
+
void 0
|
|
151
|
+
);
|
|
152
|
+
return { anchor, terms };
|
|
153
|
+
}
|
|
154
|
+
function matchesSearch(data, plan, config) {
|
|
155
|
+
if (!plan.anchor) return false;
|
|
156
|
+
const words = indexedWords(data, config);
|
|
157
|
+
const values = config.fields.flatMap(
|
|
158
|
+
({ field }) => fieldValues(data, field).map((value) => collapseSpaces(foldText(value)))
|
|
159
|
+
);
|
|
160
|
+
return plan.terms.every(
|
|
161
|
+
({ words: termWords, phrase }) => termWords.every((word) => words.some((w) => w.startsWith(word))) && (!phrase || values.some((value) => value.includes(phrase)))
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// utils/index.ts
|
|
28
166
|
function resolveEffectiveMutualSchema(mutualSchema, createMutualSchema) {
|
|
29
167
|
if (!createMutualSchema) return mutualSchema;
|
|
30
168
|
if (!mutualSchema) return createMutualSchema;
|
|
@@ -39,6 +177,25 @@ function makeSchema(config, effectiveMutualSchema) {
|
|
|
39
177
|
return finalSchema;
|
|
40
178
|
}
|
|
41
179
|
var createEntityConfig = (config) => {
|
|
180
|
+
var _a;
|
|
181
|
+
if (config.search) {
|
|
182
|
+
if (config.searchableFields) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
`${config.name}: 'search' and 'searchableFields' can't both be set. 'searchableFields' scans every entity on each search; 'search' looks matches up by word. Keep one.`
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
if (!((_a = config.search.fields) == null ? void 0 : _a.length)) {
|
|
188
|
+
throw new Error(`${config.name}: 'search.fields' needs at least one field.`);
|
|
189
|
+
}
|
|
190
|
+
for (const { field, match } of config.search.fields) {
|
|
191
|
+
if (match !== void 0 && match !== "words") {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`${config.name}: 'search.fields' entry '${String(field)}' has an unknown match '${match}'. Supported: 'words'.`
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
validateSearchSettings(config.search, String(config.name));
|
|
198
|
+
}
|
|
42
199
|
const { mutualSchema, createMutualSchema } = config.mutual || {};
|
|
43
200
|
const effectiveMutualSchema = resolveEffectiveMutualSchema(
|
|
44
201
|
mutualSchema,
|
|
@@ -78,9 +235,19 @@ var createMutualConfig = (config) => {
|
|
|
78
235
|
});
|
|
79
236
|
};
|
|
80
237
|
export {
|
|
238
|
+
DEFAULT_IGNORE_WORDS,
|
|
239
|
+
DEFAULT_MAX_WORDS,
|
|
81
240
|
Entity,
|
|
82
241
|
createEntityConfig,
|
|
83
242
|
createMutualConfig,
|
|
84
|
-
|
|
243
|
+
foldText,
|
|
244
|
+
indexedWords,
|
|
245
|
+
matchesSearch,
|
|
246
|
+
planSearch,
|
|
247
|
+
resolveEffectiveMutualSchema,
|
|
248
|
+
resolveSearchConfig,
|
|
249
|
+
searchConfigHash,
|
|
250
|
+
splitWords,
|
|
251
|
+
validateSearchSettings
|
|
85
252
|
};
|
|
86
253
|
//# sourceMappingURL=index.js.map
|
package/dist/base/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../types/monorise.type.ts","../utils/index.ts"],"sourcesContent":["import type { z } from 'zod';\nimport type { createEntityConfig } from '../utils';\nimport type { WhereConditions } from './conditions.type';\n\nexport enum Entity {}\n\nexport interface EntitySchemaMap {\n [key: string]: Record<string, any>;\n}\n\n/**\n * @description Configuration for a mutual relationship between two entities.\n * Defines the schema for mutualData validation. Define once, reference from both entity configs.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * mutualDataSchema: z.object({\n * role: z.enum(['student', 'auditor']),\n * enrolledAt: z.string().datetime(),\n * }),\n * });\n * ```\n */\n/**\n * @description The shape `createMutualConfig(...)` is CALLED with — looser than the resolved\n * `MutualConfig` it returns. `mutualDataSchema` is optional here (and mutually exclusive with\n * `asEntity`) because `createMutualConfig` resolves it before returning: every OTHER consumer in\n * this codebase (`mutualFields[key].mutual`, `MutualService`, the processors) reads the resolved\n * `MutualConfig` type below, where `mutualDataSchema` stays REQUIRED — the same \"loose input,\n * strict resolved output\" split `createEntityConfig`/`MonoriseEntityConfig` already use for\n * `finalSchema`/`effectiveMutualSchema`. Import this type only if you're writing something that\n * itself calls `createMutualConfig`; every other call site should keep using `MutualConfig`.\n */\nexport interface MutualConfigInput<MD extends z.ZodRawShape = z.ZodRawShape> {\n /**\n * Stable analytics dataset name. When provided, it must be lower-kebab-case;\n * the generator validates this so unnamed mutuals remain backwards compatible.\n */\n name?: string;\n entities: [Entity, Entity];\n /** Required unless `asEntity` is set — see `asEntity`'s own doc comment. */\n mutualDataSchema?: z.ZodObject<MD>;\n\n /**\n * @description (Optional) Materialize this mutual relationship as a real,\n * independently-queryable `Entity` whenever it's created — whether imperatively via\n * `MutualService.createMutual` or automatically via a declarative `mutualFields` entry that\n * references this config — by passing the `createEntityConfig(...)` return value for the\n * entity type it should materialize as.\n *\n * When set, in addition to the mutual edge, a real `Entity` is created:\n * `entityType = asEntity.name`, `entityId = <the mutual's own generated ulid>`,\n * `data = <the mutual's own parsed mutualData>`. This lets the relationship be looked up via\n * monorise's `tags` mechanism (an indexed GSI lookup) instead of scanning and filtering every\n * edge in application code, and lets the synthetic entity carry its own `mutualFields`.\n *\n * `mutualDataSchema` must be OMITTED when `asEntity` is set: it's derived automatically from\n * `asEntity.finalSchema` (that entity's own `baseSchema` + `createSchema` +\n * `effectiveMutualSchema`, merged — the same schema this codebase already validates every\n * normal `createEntity` payload against). Chosen over a narrower `baseSchema`/`createSchema`\n * derivation because `MutualService.createMutual`'s `asEntity` path fires\n * `afterCreateEntityHook` on the synthetic entity — the same hook that wires up an entity's\n * OWN further `mutualFields` — so anything narrower than `finalSchema` would silently break\n * that wiring for any `asEntity`-targeted entity that itself declares further relationships.\n * Providing both `asEntity` and `mutualDataSchema` is a build-time AND runtime error.\n *\n * The synthetic entity is always created SYNCHRONOUSLY, in the same DynamoDB transaction as\n * the mutual write, with its `afterCreateEntityHook` (tags/mutualFields wiring) firing\n * immediately after the commit. There is no asynchronous mode: the entity either exists the\n * moment the mutual does, or neither is written. That costs a `TransactWriteItems` (2x WCU\n * versus a plain write) but leaves no window in which the mutual exists and its projection\n * does not.\n *\n * An explicit `options.asEntity` passed directly at an imperative `createMutual(...)` call\n * site always overrides this config-level value — see `resolveAsEntity` in `@monorise/core`'s\n * `mutual.service`.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * asEntity: enrollmentEntityConfig, // the createEntityConfig(...) result for Entity.ENROLLMENT\n * });\n * ```\n */\n asEntity?: ReturnType<typeof createEntityConfig>;\n}\n\n/**\n * @description The resolved shape `createMutualConfig(...)` RETURNS, and what every other\n * consumer in this codebase (`mutualFields[key].mutual`, `MutualService`, the mutual processor)\n * actually references. Unlike `MutualConfigInput`, `mutualDataSchema` is REQUIRED here — by the\n * time a `MutualConfig` object exists, `createMutualConfig` has already derived it from\n * `asEntity.finalSchema` when needed, so every existing `.mutualDataSchema` read across this\n * codebase keeps its original, always-defined guarantee regardless of whether the mutual uses\n * `asEntity` or not.\n */\nexport interface MutualConfig<MD extends z.ZodRawShape = z.ZodRawShape>\n extends Omit<MutualConfigInput<MD>, 'mutualDataSchema'> {\n mutualDataSchema: z.ZodObject<MD>;\n}\n\nexport type DraftEntity<T extends Entity = Entity> =\n T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n\nexport type NumericFields<T> = {\n [K in keyof T as T[K] extends number ? K : never]?: number;\n};\n\nexport type CreatedEntity<T extends Entity = Entity> = {\n entityId: string;\n entityType: string;\n data: T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n createdAt: string;\n updatedAt: string;\n};\n\n/**\n * @description Configuration for a monorise entity, a shared configuration that is used across frontend and backend.\n * This can be served as a single source of truth for the entity configuration.\n * It is used to define the schema, and mutual relationships between this entity and other entities.\n *\n * @example\n * ```ts\n * const baseSchema = z.object({\n * title: z.string(),\n * }).partial();\n *\n * const createSchema = baseSchema.extend({\n * title: z.string(),\n * })\n *\n * const config = createEntityConfig({\n * name: 'learner',\n * displayName: 'Learner',\n * baseSchema,\n * createSchema,\n * });\n * ```\n */\nexport interface MonoriseEntityConfig<\n T extends Entity = Entity,\n B extends z.ZodRawShape = z.ZodRawShape,\n C extends z.ZodRawShape = z.ZodRawShape,\n M extends z.ZodRawShape = z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n CMO extends z.AnyZodObject | undefined = undefined,\n> {\n /**\n * @description Name of the entity. Must be in **lower-kebab-case** and **unique** across all entities\n *\n * @example `learner`, `learning-activity`\n */\n name: string | T;\n\n /**\n * @description Display name of the entity. It is not required to be unique\n */\n displayName: string;\n\n /**\n * @description (DEPRECATED) Use `uniqueFields` instead, Monorise should not handle auth mechanism\n * @description (Optional) Specify the authentication method to be used for the entity\n */\n authMethod?: {\n /**\n * @description Authentication method using email\n *\n * Note: The email used for authentication is unique per entity.\n * For example, if `johndoe@mail.com` is used for `learner` entity,\n * it can be reused again on `admin` entity. However, the same email\n * address cannot be repeated for the same entity.\n */\n email: {\n /**\n * @description Number of milliseconds before the token expires\n */\n tokenExpiresIn: number;\n };\n };\n\n /**\n * @description Base schema for the entity\n */\n baseSchema: z.ZodObject<B>;\n\n /**\n * @description Minimal schema required to create an entity\n */\n createSchema?: CO;\n searchableFields?: (keyof B)[];\n uniqueFields?: (keyof B)[];\n\n /**\n * @description Define mutual relationship of this entity with other entities\n */\n mutual?: {\n /**\n * @description Subscribes to update events from specified entities in the array.\n * These events will be used to run prejoin processor.\n */\n subscribes?: { entityType: Entity }[];\n /**\n * @description Virtual schema for mutual relationship. The schema is only used for validation purpose, but these fields are not stored in the database.\n * Used to validate mutual fields on create, and — derived to a partial — on update. You do NOT need to author this `.partial()`: the SDK partials it for the update path, so an update that doesn't touch every mutual relationship stays valid regardless of how this is declared.\n */\n mutualSchema: MO;\n\n /**\n * @description (Optional) Stricter schema applied ONLY when the entity is created — falls back to `mutualSchema` if not provided, so existing configs are unaffected. When provided, its shape is merged over `mutualSchema` for create; fields only `mutualSchema` declares (and `createMutualSchema` doesn't mention) are still validated and wired, not dropped.\n *\n * Use this when a mutual relationship must always be wired at creation time (e.g. every Competition must have an owning Organisation from the start). It does not affect updates either way — the update path derives a partial from `mutualSchema` itself, so a required-at-create relationship never has to be resent on an unrelated patch.\n *\n * Without this, a create silently succeeds even if a required mutual link is omitted from the payload — the entity is created but never gets wired to the relationship, with no error anywhere.\n *\n * Note: this only strengthens the *runtime* validation on create — `EntitySchemaMap` (the type callers see back from a read, generated from `finalSchema`) stays `MO`-shaped regardless, since mutual fields are never stored and a read can never actually return one. Don't expect a `createMutualSchema`-required field to show up as required in generated read types.\n *\n * The same-named `PUT /entity/:type/:id` upsert endpoint applies this schema only when the entity doesn't already exist — the same call is strict or lenient purely depending on whether that ID was already there.\n *\n * @example\n * ```ts\n * const mutualSchema = z.object({ organisationIds: z.string().array() }).partial();\n * const createMutualSchema = z.object({ organisationIds: z.string().array() }); // required on create\n * ```\n */\n createMutualSchema?: CMO;\n // Deliberately typed via its own `CMO` generic rather than `MO` — the\n // whole point is that it's allowed to be a DIFFERENT (stricter) shape\n // than `mutualSchema`, e.g. built via `mutualSchema.required({ field:\n // true })`, which is a structurally different ZodObject type, not `MO`\n // itself. Only the runtime merge (`resolveEffectiveMutualSchema` /\n // `effectiveMutualSchema`, see `packages/base/utils`) combines `MO` and\n // `CMO` — `finalSchema`'s TYPE deliberately stays `MO`-based; see the\n // note above and `makeSchema`'s own comment for why.\n\n /**\n * @description Keys of `mutualFields` are fields defined in `mutualSchema`.\n * Each field is a mutual relationship between this entity and another entity.\n */\n mutualFields: {\n [key: string]: {\n entityType: Entity;\n toMutualIds?: (context: any) => string[];\n /**\n * @description (Optional) Custom function to process `mutualData`. If not provided, `mutualData` will be empty.\n *\n * @returns the final state of `mutualData` to be stored in the mutual record. Must be an object.\n */\n mutualDataProcessor?: (\n mutualIds: string[],\n currentMutual: any,\n customContext?: Record<string, any>,\n ) => Record<string, any>;\n /**\n * @description (Optional) Reference to a mutual config created by `createMutualConfig`.\n * Provides mutualData schema validation for create/update operations on this mutual relationship.\n */\n mutual?: MutualConfig;\n };\n };\n\n /**\n * @description (Optional) Better known as tree processor\n * This is used to prejoin entities that are not directly related as mutual.\n * For example, if `learner` entity is related to `course` entity, and `course` entity is related to `module` entity,\n * prejoins can be used to join `learner` and `module` entities.\n * With this, the `learner` entity can access the `module` entity without having to go through the `course` entity,\n * hence reducing the number of queries.\n *\n * DynamoDB best practices: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-normalization.html\n *\n */\n prejoins?: {\n mutualField: string;\n targetEntityType: Entity;\n entityPaths: {\n skipCache?: boolean;\n entityType: Entity;\n processor?: (items: any[], context: Record<string, any>) => any;\n }[];\n }[];\n };\n /**\n * Use this function to perform side effects on the final schema for example refine/superRefine the schema\n *\n * @param schema The final schema of the entity (the combination of `baseSchema`/`createSchema` and `mutualSchema` if specified)\n * @returns void\n *\n * @example\n * ```ts\n * effect: (schema) => {\n * schema.refine(\n * // refinement logic here\n * )\n * }\n */\n effect?: (\n schema: z.ZodObject<z.ZodRawShape>,\n ) => z.ZodEffects<z.ZodObject<z.ZodRawShape>>;\n\n /**\n * @description (Optional) Use tags to create additional access patterns for the entity.\n * Time complexity for retrieving tagged entities is O(1).\n *\n * The following configuration will create a tag named `region` for the `organization` entity grouped by `region`.\n * You would then be able to retrieve all organizations in a specific region by:\n * GET `/core/tag/organization/region?group={region_name}`\n *\n * @example\n *\n * ```ts\n * {\n * name: 'organization',\n * tags: [\n * {\n * name: 'region',\n * processor: (entity) => {\n * return [\n * {\n * group: entity.data.region\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n *\n * @description\n *\n * The following configuration will create a tag named `dob` for the `user` entity sorted by `dob`.\n * You would then be able to retrieve all users sorted by `dob` by:\n * GET `/core/tag/user/dob?start=2000-01-01&end=2020-12-31`\n *\n * @example\n * ```ts\n * {\n * name: 'user',\n * tags: [\n * {\n * name: 'dob',\n * processor: (entity) => {\n * return [\n * {\n * sortValue: entity.data.dob\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n */\n tags?: {\n name: string;\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => {\n group?: string;\n sortValue?: string;\n }[];\n }[];\n\n /**\n * @description (Optional) Configure a DynamoDB TTL for this entity. When set, `expiresAt`\n * is computed via `processor` on create, and recomputed on every update/upsert. Once past,\n * DynamoDB automatically deletes the item (and its derived index rows, since they all carry\n * the same `expiresAt`).\n *\n * `processor` returning `undefined` means \"no TTL\" for that record. On updates, an `undefined`\n * result leaves any existing `expiresAt` untouched rather than clearing it.\n *\n * @example\n * ```ts\n * // fixed 30-day TTL from creation/each update\n * ttl: {\n * processor: () => Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,\n * }\n * ```\n *\n * @example\n * ```ts\n * // data-driven TTL, eg. expire when a subscription ends\n * ttl: {\n * processor: (entity) => {\n * return entity.data.subscriptionEndsAt\n * ? new Date(entity.data.subscriptionEndsAt)\n * : undefined;\n * },\n * }\n * ```\n */\n ttl?: {\n /**\n * @description Returns the expiry as epoch seconds (absolute) or a `Date`.\n * Return `undefined` for no expiry.\n */\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => number | Date | undefined;\n };\n\n /**\n * @description (Optional) Constraints for `adjustEntity` operations.\n * When adjusting numeric fields, these constraints are enforced at the database level.\n * If an adjustment would violate a constraint, the operation is rejected.\n *\n * @deprecated Use `conditions` instead. Will be removed in a future version.\n *\n * @example\n * ```ts\n * {\n * adjustmentConstraints: {\n * // Static: same for all entities of this type\n * balance: { min: 0 },\n * credits: { min: 0, max: 10000 },\n *\n * // Dynamic: reads constraint value from entity's own data\n * balance: { minField: 'minBalance' },\n * credits: { min: 0, maxField: 'creditLimit' },\n * }\n * }\n * ```\n */\n adjustmentConstraints?: {\n [fieldName: string]: {\n /** Static minimum value */\n min?: number;\n /** Static maximum value */\n max?: number;\n /** Field name on the entity whose value is used as the minimum (must be a numeric field) */\n minField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n };\n /** Field name on the entity whose value is used as the maximum (must be a numeric field) */\n maxField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n };\n };\n };\n\n /**\n * @description Named conditions for adjustEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data, adjustments) => WhereConditions` that receives the entity's current data\n * and the adjustment deltas.\n *\n * When defined, `$condition` is **required** in the adjustEntity request body.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression.\n *\n * @example\n * ```ts\n * {\n * adjustmentConditions: {\n * withdraw: (data, adjustments) => ({\n * balance: { $gte: (data.minBalance ?? 0) + Math.abs(adjustments?.balance ?? 0) },\n * }),\n * deposit: (data, adjustments) => ({\n * balance: { $lte: 1000000 - (adjustments.balance ?? 0) },\n * }),\n * }\n * }\n * ```\n */\n adjustmentConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((\n data: Partial<z.infer<z.ZodObject<B>>>,\n adjustments: Record<string, number>,\n ) => WhereConditions);\n };\n\n /**\n * @description Named conditions for updateEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data) => WhereConditions` that receives the entity's current data.\n *\n * `$condition` is always **optional** for updateEntity.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression. Replaces raw `$where` (deprecated).\n *\n * @example\n * ```ts\n * {\n * updateConditions: {\n * publish: { status: { $eq: 'draft' } },\n * archive: (data) => ({ status: { $ne: 'archived' } }),\n * }\n * }\n * ```\n */\n updateConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions);\n };\n\n /**\n * @description (Optional) Opt in to accepting legacy raw `$where` on updateEntity.\n * Disabled by default: raw DynamoDB condition operators must never be\n * client-facing — an authenticated client could otherwise probe field\n * existence or guess values via the 200-vs-409 response status.\n *\n * Only enable this if you trust the caller (e.g. server-to-server) or have\n * your own validation in front of it. Prefer `updateConditions` instead.\n *\n * @default false\n */\n allowLegacyWhere?: boolean;\n}\n","import { z } from 'zod';\nimport type {\n Entity,\n MonoriseEntityConfig,\n MutualConfig,\n MutualConfigInput,\n} from '../types/monorise.type';\n\n/**\n * @description Merges `mutualSchema` and `createMutualSchema` into the schema\n * actually used to validate a create payload. A plain `createMutualSchema ||\n * mutualSchema` fallback would DROP any mutual field that's declared on\n * `mutualSchema` but omitted from `createMutualSchema` (e.g. a\n * `createMutualSchema` authored to cover only the newly-required field,\n * without repeating every other optional mutual field) — `.parse()` strips\n * unknown keys, so that field's wiring would silently never fire even when\n * the caller supplied it. Merging shapes (with `createMutualSchema`'s keys\n * taking precedence on overlap, since it's the stricter one) keeps every\n * mutual field in play while still enforcing the create-only requirement.\n */\nfunction resolveEffectiveMutualSchema<M extends z.AnyZodObject | undefined>(\n mutualSchema: M,\n createMutualSchema?: z.AnyZodObject,\n): M extends z.AnyZodObject ? z.AnyZodObject : z.AnyZodObject | undefined {\n if (!createMutualSchema) return mutualSchema as any;\n if (!mutualSchema) return createMutualSchema as any;\n\n return mutualSchema.merge(createMutualSchema) as any;\n}\n\nfunction makeSchema<\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n effectiveMutualSchema: z.AnyZodObject | undefined,\n) {\n const { baseSchema, createSchema, effect } = config;\n\n // Deliberately NOT `MO & CMO`-typed: finalSchema.parse() runs against\n // effectiveMutualSchema's real runtime shape (below), but EntitySchemaMap\n // — the type callers see back from a *read* — is generated from this\n // same FinalSchemaType (packages/cli/commands/utils/generate.ts). Mutual\n // fields are never stored, so a required createMutualSchema field must\n // stay optional here; only the create-path runtime validation is allowed\n // to be strict.\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<B & CO['shape'] & MO['shape']>\n : z.ZodObject<B & CO['shape']>\n : MO extends z.AnyZodObject\n ? z.ZodObject<B & MO['shape']>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...effectiveMutualSchema?.shape,\n }) as FinalSchemaType;\n\n if (effect) {\n return effect(finalSchema) as z.ZodEffects<FinalSchemaType>;\n }\n\n return finalSchema;\n}\n\nconst createEntityConfig = <\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n) => {\n // Computed once here (config-definition time, not per-request/per-item)\n // and reused by every create-path call site (afterCreateEntityHook,\n // TransactionService.collectCreateEvents, UpsertEntityController) instead\n // of each rebuilding the same merged ZodObject from scratch.\n const { mutualSchema, createMutualSchema } = config.mutual || {};\n const effectiveMutualSchema = resolveEffectiveMutualSchema(\n mutualSchema,\n createMutualSchema,\n );\n\n return {\n ...config,\n // Derived output, not an input on MonoriseEntityConfig — there's\n // nowhere to declare this on the config type itself. Read by name\n // across packages/core (EntityServiceLifeCycle, TransactionService,\n // UpsertEntityController); don't hand-set it on a config object built\n // outside this factory (e.g. a test fixture) — build through\n // createEntityConfig instead, or it silently falls out of sync with\n // mutual.mutualSchema/createMutualSchema.\n effectiveMutualSchema,\n finalSchema: makeSchema(config, effectiveMutualSchema),\n };\n};\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfigInput<MD>,\n): MutualConfig<MD> => {\n // Catches a specific footgun before it falls through to the generic\n // \"one of mutualDataSchema or asEntity is required\" error below: a config\n // module that does `asEntity: importedEntityConfig` where\n // `importedEntityConfig` comes from a circular import (e.g. student.ts\n // imports enrollmentEntityConfig, which itself lives in a module that\n // imports student.ts) evaluates to `undefined` at this point, not a\n // missing key — `'asEntity' in config` is true, `config.asEntity` is not.\n // The generic error below would say \"one of ... is required\", which sends\n // people looking for a typo instead of an import cycle.\n if ('asEntity' in config && config.asEntity === undefined) {\n throw new Error(\n \"createMutualConfig: 'asEntity' is undefined — likely a circular import between entity config files (the imported entity config module hasn't finished initializing yet). Restructure the imports to break the cycle.\",\n );\n }\n\n if (config.asEntity && config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: 'asEntity' and 'mutualDataSchema' are mutually exclusive. \" +\n \"When 'asEntity' is set, mutualDataSchema is derived automatically from \" +\n \"asEntity.finalSchema — remove the explicit mutualDataSchema (or drop 'asEntity' \" +\n 'if this mutual should keep its own independently-authored schema).',\n );\n }\n\n if (!config.asEntity && !config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: one of 'mutualDataSchema' or 'asEntity' is required.\",\n );\n }\n\n // Unchanged identity behavior when `asEntity` isn't set — existing configs are unaffected.\n // `mutualDataSchema` is guaranteed present here (checked above), so this cast just tells\n // TypeScript what the runtime guard already established.\n if (!config.asEntity) return config as MutualConfig<MD>;\n\n // `finalSchema` (not baseSchema/createSchema alone) on purpose: the declarative mutual\n // processor's `afterCreateEntityHook` call needs the full schema to correctly wire the\n // synthetic entity's own further `mutualFields` too (see mutual-processor.ts).\n //\n // This does NOT mean finalSchema-shaped data is what gets PERSISTED as this mutual's\n // `mutualData` or the synthetic entity's `data` — both `MutualService.createMutual` and\n // `mutual-processor.ts` re-derive a narrower `asEntity.createSchema ?? asEntity.baseSchema`\n // parse for anything actually written to storage, specifically so the target entity's own\n // mutual-field keys (e.g. `courseIds`, if the target entity itself declares `mutualFields`)\n // never get baked into stored data — the same \"mutual fields are never stored\" invariant\n // `makeSchema` already documents for ordinary entities. `mutualDataSchema` staying as\n // `finalSchema` is what makes the fuller shape available to whichever call site needs it for\n // hook-wiring purposes, without that fuller shape leaking into what's actually persisted.\n return {\n ...config,\n mutualDataSchema: config.asEntity.finalSchema as unknown as z.ZodObject<MD>,\n };\n};\n\nexport { createEntityConfig, createMutualConfig, resolveEffectiveMutualSchema };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACJZ,SAAS,SAAS;AAoBlB,SAAS,6BACP,cACA,oBACwE;AACxE,MAAI,CAAC,mBAAoB,QAAO;AAChC,MAAI,CAAC,aAAc,QAAO;AAE1B,SAAO,aAAa,MAAM,kBAAkB;AAC9C;AAEA,SAAS,WASP,QACA,uBACA;AACA,QAAM,EAAE,YAAY,cAAc,OAAO,IAAI;AAiB7C,QAAM,cAAc,EAAE,OAAO,iDACxB,WAAW,QACX,6CAAc,QACd,+DAAuB,MAC3B;AAED,MAAI,QAAQ;AACV,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,qBAAqB,CASzB,WACG;AAKH,QAAM,EAAE,cAAc,mBAAmB,IAAI,OAAO,UAAU,CAAC;AAC/D,QAAM,wBAAwB;AAAA,IAC5B;AAAA,IACA;AAAA,EACF;AAEA,SAAO,iCACF,SADE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASL;AAAA,IACA,aAAa,WAAW,QAAQ,qBAAqB;AAAA,EACvD;AACF;AAEA,IAAM,qBAAqB,CACzB,WACqB;AAUrB,MAAI,cAAc,UAAU,OAAO,aAAa,QAAW;AACzD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,YAAY,OAAO,kBAAkB;AAC9C,UAAM,IAAI;AAAA,MACR;AAAA,IAIF;AAAA,EACF;AAEA,MAAI,CAAC,OAAO,YAAY,CAAC,OAAO,kBAAkB;AAChD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAKA,MAAI,CAAC,OAAO,SAAU,QAAO;AAe7B,SAAO,iCACF,SADE;AAAA,IAEL,kBAAkB,OAAO,SAAS;AAAA,EACpC;AACF;","names":["Entity"]}
|
|
1
|
+
{"version":3,"sources":["../types/monorise.type.ts","../utils/index.ts","../utils/search.ts"],"sourcesContent":["import type { z } from 'zod';\nimport type { createEntityConfig } from '../utils';\nimport type { WhereConditions } from './conditions.type';\n\nexport enum Entity {}\n\nexport interface EntitySchemaMap {\n [key: string]: Record<string, any>;\n}\n\n/**\n * @description How a field's value is matched. `words`: split on spaces and\n * symbols, and each word is matched from its start (\"jo\" finds \"John\").\n */\nexport type SearchMatch = 'words';\n\n/**\n * @description Search settings shared by an entity's `search` config and the\n * `search` key of `monorise.config.ts`. An entity's value replaces the\n * global one.\n */\nexport interface SearchSettings {\n /**\n * @description Most words indexed per entity, counted across `fields` in\n * order after duplicates and `ignoreWords` are dropped. Words past it can't\n * be searched. Each word is a copy of the entity that every update of the\n * entity rewrites. Defaults to `DEFAULT_MAX_WORDS` (8).\n */\n maxWords?: number;\n /**\n * @description Words that are never indexed and are skipped in queries\n * (also known as stop words). Replaces the default list: spread\n * `DEFAULT_IGNORE_WORDS` to extend it, or pass `[]` to ignore nothing.\n */\n ignoreWords?: readonly string[];\n}\n\n// Generic over the field names rather than the schema shape, so a config for\n// one entity stays assignable to the general config type.\nexport interface SearchConfig<K extends PropertyKey = string>\n extends SearchSettings {\n /**\n * @description Fields to index, most-searched first: earlier fields fill\n * `maxWords` first.\n */\n fields: { field: K; match?: SearchMatch }[];\n}\n\n/**\n * @description Configuration for a mutual relationship between two entities.\n * Defines the schema for mutualData validation. Define once, reference from both entity configs.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * mutualDataSchema: z.object({\n * role: z.enum(['student', 'auditor']),\n * enrolledAt: z.string().datetime(),\n * }),\n * });\n * ```\n */\n/**\n * @description The shape `createMutualConfig(...)` is CALLED with — looser than the resolved\n * `MutualConfig` it returns. `mutualDataSchema` is optional here (and mutually exclusive with\n * `asEntity`) because `createMutualConfig` resolves it before returning: every OTHER consumer in\n * this codebase (`mutualFields[key].mutual`, `MutualService`, the processors) reads the resolved\n * `MutualConfig` type below, where `mutualDataSchema` stays REQUIRED — the same \"loose input,\n * strict resolved output\" split `createEntityConfig`/`MonoriseEntityConfig` already use for\n * `finalSchema`/`effectiveMutualSchema`. Import this type only if you're writing something that\n * itself calls `createMutualConfig`; every other call site should keep using `MutualConfig`.\n */\nexport interface MutualConfigInput<MD extends z.ZodRawShape = z.ZodRawShape> {\n /**\n * Stable analytics dataset name. When provided, it must be lower-kebab-case;\n * the generator validates this so unnamed mutuals remain backwards compatible.\n */\n name?: string;\n entities: [Entity, Entity];\n /** Required unless `asEntity` is set — see `asEntity`'s own doc comment. */\n mutualDataSchema?: z.ZodObject<MD>;\n\n /**\n * @description (Optional) Materialize this mutual relationship as a real,\n * independently-queryable `Entity` whenever it's created — whether imperatively via\n * `MutualService.createMutual` or automatically via a declarative `mutualFields` entry that\n * references this config — by passing the `createEntityConfig(...)` return value for the\n * entity type it should materialize as.\n *\n * When set, in addition to the mutual edge, a real `Entity` is created:\n * `entityType = asEntity.name`, `entityId = <the mutual's own generated ulid>`,\n * `data = <the mutual's own parsed mutualData>`. This lets the relationship be looked up via\n * monorise's `tags` mechanism (an indexed GSI lookup) instead of scanning and filtering every\n * edge in application code, and lets the synthetic entity carry its own `mutualFields`.\n *\n * `mutualDataSchema` must be OMITTED when `asEntity` is set: it's derived automatically from\n * `asEntity.finalSchema` (that entity's own `baseSchema` + `createSchema` +\n * `effectiveMutualSchema`, merged — the same schema this codebase already validates every\n * normal `createEntity` payload against). Chosen over a narrower `baseSchema`/`createSchema`\n * derivation because `MutualService.createMutual`'s `asEntity` path fires\n * `afterCreateEntityHook` on the synthetic entity — the same hook that wires up an entity's\n * OWN further `mutualFields` — so anything narrower than `finalSchema` would silently break\n * that wiring for any `asEntity`-targeted entity that itself declares further relationships.\n * Providing both `asEntity` and `mutualDataSchema` is a build-time AND runtime error.\n *\n * The synthetic entity is always created SYNCHRONOUSLY, in the same DynamoDB transaction as\n * the mutual write, with its `afterCreateEntityHook` (tags/mutualFields wiring) firing\n * immediately after the commit. There is no asynchronous mode: the entity either exists the\n * moment the mutual does, or neither is written. That costs a `TransactWriteItems` (2x WCU\n * versus a plain write) but leaves no window in which the mutual exists and its projection\n * does not.\n *\n * An explicit `options.asEntity` passed directly at an imperative `createMutual(...)` call\n * site always overrides this config-level value — see `resolveAsEntity` in `@monorise/core`'s\n * `mutual.service`.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * asEntity: enrollmentEntityConfig, // the createEntityConfig(...) result for Entity.ENROLLMENT\n * });\n * ```\n */\n asEntity?: ReturnType<typeof createEntityConfig>;\n}\n\n/**\n * @description The resolved shape `createMutualConfig(...)` RETURNS, and what every other\n * consumer in this codebase (`mutualFields[key].mutual`, `MutualService`, the mutual processor)\n * actually references. Unlike `MutualConfigInput`, `mutualDataSchema` is REQUIRED here — by the\n * time a `MutualConfig` object exists, `createMutualConfig` has already derived it from\n * `asEntity.finalSchema` when needed, so every existing `.mutualDataSchema` read across this\n * codebase keeps its original, always-defined guarantee regardless of whether the mutual uses\n * `asEntity` or not.\n */\nexport interface MutualConfig<MD extends z.ZodRawShape = z.ZodRawShape>\n extends Omit<MutualConfigInput<MD>, 'mutualDataSchema'> {\n mutualDataSchema: z.ZodObject<MD>;\n}\n\nexport type DraftEntity<T extends Entity = Entity> =\n T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n\nexport type NumericFields<T> = {\n [K in keyof T as T[K] extends number ? K : never]?: number;\n};\n\nexport type CreatedEntity<T extends Entity = Entity> = {\n entityId: string;\n entityType: string;\n data: T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n createdAt: string;\n updatedAt: string;\n};\n\n/**\n * @description Configuration for a monorise entity, a shared configuration that is used across frontend and backend.\n * This can be served as a single source of truth for the entity configuration.\n * It is used to define the schema, and mutual relationships between this entity and other entities.\n *\n * @example\n * ```ts\n * const baseSchema = z.object({\n * title: z.string(),\n * }).partial();\n *\n * const createSchema = baseSchema.extend({\n * title: z.string(),\n * })\n *\n * const config = createEntityConfig({\n * name: 'learner',\n * displayName: 'Learner',\n * baseSchema,\n * createSchema,\n * });\n * ```\n */\nexport interface MonoriseEntityConfig<\n T extends Entity = Entity,\n B extends z.ZodRawShape = z.ZodRawShape,\n C extends z.ZodRawShape = z.ZodRawShape,\n M extends z.ZodRawShape = z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n CMO extends z.AnyZodObject | undefined = undefined,\n> {\n /**\n * @description Name of the entity. Must be in **lower-kebab-case** and **unique** across all entities\n *\n * @example `learner`, `learning-activity`\n */\n name: string | T;\n\n /**\n * @description Display name of the entity. It is not required to be unique\n */\n displayName: string;\n\n /**\n * @description (DEPRECATED) Use `uniqueFields` instead, Monorise should not handle auth mechanism\n * @description (Optional) Specify the authentication method to be used for the entity\n */\n authMethod?: {\n /**\n * @description Authentication method using email\n *\n * Note: The email used for authentication is unique per entity.\n * For example, if `johndoe@mail.com` is used for `learner` entity,\n * it can be reused again on `admin` entity. However, the same email\n * address cannot be repeated for the same entity.\n */\n email: {\n /**\n * @description Number of milliseconds before the token expires\n */\n tokenExpiresIn: number;\n };\n };\n\n /**\n * @description Base schema for the entity\n */\n baseSchema: z.ZodObject<B>;\n\n /**\n * @description Minimal schema required to create an entity\n */\n createSchema?: CO;\n /**\n * @description (Optional) Fields `?query=` matches against, by scanning every\n * entity of this type. Use `search` instead to look matches up by word\n * without the scan. Can't be combined with `search`.\n */\n searchableFields?: (keyof B)[];\n /**\n * @description (Optional) Index these fields by word, so `?query=` reads\n * only the entities that contain the words searched for. Can't be combined\n * with `searchableFields`.\n *\n * `maxWords` and `ignoreWords` fall back to the `search` settings in\n * `monorise.config.ts`, then to the built-in defaults.\n *\n * @example\n * ```ts\n * search: {\n * fields: [{ field: 'displayName' }, { field: 'email' }],\n * },\n * ```\n */\n search?: SearchConfig<keyof B>;\n uniqueFields?: (keyof B)[];\n\n /**\n * @description Define mutual relationship of this entity with other entities\n */\n mutual?: {\n /**\n * @description Subscribes to update events from specified entities in the array.\n * These events will be used to run prejoin processor.\n */\n subscribes?: { entityType: Entity }[];\n /**\n * @description Virtual schema for mutual relationship. The schema is only used for validation purpose, but these fields are not stored in the database.\n * Used to validate mutual fields on create, and — derived to a partial — on update. You do NOT need to author this `.partial()`: the SDK partials it for the update path, so an update that doesn't touch every mutual relationship stays valid regardless of how this is declared.\n */\n mutualSchema: MO;\n\n /**\n * @description (Optional) Stricter schema applied ONLY when the entity is created — falls back to `mutualSchema` if not provided, so existing configs are unaffected. When provided, its shape is merged over `mutualSchema` for create; fields only `mutualSchema` declares (and `createMutualSchema` doesn't mention) are still validated and wired, not dropped.\n *\n * Use this when a mutual relationship must always be wired at creation time (e.g. every Competition must have an owning Organisation from the start). It does not affect updates either way — the update path derives a partial from `mutualSchema` itself, so a required-at-create relationship never has to be resent on an unrelated patch.\n *\n * Without this, a create silently succeeds even if a required mutual link is omitted from the payload — the entity is created but never gets wired to the relationship, with no error anywhere.\n *\n * Note: this only strengthens the *runtime* validation on create — `EntitySchemaMap` (the type callers see back from a read, generated from `finalSchema`) stays `MO`-shaped regardless, since mutual fields are never stored and a read can never actually return one. Don't expect a `createMutualSchema`-required field to show up as required in generated read types.\n *\n * The same-named `PUT /entity/:type/:id` upsert endpoint applies this schema only when the entity doesn't already exist — the same call is strict or lenient purely depending on whether that ID was already there.\n *\n * @example\n * ```ts\n * const mutualSchema = z.object({ organisationIds: z.string().array() }).partial();\n * const createMutualSchema = z.object({ organisationIds: z.string().array() }); // required on create\n * ```\n */\n createMutualSchema?: CMO;\n // Deliberately typed via its own `CMO` generic rather than `MO` — the\n // whole point is that it's allowed to be a DIFFERENT (stricter) shape\n // than `mutualSchema`, e.g. built via `mutualSchema.required({ field:\n // true })`, which is a structurally different ZodObject type, not `MO`\n // itself. Only the runtime merge (`resolveEffectiveMutualSchema` /\n // `effectiveMutualSchema`, see `packages/base/utils`) combines `MO` and\n // `CMO` — `finalSchema`'s TYPE deliberately stays `MO`-based; see the\n // note above and `makeSchema`'s own comment for why.\n\n /**\n * @description Keys of `mutualFields` are fields defined in `mutualSchema`.\n * Each field is a mutual relationship between this entity and another entity.\n */\n mutualFields: {\n [key: string]: {\n entityType: Entity;\n toMutualIds?: (context: any) => string[];\n /**\n * @description (Optional) Custom function to process `mutualData`. If not provided, `mutualData` will be empty.\n *\n * @returns the final state of `mutualData` to be stored in the mutual record. Must be an object.\n */\n mutualDataProcessor?: (\n mutualIds: string[],\n currentMutual: any,\n customContext?: Record<string, any>,\n ) => Record<string, any>;\n /**\n * @description (Optional) Reference to a mutual config created by `createMutualConfig`.\n * Provides mutualData schema validation for create/update operations on this mutual relationship.\n */\n mutual?: MutualConfig;\n };\n };\n\n /**\n * @description (Optional) Better known as tree processor\n * This is used to prejoin entities that are not directly related as mutual.\n * For example, if `learner` entity is related to `course` entity, and `course` entity is related to `module` entity,\n * prejoins can be used to join `learner` and `module` entities.\n * With this, the `learner` entity can access the `module` entity without having to go through the `course` entity,\n * hence reducing the number of queries.\n *\n * DynamoDB best practices: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-normalization.html\n *\n */\n prejoins?: {\n mutualField: string;\n targetEntityType: Entity;\n entityPaths: {\n skipCache?: boolean;\n entityType: Entity;\n processor?: (items: any[], context: Record<string, any>) => any;\n }[];\n }[];\n };\n /**\n * Use this function to perform side effects on the final schema for example refine/superRefine the schema\n *\n * @param schema The final schema of the entity (the combination of `baseSchema`/`createSchema` and `mutualSchema` if specified)\n * @returns void\n *\n * @example\n * ```ts\n * effect: (schema) => {\n * schema.refine(\n * // refinement logic here\n * )\n * }\n */\n effect?: (\n schema: z.ZodObject<z.ZodRawShape>,\n ) => z.ZodEffects<z.ZodObject<z.ZodRawShape>>;\n\n /**\n * @description (Optional) Use tags to create additional access patterns for the entity.\n * Time complexity for retrieving tagged entities is O(1).\n *\n * The following configuration will create a tag named `region` for the `organization` entity grouped by `region`.\n * You would then be able to retrieve all organizations in a specific region by:\n * GET `/core/tag/organization/region?group={region_name}`\n *\n * @example\n *\n * ```ts\n * {\n * name: 'organization',\n * tags: [\n * {\n * name: 'region',\n * processor: (entity) => {\n * return [\n * {\n * group: entity.data.region\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n *\n * @description\n *\n * The following configuration will create a tag named `dob` for the `user` entity sorted by `dob`.\n * You would then be able to retrieve all users sorted by `dob` by:\n * GET `/core/tag/user/dob?start=2000-01-01&end=2020-12-31`\n *\n * @example\n * ```ts\n * {\n * name: 'user',\n * tags: [\n * {\n * name: 'dob',\n * processor: (entity) => {\n * return [\n * {\n * sortValue: entity.data.dob\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n */\n tags?: {\n name: string;\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => {\n group?: string;\n sortValue?: string;\n }[];\n }[];\n\n /**\n * @description (Optional) Configure a DynamoDB TTL for this entity. When set, `expiresAt`\n * is computed via `processor` on create, and recomputed on every update/upsert. Once past,\n * DynamoDB automatically deletes the item (and its derived index rows, since they all carry\n * the same `expiresAt`).\n *\n * `processor` returning `undefined` means \"no TTL\" for that record. On updates, an `undefined`\n * result leaves any existing `expiresAt` untouched rather than clearing it.\n *\n * @example\n * ```ts\n * // fixed 30-day TTL from creation/each update\n * ttl: {\n * processor: () => Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,\n * }\n * ```\n *\n * @example\n * ```ts\n * // data-driven TTL, eg. expire when a subscription ends\n * ttl: {\n * processor: (entity) => {\n * return entity.data.subscriptionEndsAt\n * ? new Date(entity.data.subscriptionEndsAt)\n * : undefined;\n * },\n * }\n * ```\n */\n ttl?: {\n /**\n * @description Returns the expiry as epoch seconds (absolute) or a `Date`.\n * Return `undefined` for no expiry.\n */\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => number | Date | undefined;\n };\n\n /**\n * @description (Optional) Constraints for `adjustEntity` operations.\n * When adjusting numeric fields, these constraints are enforced at the database level.\n * If an adjustment would violate a constraint, the operation is rejected.\n *\n * @deprecated Use `conditions` instead. Will be removed in a future version.\n *\n * @example\n * ```ts\n * {\n * adjustmentConstraints: {\n * // Static: same for all entities of this type\n * balance: { min: 0 },\n * credits: { min: 0, max: 10000 },\n *\n * // Dynamic: reads constraint value from entity's own data\n * balance: { minField: 'minBalance' },\n * credits: { min: 0, maxField: 'creditLimit' },\n * }\n * }\n * ```\n */\n adjustmentConstraints?: {\n [fieldName: string]: {\n /** Static minimum value */\n min?: number;\n /** Static maximum value */\n max?: number;\n /** Field name on the entity whose value is used as the minimum (must be a numeric field) */\n minField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n };\n /** Field name on the entity whose value is used as the maximum (must be a numeric field) */\n maxField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : never]: K;\n };\n };\n };\n\n /**\n * @description Named conditions for adjustEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data, adjustments) => WhereConditions` that receives the entity's current data\n * and the adjustment deltas.\n *\n * When defined, `$condition` is **required** in the adjustEntity request body.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression.\n *\n * @example\n * ```ts\n * {\n * adjustmentConditions: {\n * withdraw: (data, adjustments) => ({\n * balance: { $gte: (data.minBalance ?? 0) + Math.abs(adjustments?.balance ?? 0) },\n * }),\n * deposit: (data, adjustments) => ({\n * balance: { $lte: 1000000 - (adjustments.balance ?? 0) },\n * }),\n * }\n * }\n * ```\n */\n adjustmentConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((\n data: Partial<z.infer<z.ZodObject<B>>>,\n adjustments: Record<string, number>,\n ) => WhereConditions);\n };\n\n /**\n * @description Named conditions for updateEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data) => WhereConditions` that receives the entity's current data.\n *\n * `$condition` is always **optional** for updateEntity.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression. Replaces raw `$where` (deprecated).\n *\n * @example\n * ```ts\n * {\n * updateConditions: {\n * publish: { status: { $eq: 'draft' } },\n * archive: (data) => ({ status: { $ne: 'archived' } }),\n * }\n * }\n * ```\n */\n updateConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions);\n };\n\n /**\n * @description (Optional) Opt in to accepting legacy raw `$where` on updateEntity.\n * Disabled by default: raw DynamoDB condition operators must never be\n * client-facing — an authenticated client could otherwise probe field\n * existence or guess values via the 200-vs-409 response status.\n *\n * Only enable this if you trust the caller (e.g. server-to-server) or have\n * your own validation in front of it. Prefer `updateConditions` instead.\n *\n * @default false\n */\n allowLegacyWhere?: boolean;\n}\n","import { z } from 'zod';\nimport type {\n Entity,\n MonoriseEntityConfig,\n MutualConfig,\n MutualConfigInput,\n // Named here so the declaration emitted for createEntityConfig's return\n // type can refer to it.\n SearchConfig,\n} from '../types/monorise.type';\nimport { validateSearchSettings } from './search';\n\n/**\n * @description Merges `mutualSchema` and `createMutualSchema` into the schema\n * actually used to validate a create payload. A plain `createMutualSchema ||\n * mutualSchema` fallback would DROP any mutual field that's declared on\n * `mutualSchema` but omitted from `createMutualSchema` (e.g. a\n * `createMutualSchema` authored to cover only the newly-required field,\n * without repeating every other optional mutual field) — `.parse()` strips\n * unknown keys, so that field's wiring would silently never fire even when\n * the caller supplied it. Merging shapes (with `createMutualSchema`'s keys\n * taking precedence on overlap, since it's the stricter one) keeps every\n * mutual field in play while still enforcing the create-only requirement.\n */\nfunction resolveEffectiveMutualSchema<M extends z.AnyZodObject | undefined>(\n mutualSchema: M,\n createMutualSchema?: z.AnyZodObject,\n): M extends z.AnyZodObject ? z.AnyZodObject : z.AnyZodObject | undefined {\n if (!createMutualSchema) return mutualSchema as any;\n if (!mutualSchema) return createMutualSchema as any;\n\n return mutualSchema.merge(createMutualSchema) as any;\n}\n\nfunction makeSchema<\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n effectiveMutualSchema: z.AnyZodObject | undefined,\n) {\n const { baseSchema, createSchema, effect } = config;\n\n // Deliberately NOT `MO & CMO`-typed: finalSchema.parse() runs against\n // effectiveMutualSchema's real runtime shape (below), but EntitySchemaMap\n // — the type callers see back from a *read* — is generated from this\n // same FinalSchemaType (packages/cli/commands/utils/generate.ts). Mutual\n // fields are never stored, so a required createMutualSchema field must\n // stay optional here; only the create-path runtime validation is allowed\n // to be strict.\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<B & CO['shape'] & MO['shape']>\n : z.ZodObject<B & CO['shape']>\n : MO extends z.AnyZodObject\n ? z.ZodObject<B & MO['shape']>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...effectiveMutualSchema?.shape,\n }) as FinalSchemaType;\n\n if (effect) {\n return effect(finalSchema) as z.ZodEffects<FinalSchemaType>;\n }\n\n return finalSchema;\n}\n\nconst createEntityConfig = <\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n) => {\n if (config.search) {\n if (config.searchableFields) {\n throw new Error(\n `${config.name}: 'search' and 'searchableFields' can't both be set. 'searchableFields' scans every entity on each search; 'search' looks matches up by word. Keep one.`,\n );\n }\n if (!config.search.fields?.length) {\n throw new Error(`${config.name}: 'search.fields' needs at least one field.`);\n }\n for (const { field, match } of config.search.fields) {\n if (match !== undefined && match !== 'words') {\n throw new Error(\n `${config.name}: 'search.fields' entry '${String(field)}' has an unknown match '${match}'. Supported: 'words'.`,\n );\n }\n }\n validateSearchSettings(config.search, String(config.name));\n }\n\n // Computed once here (config-definition time, not per-request/per-item)\n // and reused by every create-path call site (afterCreateEntityHook,\n // TransactionService.collectCreateEvents, UpsertEntityController) instead\n // of each rebuilding the same merged ZodObject from scratch.\n const { mutualSchema, createMutualSchema } = config.mutual || {};\n const effectiveMutualSchema = resolveEffectiveMutualSchema(\n mutualSchema,\n createMutualSchema,\n );\n\n return {\n ...config,\n // Derived output, not an input on MonoriseEntityConfig — there's\n // nowhere to declare this on the config type itself. Read by name\n // across packages/core (EntityServiceLifeCycle, TransactionService,\n // UpsertEntityController); don't hand-set it on a config object built\n // outside this factory (e.g. a test fixture) — build through\n // createEntityConfig instead, or it silently falls out of sync with\n // mutual.mutualSchema/createMutualSchema.\n effectiveMutualSchema,\n finalSchema: makeSchema(config, effectiveMutualSchema),\n };\n};\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfigInput<MD>,\n): MutualConfig<MD> => {\n // Catches a specific footgun before it falls through to the generic\n // \"one of mutualDataSchema or asEntity is required\" error below: a config\n // module that does `asEntity: importedEntityConfig` where\n // `importedEntityConfig` comes from a circular import (e.g. student.ts\n // imports enrollmentEntityConfig, which itself lives in a module that\n // imports student.ts) evaluates to `undefined` at this point, not a\n // missing key — `'asEntity' in config` is true, `config.asEntity` is not.\n // The generic error below would say \"one of ... is required\", which sends\n // people looking for a typo instead of an import cycle.\n if ('asEntity' in config && config.asEntity === undefined) {\n throw new Error(\n \"createMutualConfig: 'asEntity' is undefined — likely a circular import between entity config files (the imported entity config module hasn't finished initializing yet). Restructure the imports to break the cycle.\",\n );\n }\n\n if (config.asEntity && config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: 'asEntity' and 'mutualDataSchema' are mutually exclusive. \" +\n \"When 'asEntity' is set, mutualDataSchema is derived automatically from \" +\n \"asEntity.finalSchema — remove the explicit mutualDataSchema (or drop 'asEntity' \" +\n 'if this mutual should keep its own independently-authored schema).',\n );\n }\n\n if (!config.asEntity && !config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: one of 'mutualDataSchema' or 'asEntity' is required.\",\n );\n }\n\n // Unchanged identity behavior when `asEntity` isn't set — existing configs are unaffected.\n // `mutualDataSchema` is guaranteed present here (checked above), so this cast just tells\n // TypeScript what the runtime guard already established.\n if (!config.asEntity) return config as MutualConfig<MD>;\n\n // `finalSchema` (not baseSchema/createSchema alone) on purpose: the declarative mutual\n // processor's `afterCreateEntityHook` call needs the full schema to correctly wire the\n // synthetic entity's own further `mutualFields` too (see mutual-processor.ts).\n //\n // This does NOT mean finalSchema-shaped data is what gets PERSISTED as this mutual's\n // `mutualData` or the synthetic entity's `data` — both `MutualService.createMutual` and\n // `mutual-processor.ts` re-derive a narrower `asEntity.createSchema ?? asEntity.baseSchema`\n // parse for anything actually written to storage, specifically so the target entity's own\n // mutual-field keys (e.g. `courseIds`, if the target entity itself declares `mutualFields`)\n // never get baked into stored data — the same \"mutual fields are never stored\" invariant\n // `makeSchema` already documents for ordinary entities. `mutualDataSchema` staying as\n // `finalSchema` is what makes the fuller shape available to whichever call site needs it for\n // hook-wiring purposes, without that fuller shape leaking into what's actually persisted.\n return {\n ...config,\n mutualDataSchema: config.asEntity.finalSchema as unknown as z.ZodObject<MD>,\n };\n};\n\nexport { createEntityConfig, createMutualConfig, resolveEffectiveMutualSchema };\n","import type {\n SearchConfig,\n SearchMatch,\n SearchSettings,\n} from '../types/monorise.type';\n\nexport const DEFAULT_MAX_WORDS = 8;\n\n/**\n * @description Words ignored unless an entity or `monorise.config.ts` sets\n * its own list. Deliberately short: an ignored word can never be found on its\n * own, so words that are also names (\"an\", \"will\", \"may\") are left out.\n */\nexport const DEFAULT_IGNORE_WORDS: readonly string[] = [\n 'the',\n 'and',\n 'of',\n 'in',\n 'to',\n 'for',\n 'with',\n 'on',\n 'at',\n 'by',\n 'from',\n 'or',\n 'is',\n 'are',\n 'was',\n 'be',\n 'as',\n 'it',\n 'this',\n 'that',\n];\n\n// One-letter words are never indexed, and a query needs a longer word to be\n// looked up: a one-letter prefix would read a large part of the index.\nconst MIN_WORD_LENGTH = 2;\n\nconst NON_WORD = /[^\\p{L}\\p{N}]+/u;\nconst MARKS = /\\p{M}/gu;\n\nexport type ResolvedSearchConfig = {\n fields: { field: string; match: SearchMatch }[];\n maxWords: number;\n ignoreWords: string[];\n};\n\n/**\n * @description Lowercases and strips accents, so \"José\" and \"jose\" match.\n */\nexport function foldText(text: string): string {\n return text.normalize('NFKD').replace(MARKS, '').toLowerCase();\n}\n\n/**\n * @description Splits on anything that isn't a letter or digit:\n * \"example@mail.com\" becomes [\"example\", \"mail\", \"com\"].\n */\nexport function splitWords(text: string): string[] {\n return foldText(text).split(NON_WORD).filter(Boolean);\n}\n\nconst collapseSpaces = (text: string) => text.trim().replace(/\\s+/g, ' ');\n\n/**\n * @description An entity's `search` config with the `monorise.config.ts`\n * settings and built-in defaults filled in.\n */\nexport function resolveSearchConfig(\n search: SearchConfig<PropertyKey>,\n defaults?: SearchSettings,\n): ResolvedSearchConfig {\n const ignoreWords =\n search.ignoreWords ?? defaults?.ignoreWords ?? DEFAULT_IGNORE_WORDS;\n\n return {\n fields: search.fields.map(({ field, match }) => ({\n field: String(field),\n match: match ?? 'words',\n })),\n maxWords: search.maxWords ?? defaults?.maxWords ?? DEFAULT_MAX_WORDS,\n ignoreWords: [...new Set(ignoreWords.map(foldText))].sort(),\n };\n}\n\n/**\n * @description Throws on settings the index can't use. `where` names the\n * config in the message.\n */\nexport function validateSearchSettings(\n settings: SearchSettings,\n where: string,\n): void {\n const { maxWords, ignoreWords } = settings;\n if (maxWords !== undefined && (!Number.isInteger(maxWords) || maxWords < 1)) {\n throw new Error(`${where}: 'search.maxWords' must be a positive integer.`);\n }\n if (\n ignoreWords !== undefined &&\n (!Array.isArray(ignoreWords) ||\n ignoreWords.some((word) => typeof word !== 'string'))\n ) {\n throw new Error(\n `${where}: 'search.ignoreWords' must be an array of strings.`,\n );\n }\n}\n\n/**\n * @description Changes whenever the words an entity is indexed by would.\n * Only used to notice that, so it doesn't need to be cryptographic (cyrb53).\n */\nexport function searchConfigHash(config: ResolvedSearchConfig): string {\n const input = JSON.stringify(config);\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (let i = 0; i < input.length; i++) {\n const char = input.charCodeAt(i);\n h1 = Math.imul(h1 ^ char, 2654435761);\n h2 = Math.imul(h2 ^ char, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n\n return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);\n}\n\n// Strings and numbers, and the strings and numbers inside an array.\nfunction fieldValues(\n data: Record<string, unknown> | undefined,\n field: string,\n): string[] {\n const value = data?.[field];\n const values = Array.isArray(value) ? value : [value];\n\n return values\n .filter((v) => typeof v === 'string' || typeof v === 'number')\n .map(String);\n}\n\n/**\n * @description The words an entity can be found by: fields in config order,\n * without one-letter words, ignored words and duplicates, up to `maxWords`.\n * Writing the index and checking a match both use this, so a word past the\n * cap is never found, whichever word a query is looked up by.\n */\nexport function indexedWords(\n data: Record<string, unknown> | undefined,\n config: ResolvedSearchConfig,\n): string[] {\n const ignore = new Set(config.ignoreWords);\n const words = new Set<string>();\n\n for (const { field } of config.fields) {\n for (const value of fieldValues(data, field)) {\n for (const word of splitWords(value)) {\n if (word.length < MIN_WORD_LENGTH || ignore.has(word)) continue;\n words.add(word);\n if (words.size === config.maxWords) return [...words];\n }\n }\n }\n\n return [...words];\n}\n\nexport type SearchTerm = {\n /** Each must be the start of one of the entity's indexed words. */\n words: string[];\n /** Must also appear as typed in one field: quoted, or joined by symbols. */\n phrase?: string;\n};\n\nexport type SearchPlan = {\n /** The word whose index rows are read. Without one, nothing matches. */\n anchor?: string;\n terms: SearchTerm[];\n};\n\n/**\n * @description Parses a query. Plain words match from the start of a word,\n * in any order. Quoted text and text joined by symbols (\"example@mail.com\")\n * must also appear exactly. The anchor is the longest word.\n */\nexport function planSearch(\n query: string,\n ignoreWords: readonly string[],\n): SearchPlan {\n const ignore = new Set(ignoreWords);\n const parsed: { text: string; quoted: boolean }[] = [];\n const termPattern = /\"([^\"]+)\"|(\\S+)/g;\n for (\n let match = termPattern.exec(query);\n match;\n match = termPattern.exec(query)\n ) {\n parsed.push({ text: match[1] ?? match[2], quoted: match[1] !== undefined });\n }\n\n const terms: SearchTerm[] = [];\n let trailing: string | undefined;\n\n parsed.forEach(({ text, quoted }, i) => {\n const parts = splitWords(text);\n const words = parts.filter(\n (word) => word.length >= MIN_WORD_LENGTH && !ignore.has(word),\n );\n\n if (quoted || parts.length > 1) {\n terms.push({ words, phrase: collapseSpaces(foldText(text)) });\n } else if (words.length) {\n terms.push({ words });\n } else if (\n i === parsed.length - 1 &&\n (parts[0]?.length ?? 0) >= MIN_WORD_LENGTH\n ) {\n // An ignored last word may still be being typed (\"and\" on the way to\n // \"anderson\").\n trailing = parts[0];\n }\n });\n\n const required = terms.flatMap((term) => term.words);\n if (!required.length && trailing) {\n // On its own it's looked up as a prefix. Next to other words it's dropped.\n return { anchor: trailing, terms: [...terms, { words: [trailing] }] };\n }\n\n const anchor = required.reduce<string | undefined>(\n (longest, word) =>\n !longest || word.length > longest.length ? word : longest,\n undefined,\n );\n\n return { anchor, terms };\n}\n\n/**\n * @description Whether an entity's data matches a planned query.\n */\nexport function matchesSearch(\n data: Record<string, unknown> | undefined,\n plan: SearchPlan,\n config: ResolvedSearchConfig,\n): boolean {\n if (!plan.anchor) return false;\n\n const words = indexedWords(data, config);\n const values = config.fields.flatMap(({ field }) =>\n fieldValues(data, field).map((value) => collapseSpaces(foldText(value))),\n );\n\n return plan.terms.every(\n ({ words: termWords, phrase }) =>\n termWords.every((word) => words.some((w) => w.startsWith(word))) &&\n (!phrase || values.some((value) => value.includes(phrase))),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACJZ,SAAS,SAAS;;;ACMX,IAAM,oBAAoB;AAO1B,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIA,IAAM,kBAAkB;AAExB,IAAM,WAAW;AACjB,IAAM,QAAQ,WAAC,UAAM,IAAE;AAWhB,SAAS,SAAS,MAAsB;AAC7C,SAAO,KAAK,UAAU,MAAM,EAAE,QAAQ,OAAO,EAAE,EAAE,YAAY;AAC/D;AAMO,SAAS,WAAW,MAAwB;AACjD,SAAO,SAAS,IAAI,EAAE,MAAM,QAAQ,EAAE,OAAO,O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