@flumens/models 0.29.1 → 0.30.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.
@@ -1,19 +1,16 @@
1
+ import { IObservableArray } from 'mobx';
1
2
  import { Deferred } from '@flumens/utils';
2
3
  import ModelClass from './Model';
3
- import Store from './Stores/Store';
4
- interface IObservableArray<T = any> extends Array<T> {
5
- spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[];
6
- clear(): T[];
7
- replace(newItems: T[]): T[];
8
- remove(value: T): boolean;
9
- toJSON(): T[];
10
- }
4
+ export type ModelConstructor<T extends ModelClass> = new (...args: never[]) => T;
5
+ type CollectionStore = {
6
+ findAll(query?: unknown): Promise<unknown[]>;
7
+ };
11
8
  export type Options<T extends ModelClass> = {
12
9
  data?: T[];
13
10
  id?: string;
14
11
  cid?: string;
15
- store?: Store;
16
- Model?: any;
12
+ store?: CollectionStore;
13
+ Model?: ModelConstructor<T>;
17
14
  };
18
15
  export default class Collection<T extends ModelClass> {
19
16
  /**
@@ -33,16 +30,16 @@ export default class Collection<T extends ModelClass> {
33
30
  /**
34
31
  * The offline store used to save and fetch the model from.
35
32
  */
36
- protected store?: Store;
33
+ protected store?: CollectionStore;
37
34
  /**
38
35
  * A promise to flag if all the models were initialised from the store.
39
36
  */
40
37
  readonly ready: Deferred<boolean>;
41
- Model: new (args: any) => T;
42
- constructor({ id, cid, data, store, Model }: Options<T>);
38
+ Model: ModelConstructor<T>;
39
+ constructor({ id, cid, data, store, Model, }: Options<T>);
43
40
  fetch(): Promise<void>;
44
41
  reset(): Promise<void>;
45
- filter(predicate: (value: T, index: number, array: T[]) => any): T[];
42
+ filter(predicate: (value: T, index: number, array: T[]) => unknown): T[];
46
43
  push(...items: T[]): number;
47
44
  pop(): T | undefined;
48
45
  find(predicate: (value: T, index: number, obj: T[]) => unknown): T | undefined;
@@ -33,7 +33,7 @@ export interface Data extends GenericModelData {
33
33
  /** A flag that is set when the full profile is downloaded. */
34
34
  profileFetched?: boolean;
35
35
  }
36
- export interface Options extends GenericModelOptions {
36
+ export interface Options<T extends Data = Data> extends GenericModelOptions<T> {
37
37
  /**
38
38
  * Drupal site config.
39
39
  */
@@ -44,65 +44,31 @@ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
44
44
  static loginSchema: z.ZodObject<{
45
45
  email: z.ZodString;
46
46
  password: z.ZodString;
47
- }, "strip", z.ZodTypeAny, {
48
- email: string;
49
- password: string;
50
- }, {
51
- email: string;
52
- password: string;
53
- }>;
47
+ }, z.core.$strip>;
54
48
  static loginSchemaBackend: z.ZodObject<{
55
49
  id: z.ZodNumber;
56
50
  email: z.ZodString;
57
- }, "strip", z.ZodTypeAny, {
58
- id: number;
59
- email: string;
60
- }, {
61
- id: number;
62
- email: string;
63
- }>;
51
+ }, z.core.$strip>;
64
52
  static resetSchema: z.ZodObject<{
65
53
  email: z.ZodString;
66
- }, "strip", z.ZodTypeAny, {
67
- email: string;
68
- }, {
69
- email: string;
70
- }>;
54
+ }, z.core.$strip>;
71
55
  static registerSchema: z.ZodObject<{
72
56
  email: z.ZodString;
73
57
  password: z.ZodString;
74
- }, "strip", z.ZodTypeAny, {
75
- email: string;
76
- password: string;
77
- }, {
78
- email: string;
79
- password: string;
80
- }>;
58
+ }, z.core.$strip>;
81
59
  static registerSchemaBackend: z.ZodObject<{
82
60
  uid: z.ZodArray<z.ZodObject<{
83
61
  value: z.ZodNumber;
84
- }, "strip", z.ZodTypeAny, {
85
- value: number;
86
- }, {
87
- value: number;
88
- }>, "many">;
89
- }, "strip", z.ZodTypeAny, {
90
- uid: {
91
- value: number;
92
- }[];
93
- }, {
94
- uid: {
95
- value: number;
96
- }[];
97
- }>;
62
+ }, z.core.$strip>>;
63
+ }, z.core.$strip>;
98
64
  private _refreshingProfilePromise?;
99
65
  private _refreshingTokenPromise?;
100
- constructor({ config, ...options }: Options);
66
+ constructor({ config, ...options }: Options<T>);
101
67
  logIn(email: string, password: string): Promise<void>;
102
- register(email: string, password: string, otherFields: any): Promise<void>;
68
+ register(email: string, password: string, otherFields: Record<string, unknown>): Promise<void>;
103
69
  resetPassword(email: string): Promise<void>;
104
70
  delete(): Promise<void>;
105
- updateRemote(values: Record<string, any>): Promise<void>;
71
+ updateRemote(values: Record<string, unknown>): Promise<void>;
106
72
  /**
107
73
  * Gets full user profile inc. fresh new tokens.
108
74
  */
@@ -113,7 +79,7 @@ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
113
79
  hasLogIn(): boolean;
114
80
  isLoggedIn(): boolean;
115
81
  logOut(): Promise<void>;
116
- reset(defaultsToSet?: any): Promise<void>;
82
+ reset(defaultsToSet?: Partial<T>): Promise<void>;
117
83
  getAccessToken(forceRefresh?: boolean): Promise<string>;
118
84
  protected _sendVerificationEmail(email?: string): Promise<import("axios").AxiosResponse<any, any>>;
119
85
  private _exchangePasswordToTokens;
@@ -1,5 +1,5 @@
1
1
  interface Attribute {
2
- value: any;
2
+ value: unknown;
3
3
  id: string;
4
4
  }
5
5
  export interface Media {
@@ -77,14 +77,14 @@ interface Metadata {
77
77
  interface AutoChecks {
78
78
  result: string;
79
79
  enabled: string;
80
- output: any[];
80
+ output: unknown[];
81
81
  }
82
82
  interface Verifier {
83
83
  id: string;
84
84
  name: string;
85
85
  }
86
86
  export type VerifiedStates = 'C' | 'V' | 'R';
87
- interface Identification {
87
+ export interface Identification {
88
88
  verification_status: VerifiedStates;
89
89
  auto_checks: AutoChecks;
90
90
  query?: 'Q';
@@ -1,5 +1,5 @@
1
1
  interface Attribute {
2
- value: any;
2
+ value: unknown;
3
3
  id: string;
4
4
  }
5
5
  export interface Media {
@@ -6,49 +6,31 @@ export declare const dtoSchema: z.ZodObject<{
6
6
  createdOn: z.ZodString;
7
7
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
8
  groupType: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
- joiningMethod: z.ZodOptional<z.ZodNullable<z.ZodEnum<["P", "R", "A", "I"]>>>;
9
+ joiningMethod: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
10
+ R: "R";
11
+ P: "P";
12
+ I: "I";
13
+ A: "A";
14
+ }>>>;
10
15
  websiteId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
11
16
  groupTypeId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
17
  createdById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
13
18
  fromDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
14
19
  toDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
15
- indexedLocationIds: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNumber, "many">>>;
16
- userIsAdministrator: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
17
- userIsMember: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
18
- userIsPending: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
19
- }, "strip", z.ZodTypeAny, {
20
- id: string;
21
- title: string;
22
- createdOn: string;
23
- description?: string | null | undefined;
24
- groupType?: string | null | undefined;
25
- joiningMethod?: "R" | "P" | "I" | "A" | null | undefined;
26
- websiteId?: string | null | undefined;
27
- groupTypeId?: string | null | undefined;
28
- createdById?: string | null | undefined;
29
- fromDate?: string | null | undefined;
30
- toDate?: string | null | undefined;
31
- indexedLocationIds?: number[] | null | undefined;
32
- userIsAdministrator?: "t" | "f" | null | undefined;
33
- userIsMember?: "t" | "f" | null | undefined;
34
- userIsPending?: "t" | "f" | null | undefined;
35
- }, {
36
- id: string;
37
- title: string;
38
- createdOn: string;
39
- description?: string | null | undefined;
40
- groupType?: string | null | undefined;
41
- joiningMethod?: "R" | "P" | "I" | "A" | null | undefined;
42
- websiteId?: string | null | undefined;
43
- groupTypeId?: string | null | undefined;
44
- createdById?: string | null | undefined;
45
- fromDate?: string | null | undefined;
46
- toDate?: string | null | undefined;
47
- indexedLocationIds?: number[] | null | undefined;
48
- userIsAdministrator?: "t" | "f" | null | undefined;
49
- userIsMember?: "t" | "f" | null | undefined;
50
- userIsPending?: "t" | "f" | null | undefined;
51
- }>;
20
+ indexedLocationIds: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNumber>>>;
21
+ userIsAdministrator: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
22
+ t: "t";
23
+ f: "f";
24
+ }>>>;
25
+ userIsMember: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
26
+ t: "t";
27
+ f: "f";
28
+ }>>>;
29
+ userIsPending: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
30
+ t: "t";
31
+ f: "f";
32
+ }>>>;
33
+ }, z.core.$strip>;
52
34
  declare const locationDTOSchema: z.ZodObject<{
53
35
  id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
54
36
  createdOn: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -69,50 +51,10 @@ declare const locationDTOSchema: z.ZodObject<{
69
51
  locationUpdatedById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
52
  locationComment: z.ZodOptional<z.ZodNullable<z.ZodString>>;
71
53
  locationExternalKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
72
- }, "strip", z.ZodTypeAny, {
73
- locationId: string;
74
- locationName: string;
75
- locationBoundaryGeom: string;
76
- locationLat: string;
77
- locationLon: string;
78
- locationCreatedOn: string;
79
- locationUpdatedOn: string;
80
- locationCentroidSref: string;
81
- locationCentroidSrefSystem: string;
82
- id?: string | null | undefined;
83
- createdOn?: string | null | undefined;
84
- createdById?: string | null | undefined;
85
- groupId?: string | null | undefined;
86
- groupTitle?: string | null | undefined;
87
- locationCode?: string | null | undefined;
88
- locationCreatedById?: string | null | undefined;
89
- locationUpdatedById?: string | null | undefined;
90
- locationComment?: string | null | undefined;
91
- locationExternalKey?: string | null | undefined;
92
- }, {
93
- locationId: string;
94
- locationName: string;
95
- locationBoundaryGeom: string;
96
- locationLat: string;
97
- locationLon: string;
98
- locationCreatedOn: string;
99
- locationUpdatedOn: string;
100
- locationCentroidSref: string;
101
- locationCentroidSrefSystem: string;
102
- id?: string | null | undefined;
103
- createdOn?: string | null | undefined;
104
- createdById?: string | null | undefined;
105
- groupId?: string | null | undefined;
106
- groupTitle?: string | null | undefined;
107
- locationCode?: string | null | undefined;
108
- locationCreatedById?: string | null | undefined;
109
- locationUpdatedById?: string | null | undefined;
110
- locationComment?: string | null | undefined;
111
- locationExternalKey?: string | null | undefined;
112
- }>;
54
+ }, z.core.$strip>;
113
55
  type LocationDTO = z.infer<typeof locationDTOSchema>;
