@miso.ai/doggoganger 0.10.0-beta.1 → 0.10.0-beta.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.
- package/cli/index.js +2 -1
- package/dist/umd/doggoganger-browser.min.js +1 -1
- package/package.json +5 -4
- package/src/api.js +2 -2
- package/src/fetch.js +3 -3
- package/src/index.js +1 -0
- package/src/route/ask.js +11 -4
- package/src/route/utils.js +4 -2
- package/test/fetch.test.js +80 -0
package/cli/index.js
CHANGED
|
@@ -4,12 +4,13 @@ import { dirname, resolve, join } from 'path';
|
|
|
4
4
|
import nodemon from 'nodemon';
|
|
5
5
|
import yargs from 'yargs/yargs';
|
|
6
6
|
import { hideBin } from 'yargs/helpers';
|
|
7
|
-
import { doggoganger } from '../src/index.js';
|
|
7
|
+
import { doggoganger, version } from '../src/index.js';
|
|
8
8
|
|
|
9
9
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
10
10
|
const SRC_DIR = join(__dirname, '../src');
|
|
11
11
|
|
|
12
12
|
let { watch, ...argv } = yargs(hideBin(process.argv))
|
|
13
|
+
.version(version)
|
|
13
14
|
.option('verbose', {
|
|
14
15
|
alias: 'v',
|
|
15
16
|
describe: 'Be verbose',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).doggoganger=e()}(this,function(){"use strict";function t({seed:t=n()}={}){return new e(new r(function(t=1){if(Array.isArray(t)&&4===t.length)return[...t];const e=function(t){let e=t>>>0;return()=>{e+=2654435769;let t=e;return t=(t^t>>>16)>>>0,t=Math.imul(t,2246822507)>>>0,t=(t^t>>>13)>>>0,t=Math.imul(t,3266489909)>>>0,(t^t>>>16)>>>0}}(t);return[e(),e(),e(),e()]}(t)))}class e{constructor(t){this._engine=t}random(){return this._engine.next()/4294967296}randomInt(t,e){return null!=e&&e>t?t+Math.floor(this.random()*(e-t+1)):t}randomGauss(){return 2*(this.random()+this.random()+this.random())-3}seed(){return 4294967296*this.random()>>>0}uuid(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(t^16*this.random()>>t/4).toString(16))}shortId(){let t="";for(let e=0;8>e;e++)t+=this.randomInt(0,35).toString(36);return t}}function s(t,e){return(t<<e|t>>>32-e)>>>0}function n(){return 4294967296*Math.random()>>>0}class r{constructor(t){this._state=t}get state(){return[...this._state]}next(){const t=this._state,e=9*s(5*t[1]>>>0,7)>>>0,n=t[1]<<9>>>0;return t[2]^=t[0],t[3]^=t[1],t[1]^=t[2],t[0]^=t[3],t[2]^=n,t[3]=s(t[3],11),e}}var i=["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"];class o{constructor(t){this._prng=t._prng}words({decorates:t=[],output:e="string",size:s,min:n,max:r,...i}={}){let o=this.limit(s||[n,r])(this.base(i));for(const e of t)o=this._lookup(e)(o);return this._lookup(e)(o)}_lookup(t){switch(typeof t){case"string":return this._fns[t]();case"function":return t;case"object":if(Array.isArray(t)){const[e,s={}]=t;return this._fns[e](s)}}throw Error("Unrecognized decorator/output form: "+t)}get _fns(){return{string:t=>this.string(t),array:t=>this.array(t),title:t=>this.title(t),description:t=>this.description(t),multiline:t=>this.multiline(t)}}*base({words:t=i,fixedStarts:e=0}={}){const s=t.length;for(let n=0;;n++)yield t[e>n?n:this._prng.randomInt(0,s-1)]}string({separator:t=" "}={}){return e=>[...e].join(t)}array(){return t=>[...t]}multiline({wordsPerLine:t={avg:10,std:3,min:1}}={}){return e=>{let s=this._gaussMS(t),n="";for(let r of e)n&&(0===s--?(n+="\n",s=this._gaussMS(t)):n+=" "),n+=r;return n}}limit(t=[5,10]){const e="number"==typeof t?t:this._prng.randomInt(...t);return function*(t){let s=0;for(let n of t){if(s++>=e)break;yield n}}}title({}={}){return function*(t){for(let e of t)yield a(e)}}description({wordsPerSentence:t={avg:24,std:5,min:1},punctuation:e="."}={}){const s=this;return function*(n){let r=0;yield*function*(t,e){let s;for(const n of t)s&&(yield*e(s)),s=n;s&&(yield*e(s,!0))}(n,function*(n,i){0===r&&(n=a(n),r=s._gaussMS(t)),(0===--r||i)&&(n+=e),yield n})}}_gaussMS(t){if("number"==typeof t)return Math.round(t);let{avg:e,std:s,min:n,max:r}=t;void 0===s&&(s=e/4);let i=this._prng.randomGauss()*s+e;return void 0!==n&&(i=Math.max(n,i)),void 0!==r&&(i=Math.min(r,i)),Math.round(i)}}function a(t){return t[0].toUpperCase()+t.substring(1)}const u="// 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)}.`);";const l='<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>Sample Page</title>\n <link rel="stylesheet" href="styles.css">\n</head>\n<body>\n <header>\n <nav>\n <a href="/">Home</a>\n <a href="/about">About</a>\n </nav>\n </header>\n\n <main>\n <h1>Welcome</h1>\n <p>This is a <strong>sample</strong> paragraph with <em>emphasis</em>.</p>\n\n <ul>\n <li>Item 1</li>\n <li>Item 2</li>\n </ul>\n\n <form action="/submit" method="post">\n <label for="name">Name:</label>\n <input type="text" id="name" name="name" required>\n <button type="submit">Submit</button>\n </form>\n\n <table>\n <thead>\n <tr>\n <th>Name</th>\n <th>Value</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Alpha</td>\n <td>100</td>\n </tr>\n </tbody>\n </table>\n </main>\n\n <footer>\n <p>© 2024 Example</p>\n </footer>\n\n <script src="main.js"><\/script>\n</body>\n</html>';var c=Object.freeze({__proto__:null,html:function(){return l},javascript:function(){return u},js:function(){return u}});class h{constructor(t){this._prng=t._prng,this._words=t.words}_extractLangFeatures(t=[]){const e=new Set,s=[];for(const n of t)if(n.startsWith("lang-")){let t=n.slice(5);"javascript"===t&&(t="js"),e.add(t)}else s.push(n);return[[...e],s]}markdown({sources:t,citation:e,features:s,blocks:n=[8,12],sampling:r=1}={}){let i=[];[i,s]=this._extractLangFeatures(s);let o=this._sample([()=>this.atxHeading({features:s}),()=>this.paragraph({sources:t,citation:e,features:s}),...i.map(t=>()=>this.fencedCodeBlock({lang:t,features:s})),...i.length?[]:[()=>this.fencedCodeBlock({features:s})],()=>this.paragraph({sources:t,citation:e,features:s}),()=>this.table({features:s}),()=>this.image(),()=>this.paragraph({sources:t,citation:e,features:s}),()=>this.hr(),()=>this.html(),()=>this.atxHeading({features:s}),()=>this.paragraph({sources:t,citation:e,features:s}),()=>this.list({features:s}),()=>this.paragraph({sources:t,citation:e,features:s})],r).join("\n\n");if(e&&e.unused&&e.unused.length){const s=[...e.unused];s.sort((t,e)=>t-e),o+=s.map(s=>this._citation(e,t[s])).join("")}return o}_sample(t,e){const s=[];for(const n of t)1>e&&this._prng.random()>=e||s.push(n());return s}hr(){return"*-_".charAt(this._prng.randomInt(0,2)).repeat(this._prng.randomInt(3,6))}atxHeading({level:t=[1,6],size:e=[1,8],content:s}={}){const n=s||this._words.words({size:e});return`${"#".repeat(this._prng.randomInt(...t))} ${n}`}setextHeading({level:t=[1,2],size:e=[1,8],content:s}={}){return`${s||this._words.words({size:e})}\n${"=-".charAt(this._prng.randomInt(...t)-1).repeat(3)}`}linkReferenceDefinition({label:t,destination:e,title:s}){return`[${t}]: ${e}${void 0!==s?" "+s:""}`}indentedCodeBlock({lang:t,content:e,size:s}){return e=e||this._codeContent({lang:t,size:s}),this._indent(4,e)}fencedCodeBlock({lang:t,content:e,size:s,fenceChar:n="`"}={}){return"random"===n&&(n="`~".charAt(this._prng.randomInt(0,1))),e=e||this._codeContent({lang:t,size:s}),`${n.repeat(3)}${t||""}\n${e}\n${n.repeat(3)}`}paragraph({sources:t,citation:e,size:s=[20,50]}={}){const n=["description",this.decorateInlineFeatures()];return t&&e&&n.push(this.decorateCitation(t,e)),this._words.words({size:s,decorates:n})}table({columns:t=[2,4],rows:e=[2,8]}={}){const s=this._prng.randomInt(...t),n=this._prng.randomInt(...e),r=[...this._multiply({size:1},s-1),{size:[3,8]}],i=[this._words.words({size:s,output:"array"}),r.map(()=>"---")];for(let t=0;n-1>t;t++)i.push(r.map(({size:t})=>this._words.words({size:t})));return i.map(this._tableRow).join("\n")}image({url:t,imageSize:e=[400,250],...s}={}){return t=t||this._imageUrl(e),``}blockquote({size:t=[3,5]}={}){return this._blockquote(this._words.words({size:t}))}list({features:t,type:e="random",count:s=[1,8],size:n=[5,15]}={}){let r="number"==typeof s?s:this._prng.randomInt(...s);const i="random"===e?["ordered","bullet","task"][this._prng.randomInt(0,2)]:e,o=[];for(;r>0;){const s=this._prng.randomInt(1,r);let a=this.paragraph({features:t,size:n});s>1&&(a+="\n"+this.list({features:t,type:e,count:s-1,size:n})),o.push(this._listItem(i,a)),r-=s}return o.join("\n")}codeSpan(t){return`\`${this._content(t)}\``}emphasis({level:t=[1,3],options:e}={}){const s="number"==typeof t?t:this._prng.randomInt(...t),n="_*".charAt(this._prng.randomInt(0,1)).repeat(s);return`${n}${this._content(e)}${n}`}link({url:t="https://miso.ai",...e}={}){return`[${this._content(e)}](${t})`}html({}={}){return`<div>${this._svg()}</div>`}_svg(){return'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-calculator" viewBox="0 0 16 16"><path d="M12 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1zM4 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2z"/><path d="M4 2.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.5.5h-7a.5.5 0 0 1-.5-.5zm0 4a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm3-6a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm3-6a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v4a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5z"/></svg>'}_INLINE_FEATURES={"code-span":()=>["`","`"],"emphasis-1":()=>this._multiply(this._emphasisAdfix(1),2),"emphasis-2":()=>this._multiply(this._emphasisAdfix(2),2),"emphasis-3":()=>this._multiply(this._emphasisAdfix(3),2),strikethrough:()=>["~","~"],link:({url:t="https://miso.ai"}={})=>["[",`](${t})`]};_emphasisAdfix(t=[1,3]){const e="number"==typeof t?t:this._prng.randomInt(...t);return"_*".charAt(this._prng.randomInt(0,1)).repeat(e)}get _INLINE_FEATURE_LIST(){return Object.keys(this._INLINE_FEATURES)}get _INLINE_FEATURE_SET(){return new Set(this._INLINE_FEATURE_LIST)}decorateInlineFeatures({features:t,size:e=[1,3],rest:s=[0,8]}={}){t=(t=t||this._INLINE_FEATURE_LIST).filter(t=>this._INLINE_FEATURE_SET.has(t));const n=this._shuffle([...t]);let r=n.length-1;const i=()=>"number"==typeof s?s:this._prng.randomInt(...s),o=()=>"number"==typeof e?e:this._prng.randomInt(...e),a=()=>0>r?t[this._prng.randomInt(0,t.length-1)]:n[r--],u=this;return function*(t){let e,s=i();yield*function*(t,e){let s;for(const n of t)s&&(yield*e(s)),s=n;s&&(yield*e(s,!0))}(t,function*(t,n){if(!e&&0===s){const[n,r]=u._INLINE_FEATURES[a()]();t=`${n}${t}`,s=o(),e=r}if(s--,e){const o=t.length,a=t.charAt(o-1);"."===(r=a)||","===r||"!"===r||"?"===r||":"===r||";"===r?(t=`${t.substring(0,o-1)}${e}${a}`,e=void 0,s=i()):(n||0===s)&&(t=`${t}${e}`,e=void 0,s=i())}var r;yield t})}}decorateCitation(t,{density:e=.667,unused:s,...n}){const r=t.length,i=()=>s&&s.length?s.pop():this._prng.randomInt(0,r-1),o=this;return function*(s){for(const r of s)"."===r.charAt(r.length-1)&&o._prng.random()<e?yield`${r}${o._citation(n,t[i()])}`:yield r}}_content({size:t=[1,3],content:e}={}){return e||this._words.words({size:t})}_blockquote(t){return t.split("\n").map(t=>"> "+t).join("\n")}_indent(t,e){return e.split("\n").map(e=>" ".repeat(t)+e).join("\n")}_listItem(t,e){const[s,n]=e.split("\n",2),r=`${this._listItemPrefix(t)} ${s}`;return n?r+"\n"+this._indent("ordered"===t?3:2,n):r}_listItemPrefix(t,e="random"){switch(t){case"ordered":return"1.";case"bullet":return"-";case"task":return`- [${("random"===e?.5>this._prng.random():e)?"x":" "}]`;default:throw Error("unknown list item type: "+t)}}_codeContent({lang:t,size:e=[10,30]}){return t&&c[t]?c[t]():this._words.words({output:"multiline",size:e})}_tableRow(t){return`| ${t.join(" | ")} |`}_multiply(t,e){const s=[];for(let n=0;e>n;n++)s.push("function"==typeof t?t():t);return s}_shuffle(t){for(let e=t.length-1;e>0;e--){const s=this._prng.randomInt(0,e);[t[e],t[s]]=[t[s],t[e]]}return t}_imageUrl(t){return`https://picsum.photos/seed/${this._prng.randomInt(0,999)}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}_citation({link:t,start:e,end:s},{index:n,url:r}){return t?`[${e}${n}${s}](${r})`:`${e}${n}${s}`}}const d=Date.UTC(2025,0,1),m=Date.UTC(2025,11,31,23,59,59,999);class p{constructor(t){this._prng=t._prng,this._words=t.words,this._markdown=t.markdown}date({}={}){return new Date(d+this._prng.random()*(m-d)).toISOString()}image({size:t=300}={}){return this._imageUrl(t)}authors({size:t=[1,3]}={}){return this._words.words({size:t,decorates:["title"],output:"array"})}tags({size:t=[1,4]}={}){return this._words.words({size:t,output:"array"})}title({size:t=[2,6]}={}){return this._words.words({size:t,decorates:["title"]})}term({}={}){const t=this._prng.random();return this._words.words({size:.7>t?1:.9>t?2:3,decorates:["title"]})}description({size:t=[10,20],...e}={}){return this._words.words({size:t,decorates:[Object.keys(e).length?["description",e]:"description"]})}html({paragraphs:t=8,sections:e,paragraph:s,image:n}={}){s={size:[30,60],...s},n={size:[480,270],...n},void 0===e&&(e=Math.floor(t*(1+this._prng.random())/4));const r=[],i=t/(e=Math.max(1,Math.min(e,t)));let o=0;for(let t=0;e>t;t++){for(t>0&&r.push(`<h4>${this.title()}</h4>`);o++<(t+1)*i;)r.push(`<p>${this.description(s)}</p>`);r.push(`<div class="image-container"><img src="${this.image(n)}"></div>`)}return r.join("")}availability(){return this._prng.random()>.3?"IN_STOCK":"OUT_OF_STOCK"}price(){return Math.floor(1e4*this._prng.random())/100}rating(){return Math.floor(500*this._prng.random())/100+1}answer({sources:t,format:e,citation:s,sampling:n,features:r}){if("markdown"===e){let e=1;return t=t.map(({url:t})=>({url:t,index:e++})),this._markdown.markdown({sources:t,citation:s,sampling:n,features:r})}return this._words.words({min:this._sample(50,n),max:this._sample(50,n),decorates:["description"]})}_imageUrl(t){return`https://picsum.photos/seed/${this._prng.randomInt(0,999)}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}_sample(t,e){return void 0!==e?Math.ceil(t*e):t}}class _{constructor(t){this._prng=t._prng}repeat(t,e){const s=this._prng.randomInt(...e),n=[];for(let e=0;s>e;e++)n.push(t());return n}shuffle(t){for(let e=t.length-1;e>0;e--){const s=this._prng.randomInt(0,e);[t[e],t[s]]=[t[s],t[e]]}return t}imageUrl(t){return`https://picsum.photos/seed/${this._prng.randomInt(0,999)}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}}class f{constructor({seed:e=n()}={}){this._seed=e,this._prng=t({seed:e}),this.utils=new _(this),this.words=new o(this),this.markdown=new h(this),this.fields=new p(this)}get prng(){return this._prng}get seed(){return this._seed}}let g=class{constructor(t){this._lorem=t._lorem}_product({}={}){const{fields:t,prng:e,utils:s}=this._lorem,n=e.shortId(),r=s.repeat(()=>t.price(),[1,2]);return r.sort((t,e)=>t-e),{product_id:n,authors:t.authors(),categories:[],tags:t.tags(),title:t.title(),description:t.description(),cover_image:t.image(),url:"https://dummy.miso.ai/products/"+n,sale_price:r[0],original_price:r[r.length-1],rating:t.rating(),availability:t.availability()}}};const w=new Set(["cover_image","url","created_at","updated_at","published_at"]);class y{constructor(t){this._lorem=t._lorem}_article({html:t,fl:e=[]}={}){const{fields:s,prng:n}=this._lorem,r={product_id:n.shortId(),authors:s.authors(),categories:[],tags:s.tags(),title:s.title({size:[4,10]}),snippet:s.description({size:[20,40]}),html:s.html(t)};for(const t of e)w.has(t)&&(r[t]=this._property(r,t));return r}_property({product_id:t},e){const{fields:s}=this._lorem;switch(e){case"cover_image":return s.image();case"url":return"/products/"+t;case"created_at":case"updated_at":case"published_at":return s.date()}}}class b{constructor(t){this._lorem=t._lorem}_question({}={}){return this._lorem.fields.description({size:[4,8],punctuation:"?"})}}class v{constructor(t){this._lorem=t._lorem}_image({fl:t=[]}={}){const{fields:e,prng:s}=this._lorem,n=s.shortId();return{product_id:n,image_src:e.image({size:[1200,400]}),image_alt:e.title({size:[2,4]}),title:e.title({size:[4,10]}),url:"/products/"+n,created_at:e.date(),updated_at:e.date(),published_at:e.date()}}}class I{constructor(t){this._lorem=t._lorem}_completions({q:t,completion_fields:e,rows:s}={}){let n=0;const r={};for(const i of e)r[i]=this._completionsForField(i,t,n,s),n+=s;return r}_completionsForField(t,e,s,n){const r=[];for(let i=0;n>i;i++)r.push(this._completion(t,e,s));return r}_completion(t,e,s){const{fields:n,prng:r}=this._lorem,i=n.title(),o=r.randomInt(0,i.length),a=i.substring(0,o),u=i.substring(o);return{text:`${a}${e}${u}`,text_with_markups:`${this._marked(a)}${e}${this._marked(u)}`,text_with_inverted_markups:`${a}${this._marked(e)}${u}`,_field:t,_index:s}}_marked(t){return t.length>0?`<mark>${t}</mark>`:""}}const $=5,q=[1e3,5e3],z=[.75,.25];class x{constructor(t){this._lorem=t._lorem}_facets({facets:t,...e}={}){const s={};for(let n of t)"string"==typeof n&&(n={field:n}),s[n.field]=this._facetCountList(n,e);return s}_facetCountList(t,{_ctrl:e={},...s}={}){let{field:n,size:r=$}=t;r=0===e.total?0:Math.max(1,Math.min(r,10));let i=this._highestFacetCountValue(n,s);const o=new Set,a=[];for(let t=0;r>t;t++)a.push([this._getTerm(n,o),i]),i=this._nextFacetCountValue(i,n,s);return a}_getTerm(t,e){const{fields:s}=this._lorem;if(e.size>50)return s.term({field:t});for(;;){const n=s.term({field:t});if(!e.has(n))return e.add(n),n}}_highestFacetCountValue(t,e){const[s,n]=q;return this._lorem.prng.randomInt(s,n)}_nextFacetCountValue(t,e,s){const[n,r]=z,i=n+this._lorem.prng.random()*(r-n);return Math.ceil(t*i)}}function k(t,e){return void 0!==e?Math.ceil(t*e):t}function A({html:t,...e}){return e}let M=class{constructor(t){this._data=t}_searchResults({_ctrl:t={},fl:e=["cover_image","url"],rows:s=10,facets:n,_meta:{page:r=0}={}}){const{prng:i}=this._data._lorem,o=void 0!==t.total?t.total:i.randomInt(1e3,1e4);return{products:this._data.articles({rows:Math.min(o-r*s,s),fl:e}).map(A),total:o,facet_counts:n?{facet_fields:this._data.facets({facets:n,_ctrl:t})}:void 0}}};class S{constructor(t){this._data=t}_answer({_ctrl:t={},question:e,parent_question_id:s,fl:n=["cover_image","url"],source_fl:r=["cover_image","url"],related_resource_fl:i=["cover_image","url"],cite_link:o=!1,cite_start:a="[",cite_end:u="]",rows:l=10,facets:c,timestamp:h=Date.UTC(2026,0,1),_meta:{page:d=0}={}},{answerFormat:m="markdown",answerSampling:p,answerLanguages:_=[]}={}){const f=this._data,{fields:g,prng:w,utils:y}=f._lorem,b=w.uuid(),v=function(t){const e=new Date(t).toISOString();return e.endsWith("Z")?e.slice(0,-1):e}(h),I=void 0!==p?Math.max(0,Math.min(1,p)):void 0,$=_.length?_.map(t=>"lang-"+t):void 0,q=f.articles({rows:this._sampleRandomInt(6,8,I),fl:i}).map(A),z=f.images({rows:this._sampleRandomInt(2,12,I)}),x=f.articles({rows:this._sampleRandomInt(4,6,I),fl:r}).map(A),k=void 0!==t.total?t.total:w.randomInt(1e3,1e4),M=f.articles({rows:Math.min(k-d*l,l),fl:n}).map(A),S=c?{facet_fields:f.facets({facets:c,_ctrl:t})}:void 0,E={link:"0"!==o&&!!o,start:a,end:u,unused:y.shuffle([...Array(x.length).keys()])};return{question:e,question_id:b,...s&&{parent_question_id:s},datetime:v,answer:g.answer({sources:x,citation:E,format:m,sampling:I,features:$}),images:z,sources:x,products:M,total:k,facet_counts:S,related_resources:q,followup_questions:f.questions({rows:this._sampleRandomInt(3,6)})}}_sampleRandomInt(t,e,s){return this._data._lorem.prng.randomInt(k(t,s),k(e,s))}}function E(t){return new T(t)}class T{constructor(t){this._lorem=function(t){return new f(t)}(t),this._articles=new y(this),this._products=new g(this),this._questions=new b(this),this._images=new v(this),this._completions=new I(this),this._facets=new x(this),this._search=new M(this),this._answers=new S(this)}get lorem(){return this._lorem}articles({rows:t,...e}={}){const s=[];for(let n=0;t>n;n++)s.push(this._articles._article({...e,index:n}));return s}products({rows:t,...e}={}){const s=[];for(let n=0;t>n;n++)s.push(this._products._product({...e,index:n}));return s}questions({rows:t=5,...e}={}){const s=[];for(let n=0;t>n;n++)s.push(this._questions._question({...e,index:n}));return s}images({rows:t,...e}={}){const s=[];for(let n=0;t>n;n++)s.push(this._images._image({...e,index:n}));return s}completions(t){return this._completions._completions(t)}facets(t){return this._facets._facets(t)}searchResults(t){return this._search._searchResults(t)}answer(t,e){return this._answers._answer(t,e)}}const j=[{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 F{constructor(t={}){this._options=t,this._answers=new Map}questions(t,{seed:e,...s}={}){const n=E({seed:e}),r=this._createAnswer(n,0,t,s),{question_id:i}=r;return{question_id:i}}search(t,{seed:e,...s}={}){const n=E({seed:e}),r={miso_id:n._lorem.prng.uuid(),...n.searchResults(t)};return(void 0===t.answer||t.answer)&&(r.question_id=this._createAnswer(n,1,t,s).question_id),r}autocomplete({q:t,completion_fields:e=["title"],rows:s=5,...n},{seed:r}={}){return{completions:E({seed:r}).completions({q:t,completion_fields:e,rows:s})}}search_autocomplete(t,e){return this.autocomplete(t,e)}_createAnswer(t,e,s,n={}){const r=new C(t,e,s,{...this._options,...n});return this._answers.set(r.question_id,r),r}answer(t){const e=this._answers.get(t);if(!e){const e=Error("Question not found: "+t);throw e.status=404,e}return e.get()}related_questions(t,{seed:e}={}){const s=E({seed:e}),n=s._lorem.prng.uuid();return{related_questions:s.questions(t),miso_id:n}}trending_questions(t,e){return this.related_questions(t,e)}}class C{constructor(t,e,s,{answerFormat:n,answerSampling:r,answerLanguages:i,...o}={}){this._mode=e,this._options=Object.freeze(o);const a=this.timestamp=Date.now();this._data=t.answer({...s,timestamp:a},{answerFormat:n,answerSampling:r,answerLanguages:i})}get question_id(){return this._data.question_id}get searchResults(){const{products:t,total:e,facet_counts:s}=this._data;return function(t){if("object"!=typeof t)return t;const e={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&void 0!==t[s]&&(e[s]=t[s]);return e}({products:t,total:e,facet_counts:s})}get(){const t=(Date.now()-this.timestamp)*(this._options.speedRate||1)/1e3,e=this._question(t),[s,n,r,i]=this._answer(t),o=this._sources(t,r),a=this._related_resources(t,r),u=this._followup_questions(t,r),{question_id:l,datetime:c,parent_question_id:h,images:d}=this._data;switch(this._mode){case 0:return{answer:n,answer_stage:s,datetime:c,finished:r,revision:i,parent_question_id:h,question:e,question_id:l,images:d,sources:o,related_resources:a,followup_questions:u};case 1:return{answer:n,answer_stage:s,datetime:c,finished:r,revision:i,question_id:l,images:d,sources:o};default:throw Error("Unknown mode: "+this._mode)}}_question(t){const{question:e}=this._data;return t>3?e+" [revised]":e}_answer(t){let e=t;for(const s of j)if(e-=s.duration,0>e)return[s.name,s.text,!1,t];const{answer:s}=this._data,n=Math.floor(100*e),r=n>=s.length;return["result",r?s:s.slice(0,n),r,t]}_sources(t,e){const{sources:s}=this._data;if(e)return s;const{length:n}=s;return s.slice(0,Math.floor(n*t/3))}_related_resources(t,e){const{related_resources:s}=this._data;if(e)return s;const{length:n}=s;return s.slice(0,Math.floor(n*t/3))}_followup_questions(t,e){const{followup_questions:s}=this._data;if(e||!s)return s;const{length:n}=s;return s.slice(0,Math.floor(n*t/3))}}class R{constructor(t){this._options=t}search({rows:t=5,...e},{seed:s}={}){return{products:E({seed:s}).products({rows:t})}}autocomplete({q:t,completion_fields:e=["title"],rows:s=5,...n},{seed:r}={}){return{completions:E({seed:r}).completions({q:t,completion_fields:e,rows:s})}}}class U{constructor(t){this._options=t}user_to_products({rows:t=5,...e},{seed:s}={}){return{products:E({seed:s}).products({rows:t})}}product_to_products({rows:t=5,...e},{seed:s}={}){return{products:E({seed:s}).products({rows:t})}}}class L{constructor(t){this._options=t}upload(t,{}={}){return[]}}class N{constructor(t){this._options=t}upload(t,{}={}){return[]}batchDelete(t,{}={}){return[]}ids({}={}){const t=[];for(let e=0;5e3>e;e++)t.push(O(e));return{ids:t}}}function O(t){return`${10>t?"p_000":100>t?"p_00":1e3>t?"p_0":"p_"}${t}`}class D{constructor(t={}){this.ask=new F(t),this.search=new R(t),this.recommendation=new U(t),this.interactions=new L(t),this.products=new N(t)}}return{buildApi:function(t){return new D(t)},misoData:E}});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).doggoganger=e()}(this,function(){"use strict";function t({seed:t=r()}={}){return new e(new n(function(t=1){if(Array.isArray(t)&&4===t.length)return[...t];const e=function(t){let e=t>>>0;return()=>{e+=2654435769;let t=e;return t=(t^t>>>16)>>>0,t=Math.imul(t,2246822507)>>>0,t=(t^t>>>13)>>>0,t=Math.imul(t,3266489909)>>>0,(t^t>>>16)>>>0}}(t);return[e(),e(),e(),e()]}(t)))}class e{constructor(t){this._engine=t}random(){return this._engine.next()/4294967296}randomBool(t=.5){return this.random()<t}randomInt(t,e){return null!=e&&e>t?t+Math.floor(this.random()*(e-t+1)):t}randomGauss(){return 2*(this.random()+this.random()+this.random())-3}seed(){return 4294967296*this.random()>>>0}uuid(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(t^16*this.random()>>t/4).toString(16))}shortId(){let t="";for(let e=0;8>e;e++)t+=this.randomInt(0,35).toString(36);return t}}function s(t,e){return(t<<e|t>>>32-e)>>>0}function r(){return 4294967296*Math.random()>>>0}class n{constructor(t){this._state=t}get state(){return[...this._state]}next(){const t=this._state,e=9*s(5*t[1]>>>0,7)>>>0,r=t[1]<<9>>>0;return t[2]^=t[0],t[3]^=t[1],t[1]^=t[2],t[0]^=t[3],t[2]^=r,t[3]=s(t[3],11),e}}var i=["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"];class o{constructor(t){this._prng=t._prng}words({decorates:t=[],output:e="string",size:s,min:r,max:n,...i}={}){let o=this.limit(s||[r,n])(this.base(i));for(const e of t)o=this._lookup(e)(o);return this._lookup(e)(o)}_lookup(t){switch(typeof t){case"string":return this._fns[t]();case"function":return t;case"object":if(Array.isArray(t)){const[e,s={}]=t;return this._fns[e](s)}}throw Error("Unrecognized decorator/output form: "+t)}get _fns(){return{string:t=>this.string(t),array:t=>this.array(t),title:t=>this.title(t),description:t=>this.description(t),multiline:t=>this.multiline(t)}}*base({words:t=i,fixedStarts:e=0}={}){const s=t.length;for(let r=0;;r++)yield t[e>r?r:this._prng.randomInt(0,s-1)]}string({separator:t=" "}={}){return e=>[...e].join(t)}array(){return t=>[...t]}multiline({wordsPerLine:t={avg:10,std:3,min:1}}={}){return e=>{let s=this._gaussMS(t),r="";for(let n of e)r&&(0===s--?(r+="\n",s=this._gaussMS(t)):r+=" "),r+=n;return r}}limit(t=[5,10]){const e="number"==typeof t?t:this._prng.randomInt(...t);return function*(t){let s=0;for(let r of t){if(s++>=e)break;yield r}}}title({}={}){return function*(t){for(let e of t)yield a(e)}}description({wordsPerSentence:t={avg:24,std:5,min:1},punctuation:e="."}={}){const s=this;return function*(r){let n=0;yield*function*(t,e){let s;for(const r of t)s&&(yield*e(s)),s=r;s&&(yield*e(s,!0))}(r,function*(r,i){0===n&&(r=a(r),n=s._gaussMS(t)),(0===--n||i)&&(r+=e),yield r})}}_gaussMS(t){if("number"==typeof t)return Math.round(t);let{avg:e,std:s,min:r,max:n}=t;void 0===s&&(s=e/4);let i=this._prng.randomGauss()*s+e;return void 0!==r&&(i=Math.max(r,i)),void 0!==n&&(i=Math.min(n,i)),Math.round(i)}}function a(t){return t[0].toUpperCase()+t.substring(1)}const u=[["paragraph",5],["heading",2],["list",2],["table",2],["hr",1],["blockQuote",1],["codeBlock",1],["rawHtml",1],["image",1]].reduce((t,[e,s])=>{for(let r=0;s>r;r++)t.push(e);return t},[]);class l{constructor(t){this._lorem=t,this._prng=t._prng,this._words=t.words,this._code=t.code,this._INLINE_FEATURES={"code-span":()=>["`","`"],"emphasis-1":()=>this._multiply(this._emphasisAdfix(1),2),"emphasis-2":()=>this._multiply(this._emphasisAdfix(2),2),"emphasis-3":()=>this._multiply(this._emphasisAdfix(3),2),strikethrough:()=>["~","~"],link:({url:t="https://miso.ai"}={})=>["[",`](${t})`]}}_extractLangFeatures(t=[]){const e=new Set,s=[];for(const r of t)if(r.startsWith("lang-")){let t=r.slice(5);"javascript"===t&&(t="js"),e.add(t)}else s.push(r);return[[...e],s]}markdown({features:t,blocks:e=[8,12],...s}={}){const{sources:r,citation:n}=s,i=this._lorem.prng.randomInt(...e);let o=this._lorem.utils.select(u,i).map(t=>this[t](s)).join("\n\n");if(n&&n.unused&&n.unused.length){const t=[...n.unused];t.sort((t,e)=>t-e),o+=t.map(t=>this._citation(n,r[t])).join("")}return o}_sample(t,e){const s=[];for(const r of t)1>e&&this._prng.random()>=e||s.push(r());return s}hr(){const t="*-_".charAt(this._prng.randomInt(0,2)),e=this._prng.randomInt(3,6);return t.repeat(e)}heading(t){return this._prng.randomBool(.75)?this.atxHeading(t):this.setextHeading(t)}atxHeading({level:t=[1,6],size:e=[1,8],content:s}={}){const r=s||this._words.words({size:e});return`${"#".repeat(this._prng.randomInt(...t))} ${r}`}setextHeading({level:t=[1,2],size:e=[1,8],content:s}={}){return`${s||this._words.words({size:e})}\n${"=-".charAt(this._prng.randomInt(...t)-1).repeat(3)}`}linkReferenceDefinition({label:t,destination:e,title:s}){return`[${t}]: ${e}${void 0!==s?" "+s:""}`}codeBlock(t){return this._prng.randomBool(.75)?this.fencedCodeBlock(t):this.indentedCodeBlock(t)}indentedCodeBlock({lang:t,content:e,size:s}){return e=e||this._codeContent({lang:t,size:s}),this._indent(4,e)}fencedCodeBlock({lang:t,content:e,size:s,fenceChar:r="`"}={}){return"random"===r&&(r="`~".charAt(this._prng.randomInt(0,1))),e=e||this._codeContent({lang:t,size:s}),`${r.repeat(3)}${t||""}\n${e}\n${r.repeat(3)}`}paragraph({sources:t,citation:e,size:s=[20,50]}={}){const r=["description",this.decorateInlineFeatures()];return t&&e&&r.push(this.decorateCitation(t,e)),this._words.words({size:s,decorates:r})}table({columns:t=[2,4],rows:e=[2,8]}={}){const s=this._prng.randomInt(...t),r=this._prng.randomInt(...e),n=[...this._multiply({size:1},s-1),{size:[3,8]}],i=[this._words.words({size:s,output:"array"}),n.map(()=>"---")];for(let t=0;r-1>t;t++)i.push(n.map(({size:t})=>this._words.words({size:t})));return i.map(this._tableRow).join("\n")}image({url:t,imageSize:e=[400,250],...s}={}){return t=t||this._imageUrl(e),``}blockQuote({size:t=[3,5]}={}){return this._blockQuote(this._words.words({size:t}))}list({features:t,type:e="random",count:s=[1,8],size:r=[5,15]}={}){let n="number"==typeof s?s:this._prng.randomInt(...s);const i="random"===e?["ordered","bullet","task"][this._prng.randomInt(0,2)]:e,o=[];for(;n>0;){const s=this._prng.randomInt(1,n);let a=this.paragraph({features:t,size:r});s>1&&(a+="\n"+this.list({features:t,type:e,count:s-1,size:r})),o.push(this._listItem(i,a)),n-=s}return o.join("\n")}codeSpan(t){return`\`${this._content(t)}\``}emphasis({level:t=[1,3],options:e}={}){const s="number"==typeof t?t:this._prng.randomInt(...t),r="_*".charAt(this._prng.randomInt(0,1)).repeat(s);return`${r}${this._content(e)}${r}`}link({url:t="https://miso.ai",...e}={}){return`[${this._content(e)}](${t})`}rawHtml({}={}){return`<div>${this._svg()}</div>`}_svg(){return'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-calculator" viewBox="0 0 16 16"><path d="M12 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1zM4 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2z"/><path d="M4 2.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.5.5h-7a.5.5 0 0 1-.5-.5zm0 4a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm3-6a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm3-6a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v4a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5z"/></svg>'}_emphasisAdfix(t=[1,3]){const e="number"==typeof t?t:this._prng.randomInt(...t);return"_*".charAt(this._prng.randomInt(0,1)).repeat(e)}get _INLINE_FEATURE_LIST(){return Object.keys(this._INLINE_FEATURES)}get _INLINE_FEATURE_SET(){return new Set(this._INLINE_FEATURE_LIST)}decorateInlineFeatures({features:t,size:e=[1,3],rest:s=[0,8]}={}){t=(t=t||this._INLINE_FEATURE_LIST).filter(t=>this._INLINE_FEATURE_SET.has(t));const r=this._shuffle([...t]);let n=r.length-1;const i=()=>"number"==typeof s?s:this._prng.randomInt(...s),o=()=>"number"==typeof e?e:this._prng.randomInt(...e),a=()=>0>n?t[this._prng.randomInt(0,t.length-1)]:r[n--],u=this;return function*(t){let e,s=i();yield*function*(t,e){let s;for(const r of t)s&&(yield*e(s)),s=r;s&&(yield*e(s,!0))}(t,function*(t,r){if(!e&&0===s){const[r,n]=u._INLINE_FEATURES[a()]();t=`${r}${t}`,s=o(),e=n}if(s--,e){const o=t.length,a=t.charAt(o-1);"."===(n=a)||","===n||"!"===n||"?"===n||":"===n||";"===n?(t=`${t.substring(0,o-1)}${e}${a}`,e=void 0,s=i()):(r||0===s)&&(t=`${t}${e}`,e=void 0,s=i())}var n;yield t})}}decorateCitation(t,{density:e=.667,unused:s,...r}){const n=t.length,i=()=>s&&s.length?s.pop():this._prng.randomInt(0,n-1),o=this;return function*(s){for(const n of s)"."===n.charAt(n.length-1)&&o._prng.random()<e?yield`${n}${o._citation(r,t[i()])}`:yield n}}_content({size:t=[1,3],content:e}={}){return e||this._words.words({size:t})}_blockQuote(t){return t.split("\n").map(t=>"> "+t).join("\n")}_indent(t,e){return e.split("\n").map(e=>" ".repeat(t)+e).join("\n")}_listItem(t,e){const[s,r]=e.split("\n",2),n=`${this._listItemPrefix(t)} ${s}`;return r?n+"\n"+this._indent("ordered"===t?3:2,r):n}_listItemPrefix(t,e="random"){switch(t){case"ordered":return"1.";case"bullet":return"-";case"task":return`- [${("random"===e?.5>this._prng.random():e)?"x":" "}]`;default:throw Error("unknown list item type: "+t)}}_codeContent({lang:t,size:e=[10,30]}){return this._prng.randomBool()?this._code[t||"any"]():this._words.words({output:"multiline",size:e})}_tableRow(t){return`| ${t.join(" | ")} |`}_multiply(t,e){const s=[];for(let r=0;e>r;r++)s.push("function"==typeof t?t():t);return s}_shuffle(t){for(let e=t.length-1;e>0;e--){const s=this._prng.randomInt(0,e);[t[e],t[s]]=[t[s],t[e]]}return t}_imageUrl(t){return`https://picsum.photos/seed/${this._prng.randomInt(0,999)}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}_citation({link:t,start:e,end:s},{index:r,url:n}){return t?`[${e}${r}${s}](${n})`:`${e}${r}${s}`}}const c=Date.UTC(2025,0,1),d=Date.UTC(2025,11,31,23,59,59,999);class h{constructor(t){this._prng=t._prng,this._words=t.words,this._markdown=t.markdown}date({}={}){return new Date(c+this._prng.random()*(d-c)).toISOString()}image({size:t=300}={}){return this._imageUrl(t)}authors({size:t=[1,3]}={}){return this._words.words({size:t,decorates:["title"],output:"array"})}tags({size:t=[1,4]}={}){return this._words.words({size:t,output:"array"})}title({size:t=[2,6]}={}){return this._words.words({size:t,decorates:["title"]})}term({}={}){const t=this._prng.random();return this._words.words({size:.7>t?1:.9>t?2:3,decorates:["title"]})}description({size:t=[10,20],...e}={}){const s=Object.keys(e).length?["description",e]:"description";return this._words.words({size:t,decorates:[s]})}html({paragraphs:t=8,sections:e,paragraph:s,image:r}={}){s={size:[30,60],...s},r={size:[480,270],...r},void 0===e&&(e=Math.floor(t*(1+this._prng.random())/4));const n=[],i=t/(e=Math.max(1,Math.min(e,t)));let o=0;for(let t=0;e>t;t++){for(t>0&&n.push(`<h4>${this.title()}</h4>`);o++<(t+1)*i;)n.push(`<p>${this.description(s)}</p>`);n.push(`<div class="image-container"><img src="${this.image(r)}"></div>`)}return n.join("")}availability(){return this._prng.random()>.3?"IN_STOCK":"OUT_OF_STOCK"}price(){return Math.floor(1e4*this._prng.random())/100}rating(){return Math.floor(500*this._prng.random())/100+1}answer({sources:t,format:e,citation:s,sampling:r,features:n}){if("markdown"===e){let e=1;return t=t.map(({url:t})=>({url:t,index:e++})),this._markdown.markdown({sources:t,citation:s,sampling:r,features:n})}return this._words.words({min:this._sample(50,r),max:this._sample(50,r),decorates:["description"]})}_imageUrl(t){return`https://picsum.photos/seed/${this._prng.randomInt(0,999)}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}_sample(t,e){return void 0!==e?Math.ceil(t*e):t}}function m(t,e=2){const s=" ".repeat(e);return`${s}${t.replaceAll("\n","\n"+s)}`}const p='\x3c!-- head --\x3e\n<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n<title>Sample Page</title>\n<link rel="stylesheet" href="styles.css">',_=[p,"\x3c!-- header --\x3e\n<h1>Welcome</h1>","\x3c!-- typography --\x3e\n<p>This is a <strong>sample</strong> paragraph with <em>emphasis</em>.</p>",'\x3c!-- link --\x3e\n<a href="/">Link</a>',"\x3c!-- escaped --\x3e\n<p>© 2024 Example</p>","\x3c!-- list --\x3e\n<ul>\n <li>Item 1</li>\n <li>Item 2</li>\n</ul>",'\x3c!-- form --\x3e\n<form action="/submit" method="post">\n <label for="name">Name:</label>\n <input type="text" id="name" name="name" required>\n <button type="submit">Submit</button>\n</form>','\x3c!-- script --\x3e\n<script src="main.js"><\/script>'];const g=["// 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';","// variables\nlet a = 10;\nconst b = 20;","// function declaration\nfunction sum(x, y) {\n return x + y;\n}","// generator function\nfunction* iterator() {\n yield 0;\n yield 1;\n}","// arrow function\nconst multiply = (x, y) => x * y;","// class\nclass Person {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n greet() {\n console.log('Hello, my name is Miso.');\n }\n}","// primitive\nconst str = 'Hello, world!';\nconst num = 10.99;","// object\nconst person = new Person('John', 30);\nperson.greet();","// object literal\nconst object = {\n name: 'John',\n [x]: 10,\n ...props,\n};","// array literal\nconst arr = [1, 2, 3, 4, 5, ...props];","// regexp literal\nconst regexp = /\\w+/g;","// operators\nconst sum = a + b;\nconst product = a * b;\nconst negation = -a;\nconst max = a > b ? a : b;","// flow control\nlet i = 9;\nfor (const n of arr) {\n if (n > i) {\n console.log(n);\n }\n i++;\n}","// async/await\n(async () => {\n const result = await asyncFunction();\n})();","// try/catch\ntry {\n} catch (e) {\n}","// destructing\nconst { name, age, ...rest } = person;\nconst [ x, y, ...rest ] = arr;","// template literals\nconsole.log(`The sum of ${a} and ${b} is ${sum(a, b)}.`);"],f=["html","javascript"];class w{constructor(t){this._lorem=t}any(t){return this[this._lorem.utils.selectOne(f)](t)}html(t){return function(t,{blocks:e=[2,4]}={}){const s=t.prng.randomInt(...e),r=t.utils.select(_,s),n=r.includes(p),i=r.filter(t=>t!==p);return`<!DOCTYPE html>\n<html lang="en">${n?`\n <head>\n${m(p,4)}\n </head>`:""}\n <body>\n${i.map(t=>m(t,4)).join("\n\n")}\n </body>\n</html>`}(this._lorem,t)}javaScript(t){return function(t,{blocks:e=[2,4]}={}){const s=t.prng.randomInt(...e);return t.utils.select(g,s).join("\n\n")}(this._lorem,t)}js(...t){return this.javaScript(...t)}javascript(...t){return this.javaScript(...t)}}class y{constructor(t){this._prng=t._prng}repeat(t,e){const s=this._prng.randomInt(...e),r=[];for(let e=0;s>e;e++)r.push("function"==typeof t?t():t);return r}shuffle(t){return this.select(t)}selectOne(t){return t[this._prng.randomInt(0,t.length-1)]}select(t,e){if(1===e)return[this.selectOne(t)];const s=[...t],r=s.length;if(void 0===e&&(e=r),0>e)throw Error("n must be non-negative");e=Math.min(e,r);for(let t=0;e>t;t++){const e=this._prng.randomInt(t,r-1);[s[t],s[e]]=[s[e],s[t]]}return s.slice(0,e)}imageUrl(t){return`https://picsum.photos/seed/${this._prng.randomInt(0,999)}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}}class v{constructor({seed:e=r()}={}){this._seed=e,this._prng=t({seed:e}),this.utils=new y(this),this.words=new o(this),this.code=new w(this),this.markdown=new l(this),this.fields=new h(this)}get prng(){return this._prng}get seed(){return this._seed}}let b=class{constructor(t){this._lorem=t._lorem}_product({}={}){const{fields:t,prng:e,utils:s}=this._lorem,r=e.shortId(),n=s.repeat(()=>t.price(),[1,2]);return n.sort((t,e)=>t-e),{product_id:r,authors:t.authors(),categories:[],tags:t.tags(),title:t.title(),description:t.description(),cover_image:t.image(),url:"https://dummy.miso.ai/products/"+r,sale_price:n[0],original_price:n[n.length-1],rating:t.rating(),availability:t.availability()}}};const x=new Set(["cover_image","url","created_at","updated_at","published_at"]);class I{constructor(t){this._lorem=t._lorem}_article({html:t,fl:e=[]}={}){const{fields:s,prng:r}=this._lorem,n={product_id:r.shortId(),authors:s.authors(),categories:[],tags:s.tags(),title:s.title({size:[4,10]}),snippet:s.description({size:[20,40]}),html:s.html(t)};for(const t of e)x.has(t)&&(n[t]=this._property(n,t));return n}_property({product_id:t},e){const{fields:s}=this._lorem;switch(e){case"cover_image":return s.image();case"url":return"/products/"+t;case"created_at":case"updated_at":case"published_at":return s.date()}}}class ${constructor(t){this._lorem=t._lorem}_question({}={}){return this._lorem.fields.description({size:[4,8],punctuation:"?"})}}class q{constructor(t){this._lorem=t._lorem}_image({fl:t=[]}={}){const{fields:e,prng:s}=this._lorem,r=s.shortId();return{product_id:r,image_src:e.image({size:[1200,400]}),image_alt:e.title({size:[2,4]}),title:e.title({size:[4,10]}),url:"/products/"+r,created_at:e.date(),updated_at:e.date(),published_at:e.date()}}}class z{constructor(t){this._lorem=t._lorem}_completions({q:t,completion_fields:e,rows:s}={}){let r=0;const n={};for(const i of e)n[i]=this._completionsForField(i,t,r,s),r+=s;return n}_simpleCompletions({q:t,rows:e}={}){return this._completionsForField("query_suggestion",t,0,e).map(t=>t.text)}_completionsForField(t,e,s,r){const n=[];for(let i=0;r>i;i++)n.push(this._completion(t,e,s));return n}_completion(t,e,s){const{fields:r,prng:n}=this._lorem,i=r.title(),o=n.randomInt(0,i.length),a=i.substring(0,o),u=i.substring(o);return{text:`${a}${e}${u}`,text_with_markups:`${this._marked(a)}${e}${this._marked(u)}`,text_with_inverted_markups:`${a}${this._marked(e)}${u}`,_field:t,_index:s}}_marked(t){return t.length>0?`<mark>${t}</mark>`:""}}const k=5,M=[1e3,5e3],S=[.75,.25];class A{constructor(t){this._lorem=t._lorem}_facets({facets:t,...e}={}){const s={};for(let r of t)"string"==typeof r&&(r={field:r}),s[r.field]=this._facetCountList(r,e);return s}_facetCountList(t,{_ctrl:e={},...s}={}){let{field:r,size:n=k}=t;n=0===e.total?0:Math.max(1,Math.min(n,10));let i=this._highestFacetCountValue(r,s);const o=new Set,a=[];for(let t=0;n>t;t++)a.push([this._getTerm(r,o),i]),i=this._nextFacetCountValue(i,r,s);return a}_getTerm(t,e){const{fields:s}=this._lorem;if(e.size>50)return s.term({field:t});for(;;){const r=s.term({field:t});if(!e.has(r))return e.add(r),r}}_highestFacetCountValue(t,e){const[s,r]=M;return this._lorem.prng.randomInt(s,r)}_nextFacetCountValue(t,e,s){const[r,n]=S,i=r+this._lorem.prng.random()*(n-r);return Math.ceil(t*i)}}function E(t,e){return void 0!==e?Math.ceil(t*e):t}function j({html:t,...e}){return e}let C=class{constructor(t){this._data=t}_searchResults({_ctrl:t={},fl:e=["cover_image","url"],rows:s=10,facets:r,_meta:{page:n=0}={}}){const{prng:i}=this._data._lorem,o=void 0!==t.total?t.total:i.randomInt(1e3,1e4);return{products:this._data.articles({rows:Math.min(o-n*s,s),fl:e}).map(j),total:o,facet_counts:r?{facet_fields:this._data.facets({facets:r,_ctrl:t})}:void 0}}};class F{constructor(t){this._data=t}_answer({_ctrl:t={},question:e,parent_question_id:s,fl:r=["cover_image","url"],source_fl:n=["cover_image","url"],related_resource_fl:i=["cover_image","url"],cite_link:o=!1,cite_start:a="[",cite_end:u="]",rows:l=10,facets:c,timestamp:d=Date.UTC(2026,0,1),_meta:{page:h=0}={}},{answerFormat:m="markdown",answerSampling:p,answerLanguages:_=[]}={}){const g=this._data,{fields:f,prng:w,utils:y}=g._lorem,v=w.uuid(),b=function(t){const e=new Date(t).toISOString();return e.endsWith("Z")?e.slice(0,-1):e}(d),x=void 0!==p?Math.max(0,Math.min(1,p)):void 0,I=_.length?_.map(t=>"lang-"+t):void 0,$=g.articles({rows:this._sampleRandomInt(6,8,x),fl:i}).map(j),q=g.images({rows:this._sampleRandomInt(2,12,x)}),z=g.articles({rows:this._sampleRandomInt(4,6,x),fl:n}).map(j),k=void 0!==t.total?t.total:w.randomInt(1e3,1e4),M=g.articles({rows:Math.min(k-h*l,l),fl:r}).map(j),S=c?{facet_fields:g.facets({facets:c,_ctrl:t})}:void 0,A={link:"0"!==o&&!!o,start:a,end:u,unused:y.shuffle([...Array(z.length).keys()])};return{question:e,question_id:v,...s&&{parent_question_id:s},datetime:b,answer:f.answer({sources:z,citation:A,format:m,sampling:x,features:I}),images:q,sources:z,products:M,total:k,facet_counts:S,related_resources:$,followup_questions:g.questions({rows:this._sampleRandomInt(3,6)})}}_sampleRandomInt(t,e,s){return this._data._lorem.prng.randomInt(E(t,s),E(e,s))}}function T(t){return new R(t)}class R{constructor(t){this._lorem=function(t){return new v(t)}(t),this._articles=new I(this),this._products=new b(this),this._questions=new $(this),this._images=new q(this),this._completions=new z(this),this._facets=new A(this),this._search=new C(this),this._answers=new F(this)}get lorem(){return this._lorem}articles({rows:t,...e}={}){const s=[];for(let r=0;t>r;r++)s.push(this._articles._article({...e,index:r}));return s}products({rows:t,...e}={}){const s=[];for(let r=0;t>r;r++)s.push(this._products._product({...e,index:r}));return s}questions({rows:t=5,...e}={}){const s=[];for(let r=0;t>r;r++)s.push(this._questions._question({...e,index:r}));return s}images({rows:t,...e}={}){const s=[];for(let r=0;t>r;r++)s.push(this._images._image({...e,index:r}));return s}completions(t){return this._completions._completions(t)}simpleCompletions(t){return this._completions._simpleCompletions(t)}facets(t){return this._facets._facets(t)}searchResults(t){return this._search._searchResults(t)}answer(t,e){return this._answers._answer(t,e)}}const U=[{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 L{constructor(t={}){this._options=t,this._answers=new Map}questions(t,{seed:e,...s}={}){const r=T({seed:e}),n=this._createAnswer(r,0,t,s),{question_id:i}=n;return{question_id:i}}search(t,{seed:e,...s}={}){const r=T({seed:e}),n={miso_id:r._lorem.prng.uuid(),...r.searchResults(t)};return(void 0===t.answer||t.answer)&&(n.question_id=this._createAnswer(r,1,t,s).question_id),n}query_suggestion({q:t,rows:e=5,...s},{seed:r}={}){return{completions:T({seed:r}).simpleCompletions({q:t,rows:e,...s})}}autocomplete({q:t,rows:e=5,...s},{seed:r}={}){return{completions:T({seed:r}).simpleCompletions({q:t,rows:e,...s})}}search_autocomplete({q:t,completion_fields:e=["title"],rows:s=5,...r},{seed:n}={}){return{completions:T({seed:n}).completions({q:t,completion_fields:e,rows:s,...r})}}_createAnswer(t,e,s,r={}){const n=new N(t,e,s,{...this._options,...r});return this._answers.set(n.question_id,n),n}answer(t){const e=this._answers.get(t);if(!e){const e=Error("Question not found: "+t);throw e.status=404,e}return e.get()}related_questions(t,{seed:e}={}){const s=T({seed:e}),r=s._lorem.prng.uuid();return{related_questions:s.questions(t),miso_id:r}}trending_questions(t,e){return this.related_questions(t,e)}}class N{constructor(t,e,s,{answerFormat:r,answerSampling:n,answerLanguages:i,...o}={}){this._mode=e,this._options=Object.freeze(o),this._data=t.answer(s,{answerFormat:r,answerSampling:n,answerLanguages:i}),this._timestamp=Date.now(),this._index=1}get question_id(){return this._data.question_id}get searchResults(){const{products:t,total:e,facet_counts:s}=this._data;return function(t){if("object"!=typeof t)return t;const e={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&void 0!==t[s]&&(e[s]=t[s]);return e}({products:t,total:e,facet_counts:s})}get(){const t=this._elapsed(),e=this._question(t),[s,r,n,i]=this._answer(t),o=this._sources(t,n),a=this._related_resources(t,n),u=this._followup_questions(t,n),{question_id:l,datetime:c,parent_question_id:d,images:h}=this._data;switch(this._mode){case 0:return{answer:r,answer_stage:s,datetime:c,finished:n,revision:i,parent_question_id:d,question:e,question_id:l,images:h,sources:o,related_resources:a,followup_questions:u};case 1:return{answer:r,answer_stage:s,datetime:c,finished:n,revision:i,question_id:l,images:h,sources:o};default:throw Error("Unknown mode: "+this._mode)}}_elapsed(){return this._options.detemporize?1*this._index++:(Date.now()-this._timestamp)*(this._options.speedRate||1)/1e3}_question(t){const{question:e}=this._data;return t>3?e+" [revised]":e}_answer(t){let e=t;for(const s of U)if(e-=s.duration,0>e)return[s.name,s.text,!1,t];const{answer:s}=this._data,r=Math.floor(100*e),n=r>=s.length;return["result",n?s:s.slice(0,r),n,t]}_sources(t,e){const{sources:s}=this._data;if(e)return s;const{length:r}=s;return s.slice(0,Math.floor(r*t/3))}_related_resources(t,e){const{related_resources:s}=this._data;if(e)return s;const{length:r}=s;return s.slice(0,Math.floor(r*t/3))}_followup_questions(t,e){const{followup_questions:s}=this._data;if(e||!s)return s;const{length:r}=s;return s.slice(0,Math.floor(r*t/3))}}class O{constructor(t){this._options=t}search({rows:t=5,...e},{seed:s}={}){return{products:T({seed:s}).products({rows:t})}}autocomplete({q:t,completion_fields:e=["title"],rows:s=5,...r},{seed:n}={}){return{completions:T({seed:n}).completions({q:t,completion_fields:e,rows:s})}}}class B{constructor(t){this._options=t}user_to_products({rows:t=5,...e},{seed:s}={}){return{products:T({seed:s}).products({rows:t})}}product_to_products({rows:t=5,...e},{seed:s}={}){return{products:T({seed:s}).products({rows:t})}}}class D{constructor(t){this._options=t}upload(t,{}={}){return[]}}class H{constructor(t){this._options=t}upload(t,{}={}){return[]}batchDelete(t,{}={}){return[]}ids({}={}){const t=[];for(let e=0;5e3>e;e++)t.push(P(e));return{ids:t}}}function P(t){return`${10>t?"p_000":100>t?"p_00":1e3>t?"p_0":"p_"}${t}`}class V{constructor(t={}){this.ask=new L(t),this.search=new O(t),this.recommendation=new B(t),this.interactions=new D(t),this.products=new H(t)}}return{buildApi:function(t){return new V(t)},misoData:T}});
|
package/package.json
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
"build": "npm run build:js",
|
|
15
15
|
"start:js": "rollup -w -c rollup.config.dev.js",
|
|
16
16
|
"start": "nodemon ./cli/index.js",
|
|
17
|
-
"dev": "npm run start -- -- -v"
|
|
17
|
+
"dev": "npm run start -- -- -v",
|
|
18
|
+
"test": "uvu test"
|
|
18
19
|
},
|
|
19
20
|
"repository": {
|
|
20
21
|
"type": "git",
|
|
@@ -31,8 +32,8 @@
|
|
|
31
32
|
"dependencies": {
|
|
32
33
|
"@koa/cors": "^5.0.0",
|
|
33
34
|
"@koa/router": "^12.0.0",
|
|
34
|
-
"@miso.ai/doggoganger-api": "0.10.0-beta.
|
|
35
|
-
"@miso.ai/lorem": "0.10.0-beta.
|
|
35
|
+
"@miso.ai/doggoganger-api": "0.10.0-beta.2",
|
|
36
|
+
"@miso.ai/lorem": "0.10.0-beta.2",
|
|
36
37
|
"koa": "^2.14.1",
|
|
37
38
|
"koa-body": "^6.0.1",
|
|
38
39
|
"koa-static": "^5.0.0",
|
|
@@ -46,5 +47,5 @@
|
|
|
46
47
|
"rollup-plugin-livereload": "^2.0.5",
|
|
47
48
|
"rollup-plugin-serve": "^2.0.2"
|
|
48
49
|
},
|
|
49
|
-
"version": "0.10.0-beta.
|
|
50
|
+
"version": "0.10.0-beta.2"
|
|
50
51
|
}
|
package/src/api.js
CHANGED
package/src/fetch.js
CHANGED
|
@@ -22,13 +22,13 @@ export default async function fetch(api, url, { method = 'GET', body, seed } = {
|
|
|
22
22
|
body = segments[2];
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
const apiNode = api[group];
|
|
26
|
+
if (!apiNode[name]) {
|
|
26
27
|
throw new Error(`Unknown path: ${url.pathname}`);
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
const fn = api[group][name].bind(api[group]);
|
|
30
30
|
const response = responseFunction(type);
|
|
31
|
-
const result = await
|
|
31
|
+
const result = await apiNode[name](body, { seed });
|
|
32
32
|
const resBody = response(result);
|
|
33
33
|
|
|
34
34
|
return new Response(JSON.stringify(resBody), {
|
package/src/index.js
CHANGED
package/src/route/ask.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { version } from '@miso.ai/lorem';
|
|
1
2
|
import Router from '@koa/router';
|
|
2
3
|
import { handler, parseBodyIfNecessary } from './utils.js';
|
|
3
4
|
import { delay, rollLatency } from '../utils.js';
|
|
@@ -25,7 +26,7 @@ export default function(api) {
|
|
|
25
26
|
const data = api.ask.questions(payload, getOptionsFromCtx(ctx));
|
|
26
27
|
const time = rollLatency(DEFAULT_LATENCY_OPTIONS.min, DEFAULT_LATENCY_OPTIONS.max);
|
|
27
28
|
await delay(time);
|
|
28
|
-
ctx.body = JSON.stringify({ data });
|
|
29
|
+
ctx.body = JSON.stringify({ data, version });
|
|
29
30
|
});
|
|
30
31
|
|
|
31
32
|
router.get('/questions/:id/answer', async (ctx) => {
|
|
@@ -33,7 +34,7 @@ export default function(api) {
|
|
|
33
34
|
const data = api.ask.answer(id);
|
|
34
35
|
const time = rollLatency(DEFAULT_LATENCY_OPTIONS.min, DEFAULT_LATENCY_OPTIONS.max);
|
|
35
36
|
await delay(time);
|
|
36
|
-
ctx.body = JSON.stringify({ data });
|
|
37
|
+
ctx.body = JSON.stringify({ data, version });
|
|
37
38
|
});
|
|
38
39
|
|
|
39
40
|
router.post('/search', async (ctx) => {
|
|
@@ -41,7 +42,7 @@ export default function(api) {
|
|
|
41
42
|
const data = api.ask.search(payload, getOptionsFromCtx(ctx));
|
|
42
43
|
const time = rollLatency(DEFAULT_LATENCY_OPTIONS.min, DEFAULT_LATENCY_OPTIONS.max);
|
|
43
44
|
await delay(time);
|
|
44
|
-
ctx.body = JSON.stringify({ data });
|
|
45
|
+
ctx.body = JSON.stringify({ data, version });
|
|
45
46
|
});
|
|
46
47
|
|
|
47
48
|
router.get('/search/:id/answer', async (ctx) => {
|
|
@@ -49,10 +50,16 @@ export default function(api) {
|
|
|
49
50
|
const data = api.ask.answer(id);
|
|
50
51
|
const time = rollLatency(DEFAULT_LATENCY_OPTIONS.min, DEFAULT_LATENCY_OPTIONS.max);
|
|
51
52
|
await delay(time);
|
|
52
|
-
ctx.body = JSON.stringify({ data });
|
|
53
|
+
ctx.body = JSON.stringify({ data, version });
|
|
53
54
|
});
|
|
54
55
|
|
|
55
56
|
router.post('/related_questions', handler((p, o) => api.ask.related_questions(p, o), 'query'));
|
|
56
57
|
|
|
58
|
+
router.post('/query_suggestion', handler((p, o) => api.ask.query_suggestion(p, o), 'query'));
|
|
59
|
+
|
|
60
|
+
router.post('/autocomplete', handler((p, o) => api.ask.autocomplete(p, o), 'query'));
|
|
61
|
+
|
|
62
|
+
router.post('/search_autocomplete', handler((p, o) => api.ask.search_autocomplete(p, o), 'query'));
|
|
63
|
+
|
|
57
64
|
return router;
|
|
58
65
|
}
|
package/src/route/utils.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { version } from '@miso.ai/lorem';
|
|
1
2
|
|
|
2
3
|
export function parseBodyIfNecessary(body) {
|
|
3
4
|
if (typeof body === 'string') {
|
|
@@ -22,6 +23,7 @@ export function handler(fn, response) {
|
|
|
22
23
|
} catch (error) {
|
|
23
24
|
ctx.status = error.status || 500;
|
|
24
25
|
ctx.body = {
|
|
26
|
+
doggoganger_version: version,
|
|
25
27
|
errors: true,
|
|
26
28
|
message: error.message || '',
|
|
27
29
|
};
|
|
@@ -35,9 +37,9 @@ export function responseFunction(response) {
|
|
|
35
37
|
}
|
|
36
38
|
switch (response) {
|
|
37
39
|
case 'query':
|
|
38
|
-
return data => ({ data });
|
|
40
|
+
return data => ({ data, version });
|
|
39
41
|
case 'data':
|
|
40
|
-
return data => ({ took: 5, errors: false, data });
|
|
42
|
+
return data => ({ took: 5, errors: false, data, version });
|
|
41
43
|
default:
|
|
42
44
|
throw new Error(`Unknown response type: ${response}`);
|
|
43
45
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { test } from 'uvu';
|
|
2
|
+
import * as assert from 'uvu/assert';
|
|
3
|
+
import buildApi from '../src/api.js';
|
|
4
|
+
import fetch from '../src/fetch.js';
|
|
5
|
+
|
|
6
|
+
const SEED = 42;
|
|
7
|
+
const BASE_URL = 'http://doggoganger';
|
|
8
|
+
|
|
9
|
+
test('POST /ask/questions returns a question_id', async () => {
|
|
10
|
+
const api = buildApi({ detemporize: true });
|
|
11
|
+
const res = await fetch(api, `${BASE_URL}/ask/questions`, {
|
|
12
|
+
method: 'POST',
|
|
13
|
+
body: { q: 'What is Miso?' },
|
|
14
|
+
seed: SEED,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
assert.is(res.status, 200);
|
|
18
|
+
|
|
19
|
+
const { data, version } = await res.json();
|
|
20
|
+
assert.ok(data.question_id, 'question_id should be present');
|
|
21
|
+
assert.type(data.question_id, 'string');
|
|
22
|
+
assert.type(version, 'string');
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test('POST /ask/questions with same seed returns same question_id', async () => {
|
|
26
|
+
const api1 = buildApi({ detemporize: true });
|
|
27
|
+
const api2 = buildApi({ detemporize: true });
|
|
28
|
+
|
|
29
|
+
const res1 = await fetch(api1, `${BASE_URL}/ask/questions`, {
|
|
30
|
+
method: 'POST',
|
|
31
|
+
body: { q: 'What is Miso?' },
|
|
32
|
+
seed: SEED,
|
|
33
|
+
});
|
|
34
|
+
const res2 = await fetch(api2, `${BASE_URL}/ask/questions`, {
|
|
35
|
+
method: 'POST',
|
|
36
|
+
body: { q: 'What is Miso?' },
|
|
37
|
+
seed: SEED,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const { data: data1 } = await res1.json();
|
|
41
|
+
const { data: data2 } = await res2.json();
|
|
42
|
+
|
|
43
|
+
assert.is(data1.question_id, data2.question_id);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('POST /ask/questions with different seeds returns different question_ids', async () => {
|
|
47
|
+
const api1 = buildApi({ detemporize: true });
|
|
48
|
+
const api2 = buildApi({ detemporize: true });
|
|
49
|
+
|
|
50
|
+
const res1 = await fetch(api1, `${BASE_URL}/ask/questions`, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
body: { q: 'What is Miso?' },
|
|
53
|
+
seed: SEED,
|
|
54
|
+
});
|
|
55
|
+
const res2 = await fetch(api2, `${BASE_URL}/ask/questions`, {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
body: { q: 'What is Miso?' },
|
|
58
|
+
seed: SEED + 1,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const { data: data1 } = await res1.json();
|
|
62
|
+
const { data: data2 } = await res2.json();
|
|
63
|
+
|
|
64
|
+
assert.is.not(data1.question_id, data2.question_id);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('POST /ask/questions accepts JSON string body', async () => {
|
|
68
|
+
const api = buildApi({ detemporize: true });
|
|
69
|
+
const res = await fetch(api, `${BASE_URL}/ask/questions`, {
|
|
70
|
+
method: 'POST',
|
|
71
|
+
body: JSON.stringify({ q: 'What is Miso?' }),
|
|
72
|
+
seed: SEED,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
assert.is(res.status, 200);
|
|
76
|
+
const { data } = await res.json();
|
|
77
|
+
assert.ok(data.question_id);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test.run();
|