@flumens/models 0.29.1 → 0.31.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,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;