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 Q=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 f=(t,e,r)=>yt(t,typeof e!="symbol"?e+"":e,r),K=(t,e,r)=>e.has(t)||Q("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)?Q("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),l=(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,$t=1/0,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==-$t?"-0":e}function ht(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var kt="[object AsyncFunction]",Pt="[object Function]",It="[object GeneratorFunction]",Et="[object Proxy]";function xt(t){if(!ht(t))return!1;var e=st(t);return e==Pt||e==It||e==kt||e==Et}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 Mt(t){return!!nt&&nt in t}var Dt=Function.prototype,At=Dt.toString;function Ft(t){if(t!=null){try{return At.call(t)}catch{}try{return t+""}catch{}}return""}var Rt=/[\\^$.*+?()[\]{}|]/g,Nt=/^\[object .+?Constructor\]$/,Lt=Function.prototype,Ut=Object.prototype,Gt=Lt.toString,Ht=Ut.hasOwnProperty,Kt=RegExp("^"+Gt.call(Ht).replace(Rt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function qt(t){if(!ht(t)||Mt(t))return!1;var e=xt(t)?Kt:Nt;return e.test(Ft(t))}function Bt(t,e){return t==null?void 0:t[e]}function ut(t,e){var r=Bt(t,e);return qt(r)?r:void 0}function Jt(t,e){return t===e||t!==t&&e!==e}var Vt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Wt=/^\w*$/;function Xt(t,e){if(W(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||V(t)?!0:Wt.test(t)||!Vt.test(t)||e!=null&&t in Object(e)}var x=ut(Object,"create");function Yt(){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__",te=Object.prototype,ee=te.hasOwnProperty;function re(t){var e=this.__data__;if(x){var r=e[t];return r===Qt?void 0:r}return ee.call(e,t)?e[t]:void 0}var ne=Object.prototype,ae=ne.hasOwnProperty;function ie(t){var e=this.__data__;return x?e[t]!==void 0:ae.call(e,t)}var se="__lodash_hash_undefined__";function ce(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=x&&e===void 0?se: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=Yt;b.prototype.delete=Zt;b.prototype.get=re;b.prototype.has=ie;b.prototype.set=ce;function oe(){this.__data__=[],this.size=0}function U(t,e){for(var r=t.length;r--;)if(Jt(t[r][0],e))return r;return-1}var he=Array.prototype,ue=he.splice;function le(t){var e=this.__data__,r=U(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():ue.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 de(t){return U(this.__data__,t)>-1}function pe(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=oe;z.prototype.delete=le;z.prototype.get=fe;z.prototype.has=de;z.prototype.set=pe;var ye=ut(J,"Map");function ge(){this.size=0,this.__data__={hash:new b,map:new(ye||z),string:new b}}function _e(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 _e(e)?r[typeof e=="string"?"string":"hash"]:r.map}function be(t){var e=G(this,t).delete(t);return this.size-=e?1:0,e}function me(t){return G(this,t).get(t)}function we(t){return G(this,t).has(t)}function Se(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=ge;m.prototype.delete=be;m.prototype.get=me;m.prototype.has=we;m.prototype.set=Se;var Te="Expected a function";function X(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw new TypeError(Te);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 je=500;function Oe(t){var e=X(t,function(n){return r.size===je&&r.clear(),n}),r=e.cache;return e}var ve=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ce=/\\(\\)?/g,ze=Oe(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(ve,function(r,n,a,i){e.push(a?i.replace(Ce,"$1"):n||r)}),e});function $e(t){return t==null?"":ot(t)}function ke(t,e){return W(t)?t:Xt(t,e)?[t]:ze($e(t))}var Pe=1/0;function Ie(t){if(typeof t=="string"||V(t))return t;var e=t+"";return e=="0"&&1/t==-Pe?"-0":e}function Ee(t,e){e=ke(e,t);for(var r=0,n=e.length;t!=null&&r<n;)t=t[Ie(e[r++])];return r&&r==n?t:void 0}function xe(t,e,r){var n=t==null?void 0:Ee(t,e);return n===void 0?r:n}const lt=Symbol("detach"),Y=Symbol("chunkable");function Me(){return Reflect.metadata(lt,!0)}function De(t){return Reflect.metadata(Y,t)}function Ae(t,e){return!!Reflect.getMetadata(lt,t,e)}function Fe(t,e){return!!Reflect.getMetadata(Y,t,e)}function Re(t,e){return Reflect.getMetadata(Y,t,e)}const Ne=t=>ct(t)&&!!xe(t,"speckle_type");var s,I,E,L,B,ft;class Le{constructor(e,r=1e3,n=g.md5){p(this,s);f(this,"chunkSize");f(this,"detachLineage");f(this,"lineage");f(this,"familyTree");f(this,"closureTable");f(this,"transport");f(this,"uniqueId");f(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("@")||Ae(e,c),Z=Array.isArray(u),S=Z?Fe(e,c)||c.match(/^@\((\d*)\)/):!1;if(Z&&S&&u.length!==0&&typeof u[0]!="object"){let T=this.chunkSize;typeof S=="boolean"?T=Re(e,c):T=S[1]!==""?parseInt(S[1]):this.chunkSize;const N=[];let k=new at,H=0;for(const dt of u)H===T&&(N.push(await h(this,s,B).call(this,k)),k=new at,H=0),k.data.push(dt),H++;k.data.length!==0&&N.push(await h(this,s,B).call(this,k)),typeof S=="boolean"?a[c]=N:a[c.replace(S[0],"")]=N;continue}if(u.speckle_type){const T=await h(this,s,E).call(this,{value:u,isDetached:$});a[c]=$?h(this,s,L).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:F,size:R}=h(this,s,ft).call(this,a);return a.id=w,(i||r)&&this.transport&&await this.transport.write(F,R,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(Ne(i)){this.detachLineage.push(r);const{hash:d}=await h(this,s,I).call(this,i,!1);a.push(h(this,s,L).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}.`)},L=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,L).call(this,r)},ft=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(){f(this,"speckle_type");f(this,"data");this.data=[],this.speckle_type="Speckle.Core.Models.DataChunk"}}var y,M,_,j,O,v,D,A;class Ue{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);l(this,M,(a==null?void 0:a.maxSize)||2e5),l(this,D,(a==null?void 0:a.flushRetryCount)||3),l(this,A,(a==null?void 0:a.flushTimeout)||2*g.TIME_MS.minute),l(this,_,0),l(this,j,e),l(this,O,r),l(this,v,n),l(this,y,[])}async write(e,r,n){o(this,y).push([n,e]),l(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}`);l(this,y,[]),l(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(){l(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 Ge{constructor(e){f(this,"speckle_type");if(this.speckle_type=this.constructor.name,e)for(const r in e)this[r]=e[r]}}const He=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 Ue(e,r,n,i==null?void 0:i.transport),F=new Le(w,i==null?void 0:i.chunkSize,i==null?void 0:i.hashingFunction);let R;try{R=await F.write(t)}finally{w.dispose(),F.dispose()}const c=performance.now();return a.log(`Finished sending in ${(c-d)/g.TIME_MS.second}s.`),R};exports.Base=Ge;exports.Chunkable=De;exports.Detach=Me;exports.send=He; //# sourceMappingURL=objectsender.cjs.map