@flumens/models 0.30.0 → 0.32.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.
Files changed (48) hide show
  1. package/dist/Collection.mjs +1 -0
  2. package/dist/Drupal/User.d.ts +14 -0
  3. package/dist/Drupal/User.mjs +1 -0
  4. package/dist/Drupal/user-lifecycle.e2e.d.ts +1 -0
  5. package/dist/Drupal/user-lifecycle.e2e.mjs +1 -0
  6. package/dist/Indicia/ElasticOccurrence.mjs +1 -0
  7. package/dist/Indicia/ElasticSample.mjs +1 -0
  8. package/dist/Indicia/Group.mjs +1 -0
  9. package/dist/Indicia/GroupCollection.mjs +1 -0
  10. package/dist/Indicia/Location.mjs +1 -0
  11. package/dist/Indicia/LocationCollection.mjs +1 -0
  12. package/dist/Indicia/Media.mjs +1 -0
  13. package/dist/Indicia/Occurrence.mjs +1 -0
  14. package/dist/Indicia/Sample.mjs +1 -0
  15. package/dist/Indicia/SampleCollection.mjs +1 -0
  16. package/dist/Indicia/helpers.mjs +1 -0
  17. package/dist/Model.mjs +1 -0
  18. package/dist/Stores/LocalForageStore.mjs +1 -0
  19. package/dist/Stores/SQLiteDatabase.mjs +1 -0
  20. package/dist/Stores/SQLiteStore.mjs +1 -0
  21. package/dist/Stores/Store.mjs +1 -0
  22. package/dist/Stores/utils.mjs +1 -0
  23. package/dist/Stores.d.ts +1 -0
  24. package/dist/Stores.mjs +1 -0
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.mjs +1 -0
  27. package/package.json +32 -7
  28. package/dist/Collection.js +0 -1
  29. package/dist/Drupal/User.js +0 -1
  30. package/dist/Indicia/ElasticOccurrence.js +0 -1
  31. package/dist/Indicia/ElasticSample.js +0 -1
  32. package/dist/Indicia/Group.js +0 -1
  33. package/dist/Indicia/GroupCollection.js +0 -1
  34. package/dist/Indicia/Location.js +0 -1
  35. package/dist/Indicia/LocationCollection.js +0 -1
  36. package/dist/Indicia/Media.js +0 -1
  37. package/dist/Indicia/Occurrence.js +0 -1
  38. package/dist/Indicia/Sample.js +0 -1
  39. package/dist/Indicia/SampleCollection.js +0 -1
  40. package/dist/Indicia/helpers.js +0 -1
  41. package/dist/Model.js +0 -1
  42. package/dist/Stores/LocalForageStore.js +0 -1
  43. package/dist/Stores/SQLiteDatabase.js +0 -1
  44. package/dist/Stores/SQLiteStore.js +0 -1
  45. package/dist/Stores/Store.js +0 -1
  46. package/dist/Stores/index.js +0 -1
  47. package/dist/Stores/utils.js +0 -1
  48. package/dist/index.js +0 -1