114
56
  export type LocationData = LocationDTO;
115
- export interface Options<T = any> extends OptionsOriginal<T> {
57
+ export interface Options<T extends Data = Data> extends OptionsOriginal<T> {
116
58
  skipStore?: boolean;
117
59
  url?: string;
118
60
  getAccessToken?: () => Promise<string>;
@@ -128,7 +70,7 @@ declare class Group<T extends Data = Data> extends Model<T> {
128
70
  getAccessToken?: () => Promise<string>;
129
71
  getIndiciaUserId?: () => Promise<string | number>;
130
72
  };
131
- constructor({ skipStore, store, url, getAccessToken, getIndiciaUserId, ...options }: Options);
73
+ constructor({ skipStore, store, url, getAccessToken, getIndiciaUserId, ...options }: Options<T>);
132
74
  join(): Promise<void>;
133
75
  leave(): Promise<void>;
134
76
  addRemoteLocation(locationId: string | number): Promise<this>;
@@ -1,23 +1,14 @@
1
1
  import { IObservableArray } from 'mobx';
2
2
  import { z } from 'zod';
3
3
  import Model, { Options as OptionsOriginal, Data as ModelData } from '../Model';
4
- import Media from './Media';
4
+ import Media, { MediaConstructor, WarehouseMediaNames } from './Media';
5
5
  export declare const dtoSchema: z.ZodObject<{
6
6
  lat: z.ZodString;
7
7
  lon: z.ZodString;
8
- /**
9
- * Location name.
10
- */
11
8
  name: z.ZodString;
12
- /**
13
- * Location type e.g. transect = 777, transect section = 778 etc.
14
- */
15
9
  locationTypeId: z.ZodString;
16
10
  centroidSref: z.ZodString;
17
11
  centroidSrefSystem: z.ZodString;
18
- /**
19
- * Entity ID.
20
- */
21
12
  id: z.ZodOptional<z.ZodString>;
22
13
  createdOn: z.ZodOptional<z.ZodString>;
23
14
  updatedOn: z.ZodOptional<z.ZodString>;
@@ -30,45 +21,7 @@ export declare const dtoSchema: z.ZodObject<{
30
21
  centroidGeom: z.ZodOptional<z.ZodNullable<z.ZodString>>;
31
22
  public: z.ZodOptional<z.ZodNullable<z.ZodString>>;
32
23
  comment: z.ZodOptional<z.ZodNullable<z.ZodString>>;
33
- }, "strip", z.ZodTypeAny, {
34
- name: string;
35
- lat: string;
36
- lon: string;
37
- locationTypeId: string;
38
- centroidSref: string;
39
- centroidSrefSystem: string;
40
- id?: string | undefined;
41
- code?: string | null | undefined;
42
- parentId?: string | null | undefined;
43
- createdOn?: string | undefined;
44
- createdById?: string | null | undefined;
45
- updatedOn?: string | undefined;
46
- boundaryGeom?: string | null | undefined;
47
- updatedById?: string | null | undefined;
48
- externalKey?: string | null | undefined;
49
- centroidGeom?: string | null | undefined;
50
- public?: string | null | undefined;
51
- comment?: string | null | undefined;
52
- }, {
53
- name: string;
54
- lat: string;
55
- lon: string;
56
- locationTypeId: string;
57
- centroidSref: string;
58
- centroidSrefSystem: string;
59
- id?: string | undefined;
60
- code?: string | null | undefined;
61
- parentId?: string | null | undefined;
62
- createdOn?: string | undefined;
63
- createdById?: string | null | undefined;
64
- updatedOn?: string | undefined;
65
- boundaryGeom?: string | null | undefined;
66
- updatedById?: string | null | undefined;
67
- externalKey?: string | null | undefined;
68
- centroidGeom?: string | null | undefined;
69
- public?: string | null | undefined;
70
- comment?: string | null | undefined;
71
- }>;
24
+ }, z.core.$strip>;
72
25
  export type Metadata = {
73
26
  saved?: boolean;
74
27
  groupId?: string;
@@ -83,10 +36,10 @@ export declare enum LocationType {
83
36
  }
84
37
  export type DTO = z.infer<typeof dtoSchema>;
85
38
  export type Data = Omit<DTO, 'createdOn' | 'updatedOn'> & ModelData;
86
- export interface Options<T = Data, S = Metadata> extends OptionsOriginal<T> {
39
+ export interface Options<T extends Data = Data, S extends Metadata = Metadata> extends OptionsOriginal<T> {
87
40
  metadata?: S;
88
- media?: any[];
89
- Media?: typeof Media<any, any>;
41
+ media?: (Media | Record<string, unknown>)[];
42
+ Media?: MediaConstructor;
90
43
  skipStore?: boolean;
91
44
  url?: string;
92
45
  getAccessToken?: () => Promise<string>;
@@ -98,7 +51,7 @@ declare class Location<T extends Data = Data, S extends Metadata = Metadata> ext
98
51
  url?: string;
99
52
  getAccessToken?: () => Promise<string>;
100
53
  };
101
- Media: typeof Media<any, any>;
54
+ Media: MediaConstructor;
102
55
  media: IObservableArray<Media>;
103
56
  /**
104
57
  * Model persistent observable metadata.
@@ -106,8 +59,11 @@ declare class Location<T extends Data = Data, S extends Metadata = Metadata> ext
106
59
  metadata: S;
107
60
  constructor({ skipStore, store, media, metadata, url, getAccessToken, Media: MediaClass, ...options }?: Options<T, S>);
108
61
  saveRemote(): Promise<this>;
109
- toDTO(warehouseMediaNames?: {}): any;
110
- protected uploadMedia(): Promise<any>;
62
+ toDTO(warehouseMediaNames?: WarehouseMediaNames): {
63
+ values: Record<string, unknown>;
64
+ media: unknown[];
65
+ };
66
+ protected uploadMedia(): Promise<WarehouseMediaNames>;
111
67
  get isUploaded(): boolean;
112
68
  get isSynchronising(): boolean;
113
69
  get isDraft(): boolean;
@@ -1,6 +1,6 @@
1
1
  import Collection, { Options as BaseOptions } from '../Collection';
2
2
  import Location, { LocationType } from './Location';
3
- type RemoteFetchParams = any;
3
+ type RemoteFetchParams = Record<string, unknown>;
4
4
  export interface Options<T extends Location> extends BaseOptions<T> {
5
5
  url?: string | null;
6
6
  getAccessToken: () => Promise<string>;
@@ -1,18 +1,23 @@
1
1
  import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
2
+ import type Location from './Location';
2
3
  import Occurrence from './Occurrence';
3
4
  import Sample from './Sample';
4
5
  export interface Metadata {
6
+ createdOn?: number;
7
+ updatedOn?: number;
8
+ syncedOn?: number;
9
+ [key: string]: unknown;
5
10
  }
6
11
  export type DataURI = string;
7
12
  export type URL = string;
8
- export interface Options<T = any, S = any> extends OptionsOriginal<T> {
13
+ export interface Options<T extends Data = Data, S extends Metadata = Metadata> extends OptionsOriginal<T> {
9
14
  metadata?: S;
10
15
  url?: string;
11
16
  getAccessToken?: () => Promise<string>;
12
17
  }
13
18
  export interface Data extends DataOriginal {
14
19
  type?: string;
15
- data?: any;
20
+ data?: string;
16
21
  thumbnail?: DataURI;
17
22
  queued?: string | null;
18
23
  path?: string | null;
@@ -26,6 +31,14 @@ export interface Remote {
26
31
  getAccessToken?: () => Promise<string>;
27
32
  timeout?: number;
28
33
  }
34
+ type ResizeResult = [image: HTMLImageElement, dataURI: DataURI];
35
+ export type FormDataEntry = [name: string, blob: Blob, fileName: string];
36
+ export type WarehouseMediaNames = Record<string, {
37
+ name: string;
38
+ }>;
39
+ type Submission = {
40
+ values: Record<string, unknown>;
41
+ };
29
42
  declare class Media<T extends Data = Data, S extends Metadata = Metadata> extends Model<T> {
30
43
  /**
31
44
  * Transforms and resizes an image file into a string.
@@ -36,7 +49,10 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
36
49
  * @param onSaveSuccess
37
50
  * @returns {number}
38
51
  */
39
- static getDataURI(file: any, options?: any): Promise<[
52
+ static getDataURI(file: string | Blob, options?: {
53
+ width?: number;
54
+ height?: number;
55
+ }): Promise<[
40
56
  dataURI: DataURI,
41
57
  fileType: string,
42
58
  width: number,
@@ -45,7 +61,7 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
45
61
  /**
46
62
  * http://stackoverflow.com/questions/2516117/how-to-scale-an-image-in-data-uri-format-in-javascript-real-scaling-not-usin
47
63
  */
48
- static resize(data: URL | DataURI, fileType: string, MAX_WIDTH?: number, MAX_HEIGHT?: number): Promise<unknown>;
64
+ static resize(data: URL | DataURI, fileType: string, MAX_WIDTH?: number, MAX_HEIGHT?: number): Promise<ResizeResult>;
49
65
  /**
50
66
  * Create new image model with a photo
51
67
  * @param ImageModel Class representing the model.
@@ -61,19 +77,19 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
61
77
  };
62
78
  metadata: S;
63
79
  debouncedValue: number;
64
- constructor({ metadata, ...options }?: Options);
65
- parent?: Sample | Occurrence;
80
+ constructor({ metadata, ...options }?: Options<NoInfer<T>, NoInfer<S>>);
81
+ parent?: Sample | Occurrence | Location;
66
82
  toJSON(): any;
67
83
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
68
- toDTO(warehouseMediaNames?: any): any;
84
+ toDTO(warehouseMediaNames?: WarehouseMediaNames): Submission;
69
85
  sync(): Promise<void>;
70
86
  uploadFile(force?: boolean): Promise<void>;
71
- getFormData(): Promise<unknown[]>;
87
+ getFormData(): Promise<FormDataEntry>;
72
88
  getRemoteURL(): string;
73
89
  /**
74
90
  * Returns image's absolute URL or dataURI.
75
91
  */
76
- getURL(): any;
92
+ getURL(): string;
77
93
  /**
78
94
  * Resizes itself.
79
95
  */
@@ -90,4 +106,5 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
90
106
  get isDisabled(): boolean;
91
107
  get isSynchronising(): boolean;
92
108
  }
109
+ export type MediaConstructor = new (...args: never[]) => Media;
93
110
  export default Media;
@@ -1,16 +1,20 @@
1
1
  import { IObservableArray } from 'mobx';
2
2
  import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
3
3
  import ElasticOccurrenceDTO from './ElasticOccurrence';
4
- import Media from './Media';
5
- import Sample from './Sample';
4
+ import Media, { MediaConstructor, WarehouseMediaNames } from './Media';
5
+ import Sample, { type Submission } from './Sample';
6
6
  import { RemoteConfig, Keys } from './helpers';
7
7
  export { RemoteConfig };
8
8
  export interface Metadata {
9
+ createdOn?: number;
10
+ updatedOn?: number;
11
+ syncedOn?: number;
12
+ [key: string]: unknown;
9
13
  }
10
- export interface Options<T = any, S = any> extends OptionsOriginal<T> {
14
+ export interface Options<T extends Data = Data, S extends Metadata = Metadata> extends OptionsOriginal<T> {
11
15
  metadata?: S;
12
- media?: any[];
13
- Media?: typeof Media<any, any>;
16
+ media?: (Media | Record<string, unknown>)[];
17
+ Media?: MediaConstructor;
14
18
  }
15
19
  export interface Data extends DataOriginal {
16
20
  training?: boolean;
@@ -50,13 +54,37 @@ export interface Data extends DataOriginal {
50
54
  */
51
55
  sensitivityPrecision?: '' | 100 | 1000 | 2000 | 10000 | 100000;
52
56
  comment?: string;
53
- taxon?: any;
57
+ taxon?: Record<string, unknown>;
54
58
  }
55
- export default class Occurrence<T extends Data = Data, S extends Metadata = Metadata> extends Model {
59
+ export default class Occurrence<T extends Data = Data, S extends Metadata = Metadata> extends Model<T> {
56
60
  /**
57
61
  * Transform ES document into local model.
58
62
  */
59
- static fromElasticDTO(dto: ElasticOccurrenceDTO, remoteUrl: string, survey: any): Occurrence<Data, Metadata>;
63
+ static fromElasticDTO(dto: ElasticOccurrenceDTO, remoteUrl: string, survey: {
64
+ smp?: {
65
+ occ?: {
66
+ attrs?: Record<string, RemoteConfig & {
67
+ remote?: RemoteConfig;
68
+ }>;
69
+ };
70
+ };
71
+ occ?: {
72
+ attrs?: Record<string, RemoteConfig & {
73
+ remote?: RemoteConfig;
74
+ }>;
75
+ };
76
+ }): Occurrence<{
77
+ taxaTaxonListId: number;
78
+ taxon: {
79
+ warehouseId: number;
80
+ scientificName: string;
81
+ commonName: string;
82
+ foundInName: string;
83
+ };
84
+ comment: string | undefined;
85
+ }, {
86
+ verification: import("./ElasticOccurrence").Identification;
87
+ }>;
60
88
  /**
61
89
  * Warehouse attributes and their values.
62
90
  */
@@ -65,13 +93,13 @@ export default class Occurrence<T extends Data = Data, S extends Metadata = Meta
65
93
  id: string;
66
94
  };
67
95
  };
68
- Media: typeof Media<any, any>;
96
+ Media: MediaConstructor;
69
97
  metadata: S;
70
98
  data: T;
71
99
  parent?: Sample;
72
100
  media: IObservableArray<Media>;
73
101
  debouncedValue: number;
74
- constructor({ metadata, media, Media: MediaClass, ...options }?: Options);
102
+ constructor({ metadata, media, Media: MediaClass, ...options }?: Options<T, S>);
75
103
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
76
104
  /**
77
105
  * Save the model to the offline store.
@@ -88,12 +116,11 @@ export default class Occurrence<T extends Data = Data, S extends Metadata = Meta
88
116
  toJSON(): any;
89
117
  keys: Keys;
90
118
  getSurvey(): {
91
- attrs?: {
92
- [key: string]: {
93
- remote?: RemoteConfig;
94
- };
95
- };
96
- modifySubmission?: (submission: any, model: any) => any;
119
+ attrs?: Record<string, {
120
+ remote?: RemoteConfig;
121
+ }>;
122
+ create?(options: unknown): unknown;
123
+ modifySubmission?(submission: unknown, model: unknown): unknown;
97
124
  };
98
125
  get isUploaded(): boolean;
99
126
  get isDisabled(): boolean;
@@ -101,5 +128,9 @@ export default class Occurrence<T extends Data = Data, S extends Metadata = Meta
101
128
  * Returns an object with attributes and their values
102
129
  * mapped for warehouse submission.
103
130
  */
104
- toDTO(warehouseMediaNames?: {}): any;
131
+ toDTO(warehouseMediaNames?: WarehouseMediaNames): Submission;
105
132
  }
133
+ export type OccurrenceConstructor = {
134
+ new (...args: never[]): Occurrence;
135
+ fromElasticDTO: typeof Occurrence.fromElasticDTO;
136
+ };
@@ -1,25 +1,39 @@
1
1
  import { IObservableArray } from 'mobx';
2
- import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
2
+ import Model, { Data as DataOriginal, Options as OptionsOriginal, Snapshot } from '../Model';
3
3
  import ElasticSampleDTO from './ElasticSample';
4
- import Media from './Media';
5
- import Occurrence from './Occurrence';
6
- import { RemoteConfig, Keys } from './helpers';
4
+ import Media, { FormDataEntry, MediaConstructor, WarehouseMediaNames } from './Media';
5
+ import Occurrence, { OccurrenceConstructor } from './Occurrence';
6
+ import { RemoteConfig, Keys, validateRemoteModel } from './helpers';
7
7
  export interface Metadata {
8
+ createdOn?: number;
9
+ updatedOn?: number;
10
+ syncedOn?: number;
11
+ [key: string]: unknown;
8
12
  }
9
13
  export { RemoteConfig };
10
14
  type ModelWithSubmodels = {
15
+ id?: string | number;
11
16
  occurrences?: Occurrence[];
12
17
  samples?: Sample[];
13
18
  media?: Media[];
14
19
  };
15
- export declare const getMediaFormData: (model: ModelWithSubmodels) => Promise<any[]>;
16
- export interface Options<T = any, S = any> extends OptionsOriginal<T> {
20
+ type RemoteResponse = {
21
+ values: {
22
+ id: string | number;
23
+ };
24
+ occurrences?: RemoteResponse[];
25
+ samples?: RemoteResponse[];
26
+ media?: RemoteResponse[];
27
+ };
28
+ type MediaFormData = [model: Media, formData: FormDataEntry];
29
+ export declare const getMediaFormData: (model: ModelWithSubmodels) => Promise<MediaFormData[]>;
30
+ export interface Options<T extends Data = Data, S extends Metadata = Metadata> extends OptionsOriginal<T> {
17
31
  metadata?: S;
18
- occurrences?: any[];
19
- samples?: any[];
20
- media?: any[];
21
- Occurrence?: typeof Occurrence<any, any>;
22
- Media?: typeof Media<any, any>;
32
+ occurrences?: (Occurrence | Record<string, unknown>)[];
33
+ samples?: (Sample<T, S> | Record<string, unknown>)[];
34
+ media?: (Media | Record<string, unknown>)[];
35
+ Occurrence?: OccurrenceConstructor;
36
+ Media?: MediaConstructor;
23
37
  skipStore?: boolean;
24
38
  url?: string;
25
39
  getAccessToken?: () => Promise<string>;
@@ -34,11 +48,11 @@ export interface Data extends DataOriginal {
34
48
  * Remote website survey edit page path.
35
49
  */
36
50
  inputForm?: string | null;
37
- date?: any;
51
+ date?: string | number | Date;
38
52
  sampleMethodId?: number;
39
53
  locationName?: string;
40
54
  enteredSref?: string;
41
- enteredSrefSystem: 'OSGB' | 'OSIE' | 'utm30ed50' | 4326;
55
+ enteredSrefSystem?: 'OSGB' | 'OSIE' | 'utm30ed50' | 4326;
42
56
  /**
43
57
  * Site the sample was linked to.
44
58
  */
@@ -56,13 +70,24 @@ export interface Data extends DataOriginal {
56
70
  training?: boolean;
57
71
  comment?: string;
58
72
  }
73
+ export type Submission = {
74
+ values: Record<string, unknown>;
75
+ media: {
76
+ values: Record<string, unknown>;
77
+ }[];
78
+ };
79
+ type ArrayMutator = 'copyWithin' | 'fill' | 'push' | 'remove' | 'replace' | 'splice' | 'spliceWithArray' | 'unshift';
80
+ export type ModelArray<T> = Omit<IObservableArray<T>, ArrayMutator> & Pick<IObservableArray<any>, ArrayMutator>;
81
+ type SampleSubmission = Submission & {
82
+ samples: SampleSubmission[];
83
+ occurrences: Submission[];
84
+ };
59
85
  type BaseSurvey = {
60
- attrs?: {
61
- [key: string]: {
62
- remote?: RemoteConfig;
63
- };
64
- };
65
- modifySubmission?: (submission: any, model: any) => any;
86
+ attrs?: Record<string, {
87
+ remote?: RemoteConfig;
88
+ }>;
89
+ create?(options: unknown): unknown;
90
+ modifySubmission?(submission: unknown, model: unknown): unknown;
66
91
  };
67
92
  export interface Survey extends BaseSurvey {
68
93
  smp?: Survey;
@@ -72,7 +97,7 @@ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> exten
72
97
  /**
73
98
  * Transform ES document into local model.
74
99
  */
75
- static fromElasticDTO(dto: ElasticSampleDTO, options?: Partial<Options>, survey?: any): Sample<Data, Metadata>;
100
+ static fromElasticDTO(dto: ElasticSampleDTO, options?: Partial<Options>, survey?: Survey): Sample<Data, Metadata>;
76
101
  /**
77
102
  * Warehouse attributes and their values.
78
103
  */
@@ -96,28 +121,35 @@ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> exten
96
121
  getAccessToken: () => Promise<string>;
97
122
  };
98
123
  protected survey?: Survey;
99
- Occurrence: typeof Occurrence<any, any>;
100
- Media: typeof Media<any, any>;
124
+ Occurrence: OccurrenceConstructor;
125
+ Media: MediaConstructor;
101
126
  /**
102
127
  * Model persistent observable metadata.
103
128
  */
104
129
  metadata: S;
105
- validateRemote: any;
130
+ validateRemote: typeof validateRemoteModel;
106
131
  error: {
107
132
  message: string;
108
133
  };
109
- collection?: any;
110
- samples: IObservableArray<Sample<T, S>>;
111
- occurrences: IObservableArray<Occurrence>;
112
- media: IObservableArray<Media>;
134
+ collection?: {
135
+ remove(sample: Sample): boolean;
136
+ };
137
+ samples: ModelArray<Sample<T, S>>;
138
+ occurrences: ModelArray<Occurrence>;
139
+ media: ModelArray<Media>;
113
140
  parent?: Sample<T, S>;
114
141
  debouncedValue: number;
115
- constructor({ metadata, samples, occurrences, media, Occurrence: OccurrenceClass, Media: MediaClass, skipStore, ...options }?: Options);
142
+ constructor({ metadata, samples, occurrences, media, Occurrence: OccurrenceClass, Media: MediaClass, skipStore, ...options }?: Options<T, S>);
116
143
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
117
144
  /**
118
145
  * Returns a clean (no observables) JSON representation of the model.
119
146
  */
120
- toJSON(): any;
147
+ toJSON(): Snapshot<T> & {
148
+ metadata: S;
149
+ occurrences: ReturnType<Occurrence['toJSON']>[];
150
+ samples: ReturnType<Sample<T, S>['toJSON']>[];
151
+ media: ReturnType<Media['toJSON']>[];
152
+ };
121
153
  keys: Keys;
122
154
  getSurvey(): Survey;
123
155
  /**
@@ -131,14 +163,18 @@ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> exten
131
163
  sync(): Promise<void>;
132
164
  requiresRemoteSync: () => boolean;
133
165
  saveRemote(): Promise<void>;
134
- protected postRemote(data: any): Promise<any>;
166
+ protected postRemote(data: Record<string, unknown>): Promise<RemoteResponse>;
135
167
  fetchRemote(): Promise<void>;
136
168
  updateRemote(): Promise<void>;
137
- protected putRemote(sampleId: string | number, data: any): Promise<any>;
138
- protected uploadMedia(): Promise<any>;
139
- toDTO(warehouseMediaNames?: {}): any;
169
+ protected putRemote(sampleId: string | number, data: Record<string, unknown>): Promise<RemoteResponse>;
170
+ protected uploadMedia(): Promise<WarehouseMediaNames>;
171
+ toDTO(warehouseMediaNames?: {}): SampleSubmission;
140
172
  get isUploaded(): boolean;
141
173
  get isDisabled(): boolean;
142
174
  get isSynchronising(): boolean;
143
175
  }
176
+ export type SampleConstructor<T extends Sample = Sample> = {
177
+ new (...args: never[]): T;
178
+ fromElasticDTO: typeof Sample.fromElasticDTO;
179
+ };
144
180
  export default Sample;
@@ -1,26 +1,24 @@
1
1
  import Collection, { Options as CollectionOptions } from '../Collection';
2
- import Store from '../Stores/Store';
3
- import Occurrence from './Occurrence';
4
- import Sample from './Sample';
2
+ import { OccurrenceConstructor } from './Occurrence';
3
+ import Sample, { SampleConstructor } from './Sample';
5
4
  export type Options<T extends Sample> = {
6
5
  models?: T[];
7
- store?: Store;
8
- Model?: typeof Sample<any, any>;
9
- Occurrence?: typeof Occurrence<any, any>;
6
+ Model?: SampleConstructor<T>;
7
+ Occurrence?: OccurrenceConstructor;
10
8
  url?: string;
11
9
  getAccessToken?: () => Promise<string>;
12
- } & CollectionOptions<T>;
10
+ } & Omit<CollectionOptions<T>, 'Model'>;
13
11
  export default class SampleCollection<T extends Sample> extends Collection<T> {
14
12
  protected remote: {
15
13
  synchronising: boolean;
16
14
  url: string;
17
15
  getAccessToken: () => Promise<string>;
18
16
  };
19
- Occurrence?: typeof Occurrence<any, any>;
17
+ Occurrence?: OccurrenceConstructor;
20
18
  constructor(options: Options<T>);
21
19
  fetch(): Promise<void>;
22
- fetchRemote(from: number, surveyIDs: any[]): Promise<T[]>;
23
- removeAllSynced(): Promise<any[]>;
20
+ fetchRemote(from: number, surveyIDs: (string | number)[]): Promise<T[]>;
21
+ removeAllSynced(): Promise<unknown[]>;
24
22
  reset(): Promise<void>;
25
23
  get isSynchronising(): boolean;
26
24
  }
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),r=require("../Collection.js"),a=require("./ElasticOccurrence.js"),i=require("./ElasticSample.js"),c=require("./Sample.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(s);class d extends r.default{constructor(e){super(Object.assign({id:"samples",Model:c.default},e)),this.Occurrence=e.Occurrence,this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken});t.observe(this.data,(e=>{e.addedCount&&e.added.forEach((e=>e.collection=this)),e.removedCount&&e.removed.forEach((e=>delete e.collection))}))}fetch(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.store||!this.Model)return void this.ready.resolve(!1);const e=(yield this.store.findAll()).map((e=>{const{data:t,metadata:s,occurrences:r,samples:a,media:i,attrs:c}=e.data;return new this.Model(Object.assign(Object.assign({},e),{attrs:c,data:t,metadata:s,occurrences:r,samples:a,media:i}))}));this.data.push(...e),this.ready.resolve(!0)}))}fetchRemote(t,s){return e.__awaiter(this,void 0,void 0,(function*(){console.log("Fetching remote samples, page",t);const e=[{bool:{should:s.map((e=>({match:{"metadata.survey.id":e}})))}},{bool:{must_not:{exists:{field:"event.parent_event_id"}}}},{match:{"metadata.trial":"false"}}],r=JSON.stringify({from:t,size:100,query:{bool:{must:e}},sort:[{"metadata.created_on":"desc"}]}),c=this.remote.url,o=yield this.remote.getAccessToken(),d={method:"post",url:`${c}/index.php/services/rest/es-samples/_search`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},data:r},l=(yield n.default.request(d)).data.hits.hits.map((e=>e._source)),u=l.map((e=>e.id)),h=i.fetchElasticSubSamples({parentId:u,url:c,accessToken:o}),m=a.fetchElasticOccurrences({parentId:u,url:c,accessToken:o}),[p,f]=yield Promise.all([h,m]),v=l.map(((e,t,s,r,a)=>i=>{const c=(new Date).getTime();try{const o=new s({skipStore:!0});o.data.surveyId=i.metadata.survey.id;const n=o.getSurvey(),d=s.fromElasticDTO(i,{url:e,skipStore:!0},n);o.id=d.id,o.cid=d.cid||o.cid,Object.assign(o.data,d.data),Object.assign(o.metadata,d.metadata);const l=t=>{const r=s.fromElasticDTO(t,{url:e},n);return r.syncedAt=c,r},u=e=>e.event.parent_event_id===o.id||e.event.event_id===o.id,h=r.filter(u).map(l),m=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:t}),p=h.reduce(m,{[o.id]:o}),f=s=>{const r=t.fromElasticDTO(s,e,n);return r.syncedAt=c,[r,s.event.event_id]},v=a.filter(u).map(f),y=([e,t])=>{t!==parseInt(o.id,10)?p[t]?p[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):o.occurrences.push(e)};return v.forEach(y),o.samples.push(...h),o.syncedAt=c,o}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}})(c,this.Occurrence,this.Model,p,f)).filter((e=>!!e)),y=v.filter((e=>!this.cidMap.has(e.cid)));return this.data.push(...y),y}))}removeAllSynced(){const e=[];return this.data.forEach((t=>{t.syncedAt&&e.push(t.destroy())})),Promise.all(e)}reset(){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.data.map((e=>e.destroy()));yield Promise.all(e)}))}get isSynchronising(){return this.remote.synchronising}}exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),r=require("../Collection.js"),a=require("./ElasticOccurrence.js"),i=require("./ElasticSample.js"),c=require("./Sample.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(s);class d extends r.default{constructor(e){super(Object.assign({id:"samples",Model:c.default},e)),this.Occurrence=e.Occurrence,this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken});t.observe(this.data,(e=>{e.addedCount&&e.added.forEach((e=>e.collection=this)),e.removedCount&&e.removed.forEach((e=>delete e.collection))}))}fetch(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.store||!this.Model)return void this.ready.resolve(!1);const e=yield this.store.findAll(),t=e=>{const{data:t,metadata:s,occurrences:r,samples:a,media:i,attrs:c}=e.data;return new this.Model(Object.assign(Object.assign({},e),{attrs:c,data:t,metadata:s,occurrences:r,samples:a,media:i}))},s=e.map((e=>t(e)));this.data.push(...s),this.ready.resolve(!0)}))}fetchRemote(t,s){return e.__awaiter(this,void 0,void 0,(function*(){console.log("Fetching remote samples, page",t);const e=[{bool:{should:s.map((e=>({match:{"metadata.survey.id":e}})))}},{bool:{must_not:{exists:{field:"event.parent_event_id"}}}},{match:{"metadata.trial":"false"}}],r=JSON.stringify({from:t,size:100,query:{bool:{must:e}},sort:[{"metadata.created_on":"desc"}]}),c=this.remote.url,o=yield this.remote.getAccessToken(),d={method:"post",url:`${c}/index.php/services/rest/es-samples/_search`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},data:r},l=(yield n.default.request(d)).data.hits.hits.map((e=>e._source)),u=l.map((e=>e.id)),h=i.fetchElasticSubSamples({parentId:u,url:c,accessToken:o}),m=a.fetchElasticOccurrences({parentId:u,url:c,accessToken:o}),[p,f]=yield Promise.all([h,m]),v=l.map(((e,t,s,r,a)=>i=>{const c=(new Date).getTime();try{const o=new s({skipStore:!0});o.data.surveyId=i.metadata.survey.id;const n=o.getSurvey(),d=s.fromElasticDTO(i,{url:e,skipStore:!0},n);o.id=d.id,o.cid=d.cid||o.cid,Object.assign(o.data,d.data),Object.assign(o.metadata,d.metadata);const l=t=>{const r=s.fromElasticDTO(t,{url:e},n);return r.syncedAt=c,r},u=e=>e.event.parent_event_id===o.id||e.event.event_id===o.id,h=r.filter(u).map(l),m=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:t}),p=h.reduce(m,{[o.id]:o}),f=s=>{const r=t.fromElasticDTO(s,e,n);return r.syncedAt=c,[r,s.event.event_id]},v=a.filter(u).map(f),y=([e,t])=>{t!==parseInt(o.id,10)?p[t]?p[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):o.occurrences.push(e)};return v.forEach(y),o.samples.push(...h),o.syncedAt=c,o}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}})(c,this.Occurrence,this.Model,p,f)).filter((e=>!!e)),y=v.filter((e=>!this.cidMap.has(e.cid)));return this.data.push(...y),y}))}removeAllSynced(){const e=[];return this.data.forEach((t=>{t.syncedAt&&e.push(t.destroy())})),Promise.all(e)}reset(){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.data.map((e=>e.destroy()));yield Promise.all(e)}))}get isSynchronising(){return this.remote.synchronising}}exports.default=d;
@@ -1,5 +1,6 @@
1
1
  import Model from '../Model';
2
- export declare const getErrorMessageFromObject: (errors: any) => string;
2
+ export declare const getErrorMessageFromObject: (errors: object | undefined) => string;
3
+ export type RemoteValueTransformer = (...args: never[]) => unknown;
3
4
  export interface RemoteConfig {
4
5
  id?: number | string;
5
6
  values?: {
@@ -7,7 +8,7 @@ export interface RemoteConfig {
7
8
  value?: string | number | null;
8
9
  }[] | {
9
10
  [key: string]: string | number | null;
10
- } | ((value: any, submission: any, model: any) => any);
11
+ } | RemoteValueTransformer;
11
12
  isBackwardsCompatible?: boolean;
12
13
  }
13
14
  export type Keys = (() => {
@@ -16,15 +17,17 @@ export type Keys = (() => {
16
17
  [key: string]: RemoteConfig;
17
18
  };
18
19
  export declare function validateRemoteModel(): {
19
- attributes: any;
20
+ attributes: Record<string, unknown>;
20
21
  model: any;
21
22
  models: any;
22
23
  } | null;
23
24
  interface RemoteAttr {
24
- value: any;
25
+ value: unknown;
25
26
  id: string;
26
27
  }
27
- type AttrConfig = any;
28
+ type AttrConfig = {
29
+ remote?: RemoteConfig;
30
+ };
28
31
  /**
29
32
  * A generic ElasticSearch response type.
30
33
  */
@@ -37,7 +40,7 @@ export type ElasticSearchResponse<T> = {
37
40
  };
38
41
  export declare const parseRemoteAttrs: (config: {
39
42
  [key: string]: AttrConfig;
40
- }, remoteAttrs: RemoteAttr[], isOccurrence?: boolean) => any;
43
+ }, remoteAttrs: RemoteAttr[], isOccurrence?: boolean) => Record<string, unknown>;
41
44
  export type CustomAttr = {
42
45
  attribute_id: string;
43
46
  value_id: string;
@@ -46,21 +49,24 @@ export type CustomAttr = {
46
49
  multi_value: string;
47
50
  value: string;
48
51
  raw_value: string;
49
- upper_value: any;
52
+ upper_value: unknown;
50
53
  };
51
- export declare function getLocalAttributes(doc: any, schema: any): {
52
- [k: string]: any;
54
+ type RemoteCustomAttr = Partial<Omit<CustomAttr, 'raw_value'>> & {
55
+ raw_value: unknown;
53
56
  };
54
- export declare const assignIfMissing: (model: Model, key: string, value: any) => void;
57
+ export declare function getLocalAttributes(doc: Record<string, RemoteCustomAttr | RemoteCustomAttr[]>, schema: Record<string, AttrConfig>): any;
58
+ export declare const assignIfMissing: (model: Model, key: string, value: unknown) => void;
55
59
  /**
56
60
  * migrates old attribute format to new block-based format
57
61
  */
58
62
  export declare function migrateOldAttr(model: {
59
- data: Record<string, any>;
60
- metadata?: Record<string, any>;
63
+ data: Record<string, unknown>;
64
+ metadata?: Record<string, unknown> & {
65
+ _migrated?: Record<string, unknown>;
66
+ };
61
67
  }, oldAttr: {
62
68
  id: string;
63
- remote?: any;
69
+ remote?: RemoteConfig;
64
70
  }, newAttr: {
65
71
  id: string;
66
72
  }): void;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.assignIfMissing=(e,t,r)=>{Number.isFinite(e.data[t])||e.data[t]||(Number.isFinite(r)||r)&&(e.data[t]=r)},exports.getErrorMessageFromObject=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""),exports.getLocalAttributes=function(e,t){const r=Object.entries(e).flatMap((([e,r])=>{const i=e.match(/:\d+/)?e.split(":").pop():e,s=Object.entries(t).find((a=i,([,e])=>{var t;return`${null===(t=e.remote)||void 0===t?void 0:t.id}`===a}));var a;if(!s)return null;const[o,n]=s;let d;const l=e=>{var t,r,i,s;if(!Array.isArray(null===(t=n.remote)||void 0===t?void 0:t.values))return e.raw_value;const a=null===(s=null===(i=null===(r=n.remote)||void 0===r?void 0:r.values)||void 0===i?void 0:i.find((({id:t})=>e.raw_value===t)))||void 0===s?void 0:s.value;return a||e.raw_value};return d=Array.isArray(r)?r.map(l):l(r),[[o,d]]})).filter((e=>!!e));return Object.fromEntries(r)},exports.migrateOldAttr=function(e,t,r){var i,s,a;const o=t.id,n=e.data[o];if(null==n||""===n)return;const d={},l=Array.isArray(null===(i=t.remote)||void 0===i?void 0:i.values),u="function"==typeof(null===(s=t.remote)||void 0===s?void 0:s.values);if(l){const e=t.remote.values,i=t=>e.find((e=>e.value===t||e.id===t||`${e.id}`==`${t}`));if(Array.isArray(n))d[r.id]=n.map((e=>{var t;return null===(t=i(e))||void 0===t?void 0:t.id})).filter(Boolean);else{const e=i(n);(null==e?void 0:e.id)&&(d[r.id]=String(e.id))}}else d[r.id]=u?t.remote.values(n,{values:d}):"object"==typeof n?JSON.parse(JSON.stringify(n)):n;o!==r.id&&(e.metadata&&((a=e.metadata)._migrated||(a._migrated={}),e.metadata._migrated[o]=n),delete e.data[o]),Object.assign(e.data,d)},exports.parseRemoteAttrs=(e,t,r=!1)=>{e=e||{};const i=Object.entries(e);return t.reduce(((e,t)=>{var s,a;const o=isNaN(t.value)?t.value:parseFloat(t.value),n=i.find((([,e])=>{var r;return(null===(r=e.remote)||void 0===r?void 0:r.id)===parseInt(t.id,10)}));if(n){const[t]=n;e[t]=o}if(!n||(null===(a=null===(s=n[1])||void 0===s?void 0:s.remote)||void 0===a?void 0:a.isBackwardsCompatible)){e[r?`occAttr:${t.id}`:`smpAttr:${t.id}`]=o}return e}),{})},exports.validateRemoteModel=function(){const e=this.getSurvey(),t=e.verify&&e.verify(this.data,this);let r={};if(t){const e=t&&"issues"in t;!("ValidationError"===(null==t?void 0:t.name)||"ValidationError"===(null==t?void 0:t.type))&&!e?r.errors=[t.message]:e?r.errors=t.issues.map((({message:e})=>e)):r=Object.assign({},t)}const i=(e,t)=>{const r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},s=(this.samples||[]).reduce(i,{}),a=(this.occurrences||[]).reduce(i,{}),o=(this.media||[]).reduce(i,{});if(Object.keys(r).length||Object.keys(s).length||Object.keys(a).length||Object.keys(o).length){return{attributes:r,model:this,models:Object.assign(Object.assign(Object.assign({},s),a),o)}}return null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.assignIfMissing=(e,t,r)=>{Number.isFinite(e.data[t])||e.data[t]||(Number.isFinite(r)||r)&&(e.data[t]=r)},exports.getErrorMessageFromObject=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""),exports.getLocalAttributes=function(e,t){const r=Object.entries(e).flatMap((([e,r])=>{const i=e.match(/:\d+/)?e.split(":").pop():e,s=Object.entries(t).find((a=i,([,e])=>{var t;return`${null===(t=e.remote)||void 0===t?void 0:t.id}`===a}));var a;if(!s)return null;const[o,n]=s;let d;const l=e=>{var t,r,i,s;if(!Array.isArray(null===(t=n.remote)||void 0===t?void 0:t.values))return e.raw_value;const a=null===(s=null===(i=null===(r=n.remote)||void 0===r?void 0:r.values)||void 0===i?void 0:i.find((({id:t})=>e.raw_value===t)))||void 0===s?void 0:s.value;return a||e.raw_value};return d=Array.isArray(r)?r.map(l):l(r),[[o,d]]})).filter((e=>!!e));return Object.fromEntries(r)},exports.migrateOldAttr=function(e,t,r){var i,s,a;const o=t.id,n=e.data[o];if(null==n||""===n)return;const d={},l=Array.isArray(null===(i=t.remote)||void 0===i?void 0:i.values),u="function"==typeof(null===(s=t.remote)||void 0===s?void 0:s.values);if(l){const e=t.remote.values,i=t=>e.find((e=>e.value===t||e.id===t||`${e.id}`==`${t}`));if(Array.isArray(n))d[r.id]=n.map((e=>{var t;return null===(t=i(e))||void 0===t?void 0:t.id})).filter(Boolean);else{const e=i(n);(null==e?void 0:e.id)&&(d[r.id]=String(e.id))}}else d[r.id]=u?t.remote.values(n,{values:d}):"object"==typeof n?JSON.parse(JSON.stringify(n)):n;o!==r.id&&(e.metadata&&((a=e.metadata)._migrated||(a._migrated={}),e.metadata._migrated[o]=n),delete e.data[o]),Object.assign(e.data,d)},exports.parseRemoteAttrs=(e,t,r=!1)=>{e=e||{};const i=Object.entries(e);return t.reduce(((e,t)=>{var s,a;const o=isNaN(t.value)?t.value:parseFloat(t.value),n=i.find((([,e])=>{var r;return(null===(r=e.remote)||void 0===r?void 0:r.id)===parseInt(t.id,10)}));if(n){const[t]=n;e[t]=o}if(!n||(null===(a=null===(s=n[1])||void 0===s?void 0:s.remote)||void 0===a?void 0:a.isBackwardsCompatible)){e[r?`occAttr:${t.id}`:`smpAttr:${t.id}`]=o}return e}),{})},exports.validateRemoteModel=function(){const e=this.getSurvey(),t=e.verify&&e.verify(this.data,this);let r={};if(t){const e=t&&"issues"in t;!("ValidationError"===t.name||"ValidationError"===t.type)&&!e?r.errors=[t.message]:e?r.errors=t.issues.map((({message:e})=>e)):r=Object.assign({},t)}const i=(e,t)=>{const r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},s=(this.samples||[]).reduce(i,{}),a=(this.occurrences||[]).reduce(i,{}),o=(this.media||[]).reduce(i,{});if(Object.keys(r).length||Object.keys(s).length||Object.keys(a).length||Object.keys(o).length){return{attributes:r,model:this,models:Object.assign(Object.assign(Object.assign({},s),a),o)}}return null};
package/dist/Model.d.ts CHANGED
@@ -1,20 +1,36 @@
1
1
  import { Deferred } from '@flumens/utils';
2
- import Store from './Stores/Store';
3
- export declare const copyObject: (obj: any) => any;
4
- export interface Options<T = any> {
2
+ export declare const copyObject: <T>(obj: T) => T;
3
+ export interface Data {
4
+ [key: string]: unknown;
5
+ }
6
+ export type Snapshot<T = Data> = {
7
+ id: string | undefined;
8
+ cid: string;
9
+ data: T;
10
+ createdAt: number;
11
+ updatedAt: number;
12
+ syncedAt: number | null | undefined;
13
+ };
14
+ type StoredSnapshot = Partial<Omit<Snapshot<unknown>, 'id'>> & {
15
+ id?: string | null;
16
+ };
17
+ export interface ModelStore {
18
+ save(value: unknown): Promise<unknown>;
19
+ find(key: string): Promise<StoredSnapshot | undefined>;
20
+ delete(key: string): Promise<void>;
21
+ }
22
+ export interface Options<T = Data> {
5
23
  id?: string;
6
24
  cid?: string;
7
25
  createdAt?: number;
8
26
  updatedAt?: number;
9
27
  syncedAt?: number;
10
28
  data?: T;
11
- store?: Store;
29
+ store?: ModelStore;
12
30
  /**
13
31
  * @deprecated
14
32
  */
15
- attrs?: any;
16
- }
17
- export interface Data {
33
+ attrs?: Partial<T>;
18
34
  }
19
35
  export default class Model<T extends Data = Data> {
20
36
  /**
@@ -44,20 +60,13 @@ export default class Model<T extends Data = Data> {
44
60
  /**
45
61
  * The offline store used to save and fetch the model from.
46
62
  */
47
- protected store?: Store<{
48
- id?: string;
49
- cid: string;
50
- data: T;
51
- createdAt: number;
52
- updatedAt: number;
53
- syncedAt?: number | null;
54
- }>;
63
+ protected store?: ModelStore;
55
64
  /**
56
65
  * A deferred promise to flag if the model was initialised from the store.
57
66
  */
58
67
  readonly ready: Deferred<boolean>;
59
68
  protected debouncedValue: number;
60
- constructor({ id, cid, createdAt, updatedAt, syncedAt, data, attrs, store, }: Options);
69
+ constructor({ id, cid, createdAt, updatedAt, syncedAt, data, attrs, store, }: Options<T>);
61
70
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
62
71
  private _observerPaused;
63
72
  /**
@@ -71,8 +80,8 @@ export default class Model<T extends Data = Data> {
71
80
  /**
72
81
  * Destroy the model and remove from the offline store.
73
82
  */
74
- destroy(): Promise<void>;
75
- sync(..._: any): Promise<void>;
83
+ destroy(_silent?: boolean): Promise<void>;
84
+ sync(..._: unknown[]): Promise<void>;
76
85
  /**
77
86
  * Returns a clean (no observables) JSON representation of the model.
78
87
  */
@@ -84,6 +93,7 @@ export default class Model<T extends Data = Data> {
84
93
  syncedAt: number | null | undefined;
85
94
  data: T;
86
95
  };
87
- reset(defaultsToSet?: any): Promise<void>;
96
+ reset(defaultsToSet?: Partial<T>): Promise<void>;
88
97
  get isStored(): boolean;
89
98
  }
99
+ export {};
@@ -1,22 +1,37 @@
1
1
  import Store from './Store';
2
- export default class LocalForageStore implements Store {
3
- debugging: any;
4
- localForage: any;
5
- ready: any;
6
- storeName: any;
7
- constructor(options: any);
8
- static _getDriverOrder(driverOrder: any): any;
9
- save(val: any): Promise<any>;
10
- find(key: any): Promise<any>;
11
- findAll(): Promise<any>;
12
- delete(key: any): Promise<any>;
2
+ type StoredValue = {
3
+ cid: string;
4
+ };
5
+ type Driver = string | LocalForageDriver;
6
+ type Options = {
7
+ storeName: string;
8
+ name?: string;
9
+ version?: number;
10
+ debugging?: boolean;
11
+ driverOrder?: Driver[];
12
+ LocalForage?: LocalForage;
13
+ };
14
+ export default class LocalForageStore<T extends StoredValue = StoredValue> implements Store<T, string | T, string | T, unknown, T> {
15
+ debugging?: boolean;
16
+ localForage: LocalForage | null;
17
+ ready: Promise<unknown>;
18
+ storeName: string;
19
+ constructor(options: Options);
20
+ static _getDriverOrder(driverOrder: Driver[]): string[];
21
+ save(val: T): Promise<T>;
22
+ find(key: string | T): Promise<T | undefined>;
23
+ findAll(): Promise<T[]>;
24
+ delete(key: string | T): Promise<void>;
13
25
  deleteAll(): Promise<void>;
14
26
  /**
15
27
  * Exports all objects from the store.
16
28
  */
17
- export(): Promise<any>;
29
+ export(): Promise<{
30
+ [x: string]: T;
31
+ }>;
18
32
  /**
19
33
  * Imports objects to store.
20
34
  */
21
- import(obj: any): Promise<void>;
35
+ import(obj: unknown): Promise<void>;
22
36
  }
37
+ export {};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),t=require("localforage-cordovasqlitedriver"),i=require("@flumens/utils"),o=require("./utils.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=s(r),a=s(t);let n=["indexeddb","websql","localstorage"];i.isPlatform("hybrid")&&(n=[a.default,...n]);const l={driverOrder:n};class c{constructor(e){if(i.isPlatform("hybrid")&&!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");const r=Object.assign(Object.assign({},l),e);this.debugging=r.debugging,this.localForage=null,this.ready=new Promise(((e,t)=>{const i=new Promise((e=>{r.driverOrder&&"object"==typeof r.driverOrder[0]?d.default.defineDriver(r.driverOrder[0]).then(e):e(void 0)}));if(!r.storeName)throw new Error("storeName prop is missing");this.storeName=r.storeName,i.then((()=>{const i={name:r.name||"indicia",storeName:r.storeName};r.version&&(i.version=r.version);const o=c._getDriverOrder(r.driverOrder),s=r.LocalForage||d.default;this.localForage=s.createInstance(i),this.localForage.setDriver(o).then(e).catch(t)}))}))}static _getDriverOrder(e){return e.map((e=>{switch(e){case"indexeddb":return d.default.INDEXEDDB;case"websql":return d.default.WEBSQL;case"localstorage":return d.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))}save(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r.cid)throw new Error("Invalid key passed to store");if(this.debugging){const e=yield this.find(r.cid);o.printDiff(e,r,r.cid,this.storeName)}return this.localForage.setItem(r.cid,r)}))}find(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return this.localForage.getItem(r)}))}findAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=[];return yield this.localForage.iterate((r=>{e.push(r)})),e}))}delete(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return this.localForage.removeItem(r)}))}deleteAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=yield this.findAll();yield Promise.all(e.map((e=>this.delete(e))))}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;return(yield this.findAll()).reduce(((e,r)=>Object.assign(Object.assign({},e),{[r.cid]:r})),{})}))}import(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,yield this.deleteAll(),"object"!=typeof r)throw new Error("Invalid obj passed to store");const e=Object.entries(r).map((([,e])=>this.save(e)));yield Promise.all(e)}))}}exports.default=c;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),i=require("localforage-cordovasqlitedriver"),t=require("@flumens/utils"),o=require("./utils.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=s(r),a=s(i);let n=["indexeddb","websql","localstorage"];t.isPlatform("hybrid")&&(n=[a.default,...n]);const l={driverOrder:n};class c{constructor(e){if(t.isPlatform("hybrid")&&!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");const r=Object.assign(Object.assign({},l),e);this.debugging=r.debugging,this.localForage=null,this.ready=new Promise(((e,i)=>{const t=new Promise((e=>{r.driverOrder&&"object"==typeof r.driverOrder[0]?d.default.defineDriver(r.driverOrder[0]).then(e):e(void 0)}));if(!r.storeName)throw new Error("storeName prop is missing");this.storeName=r.storeName,t.then((()=>{const t={name:r.name||"indicia",storeName:r.storeName};r.version&&(t.version=r.version);const o=c._getDriverOrder(r.driverOrder),s=r.LocalForage||d.default;this.localForage=s.createInstance(t),this.localForage.setDriver(o).then(e).catch(i)}))}))}static _getDriverOrder(e){return e.map((e=>{switch(e){case"indexeddb":return d.default.INDEXEDDB;case"websql":return d.default.WEBSQL;case"localstorage":return d.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))}save(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r.cid)throw new Error("Invalid key passed to store");if(this.debugging){const e=yield this.find(r.cid);o.printDiff(e,r,r.cid,this.storeName)}return this.localForage.setItem(r.cid,r)}))}find(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return(yield this.localForage.getItem(r))||void 0}))}findAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=[];return yield this.localForage.iterate((r=>{e.push(r)})),e}))}delete(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return this.localForage.removeItem(r)}))}deleteAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=yield this.findAll();yield Promise.all(e.map((e=>this.delete(e))))}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;return(yield this.findAll()).reduce(((e,r)=>Object.assign(Object.assign({},e),{[r.cid]:r})),{})}))}import(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,yield this.deleteAll(),"object"!=typeof r)throw new Error("Invalid obj passed to store");const e=Object.entries(r).map((([,e])=>this.save(e)));yield Promise.all(e)}))}}exports.default=c;
@@ -1,5 +1,5 @@
1
- import { BuildColumns, ColumnBuilderBase, ColumnBuilderBaseConfig, ColumnDataType, InferModelFromColumns, SQL } from 'drizzle-orm';
2
- import { SQLiteSelect, SQLiteDelete, SQLiteTable, SQLiteTableWithColumns } from 'drizzle-orm/sqlite-core';
1
+ import { BuildColumns, InferModelFromColumns, SQL } from 'drizzle-orm';
2
+ import { SQLiteColumnBuilderBase, SQLiteSelect, SQLiteDelete, SQLiteTable, SQLiteTableExtraConfig, SQLiteTableWithColumns } from 'drizzle-orm/sqlite-core';
3
3
  import { Deferred } from '@flumens/utils';
