monorise 1.15.0-dev.0 → 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.
@@ -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,222 +647,72 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
590
647
  allowLegacyWhere?: boolean;
591
648
  }
592
649
 
650
+ declare const DEFAULT_MAX_WORDS = 8;
593
651
  /**
594
- * @description An access level used as shorthand.
595
- * - On a policy, it applies to every entity and every relationship.
596
- * - On an entity, it grants every field, every tag, listing and, by default,
597
- * every relationship from that entity at that level.
598
- * - On a relationship, it grants every `mutualData` field at that level.
599
- *
600
- * `'write'` means read, create, update and delete.
601
- */
602
- type ApiKeyAccessLevel = 'none' | 'read' | 'write';
603
- /**
604
- * @description System fields a create payload may set only when the create
605
- * list names them: `$entityId` for a caller-chosen `entityId`, `$createdAt`
606
- * for a backdated `createdAt`.
607
- */
608
- type ApiKeySystemField = '$entityId' | '$createdAt';
609
- /** `'*'` for every field, present and future, or an allowlist. */
610
- type ApiKeyFieldList<F extends string = string> = '*' | F[];
611
- type EntityField<T extends Entity> = Extract<keyof DraftEntity<T>, string>;
612
- /**
613
- * @description Each entity type's tag names. The CLI augments this from the
614
- * entity configs, so `tags` in a policy accepts only real tag names.
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.
615
655
  */
616
- interface ApiKeyEntityTags {
617
- }
618
- /**
619
- * @description The `mutualData` field names of each direction whose pair has
620
- * a mutual config. The CLI augments this from the entity configs, so a
621
- * relationship grant's field lists accept only real `mutualData` fields.
622
- */
623
- interface ApiKeyMutualDataFields {
624
- }
625
- type TagName<T extends Entity> = T extends keyof ApiKeyEntityTags ? Extract<ApiKeyEntityTags[T], string> : string;
626
- type MutualDataField<A extends Entity, B extends Entity> = A extends keyof ApiKeyMutualDataFields ? B extends keyof ApiKeyMutualDataFields[A] ? Extract<ApiKeyMutualDataFields[A][B], string> : string : string;
627
- /**
628
- * @description Access to one direction of a relationship, e.g. learner→course
629
- * (`/mutual/learner/:id/course`). Field lists name `mutualData` fields.
630
- */
631
- type ApiKeyMutualGrant<A extends Entity = Entity, B extends Entity = Entity> = ApiKeyAccessLevel | {
632
- read?: ApiKeyFieldList<MutualDataField<A, B>>;
633
- create?: ApiKeyFieldList<MutualDataField<A, B>>;
634
- update?: ApiKeyFieldList<MutualDataField<A, B>>;
635
- /** Same as `create` and `update` with this list. */
636
- write?: ApiKeyFieldList<MutualDataField<A, B>>;
637
- delete?: boolean;
638
- };
639
- /**
640
- * @description Access to one entity type.
641
- *
642
- * A shorthand string is broad: every field, every tag and every relationship
643
- * from this entity at that level. An object is exact: only what it lists.
644
- * Any write grant implies read on the same fields.
645
- */
646
- type ApiKeyEntityGrant<T extends Entity = Entity> = ApiKeyAccessLevel | {
647
- /** Fields the key can read: get by ID or unique field, and every response's masking. */
648
- read?: ApiKeyFieldList<EntityField<T>>;
649
- /**
650
- * Also list the whole type: `GET /entity/:type`, search and tag
651
- * queries. Get only needs a reference to a record; listing needs none,
652
- * so an object grant lists only when it says so.
653
- */
654
- list?: boolean;
655
- /** Must include every field `createSchema` requires. */
656
- create?: ApiKeyFieldList<EntityField<T> | ApiKeySystemField>;
657
- update?: ApiKeyFieldList<EntityField<T>>;
658
- /** Same as `create` and `update` with this list. */
659
- write?: ApiKeyFieldList<EntityField<T> | ApiKeySystemField>;
660
- delete?: boolean;
661
- /** Defaults to every tag when `read` is `'*'`, otherwise to none. */
662
- tags?: ApiKeyFieldList<TagName<T>>;
663
- /**
664
- * Relationships from this entity, keyed by the target entity type. An
665
- * entry covers one direction only: `[Entity.COURSE]` under learner is
666
- * learner→course and says nothing about course→learner. `'*'` sets the
667
- * level for every direction without an entry; it defaults to `'none'`.
668
- */
669
- mutuals?: {
670
- '*'?: ApiKeyAccessLevel;
671
- } & {
672
- [O in Entity]?: ApiKeyMutualGrant<T, O>;
673
- };
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[];
674
664
  };