@@ -0,0 +1 @@
1
+ import{__awaiter as t}from"tslib";import{observable as i,intercept as e}from"mobx";import{Deferred as d,UUIDv7 as s}from"@flumens/utils";import r from"./Model.mjs";class a{constructor({id:t,cid:a,data:o=[],store:h,Model:n=r}){this.ready=new d,this.data=i.array(o),this.id=this.id||t,this.cid=this.cid||a||t||s(),this.Model=n,this.store=this.store||h,this.cidMap=i.map(),this.idMap=i.map();e(this.data,(t=>{if("update"===t.type)return t;const{added:i,index:e,removedCount:d,object:s}=t;if(t.removedCount>0){s.slice(e,e+d).forEach((t=>{this.cidMap.delete(t.cid),t.id&&this.idMap.delete(t.id)}))}return i.forEach((t=>{this.cidMap.set(t.cid,t),this.idMap.set(t.id,t)})),t}))}fetch(){return t(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(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)}upsert(...t){t.forEach((t=>{const i=this.data.findIndex((i=>!!i.id&&i.id===t.id||!!i.cid&&i.cid===t.cid));this.data[i]?this.data.spliceWithArray(i,1,[t]):this.data.push(t)}))}[Symbol.iterator](){return this.data[Symbol.iterator]()}get length(){return this.data.length}}export{a as default};
@@ -1,5 +1,19 @@
1
1
  import { z } from 'zod';
2
+ import { HandledError } from '@flumens/utils';
2
3
  import Model, { Data as GenericModelData, Options as GenericModelOptions } from '../Model';
4
+ export declare enum DrupalUserErrorCode {
5
+ EmailTaken = "AUTH_EMAIL_TAKEN",
6
+ InvalidCredentials = "AUTH_INVALID_CREDENTIALS",
7
+ UnrecognizedEmail = "AUTH_UNRECOGNIZED_EMAIL",
8
+ AccountAlreadyActivated = "AUTH_ACCOUNT_ALREADY_ACTIVATED",
9
+ AccountInactive = "AUTH_ACCOUNT_INACTIVE",
10
+ Timeout = "AUTH_REQUEST_TIMEOUT"
11
+ }
12
+ export declare class DrupalUserError extends HandledError {
13
+ readonly code: DrupalUserErrorCode;
14
+ readonly cause: unknown;
15
+ constructor(code: DrupalUserErrorCode, message: string, cause?: unknown);
16
+ }
3
17
  export type BackendConfig = {
4
18
  /**
5
19
  * Site URL without a trailing slash.
@@ -0,0 +1 @@
1
+ import{__rest as e,__awaiter as i}from"tslib";import t from"axios";import{jwtDecode as s}from"jwt-decode";import{object as r,z as o}from"zod";import{HandledError as n}from"@flumens/utils";import a from"../Model.mjs";function d(e){const i={};return Object.keys(e).forEach((t=>{if(t.match(/^field_/)){const s=t.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[t])return;if(Array.isArray(e[t])&&e[t].length)return void(i[s]=e[t][0].value);i[s]=e[t]}})),i}var c;!function(e){e.EmailTaken="AUTH_EMAIL_TAKEN",e.InvalidCredentials="AUTH_INVALID_CREDENTIALS",e.UnrecognizedEmail="AUTH_UNRECOGNIZED_EMAIL",e.AccountAlreadyActivated="AUTH_ACCOUNT_ALREADY_ACTIVATED",e.AccountInactive="AUTH_ACCOUNT_INACTIVE",e.Timeout="AUTH_REQUEST_TIMEOUT"}(c||(c={}));class h extends n{constructor(e,i,t){super(i),this.name="DrupalUserError",this.code=e,this.cause=t}}const l=e=>{var i,t,s,r,o;const n=(null===(t=null===(i=e.response)||void 0===i?void 0:i.data)||void 0===t?void 0:t.error_description)||(null===(r=null===(s=e.response)||void 0===s?void 0:s.data)||void 0===r?void 0:r.message);if(n){if(n.includes("is already taken"))throw new h(c.EmailTaken,"This email is already taken.",e);if("The user credentials were incorrect."===n)throw new h(c.InvalidCredentials,"Incorrect password or email",e);if("Unrecognized username or email address."===n)throw new h(c.UnrecognizedEmail,"Unrecognized email address.",e);if("This account is already activated"===n)throw new h(c.AccountAlreadyActivated,"This account is already activated.",e);if(n.includes("not been activated"))throw new h(c.AccountInactive,"The user has not been activated or is blocked.",e);throw new Error(n)}if(null===(o=e.message)||void 0===o?void 0:o.includes("timeout"))throw new h(c.Timeout,"Timeout",e);throw e},u=6e4;const f={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class m extends a{constructor(i){var{config:t}=i,s=e(i,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},f),s.data)})),this.config=t}logIn(e,t){return i(this,void 0,void 0,(function*(){const i=yield this._exchangePasswordToTokens(e,t);return this.data.tokens=i,yield this.refreshProfile(),this.save()}))}register(e,s,r){return i(this,void 0,void 0,(function*(){const i=JSON.stringify(Object.assign({name:[{value:e}],pass:[{value:s}],mail:[{value:e}]},r)),o={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:i,timeout:u},{data:n}=yield t(o).catch(l);if(!!m.registerSchemaBackend.safeParse(n).error)throw new Error("Invalid backend response.");const a=yield this._exchangePasswordToTokens(e,s);this.id=n.uid[0].value;const c=d(n);return Object.assign(this.data,Object.assign({email:e,tokens:a,profileFetched:!0},c)),this.save()}))}resetPassword(e){return i(this,void 0,void 0,(function*(){const i=JSON.stringify({mail:e}),s={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:i};try{yield t(s).catch(l)}catch(i){if("The user has not been activated or is blocked."===i.message)return void(yield this._sendVerificationEmail(e));l(i)}}))}delete(){return i(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),i={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield t(i).catch(l),this.logOut()}))}updateRemote(e){return i(this,void 0,void 0,(function*(){const i=yield this.getAccessToken(),s={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:e,headers:{Authorization:`Bearer ${i}`},timeout:u};yield t(s),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return i(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>i(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const i={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:u},{data:s}=yield t(i).catch(l),r=d(s);Object.assign(this.data,Object.assign({email:s.mail[0].value,profileFetched:!0},r))}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 i(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},f),e))}getAccessToken(e){return i(this,void 0,void 0,(function*(){if(!e&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:i}=this.data.tokens||{},t=function(e){if(!e)return!0;const{exp:i}=s(e),t=1e3*i;return Date.now()+12e4>t}(i);if(!i||t||e)try{yield this._refreshAccessToken()}catch(e){console.error(e);const i="The refresh token is invalid."===e.message,t="Token has no user email."===e.message;if(i||t)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(e){return i(this,void 0,void 0,(function*(){const i=JSON.stringify({mail:[{value:e||this.data.email}]}),s={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:i,timeout:u};return t(s).catch(l)}))}_exchangePasswordToTokens(e,s){return i(this,void 0,void 0,(function*(){var i;const r=new FormData;r.append("grant_type","password"),r.append("username",e),r.append("password",s),r.append("client_id",this.config.clientId),this.config.clientPass&&r.append("client_secret",this.config.clientPass),(null===(i=this.config.scopes)||void 0===i?void 0:i.length)&&r.append("scope",this.config.scopes.join(" "));const o={method:"post",url:`${this.config.url}/oauth/token`,data:r},{data:n}=yield t(o).catch(l);return n}))}_refreshAccessToken(){return i(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>i(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 i=new FormData;i.append("grant_type","refresh_token"),i.append("refresh_token",e),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass);const r={method:"post",url:`${this.config.url}/oauth/token`,data:i,timeout:u},{data:o}=yield t(r).catch(l),n=Object.assign(Object.assign({},this.data.tokens),o),a=s(n.access_token),{email:c}=a;if(!c)throw new Error("Token has no user email.");const{iss:h,email_verified:f}=a,m=a["http://indicia.org.uk/user:id"],g=a.scopes,v=d(a);this.id=a.sub,Object.assign(this.data,Object.assign({email:c,roles:g,verified:f,iss:h,indiciaUserId:m,tokens:n},v)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}m.loginSchema=r({email:o.string().email("Please fill in"),password:o.string().min(1,"Please fill in")}),m.loginSchemaBackend=r({id:o.number(),email:o.string().email()}),m.resetSchema=r({email:o.string().email("Please fill in")}),m.registerSchema=r({email:o.string().email("Please fill in"),password:o.string().min(1,"Please fill in")}),m.registerSchemaBackend=r({uid:o.array(r({value:o.number()}))});export{h as DrupalUserError,c as DrupalUserErrorCode,m as default};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ import{__awaiter as e}from"tslib";import t from"node:assert/strict";import{test as o}from"node:test";import{MailSlurp as n}from"mailslurp-client";const i=12e4,a="https://example.com",r="http://indicia.org.uk/user:id";function s(e){console.info(`[user lifecycle] ${e}`)}function d(e){const o=process.env[e];return t.ok(o,`${e} must be set`),o}const l=new URL(d("DRUPAL_SITE_URL")),c=d("APP_BACKEND_CLIENT_ID"),u=process.env.APP_BACKEND_CLIENT_PASS,f=new n({apiKey:d("MAILSLURP_API_KEY")});function m(e){return new URL(e,l)}function h(e){return`'${e.replaceAll("'","'\\''")}'`}function p(e,t={}){const o=["curl",`--request ${t.method||"GET"}`,h(e.toString())];if(new Headers(t.headers).forEach(((e,t)=>{o.push(`--header ${h(`${t}: ${e}`)}`)})),t.body instanceof FormData)for(const[e,n]of t.body.entries())o.push(`--form ${h(`${e}=${String(n)}`)}`);if(t.body instanceof URLSearchParams)for(const[e,n]of t.body.entries())o.push(`--data-urlencode ${h(`${e}=${n}`)}`);return"string"==typeof t.body&&o.push(`--data ${h(t.body)}`),o.map(((e,t)=>t?` ${e}`:e)).join(" \\\n")}function v(e){console.error(`[user lifecycle] Failed request:\n${e}`)}function y(e,o){const n=e.headers.get("access-control-allow-origin"),i="*"===n||n===a;i||v(o),t.ok(i,`${e.url} returned ${e.status} with Access-Control-Allow-Origin: ${n||"missing"}`)}function g(t){return e(this,arguments,void 0,(function*(e,t={}){const o=m(e),n=new Headers(t.headers);n.set("Origin",a);const i=Object.assign(Object.assign({},t),{headers:n}),r=p(o,i);let s;try{s=yield fetch(o,i)}catch(e){throw v(r),e}return y(s,r),{response:s,curl:r}}))}function k(o,n){return e(this,arguments,void 0,(function*(e,o,n=[]){var i,r;const d=new Headers({Origin:a,"Access-Control-Request-Method":o});n.length&&d.set("Access-Control-Request-Headers",n.join(", "));const l=m(e),c={method:"OPTIONS",headers:d},u=p(l,c);let f;try{f=yield fetch(l,c)}catch(e){throw v(u),e}y(f,u);const h=(null===(i=f.headers.get("access-control-allow-methods"))||void 0===i?void 0:i.toUpperCase())||"",g=(null===(r=f.headers.get("access-control-allow-headers"))||void 0===r?void 0:r.toLowerCase())||"";f.ok&&(h.includes("*")||h.includes(o))&&!n.some((e=>!g.includes(e)))||v(u),t.ok(f.ok,`CORS preflight returned ${f.status}`),t.ok(h.includes("*")||h.includes(o),`CORS preflight did not allow ${o}`);for(const e of n)t.ok(g.includes(e),`CORS preflight did not allow ${e}`);s(`Validated CORS preflight for ${o} ${l.pathname}`)}))}function _(t){return e(this,arguments,void 0,(function*(t,o={}){const{response:n,curl:i}=yield g(t,o);return yield function(t,o){return e(this,void 0,void 0,(function*(){if(!t.ok)throw v(o),new Error(`${t.url} returned ${t.status}: ${yield t.text()}`);s(`Received ${t.status} from ${new URL(t.url).pathname}`)}))}(n,i),n}))}function w(e,t){const o=new FormData;return o.append("grant_type","password"),o.append("username",e),o.append("password",t),o.append("client_id",c),u&&o.append("client_secret",u),o}function $(e){const t=new FormData;return t.append("grant_type","refresh_token"),t.append("refresh_token",e),t.append("client_id",c),u&&t.append("client_secret",u),t}function S(e){const o=e.split(".")[1];return t.ok(o,"Access token is not a JWT"),JSON.parse(Buffer.from(o,"base64url").toString())}function j(e,o,n){const i=S(e);t.equal(i.email,o),t.equal(i.email_verified,n),t.ok(i[r],`JWT did not include ${r}`),s(`Validated JWT email, verification, and ${r}`)}function E(o){return e(this,void 0,void 0,(function*(){var e;const n=(o.isHTML?(yield f.emailController.getEmailLinks({emailId:o.id})).links:(null===(e=o.body)||void 0===e?void 0:e.match(/https?:\/\/[^\s"'<>]+/g))||[]).map((e=>e.replaceAll("&amp;","&"))),i=n.find((e=>{const t=new URL(e,l);return/\/user\/(?:registrationpassword|reset)\//.test(t.pathname)}));return i||s(`Email links found: ${n.join(", ")||"none"}`),t.ok(i,"Drupal account link was not found in the email"),i}))}o("supports browser CORS requests",(()=>e(void 0,void 0,void 0,(function*(){yield k("/oauth/token","POST"),yield k("/user/register-with-password?_format=json","POST",["content-type"]),yield k("/user/register-with-password?_format=json&resendVerificationEmail=true","POST",["content-type"]),yield k("/user/password?_format=json","POST",["content-type"]),yield k("/user/1?_format=json","GET",["authorization"]),yield k("/user/1?_format=json","PATCH",["authorization","content-type"]),yield k("/user/1?_format=json","DELETE",["authorization"]),yield k("/user/login_status?_format=json","GET",["authorization"])})))),o("completes the Drupal user account lifecycle",{timeout:3e5},(o=>e(void 0,void 0,void 0,(function*(){var n,a,r,d,c,u,h,y,k,T,C,O,R,b;s(`Starting test against ${l.origin}`),s("Creating temporary MailSlurp inbox");const P=yield f.createInbox(),D=P.emailAddress,A=`E2e-${crypto.randomUUID()}-aA1!`,q="User",L="Updated",U="E2E User";let I,N,F,z=!1;t.ok(D,"MailSlurp did not create an email address"),o.after((()=>e(void 0,void 0,void 0,(function*(){s("Cleaning up test resources");const e=[f.deleteInbox(P.id)];F&&I&&!z&&(s(`Deleting Drupal account ${F} during cleanup`),e.push(fetch(m(`/user/${F}?_format=json`),{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}).then((e=>{e.ok||s(`Drupal account ${F} requires manual cleanup after delete returned ${e.status}`)})))),!F||I||z||s(`Drupal account ${F} requires manual cleanup because no access token was obtained`),yield Promise.allSettled(e),s("Cleanup complete")})))),s("Creating Drupal account");const J=yield _("/user/register-with-password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:[{value:D}],pass:[{value:A}],mail:[{value:D}],field_first_name:[{value:"E2E"}],field_last_name:[{value:q}]})}),V=yield J.json();F=null===(a=null===(n=V.uid)||void 0===n?void 0:n[0])||void 0===a?void 0:a.value,t.ok(F,"Registration response did not include a user ID"),s(`Created Drupal account ${F}`),s("Following the model registration login before verification");const B=yield _("/oauth/token",{method:"POST",body:w(D,A)}),x=yield B.json();I=x.access_token,N=x.refresh_token,t.ok(I,"Registration login did not return an access token"),t.ok(N,"Registration login did not return a refresh token"),j(I,D,!1),s("Confirmed the account can log in but remains unverified"),s("Waiting for account verification email");const H=yield f.waitForLatestEmail(P.id,i,!0);s("Received account verification email"),yield E(H),s("Validated initial account verification email"),s("Requesting a password reset for the unverified account"),yield _("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:D})}),s("Requesting a verification email for the unverified account"),yield _("/user/register-with-password?_format=json&resendVerificationEmail=true",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:[{value:D}]})}),s("Waiting for resent account verification email");const W=yield f.waitForLatestEmail(P.id,i,!0);t.notEqual(W.id,H.id,"Verification email was not resent");const M=yield E(W);s("Received resent account verification email"),s("Opening resent account verification link");const K={redirect:"manual"},G=p(new URL(M),K);let Y;try{Y=yield fetch(M,K)}catch(e){throw v(G),e}let Q=Y.ok||Y.status>=300&&Y.status<400;if(Q||v(G),504===Y.status){s("Checking whether the timed-out verification completed");const e=yield _("/oauth/token",{method:"POST",body:w(D,A)});Q=!0===S((yield e.json()).access_token).email_verified}t.ok(Q,`Verification returned ${Y.status}`),s(`Verified account with response ${Y.status}`),s("Requesting access and refresh tokens");const X=yield _("/oauth/token",{method:"POST",body:w(D,A)}),Z=yield X.json();I=Z.access_token,N=Z.refresh_token,t.ok(I,"Password grant did not return an access token"),t.ok(N,"Password grant did not return a refresh token"),j(I,D,!0),s("Received access and refresh tokens"),s("Fetching and validating account data");const ee=yield _(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),te=yield ee.json();t.equal(null===(d=null===(r=te.name)||void 0===r?void 0:r[0])||void 0===d?void 0:d.value,D),t.equal(null===(u=null===(c=te.mail)||void 0===c?void 0:c[0])||void 0===u?void 0:u.value,D),t.equal(null===(y=null===(h=te.field_first_name)||void 0===h?void 0:h[0])||void 0===y?void 0:y.value,"E2E"),t.equal(null===(T=null===(k=te.field_last_name)||void 0===k?void 0:k[0])||void 0===T?void 0:T.value,q),s("Validated account name, email, first name, and last name"),s("Updating account first and last names"),yield _(`/user/${F}?_format=json`,{method:"PATCH",headers:{Authorization:`Bearer ${I}`,"Content-Type":"application/json"},body:JSON.stringify({field_first_name:[{value:L}],field_last_name:[{value:U}]})}),s("Refreshing access token after account update");const oe=yield _("/oauth/token",{method:"POST",body:$(N)}),ne=yield oe.json();I=ne.access_token,N=ne.refresh_token||N,t.ok(I,"Refresh grant did not return an access token"),t.ok(N,"Refresh grant did not retain a refresh token"),j(I,D,!0),s("Refreshed access token after account update"),s("Fetching and validating updated account data");const ie=yield _(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),ae=yield ie.json();t.equal(null===(O=null===(C=ae.field_first_name)||void 0===C?void 0:C[0])||void 0===O?void 0:O.value,L),t.equal(null===(b=null===(R=ae.field_last_name)||void 0===R?void 0:R[0])||void 0===b?void 0:b.value,U),s("Updated and validated account data"),s("Requesting password reset email"),yield _("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:D})}),s("Waiting for password reset email");const re=yield f.waitForLatestEmail(P.id,i,!0);t.ok(re.to.includes(D),"Password reset email was not sent to the test account"),s("Received password reset email"),s("Deleting Drupal account"),yield _(`/user/${F}?_format=json`,{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}),z=!0,s("Checking the refresh token after account deletion");const se=$(N),{response:de,curl:le}=yield g("/oauth/token",{method:"POST",body:se});if(de.ok){const e=S((yield de.json()).access_token);t.equal(e.email,void 0,"Deleted account unexpectedly received a usable token"),s("Confirmed the deleted account token has no user email")}else{const e=yield de.text();v(le),t.match(e,/invalid|revoked|user|email/i),s(`Confirmed refresh was rejected with ${de.status}`)}s("Deleted Drupal account; lifecycle complete")}))));
@@ -0,0 +1 @@
1
+ import{__awaiter as e}from"tslib";import t from"axios";function r(r){return e(this,arguments,void 0,(function*({parentId:e,url:r,accessToken:n}){var o,i,a;const s={terms:{"event.parent_event_id":Array.isArray(e)?e:[e]}},c={terms:{"event.event_id":Array.isArray(e)?e:[e]}},d=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"]}),u={Authorization:`Bearer ${n}`},v={method:"post",url:`${r}/index.php/services/rest/es-occurrences/_search`,headers:Object.assign({"Content-Type":"application/json"},u),data:d};return(null===(a=null===(i=null===(o=(yield t.request(v)).data)||void 0===o?void 0:o.hits)||void 0===i?void 0:i.hits)||void 0===a?void 0:a.map((e=>e._source)))||[]}))}export{r as fetchElasticOccurrences};
@@ -0,0 +1 @@
1
+ import{__awaiter as e}from"tslib";import t from"axios";function o(o){return e(this,arguments,void 0,(function*({parentId:e,url:o,accessToken:i}){var a,n,s;const r=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.location_id","location.verbatim_locality"]}),d={Authorization:`Bearer ${i}`},u={method:"post",url:`${o}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},d),data:r};return(null===(s=null===(n=null===(a=(yield t.request(u)).data)||void 0===a?void 0:a.hits)||void 0===n?void 0:n.hits)||void 0===s?void 0:s.map((e=>e._source)))||[]}))}function i(o){return e(this,arguments,void 0,(function*({id:e,cid:o,url:i,accessToken:a}){var n,s,r;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":o}}]}}}));const u={Authorization:`Bearer ${a}`},l={method:"post",url:`${i}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},u),data:d},c=((null===(r=null===(s=null===(n=(yield t.request(l)).data)||void 0===n?void 0:n.hits)||void 0===s?void 0:s.hits)||void 0===r?void 0:r.map((e=>e._source)))||[])[0];if(!c)throw new Error(`Remote sample with id ${e||o} was not found`);return c}))}export{i as fetchElasticSample,o as fetchElasticSubSamples};
@@ -0,0 +1 @@
1
+ import{__rest as e,__awaiter as t}from"tslib";import{observable as o}from"mobx";import i from"axios";import{object as n,z as r}from"zod";import{getCamelCaseObj as s}from"@flumens/utils";import{isAxiosNetworkError as l,HandledError as a}from"@flumens/utils/dist/errors";import{UUIDv7 as d}from"@flumens/utils/dist/uuid";import u from"../Model.mjs";const c=n({id:r.string(),title:r.string(),createdOn:r.string(),description:r.string().nullable().optional(),groupType:r.string().nullable().optional(),joiningMethod:r.enum(["P","R","A","I"]).nullable().optional(),websiteId:r.string().nullable().optional(),groupTypeId:r.string().nullable().optional(),createdById:r.string().nullable().optional(),fromDate:r.string().nullable().optional(),toDate:r.string().nullable().optional(),indexedLocationIds:r.array(r.number()).nullable().optional(),userIsAdministrator:r.enum(["t","f"]).nullable().optional(),userIsMember:r.enum(["t","f"]).nullable().optional(),userIsPending:r.enum(["t","f"]).nullable().optional()}),p=n({id:r.string().nullable().optional(),createdOn:r.string().nullable().optional(),createdById:r.string().nullable().optional(),groupId:r.string().nullable().optional(),groupTitle:r.string().nullable().optional(),locationId:r.string(),locationName:r.string(),locationBoundaryGeom:r.string(),locationLat:r.string(),locationLon:r.string(),locationCreatedOn:r.string(),locationUpdatedOn:r.string(),locationCentroidSref:r.string(),locationCentroidSrefSystem:r.string(),locationCode:r.string().nullable().optional(),locationCreatedById:r.string().nullable().optional(),locationUpdatedById:r.string().nullable().optional(),locationComment:r.string().nullable().optional(),locationExternalKey:r.string().nullable().optional()});class g extends u{static fromDTO(t,o={}){c.parse(t);const{id:i,createdOn:n}=t,r=e(t,["id","createdOn"]);return new this(Object.assign({id:i,cid:d(),data:r,createdAt:new Date(n).getTime()},o))}constructor(t){var{skipStore:i,store:n,url:r,getAccessToken:s,getIndiciaUserId:l}=t,a=e(t,["skipStore","store","url","getAccessToken","getIndiciaUserId"]);super(Object.assign(Object.assign({},a),{store:i?void 0:n})),this.remote=o({synchronising:!1,url:r,getAccessToken:s,getIndiciaUserId:l})}join(){return t(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()}},n={headers:{Authorization:`Bearer ${t}`},timeout:8e4};try{yield i.post(e,o,n)}catch(e){if(i.isCancel(e))return;if(l(e))throw new a("Request aborted because of a network issue (timeout or similar).");throw e}}))}leave(){return t(this,void 0,void 0,(function*(){var e,t,o;const n=yield this.remote.getIndiciaUserId(),r=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users/${n}`,s={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{yield i.delete(r,s)}catch(n){if(i.isCancel(n))return;if(l(n))throw new a("Request aborted because of a network issue (timeout or similar).");if(null===(o=null===(t=null===(e=n.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 n}}))}addRemoteLocation(e){return t(this,void 0,void 0,(function*(){var t,o,n;console.log("Group location uploading");const r={values:{id:e}},s=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`;try{this.remote.synchronising=!0;const e={url:s,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:r};return yield i(e),this.remote.synchronising=!1,console.log("Group location uploading done"),this}catch(e){this.remote.synchronising=!1;const i=e;if(409===(null===(t=i.response)||void 0===t?void 0:t.status))return console.log("Location uploading duplicate was found"),this;const r=null===(n=null===(o=i.response)||void 0===o?void 0:o.data)||void 0===n?void 0:n.message;if(!r)throw e;if("object"==typeof r){throw new Error((e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""))(r))}throw new Error(r)}}))}fetchRemoteLocations(){return t(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 i.get(e,t),n=({values:e})=>s(e),r=o.data.map(n);return r.forEach((e=>p.parse(e))),r}catch(e){if(i.isCancel(e))return[];if(l(e))throw new a("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}}))}}export{g as default,c as dtoSchema};
@@ -0,0 +1 @@
1
+ import{__awaiter as e}from"tslib";import{observable as t}from"mobx";import s from"axios";import{getCamelCaseObj as i}from"@flumens/utils";import{isAxiosNetworkError as o,HandledError as r}from"@flumens/utils/dist/errors";import n from"../Collection.mjs";import a from"./Group.mjs";class l extends n{constructor(e){super(Object.assign({id:"groups",Model:a},e)),this.remote=t({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken})}fetchRemote(){return e(this,arguments,void 0,(function*(e={}){console.log(`📚 Collection: ${this.id} collection fetching`),this.remote.synchronising=!0;try{const{type:t,form:o,location:r}=e,n=yield this.remote.getAccessToken(),a=`${this.remote.url}/index.php/services/rest/groups`,l={};t&&(l.view=t),o&&(l.page=o.join(",")),Number.isFinite(r)&&(l.indexed_location_ids=r);const m={params:l,headers:{Authorization:`Bearer ${n}`},timeout:8e4},d=yield s.get(a,m),c=e=>!e.toDate||new Date(e.toDate)>new Date,h=e=>!e.fromDate||new Date(e.fromDate)<new Date,u=d.data.map((({values:e})=>e)).map(i).filter(c).filter(h),f=u.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&&(yield 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&&(yield 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&&(yield 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.upsert(...f),console.log(`📚 Collection: ${this.id} collection fetching done ${u.length} documents`)}catch(e){if(s.isCancel(e))return;if(o(e))throw new r("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}}function m(e){return t=>{const s=t.data.userIsMember||t.data.userIsPending;return"member"===e?s:!s}}export{m as byGroupMembershipStatus,l as default};
@@ -0,0 +1 @@
1
+ import{__rest as t,__awaiter as e}from"tslib";import{observable as i,intercept as n}from"mobx";import o from"axios";import{snakeCase as s}from"lodash";import{object as a,z as r}from"zod";import{UUIDv7 as d}from"@flumens/utils/dist/uuid";import l from"../Model.mjs";import c from"./Media.mjs";const u=a({lat:r.string().min(1),lon:r.string().min(1),name:r.string().min(1),locationTypeId:r.string().min(1),centroidSref:r.string().min(1),centroidSrefSystem:r.string().min(1),id:r.string().optional(),createdOn:r.string().optional(),updatedOn:r.string().optional(),parentId:r.string().nullable().optional(),boundaryGeom:r.string().nullable().optional(),code:r.string().nullable().optional(),createdById:r.string().nullable().optional(),updatedById:r.string().nullable().optional(),externalKey:r.string().nullable().optional(),centroidGeom:r.string().nullable().optional(),public:r.string().nullable().optional(),comment:r.string().nullable().optional()});var m;!function(t){t.MothTrap="18879",t.Transect="777",t.TransectSection="778",t.Site="14",t.BaitTrapSite="24555",t.BaitTrap="24554"}(m||(m={}));class p extends l{static fromDTO(e,i={}){u.parse(e);const{id:n,createdOn:o,updatedOn:s,externalKey:a}=e,r=t(e,["id","createdOn","updatedOn","externalKey"]);return new this(Object.assign({cid:a||d(),id:n,createdAt:new Date(o).getTime(),updatedAt:new Date(s).getTime(),data:r},i))}constructor(e={}){var{skipStore:o,store:s,media:a=[],metadata:r={},url:d,getAccessToken:l,Media:u=c}=e,m=t(e,["skipStore","store","media","metadata","url","getAccessToken","Media"]);super(Object.assign(Object.assign({},m),{store:o?void 0:s})),this.Media=u,this.metadata=i(r);const p=a.map(((t,e={})=>i=>i instanceof t?i:new t(Object.assign(Object.assign({},i),e)))(this.Media));this.media=i(p);const h=t=>t.parent=this;this.media.forEach(h);n(this.media,(t=>{var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(h),this.setUpdatedAtTimestamp(Date.now())):t.removedCount&&this.setUpdatedAtTimestamp(Date.now()),t})),this.remote=i({synchronising:!1,url:d,getAccessToken:l})}saveRemote(){return e(this,void 0,void 0,(function*(){var t,e,i,n,s;try{this.remote.synchronising=!0;const t=yield this.uploadMedia(),e=this.toDTO(t),i=`${this.remote.url}/index.php/services/rest/locations`,n={url:i,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:e},{data:s}=yield o(n),a=new Date(s.values.updated_on).getTime();return this.updatedAt=a,this.syncedAt=a,this.id=s.values.id,this.remote.synchronising=!1,this.store&&this.save(),console.log("Location uploading done"),this}catch(o){this.remote.synchronising=!1;const a=o;if(409===(null===(t=a.response)||void 0===t?void 0:t.status)&&(null===(e=a.response)||void 0===e?void 0:e.data.duplicate_of)){console.log("Location uploading duplicate was found");const t=(new Date).getTime();return this.updatedAt=t,this.syncedAt=t,this.id=null===(i=a.response)||void 0===i?void 0:i.data.duplicate_of.id,this}const r=null===(s=null===(n=a.response)||void 0===n?void 0:n.data)||void 0===s?void 0:s.message;if(!r)throw o;if("object"==typeof r){throw new Error((t=>Object.entries(t).reduce(((t,e)=>`${t}${e[0]} ${e[1]}\n`),""))(r))}throw new Error(r)}}))}toDTO(t={}){const e=(i=this.data,Object.entries(i).reduce(((t,[e,i])=>(t[e.includes("locAttr:")?e:s(e)]=i,t)),{}));var i;const n={values:Object.assign({external_key:this.cid},e),media:[]};return this.media.forEach((e=>{const i=e.toDTO(t);i&&n.media.push(i)})),n}uploadMedia(){return e(this,void 0,void 0,(function*(){yield Promise.all(this.media.map((t=>t.uploadFile())));const t={};return this.media.forEach((e=>{t[e.cid]={name:e.data.queued}})),t}))}get isUploaded(){return!!this.id||!!this.syncedAt}get isSynchronising(){return this.remote.synchronising}get isDraft(){return!this.id}}export{m as LocationType,p as default,u as dtoSchema};
@@ -0,0 +1 @@
1
+ import{__awaiter as o}from"tslib";import{observable as t}from"mobx";import e from"../Collection.mjs";import n from"./Location.mjs";class r extends e{constructor(o){super(Object.assign({id:"locations",Model:n},o)),this.remote=t({synchronising:!1,url:o.url,getAccessToken:o.getAccessToken})}fetchRemote(){return o(this,arguments,void 0,(function*(o={}){throw console.log(o),new Error("fetchRemote not implemented")}))}get isSynchronising(){return this.remote.synchronising}}const s=o=>t=>t.data.locationTypeId===o;export{s as byLocationType,r as default};
@@ -0,0 +1 @@
1
+ import{__awaiter as t,__rest as e}from"tslib";import{observable as i,toJS as a}from"mobx";import s from"axios";import{isPlatform as r,createImage as n,getBlobFromURL as o}from"@flumens/utils";import d from"../Model.mjs";const h=r("hybrid");class u extends d{static getDataURI(t,e={}){return new Promise(((i,a)=>{if("string"==typeof t){let a=t.startsWith("data:image")?t.split(";")[0].split("/")[1]:t.split(".").pop();return a||(a="jpeg"),"jpg"===a&&(a="jpeg"),void u.resize(t,a,e.width,e.height).then((t=>{const[e,s]=t;i([s,a,e.width,e.height])}))}if(!window.FileReader)return void a(new Error("No File Reader"));const s=new FileReader;s.onload=function(a){var s,r;if(e.width||e.height)u.resize(null===(s=a.target)||void 0===s?void 0:s.result,t.type,e.width,e.height).then((e=>{const[a,s]=e;i([s,t.type,a.width,a.height])}));else{const e=new window.Image;e.onload=()=>{var s;const r=t.type.replace(/.*\/([a-z]+)$/i,"$1");i([null===(s=a.target)||void 0===s?void 0:s.result,r,e.width,e.height])},e.src=null===(r=a.target)||void 0===r?void 0:r.result}},s.readAsDataURL(t)}))}static resize(t,e,i,a){return new Promise((s=>{const r=new window.Image;r.onload=()=>{var t;let{width:n}=r,{height:o}=r;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===(t=h.getContext("2d"))||void 0===t||t.drawImage(r,0,0,n,o),s([r,h.toDataURL(e)])},r.src=t}))}static getImageModel(e,i,a){return t(this,void 0,void 0,(function*(){const t=this;if(!e)throw new Error("File not found while creating image model.");let s,r,o;if(h){const t=yield n(e);s=t.width,r=t.height,o=e.split("/").pop()}else[o,,s,r]=yield t.getDataURI(e,{width:2e3,height:2e3});const d=new t({data:{data:o,type:"jpeg",width:s,height:r,path:i}});return a||(yield d.addThumbnail()),d}))}constructor(t={}){var{metadata:a={}}=t,s=e(t,["metadata"]);s.createdAt=s.createdAt||(null==a?void 0:a.createdOn),s.updatedAt=s.updatedAt||(null==a?void 0:a.updatedOn),s.syncedAt=s.syncedAt||(null==a?void 0:a.syncedOn),super(s),this.debouncedValue=300,this.parent=this.parent,this.remote=i({synchronising:!1,url:s.url,getAccessToken:s.getAccessToken}),this.metadata=i(a)}toJSON(){const t=super.toJSON();return JSON.parse(JSON.stringify(Object.assign(Object.assign({},t),{metadata:a(this.metadata)||{}})))}setUpdatedAtTimestamp(t){var e;super.setUpdatedAtTimestamp(t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)}toDTO(t={}){const e=t[this.cid];if(!this.id&&!e)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=e.name,i}sync(){const e=Object.create(null,{sync:{get:()=>super.sync}});return t(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():e.sync.call(this)}))}uploadFile(){return t(this,arguments,void 0,(function*(t=!1){var e;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(!t&&a)return;const r=yield this.getFormData(),n=new FormData;if(n.append(...r),!this.remote.getAccessToken)throw new Error("this.remote.getAccessToken is missing");const o={Authorization:`Bearer ${yield this.remote.getAccessToken()}`,Accept:"application/json"},d=yield s.post(`${this.remote.url}/index.php/services/rest/media-queue`,n,{headers:o,timeout:12e4});if(!(null===(e=d.data[this.cid])||void 0===e?void 0:e.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 t(this,void 0,void 0,(function*(){const{type:t}=this.data;let e=t,i=t;(null==t?void 0:t.match(/image.*/))?[,e]=t.split("/"):i=`image/${i}`;const a=this.getURL(),s=yield o(a,i),r=this.cid;return[r,s,`${r}.${e}`]}))}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 t=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?`${t}/upload-queue/${this.data.queued}`:`${t}/upload/${this.data.path}`}getURL(){return this.data.data}resize(t,e){const i=this;return new Promise(((a,s)=>{u.resize(this.getURL(),this.data.type,t,e).then((t=>{const[e,s]=t;i.data.data=s,a([e,s])})).catch(s)}))}addThumbnail(t={}){const e=this;return new Promise(((t,i)=>{/^data:/i.test(this.getURL())?u.resize(this.getURL(),this.data.type,100,100).then((i=>{const[,a]=i;e.data.thumbnail=a,t()})).catch(i):u.getDataURI(this.getURL(),{width:100,height:100}).then((i=>{[e.data.thumbnail]=i,t()})).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}}export{u as default};
@@ -0,0 +1 @@
1
+ import{__rest as t,__awaiter as e}from"tslib";import{observable as a,intercept as i,toJS as s}from"mobx";import{snakeCase as n}from"lodash";import r from"../Model.mjs";import o from"./Media.mjs";import{parseRemoteAttrs as d}from"./helpers.mjs";class c extends r{static fromElasticDTO(t,e,a){var i,s,n,r,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(),O=Date.now();let g=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===(n=a.occ)||void 0===n?void 0:n.attrs;g||(g=(null===(o=null===(r=a.smp)||void 0===r?void 0:r.occ)||void 0===o?void 0:o.attrs)||(null===(c=a.occ)||void 0===c?void 0:c.attrs)||{});const A=d(g,(null==h?void 0:h.attributes)||[],!0),j=(null===(u=null==h?void 0:h.media)||void 0===u?void 0:u.map((({path:t})=>({id:t,createdAt:y,updatedAt:b,syncedAt:O,data:{data:`${e}/upload/${t}`}}))))||[],w=v.species||v.taxon_name,x=w!==v.taxon_name?v.taxon_name:"";return new this({id:l,cid:l,createdAt:y,updatedAt:b,syncedAt:O,metadata:{verification:f},data:Object.assign(Object.assign({},A),{taxaTaxonListId:parseInt(v.taxa_taxon_list_id,10),taxon:{warehouseId:parseInt(v.taxa_taxon_list_id,10),scientificName:w,commonName:x,foundInName:x?"commonName":"scientificName"},comment:null==h?void 0:h.occurrence_remarks}),media:j})}constructor(e={}){var{metadata:s={},media:n=[],Media:r=o}=e,d=t(e,["metadata","media","Media"]);d.createdAt=d.createdAt||(null==s?void 0:s.createdOn),d.updatedAt=d.updatedAt||(null==s?void 0:s.updatedOn),d.syncedAt=d.syncedAt||(null==s?void 0:s.syncedOn),super(d),this.debouncedValue=300,this.keys=()=>{return Object.assign(Object.assign({},c.keys),(t=this.getSurvey().attrs||{},Object.keys(t).reduce(((e,a)=>{var i;return Object.assign(Object.assign({},e),{[a]:(null===(i=t[a])||void 0===i?void 0:i.remote)||t[a]})}),{})));var t},this.Media=r,this.metadata=a(s);const u=n.map(((t,e={})=>a=>a instanceof t?a:new t(Object.assign(Object.assign({},a),e)))(this.Media));this.media=a(u);const l=t=>t.parent=this;this.media.forEach(l);i(this.media,(t=>{var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(l),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 e(this,void 0,void 0,(function*(){if(!this.parent)throw new Error("Trying to save locally without a parent");this.parent.save()}))}destroy(t){return e(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)))),t||(yield this.parent.save())}))}sync(){const t=Object.create(null,{sync:{get:()=>super.sync}});return e(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():t.sync.call(this)}))}toJSON(){var t;const e=super.toJSON();return JSON.parse(JSON.stringify(Object.assign(Object.assign({},e),{media:(null===(t=this.media)||void 0===t?void 0:t.map((t=>t.toJSON())))||[],metadata:s(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,a=Object.assign(Object.assign({},c.keys),e),i={values:{external_key:this.cid},media:[]};this.id&&(i.values.id=this.id);const s=(t,e)=>{const s=a[t].values;if(!s)return e;if("function"==typeof s)return s(e,i,this);if(s instanceof Array){const a=s.find((({value:t})=>t===e));if(!a||!a.id)throw new Error(`A "${t}" attribute "${e}" value could not be mapped to a remote database field.`);return a.id}return e instanceof Array?e.map((t=>s[t])):s[e]};Object.keys(this.data).forEach((t=>{let e=this.data[t];const r=t=>null==t;if(r(e))return;if(!a[t])return t=t.includes("occAttr:")?t:n(t),void(i.values[t]=e);const o=a[t].id||t;if(e=s(t,e),r(e))return;let d=Number.isNaN(Number(o))?o:`occAttr:${o}`;d=d.includes("occAttr:")?d:n(d),i.values[d]=e})),this.media.forEach((e=>{const a=e.toDTO(t);a&&i.media.push(a)}));const r=this.getSurvey();return r.modifySubmission?r.modifySubmission(i,this):i}}c.keys={taxon:{id:"taxa_taxon_list_id"}};export{c as default};
@@ -0,0 +1 @@
1
+ import{__rest as e,__awaiter as t}from"tslib";import{observable as s,intercept as i,toJS as r}from"mobx";import o from"axios";import{snakeCase as a}from"lodash";import n from"wellknown";import{isAxiosNetworkError as c,HandledError as d}from"@flumens/utils";import u from"../Model.mjs";import{fetchElasticOccurrences as h}from"./ElasticOccurrence.mjs";import{fetchElasticSample as l,fetchElasticSubSamples as m}from"./ElasticSample.mjs";import p from"./Media.mjs";import v from"./Occurrence.mjs";import{parseRemoteAttrs as f,validateRemoteModel as y,getErrorMessageFromObject as g}from"./helpers.mjs";const O=(e,t={})=>s=>s instanceof e?s:new e(Object.assign(Object.assign({},s),t));function w(e,t){var s,i,r,o,a;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)=>w(e,t.samples[s])))),e.occurrences&&t.occurrences&&(null===(o=e.occurrences)||void 0===o||o.forEach(((e,s)=>w(e,t.occurrences[s])))),e.media&&t.media&&(null===(a=e.media)||void 0===a||a.forEach(((e,s)=>w(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 b=e=>t(void 0,void 0,void 0,(function*(){const s=[];if(e.media){const i=e=>t(void 0,void 0,void 0,(function*(){const t=yield e.getFormData();return[e,t]})),r=yield Promise.all(e.media.map(i));s.push(...r)}if(e.occurrences){const t=yield Promise.all(e.occurrences.map(b));s.push(...t.flat())}if(e.samples){const t=yield Promise.all(e.samples.map(b));s.push(...t.flat())}return s}));function A(e,t){const s={values:{id:t||-1}};return e.occurrences&&(s.occurrences=e.occurrences.map((e=>A(e)))),e.samples&&(s.samples=e.samples.map((e=>A(e)))),e.media&&(s.media=e.media.map((e=>A(e)))),s}function E(e){try{const t=18e4;console.warn(JSON.stringify(e).substring(0,t))}catch(e){}}class j extends u{static fromElasticDTO(e,t={},s){var i,r;const{id:o,event:a,location:c,metadata:d}=e,{url:u}=t,h=new Date(a.date_start),l=new Date(d.updated_on).getTime(),m=Date.now(),[p,v]=c.point.split(",").map(parseFloat),y="OSGB"===c.output_sref_system?c.output_sref:"",g=c.geom?n.parse(c.geom):null,O=a.parent_event_id,w=f(O?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,a.attributes||[]),b=null===(i=a.media)||void 0===i?void 0:i.map((({path:e})=>({id:e,metadata:{updatedOn:h,createdOn:h,syncedOn:h},data:{data:`${u}/upload/${e}`}}))),A=c.name||c.verbatim_locality;return new this(Object.assign({id:o,cid:a.source_system_key||o,createdAt:h.getTime(),updatedAt:l,syncedAt:m,metadata:{saved:!0},data:Object.assign(Object.assign({},w),{surveyId:d.survey.id,date:h.toISOString().split("T")[0],locationName:A,location:{code:c.code,name:A,latitude:p,longitude:v,shape:g,gridref:y},enteredSrefSystem:4326,groupId:null===(r=d.group)||void 0===r?void 0:r.id,locationId:c.location_id,comment:a.event_remarks,training:"true"===d.trial}),media:b},t))}constructor(t={}){var{metadata:r={},samples:o=[],occurrences:a=[],media:n=[],Occurrence:c=v,Media:d=p,skipStore:u}=t,h=e(t,["metadata","samples","occurrences","media","Occurrence","Media","skipStore"]);h.createdAt=h.createdAt||(null==r?void 0:r.createdOn),h.updatedAt=h.updatedAt||(null==r?void 0:r.updatedOn),h.syncedAt=h.syncedAt||(null==r?void 0:r.syncedOn);const l=u?void 0:h.store;super(Object.assign(Object.assign({},h),{store:l})),this.validateRemote=y,this.error=s({message:""}),this.debouncedValue=300,this.keys=()=>{return Object.assign(Object.assign({},j.keys),(e=this.getSurvey().attrs||{},Object.keys(e).reduce(((t,s)=>{var i;return Object.assign(Object.assign({},t),{[s]:(null===(i=e[s])||void 0===i?void 0:i.remote)||e[s]})}),{})));var e},this.requiresRemoteSync=()=>!this.syncedAt||this.updatedAt>this.syncedAt,this.Occurrence=c,this.Media=d,this.remote=s({synchronising:!1,url:h.url,getAccessToken:h.getAccessToken}),this.metadata=s(r);const m=o.map(O(this.constructor));this.samples=s(m);const f=a.map(O(this.Occurrence,{Media:this.Media}));this.occurrences=s(f);const g=n.map(O(this.Media));this.media=s(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};i(this.samples,b),i(this.occurrences,b),i(this.media,b)}setUpdatedAtTimestamp(e){var t;super.setUpdatedAtTimestamp(e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)}toJSON(){var e,t;const s=super.toJSON();return i=Object.assign(Object.assign({},s),{metadata:r(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===(t=this.media)||void 0===t?void 0:t.map((e=>e.toJSON())))||[]}),JSON.parse(JSON.stringify(i));var i}getSurvey(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}}save(){return t(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:o,media:a}=t,n=e(t,["data","metadata","occurrences","samples","media"]),c=Object.assign(Object.assign({},n),{data:{data:s,metadata:i,occurrences:r,samples:o,media:a}});yield this.store.save(c)}))}destroy(e){return t(this,void 0,void 0,(function*(){var t;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(),e)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===(t=this.collection)||void 0===t||t.remove(this),yield s(),this.data.deleted=!0}}))}sync(){const e=Object.create(null,{sync:{get:()=>super.sync}});return t(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():e.sync.call(this)}))}saveRemote(){return t(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,w(this,s);const i=(new Date).getTime();this.updatedAt=i,this.syncedAt=i,this.save()}catch(e){throw this.remote.synchronising=!1,e}}))}postRemote(e){return t(this,void 0,void 0,(function*(){var t,s,i;try{const t={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};return(yield o.post(`${this.remote.url}/index.php/services/rest/samples`,e,{headers:t,timeout:12e4})).data}catch(r){const o=r;if(409===o.status&&(null===(t=o.response)||void 0===t?void 0:t.data.duplicate_of))return A(this,o.response.data.duplicate_of.id);if(c(o))throw new d("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw E(e),new Error(g(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 t(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 l({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 o=m({parentId:this.id,url:e,accessToken:t}),a=h({parentId:this.id,url:e,accessToken:t}),[n,c]=yield Promise.all([o,a]),d=(new Date).getTime(),u=n.map((t=>{const s=this.constructor.fromElasticDTO(t,{url:e},this.getSurvey());return s.syncedAt=d,s})),p=u.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.id]:t})),{[this.id]:this});this.samples.clear(),this.samples.push(...u);c.map((e=>{const t=this.Occurrence.fromElasticDTO(e,this.remote.url,this.getSurvey());return t.syncedAt=d,[t,e.event.event_id]})).forEach((([e,t])=>{t!==parseInt(this.id,10)?p[t]?p[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):this.occurrences.push(e)})),this.syncedAt=d}))}updateRemote(){return t(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);w(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(e,s){return t(this,void 0,void 0,(function*(){var t,i;const r={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};try{return(yield o.put(`${this.remote.url}/samples/${e}`,s,{headers:r,timeout:12e4})).data}catch(e){const r=e;if(c(r))throw new d("Request aborted because of a network issue (timeout or similar).");if(400===r.status)throw E(s),new Error(g(null===(i=null===(t=r.response)||void 0===t?void 0:t.data)||void 0===i?void 0:i.message));throw new Error(r.message)}}))}uploadMedia(){return t(this,void 0,void 0,(function*(){let e={};const s=yield b(this);if(!s.length)return e;const i=e=>t(this,void 0,void 0,(function*(){const t={Authorization:`Bearer ${yield this.remote.getAccessToken()}`,Accept:"application/json"};try{return(yield o.post(`${this.remote.url}/index.php/services/rest/media-queue`,e,{headers:t,timeout:12e4})).data}catch(e){if("timeout"===e.message)throw new d("Request aborted because of a network issue (timeout or similar).");throw e}})),r=[],a=Date.now()-432e5;s.forEach((t=>{const[s]=t;s.syncedAt>a&&s.data.queued?e[s.cid]={name:s.data.queued}:r.push(t)}));for(let t=0;t<r.length;t+=5){const s=r.slice(t,t+5),o=new FormData;s.forEach((([,e])=>o.append(...e)));const a=yield i(o),n=(new Date).getTime();s.forEach((([e])=>{e.syncedAt=n,e.data.queued=a[e.cid].name})),e=Object.assign(Object.assign({},e),a)}return e}))}toDTO(e={}){const t="function"==typeof this.keys?this.keys():this.keys,s=Object.assign(Object.assign({},j.keys),t),i={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(i.values.id=this.id);const r=(e,t)=>{const o=s[e].values;if(!o)return t;if("function"==typeof o)return o(t,i,this);if(t instanceof Array)return t.map((t=>r(e,t)));if(o instanceof Array){const s=o.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 o[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:a(e),void(i.values[e]=t);if(t=r(e,t),o(t))return;const n=s[e].id||e;let c=Number.isNaN(Number(n))?n:`smpAttr:${n}`;c=c.includes("smpAttr:")?c:a(c),i.values[c]=t})),this.samples.forEach((t=>{this.data.training&&(t.data.training=this.data.training);const s=t.toDTO(e);s&&i.samples.push(s)})),this.occurrences.forEach((t=>{this.data.training&&(t.data.training=this.data.training);const s=t.toDTO(e);s&&i.occurrences.push(s)})),this.media.forEach((t=>{const s=t.toDTO(e);s&&i.media.push(s)}));const o=this.getSurvey();return o.modifySubmission?o.modifySubmission(i,this):i}get isUploaded(){return this.parent?this.parent.isUploaded:!!this.id||!!this.syncedAt}get isDisabled(){return this.isUploaded}get isSynchronising(){return this.remote.synchronising}}j.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}}};export{j as default,b as getMediaFormData};
@@ -0,0 +1 @@
1
+ import{__awaiter as e}from"tslib";import{observable as t,observe as s}from"mobx";import r from"axios";import a from"../Collection.mjs";import{fetchElasticOccurrences as o}from"./ElasticOccurrence.mjs";import{fetchElasticSubSamples as i}from"./ElasticSample.mjs";import c from"./Sample.mjs";class n extends a{constructor(e){super(Object.assign({id:"samples",Model:c},e)),this.Occurrence=e.Occurrence,this.remote=t({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken});s(this.data,(e=>{e.addedCount&&e.added.forEach((e=>e.collection=this)),e.removedCount&&e.removed.forEach((e=>delete e.collection))}))}fetch(){return e(this,void 0,void 0,(function*(){if(!this.store||!this.Model)return void this.ready.resolve(!1);const e=yield this.store.findAll(),t=e=>{const{data:t,metadata:s,occurrences:r,samples:a,media:o,attrs:i}=e.data;return new this.Model(Object.assign(Object.assign({},e),{attrs:i,data:t,metadata:s,occurrences:r,samples:a,media:o}))},s=e.map((e=>t(e)));this.data.push(...s),this.ready.resolve(!0)}))}fetchRemote(t,s){return e(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"}}],a=JSON.stringify({from:t,size:100,query:{bool:{must:e}},sort:[{"metadata.created_on":"desc"}]}),c=this.remote.url,n=yield this.remote.getAccessToken(),d={method:"post",url:`${c}/index.php/services/rest/es-samples/_search`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},data:a},l=(yield r.request(d)).data.hits.hits.map((e=>e._source)),m=l.map((e=>e.id)),u=i({parentId:m,url:c,accessToken:n}),h=o({parentId:m,url:c,accessToken:n}),[p,f]=yield Promise.all([u,h]),y=l.map(((e,t,s,r,a)=>o=>{const i=(new Date).getTime();try{const c=new s({skipStore:!0});c.data.surveyId=o.metadata.survey.id;const n=c.getSurvey(),d=s.fromElasticDTO(o,{url:e,skipStore:!0},n);c.id=d.id,c.cid=d.cid||c.cid,Object.assign(c.data,d.data),Object.assign(c.metadata,d.metadata);const l=t=>{const r=s.fromElasticDTO(t,{url:e},n);return r.syncedAt=i,r},m=e=>e.event.parent_event_id===c.id||e.event.event_id===c.id,u=r.filter(m).map(l),h=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:t}),p=u.reduce(h,{[c.id]:c}),f=s=>{const r=t.fromElasticDTO(s,e,n);return r.syncedAt=i,[r,s.event.event_id]},y=a.filter(m).map(f),v=([e,t])=>{t!==parseInt(c.id,10)?p[t]?p[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):c.occurrences.push(e)};return y.forEach(v),c.samples.push(...u),c.syncedAt=i,c}catch(e){return console.warn(JSON.stringify(o)),console.error(e),null}})(c,this.Occurrence,this.Model,p,f)).filter((e=>!!e)),v=y.filter((e=>!this.cidMap.has(e.cid)));return this.data.push(...v),v}))}removeAllSynced(){const e=[];return this.data.forEach((t=>{t.syncedAt&&e.push(t.destroy())})),Promise.all(e)}reset(){return e(this,void 0,void 0,(function*(){const e=this.data.map((e=>e.destroy()));yield Promise.all(e)}))}get isSynchronising(){return this.remote.synchronising}}export{n as default};
@@ -0,0 +1 @@
1
+ const e=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),"");function t(){const e=this.getSurvey(),t=e.verify&&e.verify(this.data,this);let i={};if(t){const e=t&&"issues"in t;!("ValidationError"===t.name||"ValidationError"===t.type)&&!e?i.errors=[t.message]:e?i.errors=t.issues.map((({message:e})=>e)):i=Object.assign({},t)}const r=(e,t)=>{const i=t.validateRemote();return i&&(e[t.cid]=i,e[t.cid].model=t),e},a=(this.samples||[]).reduce(r,{}),n=(this.occurrences||[]).reduce(r,{}),s=(this.media||[]).reduce(r,{});if(Object.keys(i).length||Object.keys(a).length||Object.keys(n).length||Object.keys(s).length){return{attributes:i,model:this,models:Object.assign(Object.assign(Object.assign({},a),n),s)}}return null}const i=(e,t,i=!1)=>{e=e||{};const r=Object.entries(e);return t.reduce(((e,t)=>{var a,n;const s=isNaN(t.value)?t.value:parseFloat(t.value),o=r.find((([,e])=>{var i;return(null===(i=e.remote)||void 0===i?void 0:i.id)===parseInt(t.id,10)}));if(o){const[t]=o;e[t]=s}if(!o||(null===(n=null===(a=o[1])||void 0===a?void 0:a.remote)||void 0===n?void 0:n.isBackwardsCompatible)){e[i?`occAttr:${t.id}`:`smpAttr:${t.id}`]=s}return e}),{})};function r(e,t){const i=Object.entries(e).flatMap((([e,i])=>{const r=e.match(/:\d+/)?e.split(":").pop():e,a=Object.entries(t).find((n=r,([,e])=>{var t;return`${null===(t=e.remote)||void 0===t?void 0:t.id}`===n}));var n;if(!a)return null;const[s,o]=a;let d;const l=e=>{var t,i,r,a;if(!Array.isArray(null===(t=o.remote)||void 0===t?void 0:t.values))return e.raw_value;const n=null===(a=null===(r=null===(i=o.remote)||void 0===i?void 0:i.values)||void 0===r?void 0:r.find((({id:t})=>e.raw_value===t)))||void 0===a?void 0:a.value;return n||e.raw_value};return d=Array.isArray(i)?i.map(l):l(i),[[s,d]]})).filter((e=>!!e));return Object.fromEntries(i)}const a=(e,t,i)=>{Number.isFinite(e.data[t])||e.data[t]||(Number.isFinite(i)||i)&&(e.data[t]=i)};function n(e,t,i){var r,a,n;const s=t.id,o=e.data[s];if(null==o||""===o)return;const d={},l=Array.isArray(null===(r=t.remote)||void 0===r?void 0:r.values),u="function"==typeof(null===(a=t.remote)||void 0===a?void 0:a.values);if(l){const e=t.remote.values,r=t=>e.find((e=>e.value===t||e.id===t||`${e.id}`==`${t}`));if(Array.isArray(o))d[i.id]=o.map((e=>{var t;return null===(t=r(e))||void 0===t?void 0:t.id})).filter(Boolean);else{const e=r(o);(null==e?void 0:e.id)&&(d[i.id]=String(e.id))}}else d[i.id]=u?t.remote.values(o,{values:d}):"object"==typeof o?JSON.parse(JSON.stringify(o)):o;s!==i.id&&(e.metadata&&((n=e.metadata)._migrated||(n._migrated={}),e.metadata._migrated[s]=o),delete e.data[s]),Object.assign(e.data,d)}export{a as assignIfMissing,e as getErrorMessageFromObject,r as getLocalAttributes,n as migrateOldAttr,i as parseRemoteAttrs,t as validateRemoteModel};
package/dist/Model.mjs ADDED
@@ -0,0 +1 @@
1
+ import{__awaiter as t}from"tslib";import{makeObservable as s,observable as e,set as i,toJS as d}from"mobx";import{deepObserve as r}from"mobx-utils";import{Deferred as a,UUIDv7 as o}from"@flumens/utils";const h=t=>JSON.parse(JSON.stringify(t)),c={};class n{constructor({id:t,cid:i="",createdAt:d,updatedAt:n,syncedAt:u,data:l={},attrs:y={},store:A}){this.ready=new a,this.debouncedValue=3e3,this._observerPaused=!1,this.id=t,this.cid=i||t||o();const v=Date.now();let p;this.createdAt=d||v,this.updatedAt=n||v,this.syncedAt=u,this.data=h(Object.assign(Object.assign(Object.assign({},c),l),y)),s(this,{createdAt:e,updatedAt:e,syncedAt:e,data:e}),this.store=A;const f=(...t)=>{clearTimeout(p),p=setTimeout((()=>this.sync.apply(this,t)),this.debouncedValue)};r(this.data,(()=>{this._observerPaused||(this.updatedAt=Date.now(),f())}))}setUpdatedAtTimestamp(t){this.updatedAt=t}fetch(){return t(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,i(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(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(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(...s){return t(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:d(this.data)}}reset(t){this.id="";const s=JSON.parse(JSON.stringify(Object.assign(Object.assign({},c),t)));i(this.data,s);const e=Object.keys(s);return Object.keys(this.data).forEach((t=>{e.includes(t)||(this.data[t]=null,delete this.data[t])})),this.save()}get isStored(){return!!this.store}}export{h as copyObject,n as default};
@@ -0,0 +1 @@
1
+ import{__awaiter as e}from"tslib";import r from"localforage";import i from"localforage-cordovasqlitedriver";import{isPlatform as t}from"@flumens/utils";import{printDiff as o}from"./utils.mjs";let s=["indexeddb","websql","localstorage"];t("hybrid")&&(s=[i,...s]);const d={driverOrder:s};class n{constructor(e){if(t("hybrid")&&!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");const i=Object.assign(Object.assign({},d),e);this.debugging=i.debugging,this.localForage=null,this.ready=new Promise(((e,t)=>{const o=new Promise((e=>{i.driverOrder&&"object"==typeof i.driverOrder[0]?r.defineDriver(i.driverOrder[0]).then(e):e(void 0)}));if(!i.storeName)throw new Error("storeName prop is missing");this.storeName=i.storeName,o.then((()=>{const o={name:i.name||"indicia",storeName:i.storeName};i.version&&(o.version=i.version);const s=n._getDriverOrder(i.driverOrder),d=i.LocalForage||r;this.localForage=d.createInstance(o),this.localForage.setDriver(s).then(e).catch(t)}))}))}static _getDriverOrder(e){return e.map((e=>{switch(e){case"indexeddb":return r.INDEXEDDB;case"websql":return r.WEBSQL;case"localstorage":return r.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))}save(r){return e(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(e,r,r.cid,this.storeName)}return this.localForage.setItem(r.cid,r)}))}find(r){return e(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return(yield this.localForage.getItem(r))||void 0}))}findAll(){return e(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(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(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(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(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)}))}}export{n as default};
@@ -0,0 +1 @@
1
+ import{__awaiter as e}from"tslib";import{defineCustomElements as t}from"jeep-sqlite/loader/index.js";import{SQLiteConnection as i,CapacitorSQLite as o}from"@capacitor-community/sqlite";import{Capacitor as n}from"@capacitor/core";import{Filesystem as s}from"@capacitor/filesystem";import{Deferred as r}from"@flumens/utils";import{formatSqlQuery as a}from"./utils.mjs";class l{static migrateCordova(t){return e(this,void 0,void 0,(function*(){var e;console.log("SQLite: Cordova db migration");const n=new i(o);try{let i;try{i=yield n.getMigratableDbList(t?"Library/LocalDatabase":void 0)}catch(e){console.log("SQLite: err",e.message)}if(!(null===(e=null==i?void 0: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(o),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new r,this.name=e||this.name,this.debug=t||this.debug,this.isWeb=n||this.isWeb}init(){return e(this,void 0,void 0,(function*(){if(this.isWeb){t(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(this,arguments,void 0,(function*({sql:e,params:t}){var i;yield this.ready;const o=yield this.db.query(e,t).then((e=>e.values||[])).catch((i=>{throw console.error("SQLite query error:",i,{sql:e,params:t}),i}));return this.debug&&(console.groupCollapsed(`💾 SQL: ${e.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30)}...`),console.debug(a(e,t||[])),console.groupEnd(),yield null===(i=this.sqliteConnection)||void 0===i?void 0:i.saveToStore(this.name)),o}))}export(){return e(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.convertFileSrc(e))).blob()}))}import(t){return e(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(o){o.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 s.writeFile({path:e,data:i})}))}}export{l as default};
@@ -0,0 +1 @@
1
+ import{__awaiter as e,__rest as t}from"tslib";import{getTableColumns as i,sql as n,eq as r,and as d}from"drizzle-orm";import{toCamelCase as s}from"drizzle-orm/casing";import{SQLiteSyncDialect as o,sqliteTable as a,getTableConfig as l,SQLiteInsertBuilder as u,QueryBuilder as c,SQLiteDeleteBase as m,integer as y,text as h,customType as f}from"drizzle-orm/sqlite-core";import{Deferred as p}from"@flumens/utils";import{printDiff as v}from"./utils.mjs";function b(e,t){const r=i(e);return Object.entries(r).filter((([e])=>!t.includes(e))).reduce(((e,[t,i])=>Object.assign(Object.assign({},e),{[t]:n.raw(`excluded.${i.name}`)})),{})}const g=e=>f({dataType:()=>"jsonb",toDriver:e=>JSON.stringify(e)})(e),A=new o,O=()=>({id:h().unique(),cid:h().primaryKey().notNull().default("id"),data:g("data").notNull(),createdAt:y("created_at").notNull(),updatedAt:y("updated_at").notNull(),syncedAt:y("synced_at")});class ${constructor({db:e,name:t,debug:i,columns:n=O(),extraConf:r}){this.ready=new p,this.db=e,this.name=t,this.debug=i||!1,this.table=a(this.name,n,r),this.init()}init(){return e(this,void 0,void 0,(function*(){yield this.db.ready;const e=l(this.table),t=e.columns.map((e=>`${e.name} ${e.getSQLType()}${e.primary?" primary key":""}${e.isUnique?" unique":""}${e.notNull?" not null":""}${e.default?` default ${e.default}`:""}`)).join(",\n");let i="";e.primaryKeys.length>0&&(i=", ",i+=e.primaryKeys.map((e=>`PRIMARY KEY (${e.columns.map((e=>e.name)).join(", ")})`)).join(", "));let n="";if(e.foreignKeys.length>0&&(n=", ",n+=e.foreignKeys.map((e=>{const t=e.reference(),i=l(t.foreignTable),n=e.onDelete?` ON DELETE ${e.onDelete}`:"";return`FOREIGN KEY (${t.columns[0].name}) REFERENCES ${i.name}(${t.foreignColumns[0].name}) ${n}`})).join(", ")),yield this.db.query({sql:`CREATE TABLE IF NOT EXISTS ${this.name} (${t} ${i} ${n});`}),e.indexes.length){const t=e.indexes.map((e=>{const t=e.config.unique?"UNIQUE":"",i=e.config.columns.map((({name:e})=>e)).join(", "),n=e.config.name||`${this.name}_${i.replace(/, /g,"_")}_idx`;return this.db.query({sql:`CREATE ${t} INDEX IF NOT EXISTS ${n} ON ${this.name} (${i});`})}));yield Promise.all(t)}this.ready.resolve(!0)}))}save(t){return e(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});v(e,t,t.cid,this.name)}let e=new u(this.table,{},A).values(t);const i=this._getPrimaryCol();i&&(e=e.onConflictDoUpdate({target:i,set:b(this.table,[])})),yield this.db.query(e.toSQL())}))}find(t){return e(this,void 0,void 0,(function*(){yield this.ready;const[e]=yield this.findAll((e=>{if("function"==typeof t)return t(e).limit(1);if("string"==typeof t){const i=this._getPrimaryCol();if(!i)throw new Error("Primary col is missing");return e.where(r(i,t)).limit(1)}const i=Object.entries(t).map((([e,t])=>r(this.table[e],t)));return e.where(d(...i)).limit(1)}));return e}))}findAll(t){return e(this,void 0,void 0,(function*(){yield this.ready;let e=(new c).select().from(this.table);t&&(e=t(e));return(yield this.db.query(e.toSQL())).map((e=>Object.entries(e).reduce(((e,[t,n])=>{var r;const d="jsonb"===(null===(r=i(this.table)[t])||void 0===r?void 0:r.sqlName);return e[s(t)]=d?JSON.parse(n):n,e}),{})))}))}delete(t){return e(this,void 0,void 0,(function*(){yield this.ready;yield this.deleteAll((e=>{if("function"==typeof t)return t(e);if("string"==typeof t){const i=this._getPrimaryCol();if(!i)throw new Error("Primary col is missing");return e.where(r(i,t))}const i=Object.entries(t).map((([e,t])=>r(this.table[e],t)));return e.where(d(...i))}))}))}deleteAll(t){return e(this,void 0,void 0,(function*(){yield this.ready;let e=new m(this.table,{},A);t&&(e=t(e)),yield this.db.query(e.toSQL())}))}export(){return e(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(i){return e(this,void 0,void 0,(function*(){if(yield this.ready,yield this.deleteAll(),"object"!=typeof i)throw new Error("Invalid obj passed to store");const e=Object.entries(i).map((([,e])=>this.save((e=>{var i,n,r,d,s,o;if(!e.createdAt&&(null===(i=e.metadata)||void 0===i?void 0:i.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(r=e.metadata)||void 0===r?void 0:r.updatedOn)&&(e.updatedAt=null===(d=e.metadata)||void 0===d?void 0:d.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){const{id:i,cid:n,createdAt:r,updatedAt:d,syncedAt:s}=e,o=t(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:i,cid:n,createdAt:r,updatedAt:d,syncedAt:s,data:Object.assign({},o)}}return e})(e))));Promise.all(e)}))}_getPrimaryCol(){return Object.values(i(this.table)).find((({primary:e})=>!!e))}}export{b as conflictUpdateAllExcept,$ as default,O as defaultCols,g as jsonb};
@@ -0,0 +1 @@
1
+ class a{}export{a as default};
@@ -0,0 +1 @@
1
+ import{diff as o}from"deep-diff";import{merge as e}from"lodash";function n(n,r,t,l=""){const i=o(n,r);if(!i)return;let s={},p=0,c="";if(i.forEach((o=>{const n={[l]:{[t]:{}}};if(!o.path)return n[l][t]=o.rhs,console.groupCollapsed(`Δ + ${t}`),console.log(n),void console.groupEnd();o.path.reduce(((e,n,r)=>{if(o.path.length-1>r)return e[n]={},e[n];const t=JSON.stringify(o.lhs,null,2),l=JSON.stringify(o.rhs,null,2);if(t===l)return e[n];p++,e[n]=`${t} -> ${l}`,c=`${n}: ${t} -> ${l}`}),n[l][t]),s=e(s,n)})),p){let o=`Δ ${t}`;1===p&&(o+=` ${c}`),console.groupCollapsed(o),console.log(s),console.groupEnd()}}const r=(o,e)=>{const n=o=>null==o?"NULL":"number"==typeof o||"bigint"==typeof o?`${o}`:"boolean"==typeof o?o?"TRUE":"FALSE":o instanceof Date?`'${o.toISOString()}'`:Array.isArray(o)?o.length?`(${o.map(n).join(", ")})`:"(NULL)":"object"==typeof o?`'${JSON.stringify(o).replace(/'/g,"''")}'`:`'${String(o).replace(/'/g,"''")}'`;let r=0;return o.replace(/\?/g,(()=>{if(r>=e.length)return"?";const o=n(e[r]);return r+=1,o}))};export{r as formatSqlQuery,n as printDiff};
@@ -0,0 +1 @@
1
+ export * from './Stores/index.js';
@@ -0,0 +1 @@
1
+ export{default as SQLiteDatabase}from"./Stores/SQLiteDatabase.mjs";export{default as LocalForageStore}from"./Stores/LocalForageStore.mjs";export{default as SQLiteStore}from"./Stores/SQLiteStore.mjs";export{default as IStore}from"./Stores/Store.mjs";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { default as DrupalUserModel } from './Drupal/User';
1
+ export { default as DrupalUserModel, DrupalUserError, DrupalUserErrorCode, } from './Drupal/User';
2
2
  export * from './Stores';
3
3
  export { default as Model } from './Model';
4
4
  export { default as Collection } from './Collection';
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export{DrupalUserError,DrupalUserErrorCode,default as DrupalUserModel}from"./Drupal/User.mjs";export{default as SQLiteDatabase}from"./Stores/SQLiteDatabase.mjs";export{default as LocalForageStore}from"./Stores/LocalForageStore.mjs";export{default as SQLiteStore}from"./Stores/SQLiteStore.mjs";export{default as IStore}from"./Stores/Store.mjs";export{default as Model}from"./Model.mjs";export{default as Collection}from"./Collection.mjs";export{default as IndiciaMedia}from"./Indicia/Media.mjs";export{default as IndiciaOccurrence}from"./Indicia/Occurrence.mjs";export{default as IndiciaSample}from"./Indicia/Sample.mjs";export{default as IndiciaGroup,dtoSchema as groupDtoSchema}from"./Indicia/Group.mjs";export{default as IndiciaLocation,LocationType,dtoSchema as locationDtoSchema}from"./Indicia/Location.mjs";export{default as IndiciaSampleCollection}from"./Indicia/SampleCollection.mjs";export{default as IndiciaGroupCollection,byGroupMembershipStatus}from"./Indicia/GroupCollection.mjs";export{default as IndiciaLocationCollection,byLocationType}from"./Indicia/LocationCollection.mjs";
package/package.json CHANGED
@@ -1,12 +1,26 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.30.0",
4
- "main": "dist/index.js",
3
+ "version": "0.32.0",
4
+ "type": "module",
5
+ "main": "dist/index.mjs",
6
+ "module": "dist/index.mjs",
5
7
  "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.mjs"
12
+ },
13
+ "./dist/*": {
14
+ "types": "./dist/*.d.ts",
15
+ "default": "./dist/*.mjs"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
6
19
  "scripts": {
7
20
  "build": "rollup -c",
8
21
  "build:watch": "rollup -c -w",
9
22
  "test:eslint": "eslint src --quiet --ext .jsx --ext .ts --ext .tsx --ext .js && echo '\\033[37;42;1m PASS \\033[00m'",
23
+ "test:e2e": "node --env-file=./src/Drupal/.env --test ./src/Drupal/user-lifecycle.e2e.ts",
10
24
  "prepare": "npm run build",
11
25
  "postpublish": "TAG_NAME=models-v\"$npm_package_version\" && git tag $TAG_NAME && git push origin \"$TAG_NAME\"",
12
26
  "check": "npx tsc --noEmit --skipLibCheck && npm run test:eslint",
@@ -18,13 +32,14 @@
18
32
  "devDependencies": {
19
33
  "@rollup/plugin-json": "6.1.0",
20
34
  "@rollup/plugin-node-resolve": "16.0.0",
35
+ "@rollup/plugin-terser": "1.0.0",
21
36
  "@rollup/plugin-typescript": "12.1.2",
22
37
  "@trivago/prettier-plugin-sort-imports": "5.2.2",
23
38
  "@types/wellknown": "^0.5.8",
39
+ "mailslurp-client": "^17.4.0",
24
40
  "prettier": "3.5.0",
25
41
  "rollup-plugin-clear": "2.0.7",
26
42
  "rollup-plugin-copy": "3.5.0",
27
- "rollup-plugin-terser": "7.0.2",
28
43
  "tslib": "2.8.1",
29
44
  "typescript": "5.7.3"
30
45
  },
@@ -33,22 +48,32 @@
33
48
  "drizzle-orm": "0.44.7"
34
49
  },
35
50
  "optionalDependencies": {
51
+ "@capacitor-community/sqlite": "^6 || ^7 || ^8",
36
52
  "@capacitor/core": "^6 || ^7 || ^8",
37
53
  "@capacitor/filesystem": "^6 || ^7 || ^8",
38
- "@capacitor-community/sqlite": "^6 || ^7 || ^8",
39
54
  "deep-diff": "^1",
40
55
  "jeep-sqlite": "^2",
41
56
  "jwt-decode": "^4",
42
57
  "localforage": "^1",
43
58
  "localforage-cordovasqlitedriver": "^1",
44
59
  "mobx-utils": "^6",
45
- "zod": "^4",
46
- "wellknown": "^0.5.0"
60
+ "wellknown": "^0.5.0",
61
+ "zod": "^4"
47
62
  },
48
63
  "jest": {
49
64
  "testEnvironment": "jsdom",
50
- "preset": "ts-jest",
65
+ "transform": {
66
+ "^.+\\.tsx?$": [
67
+ "ts-jest",
68
+ {
69
+ "isolatedModules": true
70
+ }
71
+ ]
72
+ },
51
73
  "moduleNameMapper": {
74
+ "^@flumens/(utils|models|tailwind|ionic)/dist/(.*)$": "<rootDir>/../$1/src/$2",
75
+ "^@flumens/(utils|models|tailwind|ionic)$": "<rootDir>/../$1/src",
76
+ "^(\\.{1,2}/.*)\\.js$": "$1",
52
77
  "^.+.(css|style|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
53
78
  },
54
79
  "testPathIgnorePatterns": [
@@ -1 +0,0 @@
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=e.observable.map(),this.idMap=e.observable.map();e.intercept(this.data,(t=>{if("update"===t.type)return t;const{added:e,index:i,removedCount:r,object:d}=t;if(t.removedCount>0){d.slice(i,i+r).forEach((t=>{this.cidMap.delete(t.cid),t.id&&this.idMap.delete(t.id)}))}return e.forEach((t=>{this.cidMap.set(t.cid,t),this.idMap.set(t.id,t)})),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)}upsert(...t){t.forEach((t=>{const e=this.data.findIndex((e=>!!e.id&&e.id===t.id||!!e.cid&&e.cid===t.cid));this.data[e]?this.data.spliceWithArray(e,1,[t]):this.data.push(t)}))}[Symbol.iterator](){return this.data[Symbol.iterator]()}get length(){return this.data.length}}exports.default=d;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),i=require("axios"),t=require("jwt-decode"),s=require("zod"),r=require("@flumens/utils"),o=require("../Model.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=n(i);function d(e){const i={};return Object.keys(e).forEach((t=>{if(t.match(/^field_/)){const s=t.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[t])return;if(Array.isArray(e[t])&&e[t].length)return void(i[s]=e[t][0].value);i[s]=e[t]}})),i}const c=e=>{var i,t,s,o,n;const a=(null===(t=null===(i=e.response)||void 0===i?void 0:i.data)||void 0===t?void 0:t.error_description)||(null===(o=null===(s=e.response)||void 0===s?void 0:s.data)||void 0===o?void 0:o.message);if(a){if(a.includes("is already taken"))throw new r.HandledError("This email is already taken.");if("The user credentials were incorrect."===a)throw new r.HandledError("Incorrect password or email");if("Unrecognized username or email address."===a)throw new r.HandledError("Unrecognized email address.");if("This account is already activated"===a)throw new r.HandledError("This account is already activated.");if(a.includes("not been activated"))throw new r.HandledError("The user has not been activated or is blocked.");throw new Error(a)}if(null===(n=e.message)||void 0===n?void 0:n.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 o.default{constructor(i){var{config:t}=i,s=e.__rest(i,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},h),s.data)})),this.config=t}logIn(i,t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._exchangePasswordToTokens(i,t);return this.data.tokens=e,yield this.refreshProfile(),this.save()}))}register(i,t,s){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify(Object.assign({name:[{value:i}],pass:[{value:t}],mail:[{value:i}]},s)),r={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:e,timeout:l},{data:o}=yield a.default(r).catch(c);if(!!u.registerSchemaBackend.safeParse(o).error)throw new Error("Invalid backend response.");const n=yield this._exchangePasswordToTokens(i,t);this.id=o.uid[0].value;const h=d(o);return Object.assign(this.data,Object.assign({email:i,tokens:n,profileFetched:!0},h)),this.save()}))}resetPassword(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:i}),t={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:e};try{yield a.default(t).catch(c)}catch(e){if("The user has not been activated or is blocked."===e.message)return void(yield this._sendVerificationEmail(i));c(e)}}))}delete(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),i={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield a.default(i).catch(c),this.logOut()}))}updateRemote(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(),t={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:i,headers:{Authorization:`Bearer ${e}`},timeout:l};yield a.default(t),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 i={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:l},{data:t}=yield a.default(i).catch(c),s=d(t);Object.assign(this.data,Object.assign({email:t.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(i){return e.__awaiter(this,void 0,void 0,(function*(){if(!i&&!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:i}=t.jwtDecode(e),s=1e3*i;return Date.now()+12e4>s}(e);if(!e||s||i)try{yield this._refreshAccessToken()}catch(e){console.error(e);const i="The refresh token is invalid."===e.message,t="Token has no user email."===e.message;if(i||t)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:[{value:i||this.data.email}]}),t={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:e,timeout:l};return a.default(t).catch(c)}))}_exchangePasswordToTokens(i,t){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=new FormData;s.append("grant_type","password"),s.append("username",i),s.append("password",t),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:o}=yield a.default(r).catch(c);return o}))}_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 i=new FormData;i.append("grant_type","refresh_token"),i.append("refresh_token",e),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass);const s={method:"post",url:`${this.config.url}/oauth/token`,data:i,timeout:l},{data:r}=yield a.default(s).catch(c),o=Object.assign(Object.assign({},this.data.tokens),r),n=t.jwtDecode(o.access_token),{email:h}=n;if(!h)throw new Error("Token has no user email.");const{iss:u,email_verified:f}=n,g=n["http://indicia.org.uk/user:id"],m=n.scopes,v=d(n);this.id=n.sub,Object.assign(this.data,Object.assign({email:h,roles:m,verified:f,iss:u,indiciaUserId:g,tokens:o},v)),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 +0,0 @@
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 +0,0 @@
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.location_id","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)))||[]}))};
@@ -1 +0,0 @@
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"),n=require("@flumens/utils/dist/errors"),s=require("@flumens/utils/dist/uuid"),a=require("../Model.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=l(o);const d=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 a.default{static fromDTO(t,o={}){d.parse(t);const{id:i,createdOn:r}=t,n=e.__rest(t,["id","createdOn"]);return new this(Object.assign({id:i,cid:s.UUIDv7(),data:n,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 u.default.post(e,o,i)}catch(e){if(u.default.isCancel(e))return;if(n.isAxiosNetworkError(e))throw new n.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(),r=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users/${i}`,s={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{yield u.default.delete(r,s)}catch(i){if(u.default.isCancel(i))return;if(n.isAxiosNetworkError(i))throw new n.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 u.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 u.default.get(e,t),i=({values:e})=>r.getCamelCaseObj(e),n=o.data.map(i);return n.forEach((e=>c.parse(e))),n}catch(e){if(u.default.isCancel(e))return[];if(n.isAxiosNetworkError(e))throw new n.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=d;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),i=require("@flumens/utils"),r=require("@flumens/utils/dist/errors"),o=require("../Collection.js"),a=require("./Group.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=n(s);class d extends o.default{constructor(e){super(Object.assign({id:"groups",Model:a.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:r}=e,o=yield this.remote.getAccessToken(),a=`${this.remote.url}/index.php/services/rest/groups`,n={};t&&(n.view=t),s&&(n.page=s.join(",")),Number.isFinite(r)&&(n.indexed_location_ids=r);const d={params:n,headers:{Authorization:`Bearer ${o}`},timeout:8e4},u=yield l.default.get(a,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(i.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&&(yield 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&&(yield 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&&(yield 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.upsert(...f),console.log(`📚 Collection: ${this.id} collection fetching done ${m.length} documents`)}catch(e){if(l.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 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;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),i=require("axios"),s=require("lodash"),n=require("zod"),a=require("@flumens/utils/dist/uuid"),o=require("../Model.js"),r=require("./Media.js");function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=d(i);const c=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.Site="14",u.BaitTrapSite="24555",u.BaitTrap="24554";class p extends o.default{static fromDTO(t,i={}){c.parse(t);const{id:s,createdOn:n,updatedOn:o,externalKey:r}=t,d=e.__rest(t,["id","createdOn","updatedOn","externalKey"]);return new this(Object.assign({cid:r||a.UUIDv7(),id:s,createdAt:new Date(n).getTime(),updatedAt:new Date(o).getTime(),data:d},i))}constructor(i={}){var{skipStore:s,store:n,media:a=[],metadata:o={},url:d,getAccessToken:l,Media:c=r.default}=i,u=e.__rest(i,["skipStore","store","media","metadata","url","getAccessToken","Media"]);super(Object.assign(Object.assign({},u),{store:s?void 0:n})),this.Media=c,this.metadata=t.observable(o);const p=a.map(((e,t={})=>i=>i instanceof e?i:new e(Object.assign(Object.assign({},i),t)))(this.Media));this.media=t.observable(p);const h=e=>e.parent=this;this.media.forEach(h);t.intercept(this.media,(e=>{var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(h),this.setUpdatedAtTimestamp(Date.now())):e.removedCount&&this.setUpdatedAtTimestamp(Date.now()),e})),this.remote=t.observable({synchronising:!1,url:d,getAccessToken:l})}saveRemote(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t,i,s,n;try{this.remote.synchronising=!0;const e=yield this.uploadMedia(),t=this.toDTO(e),i=`${this.remote.url}/index.php/services/rest/locations`,s={url:i,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:t},{data:n}=yield l.default(s),a=new Date(n.values.updated_on).getTime();return this.updatedAt=a,this.syncedAt=a,this.id=n.values.id,this.remote.synchronising=!1,this.store&&this.save(),console.log("Location uploading done"),this}catch(a){this.remote.synchronising=!1;const o=a;if(409===(null===(e=o.response)||void 0===e?void 0:e.status)&&(null===(t=o.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=o.response)||void 0===i?void 0:i.data.duplicate_of.id,this}const r=null===(n=null===(s=o.response)||void 0===s?void 0:s.data)||void 0===n?void 0:n.message;if(!r)throw a;if("object"==typeof r){throw new Error((e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""))(r))}throw new Error(r)}}))}toDTO(e={}){const t=(i=this.data,Object.entries(i).reduce(((e,[t,i])=>(e[t.includes("locAttr:")?t:s.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.id||!!this.syncedAt}get isSynchronising(){return this.remote.synchronising}get isDraft(){return!this.id}}exports.default=p,exports.dtoSchema=c;
@@ -1 +0,0 @@
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;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),i=require("axios"),a=require("@flumens/utils"),s=require("../Model.js");function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=r(i);const o=a.isPlatform("hybrid");class d extends s.default{static getDataURI(t,e={}){return new Promise(((i,a)=>{if("string"==typeof t){let a=t.startsWith("data:image")?t.split(";")[0].split("/")[1]:t.split(".").pop();return a||(a="jpeg"),"jpg"===a&&(a="jpeg"),void d.resize(t,a,e.width,e.height).then((t=>{const[e,s]=t;i([s,a,e.width,e.height])}))}if(!window.FileReader)return void a(new Error("No File Reader"));const s=new FileReader;s.onload=function(a){var s,r;if(e.width||e.height)d.resize(null===(s=a.target)||void 0===s?void 0:s.result,t.type,e.width,e.height).then((e=>{const[a,s]=e;i([s,t.type,a.width,a.height])}));else{const e=new window.Image;e.onload=()=>{var s;const r=t.type.replace(/.*\/([a-z]+)$/i,"$1");i([null===(s=a.target)||void 0===s?void 0:s.result,r,e.width,e.height])},e.src=null===(r=a.target)||void 0===r?void 0:r.result}},s.readAsDataURL(t)}))}static resize(t,e,i,a){return new Promise((s=>{const r=new window.Image;r.onload=()=>{var t;let{width:n}=r,{height:o}=r;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===(t=h.getContext("2d"))||void 0===t||t.drawImage(r,0,0,n,o),s([r,h.toDataURL(e)])},r.src=t}))}static getImageModel(e,i,s){return t.__awaiter(this,void 0,void 0,(function*(){const t=this;if(!e)throw new Error("File not found while creating image model.");let r,n,d;if(o){const t=yield a.createImage(e);r=t.width,n=t.height,d=e.split("/").pop()}else[d,,r,n]=yield t.getDataURI(e,{width:2e3,height:2e3});const h=new t({data:{data:d,type:"jpeg",width:r,height:n,path:i}});return s||(yield h.addThumbnail()),h}))}constructor(i={}){var{metadata:a={}}=i,s=t.__rest(i,["metadata"]);s.createdAt=s.createdAt||(null==a?void 0:a.createdOn),s.updatedAt=s.updatedAt||(null==a?void 0:a.updatedOn),s.syncedAt=s.syncedAt||(null==a?void 0:a.syncedOn),super(s),this.debouncedValue=300,this.parent=this.parent,this.remote=e.observable({synchronising:!1,url:s.url,getAccessToken:s.getAccessToken}),this.metadata=e.observable(a)}toJSON(){const t=super.toJSON();return JSON.parse(JSON.stringify(Object.assign(Object.assign({},t),{metadata:e.toJS(this.metadata)||{}})))}setUpdatedAtTimestamp(t){var e;super.setUpdatedAtTimestamp(t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)}toDTO(t={}){const e=t[this.cid];if(!this.id&&!e)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=e.name,i}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)}))}uploadFile(){return t.__awaiter(this,arguments,void 0,(function*(t=!1){var e;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(!t&&a)return;const s=yield this.getFormData(),r=new FormData;if(r.append(...s),!this.remote.getAccessToken)throw new Error("this.remote.getAccessToken is missing");const o={Authorization:`Bearer ${yield this.remote.getAccessToken()}`,Accept:"application/json"},d=yield n.default.post(`${this.remote.url}/index.php/services/rest/media-queue`,r,{headers:o,timeout:12e4});if(!(null===(e=d.data[this.cid])||void 0===e?void 0:e.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 t.__awaiter(this,void 0,void 0,(function*(){const{type:t}=this.data;let e=t,i=t;(null==t?void 0:t.match(/image.*/))?[,e]=t.split("/"):i=`image/${i}`;const s=this.getURL(),r=yield a.getBlobFromURL(s,i),n=this.cid;return[n,r,`${n}.${e}`]}))}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 t=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?`${t}/upload-queue/${this.data.queued}`:`${t}/upload/${this.data.path}`}getURL(){return this.data.data}resize(t,e){const i=this;return new Promise(((a,s)=>{d.resize(this.getURL(),this.data.type,t,e).then((t=>{const[e,s]=t;i.data.data=s,a([e,s])})).catch(s)}))}addThumbnail(t={}){const e=this;return new Promise(((t,i)=>{/^data:/i.test(this.getURL())?d.resize(this.getURL(),this.data.type,100,100).then((i=>{const[,a]=i;e.data.thumbnail=a,t()})).catch(i):d.getDataURI(this.getURL(),{width:100,height:100}).then((i=>{[e.data.thumbnail]=i,t()})).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=d;
@@ -1 +0,0 @@
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"),r=require("./helpers.js");class n extends i.default{static fromElasticDTO(t,e,a){var i,s,n,d,o,c,u;const{id:l,metadata:m,event:v,occurrence:p,taxon:h,identification:y}=t,f=new Date(m.created_on).getTime(),b=new Date(m.updated_on).getTime(),_=Date.now();let O=v.parent_event_id?null===(s=null===(i=a.smp)||void 0===i?void 0:i.occ)||void 0===s?void 0:s.attrs:null===(n=a.occ)||void 0===n?void 0:n.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=r.parseRemoteAttrs(O,(null==p?void 0:p.attributes)||[],!0),A=(null===(u=null==p?void 0:p.media)||void 0===u?void 0:u.map((({path:t})=>({id:t,createdAt:f,updatedAt:b,syncedAt:_,data:{data:`${e}/upload/${t}`}}))))||[],w=h.species||h.taxon_name,j=w!==h.taxon_name?h.taxon_name:"";return new this({id:l,cid:l,createdAt:f,updatedAt:b,syncedAt:_,metadata:{verification:y},data:Object.assign(Object.assign({},g),{taxaTaxonListId:parseInt(h.taxa_taxon_list_id,10),taxon:{warehouseId:parseInt(h.taxa_taxon_list_id,10),scientificName:w,commonName:j,foundInName:j?"commonName":"scientificName"},comment:null==p?void 0:p.occurrence_remarks}),media:A})}constructor(a={}){var{metadata:i={},media:r=[],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({},n.keys),(t=this.getSurvey().attrs||{},Object.keys(t).reduce(((e,a)=>{var i;return Object.assign(Object.assign({},e),{[a]:(null===(i=t[a])||void 0===i?void 0:i.remote)||t[a]})}),{})));var t},this.Media=d,this.metadata=e.observable(i);const c=r.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({},n.keys),e),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);const r=(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 n=t=>null==t;if(n(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=r(t,e),n(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}}n.keys={taxon:{id:"taxa_taxon_list_id"}},exports.default=n;
@@ -1 +0,0 @@
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"),c=require("./ElasticSample.js"),d=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=18e4;console.warn(JSON.stringify(e).substring(0,t))}catch(e){}}class O extends o.default{static fromElasticDTO(e,t={},s){var i,r;const{id:a,event:o,location:n,metadata:c}=e,{url:d}=t,u=new Date(o.date_start),h=new Date(c.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:`${d}/upload/${e}`}}))),_=n.name||n.verbatim_locality;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:c.survey.id,date:u.toISOString().split("T")[0],locationName:_,location:{code:n.code,name:_,latitude:v,longitude:f,shape:g,gridref:y},enteredSrefSystem:4326,groupId:null===(r=c.group)||void 0===r?void 0:r.id,locationId:n.location_id,comment:o.event_remarks,training:"true"===c.trial}),media:b},t))}constructor(s={}){var{metadata:i={},samples:r=[],occurrences:a=[],media:o=[],Occurrence:n=u.default,Media:c=d.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)=>{var i;return Object.assign(Object.assign({},t),{[s]:(null===(i=e[s])||void 0===i?void 0:i.remote)||e[s]})}),{})));var e},this.requiresRemoteSync=()=>!this.syncedAt||this.updatedAt>this.syncedAt,this.Occurrence=n,this.Media=c,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"]),c=Object.assign(Object.assign({},n),{data:{data:s,metadata:i,occurrences:r,samples:a,media:o}});yield this.store.save(c)}))}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 c.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=c.fetchElasticSubSamples({parentId:this.id,url:e,accessToken:t}),o=n.fetchElasticOccurrences({parentId:this.id,url:e,accessToken:t}),[d,u]=yield Promise.all([a,o]),l=(new Date).getTime(),h=d.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()}`,Accept:"application/json"};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 c=Number.isNaN(Number(n))?n:`smpAttr:${n}`;c=c.includes("smpAttr:")?c:i.snakeCase(c),r.values[c]=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.id||!!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 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),r=require("../Collection.js"),a=require("./ElasticOccurrence.js"),i=require("./ElasticSample.js"),c=require("./Sample.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(s);class d extends r.default{constructor(e){super(Object.assign({id:"samples",Model:c.default},e)),this.Occurrence=e.Occurrence,this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken});t.observe(this.data,(e=>{e.addedCount&&e.added.forEach((e=>e.collection=this)),e.removedCount&&e.removed.forEach((e=>delete e.collection))}))}fetch(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.store||!this.Model)return void this.ready.resolve(!1);const e=yield this.store.findAll(),t=e=>{const{data:t,metadata:s,occurrences:r,samples:a,media:i,attrs:c}=e.data;return new this.Model(Object.assign(Object.assign({},e),{attrs:c,data:t,metadata:s,occurrences:r,samples:a,media:i}))},s=e.map((e=>t(e)));this.data.push(...s),this.ready.resolve(!0)}))}fetchRemote(t,s){return e.__awaiter(this,void 0,void 0,(function*(){console.log("Fetching remote samples, page",t);const e=[{bool:{should:s.map((e=>({match:{"metadata.survey.id":e}})))}},{bool:{must_not:{exists:{field:"event.parent_event_id"}}}},{match:{"metadata.trial":"false"}}],r=JSON.stringify({from:t,size:100,query:{bool:{must:e}},sort:[{"metadata.created_on":"desc"}]}),c=this.remote.url,o=yield this.remote.getAccessToken(),d={method:"post",url:`${c}/index.php/services/rest/es-samples/_search`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},data:r},l=(yield n.default.request(d)).data.hits.hits.map((e=>e._source)),u=l.map((e=>e.id)),h=i.fetchElasticSubSamples({parentId:u,url:c,accessToken:o}),m=a.fetchElasticOccurrences({parentId:u,url:c,accessToken:o}),[p,f]=yield Promise.all([h,m]),v=l.map(((e,t,s,r,a)=>i=>{const c=(new Date).getTime();try{const o=new s({skipStore:!0});o.data.surveyId=i.metadata.survey.id;const n=o.getSurvey(),d=s.fromElasticDTO(i,{url:e,skipStore:!0},n);o.id=d.id,o.cid=d.cid||o.cid,Object.assign(o.data,d.data),Object.assign(o.metadata,d.metadata);const l=t=>{const r=s.fromElasticDTO(t,{url:e},n);return r.syncedAt=c,r},u=e=>e.event.parent_event_id===o.id||e.event.event_id===o.id,h=r.filter(u).map(l),m=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:t}),p=h.reduce(m,{[o.id]:o}),f=s=>{const r=t.fromElasticDTO(s,e,n);return r.syncedAt=c,[r,s.event.event_id]},v=a.filter(u).map(f),y=([e,t])=>{t!==parseInt(o.id,10)?p[t]?p[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):o.occurrences.push(e)};return v.forEach(y),o.samples.push(...h),o.syncedAt=c,o}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}})(c,this.Occurrence,this.Model,p,f)).filter((e=>!!e)),y=v.filter((e=>!this.cidMap.has(e.cid)));return this.data.push(...y),y}))}removeAllSynced(){const e=[];return this.data.forEach((t=>{t.syncedAt&&e.push(t.destroy())})),Promise.all(e)}reset(){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.data.map((e=>e.destroy()));yield Promise.all(e)}))}get isSynchronising(){return this.remote.synchronising}}exports.default=d;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.assignIfMissing=(e,t,r)=>{Number.isFinite(e.data[t])||e.data[t]||(Number.isFinite(r)||r)&&(e.data[t]=r)},exports.getErrorMessageFromObject=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""),exports.getLocalAttributes=function(e,t){const r=Object.entries(e).flatMap((([e,r])=>{const i=e.match(/:\d+/)?e.split(":").pop():e,s=Object.entries(t).find((a=i,([,e])=>{var t;return`${null===(t=e.remote)||void 0===t?void 0:t.id}`===a}));var a;if(!s)return null;const[o,n]=s;let d;const l=e=>{var t,r,i,s;if(!Array.isArray(null===(t=n.remote)||void 0===t?void 0:t.values))return e.raw_value;const a=null===(s=null===(i=null===(r=n.remote)||void 0===r?void 0:r.values)||void 0===i?void 0:i.find((({id:t})=>e.raw_value===t)))||void 0===s?void 0:s.value;return a||e.raw_value};return d=Array.isArray(r)?r.map(l):l(r),[[o,d]]})).filter((e=>!!e));return Object.fromEntries(r)},exports.migrateOldAttr=function(e,t,r){var i,s,a;const o=t.id,n=e.data[o];if(null==n||""===n)return;const d={},l=Array.isArray(null===(i=t.remote)||void 0===i?void 0:i.values),u="function"==typeof(null===(s=t.remote)||void 0===s?void 0:s.values);if(l){const e=t.remote.values,i=t=>e.find((e=>e.value===t||e.id===t||`${e.id}`==`${t}`));if(Array.isArray(n))d[r.id]=n.map((e=>{var t;return null===(t=i(e))||void 0===t?void 0:t.id})).filter(Boolean);else{const e=i(n);(null==e?void 0:e.id)&&(d[r.id]=String(e.id))}}else d[r.id]=u?t.remote.values(n,{values:d}):"object"==typeof n?JSON.parse(JSON.stringify(n)):n;o!==r.id&&(e.metadata&&((a=e.metadata)._migrated||(a._migrated={}),e.metadata._migrated[o]=n),delete e.data[o]),Object.assign(e.data,d)},exports.parseRemoteAttrs=(e,t,r=!1)=>{e=e||{};const i=Object.entries(e);return t.reduce(((e,t)=>{var s,a;const o=isNaN(t.value)?t.value:parseFloat(t.value),n=i.find((([,e])=>{var r;return(null===(r=e.remote)||void 0===r?void 0:r.id)===parseInt(t.id,10)}));if(n){const[t]=n;e[t]=o}if(!n||(null===(a=null===(s=n[1])||void 0===s?void 0:s.remote)||void 0===a?void 0:a.isBackwardsCompatible)){e[r?`occAttr:${t.id}`:`smpAttr:${t.id}`]=o}return e}),{})},exports.validateRemoteModel=function(){const e=this.getSurvey(),t=e.verify&&e.verify(this.data,this);let r={};if(t){const e=t&&"issues"in t;!("ValidationError"===t.name||"ValidationError"===t.type)&&!e?r.errors=[t.message]:e?r.errors=t.issues.map((({message:e})=>e)):r=Object.assign({},t)}const i=(e,t)=>{const r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},s=(this.samples||[]).reduce(i,{}),a=(this.occurrences||[]).reduce(i,{}),o=(this.media||[]).reduce(i,{});if(Object.keys(r).length||Object.keys(s).length||Object.keys(a).length||Object.keys(o).length){return{attributes:r,model:this,models:Object.assign(Object.assign(Object.assign({},s),a),o)}}return null};
package/dist/Model.js DELETED
@@ -1 +0,0 @@
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 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),i=require("localforage-cordovasqlitedriver"),t=require("@flumens/utils"),o=require("./utils.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=s(r),a=s(i);let n=["indexeddb","websql","localstorage"];t.isPlatform("hybrid")&&(n=[a.default,...n]);const l={driverOrder:n};class c{constructor(e){if(t.isPlatform("hybrid")&&!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");const r=Object.assign(Object.assign({},l),e);this.debugging=r.debugging,this.localForage=null,this.ready=new Promise(((e,i)=>{const t=new Promise((e=>{r.driverOrder&&"object"==typeof r.driverOrder[0]?d.default.defineDriver(r.driverOrder[0]).then(e):e(void 0)}));if(!r.storeName)throw new Error("storeName prop is missing");this.storeName=r.storeName,t.then((()=>{const t={name:r.name||"indicia",storeName:r.storeName};r.version&&(t.version=r.version);const o=c._getDriverOrder(r.driverOrder),s=r.LocalForage||d.default;this.localForage=s.createInstance(t),this.localForage.setDriver(o).then(e).catch(i)}))}))}static _getDriverOrder(e){return e.map((e=>{switch(e){case"indexeddb":return d.default.INDEXEDDB;case"websql":return d.default.WEBSQL;case"localstorage":return d.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))}save(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r.cid)throw new Error("Invalid key passed to store");if(this.debugging){const e=yield this.find(r.cid);o.printDiff(e,r,r.cid,this.storeName)}return this.localForage.setItem(r.cid,r)}))}find(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return(yield this.localForage.getItem(r))||void 0}))}findAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=[];return yield this.localForage.iterate((r=>{e.push(r)})),e}))}delete(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return this.localForage.removeItem(r)}))}deleteAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=yield this.findAll();yield Promise.all(e.map((e=>this.delete(e))))}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;return(yield this.findAll()).reduce(((e,r)=>Object.assign(Object.assign({},e),{[r.cid]:r})),{})}))}import(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,yield this.deleteAll(),"object"!=typeof r)throw new Error("Invalid obj passed to store");const e=Object.entries(r).map((([,e])=>this.save(e)));yield Promise.all(e)}))}}exports.default=c;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),i=require("@capacitor-community/sqlite"),o=require("@capacitor/core"),n=require("@capacitor/filesystem"),s=require("@flumens/utils"),r=require("./utils.js");exports.default=class{static migrateCordova(t){return e.__awaiter(this,void 0,void 0,(function*(){var e;console.log("SQLite: Cordova db migration");const o=new i.SQLiteConnection(i.CapacitorSQLite);try{let i;try{i=yield o.getMigratableDbList(t?"Library/LocalDatabase":void 0)}catch(e){console.log("SQLite: err",e.message)}if(!(null===(e=null==i?void 0: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 o.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,i.values),yield o.deleteOldDatabases(t?"Library/LocalDatabase":void 0,i.values),console.log("SQLite: migrating done",i.values)}catch(e){console.error(e)}yield o.checkConnectionsConsistency(),yield o.closeAllConnections()}))}get db(){return this.connection}constructor({name:e,debug:t,web:o}){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=o||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 o=yield this.db.query(e,t).then((e=>e.values||[])).catch((i=>{throw console.error("SQLite query error:",i,{sql:e,params:t}),i}));return this.debug&&(console.groupCollapsed(`💾 SQL: ${e.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30)}...`),console.debug(r.formatSqlQuery(e,t||[])),console.groupEnd(),yield null===(i=this.sqliteConnection)||void 0===i?void 0:i.saveToStore(this.name)),o}))}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(o.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(o){o.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 n.Filesystem.writeFile({path:e,data:i})}))}};
@@ -1 +0,0 @@
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"),n=require("@flumens/utils"),a=require("./utils.js");function d(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().unique(),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=d,exports.default=class{constructor({db:e,name:t,debug:i,columns:a=o(),extraConf:d}){this.ready=new n.Deferred,this.db=e,this.name=t,this.debug=i||!1,this.table=r.sqliteTable(this.name,a,d),this.init()}init(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.db.ready;const e=r.getTableConfig(this.table),t=e.columns.map((e=>`${e.name} ${e.getSQLType()}${e.primary?" primary key":""}${e.isUnique?" unique":""}${e.notNull?" not null":""}${e.default?` default ${e.default}`:""}`)).join(",\n");let i="";e.primaryKeys.length>0&&(i=", ",i+=e.primaryKeys.map((e=>`PRIMARY KEY (${e.columns.map((e=>e.name)).join(", ")})`)).join(", "));let n="";if(e.foreignKeys.length>0&&(n=", ",n+=e.foreignKeys.map((e=>{const t=e.reference(),i=r.getTableConfig(t.foreignTable),n=e.onDelete?` ON DELETE ${e.onDelete}`:"";return`FOREIGN KEY (${t.columns[0].name}) REFERENCES ${i.name}(${t.foreignColumns[0].name}) ${n}`})).join(", ")),yield this.db.query({sql:`CREATE TABLE IF NOT EXISTS ${this.name} (${t} ${i} ${n});`}),e.indexes.length){const t=e.indexes.map((e=>{const t=e.config.unique?"UNIQUE":"",i=e.config.columns.map((({name:e})=>e)).join(", "),r=e.config.name||`${this.name}_${i.replace(/, /g,"_")}_idx`;return this.db.query({sql:`CREATE ${t} INDEX IF NOT EXISTS ${r} ON ${this.name} (${i});`})}));yield Promise.all(t)}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});a.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:d(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(n){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;let e=(new r.QueryBuilder).select().from(this.table);n&&(e=n(e));return(yield this.db.query(e.toSQL())).map((e=>Object.entries(e).reduce(((e,[r,n])=>{var a;const d="jsonb"===(null===(a=t.getTableColumns(this.table)[r])||void 0===a?void 0:a.sqlName);return e[i.toCamelCase(r)]=d?JSON.parse(n):n,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,n,a,d,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===(n=t.metadata)||void 0===n?void 0:n.updatedOn)&&(t.updatedAt=null===(a=t.metadata)||void 0===a?void 0:a.updatedOn),!t.syncedAt&&(null===(d=t.metadata)||void 0===d?void 0:d.syncedOn)&&(t.syncedAt=null===(s=t.metadata)||void 0===s?void 0:s.syncedOn),t.samples){const{id:i,cid:r,createdAt:n,updatedAt:a,syncedAt:d}=t,s=e.__rest(t,["id","cid","createdAt","updatedAt","syncedAt"]);t={id:i,cid:r,createdAt:n,updatedAt:a,syncedAt:d,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;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.default=class{};
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./SQLiteDatabase.js"),r=require("./LocalForageStore.js"),t=require("./SQLiteStore.js"),o=require("./Store.js");exports.SQLiteDatabase=e.default,exports.LocalForageStore=r.default,exports.SQLiteStore=t.default,exports.IStore=o.default;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("deep-diff"),r=require("lodash");exports.formatSqlQuery=(e,r)=>{const o=e=>null==e?"NULL":"number"==typeof e||"bigint"==typeof e?`${e}`:"boolean"==typeof e?e?"TRUE":"FALSE":e instanceof Date?`'${e.toISOString()}'`:Array.isArray(e)?e.length?`(${e.map(o).join(", ")})`:"(NULL)":"object"==typeof e?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`;let t=0;return e.replace(/\?/g,(()=>{if(t>=r.length)return"?";const e=o(r[t]);return t+=1,e}))},exports.printDiff=function(o,t,n,l=""){const i=e.diff(o,t);if(!i)return;let s={},f=0,p="";if(i.forEach((e=>{const o={[l]:{[n]:{}}};if(!e.path)return o[l][n]=e.rhs,console.groupCollapsed(`Δ + ${n}`),console.log(o),void console.groupEnd();e.path.reduce(((r,o,t)=>{if(e.path.length-1>t)return r[o]={},r[o];const n=JSON.stringify(e.lhs,null,2),l=JSON.stringify(e.rhs,null,2);if(n===l)return r[o];f++,r[o]=`${n} -> ${l}`,p=`${o}: ${n} -> ${l}`}),o[l][n]),s=r.merge(s,o)})),f){let e=`Δ ${n}`;1===f&&(e+=` ${p}`),console.groupCollapsed(e),console.log(s),console.groupEnd()}};
package/dist/index.js DELETED
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./Drupal/User.js"),r=require("./Stores/SQLiteDatabase.js"),o=require("./Stores/LocalForageStore.js"),t=require("./Stores/SQLiteStore.js"),i=require("./Stores/Store.js"),a=require("./Model.js"),s=require("./Collection.js"),c=require("./Indicia/Media.js"),u=require("./Indicia/Occurrence.js"),l=require("./Indicia/Sample.js"),p=require("./Indicia/Group.js"),d=require("./Indicia/Location.js"),n=require("./Indicia/SampleCollection.js"),S=require("./Indicia/GroupCollection.js"),x=require("./Indicia/LocationCollection.js");exports.DrupalUserModel=e.default,exports.SQLiteDatabase=r.default,exports.LocalForageStore=o.default,exports.SQLiteStore=t.default,exports.IStore=i.default,exports.Model=a.default,exports.Collection=s.default,exports.IndiciaMedia=c.default,exports.IndiciaOccurrence=u.default,exports.IndiciaSample=l.default,exports.IndiciaGroup=p.default,exports.groupDtoSchema=p.dtoSchema,exports.IndiciaLocation=d.default,Object.defineProperty(exports,"LocationType",{enumerable:!0,get:function(){return d.LocationType}}),exports.locationDtoSchema=d.dtoSchema,exports.IndiciaSampleCollection=n.default,exports.IndiciaGroupCollection=S.default,exports.byGroupMembershipStatus=S.byGroupMembershipStatus,exports.IndiciaLocationCollection=x.default,exports.byLocationType=x.byLocationType;