entropic-bond 1.50.0 → 1.50.2

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 (111) hide show
  1. package/lib/auth/auth-mock.d.ts +22 -0
  2. package/lib/auth/auth-mock.spec.d.ts +1 -0
  3. package/lib/auth/auth.d.ts +131 -0
  4. package/lib/auth/user-auth-types.d.ts +19 -0
  5. package/lib/cloud-functions/cloud-functions-mock.d.ts +11 -0
  6. package/lib/cloud-functions/cloud-functions-mock.spec.d.ts +1 -0
  7. package/lib/cloud-functions/cloud-functions.d.ts +19 -0
  8. package/lib/cloud-storage/cloud-storage.d.ts +24 -0
  9. package/lib/cloud-storage/cloud-storage.spec.d.ts +1 -0
  10. package/lib/cloud-storage/mock-cloud-storage.d.ts +20 -0
  11. package/lib/cloud-storage/stored-file.d.ts +39 -0
  12. package/lib/entropic-bond.js +1667 -0
  13. package/lib/entropic-bond.umd.cjs +7 -0
  14. package/lib/index.d.ts +19 -0
  15. package/lib/observable/observable.d.ts +52 -0
  16. package/lib/observable/observable.spec.d.ts +1 -0
  17. package/lib/persistent/entropic-component.d.ts +76 -0
  18. package/lib/persistent/entropic-component.spec.d.ts +1 -0
  19. package/lib/persistent/persistent.d.ts +281 -0
  20. package/lib/persistent/persistent.spec.d.ts +67 -0
  21. package/lib/server-auth/server-auth-mock.d.ts +12 -0
  22. package/lib/server-auth/server-auth-mock.spec.d.ts +1 -0
  23. package/lib/server-auth/server-auth.d.ts +24 -0
  24. package/lib/store/data-source.d.ts +137 -0
  25. package/lib/store/json-data-source.d.ts +68 -0
  26. package/lib/store/json-data-source.spec.d.ts +1 -0
  27. package/lib/store/mocks/test-user.d.ts +49 -0
  28. package/lib/store/model.d.ts +238 -0
  29. package/lib/store/model.spec.d.ts +1 -0
  30. package/lib/store/store.d.ts +62 -0
  31. package/lib/store/store.spec.d.ts +1 -0
  32. package/lib/types/utility-types.d.ts +45 -0
  33. package/lib/types/utility-types.spec.d.ts +1 -0
  34. package/lib/utils/test-utils/test-person.d.ts +33 -0
  35. package/{src/utils/utils.ts → lib/utils/utils.d.ts} +10 -34
  36. package/lib/utils/utils.spec.d.ts +1 -0
  37. package/package.json +7 -4
  38. package/.github/workflows/release.yml +0 -26
  39. package/CHANGELOG.md +0 -1151
  40. package/docs/.nojekyll +0 -1
  41. package/docs/README.md +0 -94
  42. package/docs/classes/Auth.md +0 -391
  43. package/docs/classes/AuthMock.md +0 -278
  44. package/docs/classes/AuthService.md +0 -188
  45. package/docs/classes/CloudFunctions.md +0 -123
  46. package/docs/classes/CloudFunctionsMock.md +0 -97
  47. package/docs/classes/CloudStorage.md +0 -215
  48. package/docs/classes/DataSource.md +0 -248
  49. package/docs/classes/EntropicComponent.md +0 -666
  50. package/docs/classes/JsonDataSource.md +0 -328
  51. package/docs/classes/MockCloudStorage.md +0 -279
  52. package/docs/classes/Model.md +0 -274
  53. package/docs/classes/Observable.md +0 -120
  54. package/docs/classes/Persistent.md +0 -420
  55. package/docs/classes/ServerAuth.md +0 -211
  56. package/docs/classes/ServerAuthMock.md +0 -176
  57. package/docs/classes/ServerAuthService.md +0 -130
  58. package/docs/classes/Store.md +0 -218
  59. package/docs/classes/StoredFile.md +0 -636
  60. package/docs/enums/StoredFileEvent.md +0 -41
  61. package/docs/interfaces/AuthError.md +0 -30
  62. package/docs/interfaces/CloudFunctionsService.md +0 -69
  63. package/docs/interfaces/Collection.md +0 -13
  64. package/docs/interfaces/CustomCredentials.md +0 -7
  65. package/docs/interfaces/DocumentReference.md +0 -49
  66. package/docs/interfaces/JsonRawData.md +0 -7
  67. package/docs/interfaces/SignData.md +0 -63
  68. package/docs/interfaces/StoreParams.md +0 -52
  69. package/docs/interfaces/StoredFileChange.md +0 -41
  70. package/docs/interfaces/UploadControl.md +0 -90
  71. package/docs/interfaces/UserCredentials.md +0 -113
  72. package/docs/interfaces/Values.md +0 -17
  73. package/docs/modules.md +0 -1273
  74. package/src/auth/auth-mock.spec.ts +0 -168
  75. package/src/auth/auth-mock.ts +0 -129
  76. package/src/auth/auth.ts +0 -185
  77. package/src/auth/user-auth-types.ts +0 -21
  78. package/src/cloud-functions/cloud-functions-mock.spec.ts +0 -136
  79. package/src/cloud-functions/cloud-functions-mock.ts +0 -23
  80. package/src/cloud-functions/cloud-functions.ts +0 -83
  81. package/src/cloud-storage/cloud-storage.spec.ts +0 -207
  82. package/src/cloud-storage/cloud-storage.ts +0 -60
  83. package/src/cloud-storage/mock-cloud-storage.ts +0 -72
  84. package/src/cloud-storage/stored-file.ts +0 -102
  85. package/src/index.ts +0 -19
  86. package/src/observable/observable.spec.ts +0 -105
  87. package/src/observable/observable.ts +0 -67
  88. package/src/persistent/entropic-component.spec.ts +0 -143
  89. package/src/persistent/entropic-component.ts +0 -135
  90. package/src/persistent/persistent.spec.ts +0 -828
  91. package/src/persistent/persistent.ts +0 -650
  92. package/src/server-auth/server-auth-mock.spec.ts +0 -53
  93. package/src/server-auth/server-auth-mock.ts +0 -45
  94. package/src/server-auth/server-auth.ts +0 -49
  95. package/src/store/data-source.ts +0 -186
  96. package/src/store/json-data-source.spec.ts +0 -100
  97. package/src/store/json-data-source.ts +0 -256
  98. package/src/store/mocks/mock-data.json +0 -155
  99. package/src/store/mocks/test-user.ts +0 -122
  100. package/src/store/model.spec.ts +0 -659
  101. package/src/store/model.ts +0 -462
  102. package/src/store/store.spec.ts +0 -30
  103. package/src/store/store.ts +0 -113
  104. package/src/types/utility-types.spec.ts +0 -117
  105. package/src/types/utility-types.ts +0 -116
  106. package/src/utils/test-utils/test-person.ts +0 -44
  107. package/src/utils/utils.spec.ts +0 -95
  108. package/tsconfig-build.json +0 -7
  109. package/tsconfig-cjs.json +0 -9
  110. package/tsconfig.json +0 -33
  111. package/vite.config.ts +0 -22