675
665
  /**
676
- * @description A policy. The shorthands `'read'` and `'write'` apply to every
677
- * entity and relationship, and grant no custom routes.
666
+ * @description Lowercases and strips accents, so "José" and "jose" match.
678
667
  */
679
- type ApiKeyPolicy = 'read' | 'write' | {
680
- entities?: {
681
- '*'?: ApiKeyAccessLevel;
682
- } & {
683
- [T in Entity]?: ApiKeyEntityGrant<T>;
684
- };
685
- /**
686
- * Custom route permissions this policy grants: the names custom routes
687
- * declare with `requires(...)`. A custom route without `requires(...)`
688
- * is callable only by `full` keys.
689
- */
690
- routes?: string[];
691
- };
668
+ declare function foldText(text: string): string;
692
669
  /**
693
- * @description Every custom route permission the project's policies grant.
694
- * The CLI augments it from the policies, so `requires()` accepts only names
695
- * some policy grants.
670
+ * @description Splits on anything that isn't a letter or digit:
671
+ * "example@mail.com" becomes ["example", "mail", "com"].
696
672
  */
697
- interface ApiKeyRoutePermissions {
698
- }
699
- /** A custom route permission name; any string until the CLI augments `ApiKeyRoutePermissions`. */
700
- type ApiKeyRoutePermission = keyof ApiKeyRoutePermissions extends never ? string : Extract<keyof ApiKeyRoutePermissions, string>;
673
+ declare function splitWords(text: string): string[];
701
674
  /**
702
- * @description Policies keyed by name. `API_KEYS` maps these names to keys.
703
- * `full` is built in and cannot be redefined.
675
+ * @description An entity's `search` config with the `monorise.config.ts`
676
+ * settings and built-in defaults filled in.
704
677
  */
705
- type ApiKeyPolicies = Record<string, ApiKeyPolicy>;
706
-
678
+ declare function resolveSearchConfig(search: SearchConfig<PropertyKey>, defaults?: SearchSettings): ResolvedSearchConfig;
707
679
  /**
708
- * @description Built-in policy: read, write and delete on every entity and
709
- * relationship, plus every custom route. Every key in the legacy array form of
710
- * `API_KEYS` maps to it.
680
+ * @description Throws on settings the index can't use. `where` names the
681
+ * config in the message.
711
682
  */
712
- declare const FULL_API_KEY_POLICY = "full";
713
- /** `'*'` for every field, or the allowed fields. */
714
- type ApiKeyFieldAccess = '*' | ReadonlySet<string>;
715
- /** What a policy allows on one entity type. `null` means not granted. */
716
- type ApiKeyEntityAccess = {
717
- /**
718
- * Whether the key can see the type at all: the policy grants it anything
719
- * but `'none'`, by name or through its `'*'` entry. A type the key can't
720
- * see answers 404, as if it didn't exist.
721
- */
722
- visible: boolean;
723
- /** Fields the key can read, by ID or unique field, and in every response. */
724
- read: ApiKeyFieldAccess | null;
725
- /** Whether the key can list the whole type: listing, search and tag queries. */
726
- list: boolean;
727
- create: ApiKeyFieldAccess | null;
728
- update: ApiKeyFieldAccess | null;
729
- delete: boolean;
730
- tags: ApiKeyFieldAccess | null;
731
- };
732
- /** What a policy allows on one direction of a relationship. Fields are `mutualData` fields. */
733
- type ApiKeyMutualAccess = {
734
- read: ApiKeyFieldAccess | null;
735
- create: ApiKeyFieldAccess | null;
736
- update: ApiKeyFieldAccess | null;
737
- delete: boolean;
738
- };
739
- type CompiledApiKeyPolicy = {
740
- name: string;
741
- /** True only for the built-in `full` policy. */
742
- full: boolean;
743
- entity(entityType: string): ApiKeyEntityAccess;
744
- /**
745
- * Access to the direction `byEntityType`→`entityType`, as in
746
- * `/mutual/:byEntityType/:byEntityId/:entityType`. `null` when either end
747
- * type isn't visible.
748
- */
749
- mutual(byEntityType: string, entityType: string): ApiKeyMutualAccess | null;
750
- /** Whether the policy grants a custom route permission. `full` grants every one. */
751
- allowsRoute(permission: string): boolean;
752
- };
683
+ declare function validateSearchSettings(settings: SearchSettings, where: string): void;
753
684
  /**
754
- * @description Compiles a policy into the access it grants. Compiled entity
755
- * grants are cached, so compile once per policy and reuse the result.
756
- *
757
- * `name === 'full'` compiles the built-in policy and ignores `policy`.
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).
758
687
  */
