@miso.ai/doggoganger 0.9.0-beta.14 → 0.9.0-beta.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/umd/doggoganger-browser.min.js +1 -1
- package/package.json +1 -1
- package/src/data/lorem.js +1 -9
- package/src/data/utils.js +8 -0
- package/src/index.js +1 -1
- package/src/middleware/error.js +29 -0
- package/src/middleware/index.js +2 -0
- package/src/middleware/latency.js +39 -0
- package/src/route/index.js +5 -1
- package/src/route/products.js +9 -0
- package/src/utils.js +17 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(t="undefined"!=typeof globalThis?globalThis:t||self).doggoganger=n()}(this,(function(){"use strict";function t(t,n){return null!=n&&n>t?t+Math.floor(Math.random()*(n-t)):t}function n(){return Math.random().toString(36).substring(2,10)}function e(t){return`https://picsum.photos/seed/${Math.floor(1e3*Math.random())}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}function r(t,n){return void 0!==n?Math.ceil(t*n):t}var o=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","curabitur","vel","hendrerit","libero","eleifend","blandit","nunc","ornare","odio","ut","orci","gravida","imperdiet","nullam","purus","lacinia","a","pretium","quis","congue","praesent","sagittis","laoreet","auctor","mauris","non","velit","eros","dictum","proin","accumsan","sapien","nec","massa","volutpat","venenatis","sed","eu","molestie","lacus","quisque","porttitor","ligula","dui","mollis","tempus","at","magna","vestibulum","turpis","ac","diam","tincidunt","id","condimentum","enim","sodales","in","hac","habitasse","platea","dictumst","aenean","neque","fusce","augue","leo","eget","semper","mattis","tortor","scelerisque","nulla","interdum","tellus","malesuada","rhoncus","porta","sem","aliquet","et","nam","suspendisse","potenti","vivamus","luctus","fringilla","erat","donec","justo","vehicula","ultricies","varius","ante","primis","faucibus","ultrices","posuere","cubilia","curae","etiam","cursus","aliquam","quam","dapibus","nisl","feugiat","egestas","class","aptent","taciti","sociosqu","ad","litora","torquent","per","conubia","nostra","inceptos","himenaeos","phasellus","nibh","pulvinar","vitae","urna","iaculis","lobortis","nisi","viverra","arcu","morbi","pellentesque","metus","commodo","ut","facilisis","felis","tristique","ullamcorper","placerat","aenean","convallis","sollicitudin","integer","rutrum","duis","est","etiam","bibendum","donec","pharetra","vulputate","maecenas","mi","fermentum","consequat","suscipit","aliquam","habitant","senectus","netus","fames","quisque","euismod","curabitur","lectus","elementum","tempor","risus","cras"];function s({decorates:n=[],output:e="string",size:r,min:s,max:i,...u}={}){let c=function(n=[5,10]){const e="number"==typeof n?n:t(...n);return function*(t){let n=0;for(let r of t){if(n++>=e)break;yield r}}}(r||[s,i])(function*({words:t=o,fixedStarts:n=0}={}){const e=t.length;for(let r=0;;r++)yield t[n>r?r:Math.floor(Math.random()*e)]}(u));for(const t of n)c=a(t)(c);return a(e)(c)}const i={string:function({separator:t=" "}={}){return n=>[...n].join(t)},array:function(){return t=>[...t]},title:function({}={}){return function*(t){for(let n of t)yield u(n)}},description:function({wordsPerSentence:t={avg:24,std:5,min:1},punctuation:n="."}={}){return function*(e){let r,o=0;for(let s of e)r&&(yield r),r=s,0===o&&(r=u(r),o=c(t)),0==--o&&(r+=n);r&&(r.endsWith(n)||(r+=n),yield r)}},multiline:function({wordsPerLine:t={avg:10,std:3,min:1}}={}){return n=>{let e=c(t),r="";for(let o of n)r&&(0==e--?(r+="\n",e=c(t)):r+=" "),r+=o;return r}}};function a(t){switch(typeof t){case"string":return i[t]();case"function":return t;case"object":if(Array.isArray(t)){const[n,e={}]=t;return i[n](e)}}throw Error("Unrecognized decorator/output form: "+t)}function u(t){return t[0].toUpperCase()+t.substring(1)}function c(t){if("number"==typeof t)return Math.round(n);let{avg:n,std:e,min:r,max:o}=t;void 0===e&&(e=n/4);let s=(l()+l()+l())*e+n;return void 0!==r&&(s=Math.max(r,s)),void 0!==o&&(s=Math.min(o,s)),Math.round(s)}function l(){return 2*Math.random()-1}const f="// module\nimport { a, b } from './module';\nimport * as module from './module';\nimport module from './module';\nexport default module;\nexport const a = 0;\nexport * from './module';\nexport * as module from './module';\n\n// variables\nlet a = 10;\nconst b = 20;\n\n// function declaration\nfunction sum(x, y) {\n return x + y;\n}\n\n// generator function\nfunction* iterator() {\n yield 0;\n yield 1;\n}\n\n// arrow function\nconst multiply = (x, y) => x * y;\n\n// class\nclass Person {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n\n greet() {\n console.log('Hello, my name is Miso.');\n }\n}\n\n// primitive\nconst str = 'Hello, world!';\nconst num = 10.99;\n\n// object\nconst person = new Person('John', 30);\nperson.greet();\n\n// object literal\nconst object = {\n name: 'John',\n [x]: 10,\n ...props,\n};\n\n// array literal\nconst arr = [1, 2, 3, 4, 5, ...props];\n\n// regexp literal\nconst regexp = /\\w+/g;\n\n// operators\nconst sum = a + b;\nconst product = a * b;\nconst negation = -a;\nconst max = a > b ? a : b;\n\n// flow control\nlet i = 9;\nfor (const n of arr) {\n if (n > i) {\n console.log(n);\n }\n i++;\n}\n\n// async/await\n(async () => {\n const result = await asyncFunction();\n})();\n\n// try/catch\ntry {\n} catch (e) {\n}\n\n// destructuring\nconst { name, age, ...rest } = person;\nconst [ x, y, ...rest ] = arr;\n\n// template literals\nconsole.log(`The sum of ${a} and ${b} is ${sum(a, b)}.`);";var d=Object.freeze({__proto__:null,javascript:function(){return f},js:function(){return f}});function p({features:n,blocks:r=[8,12],sampling:o=1}={}){let i=[];return[i,n]=function(t=[]){const n=new Set,e=[];for(const r of t)if(r.startsWith("lang-")){let t=r.slice(5);"javascript"===t&&(t="js"),n.add(t)}else e.push(r);return[[...n],e]}(n),function(t,n){const e=[];for(const r of t)1>n&&Math.random()>=n||e.push(r());return e}([()=>m({features:n}),()=>g({features:n}),...i.map((t=>()=>h({lang:t,features:n}))),...i.length?[]:[()=>h({features:n})],()=>g({features:n}),()=>function({columns:n=[2,4],rows:e=[2,8]}){n=t(...n),e=t(...e);const r=[...$({size:1},n-1),{size:[3,8]}],o=s({size:n,output:"array"}),i=r.map((()=>"---")),a=[o,i];for(let t=0;e-1>t;t++)a.push(r.map((({size:t})=>s({size:t}))));return a.map(x).join("\n")}({features:n}),()=>function({url:t,imageSize:n=[400,250],...r}={}){return t=t||e(n),`![${function({size:t=[1,3],content:n}={}){return n||s({size:t})}(r)}](${t})`}(),()=>g({features:n}),()=>"*-_".charAt(t(0,2)).repeat(t(3,6)),()=>m({features:n}),()=>g({features:n}),()=>w({features:n}),()=>g({features:n})],o).join("\n\n")}function m({level:n=[1,6],size:e=[1,8],content:r}){const o=r||s({size:e});return`${"#".repeat(t(...n))} ${o}`}function h({lang:n,content:e,size:r,fenceChar:o="`"}){return"random"===o&&(o="`~".charAt(t(0,1))),e=e||function({lang:t,size:n=[10,30]}){return t&&d[t]?d[t]():s({output:"multiline",size:n})}({lang:n,size:r}),`${o.repeat(3)}${n||""}\n${e}\n${o.repeat(3)}`}function g({size:t=[20,50]}){return s({size:t,decorates:["description",z()]})}const _=["ordered","bullet","task"];function w({features:n,type:e="random",count:r=[1,8],size:o=[5,15]}){r="number"==typeof r?r:t(...r);const s="random"===e?_[Math.floor(3*Math.random())]:e,i=[];for(;r>0;){const a=t(1,r);let u=g({features:n,size:o});a>1&&(u+="\n"+w({features:n,type:e,count:a-1,size:o})),i.push(M(s,u)),r-=a}return i.join("\n")}const y={"code-span":()=>["`","`"],"emphasis-1":()=>$(b(1),2),"emphasis-2":()=>$(b(2),2),"emphasis-3":()=>$(b(3),2),strikethrough:()=>["~","~"],link:({url:t="https://miso.ai"}={})=>["[",`](${t})`]};function b(n=[1,3]){return n="number"==typeof n?n:t(...n),"_*".charAt(t(0,1)).repeat(n)}const q=Object.keys(y),v=new Set(q);function z({features:n=q,size:e=[1,3],rest:r=[0,8]}={}){n=n.filter((t=>v.has(t)));const o=function(t){for(let n=t.length-1;n>0;n--){const e=Math.floor(Math.random()*(n+1));[t[n],t[e]]=[t[e],t[n]]}return t}([...n]);let s=o.length-1;const i=()=>"number"==typeof r?r:t(...r);return function*(r){let a,u,c=i();for(const l of r)if(u&&(yield u),0===c)if(a)u=`${l}${a}`,a=void 0,c=i();else{const[r,i]=y[0>s?n[t(0,n.length-1)]:o[s--]]();u=`${r}${l}`,a=i,c="number"==typeof e?e:t(...e)}else u=l,c--;u&&(yield void 0!==a?`${u}${a}`:u)}}function M(t,n){const[e,r]=n.split("\n",2),o=`${function(t,n="random"){switch(t){case"ordered":return"1.";case"bullet":return"-";case"task":return`- [${("random"===n?.5>Math.random():n)?"x":" "}]`;default:throw Error("unknown list item type: "+t)}}(t)} ${e}`;return r?o+"\n"+function(t,n){return n.split("\n").map((n=>" ".repeat(t)+n)).join("\n")}("ordered"===t?3:2,r):o}function x(t){return`| ${t.join(" | ")} |`}function $(t,n){const e=[];for(let r=0;n>r;r++)e.push("function"==typeof t?t():t);return e}function j({size:t=300}={}){return e(t)}function S({size:t=[1,3]}={}){return s({size:t,decorates:["title"],output:"array"})}function k({size:t=[1,4]}={}){return s({size:t,output:"array"})}function O({size:t=[2,6]}={}){return s({size:t,decorates:["title"]})}function A({size:t=[10,20],...n}={}){return s({size:t,decorates:[Object.keys(n).length?["description",n]:"description"]})}function T(){return Math.floor(1e4*Math.random())/100}function*C({rows:t,...n}={}){for(let e=0;t>e;e++)yield F({...n,index:e})}function F({}={}){const e=n(),r=function(n,e){const r=t(...e),o=[];for(let t=0;r>t;t++)o.push(n());return o}(T,[1,2]);return r.sort(),{product_id:e,authors:S(),categories:[],tags:k(),title:O(),description:A(),cover_image:j(),url:"/products/"+e,sale_price:r[0],original_price:r[r.length-1],rating:Math.floor(500*Math.random())/100+1,availability:Math.random()>.3?"IN_STOCK":"OUT_OF_STOCK"}}function*D({rows:t,...n}={}){for(let e=0;t>e;e++)yield L({...n,index:e})}function L({}={}){const t=n();return{product_id:t,authors:S(),categories:[],tags:k(),title:O({size:[4,10]}),snippet:A({size:[20,40]}),cover_image:j(),url:"/products/"+t}}function*P({rows:t,...n}={}){for(let e=0;t>e;e++)yield U({...n,index:e})}function U({}={}){return A({size:[4,8],punctuation:"?"})}function W({question:t,parent_question_id:n,timestamp:e=Date.now()},{answerFormat:o="markdown",answerSampling:i,answerLanguages:a=[]}={}){const u="10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(t^16*Math.random()>>t/4).toString(16))),c=function(t){const n=new Date(t).toISOString();return n.endsWith("Z")?n.slice(0,-1):n}(e),l=void 0!==i?Math.max(0,Math.min(1,i)):void 0,f=function({format:t,sampling:n,features:e}){return"markdown"===t?p({sampling:n,features:e}):s({min:r(50,n),max:r(50,n),decorates:["description"]})}({format:o,sampling:l,features:a.length?a.map((t=>"lang-"+t)):void 0}),d=[...D({rows:E(6,8,l)})];return{question:t,question_id:u,...n&&{parent_question_id:n},datetime:c,answer:f,sources:[...D({rows:E(4,6,l)})],related_resources:d,followup_questions:[...P({rows:E(3,6)})]}}function E(n,e,o){return t(r(n,o),r(e,o))}const H=[{name:"fetch",duration:1.5,text:"Checking the question and fetching results... "},{name:"verify",duration:1.5,text:"Verifying results... "},{name:"generate",duration:1.5,text:"Generating answer... "}];class I{constructor(t={}){this._options=t,this._answers=new Map}questions(t,n={}){return new J(t,{...this._options,...n})}}class J{constructor({question:t,parent_question_id:n},{answerFormat:e,answerSampling:r,answerLanguages:o,...s}={}){this._options=Object.freeze(s);const i=this.timestamp=Date.now();this._data=W({question:t,parent_question_id:n,timestamp:i},{answerFormat:e,answerSampling:r,answerLanguages:o})}get question_id(){return this._data.question_id}get(){const t=(Date.now()-this.timestamp)*(this._options.speedRate||1)/1e3,[n,e,r]=this._answer(t),o=this._sources(t,r),s=this._related_resources(t,r),i=this._followup_questions(t,r),{question_id:a,question:u,datetime:c,parent_question_id:l}=this._data;return{answer:e,answer_stage:n,datetime:c,finished:r,parent_question_id:l,question:u,question_id:a,sources:o,related_resources:s,followup_questions:i}}_answer(t){for(const n of H)if(0>(t-=n.duration))return[n.name,n.text,!1];const{answer:n}=this._data,e=Math.floor(100*t),r=e>=n.length;return["result",r?n:n.slice(0,e),r]}_sources(t,n){const{sources:e}=this._data;if(n)return e;const{length:r}=e;return e.slice(0,Math.floor(r*t/3))}_related_resources(t,n){const{related_resources:e}=this._data;if(n)return e;const{length:r}=e;return e.slice(0,Math.floor(r*t/3))}_followup_questions(t,n){const{followup_questions:e}=this._data;if(n||!e)return e;const{length:r}=e;return e.slice(0,Math.floor(r*t/3))}}class K{constructor(t){this._options=t}search({rows:t=5}){return{products:[...C({rows:t})]}}}class G{constructor(t){this._options=t}user_to_products({rows:t=5}){return{products:[...C({rows:t})]}}product_to_products({rows:t=5}){return{products:[...C({rows:t})]}}}class N{constructor(t){this._options=t}upload(t){return[]}}class R{constructor(t){this._options=t}upload(t){return[]}ids(){const t=[];for(let n=0;5e3>n;n++)t.push(V(n));return{ids:t}}}function V(t){return`${10>t?"p_000":100>t?"p_00":1e3>t?"p_0":"p_"}${t}`}class Z{constructor(t){this.ask=new I(t),this.search=new K(t),this.recommendation=new G(t),this.interactions=new N(t),this.products=new R(t)}}return{buildApi:(...t)=>new Z(...t)}}));
|
|
1
|
+
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(t="undefined"!=typeof globalThis?globalThis:t||self).doggoganger=n()}(this,(function(){"use strict";function t(t,n){return null!=n&&n>t?t+Math.floor(Math.random()*(n-t)):t}function n(){return Math.random().toString(36).substring(2,10)}function e(t){return`https://picsum.photos/seed/${Math.floor(1e3*Math.random())}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}function r(t,n){return void 0!==n?Math.ceil(t*n):t}function o(){return 2*Math.random()-1}var s=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","curabitur","vel","hendrerit","libero","eleifend","blandit","nunc","ornare","odio","ut","orci","gravida","imperdiet","nullam","purus","lacinia","a","pretium","quis","congue","praesent","sagittis","laoreet","auctor","mauris","non","velit","eros","dictum","proin","accumsan","sapien","nec","massa","volutpat","venenatis","sed","eu","molestie","lacus","quisque","porttitor","ligula","dui","mollis","tempus","at","magna","vestibulum","turpis","ac","diam","tincidunt","id","condimentum","enim","sodales","in","hac","habitasse","platea","dictumst","aenean","neque","fusce","augue","leo","eget","semper","mattis","tortor","scelerisque","nulla","interdum","tellus","malesuada","rhoncus","porta","sem","aliquet","et","nam","suspendisse","potenti","vivamus","luctus","fringilla","erat","donec","justo","vehicula","ultricies","varius","ante","primis","faucibus","ultrices","posuere","cubilia","curae","etiam","cursus","aliquam","quam","dapibus","nisl","feugiat","egestas","class","aptent","taciti","sociosqu","ad","litora","torquent","per","conubia","nostra","inceptos","himenaeos","phasellus","nibh","pulvinar","vitae","urna","iaculis","lobortis","nisi","viverra","arcu","morbi","pellentesque","metus","commodo","ut","facilisis","felis","tristique","ullamcorper","placerat","aenean","convallis","sollicitudin","integer","rutrum","duis","est","etiam","bibendum","donec","pharetra","vulputate","maecenas","mi","fermentum","consequat","suscipit","aliquam","habitant","senectus","netus","fames","quisque","euismod","curabitur","lectus","elementum","tempor","risus","cras"];function i({decorates:n=[],output:e="string",size:r,min:o,max:i,...a}={}){let c=function(n=[5,10]){const e="number"==typeof n?n:t(...n);return function*(t){let n=0;for(let r of t){if(n++>=e)break;yield r}}}(r||[o,i])(function*({words:t=s,fixedStarts:n=0}={}){const e=t.length;for(let r=0;;r++)yield t[n>r?r:Math.floor(Math.random()*e)]}(a));for(const t of n)c=u(t)(c);return u(e)(c)}const a={string:function({separator:t=" "}={}){return n=>[...n].join(t)},array:function(){return t=>[...t]},title:function({}={}){return function*(t){for(let n of t)yield c(n)}},description:function({wordsPerSentence:t={avg:24,std:5,min:1},punctuation:n="."}={}){return function*(e){let r,o=0;for(let s of e)r&&(yield r),r=s,0===o&&(r=c(r),o=l(t)),0==--o&&(r+=n);r&&(r.endsWith(n)||(r+=n),yield r)}},multiline:function({wordsPerLine:t={avg:10,std:3,min:1}}={}){return n=>{let e=l(t),r="";for(let o of n)r&&(0==e--?(r+="\n",e=l(t)):r+=" "),r+=o;return r}}};function u(t){switch(typeof t){case"string":return a[t]();case"function":return t;case"object":if(Array.isArray(t)){const[n,e={}]=t;return a[n](e)}}throw Error("Unrecognized decorator/output form: "+t)}function c(t){return t[0].toUpperCase()+t.substring(1)}function l(t){if("number"==typeof t)return Math.round(n);let{avg:n,std:e,min:r,max:s}=t;void 0===e&&(e=n/4);let i=(o()+o()+o())*e+n;return void 0!==r&&(i=Math.max(r,i)),void 0!==s&&(i=Math.min(s,i)),Math.round(i)}const f="// module\nimport { a, b } from './module';\nimport * as module from './module';\nimport module from './module';\nexport default module;\nexport const a = 0;\nexport * from './module';\nexport * as module from './module';\n\n// variables\nlet a = 10;\nconst b = 20;\n\n// function declaration\nfunction sum(x, y) {\n return x + y;\n}\n\n// generator function\nfunction* iterator() {\n yield 0;\n yield 1;\n}\n\n// arrow function\nconst multiply = (x, y) => x * y;\n\n// class\nclass Person {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n\n greet() {\n console.log('Hello, my name is Miso.');\n }\n}\n\n// primitive\nconst str = 'Hello, world!';\nconst num = 10.99;\n\n// object\nconst person = new Person('John', 30);\nperson.greet();\n\n// object literal\nconst object = {\n name: 'John',\n [x]: 10,\n ...props,\n};\n\n// array literal\nconst arr = [1, 2, 3, 4, 5, ...props];\n\n// regexp literal\nconst regexp = /\\w+/g;\n\n// operators\nconst sum = a + b;\nconst product = a * b;\nconst negation = -a;\nconst max = a > b ? a : b;\n\n// flow control\nlet i = 9;\nfor (const n of arr) {\n if (n > i) {\n console.log(n);\n }\n i++;\n}\n\n// async/await\n(async () => {\n const result = await asyncFunction();\n})();\n\n// try/catch\ntry {\n} catch (e) {\n}\n\n// destructuring\nconst { name, age, ...rest } = person;\nconst [ x, y, ...rest ] = arr;\n\n// template literals\nconsole.log(`The sum of ${a} and ${b} is ${sum(a, b)}.`);";var d=Object.freeze({__proto__:null,javascript:function(){return f},js:function(){return f}});function p({features:n,blocks:r=[8,12],sampling:o=1}={}){let s=[];return[s,n]=function(t=[]){const n=new Set,e=[];for(const r of t)if(r.startsWith("lang-")){let t=r.slice(5);"javascript"===t&&(t="js"),n.add(t)}else e.push(r);return[[...n],e]}(n),function(t,n){const e=[];for(const r of t)1>n&&Math.random()>=n||e.push(r());return e}([()=>m({features:n}),()=>g({features:n}),...s.map((t=>()=>h({lang:t,features:n}))),...s.length?[]:[()=>h({features:n})],()=>g({features:n}),()=>function({columns:n=[2,4],rows:e=[2,8]}){n=t(...n),e=t(...e);const r=[...$({size:1},n-1),{size:[3,8]}],o=i({size:n,output:"array"}),s=r.map((()=>"---")),a=[o,s];for(let t=0;e-1>t;t++)a.push(r.map((({size:t})=>i({size:t}))));return a.map(x).join("\n")}({features:n}),()=>function({url:t,imageSize:n=[400,250],...r}={}){return t=t||e(n),`![${function({size:t=[1,3],content:n}={}){return n||i({size:t})}(r)}](${t})`}(),()=>g({features:n}),()=>"*-_".charAt(t(0,2)).repeat(t(3,6)),()=>m({features:n}),()=>g({features:n}),()=>w({features:n}),()=>g({features:n})],o).join("\n\n")}function m({level:n=[1,6],size:e=[1,8],content:r}){const o=r||i({size:e});return`${"#".repeat(t(...n))} ${o}`}function h({lang:n,content:e,size:r,fenceChar:o="`"}){return"random"===o&&(o="`~".charAt(t(0,1))),e=e||function({lang:t,size:n=[10,30]}){return t&&d[t]?d[t]():i({output:"multiline",size:n})}({lang:n,size:r}),`${o.repeat(3)}${n||""}\n${e}\n${o.repeat(3)}`}function g({size:t=[20,50]}){return i({size:t,decorates:["description",z()]})}const _=["ordered","bullet","task"];function w({features:n,type:e="random",count:r=[1,8],size:o=[5,15]}){r="number"==typeof r?r:t(...r);const s="random"===e?_[Math.floor(3*Math.random())]:e,i=[];for(;r>0;){const a=t(1,r);let u=g({features:n,size:o});a>1&&(u+="\n"+w({features:n,type:e,count:a-1,size:o})),i.push(M(s,u)),r-=a}return i.join("\n")}const y={"code-span":()=>["`","`"],"emphasis-1":()=>$(b(1),2),"emphasis-2":()=>$(b(2),2),"emphasis-3":()=>$(b(3),2),strikethrough:()=>["~","~"],link:({url:t="https://miso.ai"}={})=>["[",`](${t})`]};function b(n=[1,3]){return n="number"==typeof n?n:t(...n),"_*".charAt(t(0,1)).repeat(n)}const q=Object.keys(y),v=new Set(q);function z({features:n=q,size:e=[1,3],rest:r=[0,8]}={}){n=n.filter((t=>v.has(t)));const o=function(t){for(let n=t.length-1;n>0;n--){const e=Math.floor(Math.random()*(n+1));[t[n],t[e]]=[t[e],t[n]]}return t}([...n]);let s=o.length-1;const i=()=>"number"==typeof r?r:t(...r);return function*(r){let a,u,c=i();for(const l of r)if(u&&(yield u),0===c)if(a)u=`${l}${a}`,a=void 0,c=i();else{const[r,i]=y[0>s?n[t(0,n.length-1)]:o[s--]]();u=`${r}${l}`,a=i,c="number"==typeof e?e:t(...e)}else u=l,c--;u&&(yield void 0!==a?`${u}${a}`:u)}}function M(t,n){const[e,r]=n.split("\n",2),o=`${function(t,n="random"){switch(t){case"ordered":return"1.";case"bullet":return"-";case"task":return`- [${("random"===n?.5>Math.random():n)?"x":" "}]`;default:throw Error("unknown list item type: "+t)}}(t)} ${e}`;return r?o+"\n"+function(t,n){return n.split("\n").map((n=>" ".repeat(t)+n)).join("\n")}("ordered"===t?3:2,r):o}function x(t){return`| ${t.join(" | ")} |`}function $(t,n){const e=[];for(let r=0;n>r;r++)e.push("function"==typeof t?t():t);return e}function j({size:t=300}={}){return e(t)}function S({size:t=[1,3]}={}){return i({size:t,decorates:["title"],output:"array"})}function k({size:t=[1,4]}={}){return i({size:t,output:"array"})}function O({size:t=[2,6]}={}){return i({size:t,decorates:["title"]})}function A({size:t=[10,20],...n}={}){return i({size:t,decorates:[Object.keys(n).length?["description",n]:"description"]})}function T(){return Math.floor(1e4*Math.random())/100}function*C({rows:t,...n}={}){for(let e=0;t>e;e++)yield F({...n,index:e})}function F({}={}){const e=n(),r=function(n,e){const r=t(...e),o=[];for(let t=0;r>t;t++)o.push(n());return o}(T,[1,2]);return r.sort(),{product_id:e,authors:S(),categories:[],tags:k(),title:O(),description:A(),cover_image:j(),url:"/products/"+e,sale_price:r[0],original_price:r[r.length-1],rating:Math.floor(500*Math.random())/100+1,availability:Math.random()>.3?"IN_STOCK":"OUT_OF_STOCK"}}function*D({rows:t,...n}={}){for(let e=0;t>e;e++)yield L({...n,index:e})}function L({}={}){const t=n();return{product_id:t,authors:S(),categories:[],tags:k(),title:O({size:[4,10]}),snippet:A({size:[20,40]}),cover_image:j(),url:"/products/"+t}}function*P({rows:t,...n}={}){for(let e=0;t>e;e++)yield U({...n,index:e})}function U({}={}){return A({size:[4,8],punctuation:"?"})}function W({question:t,parent_question_id:n,timestamp:e=Date.now()},{answerFormat:o="markdown",answerSampling:s,answerLanguages:a=[]}={}){const u="10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(t^16*Math.random()>>t/4).toString(16))),c=function(t){const n=new Date(t).toISOString();return n.endsWith("Z")?n.slice(0,-1):n}(e),l=void 0!==s?Math.max(0,Math.min(1,s)):void 0,f=function({format:t,sampling:n,features:e}){return"markdown"===t?p({sampling:n,features:e}):i({min:r(50,n),max:r(50,n),decorates:["description"]})}({format:o,sampling:l,features:a.length?a.map((t=>"lang-"+t)):void 0}),d=[...D({rows:E(6,8,l)})];return{question:t,question_id:u,...n&&{parent_question_id:n},datetime:c,answer:f,sources:[...D({rows:E(4,6,l)})],related_resources:d,followup_questions:[...P({rows:E(3,6)})]}}function E(n,e,o){return t(r(n,o),r(e,o))}const H=[{name:"fetch",duration:1.5,text:"Checking the question and fetching results... "},{name:"verify",duration:1.5,text:"Verifying results... "},{name:"generate",duration:1.5,text:"Generating answer... "}];class I{constructor(t={}){this._options=t,this._answers=new Map}questions(t,n={}){return new J(t,{...this._options,...n})}}class J{constructor({question:t,parent_question_id:n},{answerFormat:e,answerSampling:r,answerLanguages:o,...s}={}){this._options=Object.freeze(s);const i=this.timestamp=Date.now();this._data=W({question:t,parent_question_id:n,timestamp:i},{answerFormat:e,answerSampling:r,answerLanguages:o})}get question_id(){return this._data.question_id}get(){const t=(Date.now()-this.timestamp)*(this._options.speedRate||1)/1e3,[n,e,r]=this._answer(t),o=this._sources(t,r),s=this._related_resources(t,r),i=this._followup_questions(t,r),{question_id:a,question:u,datetime:c,parent_question_id:l}=this._data;return{answer:e,answer_stage:n,datetime:c,finished:r,parent_question_id:l,question:u,question_id:a,sources:o,related_resources:s,followup_questions:i}}_answer(t){for(const n of H)if(0>(t-=n.duration))return[n.name,n.text,!1];const{answer:n}=this._data,e=Math.floor(100*t),r=e>=n.length;return["result",r?n:n.slice(0,e),r]}_sources(t,n){const{sources:e}=this._data;if(n)return e;const{length:r}=e;return e.slice(0,Math.floor(r*t/3))}_related_resources(t,n){const{related_resources:e}=this._data;if(n)return e;const{length:r}=e;return e.slice(0,Math.floor(r*t/3))}_followup_questions(t,n){const{followup_questions:e}=this._data;if(n||!e)return e;const{length:r}=e;return e.slice(0,Math.floor(r*t/3))}}class K{constructor(t){this._options=t}search({rows:t=5}){return{products:[...C({rows:t})]}}}class G{constructor(t){this._options=t}user_to_products({rows:t=5}){return{products:[...C({rows:t})]}}product_to_products({rows:t=5}){return{products:[...C({rows:t})]}}}class N{constructor(t){this._options=t}upload(t){return[]}}class R{constructor(t){this._options=t}upload(t){return[]}ids(){const t=[];for(let n=0;5e3>n;n++)t.push(V(n));return{ids:t}}}function V(t){return`${10>t?"p_000":100>t?"p_00":1e3>t?"p_0":"p_"}${t}`}class Z{constructor(t){this.ask=new I(t),this.search=new K(t),this.recommendation=new G(t),this.interactions=new N(t),this.products=new R(t)}}return{buildApi:(...t)=>new Z(...t)}}));
|
package/package.json
CHANGED
package/src/data/lorem.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomInt } from './utils.js';
|
|
1
|
+
import { randomInt, gaussRandom } from './utils.js';
|
|
2
2
|
import DEFAULT_WORDS from './words.js';
|
|
3
3
|
|
|
4
4
|
export function lorem({ decorates = [], output = 'string', size, min, max, ...options } = {}) {
|
|
@@ -152,11 +152,3 @@ function gaussMS(args) {
|
|
|
152
152
|
}
|
|
153
153
|
return Math.round(n);
|
|
154
154
|
}
|
|
155
|
-
|
|
156
|
-
function gaussRandom() {
|
|
157
|
-
return uniformRandom() + uniformRandom() + uniformRandom();
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function uniformRandom() {
|
|
161
|
-
return Math.random() * 2 - 1;
|
|
162
|
-
}
|
package/src/data/utils.js
CHANGED
|
@@ -42,3 +42,11 @@ export function formatDatetime(timestamp) {
|
|
|
42
42
|
export function sample(size, sampling) {
|
|
43
43
|
return sampling !== undefined ? Math.ceil(size * sampling) : size;
|
|
44
44
|
}
|
|
45
|
+
|
|
46
|
+
export function gaussRandom() {
|
|
47
|
+
return uniformRandom() + uniformRandom() + uniformRandom();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function uniformRandom() {
|
|
51
|
+
return Math.random() * 2 - 1;
|
|
52
|
+
}
|
package/src/index.js
CHANGED
|
@@ -10,7 +10,7 @@ import { exclusion } from './utils.js';
|
|
|
10
10
|
export default function doggoganger({ port = 9901, serve = false, ...options } = {}) {
|
|
11
11
|
const app = new Koa();
|
|
12
12
|
const router = new Router();
|
|
13
|
-
const api = _route(new Api(options));
|
|
13
|
+
const api = _route(new Api(options), options);
|
|
14
14
|
|
|
15
15
|
router.use('/api', api.routes(), api.allowedMethods());
|
|
16
16
|
router.use('/v1', api.routes(), api.allowedMethods());
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { trimObj } from '../utils.js';
|
|
2
|
+
|
|
3
|
+
const DEFAULT_OPTIONS = {
|
|
4
|
+
rate: 0,
|
|
5
|
+
verbose: false,
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export default function error(options) {
|
|
9
|
+
const globalOptions = {
|
|
10
|
+
...DEFAULT_OPTIONS,
|
|
11
|
+
...trimObj(options),
|
|
12
|
+
};
|
|
13
|
+
return async (ctx, next) => {
|
|
14
|
+
const { rate, verbose } = {
|
|
15
|
+
...globalOptions,
|
|
16
|
+
...getOptionsFromCtx(ctx),
|
|
17
|
+
};
|
|
18
|
+
if (rate && Math.random() < rate) {
|
|
19
|
+
verbose && console.log(`Simulate error`);
|
|
20
|
+
throw new Error();
|
|
21
|
+
}
|
|
22
|
+
await next();
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function getOptionsFromCtx(ctx) {
|
|
27
|
+
const rate = Number(ctx.get('x-error-rate')) || undefined;
|
|
28
|
+
return trimObj({ rate });
|
|
29
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { delay, trimObj } from '../utils.js';
|
|
2
|
+
import { gaussRandom } from '../data/utils.js';
|
|
3
|
+
|
|
4
|
+
const DEFAULT_OPTIONS = {
|
|
5
|
+
enabled: true,
|
|
6
|
+
verbose: false,
|
|
7
|
+
min: 200,
|
|
8
|
+
max: 2000,
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export default function latency(options) {
|
|
12
|
+
const globalOptions = {
|
|
13
|
+
...DEFAULT_OPTIONS,
|
|
14
|
+
...trimObj(options),
|
|
15
|
+
};
|
|
16
|
+
return async (ctx, next) => {
|
|
17
|
+
const { enabled, min, max, verbose } = {
|
|
18
|
+
...globalOptions,
|
|
19
|
+
...getOptionsFromCtx(ctx),
|
|
20
|
+
};
|
|
21
|
+
if (enabled) {
|
|
22
|
+
const time = (min + max) / 2 + gaussRandom() * (max - min) / 6;
|
|
23
|
+
verbose && console.log(`Add latency: ${time}ms`);
|
|
24
|
+
await delay(time);
|
|
25
|
+
}
|
|
26
|
+
await next();
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function getOptionsFromCtx(ctx) {
|
|
31
|
+
const latencyStr = ctx.get('x-latency') || undefined;
|
|
32
|
+
if (latencyStr === '0' || latencyStr === 'false') {
|
|
33
|
+
return { enabled: false };
|
|
34
|
+
}
|
|
35
|
+
const value = Number(latencyStr) || undefined;
|
|
36
|
+
const min = value || Number(ctx.get('x-latency-min')) || undefined;
|
|
37
|
+
const max = value || Number(ctx.get('x-latency-max')) || undefined;
|
|
38
|
+
return trimObj({ min, max });
|
|
39
|
+
}
|
package/src/route/index.js
CHANGED
|
@@ -4,14 +4,18 @@ import recommendation from './recommendation.js';
|
|
|
4
4
|
import search from './search.js';
|
|
5
5
|
import interactions from './interactions.js';
|
|
6
6
|
import products from './products.js';
|
|
7
|
+
import { latency, error } from '../middleware/index.js';
|
|
7
8
|
|
|
8
9
|
function use(router, path, middleware) {
|
|
9
10
|
router.use(path, middleware.routes(), middleware.allowedMethods());
|
|
10
11
|
}
|
|
11
12
|
|
|
12
|
-
export default function(api) {
|
|
13
|
+
export default function(api, options) {
|
|
13
14
|
const router = new Router();
|
|
14
15
|
|
|
16
|
+
router.use(latency(options.latency));
|
|
17
|
+
//router.use(error(options.error));
|
|
18
|
+
|
|
15
19
|
use(router, '/ask', ask(api));
|
|
16
20
|
use(router, '/recommendation', recommendation(api));
|
|
17
21
|
use(router, '/search', search(api));
|
package/src/route/products.js
CHANGED
package/src/utils.js
CHANGED
|
@@ -24,3 +24,20 @@ export async function exclusion(ctx, next) {
|
|
|
24
24
|
ctx.status = 404;
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
+
|
|
28
|
+
export async function delay(time) {
|
|
29
|
+
return new Promise(resolve => setTimeout(resolve, time));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function trimObj(obj) {
|
|
33
|
+
if (typeof obj !== 'object') {
|
|
34
|
+
return obj;
|
|
35
|
+
}
|
|
36
|
+
const trimmed = {};
|
|
37
|
+
for (const k in obj) {
|
|
38
|
+
if (Object.prototype.hasOwnProperty.call(obj, k) && obj[k] !== undefined) {
|
|
39
|
+
trimmed[k] = obj[k];
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return trimmed;
|
|
43
|
+
}
|