4
4
  import SQLiteDatabase from './SQLiteDatabase';
5
5
  import Store from './Store';
@@ -19,7 +19,7 @@ export declare const defaultCols: () => {
19
19
  name: string;
20
20
  dataType: "custom";
21
21
  columnType: "SQLiteCustomColumn";
22
- data: any;
22
+ data: unknown;
23
23
  driverParam: string;
24
24
  enumValues: undefined;
25
25
  }>>;
@@ -27,29 +27,34 @@ export declare const defaultCols: () => {
27
27
  updatedAt: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"updated_at">>;
28
28
  syncedAt: import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"synced_at">;
29
29
  };
30
- type SelectQueryFn = (q: SQLiteSelect) => SQLiteSelect;
30
+ export type SelectQueryFn = (q: SQLiteSelect) => SQLiteSelect;
31
31
  type DeleteQueryFn = (q: SQLiteDelete) => SQLiteDelete;
32
- export type ColumnMap<T extends Record<string, ColumnBuilderBase<ColumnBuilderBaseConfig<ColumnDataType, string>, object>>> = InferModelFromColumns<BuildColumns<'', T, 'sqlite'>>;
33
- export type InferSelectModel<T extends SQLiteTable<any>> = T['$inferSelect'];
34
- type SQLiteStoreOptions<TColumns = ReturnType<typeof defaultCols>> = {
32
+ export type ColumnMap<T extends Record<string, SQLiteColumnBuilderBase>> = InferModelFromColumns<BuildColumns<'', T, 'sqlite'>>;
33
+ export type InferSelectModel<T extends SQLiteTable> = T['$inferSelect'];
34
+ export type InferQuery<T extends {
35
+ _: {
36
+ result: unknown[];
37
+ };
38
+ }> = T['_']['result'][number];
39
+ export type SQLiteStoreOptions<TColumns extends Record<string, SQLiteColumnBuilderBase> = ReturnType<typeof defaultCols>, TName extends string = string> = {
35
40
  db: SQLiteDatabase;
36
- name: string;
41
+ name: TName;
37
42
  debug?: boolean;
38
43
  columns?: TColumns;
39
- extraConf?: any;
44
+ extraConf?: (columns: BuildColumns<TName, TColumns, 'sqlite'>) => SQLiteTableExtraConfig;
40
45
  };
41
- export default class SQLiteStore<TColumns extends Record<string, ColumnBuilderBase<ColumnBuilderBaseConfig<ColumnDataType, string>, object>> = ReturnType<typeof defaultCols>, T = ColumnMap<TColumns>> implements Store {
42
- readonly name: string;
46
+ export default class SQLiteStore<TColumns extends Record<string, SQLiteColumnBuilderBase> = ReturnType<typeof defaultCols>, T = ColumnMap<TColumns>, TName extends string = string> implements Store<T, string | Partial<T> | SelectQueryFn, string | Partial<T> | DeleteQueryFn, SelectQueryFn> {
47
+ readonly name: TName;
43
48
  readonly db: SQLiteDatabase;
44
49
  readonly table: SQLiteTableWithColumns<{
45
- name: string;
50
+ name: TName;
46
51
  schema: undefined;
47
- columns: BuildColumns<string, TColumns, 'sqlite'>;
52
+ columns: BuildColumns<TName, TColumns, 'sqlite'>;
48
53
  dialect: 'sqlite';
49
54
  }>;
50
55
  readonly ready: Deferred<boolean>;
51
56
  private readonly debug;
52
- constructor({ db, name, debug, columns, extraConf, }: SQLiteStoreOptions<TColumns>);
57
+ constructor({ db, name, debug, columns, extraConf, }: SQLiteStoreOptions<TColumns, TName>);
53
58
  private init;
54
59
  save(values: T | T[]): Promise<void>;
55
60
  find(q: string | Partial<T> | SelectQueryFn): Promise<T>;
@@ -59,11 +64,13 @@ export default class SQLiteStore<TColumns extends Record<string, ColumnBuilderBa
59
64
  /**
60
65
  * Exports all objects from the store.
61
66
  */
62
- export(): Promise<any>;
67
+ export(): Promise<{
68
+ [x: string]: T;
69
+ }>;
63
70
  /**
64
71
  * Imports objects to store.
65
72
  */
66
- import(obj: any): Promise<void>;
73
+ import(obj: unknown): Promise<void>;
67
74
  private _getPrimaryCol;
68
75
  }
69
76
  export {};
@@ -1,9 +1,9 @@
1
- export default abstract class Store<T = any> {
2
- abstract save(val: T): Promise<void>;
3
- abstract find(cid: any): Promise<T | undefined>;
4
- abstract findAll(q?: any): Promise<T[]>;
5
- abstract delete(cid: any): Promise<void>;
1
+ export default abstract class Store<T = unknown, FindKey = unknown, DeleteKey = FindKey, Query = unknown, SaveResult = void> {
2
+ abstract save(val: T): Promise<SaveResult>;
3
+ abstract find(key: FindKey): Promise<T | undefined>;
4
+ abstract findAll(query?: Query): Promise<T[]>;
5
+ abstract delete(key: DeleteKey): Promise<void>;
6
6
  abstract deleteAll(): Promise<void>;
7
- abstract export(): Promise<any>;
8
- abstract import(obj: any): Promise<void>;
7
+ abstract export(): Promise<Record<string, T>>;
8
+ abstract import(obj: unknown): Promise<void>;
9
9
  }
@@ -1,5 +1,5 @@
1
- export declare function printDiff(currentVal: any, val: any, cid: string, name?: string): void;
1
+ export declare function printDiff(currentVal: unknown, val: unknown, cid: string, name?: string): void;
2
2
  /**
3
3
  * For debugging only.
4
4
  */
5
- export declare const formatSqlQuery: (query: string, params: any[]) => string;
5
+ export declare const formatSqlQuery: (query: string, params: unknown[]) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.29.1",
3
+ "version": "0.30.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {
@@ -29,20 +29,20 @@
29
29
  "typescript": "5.7.3"
30
30
  },
31
31
  "peerDependencies": {
32
- "@flumens/utils": "*"
32
+ "@flumens/utils": "*",
33
+ "drizzle-orm": "0.44.7"
33
34
  },
34
35
  "optionalDependencies": {
35
- "@capacitor/core": "^6 || ^7",
36
- "@capacitor/filesystem": "^6 || ^7",
37
- "@capacitor-community/sqlite": "^6 || ^7",
36
+ "@capacitor/core": "^6 || ^7 || ^8",
37
+ "@capacitor/filesystem": "^6 || ^7 || ^8",
38
+ "@capacitor-community/sqlite": "^6 || ^7 || ^8",
38
39
  "deep-diff": "^1",
39
- "drizzle-orm": "0.44.7",
40
40
  "jeep-sqlite": "^2",
41
41
  "jwt-decode": "^4",
42
42
  "localforage": "^1",
43
43
  "localforage-cordovasqlitedriver": "^1",
44
44
  "mobx-utils": "^6",
45
- "zod": "^3",
45
+ "zod": "^4",
46
46
  "wellknown": "^0.5.0"
47
47
  },
48
48
  "jest": {
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};