@flumens/models 0.11.4 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Collection.js +1 -1
- package/dist/Drupal/User.d.ts +3 -0
- package/dist/Drupal/User.js +1 -1
- package/dist/Indicia/ElasticOccurrence.js +1 -1
- package/dist/Indicia/ElasticSample.js +1 -1
- package/dist/Indicia/Group.js +1 -1
- package/dist/Indicia/GroupCollection.js +1 -1
- package/dist/Indicia/Location.js +1 -1
- package/dist/Indicia/LocationCollection.js +1 -1
- package/dist/Indicia/Media.js +1 -1
- package/dist/Indicia/Occurrence.js +1 -1
- package/dist/Indicia/Sample.js +1 -1
- package/dist/Indicia/SampleCollection.js +1 -1
- package/dist/Indicia/helpers.js +1 -1
- package/dist/Model.js +1 -1
- package/dist/Stores/LocalForageStore.js +1 -1
- package/dist/Stores/SQLiteDatabase.js +1 -1
- package/dist/Stores/SQLiteStore.js +1 -1
- package/dist/Stores/Store.js +1 -1
- package/dist/Stores/utils.js +1 -1
- package/package.json +1 -1
package/dist/Collection.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),i=require("@flumens/utils"),r=require("./Model.js");class d{constructor({id:t,cid:d,data:s=[],store:a,Model:o=r.default}){this.ready=new i.Deferred,this.data=e.observable.array(s),this.id=this.id||t,this.cid=this.cid||d||t||i.UUIDv7(),this.Model=o,this.store=this.store||a,this.cidMap=new Map,this.idMap=new Map;e.intercept(this.data,(t=>{if(t.added&&t.added.length){const e=t=>{this.cidMap.set(t.cid,t),this.idMap.set(t.id,t)};t.added.forEach(e)}if(t.removedCount>0){let e=Array.from(this.cidMap.keys())[t.index];this.cidMap.delete(e),e=Array.from(this.idMap.keys())[t.index],this.idMap.delete(e)}return t}))}fetch(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store||!this.Model)return void this.ready.resolve(!1);const t=(yield this.store.findAll()).map((t=>new this.Model(t)));this.data.push(...t),this.ready.resolve(!0)}))}reset(){return t.__awaiter(this,void 0,void 0,(function*(){for(;this.data.length;){const t=this.data.pop();yield null==t?void 0:t.destroy()}}))}filter(t){return this.data.filter(t)}push(...t){return this.data.push(...t)}pop(){return this.data.pop()}find(t){return this.data.find(t)}map(t){return this.data.map(t)}remove(t){return this.data.remove(t)}[Symbol.iterator](){return this.data[Symbol.iterator]()}get length(){return this.data.length}}exports.default=d;
|
package/dist/Drupal/User.d.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface Data extends GenericModelData {
|
|
|
30
30
|
expires_in: number;
|
|
31
31
|
token_type: string;
|
|
32
32
|
};
|
|
33
|
+
/** A flag that is set when the full profile is downloaded. */
|
|
34
|
+
profileFetched?: boolean;
|
|
33
35
|
}
|
|
34
36
|
export interface Options extends GenericModelOptions {
|
|
35
37
|
/**
|
|
@@ -100,6 +102,7 @@ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
|
|
|
100
102
|
register(email: string, password: string, otherFields: any): Promise<void>;
|
|
101
103
|
resetPassword(email: string): Promise<void>;
|
|
102
104
|
delete(): Promise<void>;
|
|
105
|
+
updateRemote(values: Record<string, any>): Promise<void>;
|
|
103
106
|
/**
|
|
104
107
|
* Gets full user profile inc. fresh new tokens.
|
|
105
108
|
*/
|
package/dist/Drupal/User.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),i=require("jwt-decode"),s=require("zod"),r=require("@flumens/utils"),a=require("../Model.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(t);function d(e){const t={};return Object.keys(e).forEach((i=>{if(i.match(/^field_/)){const s=i.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[i])return;if(Array.isArray(e[i])&&e[i].length)return void(t[s]=e[i][0].value);t[s]=e[i]}})),t}const c=e=>{var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new r.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new r.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new r.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new r.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new r.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new r.HandledError("Timeout");throw e},l=6e4;const h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class u extends a.default{constructor(t){var{config:i}=t,s=e.__rest(t,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},h),s.data)})),this.config=i}logIn(t,i){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._exchangePasswordToTokens(t,i);return this.data.tokens=e,yield this.refreshProfile(),this.save()}))}register(t,i,s){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify(Object.assign({name:[{value:t}],pass:[{value:i}],mail:[{value:t}]},s)),r={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:e,timeout:l},{data:a}=yield n.default(r).catch(c);if(!!u.registerSchemaBackend.safeParse(a).error)throw new Error("Invalid backend response.");const o=yield this._exchangePasswordToTokens(t,i);this.id=a.uid[0].value;const h=d(a);return Object.assign(this.data,Object.assign({email:t,tokens:o,profileFetched:!0},h)),this.save()}))}resetPassword(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:t}),i={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:e};try{yield n.default(i).catch(c)}catch(e){if("The user has not been activated or is blocked."===e.message)return void(yield this._sendVerificationEmail(t));c(e)}}))}delete(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),t={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield n.default(t).catch(c),this.logOut()}))}updateRemote(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(),i={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:t,headers:{Authorization:`Bearer ${e}`},timeout:l};yield n.default(i),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const t={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:l},{data:i}=yield n.default(t).catch(c),s=d(i);Object.assign(this.data,Object.assign({email:i.mail[0].value,profileFetched:!0},s))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return e.__awaiter(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},h),e))}getAccessToken(t){return e.__awaiter(this,void 0,void 0,(function*(){if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:e}=this.data.tokens||{},s=function(e){if(!e)return!0;const{exp:t}=i.jwtDecode(e),s=1e3*t;return Date.now()+12e4>s}(e);if(!e||s||t)try{yield this._refreshAccessToken()}catch(e){console.error(e);const t="The refresh token is invalid."===e.message,i="Token has no user email."===e.message;if(t||i)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:[{value:t||this.data.email}]}),i={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:e,timeout:l};return n.default(i).catch(c)}))}_exchangePasswordToTokens(t,i){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=new FormData;s.append("grant_type","password"),s.append("username",t),s.append("password",i),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(e=this.config.scopes)||void 0===e?void 0:e.length)&&s.append("scope",this.config.scopes.join(" "));const r={method:"post",url:`${this.config.url}/oauth/token`,data:s},{data:a}=yield n.default(r).catch(c);return a}))}_refreshAccessToken(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const t=new FormData;t.append("grant_type","refresh_token"),t.append("refresh_token",e),t.append("client_id",this.config.clientId),this.config.clientPass&&t.append("client_secret",this.config.clientPass);const s={method:"post",url:`${this.config.url}/oauth/token`,data:t,timeout:l},{data:r}=yield n.default(s).catch(c),a=Object.assign(Object.assign({},this.data.tokens),r),o=i.jwtDecode(a.access_token),{email:h}=o;if(!h)throw new Error("Token has no user email.");const{iss:u,email_verified:f}=o,g=o["http://indicia.org.uk/user:id"],m=o.scopes,p=d(o);this.id=o.sub,Object.assign(this.data,Object.assign({email:h,roles:m,verified:f,iss:u,indiciaUserId:g,tokens:a},p)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}u.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),u.resetSchema=s.object({email:s.z.string().email("Please fill in")}),u.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),exports.default=u;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(require("axios"));exports.fetchElasticOccurrences=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var n,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(require("axios"));exports.fetchElasticOccurrences=function(t){return e.__awaiter(this,arguments,void 0,(function*({parentId:e,url:t,accessToken:a}){var n,i,o;const s={terms:{"event.parent_event_id":Array.isArray(e)?e:[e]}},c={terms:{"event.event_id":Array.isArray(e)?e:[e]}},u=JSON.stringify({size:5e3,query:{bool:{must:[{bool:{should:[s,c]}}]}},_source:["id","event.event_id","event.parent_event_id","metadata.created_on","metadata.updated_on","identification","occurrence.occurrence_remarks","occurrence.attributes","occurrence.media","taxon.species","taxon.taxon_name","taxon.taxa_taxon_list_id"]}),d={Authorization:`Bearer ${a}`},l={method:"post",url:`${t}/index.php/services/rest/es-occurrences/_search`,headers:Object.assign({"Content-Type":"application/json"},d),data:u};return(null===(o=null===(i=null===(n=(yield r.default.request(l)).data)||void 0===n?void 0:n.hits)||void 0===i?void 0:i.hits)||void 0===o?void 0:o.map((e=>e._source)))||[]}))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=t(require("axios"));exports.fetchElasticSample=function(t){return e.__awaiter(this,arguments,void 0,(function(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=t(require("axios"));exports.fetchElasticSample=function(t){return e.__awaiter(this,arguments,void 0,(function*({id:e,cid:t,url:i,accessToken:o}){var r,s,n;let d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{id:e}}]}}});e||(d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{"event.source_system_key":t}}]}}}));const u={Authorization:`Bearer ${o}`},l={method:"post",url:`${i}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},u),data:d},c=((null===(n=null===(s=null===(r=(yield a.default.request(l)).data)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.hits)||void 0===n?void 0:n.map((e=>e._source)))||[])[0];if(!c)throw new Error(`Remote sample with id ${e||t} was not found`);return c}))},exports.fetchElasticSubSamples=function(t){return e.__awaiter(this,arguments,void 0,(function*({parentId:e,url:t,accessToken:i}){var o,r,s;const n=JSON.stringify({size:2e3,query:{bool:{must:[{terms:{"event.parent_event_id":Array.isArray(e)?e:[e]}}]}},_source:["id","event.event_id","event.parent_event_id","event.source_system_key","event.attributes","event.media","event.event_remarks","event.date_start","metadata.created_on","metadata.updated_on","metadata.survey.id","metadata.group.id","metadata.trial","location.geom","location.output_sref_system","location.output_sref","location.point","location.code","location.name","location.verbatim_locality"]}),d={Authorization:`Bearer ${i}`},u={method:"post",url:`${t}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},d),data:n};return(null===(s=null===(r=null===(o=(yield a.default.request(u)).data)||void 0===o?void 0:o.hits)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.map((e=>e._source)))||[]}))};
|
package/dist/Indicia/Group.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),o=require("axios"),i=require("zod"),r=require("@flumens/utils/dist/errors"),n=require("@flumens/utils/dist/uuid"),s=require("../Model.js"),a=require("./helpers.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=l(o);const u=i.object({id:i.z.string(),title:i.z.string(),createdOn:i.z.string(),description:i.z.string().nullable().optional(),groupType:i.z.string().nullable().optional(),joiningMethod:i.z.enum(["P","R","A","I"]).nullable().optional(),websiteId:i.z.string().nullable().optional(),groupTypeId:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),fromDate:i.z.string().nullable().optional(),toDate:i.z.string().nullable().optional(),indexedLocationIds:i.z.array(i.z.number()).nullable().optional(),userIsAdministrator:i.z.enum(["t","f"]).nullable().optional(),userIsMember:i.z.enum(["t","f"]).nullable().optional(),userIsPending:i.z.enum(["t","f"]).nullable().optional()}),c=i.object({id:i.z.string().nullable().optional(),createdOn:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),groupId:i.z.string().nullable().optional(),groupTitle:i.z.string().nullable().optional(),locationId:i.z.string(),locationName:i.z.string(),locationBoundaryGeom:i.z.string(),locationLat:i.z.string(),locationLon:i.z.string(),locationCreatedOn:i.z.string(),locationUpdatedOn:i.z.string(),locationCentroidSref:i.z.string(),locationCentroidSrefSystem:i.z.string(),locationCode:i.z.string().nullable().optional(),locationCreatedById:i.z.string().nullable().optional(),locationUpdatedById:i.z.string().nullable().optional(),locationComment:i.z.string().nullable().optional(),locationExternalKey:i.z.string().nullable().optional()});class g extends s.default{static fromDTO(t,o={}){u.parse(t);const{id:i,createdOn:r}=t,s=e.__rest(t,["id","createdOn"]);return new this(Object.assign({id:i,cid:n.UUIDv7(),data:s,createdAt:new Date(r).getTime()},o))}constructor(o){var{skipStore:i,store:r,url:n,getAccessToken:s,getIndiciaUserId:a}=o,l=e.__rest(o,["skipStore","store","url","getAccessToken","getIndiciaUserId"]);super(Object.assign(Object.assign({},l),{store:i?void 0:r})),this.remote=t.observable({synchronising:!1,url:n,getAccessToken:s,getIndiciaUserId:a})}join(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users`,t=yield this.remote.getAccessToken(),o={values:{id:yield this.remote.getIndiciaUserId()}},i={headers:{Authorization:`Bearer ${t}`},timeout:8e4};try{yield d.default.post(e,o,i)}catch(e){if(d.default.isCancel(e))return;if(r.isAxiosNetworkError(e))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}}))}leave(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t,o;const i=yield this.remote.getIndiciaUserId(),n=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users/${i}`,s={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{yield d.default.delete(n,s)}catch(i){if(d.default.isCancel(i))return;if(r.isAxiosNetworkError(i))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");if(null===(o=null===(t=null===(e=i.response)||void 0===e?void 0:e.data)||void 0===t?void 0:t.message)||void 0===o?void 0:o.includes("User is not a member of the group"))return;throw i}}))}addRemoteLocation(t){return e.__awaiter(this,void 0,void 0,(function*(){var e,o,i;console.log("Group location uploading");const r={values:{id:t}},n=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`;try{this.remote.synchronising=!0;const e={url:n,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:r};return yield d.default(e),this.remote.synchronising=!1,console.log("Group location uploading done"),this}catch(t){this.remote.synchronising=!1;const r=t;if(409===(null===(e=r.response)||void 0===e?void 0:e.status))return console.log("Location uploading duplicate was found"),this;const n=null===(i=null===(o=r.response)||void 0===o?void 0:o.data)||void 0===i?void 0:i.message;if(!n)throw t;if("object"==typeof n){const e=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),"");throw new Error(e(n))}throw new Error(n)}}))}fetchRemoteLocations(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`,t={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{const o=yield d.default.get(e,t),i=({values:e})=>a.getCamelCaseObj(e),r=o.data.map(i);return r.forEach((e=>c.parse(e))),r}catch(e){if(d.default.isCancel(e))return[];if(r.isAxiosNetworkError(e))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw e}}))}}exports.default=g,exports.dtoSchema=u;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),i=require("@flumens/utils/dist/errors"),r=require("../Collection.js"),o=require("./Group.js"),a=require("./helpers.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=n(s);class d extends r.default{constructor(e){super(Object.assign({id:"groups",Model:o.default},e)),this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken})}fetchRemote(){return e.__awaiter(this,arguments,void 0,(function*(e={}){console.log(`📚 Collection: ${this.id} collection fetching`),this.remote.synchronising=!0;try{const{type:t,form:s,location:i}=e,r=yield this.remote.getAccessToken(),o=`${this.remote.url}/index.php/services/rest/groups`,n={};t&&(n.view=t),s&&(n.page=s.join(",")),Number.isFinite(i)&&(n.indexed_location_ids=i);const d={params:n,headers:{Authorization:`Bearer ${r}`},timeout:8e4},u=yield l.default.get(o,d),c=e=>!e.toDate||new Date(e.toDate)>new Date,h=e=>!e.fromDate||new Date(e.fromDate)<new Date,m=u.data.map((({values:e})=>e)).map(a.getCamelCaseObj).filter(c).filter(h),f=m.map((e=>this.Model.fromDTO(e,{skipStore:"joinable"===t})));if(t){if("member"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsMember&&(t.destroy(),this.data.splice(e,1),e--)}else if("pending"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsPending&&(t.destroy(),this.data.splice(e,1),e--)}else if("joinable"===t)for(let e=0;e<this.data.length;e++){this.data[e].isStored||(this.data.splice(e,1),e--)}}else for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&t.destroy(),this.data.splice(e,1),e--}"member"===t&&(yield Promise.all(f.map((e=>e.save())))),"pending"===t&&(yield Promise.all(f.map((e=>e.save())))),this.data.push(...f),console.log(`📚 Collection: ${this.id} collection fetching done ${m.length} documents`)}catch(e){if(l.default.isCancel(e))return;if(i.isAxiosNetworkError(e))throw new i.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw this.remote.synchronising=!1,e}this.remote.synchronising=!1}))}get isSynchronising(){return this.remote.synchronising}}exports.byGroupMembershipStatus=function(e){return t=>{const s=t.data.userIsMember||t.data.userIsPending;return"member"===e?s:!s}},exports.default=d;
|
package/dist/Indicia/Location.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),i=require("axios"),o=require("lodash"),n=require("zod"),s=require("@flumens/utils/dist/uuid"),r=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=a(i);const l=n.object({lat:n.z.string().min(1),lon:n.z.string().min(1),name:n.z.string().min(1),locationTypeId:n.z.string().min(1),centroidSref:n.z.string().min(1),centroidSrefSystem:n.z.string().min(1),id:n.z.string().optional(),createdOn:n.z.string().optional(),updatedOn:n.z.string().optional(),parentId:n.z.string().nullable().optional(),boundaryGeom:n.z.string().nullable().optional(),code:n.z.string().nullable().optional(),createdById:n.z.string().nullable().optional(),updatedById:n.z.string().nullable().optional(),externalKey:n.z.string().nullable().optional(),centroidGeom:n.z.string().nullable().optional(),public:n.z.string().nullable().optional(),comment:n.z.string().nullable().optional()});var u;exports.LocationType=void 0,(u=exports.LocationType||(exports.LocationType={})).MothTrap="18879",u.Transect="777",u.TransectSection="778",u.GroupSite="14";class c extends r.default{static fromDTO(t,i={}){l.parse(t);const{id:o,createdOn:n,updatedOn:r,externalKey:a}=t,d=e.__rest(t,["id","createdOn","updatedOn","externalKey"]);return new this(Object.assign({cid:a||s.UUIDv7(),id:o,createdAt:new Date(n).getTime(),updatedAt:new Date(r).getTime(),data:d},i))}constructor(i){var{skipStore:o,store:n,media:s=[],metadata:r={},url:a,getAccessToken:d}=i,l=e.__rest(i,["skipStore","store","media","metadata","url","getAccessToken"]);super(Object.assign(Object.assign({},l),{store:o?void 0:n})),this.metadata=t.observable(r),this.media=t.observable(s),this.remote=t.observable({synchronising:!1,url:a,getAccessToken:d})}saveRemote(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t,i,o,n;try{this.remote.synchronising=!0;const e=yield this.uploadMedia(),t=this.toDTO(e),i=`${this.remote.url}/index.php/services/rest/locations`,o={url:i,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:t},{data:n}=yield d.default(o),s=new Date(n.values.updated_on).getTime();return this.updatedAt=s,this.syncedAt=s,this.id=n.values.id,this.remote.synchronising=!1,this.store&&this.save(),console.log("Location uploading done"),this}catch(s){this.remote.synchronising=!1;const r=s;if(409===(null===(e=r.response)||void 0===e?void 0:e.status)&&(null===(t=r.response)||void 0===t?void 0:t.data.duplicate_of)){console.log("Location uploading duplicate was found");const e=(new Date).getTime();return this.updatedAt=e,this.syncedAt=e,this.id=null===(i=r.response)||void 0===i?void 0:i.data.duplicate_of.id,this}const a=null===(n=null===(o=r.response)||void 0===o?void 0:o.data)||void 0===n?void 0:n.message;if(!a)throw s;if("object"==typeof a){throw new Error((e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""))(a))}throw new Error(a)}}))}toDTO(e={}){const t=(i=this.data,Object.entries(i).reduce(((e,[t,i])=>(e[t.includes("locAttr:")?t:o.snakeCase(t)]=i,e)),{}));var i;const n={values:Object.assign({external_key:this.cid},t),media:[]};return this.media.forEach((t=>{const i=t.toDTO(e);i&&n.media.push(i)})),n}uploadMedia(){return e.__awaiter(this,void 0,void 0,(function*(){yield Promise.all(this.media.map((e=>e.uploadFile())));const e={};return this.media.forEach((t=>{e[t.cid]={name:t.data.queued}})),e}))}get isUploaded(){return!!this.syncedAt}get isSynchronising(){return this.remote.synchronising}get isDraft(){return!this.id}}exports.default=c,exports.dtoSchema=l;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),o=require("../Collection.js"),r=require("./Location.js");class s extends o.default{constructor(e){super(Object.assign({id:"locations",Model:r.default},e)),this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken})}fetchRemote(){return e.__awaiter(this,arguments,void 0,(function*(e={}){throw console.log(e),new Error("fetchRemote not implemented")}))}get isSynchronising(){return this.remote.synchronising}}exports.byLocationType=e=>t=>t.data.locationTypeId===e,exports.default=s;
|
package/dist/Indicia/Media.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),i=require("axios"),a=require("@flumens/utils"),r=require("../Model.js"),s=require("./helpers.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(i);const d=a.isPlatform("hybrid");class h extends r.default{static getDataURI(e,t={}){return new Promise(((i,a)=>{if("string"==typeof e){let a=e.replace(/.*\.([a-z]+)$/i,"$1");return"jpg"===a&&(a="jpeg"),void h.resize(e,a,t.width,t.height).then((e=>{const[t,r]=e;i([r,a,t.width,t.height])}))}if(!window.FileReader)return void a(new Error("No File Reader"));const r=new FileReader;r.onload=function(a){var r,s;if(t.width||t.height)h.resize(null===(r=a.target)||void 0===r?void 0:r.result,e.type,t.width,t.height).then((t=>{const[a,r]=t;i([r,e.type,a.width,a.height])}));else{const t=new window.Image;t.onload=()=>{var r;const s=e.type.replace(/.*\/([a-z]+)$/i,"$1");i([null===(r=a.target)||void 0===r?void 0:r.result,s,t.width,t.height])},t.src=null===(s=a.target)||void 0===s?void 0:s.result}},r.readAsDataURL(e)}))}static resize(e,t,i,a){return new Promise((r=>{const s=new window.Image;s.onload=()=>{var e;let{width:n}=s,{height:o}=s;let d=null;d=n>o?n/(!i||i>n?n:i):o/(!a||a>o?o:a),n/=d,o/=d;const h=document.createElement("canvas");h.width=n,h.height=o,null===(e=h.getContext("2d"))||void 0===e||e.drawImage(s,0,0,n,o),r([s,h.toDataURL(t)])},s.src=e}))}static getImageModel(t,i,r){return e.__awaiter(this,void 0,void 0,(function*(){const e=this;if(!t)throw new Error("File not found while creating image model.");let s,n,o;if(d){const e=yield a.createImage(t);s=e.width,n=e.height,o=t.split("/").pop()}else[o,,s,n]=yield e.getDataURI(t,{width:2e3,height:2e3});const h=new e({data:{data:o,type:"jpeg",width:s,height:n,path:i}});return r||(yield h.addThumbnail()),h}))}constructor(i={}){var{metadata:a={}}=i,r=e.__rest(i,["metadata"]);r.createdAt=r.createdAt||(null==a?void 0:a.createdOn),r.updatedAt=r.updatedAt||(null==a?void 0:a.updatedOn),r.syncedAt=r.syncedAt||(null==a?void 0:a.syncedOn),super(r),this.debouncedValue=300,this.parent=this.parent,this.remote=t.observable({synchronising:!1,url:r.url,getAccessToken:r.getAccessToken}),this.metadata=t.observable(a)}toJSON(){const e=super.toJSON();return JSON.parse(JSON.stringify(Object.assign(Object.assign({},e),{metadata:t.toJS(this.metadata)||{}})))}setupdatedAtTimestamp(e){var t;super.setUpdatedAtTimestamp(e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)}toDTO(e={}){const t=e[this.cid];if(!this.id&&!t)throw new Error("Image ID or queued ID is missing.");const i={values:{caption:this.data.caption}};return this.id?i.values.id=this.id:i.values.queued=t.name,i}sync(){const t=Object.create(null,{sync:{get:()=>super.sync}});return e.__awaiter(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():t.sync.call(this)}))}uploadFile(){return e.__awaiter(this,arguments,void 0,(function*(e=!1){var t;if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");const i=Date.now()-432e5,a=this.syncedAt>i&&this.data.queued;if(!e&&a)return;const r=yield this.getFormData(),s=new FormData;if(s.append(...r),!this.remote.getAccessToken)throw new Error("this.remote.getAccessToken is missing");const n={Authorization:`Bearer ${yield this.remote.getAccessToken()}`},d=yield o.default.post(`${this.remote.url}/index.php/services/rest/media-queue`,s,{headers:n,timeout:12e4});if(!(null===(t=d.data[this.cid])||void 0===t?void 0:t.name))throw new Error("New remote media name was not be found.");this.data.queued=d.data[this.cid].name,this.syncedAt=(new Date).getTime()}))}getFormData(){return e.__awaiter(this,void 0,void 0,(function*(){const{type:e}=this.data;let t=e,i=e;(null==e?void 0:e.match(/image.*/))?[,t]=e.split("/"):i=`image/${i}`;const a=this.getURL(),r=yield s.getBlobFromURL(a,i),n=this.cid;return[n,r,`${n}.${t}`]}))}getRemoteURL(){if(!this.remote.url)throw new Error("No remote url was set.");if(!this.data.queued&&!this.data.path)throw new Error("No media queued or path attribute.");const e=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?`${e}/upload-queue/${this.data.queued}`:`${e}/upload/${this.data.path}`}getURL(){return this.data.data}resize(e,t){const i=this;return new Promise(((a,r)=>{h.resize(this.getURL(),this.data.type,e,t).then((e=>{const[t,r]=e;i.data.data=r,a([t,r])})).catch(r)}))}addThumbnail(e={}){const t=this;return new Promise(((e,i)=>{/^data:/i.test(this.getURL())?h.resize(this.getURL(),this.data.type,100,100).then((i=>{const[,a]=i;t.data.thumbnail=a,e()})).catch(i):h.getDataURI(this.getURL(),{width:100,height:100}).then((i=>{[t.data.thumbnail]=i,e()})).catch(i)}))}get isUploaded(){if(!this.parent)throw new Error("No media parent to return disabled status.");return this.parent.isUploaded}get isDisabled(){return this.isUploaded}get isSynchronising(){return this.remote.synchronising}}exports.default=h;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),a=require("lodash"),i=require("../Model.js"),s=require("./Media.js"),n=require("./helpers.js");class r extends i.default{static fromElasticDTO(t,e,a){var i,s,r,d,o,c,u;const{id:l,metadata:m,event:p,occurrence:h,taxon:v,identification:f}=t,y=new Date(m.created_on).getTime(),b=new Date(m.updated_on).getTime(),_=Date.now();let O=p.parent_event_id?null===(s=null===(i=a.smp)||void 0===i?void 0:i.occ)||void 0===s?void 0:s.attrs:null===(r=a.occ)||void 0===r?void 0:r.attrs;O||(O=(null===(o=null===(d=a.smp)||void 0===d?void 0:d.occ)||void 0===o?void 0:o.attrs)||(null===(c=a.occ)||void 0===c?void 0:c.attrs)||{});const g=n.parseRemoteAttrs(O,(null==h?void 0:h.attributes)||[]),A=(null===(u=null==h?void 0:h.media)||void 0===u?void 0:u.map((({path:t})=>({id:t,createdAt:y,updatedAt:b,syncedAt:_,data:{data:`${e}/upload/${t}`}}))))||[],w=v.species||v.taxon_name,j=w!==v.taxon_name?v.taxon_name:"";return new this({id:l,cid:l,createdAt:y,updatedAt:b,syncedAt:_,metadata:{verification:f},data:Object.assign(Object.assign({},g),{taxon:{warehouse_id:parseInt(v.taxa_taxon_list_id,10),scientific_name:w,scientificName:w,common_name:j,commonName:j,found_in_name:j?"common_name":"scientific_name",foundInName:j?"commonName":"scientificName"},comment:null==h?void 0:h.occurrence_remarks}),media:A})}constructor(a={}){var{metadata:i={},media:n=[],Media:d=s.default}=a,o=t.__rest(a,["metadata","media","Media"]);o.createdAt=o.createdAt||(null==i?void 0:i.createdOn),o.updatedAt=o.updatedAt||(null==i?void 0:i.updatedOn),o.syncedAt=o.syncedAt||(null==i?void 0:i.syncedOn),super(o),this.debouncedValue=300,this.keys=()=>{return Object.assign(Object.assign({},r.keys),(t=this.getSurvey().attrs||{},Object.keys(t).reduce(((e,a)=>Object.assign(Object.assign({},e),{[a]:t[a].remote||t[a]})),{})));var t},this.Media=d,this.metadata=e.observable(i);const c=n.map(((t,e={})=>a=>a instanceof t?a:new t(Object.assign(Object.assign({},a),e)))(this.Media));this.media=e.observable(c);const u=t=>t.parent=this;this.media.forEach(u);e.intercept(this.media,(t=>{var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(u),this.setUpdatedAtTimestamp(Date.now())):t.removedCount&&this.setUpdatedAtTimestamp(Date.now()),t}))}setUpdatedAtTimestamp(t){var e;super.setUpdatedAtTimestamp(t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)}save(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.parent)throw new Error("Trying to save locally without a parent");this.parent.save()}))}destroy(e){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.parent)throw new Error("Trying to destroy locally without a parent");this.parent.occurrences.remove(this),yield Promise.all(this.media.map((t=>t.destroy(!0)))),e||(yield this.parent.save())}))}sync(){const e=Object.create(null,{sync:{get:()=>super.sync}});return t.__awaiter(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():e.sync.call(this)}))}toJSON(){var t;const a=super.toJSON();return JSON.parse(JSON.stringify(Object.assign(Object.assign({},a),{media:(null===(t=this.media)||void 0===t?void 0:t.map((t=>t.toJSON())))||[],metadata:e.toJS(this.metadata)||{}})))}getSurvey(){if(!this.parent)return{};return this.parent.getSurvey().occ||{}}get isUploaded(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded}get isDisabled(){return this.isUploaded}toDTO(t={}){const e="function"==typeof this.keys?this.keys():this.keys,i=Object.assign(Object.assign({},r.keys),e),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);const n=(t,e)=>{const a=i[t].values;if(!a)return e;if("function"==typeof a)return a(e,s,this);if(a instanceof Array){const i=a.find((({value:t})=>t===e));if(!i||!i.id)throw new Error(`A "${t}" attribute "${e}" value could not be mapped to a remote database field.`);return i.id}return e instanceof Array?e.map((t=>a[t])):a[e]};Object.keys(this.data).forEach((t=>{let e=this.data[t];const r=t=>null==t;if(r(e))return;if(!i[t])return t=t.includes("occAttr:")?t:a.snakeCase(t),void(s.values[t]=e);const d=i[t].id||t;if(e=n(t,e),r(e))return;let o=Number.isNaN(Number(d))?d:`occAttr:${d}`;o=o.includes("occAttr:")?o:a.snakeCase(o),s.values[o]=e})),this.media.forEach((e=>{const a=e.toDTO(t);a&&s.media.push(a)}));const d=this.getSurvey();return d.modifySubmission?d.modifySubmission(s,this):s}}r.keys={taxon:{id:"taxa_taxon_list_id"}},exports.default=r;
|
package/dist/Indicia/Sample.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("lodash"),n=require("wellknown"),a=require("@flumens/utils"),i=require("../Model.js"),o=require("./ElasticOccurrence.js"),c=require("./ElasticSample.js"),u=require("./Media.js"),d=require("./Occurrence.js"),l=require("./helpers.js");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var h=p(r),m=p(n),f=function(t,r){return void 0===r&&(r={}),function(s){return s instanceof t?s:new t(e.__assign(e.__assign({},s),r))}};function v(e,t){var r,s,n,a,i;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(n=e.samples)||void 0===n||n.forEach((function(e,r){return v(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(a=e.occurrences)||void 0===a||a.forEach((function(e,r){return v(e,t.occurrences[r])}))),e.media&&t.media&&(null===(i=e.media)||void 0===i||i.forEach((function(e,r){return v(e,t.media[r])})));else{if("process"in window&&"test"===(null===(s=null===(r=window.process)||void 0===r?void 0:r.env)||void 0===s?void 0:s.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var _=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,n;return e.__generator(this,(function(a){switch(a.label){case 0:return r=[],t.media?(s=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,t.getFormData()];case 1:return r=e.sent(),[2,[t,r]]}}))}))},[4,Promise.all(t.media.map(s))]):[3,2];case 1:n=a.sent(),r.push.apply(r,n),a.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(_))]:[3,4];case 3:n=a.sent(),r.push.apply(r,n.flat()),a.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(_))]:[3,6];case 5:n=a.sent(),r.push.apply(r,n.flat()),a.label=6;case 6:return[2,r]}}))}))};function y(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return y(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return y(e)}))),e.media&&(r.media=e.media.map((function(e){return y(e)}))),r}function g(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var w=function(r){function n(s){void 0===s&&(s={});var a=this,i=s.metadata,o=void 0===i?{}:i,c=s.samples,p=void 0===c?[]:c,h=s.occurrences,m=void 0===h?[]:h,v=s.media,_=void 0===v?[]:v,y=s.Occurrence,g=void 0===y?d.default:y,w=s.Media,b=void 0===w?u.default:w,A=s.skipStore,O=e.__rest(s,["metadata","samples","occurrences","media","Occurrence","Media","skipStore"]);O.createdAt=O.createdAt||(null==o?void 0:o.createdOn),O.updatedAt=O.updatedAt||(null==o?void 0:o.updatedOn),O.syncedAt=O.syncedAt||(null==o?void 0:o.syncedOn);var E=A?void 0:O.store;(a=r.call(this,e.__assign(e.__assign({},O),{store:E}))||this).validateRemote=l.validateRemoteModel,a.error=t.observable({message:""}),a.debouncedValue=300,a.keys=function(){var t;return e.__assign(e.__assign({},n.keys),(t=a.getSurvey().attrs||{},Object.keys(t).reduce((function(r,s){var n;return e.__assign(e.__assign({},r),((n={})[s]=t[s].remote||t[s],n))}),{})))},a.requiresRemoteSync=function(){return!a.syncedAt||a.updatedAt>a.syncedAt},a.Occurrence=g,a.Media=b,a.remote=t.observable({synchronising:!1,url:O.url,getAccessToken:O.getAccessToken}),a.metadata=t.observable(o);var S=p.map(f(a.constructor));a.samples=t.observable(S);var k=m.map(f(a.Occurrence,{Media:a.Media}));a.occurrences=t.observable(k);var T=_.map(f(a.Media));a.media=t.observable(T);var D=function(e){return e.parent=a};a.samples.forEach(D),a.occurrences.forEach(D),a.media.forEach(D);var q=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(D),a.setUpdatedAtTimestamp(Date.now())):e.removedCount&&a.setUpdatedAtTimestamp(Date.now()),e};return t.intercept(a.samples,q),t.intercept(a.occurrences,q),t.intercept(a.media,q),a}return e.__extends(n,r),n.fromElasticDTO=function(t,r,s){var n,a;void 0===r&&(r={});var i=t.id,o=t.event,c=t.location,u=t.metadata,d=r.url,p=new Date(o.date_start),h=new Date(u.updated_on).getTime(),f=Date.now(),v=c.point.split(",").map(parseFloat),_=v[0],y=v[1],g="OSGB"===c.output_sref_system?c.output_sref:"",w=c.geom?m.default.parse(c.geom):null,b=o.parent_event_id,A=l.parseRemoteAttrs(b?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,o.attributes||[]),O=null===(n=o.media)||void 0===n?void 0:n.map((function(e){var t=e.path;return{id:t,metadata:{updatedOn:p,createdOn:p,syncedOn:p},data:{data:"".concat(d,"/upload/").concat(t)}}}));return new this(e.__assign({id:i,cid:o.source_system_key||i,createdAt:p.getTime(),updatedAt:h,syncedAt:f,metadata:{saved:!0},data:e.__assign(e.__assign({},A),{surveyId:u.survey.id,date:p.toISOString(),location:{code:c.code,name:c.name||c.verbatim_locality,latitude:_,longitude:y,shape:w,gridref:g},enteredSrefSystem:4326,groupId:null===(a=u.group)||void 0===a?void 0:a.id,comment:o.event_remarks,training:"true"===u.trial}),media:O},r))},n.prototype.setUpdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},n.prototype.toJSON=function(){var s,n,a,i=r.prototype.toJSON.call(this);return a=e.__assign(e.__assign({},i),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(s=this.samples)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[],media:(null===(n=this.media)||void 0===n?void 0:n.map((function(e){return e.toJSON()})))||[]}),JSON.parse(JSON.stringify(a))},n.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},n.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i,o,c;return e.__generator(this,(function(u){switch(u.label){case 0:if(this.data.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this.store)throw new Error("Trying to sync locally without a store");return t=this.toJSON(),r=t.data,s=t.metadata,n=t.occurrences,a=t.samples,i=t.media,o=e.__rest(t,["data","metadata","occurrences","samples","media"]),c=e.__assign(e.__assign({},o),{data:{data:r,metadata:s,occurrences:n,samples:a,media:i}}),[4,this.store.save(c)];case 1:return u.sent(),[2]}}))}))},n.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(n.media.map((function(e){return e.destroy(!0)}))),Promise.all(n.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,r()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this.store)throw new Error("Trying to sync locally without a store");return[4,this.store.delete(this.cid)];case 3:return e.sent(),null===(s=this.collection)||void 0===s||s.remove(this),[4,r()];case 4:return e.sent(),this.data.deleted=!0,[2]}}))}))},n.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},n.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 2:return t=e.sent(),r=this.toDTO(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,v(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,5];case 4:throw a=e.sent(),this.remote.synchronising=!1,a;case 5:return[2]}}))}))},n.prototype.postRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,n,i,o,c,u,d;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),o={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:return o.Authorization=s.apply("Bearer ",[e.sent()]),r=o,[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/samples"),t,{headers:r,timeout:12e4})];case 2:return[2,e.sent().data];case 3:if(n=e.sent(),409===(i=n).status&&(null===(c=i.response)||void 0===c?void 0:c.data.duplicate_of))return[2,y(this,i.response.data.duplicate_of.id)];if(a.isAxiosNetworkError(i))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===i.status)throw g(t),new Error(l.getErrorMessageFromObject(null===(d=null===(u=i.response)||void 0===u?void 0:u.data)||void 0===d?void 0:d.message));throw new Error(i.message);case 4:return[2]}}))}))},n.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i,u,d,l,p,h,m,f,v,_,y,g,w,b,A,O=this;return e.__generator(this,(function(E){switch(E.label){case 0:if(!(t=this.remote.url)||t.includes("index.php"))throw new Error('A "remote" property is not configured.');if(!this.cid)throw new Error("Sample cid or id is missing for fetching remote model.");return[4,this.remote.getAccessToken()];case 1:return r=E.sent(),[4,c.fetchElasticSample({id:this.id,cid:this.cid,url:t,accessToken:r})];case 2:return s=E.sent(),this.data.surveyId||(this.data.surveyId=s.metadata.survey.id),n=this.getSurvey(),a=this.constructor.fromElasticDTO(s,{url:t,skipStore:!0},n),this.id=a.id,this.cid=a.cid||this.cid,Object.assign(this.data,a.data),Object.assign(this.metadata,a.metadata),i=c.fetchElasticSubSamples({parentId:this.id,url:t,accessToken:r}),u=o.fetchElasticOccurrences({parentId:this.id,url:t,accessToken:r}),[4,Promise.all([i,u])];case 3:return d=E.sent(),l=d[0],p=d[1],h=(new Date).getTime(),m=function(e){var r=O.constructor.fromElasticDTO(e,{url:t},O.getSurvey());return r.syncedAt=h,r},f=l.map(m),v=function(t,r){var s;return e.__assign(e.__assign({},t),((s={})[r.id]=r,s))},_=f.reduce(v,((b={})[this.id]=this,b)),this.samples.clear(),(A=this.samples).push.apply(A,f),y=function(e){var t=O.Occurrence.fromElasticDTO(e,O.remote.url,O.getSurvey());return t.syncedAt=h,[t,e.event.event_id]},g=p.map(y),w=function(e){var t=e[0],r=e[1];r!==parseInt(O.id,10)?_[r]?_[r].occurrences.push(t):console.log("Can't attach occ to missing ".concat(r," sample")):O.occurrences.push(t)},g.forEach(w),this.syncedAt=h,[2]}}))}))},n.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,t={},r=this.toDTO(t),[4,this.putRemote(this.id,r)];case 2:return v(this,e.sent()),s=(new Date).getTime(),this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1,[3,4];case 3:throw n=e.sent(),this.remote.synchronising=!1,n;case 4:return[2]}}))}))},n.prototype.putRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,n,i,o,c,u,d;return e.__generator(this,(function(e){switch(e.label){case 0:return c={},n="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:c.Authorization=n.apply("Bearer ",[e.sent()]),s=c,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.put("".concat(this.remote.url,"/samples/").concat(t),r,{headers:s,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if(i=e.sent(),o=i,a.isAxiosNetworkError(o))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw g(r),new Error(l.getErrorMessageFromObject(null===(d=null===(u=o.response)||void 0===u?void 0:u.data)||void 0===d?void 0:d.message));throw new Error(o.message);case 5:return[2]}}))}))},n.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,i,o,c,u,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,_(this)];case 1:if(r=l.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,s,n,i;return e.__generator(this,(function(e){switch(e.label){case 0:return i={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:i.Authorization=s.apply("Bearer ",[e.sent()]),r=i,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/media-queue"),t,{headers:r,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if("timeout"===(n=e.sent()).message)throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");throw n;case 5:return[2]}}))}))},n=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.data.queued?t[r.cid]={name:r.data.queued}:n.push(e)})),o=5,c=function(r){var a,i,c,u;return e.__generator(this,(function(d){switch(d.label){case 0:return a=n.slice(r,r+o),i=new FormData,a.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return c=d.sent(),u=(new Date).getTime(),a.forEach((function(e){var t=e[0];t.syncedAt=u,t.data.queued=c[t.cid].name})),t=e.__assign(e.__assign({},t),c),[2]}}))},u=0,l.label=2;case 2:return u<n.length?[5,c(u)]:[3,5];case 3:l.sent(),l.label=4;case 4:return u+=o,[3,2];case 5:return[2,t]}}))}))},n.prototype.toDTO=function(t){var r=this;void 0===t&&(t={});var a="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},n.keys),a),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var c=function(e,t){var s=i[e].values;if(!s)return t;if("function"==typeof s)return s(t,o,r);if(t instanceof Array)return t.map((function(t){return c(e,t)}));if(s instanceof Array){var n=s.find((function(e){return e.value===t}));if(!n||!n.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return n.id}return s[t]};Object.keys(this.data).forEach((function(e){var t=r.data[e],n=function(e){return null==e};if(!n(t)){if(!i[e])return e=e.includes("smpAttr:")?e:s.snakeCase(e),void(o.values[e]=t);if(!n(t=c(e,t))){var a=i[e].id||e,u=Number.isNaN(Number(a))?a:"smpAttr:".concat(a);u=u.includes("smpAttr:")?u:s.snakeCase(u),o.values[u]=t}}})),this.samples.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.toDTO(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.toDTO(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.toDTO(t);r&&o.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(o,this):o},Object.defineProperty(n.prototype,"isUploaded",{get:function(){return this.parent?this.parent.isUploaded:!!this.syncedAt},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),n.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}}},n}(i.default);exports.default=w,exports.getMediaFormData=_;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),i=require("lodash"),r=require("wellknown"),a=require("@flumens/utils"),o=require("../Model.js"),n=require("./ElasticOccurrence.js"),d=require("./ElasticSample.js"),c=require("./Media.js"),u=require("./Occurrence.js"),l=require("./helpers.js");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var m=h(s),p=h(r);const v=(e,t={})=>s=>s instanceof e?s:new e(Object.assign(Object.assign({},s),t));function f(e,t){var s,i,r,a,o;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(r=e.samples)||void 0===r||r.forEach(((e,s)=>f(e,t.samples[s])))),e.occurrences&&t.occurrences&&(null===(a=e.occurrences)||void 0===a||a.forEach(((e,s)=>f(e,t.occurrences[s])))),e.media&&t.media&&(null===(o=e.media)||void 0===o||o.forEach(((e,s)=>f(e,t.media[s]))));else{if("process"in window&&"test"===(null===(i=null===(s=window.process)||void 0===s?void 0:s.env)||void 0===i?void 0:i.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}const y=t=>e.__awaiter(void 0,void 0,void 0,(function*(){const s=[];if(t.media){const i=t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=yield t.getFormData();return[t,e]})),r=yield Promise.all(t.media.map(i));s.push(...r)}if(t.occurrences){const e=yield Promise.all(t.occurrences.map(y));s.push(...e.flat())}if(t.samples){const e=yield Promise.all(t.samples.map(y));s.push(...e.flat())}return s}));function g(e,t){const s={values:{id:t||-1}};return e.occurrences&&(s.occurrences=e.occurrences.map((e=>g(e)))),e.samples&&(s.samples=e.samples.map((e=>g(e)))),e.media&&(s.media=e.media.map((e=>g(e)))),s}function w(e){try{const t=2e5;console.warn(JSON.stringify(e).substring(0,t/2))}catch(e){}}class O extends o.default{static fromElasticDTO(e,t={},s){var i,r;const{id:a,event:o,location:n,metadata:d}=e,{url:c}=t,u=new Date(o.date_start),h=new Date(d.updated_on).getTime(),m=Date.now(),[v,f]=n.point.split(",").map(parseFloat),y="OSGB"===n.output_sref_system?n.output_sref:"",g=n.geom?p.default.parse(n.geom):null,w=o.parent_event_id,O=l.parseRemoteAttrs(w?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,o.attributes||[]),b=null===(i=o.media)||void 0===i?void 0:i.map((({path:e})=>({id:e,metadata:{updatedOn:u,createdOn:u,syncedOn:u},data:{data:`${c}/upload/${e}`}})));return new this(Object.assign({id:a,cid:o.source_system_key||a,createdAt:u.getTime(),updatedAt:h,syncedAt:m,metadata:{saved:!0},data:Object.assign(Object.assign({},O),{surveyId:d.survey.id,date:u.toISOString(),location:{code:n.code,name:n.name||n.verbatim_locality,latitude:v,longitude:f,shape:g,gridref:y},enteredSrefSystem:4326,groupId:null===(r=d.group)||void 0===r?void 0:r.id,comment:o.event_remarks,training:"true"===d.trial}),media:b},t))}constructor(s={}){var{metadata:i={},samples:r=[],occurrences:a=[],media:o=[],Occurrence:n=u.default,Media:d=c.default,skipStore:h}=s,m=e.__rest(s,["metadata","samples","occurrences","media","Occurrence","Media","skipStore"]);m.createdAt=m.createdAt||(null==i?void 0:i.createdOn),m.updatedAt=m.updatedAt||(null==i?void 0:i.updatedOn),m.syncedAt=m.syncedAt||(null==i?void 0:i.syncedOn);const p=h?void 0:m.store;super(Object.assign(Object.assign({},m),{store:p})),this.validateRemote=l.validateRemoteModel,this.error=t.observable({message:""}),this.debouncedValue=300,this.keys=()=>{return Object.assign(Object.assign({},O.keys),(e=this.getSurvey().attrs||{},Object.keys(e).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:e[s].remote||e[s]})),{})));var e},this.requiresRemoteSync=()=>!this.syncedAt||this.updatedAt>this.syncedAt,this.Occurrence=n,this.Media=d,this.remote=t.observable({synchronising:!1,url:m.url,getAccessToken:m.getAccessToken}),this.metadata=t.observable(i);const f=r.map(v(this.constructor));this.samples=t.observable(f);const y=a.map(v(this.Occurrence,{Media:this.Media}));this.occurrences=t.observable(y);const g=o.map(v(this.Media));this.media=t.observable(g);const w=e=>e.parent=this;this.samples.forEach(w),this.occurrences.forEach(w),this.media.forEach(w);const b=e=>{var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(w),this.setUpdatedAtTimestamp(Date.now())):e.removedCount&&this.setUpdatedAtTimestamp(Date.now()),e};t.intercept(this.samples,b),t.intercept(this.occurrences,b),t.intercept(this.media,b)}setUpdatedAtTimestamp(e){var t;super.setUpdatedAtTimestamp(e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)}toJSON(){var e,s;const i=super.toJSON();return r=Object.assign(Object.assign({},i),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((e=>e.toJSON()))||[],samples:(null===(e=this.samples)||void 0===e?void 0:e.map((e=>e.toJSON())))||[],media:(null===(s=this.media)||void 0===s?void 0:s.map((e=>e.toJSON())))||[]}),JSON.parse(JSON.stringify(r));var r}getSurvey(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}}save(){return e.__awaiter(this,void 0,void 0,(function*(){if(this.data.deleted)return;if(this.parent)return void this.parent.save();if(!this.store)throw new Error("Trying to sync locally without a store");const t=this.toJSON(),{data:s,metadata:i,occurrences:r,samples:a,media:o}=t,n=e.__rest(t,["data","metadata","occurrences","samples","media"]),d=Object.assign(Object.assign({},n),{data:{data:s,metadata:i,occurrences:r,samples:a,media:o}});yield this.store.save(d)}))}destroy(t){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=()=>Promise.all([Promise.all(this.media.map((e=>e.destroy(!0)))),Promise.all(this.occurrences.map((e=>e.destroy(!0))))]);if(this.parent){if(this.parent.samples.remove(this),yield s(),t)return;this.parent.save()}else{if(!this.store)throw new Error("Trying to sync locally without a store");yield this.store.delete(this.cid),null===(e=this.collection)||void 0===e||e.remove(this),yield s(),this.data.deleted=!0}}))}sync(){const t=Object.create(null,{sync:{get:()=>super.sync}});return e.__awaiter(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():t.sync.call(this)}))}saveRemote(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');try{this.remote.synchronising=!0;const e=yield this.uploadMedia(),t=this.toDTO(e),s=yield this.postRemote(t);this.remote.synchronising=!1,f(this,s);const i=(new Date).getTime();this.updatedAt=i,this.syncedAt=i,this.save()}catch(e){throw this.remote.synchronising=!1,e}}))}postRemote(t){return e.__awaiter(this,void 0,void 0,(function*(){var e,s,i;try{const e={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};return(yield m.default.post(`${this.remote.url}/index.php/services/rest/samples`,t,{headers:e,timeout:12e4})).data}catch(r){const o=r;if(409===o.status&&(null===(e=o.response)||void 0===e?void 0:e.data.duplicate_of))return g(this,o.response.data.duplicate_of.id);if(a.isAxiosNetworkError(o))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw w(t),new Error(l.getErrorMessageFromObject(null===(i=null===(s=o.response)||void 0===s?void 0:s.data)||void 0===i?void 0:i.message));throw new Error(o.message)}}))}fetchRemote(){return e.__awaiter(this,void 0,void 0,(function*(){const{url:e}=this.remote;if(!e||e.includes("index.php"))throw new Error('A "remote" property is not configured.');if(!this.cid)throw new Error("Sample cid or id is missing for fetching remote model.");const t=yield this.remote.getAccessToken(),s=yield d.fetchElasticSample({id:this.id,cid:this.cid,url:e,accessToken:t});this.data.surveyId||(this.data.surveyId=s.metadata.survey.id);const i=this.getSurvey(),r=this.constructor.fromElasticDTO(s,{url:e,skipStore:!0},i);this.id=r.id,this.cid=r.cid||this.cid,Object.assign(this.data,r.data),Object.assign(this.metadata,r.metadata);const a=d.fetchElasticSubSamples({parentId:this.id,url:e,accessToken:t}),o=n.fetchElasticOccurrences({parentId:this.id,url:e,accessToken:t}),[c,u]=yield Promise.all([a,o]),l=(new Date).getTime(),h=c.map((t=>{const s=this.constructor.fromElasticDTO(t,{url:e},this.getSurvey());return s.syncedAt=l,s})),m=h.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.id]:t})),{[this.id]:this});this.samples.clear(),this.samples.push(...h);u.map((e=>{const t=this.Occurrence.fromElasticDTO(e,this.remote.url,this.getSurvey());return t.syncedAt=l,[t,e.event.event_id]})).forEach((([e,t])=>{t!==parseInt(this.id,10)?m[t]?m[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):this.occurrences.push(e)})),this.syncedAt=l}))}updateRemote(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');try{this.remote.synchronising=!0;const e={},t=this.toDTO(e);f(this,yield this.putRemote(this.id,t));const s=(new Date).getTime();this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1}catch(e){throw this.remote.synchronising=!1,e}}))}putRemote(t,s){return e.__awaiter(this,void 0,void 0,(function*(){var e,i;const r={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};try{return(yield m.default.put(`${this.remote.url}/samples/${t}`,s,{headers:r,timeout:12e4})).data}catch(t){const r=t;if(a.isAxiosNetworkError(r))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===r.status)throw w(s),new Error(l.getErrorMessageFromObject(null===(i=null===(e=r.response)||void 0===e?void 0:e.data)||void 0===i?void 0:i.message));throw new Error(r.message)}}))}uploadMedia(){return e.__awaiter(this,void 0,void 0,(function*(){let t={};const s=yield y(this);if(!s.length)return t;const i=t=>e.__awaiter(this,void 0,void 0,(function*(){const e={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};try{return(yield m.default.post(`${this.remote.url}/index.php/services/rest/media-queue`,t,{headers:e,timeout:12e4})).data}catch(e){if("timeout"===e.message)throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}})),r=[],o=Date.now()-432e5;s.forEach((e=>{const[s]=e;s.syncedAt>o&&s.data.queued?t[s.cid]={name:s.data.queued}:r.push(e)}));for(let e=0;e<r.length;e+=5){const s=r.slice(e,e+5),a=new FormData;s.forEach((([,e])=>a.append(...e)));const o=yield i(a),n=(new Date).getTime();s.forEach((([e])=>{e.syncedAt=n,e.data.queued=o[e.cid].name})),t=Object.assign(Object.assign({},t),o)}return t}))}toDTO(e={}){const t="function"==typeof this.keys?this.keys():this.keys,s=Object.assign(Object.assign({},O.keys),t),r={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(r.values.id=this.id);const a=(e,t)=>{const i=s[e].values;if(!i)return t;if("function"==typeof i)return i(t,r,this);if(t instanceof Array)return t.map((t=>a(e,t)));if(i instanceof Array){const s=i.find((({value:e})=>e===t));if(!s||!s.id)throw new Error(`A "${e}" attribute "${t}" value could not be mapped to a remote database field.`);return s.id}return i[t]};Object.keys(this.data).forEach((e=>{let t=this.data[e];const o=e=>null==e;if(o(t))return;if(!s[e])return e=e.includes("smpAttr:")?e:i.snakeCase(e),void(r.values[e]=t);if(t=a(e,t),o(t))return;const n=s[e].id||e;let d=Number.isNaN(Number(n))?n:`smpAttr:${n}`;d=d.includes("smpAttr:")?d:i.snakeCase(d),r.values[d]=t})),this.samples.forEach((t=>{this.data.training&&(t.data.training=this.data.training);const s=t.toDTO(e);s&&r.samples.push(s)})),this.occurrences.forEach((t=>{this.data.training&&(t.data.training=this.data.training);const s=t.toDTO(e);s&&r.occurrences.push(s)})),this.media.forEach((t=>{const s=t.toDTO(e);s&&r.media.push(s)}));const o=this.getSurvey();return o.modifySubmission?o.modifySubmission(r,this):r}get isUploaded(){return this.parent?this.parent.isUploaded:!!this.syncedAt}get isDisabled(){return this.isUploaded}get isSynchronising(){return this.remote.synchronising}}O.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}}},exports.default=O,exports.getMediaFormData=y;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),
|
|
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;
|
package/dist/Indicia/helpers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("lodash");function t(e,t){const s=atob(e.split(",")[1]),r=[];for(let e=0;e<s.length;e++)r.push(s.charCodeAt(e));return new Blob([new Uint8Array(r)],{type:t})}function s(e){if(!e)return!1;return!!e.toString().match(/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i)}exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,r){if(s(e)){const s=t(e,r);return Promise.resolve(s)}return new Promise((t=>{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="blob",s.onload=()=>{const e=s.response;t(e)},s.send()}))},exports.getCamelCaseObj=t=>e.mapKeys(t,((t,s)=>e.camelCase(s))),exports.getErrorMessageFromObject=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""),exports.isDataURL=s,exports.parseRemoteAttrs=(e,t)=>{e=e||{};const s=Object.entries(e);return t.reduce(((e,t)=>{const r=s.find((([,e])=>{var s;return(null===(s=e.remote)||void 0===s?void 0:s.id)===parseInt(t.id,10)}));if(!r)return e;const[n]=r,o=isNaN(t.value)?t.value:parseFloat(t.value);return e[n]=o,e}),{})},exports.validateRemoteModel=function(){const e=this.getSurvey(),t=e.verify&&e.verify(this.data,this);let s={};if(t){const e=t&&"issues"in t;!("ValidationError"===(null==t?void 0:t.name)||"ValidationError"===(null==t?void 0:t.type))&&!e?s.errors=[t.message]:e?s.errors=t.issues.map((({message:e})=>e)):s=Object.assign({},t)}const r=(e,t)=>{const s=t.validateRemote();return s&&(e[t.cid]=s,e[t.cid].model=t),e},n=(this.samples||[]).reduce(r,{}),o=(this.occurrences||[]).reduce(r,{}),a=(this.media||[]).reduce(r,{});if(Object.keys(s).length||Object.keys(n).length||Object.keys(o).length||Object.keys(a).length){return{attributes:s,model:this,models:Object.assign(Object.assign(Object.assign({},n),o),a)}}return null};
|
package/dist/Model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils"),i=require("@flumens/utils");const d=t=>JSON.parse(JSON.stringify(t)),r={};exports.copyObject=d,exports.default=class{constructor({id:t="",cid:a="",createdAt:o,updatedAt:h,syncedAt:c,data:n={},attrs:u={},store:l}){this.ready=new i.Deferred,this.debouncedValue=3e3,this._observerPaused=!1,this.id=t,this.cid=a||t||i.UUIDv7();const v=Date.now();let y;this.createdAt=o||v,this.updatedAt=h||v,this.syncedAt=c,this.data=d(Object.assign(Object.assign(Object.assign({},r),n),u)),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,data:e.observable}),this.store=l;const b=(...t)=>{clearTimeout(y),y=setTimeout((()=>this.sync.apply(this,t)),this.debouncedValue)};s.deepObserve(this.data,(()=>{this._observerPaused||(this.updatedAt=Date.now(),b())}))}setUpdatedAtTimestamp(t){this.updatedAt=t}fetch(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store)return void this.ready.resolve(!1);const t=yield this.store.find(this.cid);if(!t)return yield this.save(),void this.ready.resolve(!0);t.id&&(this.id=t.id),t.cid&&(this.cid=t.cid),this._observerPaused=!0,e.set(this.data,t.data),this._observerPaused=!1,this.createdAt=t.createdAt,this.updatedAt=t.updatedAt,this.syncedAt=t.syncedAt,this.ready.resolve(!0)}))}save(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store)throw new Error("Trying to save locally without a store");const t=this.toJSON();yield this.store.save(t)}))}destroy(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store)throw new Error("Trying to delete locally without a store");yield this.store.delete(this.cid)}))}sync(...e){return t.__awaiter(this,void 0,void 0,(function*(){this.store&&(yield this.save())}))}toJSON(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,data:e.toJS(this.data)}}reset(t){this.id="";const s=JSON.parse(JSON.stringify(Object.assign(Object.assign({},r),t)));e.set(this.data,s);const i=Object.keys(s);return Object.keys(this.data).forEach((t=>{i.includes(t)||(this.data[t]=null,delete this.data[t])})),this.save()}get isStored(){return!!this.store}};
|
|
@@ -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"),
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),i=require("@capacitor-community/sqlite"),n=require("@capacitor/core"),o=require("@capacitor/filesystem"),s=require("@flumens/utils");exports.default=class{static migrateCordova(t){return e.__awaiter(this,void 0,void 0,(function*(){var e;console.log("SQLite: Cordova db migration");const n=new i.SQLiteConnection(i.CapacitorSQLite);try{const i=yield n.getMigratableDbList(t?"Library/LocalDatabase":void 0);if(!(null===(e=i.values)||void 0===e?void 0:e.length))return void console.log("SQLite: no Cordova db to migrate");console.log("SQLite: migrating",i.values),yield n.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,i.values),yield n.deleteOldDatabases(t?"Library/LocalDatabase":void 0,i.values),console.log("SQLite: migrating done",i.values)}catch(e){console.error(e)}yield n.checkConnectionsConsistency(),yield n.closeAllConnections()}))}get db(){return this.connection}constructor({name:e,debug:t,web:n}){this.sqliteConnection=new i.SQLiteConnection(i.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new s.Deferred,this.name=e||this.name,this.debug=t||this.debug,this.isWeb=n||this.isWeb}init(){return e.__awaiter(this,void 0,void 0,(function*(){if(this.isWeb){t.defineCustomElements(window);const e=document.createElement("jeep-sqlite");e.setAttribute("autoSave","true"),document.body.appendChild(e),yield customElements.whenDefined("jeep-sqlite"),yield this.sqliteConnection.initWebStore()}yield this.sqliteConnection.checkConnectionsConsistency(),yield this.sqliteConnection.closeAllConnections(),this.connection=yield this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1),yield this.connection.open(),this.ready.resolve(!0)}))}query(t){return e.__awaiter(this,arguments,void 0,(function*({sql:e,params:t}){var i;yield this.ready;const n=yield this.db.query(e,t).then((e=>e.values||[]));return this.debug&&(console.groupCollapsed(`💾 SQL: ${e.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30)}...`),console.debug(e,t,n),console.groupEnd(),yield null===(i=this.sqliteConnection)||void 0===i?void 0:i.saveToStore(this.name)),n}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){if(this.isWeb){const{name:e}=this;return new Promise((t=>{indexedDB.open("jeepSqliteStore").onsuccess=function(i){i.target.result.transaction(["databases"],"readwrite").objectStore("databases").get(`${e}SQLite.db`).onsuccess=function(e){const i=new Blob([e.target.result],{type:"application/vnd.sqlite3"});t(i)}}}))}const{url:e}=yield this.db.getUrl();return(yield fetch(n.Capacitor.convertFileSrc(e))).blob()}))}import(t){return e.__awaiter(this,void 0,void 0,(function*(){if(this.isWeb){const e=new Uint8Array(yield t.arrayBuffer()),{name:i}=this;return void new Promise((t=>{indexedDB.open("jeepSqliteStore").onsuccess=function(n){n.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(e,`${i}SQLite.db`,0).onsuccess=()=>t()}}))}const{url:e}=yield this.db.getUrl(),i=yield new Promise((e=>{const i=new FileReader;i.onload=e,i.readAsDataURL(t)})).then((e=>e.target.result));yield o.Filesystem.writeFile({path:e,data:i})}))}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("drizzle-orm"),i=require("drizzle-orm/casing"),r=require("drizzle-orm/sqlite-core"),d=require("@flumens/utils"),n=require("./utils.js");function a(e,i){const r=t.getTableColumns(e);return Object.entries(r).filter((([e])=>!i.includes(e))).reduce(((e,[i,r])=>Object.assign(Object.assign({},e),{[i]:t.sql.raw(`excluded.${r.name}`)})),{})}const s=e=>r.customType({dataType:()=>"jsonb",toDriver:e=>JSON.stringify(e)})(e),l=new r.SQLiteSyncDialect,o=()=>({id:r.text(),cid:r.text().primaryKey().notNull().default("id"),data:s("data").notNull(),createdAt:r.integer("created_at").notNull(),updatedAt:r.integer("updated_at").notNull(),syncedAt:r.integer("synced_at")});exports.conflictUpdateAllExcept=a,exports.default=class{constructor({db:e,name:t,debug:i,columns:n=o()}){this.ready=new d.Deferred,this.db=e,this.name=t,this.debug=i||!1,this.table=r.sqliteTable(this.name,n),this.init()}init(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.db.ready;const e=r.getTableConfig(this.table).columns.map((e=>`${e.name} ${e.getSQLType()}${e.primary?" primary key":""}${e.notNull?" not null":""}${e.default?` default ${e.default}`:""}`)).join(",\n");yield this.db.query({sql:`CREATE TABLE IF NOT EXISTS ${this.name} (${e});`}),this.ready.resolve(!0)}))}save(t){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;if(!(Array.isArray(t)?t.length:t))return;if(this.debug&&t.cid){const e=yield this.find({cid:t.cid});n.printDiff(e,t,t.cid,this.name)}let e=new r.SQLiteInsertBuilder(this.table,{},l).values(t);const i=this._getPrimaryCol();i&&(e=e.onConflictDoUpdate({target:i,set:a(this.table,[])})),yield this.db.query(e.toSQL())}))}find(i){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const[e]=yield this.findAll((e=>{if("function"==typeof i)return i(e).limit(1);if("string"==typeof i){const r=this._getPrimaryCol();if(!r)throw new Error("Primary col is missing");return e.where(t.eq(r,i)).limit(1)}const r=Object.entries(i).map((([e,i])=>t.eq(this.table[e],i)));return e.where(t.and(...r)).limit(1)}));return e}))}findAll(d){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;let e=(new r.QueryBuilder).select().from(this.table);d&&(e=d(e));return(yield this.db.query(e.toSQL())).map((e=>Object.entries(e).reduce(((e,[r,d])=>{var n;const a="jsonb"===(null===(n=t.getTableColumns(this.table)[r])||void 0===n?void 0:n.sqlName);return e[i.toCamelCase(r)]=a?JSON.parse(d):d,e}),{})))}))}delete(i){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;yield this.deleteAll((e=>{if("function"==typeof i)return i(e);if("string"==typeof i){const r=this._getPrimaryCol();if(!r)throw new Error("Primary col is missing");return e.where(t.eq(r,i))}const r=Object.entries(i).map((([e,i])=>t.eq(this.table[e],i)));return e.where(t.and(...r))}))}))}deleteAll(t){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;let e=new r.SQLiteDeleteBase(this.table,{},l);t&&(e=t(e)),yield this.db.query(e.toSQL())}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;return(yield this.findAll()).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.cid]:t})),{})}))}import(t){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,yield this.deleteAll(),"object"!=typeof t)throw new Error("Invalid obj passed to store");const i=Object.entries(t).map((([,t])=>this.save((t=>{var i,r,d,n,a,s;if(!t.createdAt&&(null===(i=t.metadata)||void 0===i?void 0:i.createdOn)&&(t.createdAt=null===(r=t.metadata)||void 0===r?void 0:r.createdOn),!t.updatedAt&&(null===(d=t.metadata)||void 0===d?void 0:d.updatedOn)&&(t.updatedAt=null===(n=t.metadata)||void 0===n?void 0:n.updatedOn),!t.syncedAt&&(null===(a=t.metadata)||void 0===a?void 0:a.syncedOn)&&(t.syncedAt=null===(s=t.metadata)||void 0===s?void 0:s.syncedOn),t.samples){const{id:i,cid:r,createdAt:d,updatedAt:n,syncedAt:a}=t,s=e.__rest(t,["id","cid","createdAt","updatedAt","syncedAt"]);t={id:i,cid:r,createdAt:d,updatedAt:n,syncedAt:a,data:Object.assign({},s)}}return t})(t))));Promise.all(i)}))}_getPrimaryCol(){return Object.values(t.getTableColumns(this.table)).find((({primary:e})=>!!e))}},exports.defaultCols=o,exports.jsonb=s;
|
package/dist/Stores/Store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.default=class{};
|
package/dist/Stores/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("deep-diff"),o=require("lodash");exports.printDiff=function(r,n,l,t=""){const s=e.diff(r,n);if(!s)return;let i={},u=0,f="";if(s.forEach((e=>{const r={[t]:{[l]:{}}};if(!e.path)return r[t][l]=e.rhs,console.groupCollapsed(`Δ + ${l}`),console.log(r),void console.groupEnd();e.path.reduce(((o,r,n)=>{if(e.path.length-1>n)return o[r]={},o[r];const l=JSON.stringify(e.lhs,null,2),t=JSON.stringify(e.rhs,null,2);if(l===t)return o[r];u++,o[r]=`${l} -> ${t}`,f=`${r}: ${l} -> ${t}`}),r[t][l]),i=o.merge(i,r)})),u){let e=`Δ ${l}`;1===u&&(e+=` ${f}`),console.groupCollapsed(e),console.log(i),console.groupEnd()}};
|