@@ -0,0 +1,7 @@
1
+ (function(a,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(a=typeof globalThis<"u"?globalThis:a||self,v(a["entropic-bond"]={}))})(this,function(a){"use strict";var p;class v{constructor(){this.subscribers=new Set}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}notify(e){this.subscribers.forEach(t=>t(e))}get subscribersCount(){return this.subscribers.size}}let R;const L=new Uint8Array(16);function Q(){if(!R&&(R=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!R))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return R(L)}const d=[];for(let i=0;i<256;++i)d.push((i+256).toString(16).slice(1));function q(i,e=0){return d[i[e+0]]+d[i[e+1]]+d[i[e+2]]+d[i[e+3]]+"-"+d[i[e+4]]+d[i[e+5]]+"-"+d[i[e+6]]+d[i[e+7]]+"-"+d[i[e+8]]+d[i[e+9]]+"-"+d[i[e+10]]+d[i[e+11]]+d[i[e+12]]+d[i[e+13]]+d[i[e+14]]+d[i[e+15]]}const M={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Y(i,e,t){if(M.randomUUID&&!e&&!i)return M.randomUUID();i=i||{};const r=i.random||(i.rng||Q)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=r[s];return e}return q(r)}var z=Object.defineProperty,J=Object.getOwnPropertyDescriptor,H=(i,e,t,r)=>{for(var s=r>1?void 0:r?J(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=(r?o(e,t,s):o(s))||s);return r&&s&&z(e,t,s),s};const V=(p=class{static registerFactory(e,t,r){this._factoryMap[e]={factory:t,annotation:r}}static classFactory(e){if(!e)throw new Error("You should provide a class name.");if(!this._factoryMap[e])throw new Error(`You should register class ${e} prior to use.`);return this._factoryMap[e].factory}static registeredClasses(){return Object.keys(this._factoryMap)}static classesExtending(e){return Object.entries(this._factoryMap).filter(([,t])=>new t.factory instanceof e).map(([t])=>t)}static annotations(e){if(e instanceof p?e=e.className:typeof e=="string"||(e=new e().className),!this._factoryMap[e])throw new Error(`You should register class ${e} prior to use.`);return this._factoryMap[e].annotation}constructor(e=Y()){this._id=e}get className(){return this.__className}setId(e){this._id=e}get id(){return this._id}afterDeserialize(){}beforeSerialize(){}getPersistentProperties(){return this._persistentProperties?this._persistentProperties.map(e=>({...e,name:e.name.slice(1)})):[]}getPropInfo(e){const t=this.getPersistentProperties().find(r=>r.name===e);if(!t)throw new Error(`Property "${e}" has not been registered.`);return t}isRequired(e){const t=this.getPropInfo(e).validator;return t!=null}isPropValueValid(e){const t=this.getPropInfo(e);return t.validator?t.validator(this[t.name],t,this):!0}clone(e){const t=e.toObject();return delete t.id,this.fromObject(t)}fromObject(e){return this.fromObj(e),this.afterDeserialize(),this}fromObj(e){return this._persistentProperties?(this._persistentProperties.forEach(t=>{const r=this.removeUnderscore(t),s=e[r];s!=null&&(this[t.name]=this.fromDeepObject(s))}),this):this}toObject(){const e={},t=this.toObj(e);return this.pushDocument(e,this.className,t),{...t,__rootCollections:e}}toObj(e){if(!this._persistentProperties)return{};this.beforeSerialize();const t={};if(!this.className)throw new Error("You should register this class prior to streaming it.");return this._persistentProperties.forEach(r=>{const s=this[r.name],n=this.removeUnderscore(r);s!=null&&(r.isReference?t[n]=this.toReferenceObj(r,e):t[n]=this.toDeepObj(s,e),r.searchableArray&&(t[p.searchableArrayNameFor(n)]=s.map(o=>o.id)))}),t.__className=this.className,t}static searchableArrayNameFor(e){return`__${e}_searchable`}fromDeepObject(e){if(e==null)return e;if(Array.isArray(e))return e.map(t=>this.fromDeepObject(t));if(e.__documentReference){const t=e,r=p.createInstance(t);return r.__documentReference=e.__documentReference,r}if(e.__className)return p.createInstance(e);if(typeof e=="object"){const t={};return Object.entries(e).forEach(([r,s])=>t[r]=this.fromDeepObject(s)),t}return e}toDeepObj(e,t){if(e!=null){if(Array.isArray(e))return e.map(r=>this.toDeepObj(r,t));if(e.__documentReference)return e;if(e instanceof p)return e.toObj(t);if(typeof e=="object"){const r={};return Object.entries(e).forEach(([s,n])=>r[s]=this.toDeepObj(n,t)),r}return e}}toReferenceObj(e,t){const r=this[e.name],s=n=>{let o;return typeof e.storeInCollection=="function"?o=e.storeInCollection(n,e):o=e.storeInCollection||n.className,o};return Array.isArray(r)?r.map(n=>(e.isPureReference||this.pushDocument(t,s(n),n),this.buildRefObject(n,s(n),e.forcedPersistentProps))):(e.isPureReference||this.pushDocument(t,s(r),r),this.buildRefObject(r,s(r),e.forcedPersistentProps))}buildRefObject(e,t,r){const s=r==null?void 0:r.reduce((n,o)=>(e[o]!==void 0&&(n[o]=e[o]),n),{});return{id:e.id,__className:e.className||e.__className,__documentReference:{storedInCollection:t},...s}}pushDocument(e,t,r){if("__documentReference"in r&&r.__documentReference)return;e[t]||(e[t]=[]);const s=this.toDeepObj(r,e);e[t].push(s)}removeUnderscore(e){return e.name.slice(1)}static createReference(e){const t=p.createInstance(e);return t.__documentReference=e.__documentReference||{storedInCollection:t.className},t}static createInstance(e){if(typeof e=="string")return new(p.classFactory(e));try{return new(p.classFactory(e.__className))().fromObject(e)}catch(t){const r=Object.entries(e).filter(([s,n])=>n!=null&&typeof n!="function").map(([s,n])=>`${s}: ${n}`).join(`,
2
+ `);throw new Error(`${t}
3
+ -----> Class name not found in object:
4
+ {
5
+ ${r}
6
+ }
7
+ `)}}static propInfo(e,t){return p.createInstance(e).getPropInfo(t)}},p._factoryMap={},p);H([S],V.prototype,"_id",2);let h=V;function S(i,e){return _()(i,e)}function Z(i){return function(e,t){return _({storeInCollection:i,isReference:!0})(e,t)}}function G(i,e){return _({isReference:!0})(i,e)}function K(i,e){return function(t,r){return _({isReference:!0,forcedPersistentProps:i,storeInCollection:e})(t,r)}}function X(i,e,t){return _({isReference:!0,isPureReference:!0,storeInCollection:t})(i,e)}function x(i,e){return function(t,r){return _({isReference:!0,isPureReference:!0,forcedPersistentProps:i,storeInCollection:e})(t,r)}}function _(i){return function(e,t){Object.getOwnPropertyDescriptor(e,"_persistentProperties")||(e._persistentProperties?e._persistentProperties=[...e._persistentProperties]:e._persistentProperties=[]);const r=e._persistentProperties.find(s=>s.name===t);r?Object.assign(r,i):e._persistentProperties.push({name:t,...i})}}function $(i,e){return t=>{h.registerFactory(i,t,e),t.prototype.__className=i}}function ee(i){return e=>{h.registerFactory(i,e)}}function te(i,e){return _({searchableArray:!0})(i,e)}function re(i,e){return _({validator:t=>t!=null})(i,e)}function se(i=e=>e!=null){return function(e,t){return _({validator:i})(e,t)}}class ie extends h{constructor(){super(...arguments),this._onChange=new v}onChange(e){return this._onChange.subscribe(e)}removeOnChange(e){this._onChange.unsubscribe(e)}changeProp(e,t){const r="_"+String(e);return this[r]!==t?(this[r]=t,this._onChange.notify({[e]:t}),!0):!1}notify(e){this._onChange.notify(e)}pushAndNotify(e,t,r){const s="_"+String(e);if(!(r&&this[s].find(o=>!r(o,t))))return this[s].push(t),this.notify({[e]:this[e]}),t}removeAndNotify(e,t,r){const s="_"+String(e),n=this[s].length;if(this[s]=this[s].filter(o=>!r(o,t)),n!==this[s].length)return this.notify({[e]:this[e]}),t}}class D{static toPropertyPathOperations(e){return e?e.map(t=>{if(D.isArrayOperator(t.operator)&&t.value[0]instanceof h)return{property:h.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(o=>o.id),aggregate:t.aggregate};const[r,s]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${r?"."+r:""}`,operator:t.operator,value:s,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e==="containsAny"||e==="contains"}static toPropertyPathValue(e){if(typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e)[0],[r,s]=this.toPropertyPathValue(e[t]);return[`${t}${r?"."+r:""}`,s]}else return[void 0,e]}}class ne{constructor(e){this._jsonRawData={},this._lastMatchingDocs=[],this._lastLimit=0,this._cursor=0,this._simulateDelay=0,this._pendingPromises=[],e&&(this._jsonRawData=e)}setDataStore(e){return this._jsonRawData=e,this}simulateDelay(e){return this._simulateDelay=e,this}findById(e,t){var r,s;if((r=this._simulateError)!=null&&r.findById)throw new Error(this._simulateError.findById);return this.resolveWithDelay((s=this._jsonRawData[t])==null?void 0:s[e])}save(e){var t;if((t=this._simulateError)!=null&&t.store)throw new Error(this._simulateError.store);return Object.entries(e).forEach(([r,s])=>{this._jsonRawData[r]||(this._jsonRawData[r]={}),s==null||s.forEach(n=>{this._jsonRawData[r][n.id]=n})}),this.resolveWithDelay()}find(e,t){var s;if((s=this._simulateError)!=null&&s.find)throw new Error(this._simulateError.find);const r=Object.values(this._jsonRawData[t]||{});return e?(this._lastLimit=e.limit||0,this._cursor=0,this._lastMatchingDocs=Object.entries(e).reduce((n,[o,l])=>this.queryProcessor(n,o,l),Object.values(r)),this.resolveWithDelay(this._lastMatchingDocs.slice(0,e.limit))):this.resolveWithDelay(r)}delete(e,t){var r;if((r=this._simulateError)!=null&&r.delete)throw new Error(this._simulateError.delete);return delete this._jsonRawData[t][e],this.resolveWithDelay()}next(e){return e&&(this._lastLimit=e),this.incCursor(this._lastLimit),this.resolveWithDelay(this._lastMatchingDocs.slice(this._cursor,this._cursor+this._lastLimit))}count(e,t){return this.resolveWithDelay(Object.keys(this._jsonRawData[t]??{}).length)}get rawData(){return this._jsonRawData}wait(){return Promise.all([...this._pendingPromises])}incCursor(e){this._cursor+=e,this._cursor>this._lastMatchingDocs.length&&(this._cursor=this._lastMatchingDocs.length)}simulateError(e){return e===void 0?(this._simulateError=void 0,this):(typeof e=="string"?this._simulateError={store:e,find:e,findById:e,delete:e}:this._simulateError=e,this)}decCursor(e){return this._cursor-=e,this._cursor<0?(this._cursor=0,!0):!1}queryProcessor(e,t,r){return{limit:n=>e,operations:n=>this.retrieveQueryDocs(e,n),sort:({order:n,propertyName:o})=>e.sort((l,g)=>n==="asc"?this.deepValue(l,o)>this.deepValue(g,o)?1:-1:this.deepValue(l,o)<this.deepValue(g,o)?1:-1)}[t](r)}retrieveQueryDocs(e,t){return t.reduce((r,s,n)=>{if(s.aggregate){const o=e.filter(l=>this.isQueryMatched(l,s));return n===0?o:r.concat(o)}else return r.filter(o=>this.isQueryMatched(o,s))},e)}deepValue(e,t){return t.split(".").reduce((s,n)=>s[n],e)}isQueryMatched(e,t){const r={"==":(c,u)=>c===u,"!=":(c,u)=>c!==u,"<":(c,u)=>c<u,"<=":(c,u)=>c<=u,">":(c,u)=>c>u,">=":(c,u)=>c>=u,containsAny:(c,u)=>c==null?void 0:c.some(A=>u==null?void 0:u.includes(A)),contains:(c,u)=>c==null?void 0:c.includes(u)},{property:s,value:n,operator:o}=t,[l,g]=this.retrieveValuesToCompare(e,s,n);return r[o](l,g)}retrieveValuesToCompare(e,t,r){const s=e[t];if(s&&typeof r=="object"&&!Array.isArray(r)){const l=Object.keys(r)[0];var[n,o]=this.retrieveValuesToCompare(s,l,r==null?void 0:r[l])}return[n||s,o||r]}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);const t=new Promise(r=>{setTimeout(()=>r(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(r=>r===t)),t}}const j=class j{constructor(e,t,r){if(r){if(!(t instanceof h))throw new Error(j.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof h?t.className:t;this._stream=e}findById(e,t){return new Promise((r,s)=>{this._stream.findById(e,this.collectionName).then(n=>{n?(t?t.fromObject(n):t=h.createInstance(n),r(t)):r(void 0)}).catch(n=>s(n))})}save(e){const t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((r,s)=>{this._stream.save(t.__rootCollections).then(()=>r()).catch(n=>s(n))})}delete(e){return new Promise((t,r)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(s=>r(s))})}find(){return new T(this)}query(e={},t){if(t){const r=t instanceof h?t.className:t;e.operations||(e.operations=[]),e.operations.push({property:"__className",operator:"==",value:r})}return this.mapToInstance(()=>this._stream.find(this.preprocessQueryObject(e),this.collectionName))}count(e){return this._stream.count(e,this.collectionName)}next(e){return this.mapToInstance(()=>this._stream.next(e))}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(n=>h.createInstance(n)))).catch(s=>r(s))})}preprocessQueryObject(e){var r;if(Object.values(e).length===0)return e;const t=((r=e.operations)==null?void 0:r.map(s=>{const n=s.value[0]??s.value;return D.isArrayOperator(s.operator)&&n instanceof h?{property:h.searchableArrayNameFor(s.property),operator:s.operator,value:Array.isArray(s.value)?s.value.map(o=>o.id):n.id,aggregate:s.aggregate}:{property:s.property,operator:s.operator,value:s.value instanceof h?{id:s.value.id}:s.value,aggregate:s.aggregate}}))??[];return{...e,operations:t}}};j.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let C=j;class T{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){var n,o,l;if((o=(n=this.queryObject.operations)==null?void 0:n.at(-1))!=null&&o.aggregate&&!s)throw new Error(C.error.invalidQueryOrder);return(l=this.queryObject.operations)==null||l.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){var g,c,u;if((c=(g=this.queryObject.operations)==null?void 0:g.at(-1))!=null&&c.aggregate&&!s)throw new Error(C.error.invalidQueryOrder);const n=e.split(".");let o={},l=n.length>1?o:r;return n.slice(1).forEach((A,ye)=>{o[A]=ye<n.length-2?{}:r,o=o[A]}),(u=this.queryObject.operations)==null||u.push({property:n[0],operator:t,value:l,aggregate:s}),this}and(e,t,r){return this.where(e,t,r)}andDeepProp(e,t,r){return this.whereDeepProp(e,t,r)}or(e,t,r){return this.where(e,t,r,!0)}orDeepProp(e,t,r){return this.whereDeepProp(e,t,r,!0)}instanceOf(e){var r;const t=e instanceof h?e.className:e;return(r=this.queryObject.operations)==null||r.push({property:"__className",operator:"==",value:t}),this}get(e){return e&&(this.queryObject.limit=e),this.model.query(this.queryObject)}limit(e){return this.queryObject.limit=e,this}orderBy(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}orderByDeepProp(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}count(){return this.model.count(this.queryObject)}}const w=class w{constructor(){}static useDataSource(e){this._dataSource=e}static get dataSource(){return w._dataSource}static getModel(e){if(!w._dataSource)throw new Error(this.error.shouldBeRegistered);return new C(w._dataSource,e)}static getModelForSubCollection(e,t){if(!w._dataSource)throw new Error(this.error.shouldBeRegistered);return new C(w._dataSource,e,t)}static async populate(e){if(!e)return;const t=async r=>{const s=r;if(!s.__documentReference)return r;const o=await this.getModel(s.__documentReference.storedInCollection).findById(s.id,r);return o&&(o.__documentReference=void 0),o};return Array.isArray(e)?(await Promise.all(e.map(s=>t(s)))).filter(s=>s):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((t,r)=>t&&r.__documentReference===void 0,!0):e.__documentReference===void 0}};w.error={shouldBeRegistered:"You should register a data source before using the data Store."};let E=w;const b=class b{static registerCloudStorage(e,t){b._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=b._cloudStorageFactoryMap[e];if(!t)throw new Error(`You should register the ${e} cloud storage provider prior to use it`);return t()}get className(){return this.__className}static useCloudStorage(e){b._defaultCloudStorage=e}static get defaultCloudStorage(){if(!b._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return b._defaultCloudStorage}};b._cloudStorageFactoryMap={};let P=b;function B(i,e){return P.registerCloudStorage(i,e),t=>{t.prototype.__className=i}}var oe=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,ce=(i,e,t,r)=>{for(var s=r>1?void 0:r?ae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=(r?o(e,t,s):o(s))||s);return r&&s&&oe(e,t,s),s};a.MockCloudStorage=class extends P{constructor(e=""){super(),this._simulateDelay=0,this._pendingPromises=[],this.mockFileSystem={},this._pathToMockFiles=e}simulateDelay(e){return this._simulateDelay=e,this}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);const t=new Promise(r=>{setTimeout(()=>r(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(r=>r===t)),t}save(e,t){const r=e;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[e]=JSON.stringify(t),this._onProgress&&this._onProgress(100,100);const s=t instanceof File?t.name:r;return this.resolveWithDelay(s)}uploadControl(){return{resume:()=>{},pause:()=>{},cancel:()=>{},onProgress:e=>this._onProgress=e}}getUrl(e){return Promise.resolve(this._pathToMockFiles+e)}delete(e){return delete this.mockFileSystem[e],this.resolveWithDelay()}},a.MockCloudStorage=ce([B("MockCloudStorage",()=>new a.MockCloudStorage)],a.MockCloudStorage);var ue=Object.defineProperty,he=Object.getOwnPropertyDescriptor,O=(i,e,t,r)=>{for(var s=r>1?void 0:r?he(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=(r?o(e,t,s):o(s))||s);return r&&s&&ue(e,t,s),s},W=(i=>(i[i.stored=0]="stored",i[i.pendingDataSet=1]="pendingDataSet",i[i.deleted=2]="deleted",i))(W||{});a.StoredFile=class extends h{constructor(){super(...arguments),this._onChange=new v}async save({data:e,fileName:t,progress:r,cloudStorageProvider:s}={}){const n=e||this._pendingData;n&&(this._reference&&await this.delete(),this.provider=s||P.defaultCloudStorage,this._originalFileName=t||(n instanceof File?n.name:void 0),this._reference=await this.provider.save(this.id,n,r),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:0,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw new Error("Cannot delete a not stored file");await this.provider.delete(this._reference),this._reference=void 0,this._url=void 0,this._onChange.notify({event:2,storedFile:this})}set provider(e){this._provider=e,this._cloudStorageProviderName=e.className}get provider(){if(!this._provider)try{this._provider=P.createInstance(this._cloudStorageProviderName)}catch{this._provider=P.defaultCloudStorage}return this._provider}get url(){return this._url}get mimeType(){return this._mimeType}setDataToStore(e){return this._pendingData=e,this._originalFileName=e instanceof File?e.name:void 0,this._mimeType=e instanceof Blob?e.type:void 0,this._onChange.notify({event:1,pendingData:e,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(e){return this._onChange.subscribe(e)}},O([S],a.StoredFile.prototype,"_reference",2),O([S],a.StoredFile.prototype,"_url",2),O([S],a.StoredFile.prototype,"_cloudStorageProviderName",2),O([S],a.StoredFile.prototype,"_originalFileName",2),O([S],a.StoredFile.prototype,"_mimeType",2),a.StoredFile=O([$("StoredFile")],a.StoredFile);class F{}const f=class f extends F{constructor(){if(super(),this._onAuthStateChange=new v,!f._authService)throw new Error(f.error.shouldBeRegistered);f._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){f._authService!=e&&(f._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return f._authService.signUp(e)}login(e){return f._authService.login(e)}logout(){return f._authService.logout()}resetEmailPassword(e){return f._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return f._authService.resendVerificationEmail(e,t,r)}refreshToken(){return f._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return f._authService.linkAdditionalProvider(e)}unlinkProvider(e){return f._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};f.error={shouldBeRegistered:"You should register an auth service before using Auth."},f._instance=void 0;let U=f;class le extends F{constructor(){super(...arguments),this.pendingPromises=[],this._fakeRegisteredUsers={}}signUp(e){const{verificationLink:t,email:r,password:s,authProvider:n}=e,o=new Promise(async(l,g)=>{var c,u;n==="email"&&(r||g({code:"missingEmail",message:"missingEmail"}),s||g({code:"missingPassword",message:"missingPassword"})),s!=="fail"&&r!=="fail"?(this._loggedUser=this.userCredentials(e),this._fakeRegisteredUsers[this._loggedUser.id]=this._loggedUser,l(this._loggedUser),(c=this.notifyChange)==null||c.call(this,this._loggedUser)):(g({code:"userNotFound",message:t||"Test auth error"}),(u=this.notifyChange)==null||u.call(this,void 0))});return this.pendingPromises.push(o),o}login(e){const t=Object.values(this._fakeRegisteredUsers).find(r=>r.email===e.email);return e.authProvider==="email"&&!t&&e.email&&(e.email="fail"),this.signUp(e)}onAuthStateChange(e){this.notifyChange=e,this.notifyChange(this._loggedUser)}async logout(){const e=new Promise(t=>{var r;this._loggedUser=void 0,t(),(r=this.notifyChange)==null||r.call(this,void 0)});return this.pendingPromises.push(e),e}resetEmailPassword(e){return Object.values(this._fakeRegisteredUsers).find(r=>r.email===e)?Promise.resolve():Promise.reject({code:"userNotFound",message:"Test auth error"})}resendVerificationEmail(e,t,r){return Object.values(this._fakeRegisteredUsers).find(n=>n.email===e)?Promise.resolve():Promise.reject({code:"userNotFound",message:"Test auth error"})}refreshToken(){return Promise.resolve()}linkAdditionalProvider(e){throw new Error("Not implemented.")}unlinkProvider(e){throw new Error("Not implemented.")}async flush(){await Promise.all(this.pendingPromises),this.pendingPromises=[]}fakeRegisteredUser(e){if(this._fakeRegisteredUsers[e.id])throw new Error(`User with id ${e.id} already exists in fake user list`);return this._fakeRegisteredUsers[e.id]=e,this}get fakeRegisteredUsers(){return this._fakeRegisteredUsers}userCredentials(e){const t=Object.values(this._fakeRegisteredUsers).find(r=>r.email===e.email);return t?{...t}:{id:e.authProvider||`testUID${e.email?"-"+e.email:""}`,email:e.email||"testEmail",name:e.authProvider||`testName${e.email?" "+e.email:""}`,phoneNumber:"testPhone",customData:{role:"test"},lastLogin:0,creationDate:0}}}const y=class y{constructor(){}static useCloudFunctionsService(e){this._cloudFunctionsService!=e&&(this._cloudFunctionsService=e)}static get instance(){if(!this._cloudFunctionsService)throw new Error(y.error.shouldBeRegistered);return y._instance||(y._instance=new y)}getRawFunction(e){return y._cloudFunctionsService.retrieveFunction(e)}getFunction(e){const t=y._cloudFunctionsService.callFunction,r=this.getRawFunction(e);return async s=>{const n=await t(r,this.processParam(s));return this.processResult(n)}}processParam(e){if(e!=null)return e instanceof h?e.toObject():Array.isArray(e)?e.map(t=>this.processParam(t)):typeof e=="object"?Object.entries(e).reduce((t,[r,s])=>(t[r]=this.processParam(s),t),{}):e}processResult(e){if(e!=null)return e.__className?h.createInstance(e):Array.isArray(e)?e.map(t=>this.processResult(t)):typeof e=="object"?Object.entries(e).reduce((t,[r,s])=>(t[r]=this.processResult(s),t),{}):e}};y.error={shouldBeRegistered:"You should register a cloud functions service with useCloudFunctionsService static method before using CloudFunctions."};let N=y;class de{constructor(e){this._registeredFunctions=e}retrieveFunction(e){const t=this._registeredFunctions[e];if(!t)throw new Error(`Cloud function ${e} is not registered.`);return t}callFunction(e,t){return e(t)}}class I{}const m=class m extends I{constructor(){super()}static useServerAuthService(e){m._authService!=e&&(m._authService=e,this._instance=void 0)}static get instance(){if(!m._authService)throw new Error(m.error.shouldBeRegistered);return this._instance||(this._instance=new m)}getUser(e){return m._authService.getUser(e)}updateUser(e,t){return m._authService.updateUser(e,t)}setCustomCredentials(e,t){return m._authService.setCustomCredentials(e,t)}deleteUser(e){return m._authService.deleteUser(e)}};m.error={shouldBeRegistered:"You should register a Server Auth service before using the Server Auth."},m._instance=void 0;let k=m;class fe extends I{constructor(e){super(),this._userCredentials=e}getUser(e){return this._userCredentials[e]||Promise.resolve(void 0),Promise.resolve(this._userCredentials[e])}setCustomCredentials(e,t){const r=this._userCredentials[e];if(!r)throw new Error(`User ${e} not found in the auth system`);return r.customData={...t},Promise.resolve()}updateUser(e,t){return this._userCredentials[e]={...this._userCredentials,...t,id:e},Promise.resolve(this._userCredentials[e])}deleteUser(e){return delete this._userCredentials[e],Promise.resolve()}get userCredentials(){return this._userCredentials}}function pe(i,e){return i?i.replace(/\${\s*(\w*)\s*}/g,function(t,r){return e[r]||""}):""}function me(i){return i?i.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}function ge(i,e="-"){if(!i)return"";const t=i.slice(1).replace(/( |[A-Z])/g,r=>r===" "?"-":e+r[0].toLowerCase());return i[0].toLocaleLowerCase()+t.replace(/--/g,"-")}function _e(i,e){return e.split(".").reduce((t,r)=>t[r],i)}a.Auth=U,a.AuthMock=le,a.AuthService=F,a.CloudFunctions=N,a.CloudFunctionsMock=de,a.CloudStorage=P,a.DataSource=D,a.EntropicComponent=ie,a.JsonDataSource=ne,a.Model=C,a.Observable=v,a.Persistent=h,a.Query=T,a.ServerAuth=k,a.ServerAuthMock=fe,a.ServerAuthService=I,a.Store=E,a.StoredFileEvent=W,a.camelCase=me,a.getDeepValue=_e,a.persistent=S,a.persistentParser=_,a.persistentPureReference=X,a.persistentPureReferenceWithPersistentProps=x,a.persistentReference=G,a.persistentReferenceAt=Z,a.persistentReferenceWithPersistentProps=K,a.registerCloudStorage=B,a.registerLegacyClassName=ee,a.registerPersistentClass=$,a.replaceValue=pe,a.required=re,a.requiredWithValidator=se,a.searchableArray=te,a.snakeCase=ge,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
package/lib/index.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export * from './observable/observable';
2
+ export * from './persistent/entropic-component';
3
+ export * from './persistent/persistent';
4
+ export * from './store/data-source';
5
+ export * from './store/json-data-source';
6
+ export * from './store/store';
7
+ export * from './store/model';
8
+ export * from './types/utility-types';
9
+ export * from './cloud-storage/cloud-storage';
10
+ export * from './cloud-storage/mock-cloud-storage';
11
+ export * from './cloud-storage/stored-file';
12
+ export * from './auth/auth';
13
+ export * from './auth/user-auth-types';
14
+ export * from './auth/auth-mock';
15
+ export * from './cloud-functions/cloud-functions';
16
+ export * from './cloud-functions/cloud-functions-mock';
17
+ export * from './server-auth/server-auth';
18
+ export * from './server-auth/server-auth-mock';
19
+ export * from './utils/utils';
@@ -0,0 +1,52 @@
1
+ export type Callback<T> = (event: T) => void;
2
+ export type Unsubscriber = () => void;
3
+ /**
4
+ * Implements the Observer pattern.
5
+ * The Observable class is used to notify a list of subscribers when an event occurs.
6
+ * The subscribers are callback functions that are called when the event occurs.
7
+ * The event is passed as a parameter to the callback function.
8
+ * @example
9
+ * // Create an observable
10
+ * const observable = new Observable<number>()
11
+ * // Subscribe a listener
12
+ * const unsubscribe = observable.subscribe( event => console.log( event ) )
13
+ * // Notify the subscribers
14
+ * observable.notify( 1 )
15
+ * // Unsubscribe the listener
16
+ * unsubscribe()
17
+ */
18
+ export declare class Observable<T> {
19
+ /**
20
+ * Subscribes a listener callback function. On every notification,
21
+ * the listener callback will be called with an event as a parameter if sent.
22
+ *
23
+ * @param callback the listener callback
24
+ * @returns a function to unsubscribe the listener from further notifications
25
+ */
26
+ subscribe(callback: Callback<T>): Unsubscriber;
27
+ /**
28
+ * Removes the callback from the notification list.
29
+ *
30
+ * @param listenerCallback the listener callback to remove
31
+ */
32
+ unsubscribe(callback: Callback<T>): void;
33
+ /**
34
+ * Notifies all the subscribers with the event passed as parameter.
35
+ *
36
+ * @param event the event passed to all subscribers.
37
+ */
38
+ notify(event?: T): void;
39
+ /**
40
+ * Returns the number of subscribers.
41
+ *
42
+ * @returns the number of subscribers
43
+ * @example
44
+ * const observable = new Observable<number>()
45
+ * observable.subscribe( event => console.log( event ) )
46
+ * observable.subscribe( event => console.log( event ) )
47
+ * observable.subscribe( event => console.log( event ) )
48
+ * console.log( observable.subscribersCount ) // 3
49
+ */
50
+ get subscribersCount(): number;
51
+ private subscribers;
52
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,76 @@
1
+ import { Callback, Unsubscriber } from '../observable/observable';
2
+ import { ClassArrayPropNames, ClassProps, Elements } from '../types/utility-types';
3
+ import { Persistent } from './persistent';
4
+ export type PropChangeEvent<T> = Partial<ClassProps<T>>;
5
+ export type PropChangeCallback<T> = Callback<PropChangeEvent<T>>;
6
+ type ArrayPropsElem<T> = Elements<T[ClassArrayPropNames<T>]>;
7
+ export type CompareFunction<T> = (a: ArrayPropsElem<T>, b: ArrayPropsElem<T>) => boolean;
8
+ /**
9
+ * Derived classes from EntropicComponent will have the ability to notify
10
+ * property changes by calling one of the provided notification methods.
11
+ * It extends Persistent class therefore EntropicComponent children will have
12
+ * persistance through the Entropic Bond persistence mechanism
13
+ */
14
+ export declare class EntropicComponent extends Persistent {
15
+ /**
16
+ * Subscribes a listener callback function. Every time a property is changed,
17
+ * the listener callback will be called with the property change event.
18
+ *
19
+ * @param listenerCallback the listener callback
20
+ * @returns a function to unsubscribe the listener from further notifications
21
+ */
22
+ onChange(listenerCallback: PropChangeCallback<this>): Unsubscriber;
23
+ /**
24
+ * Removes the listener callback subscrition from the notifications.
25
+ *
26
+ * @param listenerCallback the listener callback to remove
27
+ */
28
+ removeOnChange(listenerCallback: PropChangeCallback<this>): void;
29
+ /**
30
+ * Changes the value of the property and notifies the subscribers about the change.
31
+ * This is a helper method that can be used in the property setter.
32
+ *
33
+ * @param propName the name of the property to be changed
34
+ * @param value the new value for the property
35
+ * @returns true in case the property has been effectively changed, false otherwise
36
+ */
37
+ protected changeProp<P extends keyof this>(propName: P, value: this[P]): boolean;
38
+ /**
39
+ * Notifies the subscribers a property or group of properties change.
40
+ * This is a helper function to be used when you want to notify property changes.
41
+ *
42
+ * @param event the event with the changed properties
43
+ */
44
+ protected notify<T extends EntropicComponent>(event: PropChangeEvent<T>): void;
45
+ /**
46
+ * Inserts a new element in an arbitrary array property of this class and
47
+ * fires a change event if successfully inserted. To avoid repeated elements
48
+ * to be inserted, you can pass a function that checks for inequity.
49
+ *
50
+ * @param arrayPropName the name of the array property of this class where you
51
+ * want to insert the new element.
52
+ * @param element the element to be inserted
53
+ * @param isUnique a function that checks for inequity of the two elements
54
+ * passed as parameter. If the returned value is true, the
55
+ * value will be pushed into the array. When the function is
56
+ * not provided, the element will be inserted regardless it is
57
+ * already in the array.
58
+ * @returns the inserted element or undefined if the element was not inserted.
59
+ */
60
+ protected pushAndNotify<T extends EntropicComponent>(arrayPropName: ClassArrayPropNames<T>, element: ArrayPropsElem<T>, isUnique?: CompareFunction<T>): ArrayPropsElem<T> | undefined;
61
+ /**
62
+ * Removes an element from an arbitrary array property of this class and fires
63
+ * a change event on operation success.
64
+ *
65
+ * @param arrayPropName the name of the array property of this class where you
66
+ * want to insert the new element.
67
+ * @param element the element to be inserted
68
+ * @param isEqual a function that checks for equity of the two elements
69
+ * passed as parameter. If the returned value is true, the
70
+ * value will be removed from the array.
71
+ * @returns the removed element or undefined if the element was not removed.
72
+ */
73
+ protected removeAndNotify<T extends EntropicComponent>(arrayPropName: ClassArrayPropNames<T>, element: ArrayPropsElem<T>, isEqual: CompareFunction<T>): ArrayPropsElem<T> | undefined;
74
+ private _onChange;
75
+ }
76
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,281 @@
1
+ import { ClassPropNames, SomeClassProps, UnderscoredProp } from '../types/utility-types';
2
+ export type PersistentConstructor = new () => Persistent;
3
+ /**
4
+ * The corresponding type of the plain object of a persistent class.
5
+ */
6
+ export type PersistentObject<T extends Persistent> = Omit<SomeClassProps<T>, 'className'> & Partial<DocumentReference> & {
7
+ __className: string;
8
+ __rootCollections?: Collections;
9
+ };
10
+ export type PersistentObjectWithId<T extends Persistent> = PersistentObject<T> & {
11
+ id: string;
12
+ };
13
+ /**
14
+ * The type of the plain object of a persistent class for all the nested properties.
15
+ */
16
+ export type MakePersistentObjects<T> = {
17
+ [A in keyof T]: T[A] extends Persistent ? PersistentObject<T[A]> : MakePersistentObjects<T[A]>;
18
+ };
19
+ /**
20
+ * A collection of document objects typically returned by Persistent.toObject()
21
+ * @see Persistent.toObject
22
+ */
23
+ export type Collections = {
24
+ [collectionPath: string]: PersistentObjectWithId<Persistent>[] | undefined;
25
+ };
26
+ /**
27
+ * Stores information about a reference in another collection.
28
+ */
29
+ export interface DocumentReference {
30
+ id: string;
31
+ __className: string;
32
+ __documentReference: {
33
+ storedInCollection: string;
34
+ };
35
+ }
36
+ /**
37
+ * A class that provides several methods to serialize and deserialize objects.
38
+ */
39
+ export declare class Persistent {
40
+ /**
41
+ * Registers a class to be used by the persistence engine.
42
+ * @param className the name of the class to be registered
43
+ * @param factory the constructor of the registered class
44
+ * @param annotation an annotation associated with the class
45
+ */
46
+ static registerFactory(className: string, factory: PersistentConstructor, annotation?: unknown): void;
47
+ /**
48
+ * Returns the constructor of a registered class
49
+ * @param className the name of the class to be retrieved
50
+ * @returns the constructor of the class
51
+ * @throws an error if the class is not registered
52
+ * @see registerFactory
53
+ * @see registeredClasses
54
+ * @see classesExtending
55
+ * @see annotations
56
+ */
57
+ static classFactory(className: string | undefined): PersistentConstructor;
58
+ /**
59
+ * Returns the names of all registered classes
60
+ * @returns the names of all registered classes
61
+ * @see registerFactory
62
+ * @see classFactory
63
+ */
64
+ static registeredClasses(): string[];
65
+ /**
66
+ * Returns the names of all registered classes that extend a given class
67
+ * @param derivedFrom the class to be extended
68
+ * @returns the names of all registered classes that extend the given class
69
+ * @see registerFactory
70
+ * @see classFactory
71
+ */
72
+ static classesExtending(derivedFrom: PersistentConstructor | Function): string[];
73
+ /**
74
+ * Returns the annotation associated with a registered class
75
+ * @param className the name of the class to be retrieved
76
+ * @returns the annotation associated with the class
77
+ * @throws an error if the class is not registered
78
+ * @see registerFactory
79
+ */
80
+ static annotations(className: string | Persistent | PersistentConstructor): unknown;
81
+ /**
82
+ * Returns a new instance of Persistent class.
83
+ * @param className the initial id of this instance. If not provided, a new id will be generated
84
+ */
85
+ constructor(id?: string);
86
+ /**
87
+ * Gets the class name of this instance.
88
+ */
89
+ get className(): string;
90
+ /**
91
+ * Sets the id of this instance.
92
+ * @param value the id of this instance
93
+ */
94
+ protected setId(value: string): void;
95
+ /**
96
+ * Returns the id of this instance.
97
+ * @returns the id of this instance
98
+ */
99
+ get id(): string;
100
+ /**
101
+ * This method is called by the persistence engine when the instance has been
102
+ * just serialized. It is called after the properties are initialized with
103
+ * serialized data.
104
+ */
105
+ protected afterDeserialize(): void;
106
+ /**
107
+ * This method is called by the persistence engine before the instance is
108
+ * serialized.
109
+ */
110
+ protected beforeSerialize(): void;
111
+ /**
112
+ * Returns an array of the persistent properties of this instance.
113
+ * @returns an array of the persistent properties of this instance
114
+ */
115
+ getPersistentProperties(): readonly PersistentProperty[];
116
+ /**
117
+ * Get the property information of this instance
118
+ * @param propName the persistent property name
119
+ * @returns the property information
120
+ */
121
+ getPropInfo<T extends this>(propName: ClassPropNames<T>): PersistentProperty;
122
+ /**
123
+ * Query if the property is required
124
+ * To mark a property as required, use the @required decorator
125
+ * @param propName the persistent property name
126
+ * @returns true if the property is required
127
+ * @see required
128
+ */
129
+ isRequired<T extends this>(propName: ClassPropNames<T>): boolean;
130
+ /**
131
+ * Query if the property value is valid
132
+ * Define the validator function using the @required decorator
133
+ * @param propName the persistent property name
134
+ * @returns true if the property value is valid using the validator function
135
+ * passed to the @required decorator
136
+ * @see required
137
+ */
138
+ isPropValueValid<T extends this>(propName: ClassPropNames<T>): boolean;
139
+ /**
140
+ * Copy the persistent properties of the given instance to this instance.
141
+ * The property `id` will be ignored.
142
+ * Only the properties that are not null or undefined will be copied.
143
+ * @param instance the instance to be copied
144
+ * @returns this instance
145
+ * @see fromObject
146
+ * @see toObject
147
+ */
148
+ clone(instance: Persistent): this;
149
+ /**
150
+ * Initializes the persistent properties of this instance from the properties
151
+ * of given object.
152
+ * @param obj the object to be copied
153
+ * @returns this instance
154
+ * @see clone
155
+ * @see toObject
156
+ */
157
+ fromObject(obj: Partial<PersistentObject<this>> | {}): this;
158
+ private fromObj;
159
+ /**
160
+ * Returns a plain object representation of this instance.
161
+ * Only the properties that are not null or undefined will be copied.
162
+ * @returns a plain object representation of this instance
163
+ * @see fromObject
164
+ * @see clone
165
+ */
166
+ toObject(): PersistentObject<this>;
167
+ private toObj;
168
+ static searchableArrayNameFor(propName: string): string;
169
+ private fromDeepObject;
170
+ private toDeepObj;
171
+ private toReferenceObj;
172
+ private buildRefObject;
173
+ private pushDocument;
174
+ private removeUnderscore;
175
+ static createReference<T extends Persistent>(obj: PersistentObject<T> | string): T;
176
+ static createInstance<T extends Persistent>(obj: PersistentObject<T> | string): T;
177
+ static propInfo<T extends Persistent>(registeredClassName: string, propName: ClassPropNames<T>): PersistentProperty;
178
+ private _id;
179
+ private _persistentProperties;
180
+ private static _factoryMap;
181
+ }
182
+ type CollectionPathCallback = (value: Persistent, prop: PersistentProperty) => string;
183
+ type ValidatorFunction<T extends Persistent, P extends ClassPropNames<T>> = (value: T[P], property: PersistentProperty, persistentInstance: T) => boolean;
184
+ interface PersistentProperty {
185
+ name: string;
186
+ isReference?: boolean;
187
+ isPureReference?: boolean;
188
+ storeInCollection?: string | CollectionPathCallback;
189
+ subCollection?: string;
190
+ forcedPersistentProps?: ClassPropNames<Persistent>[];
191
+ toObjectSpecial?: (classObj: any) => any;
192
+ fromObjectSpecial?: (obj: any) => any;
193
+ searchableArray?: boolean;
194
+ validator?: ValidatorFunction<any, any>;
195
+ }
196
+ /**
197
+ * Decorator for a property that you want to persist.
198
+ */
199
+ export declare function persistent(target: Persistent, property: string): void;
200
+ /**
201
+ * Decorator for a property that is a reference to a persistent object and should be stored
202
+ * in a specific collection.
203
+ * @param collectionPath the path to the collection where the reference should be stored.
204
+ * @returns
205
+ */
206
+ export declare function persistentReferenceAt(collectionPath: string | CollectionPathCallback): (target: Persistent, property: string) => void;
207
+ /**
208
+ * Decorator for a property that is a reference to a persistent object.
209
+ * The reference content is automatically stored in a collection. The collection
210
+ * is determined by the class name of the decorated property.
211
+ * @see persistentPureReference
212
+ */
213
+ export declare function persistentReference(target: Persistent, property: string): void;
214
+ /**
215
+ * Decorator to declare a persistent reference (see @persistentReference) that stores
216
+ * the values in forcedPersistentProps as values in the reference object. This is useful
217
+ * when you are not able to wait for population of referenced properties.
218
+ * @param forcedPersistentProps the properties whose values should be stored in the reference object
219
+ * @param storedInCollection indicates the path of the collection where this reference is stored
220
+ */
221
+ export declare function persistentReferenceWithPersistentProps<T extends Persistent>(forcedPersistentProps: ClassPropNames<T>[], storeInCollection?: string | CollectionPathCallback): (target: Persistent, property: string) => void;
222
+ /**
223
+ * Decorator for a property that is a reference to a persistent object.
224
+ * In this case, and contrary to the @persistentReference decorator, the reference
225
+ * contents is not stored even it has been changed. Only the reference information
226
+ * is stored.
227
+ * @see persistentReference
228
+ */
229
+ export declare function persistentPureReference(target: Persistent, property: string, storeInCollection?: string | CollectionPathCallback): void;
230
+ /**
231
+ * Decorator to declare a persistent property as a pure reference (see @persistentPureReference) that stores
232
+ * the values of the properties listed in forcedPersistentProps as values in the reference object. This is useful
233
+ * when you only need a few properties to be available without needing to populate the referenced property.
234
+ * @param forcedPersistentProps the properties whose values should be stored in the reference object
235
+ * @param storedInCollection indicates the path of the collection where this reference is stored
236
+ * @see persistentReferenceWithPersistentProps
237
+ * @see persistentPureReference
238
+ * @sample
239
+ * class User extends Persistent {
240
+ * @persistentPureReferenceWithPersistentProps( ['name', 'email'] ) private _friend: User
241
+ * }
242
+ * // the reference object will contain the properties name and email of the referenced user
243
+ * // without having to populate the _friend property
244
+ */
245
+ export declare function persistentPureReferenceWithPersistentProps<T extends Persistent>(forcedPersistentProps: ClassPropNames<T>[], storeInCollection?: string | CollectionPathCallback): (target: Persistent, property: string) => void;
246
+ export declare function persistentParser(options?: Partial<PersistentProperty>): (target: Persistent, property: string) => void;
247
+ /**
248
+ * Decorator to register a persistent class. Entropic Bond needs that you register
249
+ * all persistent classes that you want to use in any persistent stream.
250
+ * @param className the name of the class
251
+ * @param annotation an optional annotation that can be used to store additional information
252
+ */
253
+ export declare function registerPersistentClass(className: string, annotation?: unknown): (constructor: PersistentConstructor) => void;
254
+ /**
255
+ * Decorator to register a legacy name for a persistent class. This is useful when you want to
256
+ * be able to load old data that was stored with a different class name.
257
+ * @param legacyName the legacy name of the class
258
+ */
259
+ export declare function registerLegacyClassName(legacyName: string): (constructor: PersistentConstructor) => void;
260
+ /**
261
+ * Decorator to make a `Persistent` array property searchable by the
262
+ * persistance engine.
263
+ * When a property is marked as searchable, the persistance engine will
264
+ * generate internally a new property with the same name but with the suffix `_searchable`
265
+ * and prefixed with the `_` character. This new property will contain an array
266
+ * with the `id` of the persistent elements in the original array.
267
+ */
268
+ export declare function searchableArray(target: Persistent, property: string): void;
269
+ /**
270
+ * Decorator to mark the property as required.
271
+ * @see requiredWithValidator
272
+ */
273
+ export declare function required(target: Persistent, property: string): void;
274
+ /**
275
+ * Decorator to mark the property as required.
276
+ * @param validator a function that returns true if the property value is valid.
277
+ * By default, the property is valid if it is not undefined and not null.
278
+ * @see required
279
+ */
280
+ export declare function requiredWithValidator<T extends Persistent, P extends ClassPropNames<T>>(validator?: ValidatorFunction<T, P>): (target: T, property: UnderscoredProp<P>) => void;
281
+ export {};
@@ -0,0 +1,67 @@
1
+ import { Persistent } from './persistent';
2
+ interface InnerObject {
3
+ nonPersistedReferences: PersistentClass[];
4
+ }
5
+ declare class PersistentClass extends Persistent {
6
+ protected beforeSerialize(): void;
7
+ protected afterDeserialize(): void;
8
+ set persistentProp(val: number | undefined);
9
+ get persistentProp(): number | undefined;
10
+ set personPureRef(value: Person | undefined);
11
+ get personPureRef(): Person | undefined;
12
+ set persistentArray(value: PersistentClass[] | undefined);
13
+ get persistentArray(): PersistentClass[] | undefined;
14
+ _persistentProp: number | undefined;
15
+ _persistentArray: PersistentClass[] | undefined;
16
+ _personPureRef: Person | undefined;
17
+ _nonPersistentProp: number | undefined;
18
+ }
19
+ declare class NotRegistered extends Persistent {
20
+ }
21
+ declare class Person extends Persistent {
22
+ protected beforeSerialize(): void;
23
+ protected afterDeserialize(): void;
24
+ set name(value: string | undefined);
25
+ get name(): string | undefined;
26
+ set salary(value: number | undefined);
27
+ get salary(): number | undefined;
28
+ set doNotPersist(value: number | undefined);
29
+ get doNotPersist(): number | undefined;
30
+ set anObjectProperty(value: PersistentClass);
31
+ get anObjectProperty(): PersistentClass;
32
+ set skills(value: string[] | undefined);
33
+ get skills(): string[] | undefined;
34
+ set arrayOfPersistent(value: PersistentClass[] | undefined);
35
+ get arrayOfPersistent(): PersistentClass[] | undefined;
36
+ set document(value: PersistentClass | undefined);
37
+ get document(): PersistentClass | undefined;
38
+ set arrayOfRefs(value: PersistentClass[]);
39
+ get arrayOfRefs(): PersistentClass[];
40
+ set persistentObject(value: InnerObject | undefined);
41
+ get persistentObject(): InnerObject | undefined;
42
+ private _name?;
43
+ private _salary?;
44
+ private _skills;
45
+ private _anObjectProperty;
46
+ private _arrayOfPersistent;
47
+ _notRegistered: NotRegistered | undefined;
48
+ _arrayOfArray: number[][] | undefined;
49
+ _arrayOfPersistentArray: PersistentClass[][] | undefined;
50
+ _plainObject: {
51
+ [key: string]: unknown;
52
+ } | undefined;
53
+ _document: PersistentClass | undefined;
54
+ _docAtArbitraryCollection: PersistentClass | undefined;
55
+ _docAtArbitraryCollectionRefFunc: PersistentClass | undefined;
56
+ private _arrayOfRefs;
57
+ private _persistentObject;
58
+ _referenceWithStoredValues: PersistentClass | undefined;
59
+ private _doNotPersist;
60
+ }
61
+ export declare class WithAnnotations extends PersistentClass {
62
+ }
63
+ export declare class WithAnnotations2 extends PersistentClass {
64
+ }
65
+ export declare class WithAnnotations3 extends PersistentClass {
66
+ }
67
+ export {};
@@ -0,0 +1,12 @@
1
+ import { UserCredentials } from '../auth/user-auth-types';
2
+ import { Collection } from '../types/utility-types';
3
+ import { ServerAuthService, CustomCredentials } from './server-auth';
4
+ export declare class ServerAuthMock extends ServerAuthService {
5
+ constructor(userCredentials: Collection<UserCredentials<{}>>);
6
+ getUser<T extends CustomCredentials>(userId: string): Promise<UserCredentials<T> | undefined>;
7
+ setCustomCredentials<T extends CustomCredentials>(userId: string, customCredentials: T): Promise<void>;
8
+ updateUser<T extends CustomCredentials>(userId: string, credentials: Partial<UserCredentials<T>>): Promise<UserCredentials<T>>;
9
+ deleteUser(userId: string): Promise<void>;
10
+ get userCredentials(): Collection<UserCredentials<{}>>;
11
+ private _userCredentials;
12
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,24 @@
1
+ import { UserCredentials } from '../auth/user-auth-types';
2
+ export interface CustomCredentials {
3
+ [key: string]: unknown;
4
+ }
5
+ export declare abstract class ServerAuthService {
6
+ abstract setCustomCredentials<T extends CustomCredentials>(userId: string, customCredentials: T): Promise<void>;
7
+ abstract getUser<T extends CustomCredentials>(userId: string): Promise<UserCredentials<T> | undefined>;
8
+ abstract updateUser<T extends CustomCredentials>(userId: string, credentials: Partial<UserCredentials<T>>): Promise<UserCredentials<T>>;
9
+ abstract deleteUser(userId: string): Promise<void>;
10
+ }
11
+ export declare class ServerAuth extends ServerAuthService {
12
+ static error: {
13
+ shouldBeRegistered: string;
14
+ };
15
+ protected constructor();
16
+ static useServerAuthService(authService: ServerAuthService): void;
17
+ static get instance(): ServerAuth;
18
+ getUser<T extends CustomCredentials>(userId: string): Promise<UserCredentials<T> | undefined>;
19
+ updateUser<T extends CustomCredentials>(userId: string, credentials: Partial<UserCredentials<T>>): Promise<UserCredentials<T>>;
20
+ setCustomCredentials<T extends CustomCredentials>(userId: string, customCredentials: T): Promise<void>;
21
+ deleteUser(userId: string): Promise<void>;
22
+ private static _instance;
23
+ private static _authService;
24
+ }