@flumens/models 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Drupal/User.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { z } from 'zod';
|
|
2
2
|
import Model, { Attrs as GenericModelAttrs, Options as GenericModelOptions } from '../Model';
|
|
3
3
|
export type BackendConfig = {
|
|
4
4
|
/**
|
|
@@ -39,11 +39,60 @@ export interface Options extends GenericModelOptions {
|
|
|
39
39
|
}
|
|
40
40
|
export default class DrupalUserModel<T extends Attrs = Attrs> extends Model<T> {
|
|
41
41
|
config: BackendConfig;
|
|
42
|
-
loginSchema:
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
static loginSchema: z.ZodObject<{
|
|
43
|
+
email: z.ZodString;
|
|
44
|
+
password: z.ZodString;
|
|
45
|
+
}, "strip", z.ZodTypeAny, {
|
|
46
|
+
email: string;
|
|
47
|
+
password: string;
|
|
48
|
+
}, {
|
|
49
|
+
email: string;
|
|
50
|
+
password: string;
|
|
51
|
+
}>;
|
|
52
|
+
static loginSchemaBackend: z.ZodObject<{
|
|
53
|
+
id: z.ZodNumber;
|
|
54
|
+
email: z.ZodString;
|
|
55
|
+
}, "strip", z.ZodTypeAny, {
|
|
56
|
+
id: number;
|
|
57
|
+
email: string;
|
|
58
|
+
}, {
|
|
59
|
+
id: number;
|
|
60
|
+
email: string;
|
|
61
|
+
}>;
|
|
62
|
+
static resetSchema: z.ZodObject<{
|
|
63
|
+
email: z.ZodString;
|
|
64
|
+
}, "strip", z.ZodTypeAny, {
|
|
65
|
+
email: string;
|
|
66
|
+
}, {
|
|
67
|
+
email: string;
|
|
68
|
+
}>;
|
|
69
|
+
static registerSchema: z.ZodObject<{
|
|
70
|
+
email: z.ZodString;
|
|
71
|
+
password: z.ZodString;
|
|
72
|
+
}, "strip", z.ZodTypeAny, {
|
|
73
|
+
email: string;
|
|
74
|
+
password: string;
|
|
75
|
+
}, {
|
|
76
|
+
email: string;
|
|
77
|
+
password: string;
|
|
78
|
+
}>;
|
|
79
|
+
static registerSchemaBackend: z.ZodObject<{
|
|
80
|
+
uid: z.ZodArray<z.ZodObject<{
|
|
81
|
+
value: z.ZodNumber;
|
|
82
|
+
}, "strip", z.ZodTypeAny, {
|
|
83
|
+
value: number;
|
|
84
|
+
}, {
|
|
85
|
+
value: number;
|
|
86
|
+
}>, "many">;
|
|
87
|
+
}, "strip", z.ZodTypeAny, {
|
|
88
|
+
uid: {
|
|
89
|
+
value: number;
|
|
90
|
+
}[];
|
|
91
|
+
}, {
|
|
92
|
+
uid: {
|
|
93
|
+
value: number;
|
|
94
|
+
}[];
|
|
95
|
+
}>;
|
|
47
96
|
private _refreshingProfilePromise?;
|
|
48
97
|
private _refreshingTokenPromise?;
|
|
49
98
|
constructor({ config, ...options }: Options);
|
package/dist/Drupal/User.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("zod"),i=require("@flumens/utils/dist/errors"),n=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e,t){Object.keys(t).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!t[r])return;if(Array.isArray(t[r])&&t[r].length)return void(e[s]=t[r][0].value);e[s]=t[r]}}))}var u=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new i.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new i.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new i.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new i.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new i.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 i.HandledError("Timeout");throw e},h=6e4;var d={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0},l=function(t){function i(r){var s=this,i=r.config,n=e.__rest(r,["config"]);return(s=t.call(this,e.__assign(e.__assign({},n),{attrs:e.__assign(e.__assign({},d),n.attrs)}))||this).config=i,s}return e.__extends(i,t),i.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.attrs.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},i.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var n,a,d,l;return e.__generator(this,(function(f){switch(f.label){case 0:return n=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),a={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:n,timeout:h},[4,o.default(a).catch(u)];case 1:if(d=f.sent().data,!!i.registerSchemaBackend.safeParse(d).error)throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 2:return l=f.sent(),this.attrs.tokens=l,this.id=d.uid[0].value,this.attrs.email=t,c(this.attrs,d),[2,this.save()]}}))}))},i.prototype.reset=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,i;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(u)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(i=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return u(i),[3,6];case 6:return[2]}}))}))},i.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(u)];case 2:return e.sent(),this.logOut(),[2]}}))}))},i.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),this.attrs.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:h},[4,o.default(r).catch(u)]):[3,3];case 2:s=e.sent().data,this.attrs.email=s.mail[0].value,c(this.attrs,s),e.label=3;case 3:return[4,this.save()];case 4:return e.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},i.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},i.prototype.isLoggedIn=function(){return this.attrs.email,!!this.id},i.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.resetDefaults()]}))}))},i.prototype.resetDefaults=function(r){return t.prototype.resetDefaults.call(this,e.__assign(e.__assign({},d),r))},i.prototype.getAccessToken=function(t){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n,a,o,c;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(i=(this.attrs.tokens||{}).access_token,n=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(i),!(!i||n||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return a=e.sent(),console.error(a),o="The refresh token is invalid."===a.message,c="Token has no user email."===a.message,o||c?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw a;case 6:return[2,null===(s=this.attrs.tokens)||void 0===s?void 0:s.access_token]}}))}))},i.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.attrs.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:h},[2,o.default(s).catch(u)]}))}))},i.prototype._exchangePasswordToTokens=function(t,r){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n;return e.__generator(this,(function(e){switch(e.label){case 0:return(i=new FormData).append("grant_type","password"),i.append("username",t),i.append("password",r),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass),(null===(s=this.config.scopes)||void 0===s?void 0:s.length)&&i.append("scope",this.config.scopes.join(" ")),n={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:i},[4,o.default(n).catch(u)];case 1:return[2,e.sent().data]}}))}))},i.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:if(!(t=(this.attrs.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:h},[4,o.default(i).catch(u)];case 1:if(n=l.sent().data,this.attrs.tokens=e.__assign(e.__assign({},this.attrs.tokens),n),a=r.jwtDecode(null===(d=this.attrs.tokens)||void 0===d?void 0:d.access_token),this.id=a.sub,this.attrs.email=a.email,!this.attrs.email)throw new Error("Token has no user email.");return this.attrs.verified=a.email_verified,this.attrs.iss=a.iss,this.attrs.indiciaUserId=a["http://indicia.org.uk/user:id"],a.scopes&&(this.attrs.roles=a.scopes),c(this.attrs,a),[4,this.save()];case 2:return l.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},i.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),i.resetSchema=s.object({email:s.z.string().email("Please fill in")}),i.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),i}(n.default);exports.default=l;
|
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("@flumens/utils/dist/errors"),a=require("../Model.js"),i=require("./Media.js"),o=require("./Occurrence.js"),u=require("./helpers.js");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=c(r);function l(e,t){var r,s,n,a;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(s=e.samples)||void 0===s||s.forEach((function(e,r){return l(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(n=e.occurrences)||void 0===n||n.forEach((function(e,r){return l(e,t.occurrences[r])}))),e.media&&t.media&&(null===(a=e.media)||void 0===a||a.forEach((function(e,r){return l(e,t.media[r])})));else{if("test"===(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var h=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(h))]:[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(h))]:[3,6];case 5:n=a.sent(),r.push.apply(r,n.flat()),a.label=6;case 6:return[2,r]}}))}))};function m(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return m(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return m(e)}))),e.media&&(r.media=e.media.map((function(e){return m(e)}))),r}function p(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var f=function(r){function a(s){var n=this;void 0===s&&(s={});var i=s.metadata,o=void 0===i?{}:i,c=s.samples,d=void 0===c?[]:c,l=s.occurrences,h=void 0===l?[]:l,m=s.media,p=void 0===m?[]:m,f=s.attrs,v=void 0===f?{}:f,_=e.__rest(s,["metadata","samples","occurrences","media","attrs"]),y={date:(new Date).toISOString(),location_type:"latlon"};(n=r.call(this,e.__assign(e.__assign({},_),{attrs:e.__assign(e.__assign({},y),v)}))||this).remote=t.observable({synchronising:!1,url:null,headers:{},timeout:12e4}),n.validateRemote=u.validateRemoteModel,n.error=t.observable({message:""}),n.debouncedValue=300,n.keys=function(){return e.__assign(e.__assign({},a.keys),function(t){return Object.keys(t).reduce((function(r,s){var n;return e.__assign(e.__assign({},r),((n={})[s]=t[s].remote||t[s],n))}),{})}(n.getSurvey().attrs||{}))},n.requiresRemoteSync=function(){return!n.syncedAt||n.updatedAt>n.syncedAt},n.metadata=t.observable(o),n.samples=t.observable(d),n.occurrences=t.observable(h),n.media=t.observable(p);var g=function(e){return e.parent=n};n.samples.forEach(g),n.occurrences.forEach(g),n.media.forEach(g);var w=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(g),n.setupdatedAtTimestamp(Date.now())):e.removedCount&&n.setupdatedAtTimestamp(Date.now()),e};return t.intercept(n.samples,w),t.intercept(n.occurrences,w),t.intercept(n.media,w),n}return e.__extends(a,r),a.fromJSON=function(t,r,s,n){var a,u,c,d,l,h,m;void 0===r&&(r=o.default),void 0===s&&(s=this),void 0===n&&(n=i.default);var p=(null===(a=null==t?void 0:t.attrs)||void 0===a?void 0:a.attrs)?null==t?void 0:t.attrs:t;return new this(e.__assign(e.__assign({},t),{attrs:p.attrs,metadata:p.metadata,createdAt:t.createdAt||(null===(u=t.metadata)||void 0===u?void 0:u.createdOn),updatedAt:t.updatedAt||(null===(c=t.metadata)||void 0===c?void 0:c.updatedOn),syncedAt:t.syncedAt||(null===(d=t.metadata)||void 0===d?void 0:d.syncedOn),samples:null===(l=p.samples)||void 0===l?void 0:l.map((function(e){return s.fromJSON(e,r,s,n)})),occurrences:null===(h=p.occurrences)||void 0===h?void 0:h.map((function(e){return r.fromJSON(e,n)})),media:null===(m=p.media)||void 0===m?void 0:m.map((function(e){return n.fromJSON(e)}))}))},a.prototype.setupdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setupdatedAtTimestamp(e)},a.prototype.toJSON=function(){var s,n,a,i,o=r.prototype.toJSON.call(this);return this.parent?JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(a=this.samples)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[],media:(null===(i=this.media)||void 0===i?void 0:i.map((function(e){return e.toJSON()})))||[]}))):JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{attrs:{attrs:o.attrs,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()})))||[]}})))},a.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},a.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(r){switch(r.label){case 0:if(this.attrs.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(),[4,this.store.save(e.__assign(e.__assign({},t),{data:t.attrs}))];case 1:return r.sent(),[2]}}))}))},a.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(s.media.map((function(e){return e.destroy(!0)}))),Promise.all(s.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(),this.collection&&this.collection.remove(this),[4,r()];case 4:return e.sent(),this.attrs.deleted=!0,[2]}}))}))},a.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)]}))}))},a.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)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.getSubmission(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,l(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]}}))}))},a.prototype.postRemote=function(t){var r,s,a;return e.__awaiter(this,void 0,void 0,(function(){var i,o,c,l,h;return e.__generator(this,(function(e){switch(e.label){case 0:return i=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return c=e.sent(),[3,3];case 2:c=this.remote.headers,e.label=3;case 3:o=c,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.post("".concat(i,"/samples"),t,{headers:o,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if(l=e.sent(),409===(h=l).status&&(null===(r=h.response)||void 0===r?void 0:r.data.duplicate_of))return[2,m(this,h.response.data.duplicate_of.id)];if(n.isAxiosNetworkError(h))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===h.status)throw p(t),new Error(u.getErrorMessageFromObject(null===(a=null===(s=h.response)||void 0===s?void 0:s.data)||void 0===a?void 0:a.message));throw new Error(h.message);case 7:return[2]}}))}))},a.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){throw new Error("Not implemented.")}))}))},a.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)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.getSubmission(t),[4,this.putRemote(this.id,r)];case 2:return l(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]}}))}))},a.prototype.putRemote=function(t,r){var s,a;return e.__awaiter(this,void 0,void 0,(function(){var i,o,c,l,h;return e.__generator(this,(function(e){switch(e.label){case 0:return i=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return c=e.sent(),[3,3];case 2:c=this.remote.headers,e.label=3;case 3:o=c,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.put("".concat(i,"/samples/").concat(t),r,{headers:o,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if(l=e.sent(),h=l,n.isAxiosNetworkError(h))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===h.status)throw p(r),new Error(u.getErrorMessageFromObject(null===(a=null===(s=h.response)||void 0===s?void 0:s.data)||void 0===a?void 0:a.message));throw new Error(h.message);case 7:return[2]}}))}))},a.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,i,o,u,c,l=this;return e.__generator(this,(function(m){switch(m.label){case 0:return t={},[4,h(this)];case 1:if(r=m.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(l,void 0,void 0,(function(){var r,s,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:return r=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return a=e.sent(),[3,3];case 2:a=this.remote.headers,e.label=3;case 3:s=a,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.post("".concat(r,"/media-queue"),t,{headers:s,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if("timeout"===(i=e.sent()).message)throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");throw i;case 7:return[2]}}))}))},a=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.attrs.queued?t[r.cid]={name:r.attrs.queued}:a.push(e)})),o=5,u=function(r){var n,i,u,c;return e.__generator(this,(function(d){switch(d.label){case 0:return n=a.slice(r,r+o),i=new FormData,n.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return u=d.sent(),c=(new Date).getTime(),n.forEach((function(e){var t=e[0];t.syncedAt=c,t.attrs.queued=u[t.cid].name})),t=e.__assign(e.__assign({},t),u),[2]}}))},c=0,m.label=2;case 2:return c<a.length?[5,u(c)]:[3,5];case 3:m.sent(),m.label=4;case 4:return c+=o,[3,2];case 5:return[2,t]}}))}))},a.prototype.getSubmission=function(t){var r=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},a.keys),n),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var u=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 u(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.attrs).forEach((function(e){var t=r.attrs[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=u(e,t))){var a=i[e].id||e,c=Number.isNaN(Number(a))?a:"smpAttr:".concat(a);c=c.includes("smpAttr:")?c:s.snakeCase(c),o.values[c]=t}}})),this.samples.forEach((function(e){r.attrs.training&&(e.attrs.training=r.attrs.training);var s=e.getSubmission(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.attrs.training&&(e.attrs.training=r.attrs.training);var s=e.getSubmission(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&o.media.push(r)}));var c=this.getSurvey();return c.modifySubmission?c.modifySubmission(o,this):o},a.prototype.isUploaded=function(){return this.parent?this.parent.isUploaded():!!this.syncedAt},a.prototype.isDisabled=function(){return this.isUploaded()},a.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}},group:{id:"group_id"},training:{id:"training",values:u.boolToWarehouseValue},deleted:{id:"deleted",values:u.boolToWarehouseValue}},a}(a.default);exports.default=f,exports.getMediaFormData=h;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("lodash"),n=require("@flumens/utils/dist/errors"),a=require("../Model.js"),i=require("./Media.js"),o=require("./Occurrence.js"),u=require("./helpers.js");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=c(r);function l(e,t){var r,s,n,a;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(s=e.samples)||void 0===s||s.forEach((function(e,r){return l(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(n=e.occurrences)||void 0===n||n.forEach((function(e,r){return l(e,t.occurrences[r])}))),e.media&&t.media&&(null===(a=e.media)||void 0===a||a.forEach((function(e,r){return l(e,t.media[r])})));else{if("test"===(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var h=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(h))]:[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(h))]:[3,6];case 5:n=a.sent(),r.push.apply(r,n.flat()),a.label=6;case 6:return[2,r]}}))}))};function m(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return m(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return m(e)}))),e.media&&(r.media=e.media.map((function(e){return m(e)}))),r}function p(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var f=function(r){function a(s){var n=this;void 0===s&&(s={});var i=s.metadata,o=void 0===i?{}:i,c=s.samples,d=void 0===c?[]:c,l=s.occurrences,h=void 0===l?[]:l,m=s.media,p=void 0===m?[]:m,f=s.attrs,v=void 0===f?{}:f,_=e.__rest(s,["metadata","samples","occurrences","media","attrs"]),y={date:(new Date).toISOString(),location_type:"latlon"};(n=r.call(this,e.__assign(e.__assign({},_),{attrs:e.__assign(e.__assign({},y),v)}))||this).remote=t.observable({synchronising:!1,url:null,headers:{},timeout:12e4}),n.validateRemote=u.validateRemoteModel,n.error=t.observable({message:""}),n.debouncedValue=300,n.keys=function(){return e.__assign(e.__assign({},a.keys),function(t){return Object.keys(t).reduce((function(r,s){var n;return e.__assign(e.__assign({},r),((n={})[s]=t[s].remote||t[s],n))}),{})}(n.getSurvey().attrs||{}))},n.requiresRemoteSync=function(){return!n.syncedAt||n.updatedAt>n.syncedAt},n.metadata=t.observable(o),n.samples=t.observable(d),n.occurrences=t.observable(h),n.media=t.observable(p);var g=function(e){return e.parent=n};n.samples.forEach(g),n.occurrences.forEach(g),n.media.forEach(g);var w=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(g),n.setupdatedAtTimestamp(Date.now())):e.removedCount&&n.setupdatedAtTimestamp(Date.now()),e};return t.intercept(n.samples,w),t.intercept(n.occurrences,w),t.intercept(n.media,w),n}return e.__extends(a,r),a.fromJSON=function(t,r,s,n){var a,u,c,d,l,h,m;void 0===r&&(r=o.default),void 0===s&&(s=this),void 0===n&&(n=i.default);var p=(null===(a=null==t?void 0:t.attrs)||void 0===a?void 0:a.attrs)?null==t?void 0:t.attrs:t;return new this(e.__assign(e.__assign({},t),{attrs:p.attrs,metadata:p.metadata,createdAt:t.createdAt||(null===(u=t.metadata)||void 0===u?void 0:u.createdOn),updatedAt:t.updatedAt||(null===(c=t.metadata)||void 0===c?void 0:c.updatedOn),syncedAt:t.syncedAt||(null===(d=t.metadata)||void 0===d?void 0:d.syncedOn),samples:null===(l=p.samples)||void 0===l?void 0:l.map((function(e){return s.fromJSON(e,r,s,n)})),occurrences:null===(h=p.occurrences)||void 0===h?void 0:h.map((function(e){return r.fromJSON(e,n)})),media:null===(m=p.media)||void 0===m?void 0:m.map((function(e){return n.fromJSON(e)}))}))},a.prototype.setupdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setupdatedAtTimestamp(e)},a.prototype.toJSON=function(){var s,n,a,i,o=r.prototype.toJSON.call(this);return this.parent?JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(a=this.samples)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[],media:(null===(i=this.media)||void 0===i?void 0:i.map((function(e){return e.toJSON()})))||[]}))):JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{attrs:{attrs:o.attrs,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()})))||[]}})))},a.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},a.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(r){switch(r.label){case 0:if(this.attrs.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(),[4,this.store.save(e.__assign(e.__assign({},t),{data:t.attrs}))];case 1:return r.sent(),[2]}}))}))},a.prototype.destroy=function(t){var r;return e.__awaiter(this,void 0,void 0,(function(){var s,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return s=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,s()]):[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===(r=this.collection)||void 0===r||r.remove(this),[4,s()];case 4:return e.sent(),this.attrs.deleted=!0,[2]}}))}))},a.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)]}))}))},a.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)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.getSubmission(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,l(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]}}))}))},a.prototype.postRemote=function(t){var r,s,a;return e.__awaiter(this,void 0,void 0,(function(){var i,o,c,l,h;return e.__generator(this,(function(e){switch(e.label){case 0:return i=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return c=e.sent(),[3,3];case 2:c=this.remote.headers,e.label=3;case 3:o=c,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.post("".concat(i,"/samples"),t,{headers:o,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if(l=e.sent(),409===(h=l).status&&(null===(r=h.response)||void 0===r?void 0:r.data.duplicate_of))return[2,m(this,h.response.data.duplicate_of.id)];if(n.isAxiosNetworkError(h))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===h.status)throw p(t),new Error(u.getErrorMessageFromObject(null===(a=null===(s=h.response)||void 0===s?void 0:s.data)||void 0===a?void 0:a.message));throw new Error(h.message);case 7:return[2]}}))}))},a.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){throw new Error("Not implemented.")}))}))},a.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)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.getSubmission(t),[4,this.putRemote(this.id,r)];case 2:return l(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]}}))}))},a.prototype.putRemote=function(t,r){var s,a;return e.__awaiter(this,void 0,void 0,(function(){var i,o,c,l,h;return e.__generator(this,(function(e){switch(e.label){case 0:return i=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return c=e.sent(),[3,3];case 2:c=this.remote.headers,e.label=3;case 3:o=c,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.put("".concat(i,"/samples/").concat(t),r,{headers:o,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if(l=e.sent(),h=l,n.isAxiosNetworkError(h))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===h.status)throw p(r),new Error(u.getErrorMessageFromObject(null===(a=null===(s=h.response)||void 0===s?void 0:s.data)||void 0===a?void 0:a.message));throw new Error(h.message);case 7:return[2]}}))}))},a.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,i,o,u,c,l=this;return e.__generator(this,(function(m){switch(m.label){case 0:return t={},[4,h(this)];case 1:if(r=m.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(l,void 0,void 0,(function(){var r,s,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:return r=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return a=e.sent(),[3,3];case 2:a=this.remote.headers,e.label=3;case 3:s=a,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.post("".concat(r,"/media-queue"),t,{headers:s,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if("timeout"===(i=e.sent()).message)throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");throw i;case 7:return[2]}}))}))},a=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.attrs.queued?t[r.cid]={name:r.attrs.queued}:a.push(e)})),o=5,u=function(r){var n,i,u,c;return e.__generator(this,(function(d){switch(d.label){case 0:return n=a.slice(r,r+o),i=new FormData,n.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return u=d.sent(),c=(new Date).getTime(),n.forEach((function(e){var t=e[0];t.syncedAt=c,t.attrs.queued=u[t.cid].name})),t=e.__assign(e.__assign({},t),u),[2]}}))},c=0,m.label=2;case 2:return c<a.length?[5,u(c)]:[3,5];case 3:m.sent(),m.label=4;case 4:return c+=o,[3,2];case 5:return[2,t]}}))}))},a.prototype.getSubmission=function(t){var r=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},a.keys),n),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var u=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 u(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.attrs).forEach((function(e){var t=r.attrs[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=u(e,t))){var a=i[e].id||e,c=Number.isNaN(Number(a))?a:"smpAttr:".concat(a);c=c.includes("smpAttr:")?c:s.snakeCase(c),o.values[c]=t}}})),this.samples.forEach((function(e){r.attrs.training&&(e.attrs.training=r.attrs.training);var s=e.getSubmission(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.attrs.training&&(e.attrs.training=r.attrs.training);var s=e.getSubmission(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&o.media.push(r)}));var c=this.getSurvey();return c.modifySubmission?c.modifySubmission(o,this):o},a.prototype.isUploaded=function(){return this.parent?this.parent.isUploaded():!!this.syncedAt},a.prototype.isDisabled=function(){return this.isUploaded()},a.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}},group:{id:"group_id"},training:{id:"training",values:u.boolToWarehouseValue},deleted:{id:"deleted",values:u.boolToWarehouseValue}},a}(a.default);exports.default=f,exports.getMediaFormData=h;
|
|
@@ -21,6 +21,7 @@ export default class SQLiteDatabase {
|
|
|
21
21
|
constructor({ name, debug, web }: SQLiteDatabaseOptions);
|
|
22
22
|
init(): Promise<void>;
|
|
23
23
|
query<T>({ sql, params }: Query): Promise<T[]>;
|
|
24
|
-
|
|
24
|
+
export(): Promise<Blob>;
|
|
25
|
+
import(blob: Blob): Promise<void>;
|
|
25
26
|
}
|
|
26
27
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite");function
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite"),r=require("@capacitor/core"),i=require("@capacitor/filesystem");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=s(require("@flumens/utils/dist/deferred")),a=function(){function s(e){var t=e.name,r=e.debug,i=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new o.default,this.name=t||this.name,this.debug=r||this.debug,this.isWeb=i||this.isWeb}return s.migrateCordova=function(t){var r;return e.__awaiter(this,void 0,void 0,(function(){var i,s,o;return e.__generator(this,(function(e){switch(e.label){case 0:console.log("SQLite: Cordova db migration"),i=new n.SQLiteConnection(n.CapacitorSQLite),e.label=1;case 1:return e.trys.push([1,5,,6]),[4,i.getMigratableDbList(t?"Library/LocalDatabase":void 0)];case 2:return s=e.sent(),(null===(r=s.values)||void 0===r?void 0:r.length)?(console.log("SQLite: migrating",s.values),[4,i.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,s.values)]):(console.log("SQLite: no Cordova db to migrate"),[2]);case 3:return e.sent(),[4,i.deleteOldDatabases(t?"Library/LocalDatabase":void 0,s.values)];case 4:return e.sent(),console.log("SQLite: migrating done",s.values),[3,6];case 5:return o=e.sent(),console.error(o),[3,6];case 6:return[4,i.checkConnectionsConsistency()];case 7:return e.sent(),[4,i.closeAllConnections()];case 8:return e.sent(),[2]}}))}))},Object.defineProperty(s.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),s.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,r;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t.defineCustomElements(window),(n=document.createElement("jeep-sqlite")).setAttribute("autoSave","true"),document.body.appendChild(n),[4,customElements.whenDefined("jeep-sqlite")]):[3,3];case 1:return e.sent(),[4,this.sqliteConnection.initWebStore()];case 2:e.sent(),e.label=3;case 3:return[4,this.sqliteConnection.checkConnectionsConsistency()];case 4:return e.sent(),[4,this.sqliteConnection.closeAllConnections()];case 5:return e.sent(),r=this,[4,this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1)];case 6:return r.connection=e.sent(),[4,this.connection.open()];case 7:return e.sent(),this.ready.resolve(!0),[2]}}))}))},s.prototype.query=function(t){var n,r=t.sql,i=t.params;return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.db.query(r,i).then((function(e){return e.values||[]}))];case 2:return t=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(r.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(r,i,t),console.groupEnd(),[4,null===(n=this.sqliteConnection)||void 0===n?void 0:n.saveToStore(this.name)]):[3,4];case 3:e.sent(),e.label=4;case 4:return[2,t]}}))}))},s.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t=this.name,[2,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(n){n.target.result.transaction(["databases"],"readwrite").objectStore("databases").get("".concat(t,"SQLite.db")).onsuccess=function(t){var n=new Blob([t.target.result],{type:"application/vnd.sqlite3"});e(n)}}}))]):[4,this.db.getUrl()];case 1:return n=e.sent().url,[4,fetch(r.Capacitor.convertFileSrc(n))];case 2:return[2,e.sent().blob()]}}))}))},s.prototype.import=function(t){return e.__awaiter(this,void 0,void 0,(function(){var n,r,s,o,a;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(r=Uint8Array.bind,[4,t.arrayBuffer()]):[3,2];case 1:return n=new(r.apply(Uint8Array,[void 0,e.sent()])),s=this.name,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(t){t.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(n,"".concat(s,"SQLite.db"),0).onsuccess=function(){return e()}}})),[2];case 2:return[4,this.db.getUrl()];case 3:return o=e.sent().url,[4,new Promise((function(e){var n=new FileReader;n.onload=e,n.readAsDataURL(t)})).then((function(e){return e.target.result}))];case 4:return a=e.sent(),[4,i.Filesystem.writeFile({path:o,data:a})];case 5:return e.sent(),[2]}}))}))},s}();exports.default=a;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils/dist/deferred"),a=require("./utils.js");function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var o=s(i);function u(r,n){var i=e.getTableColumns(r);return Object.entries(i).filter((function(t){var e=t[0];return!n.includes(e)})).reduce((function(r,n){var i,a=n[0],s=n[1];return t.__assign(t.__assign({},r),((i={})[a]=e.sql.raw("excluded.".concat(s.name)),i))}),{})}var c=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},d=new n.SQLiteSyncDialect,l=function(){function i(t){var e=t.db,r=t.name,i=t.debug,a=t.columns,s=void 0===a?{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:c("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}:a;this.ready=new o.default,this.db=e,this.name=r,this.debug=i||!1,this.table=n.sqliteTable(this.name,s),this.init()}return i.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},d).values(e),(s=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:s,set:u(this.table,[])})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},i.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},i.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},i.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},i.prototype.deleteAll=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},d),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},i.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.ready];case 1:return r.sent(),e=function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.cid]=r,n))},[4,this.findAll()];case 2:return[2,r.sent().reduce(e,{})]}}))}))},i.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,c=e.cid,d=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:c,createdAt:d,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},i.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},i}();exports.conflictUpdateAllExcept=u,exports.default=l,exports.jsonb=c;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils/dist/deferred"),a=require("./utils.js");function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var o=s(i);function u(r,n){var i=e.getTableColumns(r);return Object.entries(i).filter((function(t){var e=t[0];return!n.includes(e)})).reduce((function(r,n){var i,a=n[0],s=n[1];return t.__assign(t.__assign({},r),((i={})[a]=e.sql.raw("excluded.".concat(s.name)),i))}),{})}var c=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},d=new n.SQLiteSyncDialect,l=function(){function i(t){var e=t.db,r=t.name,i=t.debug,a=t.columns,s=void 0===a?{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:c("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}:a;this.ready=new o.default,this.db=e,this.name=r,this.debug=i||!1,this.table=n.sqliteTable(this.name,s),this.init()}return i.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),(Array.isArray(e)?e.length:e)?this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3]:[2];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},d).values(e),(s=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:s,set:u(this.table,[])})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},i.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},i.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},i.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},i.prototype.deleteAll=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},d),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},i.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.ready];case 1:return r.sent(),e=function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.cid]=r,n))},[4,this.findAll()];case 2:return[2,r.sent().reduce(e,{})]}}))}))},i.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,c=e.cid,d=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:c,createdAt:d,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},i.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},i}();exports.conflictUpdateAllExcept=u,exports.default=l,exports.jsonb=c;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flumens/models",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/src/index.d.ts",
|
|
6
6
|
"scripts": {
|
|
@@ -34,7 +34,9 @@
|
|
|
34
34
|
"@flumens/utils": "*"
|
|
35
35
|
},
|
|
36
36
|
"optionalDependencies": {
|
|
37
|
-
"@capacitor
|
|
37
|
+
"@capacitor/core": "^6",
|
|
38
|
+
"@capacitor/filesystem": "^6",
|
|
39
|
+
"@capacitor-community/sqlite": "^6",
|
|
38
40
|
"deep-diff": "^1",
|
|
39
41
|
"drizzle-orm": "^0.34.1",
|
|
40
42
|
"jeep-sqlite": "^2.8.0",
|
|
@@ -42,7 +44,7 @@
|
|
|
42
44
|
"localforage": "^1",
|
|
43
45
|
"localforage-cordovasqlitedriver": "^1",
|
|
44
46
|
"mobx-utils": "^6",
|
|
45
|
-
"
|
|
47
|
+
"zod": "^3"
|
|
46
48
|
},
|
|
47
49
|
"jest": {
|
|
48
50
|
"testEnvironment": "jsdom",
|