759
- declare const compileApiKeyPolicy: (name: string, policy?: ApiKeyPolicy) => CompiledApiKeyPolicy;
688
+ declare function searchConfigHash(config: ResolvedSearchConfig): string;
760
689
  /**
761
- * @description The parts of an entity config that policy validation reads.
762
- * Any config built by `createEntityConfig` satisfies it. Configs are keyed by
763
- * entity type.
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.
764
694
  */
765
- type ApiKeyPolicyEntityConfig = {
766
- baseSchema: z.AnyZodObject;
767
- createSchema?: z.AnyZodObject;
768
- tags?: {
769
- name: string;
770
- }[];
771
- mutual?: {
772
- mutualSchema?: z.AnyZodObject;
773
- createMutualSchema?: z.AnyZodObject;
774
- mutualFields?: Record<string, {
775
- entityType: string | Entity;
776
- mutual?: {
777
- mutualDataSchema?: z.AnyZodObject;
778
- asEntity?: {
779
- name: string | Entity;
780
- };
781
- };
782
- }>;
783
- };
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[];
784
706
  };
785
707
  /**
786
- * @description Checks policies against the entity configs. Returns one message
787
- * per problem; an empty array means the policies are valid. The CLI runs this
788
- * at build time and the API handler at cold start.
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.
789
711
  */
790
- declare const validateApiKeyPolicies: (policies: unknown, entityConfigs: Record<string, ApiKeyPolicyEntityConfig>) => string[];
712
+ declare function planSearch(query: string, ignoreWords: readonly string[]): SearchPlan;
791
713
  /**
792
- * @description Declares the API key policies. Export the result as the default
793
- * export of the file `apiKeys` points to in `monorise.config.ts`; `API_KEYS`
794
- * then maps each policy name to its keys. `full` is built in.
795
- *
796
- * @example
797
- * ```ts
798
- * export default defineApiKeyPolicies({
799
- * 'agent-read': 'read',
800
- * client: {
801
- * entities: {
802
- * [Entity.ORDER]: { read: '*', create: ['customerId', 'items'], update: ['status'] },
803
- * [Entity.PRODUCT]: 'read',
804
- * },
805
- * },
806
- * });
807
- * ```
714
+ * @description Whether an entity's data matches a planned query.
808
715
  */
809
- declare const defineApiKeyPolicies: (policies: ApiKeyPolicies) => ApiKeyPolicies;
716
+ declare function matchesSearch(data: Record<string, unknown> | undefined, plan: SearchPlan, config: ResolvedSearchConfig): boolean;
810
717
 
811
- export { type AdjustmentCondition, type AdjustmentConditionFn, type ApiKeyAccessLevel, type ApiKeyEntityAccess, type ApiKeyEntityGrant, type ApiKeyEntityTags, type ApiKeyFieldAccess, type ApiKeyFieldList, type ApiKeyMutualAccess, type ApiKeyMutualDataFields, type ApiKeyMutualGrant, type ApiKeyPolicies, type ApiKeyPolicy, type ApiKeyPolicyEntityConfig, type ApiKeyRoutePermission, type ApiKeyRoutePermissions, type ApiKeySystemField, type CompiledApiKeyPolicy, type CreatedEntity, type DraftEntity, Entity, type EntitySchemaMap, FULL_API_KEY_POLICY, type MonoriseEntityConfig, type MutualConfig, type MutualConfigInput, type NumericFields, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, compileApiKeyPolicy, createEntityConfig, createMutualConfig, defineApiKeyPolicies, resolveEffectiveMutualSchema, validateApiKeyPolicies };
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 };