UNPKG

@speckle/objectsender

Version:

Simple API helper to serialize and send objects to the server.

3 lines (2 loc) 12.2 kB
"use strict";var pt=Object.defineProperty;var Y=t=>{throw TypeError(t)};var yt=(t,e,r)=>e in t?pt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var l=(t,e,r)=>yt(t,typeof e!="symbol"?e+"":e,r),K=(t,e,r)=>e.has(t)||Y("Cannot "+r);var o=(t,e,r)=>(K(t,e,"read from private field"),r?r.call(t):e.get(t)),p=(t,e,r)=>e.has(t)?Y("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),f=(t,e,r,n)=>(K(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),h=(t,e,r)=>(K(t,e,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("reflect-metadata");const g=require("@speckle/shared");var gt=typeof global=="object"&&global&&global.Object===Object&&global,_t=typeof self=="object"&&self&&self.Object===Object&&self,J=gt||_t||Function("return this")(),C=J.Symbol,it=Object.prototype,bt=it.hasOwnProperty,mt=it.toString,P=C?C.toStringTag:void 0;function wt(t){var e=bt.call(t,P),r=t[P];try{t[P]=void 0;var n=!0}catch{}var a=mt.call(t);return n&&(e?t[P]=r:delete t[P]),a}var St=Object.prototype,Tt=St.toString;function jt(t){return Tt.call(t)}var Ot="[object Null]",vt="[object Undefined]",tt=C?C.toStringTag:void 0;function st(t){return t==null?t===void 0?vt:Ot:tt&&tt in Object(t)?wt(t):jt(t)}function ct(t){return t!=null&&typeof t=="object"}var Ct="[object Symbol]";function V(t){return typeof t=="symbol"||ct(t)&&st(t)==Ct}function zt(t,e){for(var r=-1,n=t==null?0:t.length,a=Array(n);++r<n;)a[r]=e(t[r],r,t);return a}var W=Array.isArray,et=C?C.prototype:void 0,rt=et?et.toString:void 0;function ot(t){if(typeof t=="string")return t;if(W(t))return zt(t,ot)+"";if(V(t))return rt?rt.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function ht(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var $t="[object AsyncFunction]",kt="[object Function]",Pt="[object GeneratorFunction]",It="[object Proxy]";function Et(t){if(!ht(t))return!1;var e=st(t);return e==kt||e==Pt||e==$t||e==It}var q=J["__core-js_shared__"],nt=function(){var t=/[^.]+$/.exec(q&&q.keys&&q.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function xt(t){return!!nt&&nt in t}var Mt=Function.prototype,Dt=Mt.toString;function At(t){if(t!=null){try{return Dt.call(t)}catch{}try{return t+""}catch{}}return""}var Rt=/[\\^$.*+?()[\]{}|]/g,Ft=/^\[object .+?Constructor\]$/,Lt=Function.prototype,Nt=Object.prototype,Ut=Lt.toString,Gt=Nt.hasOwnProperty,Ht=RegExp("^"+Ut.call(Gt).replace(Rt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Kt(t){if(!ht(t)||xt(t))return!1;var e=Et(t)?Ht:Ft;return e.test(At(t))}function qt(t,e){return t==null?void 0:t[e]}function ut(t,e){var r=qt(t,e);return Kt(r)?r:void 0}function Bt(t,e){return t===e||t!==t&&e!==e}var Jt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Vt=/^\w*$/;function Wt(t,e){if(W(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||V(t)?!0:Vt.test(t)||!Jt.test(t)||e!=null&&t in Object(e)}var x=ut(Object,"create");function Xt(){this.__data__=x?x(null):{},this.size=0}function Zt(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Qt="__lodash_hash_undefined__",Yt=Object.prototype,te=Yt.hasOwnProperty;function ee(t){var e=this.__data__;if(x){var r=e[t];return r===Qt?void 0:r}return te.call(e,t)?e[t]:void 0}var re=Object.prototype,ne=re.hasOwnProperty;function ae(t){var e=this.__data__;return x?e[t]!==void 0:ne.call(e,t)}var ie="__lodash_hash_undefined__";function se(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=x&&e===void 0?ie:e,this}function b(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}b.prototype.clear=Xt;b.prototype.delete=Zt;b.prototype.get=ee;b.prototype.has=ae;b.prototype.set=se;function ce(){this.__data__=[],this.size=0}function U(t,e){for(var r=t.length;r--;)if(Bt(t[r][0],e))return r;return-1}var oe=Array.prototype,he=oe.splice;function ue(t){var e=this.__data__,r=U(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():he.call(e,r,1),--this.size,!0}function fe(t){var e=this.__data__,r=U(e,t);return r<0?void 0:e[r][1]}function le(t){return U(this.__data__,t)>-1}function de(t,e){var r=this.__data__,n=U(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function z(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}z.prototype.clear=ce;z.prototype.delete=ue;z.prototype.get=fe;z.prototype.has=le;z.prototype.set=de;var pe=ut(J,"Map");function ye(){this.size=0,this.__data__={hash:new b,map:new(pe||z),string:new b}}function ge(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function G(t,e){var r=t.__data__;return ge(e)?r[typeof e=="string"?"string":"hash"]:r.map}function _e(t){var e=G(this,t).delete(t);return this.size-=e?1:0,e}function be(t){return G(this,t).get(t)}function me(t){return G(this,t).has(t)}function we(t,e){var r=G(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function m(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}m.prototype.clear=ye;m.prototype.delete=_e;m.prototype.get=be;m.prototype.has=me;m.prototype.set=we;var Se="Expected a function";function X(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw new TypeError(Se);var r=function(){var n=arguments,a=e?e.apply(this,n):n[0],i=r.cache;if(i.has(a))return i.get(a);var d=t.apply(this,n);return r.cache=i.set(a,d)||i,d};return r.cache=new(X.Cache||m),r}X.Cache=m;var Te=500;function je(t){var e=X(t,function(n){return r.size===Te&&r.clear(),n}),r=e.cache;return e}var Oe=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ve=/\\(\\)?/g,Ce=je(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(Oe,function(r,n,a,i){e.push(a?i.replace(ve,"$1"):n||r)}),e});function ze(t){return t==null?"":ot(t)}function $e(t,e){return W(t)?t:Wt(t,e)?[t]:Ce(ze(t))}function ke(t){if(typeof t=="string"||V(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Pe(t,e){e=$e(e,t);for(var r=0,n=e.length;t!=null&&r<n;)t=t[ke(e[r++])];return r&&r==n?t:void 0}function Ie(t,e,r){var n=t==null?void 0:Pe(t,e);return n===void 0?r:n}const ft=Symbol("detach"),Z=Symbol("chunkable");function Ee(){return Reflect.metadata(ft,!0)}function xe(t){return Reflect.metadata(Z,t)}function Me(t,e){return!!Reflect.getMetadata(ft,t,e)}function De(t,e){return!!Reflect.getMetadata(Z,t,e)}function Ae(t,e){return Reflect.getMetadata(Z,t,e)}const Re=t=>ct(t)&&!!Ie(t,"speckle_type");var s,I,E,N,B,lt;class Fe{constructor(e,r=1e3,n=g.md5){p(this,s);l(this,"chunkSize");l(this,"detachLineage");l(this,"lineage");l(this,"familyTree");l(this,"closureTable");l(this,"transport");l(this,"uniqueId");l(this,"hashingFunction");this.chunkSize=r,this.detachLineage=[!0],this.lineage=[],this.familyTree={},this.closureTable={},this.transport=e,this.uniqueId=0,this.hashingFunction=n||g.md5}async write(e){return await h(this,s,I).call(this,e,!0)}dispose(){this.detachLineage=[],this.lineage=[],this.familyTree={},this.closureTable={},this.transport=null}}s=new WeakSet,I=async function(e,r){const n=`${this.uniqueId++}-obj`;this.lineage.push(n);const a={speckle_type:e.speckle_type||"Base"};for(const c in e){const u=e[c];if(u===void 0||c==="id"||c.startsWith("_"))continue;if(u===null||typeof u!="object"){a[c]=u;continue}const $=c.startsWith("@")||Me(e,c),Q=Array.isArray(u),S=Q?De(e,c)||c.match(/^@\((\d*)\)/):!1;if(Q&&S&&u.length!==0&&typeof u[0]!="object"){let T=this.chunkSize;typeof S=="boolean"?T=Ae(e,c):T=S[1]!==""?parseInt(S[1]):this.chunkSize;const L=[];let k=new at,H=0;for(const dt of u)H===T&&(L.push(await h(this,s,B).call(this,k)),k=new at,H=0),k.data.push(dt),H++;k.data.length!==0&&L.push(await h(this,s,B).call(this,k)),typeof S=="boolean"?a[c]=L:a[c.replace(S[0],"")]=L;continue}if(u.speckle_type){const T=await h(this,s,E).call(this,{value:u,isDetached:$});a[c]=$?h(this,s,N).call(this,T.id):T;continue}a[c]=await h(this,s,E).call(this,{value:u,isDetached:$})}const i=this.detachLineage.pop(),d=this.lineage.pop();if(this.familyTree[d]){const c={};Object.entries(this.familyTree[d]).forEach(([u,$])=>{c[u]=$-this.detachLineage.length}),a.totalChildrenCount=Object.keys(c).length,a.totalChildrenCount&&(a.__closure=c)}const{hash:w,serializedObject:R,size:F}=h(this,s,lt).call(this,a);return a.id=w,(i||r)&&this.transport&&await this.transport.write(R,F,w),r&&this.transport&&await this.transport.flush(),{hash:w,traversed:a}},E=async function({value:e,isDetached:r=!1}){if(typeof e!="object")return e;if(Array.isArray(e)){const n=e;if(n.length===0)return e;if(typeof n[0]!="object")return n;if(!r)return Promise.all(e.map(async i=>await h(this,s,E).call(this,{value:i})));const a=[];for(const i of e)if(Re(i)){this.detachLineage.push(r);const{hash:d}=await h(this,s,I).call(this,i,!1);a.push(h(this,s,N).call(this,d))}else a.push(await h(this,s,E).call(this,{value:i,isDetached:r}));return a}if(!e.speckle_type)return e;if(e.speckle_type)return this.detachLineage.push(r),(await h(this,s,I).call(this,e,!1)).traversed;throw new Error(`Unsupported type '${typeof e}': ${e}.`)},N=function(e){return this.lineage.forEach(r=>{this.familyTree[r]||(this.familyTree[r]={}),(!this.familyTree[r][e]||this.familyTree[r][e]>this.detachLineage.length)&&(this.familyTree[r][e]=this.detachLineage.length)}),{referencedId:e,speckle_type:"reference"}},B=async function(e){this.detachLineage.push(!0);const{hash:r}=await h(this,s,I).call(this,e,!1);return h(this,s,N).call(this,r)},lt=function(e){const r=JSON.stringify(e),n=this.hashingFunction(r),a=r.substring(0,1)+`"id":"${n}",`+r.substring(1);return{hash:n,serializedObject:a,size:r.length}};class at{constructor(){l(this,"speckle_type");l(this,"data");this.data=[],this.speckle_type="Speckle.Core.Models.DataChunk"}}var y,M,_,j,O,v,D,A;class Le{constructor(e,r,n,a){p(this,y);p(this,M);p(this,_);p(this,j);p(this,O);p(this,v);p(this,D);p(this,A);f(this,M,(a==null?void 0:a.maxSize)||2e5),f(this,D,(a==null?void 0:a.flushRetryCount)||3),f(this,A,(a==null?void 0:a.flushTimeout)||2*g.TIME_MS.minute),f(this,_,0),f(this,j,e),f(this,O,r),f(this,v,n),f(this,y,[])}async write(e,r,n){o(this,y).push([n,e]),f(this,_,o(this,_)+r),!(o(this,_)<o(this,M))&&await this.flush()}async flush(){if(o(this,y).length===0)return;const e=await this.diff(),r=new FormData,n="["+e.join(",")+"]";r.append("object-batch",new Blob([n],{type:"application/json"}));const a=new URL(`/objects/${o(this,O)}`,o(this,j)),i=await g.retry(async()=>await Promise.race([fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o(this,v)}`},body:r}),g.timeoutAt(o(this,A),"Object sender flush timed out")]),o(this,D),d=>d*g.TIME_MS.second);if(i.status!==201)throw new Error(`Unexpected error when sending data. Expected status 200, got ${i.status}`);f(this,y,[]),f(this,_,0)}async diff(){const e=o(this,y).map(([i])=>i),r=new URL(`/api/diff/${o(this,O)}`,o(this,j)),n=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o(this,v)}`,"Content-Type":"application/json"},body:JSON.stringify({objects:JSON.stringify(e)})});if(!n.ok){const i=await n.json();throw new Error(`Unexpected error when sending data. Received ${i.error.message}`)}const a=await n.json();return o(this,y).filter(([i])=>!a[i]).map(([,i])=>i)}dispose(){f(this,y,[])}}y=new WeakMap,M=new WeakMap,_=new WeakMap,j=new WeakMap,O=new WeakMap,v=new WeakMap,D=new WeakMap,A=new WeakMap;class Ne{constructor(e){l(this,"speckle_type");if(this.speckle_type=this.constructor.name,e)for(const r in e)this[r]=e[r]}}const Ue=async(t,{serverUrl:e="https://app.speckle.systems",projectId:r,token:n,logger:a=console,options:i=void 0})=>{const d=performance.now();a==null||a.log("Starting to send");const w=new Le(e,r,n,i==null?void 0:i.transport),R=new Fe(w,i==null?void 0:i.chunkSize,i==null?void 0:i.hashingFunction);let F;try{F=await R.write(t)}finally{w.dispose(),R.dispose()}const c=performance.now();return a.log(`Finished sending in ${(c-d)/g.TIME_MS.second}s.`),F};exports.Base=Ne;exports.Chunkable=xe;exports.Detach=Ee;exports.send=Ue; //# sourceMappingURL=objectsender.cjs.map