@waniwani/sdk 0.14.1 → 0.14.3
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/README.md +5 -5
- package/dist/angular-html-GK625GFM.js +2 -0
- package/dist/{angular-ts-UPMUIYI3.js → angular-ts-BBPQXDS2.js} +2 -2
- package/dist/{angular-ts-A7ZNTSV6.js → angular-ts-DFS2FCNO.js} +2 -2
- package/dist/{apl-QBN4KIYA.js → apl-FBR445XW.js} +2 -2
- package/dist/{apl-ZTMAKUPW.js → apl-JGB4KP74.js} +2 -2
- package/dist/{astro-OQUOYMBE.js → astro-BMSTTQT4.js} +2 -2
- package/dist/{astro-ZC25ZSBI.js → astro-K7JGTCPV.js} +2 -2
- package/dist/{blade-QBDEYXMB.js → blade-OHP5YUT7.js} +2 -2
- package/dist/{blade-BVUO2H7O.js → blade-RWJJQSLU.js} +2 -2
- package/dist/chat/embed.js +66 -65
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/express-js/index.d.ts +4 -4
- package/dist/chat/express-js/index.js.map +1 -1
- package/dist/chat/index.d.ts +16 -9
- package/dist/chat/index.js +10 -9
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/next-js/index.d.ts +5 -5
- package/dist/chat/next-js/index.js.map +1 -1
- package/dist/chat/server/index.d.ts +4 -4
- package/dist/chat/server/index.js.map +1 -1
- package/dist/chat/styles.css +1 -1
- package/dist/{chunk-7PHUBJVC.js → chunk-AI3BZXLG.js} +2 -2
- package/dist/{chunk-5JBHQYU5.js → chunk-F4UUXA3U.js} +3 -3
- package/dist/{chunk-2RS4JWNJ.js → chunk-HFFYDWFN.js} +2 -2
- package/dist/{chunk-AGWJ4LUC.js → chunk-HWHRZFFJ.js} +2 -2
- package/dist/{chunk-BFEOSXSG.js → chunk-IPSY5OIT.js} +2 -2
- package/dist/{chunk-BKIIYGWO.js → chunk-OHRY6PPX.js} +2 -2
- package/dist/{chunk-BNESB5SU.js → chunk-ORTYTFGK.js} +2 -2
- package/dist/{chunk-TV2UKRXD.js → chunk-REK5PMSH.js} +2 -2
- package/dist/{chunk-KMHU4XIM.js → chunk-SREBMPDB.js} +2 -2
- package/dist/{chunk-4OK4GCCR.js → chunk-VDGF5EL2.js} +2 -2
- package/dist/{chunk-VNX5AK2O.js → chunk-VNL3EXC2.js} +2 -2
- package/dist/{chunk-V6FKURGI.js → chunk-W4SPRY5O.js} +2 -2
- package/dist/{chunk-4WLKD7DL.js → chunk-YP6YTC7R.js} +3 -3
- package/dist/{cobol-6DNJTKH3.js → cobol-LJNKRWP5.js} +2 -2
- package/dist/{cobol-SKJIT3WM.js → cobol-ZFZ6ZP6X.js} +2 -2
- package/dist/{code-block-37QAKDTI-IIYKFI5S.js → code-block-37QAKDTI-HV355RRX.js} +2 -2
- package/dist/{code-block-37QAKDTI-IJYLCU3C.js → code-block-37QAKDTI-Y3BUEJRG.js} +2 -2
- package/dist/cpp-HLYUQ6RF.js +2 -0
- package/dist/{crystal-YFCJLEES.js → crystal-UPNOBGN4.js} +2 -2
- package/dist/{edge-3LWPZYS7.js → edge-XE5XFLFP.js} +2 -2
- package/dist/{elixir-3H7W7YJZ.js → elixir-EXRA4QJX.js} +2 -2
- package/dist/{erb-HGSLHT5Y.js → erb-KUYJX32Q.js} +2 -2
- package/dist/{erb-AXCKAI43.js → erb-LRUOJBTB.js} +2 -2
- package/dist/{glimmer-js-ZXI6Y36F.js → glimmer-js-JA25I4AE.js} +2 -2
- package/dist/{glimmer-ts-BJKMFBLF.js → glimmer-ts-CKELYRRF.js} +2 -2
- package/dist/graphql-NLMAEKLI.js +3 -0
- package/dist/graphql-UN5O7U5U.js +2 -0
- package/dist/{hack-KV5GHBVV.js → hack-QIUJFE3G.js} +2 -2
- package/dist/haml-JQIESO7E.js +2 -0
- package/dist/{handlebars-U44VLSEQ.js → handlebars-UBV5AWUH.js} +2 -2
- package/dist/html-AWDHWPK7.js +2 -0
- package/dist/html-derivative-QY3ZIV7G.js +2 -0
- package/dist/{http-NEPTRAQZ.js → http-7ZVVH3VM.js} +2 -2
- package/dist/{http-JSPDAWSO.js → http-KIGXJYY6.js} +2 -2
- package/dist/{hurl-V6ZX2Q3F.js → hurl-B6WXEN45.js} +2 -2
- package/dist/{hurl-OT2SM4S7.js → hurl-BZB5LDD5.js} +2 -2
- package/dist/index.d.ts +9 -9
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{jinja-CCI3FGLW.js → jinja-AEVQQKWS.js} +2 -2
- package/dist/{julia-BWWONBRS.js → julia-75QR2XDN.js} +2 -2
- package/dist/{julia-QPZ7EOS6.js → julia-CPV3A4MM.js} +2 -2
- package/dist/kb/index.js.map +1 -1
- package/dist/legacy/chat/express-js/index.d.ts +4 -4
- package/dist/legacy/chat/express-js/index.js.map +1 -1
- package/dist/legacy/chat/next-js/index.d.ts +5 -5
- package/dist/legacy/chat/next-js/index.js.map +1 -1
- package/dist/legacy/index.d.ts +11 -11
- package/dist/legacy/index.js +16 -15
- package/dist/legacy/index.js.map +1 -1
- package/dist/legacy/mcp/react.d.ts +1 -1
- package/dist/legacy/mcp/react.js +1 -1
- package/dist/legacy/mcp/react.js.map +1 -1
- package/dist/{liquid-OSRU4KOW.js → liquid-S4LVU77Y.js} +2 -2
- package/dist/mcp/index.d.ts +15 -15
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react.d.ts +3 -3
- package/dist/mcp/react.js +1 -1
- package/dist/mcp/react.js.map +1 -1
- package/dist/{mcp-apps-client-OFYMQOI3.js → mcp-apps-client-WEXKWHUI.js} +2 -2
- package/dist/{mcp-apps-client-OFYMQOI3.js.map → mcp-apps-client-WEXKWHUI.js.map} +1 -1
- package/dist/{mcp-apps-client-RY3VD4L7.js → mcp-apps-client-Z5ICFYSR.js} +2 -2
- package/dist/{mcp-apps-client-RY3VD4L7.js.map → mcp-apps-client-Z5ICFYSR.js.map} +1 -1
- package/dist/{mdc-PDOFYVVO.js → mdc-NDTDGSIG.js} +2 -2
- package/dist/{mdc-TEVTGSC7.js → mdc-XWCHWP6B.js} +2 -2
- package/dist/mermaid-4DMBBIKO-DV4JRUY5.js +2 -0
- package/dist/mermaid-4DMBBIKO-IGH2CKFF.js +3 -0
- package/dist/{nim-JPSYX5KC.js → nim-U57UBFBS.js} +2 -2
- package/dist/{nim-WGQAUAVA.js → nim-Z6EEJ7SX.js} +2 -2
- package/dist/{openai-client-TZIOCMXP.js → openai-client-PUBKF5TI.js} +2 -2
- package/dist/{openai-client-TZIOCMXP.js.map → openai-client-PUBKF5TI.js.map} +1 -1
- package/dist/{openai-client-XYLENCIC.js → openai-client-VRJPAPFR.js} +2 -2
- package/dist/{openai-client-XYLENCIC.js.map → openai-client-VRJPAPFR.js.map} +1 -1
- package/dist/{perl-Y3ALUOFJ.js → perl-5IQEFQG3.js} +2 -2
- package/dist/{perl-X4IFZB22.js → perl-IZHDGBO6.js} +2 -2
- package/dist/php-MNP62HWP.js +3 -0
- package/dist/php-UQGWKJAF.js +2 -0
- package/dist/{pug-7XNGVJEC.js → pug-XHTBJJNO.js} +2 -2
- package/dist/{razor-C2NV2YNT.js → razor-UMC4HKIF.js} +2 -2
- package/dist/{rst-WIWCR2KQ.js → rst-6KQSGP2V.js} +2 -2
- package/dist/{rst-W5S2XFF7.js → rst-HCGHBPBZ.js} +2 -2
- package/dist/ruby-ML25RVXY.js +2 -0
- package/dist/ruby-OWE2HOOR.js +3 -0
- package/dist/{soy-G2LDZSDN.js → soy-ALTWCQTO.js} +2 -2
- package/dist/{svelte-EYZDXUS2.js → svelte-6TT7H4YP.js} +2 -2
- package/dist/{templ-KXQ2KV7D.js → templ-WN3SJLUV.js} +2 -2
- package/dist/{ts-tags-TCQ23O6Y.js → ts-tags-NAJDOQCO.js} +2 -2
- package/dist/{ts-tags-7WGDLEKX.js → ts-tags-XNK5N5RZ.js} +2 -2
- package/dist/{twig-JAL4753Y.js → twig-GIY7NVAA.js} +2 -2
- package/dist/{twig-C6YWFFZU.js → twig-OEIJ72KK.js} +2 -2
- package/dist/{vue-O6SLORWU.js → vue-FIH2DYBE.js} +2 -2
- package/dist/{vue-D6SXQNWM.js → vue-V6GLJNYA.js} +2 -2
- package/dist/{vue-vine-T6MFB2MU.js → vue-vine-KB45C76H.js} +2 -2
- package/package.json +2 -2
- package/dist/angular-html-VZSV3CDH.js +0 -2
- package/dist/cpp-4EW5XLOK.js +0 -2
- package/dist/graphql-KHEFECOG.js +0 -2
- package/dist/graphql-YEJQLMOO.js +0 -3
- package/dist/haml-6R7X7F2Q.js +0 -2
- package/dist/html-MYZBE4UD.js +0 -2
- package/dist/html-derivative-OWRPAN3G.js +0 -2
- package/dist/mermaid-4DMBBIKO-7EL5WRQI.js +0 -2
- package/dist/mermaid-4DMBBIKO-PAA57QRQ.js +0 -3
- package/dist/php-3V7EPUAN.js +0 -3
- package/dist/php-QERWOQJG.js +0 -2
- package/dist/ruby-EYYAUQUG.js +0 -2
- package/dist/ruby-LXZJUMFB.js +0 -3
- /package/dist/{angular-html-VZSV3CDH.js.map → angular-html-GK625GFM.js.map} +0 -0
- /package/dist/{angular-ts-UPMUIYI3.js.map → angular-ts-BBPQXDS2.js.map} +0 -0
- /package/dist/{angular-ts-A7ZNTSV6.js.map → angular-ts-DFS2FCNO.js.map} +0 -0
- /package/dist/{apl-QBN4KIYA.js.map → apl-FBR445XW.js.map} +0 -0
- /package/dist/{apl-ZTMAKUPW.js.map → apl-JGB4KP74.js.map} +0 -0
- /package/dist/{astro-OQUOYMBE.js.map → astro-BMSTTQT4.js.map} +0 -0
- /package/dist/{astro-ZC25ZSBI.js.map → astro-K7JGTCPV.js.map} +0 -0
- /package/dist/{blade-QBDEYXMB.js.map → blade-OHP5YUT7.js.map} +0 -0
- /package/dist/{blade-BVUO2H7O.js.map → blade-RWJJQSLU.js.map} +0 -0
- /package/dist/{chunk-7PHUBJVC.js.map → chunk-AI3BZXLG.js.map} +0 -0
- /package/dist/{chunk-5JBHQYU5.js.map → chunk-F4UUXA3U.js.map} +0 -0
- /package/dist/{chunk-2RS4JWNJ.js.map → chunk-HFFYDWFN.js.map} +0 -0
- /package/dist/{chunk-AGWJ4LUC.js.map → chunk-HWHRZFFJ.js.map} +0 -0
- /package/dist/{chunk-BFEOSXSG.js.map → chunk-IPSY5OIT.js.map} +0 -0
- /package/dist/{chunk-BKIIYGWO.js.map → chunk-OHRY6PPX.js.map} +0 -0
- /package/dist/{chunk-BNESB5SU.js.map → chunk-ORTYTFGK.js.map} +0 -0
- /package/dist/{chunk-TV2UKRXD.js.map → chunk-REK5PMSH.js.map} +0 -0
- /package/dist/{chunk-KMHU4XIM.js.map → chunk-SREBMPDB.js.map} +0 -0
- /package/dist/{chunk-4OK4GCCR.js.map → chunk-VDGF5EL2.js.map} +0 -0
- /package/dist/{chunk-VNX5AK2O.js.map → chunk-VNL3EXC2.js.map} +0 -0
- /package/dist/{chunk-V6FKURGI.js.map → chunk-W4SPRY5O.js.map} +0 -0
- /package/dist/{chunk-4WLKD7DL.js.map → chunk-YP6YTC7R.js.map} +0 -0
- /package/dist/{cobol-6DNJTKH3.js.map → cobol-LJNKRWP5.js.map} +0 -0
- /package/dist/{cobol-SKJIT3WM.js.map → cobol-ZFZ6ZP6X.js.map} +0 -0
- /package/dist/{code-block-37QAKDTI-IIYKFI5S.js.map → code-block-37QAKDTI-HV355RRX.js.map} +0 -0
- /package/dist/{code-block-37QAKDTI-IJYLCU3C.js.map → code-block-37QAKDTI-Y3BUEJRG.js.map} +0 -0
- /package/dist/{cpp-4EW5XLOK.js.map → cpp-HLYUQ6RF.js.map} +0 -0
- /package/dist/{crystal-YFCJLEES.js.map → crystal-UPNOBGN4.js.map} +0 -0
- /package/dist/{edge-3LWPZYS7.js.map → edge-XE5XFLFP.js.map} +0 -0
- /package/dist/{elixir-3H7W7YJZ.js.map → elixir-EXRA4QJX.js.map} +0 -0
- /package/dist/{erb-HGSLHT5Y.js.map → erb-KUYJX32Q.js.map} +0 -0
- /package/dist/{erb-AXCKAI43.js.map → erb-LRUOJBTB.js.map} +0 -0
- /package/dist/{glimmer-js-ZXI6Y36F.js.map → glimmer-js-JA25I4AE.js.map} +0 -0
- /package/dist/{glimmer-ts-BJKMFBLF.js.map → glimmer-ts-CKELYRRF.js.map} +0 -0
- /package/dist/{graphql-KHEFECOG.js.map → graphql-NLMAEKLI.js.map} +0 -0
- /package/dist/{graphql-YEJQLMOO.js.map → graphql-UN5O7U5U.js.map} +0 -0
- /package/dist/{hack-KV5GHBVV.js.map → hack-QIUJFE3G.js.map} +0 -0
- /package/dist/{haml-6R7X7F2Q.js.map → haml-JQIESO7E.js.map} +0 -0
- /package/dist/{handlebars-U44VLSEQ.js.map → handlebars-UBV5AWUH.js.map} +0 -0
- /package/dist/{html-MYZBE4UD.js.map → html-AWDHWPK7.js.map} +0 -0
- /package/dist/{html-derivative-OWRPAN3G.js.map → html-derivative-QY3ZIV7G.js.map} +0 -0
- /package/dist/{http-NEPTRAQZ.js.map → http-7ZVVH3VM.js.map} +0 -0
- /package/dist/{http-JSPDAWSO.js.map → http-KIGXJYY6.js.map} +0 -0
- /package/dist/{hurl-V6ZX2Q3F.js.map → hurl-B6WXEN45.js.map} +0 -0
- /package/dist/{hurl-OT2SM4S7.js.map → hurl-BZB5LDD5.js.map} +0 -0
- /package/dist/{jinja-CCI3FGLW.js.map → jinja-AEVQQKWS.js.map} +0 -0
- /package/dist/{julia-BWWONBRS.js.map → julia-75QR2XDN.js.map} +0 -0
- /package/dist/{julia-QPZ7EOS6.js.map → julia-CPV3A4MM.js.map} +0 -0
- /package/dist/{liquid-OSRU4KOW.js.map → liquid-S4LVU77Y.js.map} +0 -0
- /package/dist/{mdc-PDOFYVVO.js.map → mdc-NDTDGSIG.js.map} +0 -0
- /package/dist/{mdc-TEVTGSC7.js.map → mdc-XWCHWP6B.js.map} +0 -0
- /package/dist/{mermaid-4DMBBIKO-7EL5WRQI.js.map → mermaid-4DMBBIKO-DV4JRUY5.js.map} +0 -0
- /package/dist/{mermaid-4DMBBIKO-PAA57QRQ.js.map → mermaid-4DMBBIKO-IGH2CKFF.js.map} +0 -0
- /package/dist/{nim-JPSYX5KC.js.map → nim-U57UBFBS.js.map} +0 -0
- /package/dist/{nim-WGQAUAVA.js.map → nim-Z6EEJ7SX.js.map} +0 -0
- /package/dist/{perl-Y3ALUOFJ.js.map → perl-5IQEFQG3.js.map} +0 -0
- /package/dist/{perl-X4IFZB22.js.map → perl-IZHDGBO6.js.map} +0 -0
- /package/dist/{php-3V7EPUAN.js.map → php-MNP62HWP.js.map} +0 -0
- /package/dist/{php-QERWOQJG.js.map → php-UQGWKJAF.js.map} +0 -0
- /package/dist/{pug-7XNGVJEC.js.map → pug-XHTBJJNO.js.map} +0 -0
- /package/dist/{razor-C2NV2YNT.js.map → razor-UMC4HKIF.js.map} +0 -0
- /package/dist/{rst-WIWCR2KQ.js.map → rst-6KQSGP2V.js.map} +0 -0
- /package/dist/{rst-W5S2XFF7.js.map → rst-HCGHBPBZ.js.map} +0 -0
- /package/dist/{ruby-EYYAUQUG.js.map → ruby-ML25RVXY.js.map} +0 -0
- /package/dist/{ruby-LXZJUMFB.js.map → ruby-OWE2HOOR.js.map} +0 -0
- /package/dist/{soy-G2LDZSDN.js.map → soy-ALTWCQTO.js.map} +0 -0
- /package/dist/{svelte-EYZDXUS2.js.map → svelte-6TT7H4YP.js.map} +0 -0
- /package/dist/{templ-KXQ2KV7D.js.map → templ-WN3SJLUV.js.map} +0 -0
- /package/dist/{ts-tags-TCQ23O6Y.js.map → ts-tags-NAJDOQCO.js.map} +0 -0
- /package/dist/{ts-tags-7WGDLEKX.js.map → ts-tags-XNK5N5RZ.js.map} +0 -0
- /package/dist/{twig-JAL4753Y.js.map → twig-GIY7NVAA.js.map} +0 -0
- /package/dist/{twig-C6YWFFZU.js.map → twig-OEIJ72KK.js.map} +0 -0
- /package/dist/{vue-O6SLORWU.js.map → vue-FIH2DYBE.js.map} +0 -0
- /package/dist/{vue-D6SXQNWM.js.map → vue-V6GLJNYA.js.map} +0 -0
- /package/dist/{vue-vine-T6MFB2MU.js.map → vue-vine-KB45C76H.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-2NQMCQ7O.js";import{a as t}from"./chunk-BKIIYGWO.js";import{a as i}from"./chunk-YTXGYW4C.js";import{a as n}from"./chunk-QP24BTOT.js";import{d as e}from"./chunk-LPD7BHH5.js";e();var d=Object.freeze(JSON.parse(`{"displayName":"Liquid","fileTypes":["liquid"],"foldingStartMarker":"\\\\{%-?\\\\s*(capture|case|comment|form??|if|javascript|paginate|schema|style)[^%()}]+%}","foldingStopMarker":"\\\\{%\\\\s*(end(?:capture|case|comment|form??|if|javascript|paginate|schema|style))[^%()}]+%}","injections":{"L:meta.embedded.block.js, L:meta.embedded.block.css, L:meta.embedded.block.html, L:string.quoted":{"patterns":[{"include":"#injection"}]}},"name":"liquid","patterns":[{"include":"#core"}],"repository":{"attribute":{"begin":"\\\\w+:","beginCaptures":{"0":{"name":"entity.other.attribute-name.liquid"}},"end":"(?=,|%}|}}|\\\\|)","patterns":[{"include":"#value_expression"}]},"attribute_liquid":{"begin":"\\\\w+:","beginCaptures":{"0":{"name":"entity.other.attribute-name.liquid"}},"end":"(?=[,|])|$","patterns":[{"include":"#value_expression"}]},"comment_block":{"begin":"\\\\{%-?\\\\s*comment\\\\s*-?%}","end":"\\\\{%-?\\\\s*endcomment\\\\s*-?%}","name":"comment.block.liquid","patterns":[{"include":"#comment_block"},{"match":"(.(?!\\\\{%-?\\\\s*((?:|end)comment)\\\\s*-?%}))*."}]},"core":{"patterns":[{"include":"#raw_tag"},{"include":"#doc_tag"},{"include":"#comment_block"},{"include":"#style_codefence"},{"include":"#stylesheet_codefence"},{"include":"#json_codefence"},{"include":"#javascript_codefence"},{"include":"#object"},{"include":"#tag"},{"include":"text.html.basic"}]},"doc_tag":{"begin":"\\\\{%-?\\\\s*(doc)\\\\s*-?%}","beginCaptures":{"0":{"name":"meta.tag.liquid"},"1":{"name":"entity.name.tag.doc.liquid"}},"contentName":"comment.block.documentation.liquid","end":"\\\\{%-?\\\\s*(enddoc)\\\\s*-?%}","endCaptures":{"0":{"name":"meta.tag.liquid"},"1":{"name":"entity.name.tag.doc.liquid"}},"name":"meta.block.doc.liquid","patterns":[{"include":"#liquid_doc_description_tag"},{"include":"#liquid_doc_param_tag"},{"include":"#liquid_doc_example_tag"},{"include":"#liquid_doc_prompt_tag"},{"include":"#liquid_doc_fallback_tag"}]},"filter":{"captures":{"1":{"name":"support.function.liquid"}},"match":"\\\\|\\\\s*((?![.0-9])[-0-9A-Z_a-z]+:?)\\\\s*"},"injection":{"patterns":[{"include":"#raw_tag"},{"include":"#comment_block"},{"include":"#object"},{"include":"#tag_injection"}]},"invalid_range":{"match":"\\\\((.(?!\\\\.\\\\.))+\\\\)","name":"invalid.illegal.range.liquid"},"javascript_codefence":{"begin":"(\\\\{%-?)\\\\s*(javascript)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.javascript.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.javascript.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.js","end":"(\\\\{%-?)\\\\s*(endjavascript)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.javascript.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.javascript.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.javascript.liquid","patterns":[{"include":"source.js"}]},"json_codefence":{"begin":"(\\\\{%-?)\\\\s*(schema)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.schema.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.schema.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.json","end":"(\\\\{%-?)\\\\s*(endschema)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.schema.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.schema.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.schema.liquid","patterns":[{"include":"source.json"}]},"language_constant":{"match":"\\\\b(false|true|nil|blank)\\\\b|empty(?!\\\\?)","name":"constant.language.liquid"},"liquid_doc_description_tag":{"begin":"(@description)\\\\b\\\\s*","beginCaptures":{"0":{"name":"comment.block.documentation.liquid"},"1":{"name":"storage.type.class.liquid"}},"contentName":"string.quoted.single.liquid","end":"(?=@prompt|@example|@param|@description|\\\\{%-?\\\\s*enddoc\\\\s*-?%})"},"liquid_doc_example_tag":{"begin":"(@example)\\\\b\\\\s*","beginCaptures":{"0":{"name":"comment.block.documentation.liquid"},"1":{"name":"storage.type.class.liquid"}},"contentName":"meta.embedded.block.liquid","end":"(?=@prompt|@example|@param|@description|\\\\{%-?\\\\s*enddoc\\\\s*-?%})","patterns":[{"include":"#core"}]},"liquid_doc_fallback_tag":{"captures":{"1":{"name":"comment.block.liquid"}},"match":"(@\\\\w+)\\\\b"},"liquid_doc_param_tag":{"captures":{"1":{"name":"storage.type.class.liquid"},"2":{"name":"entity.name.type.instance.liquid"},"3":{"name":"variable.other.liquid"},"4":{"name":"string.quoted.single.liquid"}},"match":"(@param)\\\\s+(?:(\\\\{[^}]*}?)\\\\s+)?(\\\\[?[A-Z_a-z][-\\\\w]*]?)?(?:\\\\s+(.*))?"},"liquid_doc_prompt_tag":{"begin":"(@prompt)\\\\b\\\\s*","beginCaptures":{"0":{"name":"comment.block.documentation.liquid"},"1":{"name":"storage.type.class.liquid"}},"contentName":"string.quoted.single.liquid","end":"(?=@prompt|@example|@param|@description|\\\\{%-?\\\\s*enddoc\\\\s*-?%})"},"number":{"match":"(([-+])\\\\s*)?[0-9]+(\\\\.[0-9]+)?","name":"constant.numeric.liquid"},"object":{"begin":"(?<!comment %})(?<!comment -%})(?<!comment%})(?<!comment-%})(?<!raw %})(?<!raw -%})(?<!raw%})(?<!raw-%})\\\\{\\\\{-?","beginCaptures":{"0":{"name":"punctuation.definition.tag.begin.liquid"}},"end":"-?}}","endCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.object.liquid","patterns":[{"include":"#filter"},{"include":"#attribute"},{"include":"#value_expression"}]},"operator":{"captures":{"1":{"name":"keyword.operator.expression.liquid"}},"match":"(?:(?<=\\\\s)|\\\\b)(==|!=|[<>]|>=|<=|or|and|contains)(?:(?=\\\\s)|\\\\b)"},"range":{"begin":"\\\\(","beginCaptures":{"0":{"name":"punctuation.section.parens.begin.liquid"}},"end":"\\\\)","endCaptures":{"0":{"name":"punctuation.section.parens.end.liquid"}},"name":"meta.range.liquid","patterns":[{"match":"\\\\.\\\\.","name":"punctuation.range.liquid"},{"include":"#variable_lookup"},{"include":"#number"}]},"raw_tag":{"begin":"\\\\{%-?\\\\s*(raw)\\\\s*-?%}","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"contentName":"string.unquoted.liquid","end":"\\\\{%-?\\\\s*(endraw)\\\\s*-?%}","endCaptures":{"1":{"name":"entity.name.tag.liquid"}},"name":"meta.entity.tag.raw.liquid","patterns":[{"match":"(.(?!\\\\{%-?\\\\s*endraw\\\\s*-?%}))*."}]},"string":{"patterns":[{"include":"#string_single"},{"include":"#string_double"}]},"string_double":{"begin":"\\"","end":"\\"","name":"string.quoted.double.liquid"},"string_single":{"begin":"'","end":"'","name":"string.quoted.single.liquid"},"style_codefence":{"begin":"(\\\\{%-?)\\\\s*(style)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.style.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.css","end":"(\\\\{%-?)\\\\s*(endstyle)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.style.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.style.liquid","patterns":[{"include":"source.css"}]},"stylesheet_codefence":{"begin":"(\\\\{%-?)\\\\s*(stylesheet)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.style.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.css","end":"(\\\\{%-?)\\\\s*(endstylesheet)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.style.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.style.liquid","patterns":[{"include":"source.css"}]},"tag":{"begin":"(?<!comment %})(?<!comment -%})(?<!comment%})(?<!comment-%})(?<!raw %})(?<!raw -%})(?<!raw%})(?<!raw-%})\\\\{%-?","beginCaptures":{"0":{"name":"punctuation.definition.tag.begin.liquid"}},"end":"-?%}","endCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.tag.liquid","patterns":[{"include":"#tag_body"}]},"tag_assign":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(assign|echo)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"(?=%})","name":"meta.entity.tag.liquid","patterns":[{"include":"#filter"},{"include":"#attribute"},{"include":"#value_expression"}]},"tag_assign_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(assign|echo)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"$","name":"meta.entity.tag.liquid","patterns":[{"include":"#filter"},{"include":"#attribute_liquid"},{"include":"#value_expression"}]},"tag_body":{"patterns":[{"include":"#tag_liquid"},{"include":"#tag_assign"},{"include":"#tag_comment_inline"},{"include":"#tag_case"},{"include":"#tag_conditional"},{"include":"#tag_for"},{"include":"#tag_paginate"},{"include":"#tag_render"},{"include":"#tag_tablerow"},{"include":"#tag_expression"}]},"tag_case":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(case|when)\\\\b","beginCaptures":{"1":{"name":"keyword.control.case.liquid"}},"end":"(?=%})","name":"meta.entity.tag.case.liquid","patterns":[{"include":"#value_expression"}]},"tag_case_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(case|when)\\\\b","beginCaptures":{"1":{"name":"keyword.control.case.liquid"}},"end":"$","name":"meta.entity.tag.case.liquid","patterns":[{"include":"#value_expression"}]},"tag_comment_block_liquid":{"begin":"^\\\\s*(comment)\\\\b","end":"^\\\\s*(endcomment)\\\\b","name":"comment.block.liquid","patterns":[{"include":"#tag_comment_block_liquid"},{"match":"^\\\\s*(?!((?:|end)comment)).*"}]},"tag_comment_inline":{"begin":"#","end":"(?=%})","name":"comment.line.number-sign.liquid"},"tag_comment_inline_liquid":{"begin":"^\\\\s*#.*","end":"$","name":"comment.line.number-sign.liquid"},"tag_conditional":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(if|elsif|unless)\\\\b","beginCaptures":{"1":{"name":"keyword.control.conditional.liquid"}},"end":"(?=%})","name":"meta.entity.tag.conditional.liquid","patterns":[{"include":"#value_expression"}]},"tag_conditional_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(if|elsif|unless)\\\\b","beginCaptures":{"1":{"name":"keyword.control.conditional.liquid"}},"end":"$","name":"meta.entity.tag.conditional.liquid","patterns":[{"include":"#value_expression"}]},"tag_expression":{"patterns":[{"include":"#tag_expression_without_arguments"},{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(\\\\w+)","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"(?=%})","name":"meta.entity.tag.liquid","patterns":[{"include":"#value_expression"}]}]},"tag_expression_liquid":{"patterns":[{"include":"#tag_expression_without_arguments"},{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(\\\\w+)","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"$","name":"meta.entity.tag.liquid","patterns":[{"include":"#value_expression"}]}]},"tag_expression_without_arguments":{"patterns":[{"captures":{"1":{"name":"keyword.control.conditional.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(end(?:unless|if))\\\\b"},{"captures":{"1":{"name":"keyword.control.loop.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(end(?:for|tablerow|paginate))\\\\b"},{"captures":{"1":{"name":"keyword.control.case.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(endcase)\\\\b"},{"captures":{"1":{"name":"keyword.control.other.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(capture|case|comment|form??|if|javascript|paginate|schema|style)\\\\b"},{"captures":{"1":{"name":"keyword.control.other.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(end(?:capture|case|comment|form??|if|javascript|paginate|schema|style))\\\\b"},{"captures":{"1":{"name":"keyword.control.other.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(else|break|continue)\\\\b"}]},"tag_for":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(for)\\\\b","beginCaptures":{"1":{"name":"keyword.control.for.liquid"}},"end":"(?=%})","name":"meta.entity.tag.for.liquid","patterns":[{"include":"#tag_for_body"}]},"tag_for_body":{"patterns":[{"match":"\\\\b(in|reversed)\\\\b","name":"keyword.control.liquid"},{"match":"\\\\b(offset|limit):","name":"keyword.control.liquid"},{"include":"#value_expression"}]},"tag_for_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(for)\\\\b","beginCaptures":{"1":{"name":"keyword.control.for.liquid"}},"end":"$","name":"meta.entity.tag.for.liquid","patterns":[{"include":"#tag_for_body"}]},"tag_injection":{"begin":"(?<!comment %})(?<!comment -%})(?<!comment%})(?<!comment-%})(?<!raw %})(?<!raw -%})(?<!raw%})(?<!raw-%})\\\\{%-?(?!-?\\\\s*(end(?:style|javascript|comment|raw)))","beginCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"end":"-?%}","endCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.tag.liquid","patterns":[{"include":"#tag_body"}]},"tag_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(liquid)\\\\b","beginCaptures":{"1":{"name":"keyword.control.liquid.liquid"}},"end":"(?=%})","name":"meta.entity.tag.liquid.liquid","patterns":[{"include":"#tag_comment_block_liquid"},{"include":"#tag_comment_inline_liquid"},{"include":"#tag_assign_liquid"},{"include":"#tag_case_liquid"},{"include":"#tag_conditional_liquid"},{"include":"#tag_for_liquid"},{"include":"#tag_paginate_liquid"},{"include":"#tag_render_liquid"},{"include":"#tag_tablerow_liquid"},{"include":"#tag_expression_liquid"}]},"tag_paginate":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(paginate)\\\\b","beginCaptures":{"1":{"name":"keyword.control.paginate.liquid"}},"end":"(?=%})","name":"meta.entity.tag.paginate.liquid","patterns":[{"include":"#tag_paginate_body"}]},"tag_paginate_body":{"patterns":[{"match":"\\\\b(by)\\\\b","name":"keyword.control.liquid"},{"include":"#value_expression"}]},"tag_paginate_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(paginate)\\\\b","beginCaptures":{"1":{"name":"keyword.control.paginate.liquid"}},"end":"$","name":"meta.entity.tag.paginate.liquid","patterns":[{"include":"#tag_paginate_body"}]},"tag_render":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(render)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.render.liquid"}},"end":"(?=%})","name":"meta.entity.tag.render.liquid","patterns":[{"include":"#tag_render_special_keywords"},{"include":"#attribute"},{"include":"#value_expression"}]},"tag_render_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(render)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.render.liquid"}},"end":"$","name":"meta.entity.tag.render.liquid","patterns":[{"include":"#tag_render_special_keywords"},{"include":"#attribute_liquid"},{"include":"#value_expression"}]},"tag_render_special_keywords":{"match":"\\\\b(with|as|for)\\\\b","name":"keyword.control.other.liquid"},"tag_tablerow":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(tablerow)\\\\b","beginCaptures":{"1":{"name":"keyword.control.tablerow.liquid"}},"end":"(?=%})","name":"meta.entity.tag.tablerow.liquid","patterns":[{"include":"#tag_tablerow_body"}]},"tag_tablerow_body":{"patterns":[{"match":"\\\\b(in)\\\\b","name":"keyword.control.liquid"},{"match":"\\\\b(cols|offset|limit):","name":"keyword.control.liquid"},{"include":"#value_expression"}]},"tag_tablerow_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(tablerow)\\\\b","beginCaptures":{"1":{"name":"keyword.control.tablerow.liquid"}},"end":"$","name":"meta.entity.tag.tablerow.liquid","patterns":[{"include":"#tag_tablerow_body"}]},"value_expression":{"patterns":[{"captures":{"2":{"name":"invalid.illegal.filter.liquid"},"3":{"name":"invalid.illegal.filter.liquid"}},"match":"(\\\\[)(\\\\|)(?=[^]]*)(?=])"},{"match":"(?<=\\\\s)([-*+/])(?=\\\\s)","name":"invalid.illegal.filter.liquid"},{"include":"#language_constant"},{"include":"#operator"},{"include":"#invalid_range"},{"include":"#range"},{"include":"#number"},{"include":"#string"},{"include":"#variable_lookup"}]},"variable_lookup":{"patterns":[{"match":"\\\\b(additional_checkout_buttons|address|all_country_option_tags|all_products|articles??|block|blogs??|canonical_url|cart|checkout|collections??|comment|content_for_additional_checkout_buttons|content_for_header|content_for_index|content_for_layout|country_option_tags|currency|current_page|current_tags|customer|customer_address|discount_allocation|discount_application|external_video|font|forloop|form|fulfillment|gift_card|handle|images??|line_item|link|linklists??|location|localization|metafield|model|model_source|order|page|page_description|page_image|page_title|pages|paginate|part|policy|powered_by_link|predictive_search|product|product_option|product_variant|recommendations|request|routes|scripts??|search|section|selling_plan|selling_plan_allocation|selling_plan_group|settings|shipping_method|shop|shop_locale|store_availability|tablerow|tax_line|template|theme|transaction|unit_price_measurement|variant|video|video_source)\\\\b","name":"variable.language.liquid"},{"match":"((?<=\\\\w:\\\\s)\\\\w+)","name":"variable.parameter.liquid"},{"begin":"(?<=\\\\w)\\\\[","beginCaptures":{"0":{"name":"punctuation.section.brackets.begin.liquid"}},"end":"]","endCaptures":{"0":{"name":"punctuation.section.brackets.end.liquid"}},"name":"meta.brackets.liquid","patterns":[{"include":"#string"}]},{"match":"(?<=([]\\\\w])\\\\.)([-\\\\w]+\\\\??)","name":"variable.other.member.liquid"},{"match":"(?<=\\\\w)\\\\.(?=\\\\w)","name":"punctuation.accessor.liquid"},{"match":"(?i)[_a-z](\\\\w|-(?!}}))*","name":"variable.other.liquid"}]}},"scopeName":"text.html.liquid","embeddedLangs":["html","css","json","javascript"]}`)),m=[...t,...i,...a,...n,d];export{m as default};
|
|
2
|
-
//# sourceMappingURL=liquid-
|
|
1
|
+
import{a}from"./chunk-2NQMCQ7O.js";import{a as t}from"./chunk-OHRY6PPX.js";import{a as n}from"./chunk-QP24BTOT.js";import{a as i}from"./chunk-YTXGYW4C.js";import{d as e}from"./chunk-LPD7BHH5.js";e();var d=Object.freeze(JSON.parse(`{"displayName":"Liquid","fileTypes":["liquid"],"foldingStartMarker":"\\\\{%-?\\\\s*(capture|case|comment|form??|if|javascript|paginate|schema|style)[^%()}]+%}","foldingStopMarker":"\\\\{%\\\\s*(end(?:capture|case|comment|form??|if|javascript|paginate|schema|style))[^%()}]+%}","injections":{"L:meta.embedded.block.js, L:meta.embedded.block.css, L:meta.embedded.block.html, L:string.quoted":{"patterns":[{"include":"#injection"}]}},"name":"liquid","patterns":[{"include":"#core"}],"repository":{"attribute":{"begin":"\\\\w+:","beginCaptures":{"0":{"name":"entity.other.attribute-name.liquid"}},"end":"(?=,|%}|}}|\\\\|)","patterns":[{"include":"#value_expression"}]},"attribute_liquid":{"begin":"\\\\w+:","beginCaptures":{"0":{"name":"entity.other.attribute-name.liquid"}},"end":"(?=[,|])|$","patterns":[{"include":"#value_expression"}]},"comment_block":{"begin":"\\\\{%-?\\\\s*comment\\\\s*-?%}","end":"\\\\{%-?\\\\s*endcomment\\\\s*-?%}","name":"comment.block.liquid","patterns":[{"include":"#comment_block"},{"match":"(.(?!\\\\{%-?\\\\s*((?:|end)comment)\\\\s*-?%}))*."}]},"core":{"patterns":[{"include":"#raw_tag"},{"include":"#doc_tag"},{"include":"#comment_block"},{"include":"#style_codefence"},{"include":"#stylesheet_codefence"},{"include":"#json_codefence"},{"include":"#javascript_codefence"},{"include":"#object"},{"include":"#tag"},{"include":"text.html.basic"}]},"doc_tag":{"begin":"\\\\{%-?\\\\s*(doc)\\\\s*-?%}","beginCaptures":{"0":{"name":"meta.tag.liquid"},"1":{"name":"entity.name.tag.doc.liquid"}},"contentName":"comment.block.documentation.liquid","end":"\\\\{%-?\\\\s*(enddoc)\\\\s*-?%}","endCaptures":{"0":{"name":"meta.tag.liquid"},"1":{"name":"entity.name.tag.doc.liquid"}},"name":"meta.block.doc.liquid","patterns":[{"include":"#liquid_doc_description_tag"},{"include":"#liquid_doc_param_tag"},{"include":"#liquid_doc_example_tag"},{"include":"#liquid_doc_prompt_tag"},{"include":"#liquid_doc_fallback_tag"}]},"filter":{"captures":{"1":{"name":"support.function.liquid"}},"match":"\\\\|\\\\s*((?![.0-9])[-0-9A-Z_a-z]+:?)\\\\s*"},"injection":{"patterns":[{"include":"#raw_tag"},{"include":"#comment_block"},{"include":"#object"},{"include":"#tag_injection"}]},"invalid_range":{"match":"\\\\((.(?!\\\\.\\\\.))+\\\\)","name":"invalid.illegal.range.liquid"},"javascript_codefence":{"begin":"(\\\\{%-?)\\\\s*(javascript)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.javascript.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.javascript.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.js","end":"(\\\\{%-?)\\\\s*(endjavascript)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.javascript.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.javascript.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.javascript.liquid","patterns":[{"include":"source.js"}]},"json_codefence":{"begin":"(\\\\{%-?)\\\\s*(schema)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.schema.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.schema.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.json","end":"(\\\\{%-?)\\\\s*(endschema)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.schema.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.schema.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.schema.liquid","patterns":[{"include":"source.json"}]},"language_constant":{"match":"\\\\b(false|true|nil|blank)\\\\b|empty(?!\\\\?)","name":"constant.language.liquid"},"liquid_doc_description_tag":{"begin":"(@description)\\\\b\\\\s*","beginCaptures":{"0":{"name":"comment.block.documentation.liquid"},"1":{"name":"storage.type.class.liquid"}},"contentName":"string.quoted.single.liquid","end":"(?=@prompt|@example|@param|@description|\\\\{%-?\\\\s*enddoc\\\\s*-?%})"},"liquid_doc_example_tag":{"begin":"(@example)\\\\b\\\\s*","beginCaptures":{"0":{"name":"comment.block.documentation.liquid"},"1":{"name":"storage.type.class.liquid"}},"contentName":"meta.embedded.block.liquid","end":"(?=@prompt|@example|@param|@description|\\\\{%-?\\\\s*enddoc\\\\s*-?%})","patterns":[{"include":"#core"}]},"liquid_doc_fallback_tag":{"captures":{"1":{"name":"comment.block.liquid"}},"match":"(@\\\\w+)\\\\b"},"liquid_doc_param_tag":{"captures":{"1":{"name":"storage.type.class.liquid"},"2":{"name":"entity.name.type.instance.liquid"},"3":{"name":"variable.other.liquid"},"4":{"name":"string.quoted.single.liquid"}},"match":"(@param)\\\\s+(?:(\\\\{[^}]*}?)\\\\s+)?(\\\\[?[A-Z_a-z][-\\\\w]*]?)?(?:\\\\s+(.*))?"},"liquid_doc_prompt_tag":{"begin":"(@prompt)\\\\b\\\\s*","beginCaptures":{"0":{"name":"comment.block.documentation.liquid"},"1":{"name":"storage.type.class.liquid"}},"contentName":"string.quoted.single.liquid","end":"(?=@prompt|@example|@param|@description|\\\\{%-?\\\\s*enddoc\\\\s*-?%})"},"number":{"match":"(([-+])\\\\s*)?[0-9]+(\\\\.[0-9]+)?","name":"constant.numeric.liquid"},"object":{"begin":"(?<!comment %})(?<!comment -%})(?<!comment%})(?<!comment-%})(?<!raw %})(?<!raw -%})(?<!raw%})(?<!raw-%})\\\\{\\\\{-?","beginCaptures":{"0":{"name":"punctuation.definition.tag.begin.liquid"}},"end":"-?}}","endCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.object.liquid","patterns":[{"include":"#filter"},{"include":"#attribute"},{"include":"#value_expression"}]},"operator":{"captures":{"1":{"name":"keyword.operator.expression.liquid"}},"match":"(?:(?<=\\\\s)|\\\\b)(==|!=|[<>]|>=|<=|or|and|contains)(?:(?=\\\\s)|\\\\b)"},"range":{"begin":"\\\\(","beginCaptures":{"0":{"name":"punctuation.section.parens.begin.liquid"}},"end":"\\\\)","endCaptures":{"0":{"name":"punctuation.section.parens.end.liquid"}},"name":"meta.range.liquid","patterns":[{"match":"\\\\.\\\\.","name":"punctuation.range.liquid"},{"include":"#variable_lookup"},{"include":"#number"}]},"raw_tag":{"begin":"\\\\{%-?\\\\s*(raw)\\\\s*-?%}","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"contentName":"string.unquoted.liquid","end":"\\\\{%-?\\\\s*(endraw)\\\\s*-?%}","endCaptures":{"1":{"name":"entity.name.tag.liquid"}},"name":"meta.entity.tag.raw.liquid","patterns":[{"match":"(.(?!\\\\{%-?\\\\s*endraw\\\\s*-?%}))*."}]},"string":{"patterns":[{"include":"#string_single"},{"include":"#string_double"}]},"string_double":{"begin":"\\"","end":"\\"","name":"string.quoted.double.liquid"},"string_single":{"begin":"'","end":"'","name":"string.quoted.single.liquid"},"style_codefence":{"begin":"(\\\\{%-?)\\\\s*(style)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.style.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.css","end":"(\\\\{%-?)\\\\s*(endstyle)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.style.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.style.liquid","patterns":[{"include":"source.css"}]},"stylesheet_codefence":{"begin":"(\\\\{%-?)\\\\s*(stylesheet)\\\\s*(-?%})","beginCaptures":{"0":{"name":"meta.tag.metadata.style.start.liquid"},"1":{"name":"punctuation.definition.tag.begin.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.begin.liquid"}},"contentName":"meta.embedded.block.css","end":"(\\\\{%-?)\\\\s*(endstylesheet)\\\\s*(-?%})","endCaptures":{"0":{"name":"meta.tag.metadata.style.end.liquid"},"1":{"name":"punctuation.definition.tag.end.liquid"},"2":{"name":"entity.name.tag.style.liquid"},"3":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.block.style.liquid","patterns":[{"include":"source.css"}]},"tag":{"begin":"(?<!comment %})(?<!comment -%})(?<!comment%})(?<!comment-%})(?<!raw %})(?<!raw -%})(?<!raw%})(?<!raw-%})\\\\{%-?","beginCaptures":{"0":{"name":"punctuation.definition.tag.begin.liquid"}},"end":"-?%}","endCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.tag.liquid","patterns":[{"include":"#tag_body"}]},"tag_assign":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(assign|echo)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"(?=%})","name":"meta.entity.tag.liquid","patterns":[{"include":"#filter"},{"include":"#attribute"},{"include":"#value_expression"}]},"tag_assign_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(assign|echo)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"$","name":"meta.entity.tag.liquid","patterns":[{"include":"#filter"},{"include":"#attribute_liquid"},{"include":"#value_expression"}]},"tag_body":{"patterns":[{"include":"#tag_liquid"},{"include":"#tag_assign"},{"include":"#tag_comment_inline"},{"include":"#tag_case"},{"include":"#tag_conditional"},{"include":"#tag_for"},{"include":"#tag_paginate"},{"include":"#tag_render"},{"include":"#tag_tablerow"},{"include":"#tag_expression"}]},"tag_case":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(case|when)\\\\b","beginCaptures":{"1":{"name":"keyword.control.case.liquid"}},"end":"(?=%})","name":"meta.entity.tag.case.liquid","patterns":[{"include":"#value_expression"}]},"tag_case_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(case|when)\\\\b","beginCaptures":{"1":{"name":"keyword.control.case.liquid"}},"end":"$","name":"meta.entity.tag.case.liquid","patterns":[{"include":"#value_expression"}]},"tag_comment_block_liquid":{"begin":"^\\\\s*(comment)\\\\b","end":"^\\\\s*(endcomment)\\\\b","name":"comment.block.liquid","patterns":[{"include":"#tag_comment_block_liquid"},{"match":"^\\\\s*(?!((?:|end)comment)).*"}]},"tag_comment_inline":{"begin":"#","end":"(?=%})","name":"comment.line.number-sign.liquid"},"tag_comment_inline_liquid":{"begin":"^\\\\s*#.*","end":"$","name":"comment.line.number-sign.liquid"},"tag_conditional":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(if|elsif|unless)\\\\b","beginCaptures":{"1":{"name":"keyword.control.conditional.liquid"}},"end":"(?=%})","name":"meta.entity.tag.conditional.liquid","patterns":[{"include":"#value_expression"}]},"tag_conditional_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(if|elsif|unless)\\\\b","beginCaptures":{"1":{"name":"keyword.control.conditional.liquid"}},"end":"$","name":"meta.entity.tag.conditional.liquid","patterns":[{"include":"#value_expression"}]},"tag_expression":{"patterns":[{"include":"#tag_expression_without_arguments"},{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(\\\\w+)","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"(?=%})","name":"meta.entity.tag.liquid","patterns":[{"include":"#value_expression"}]}]},"tag_expression_liquid":{"patterns":[{"include":"#tag_expression_without_arguments"},{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(\\\\w+)","beginCaptures":{"1":{"name":"entity.name.tag.liquid"}},"end":"$","name":"meta.entity.tag.liquid","patterns":[{"include":"#value_expression"}]}]},"tag_expression_without_arguments":{"patterns":[{"captures":{"1":{"name":"keyword.control.conditional.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(end(?:unless|if))\\\\b"},{"captures":{"1":{"name":"keyword.control.loop.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(end(?:for|tablerow|paginate))\\\\b"},{"captures":{"1":{"name":"keyword.control.case.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(endcase)\\\\b"},{"captures":{"1":{"name":"keyword.control.other.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(capture|case|comment|form??|if|javascript|paginate|schema|style)\\\\b"},{"captures":{"1":{"name":"keyword.control.other.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(end(?:capture|case|comment|form??|if|javascript|paginate|schema|style))\\\\b"},{"captures":{"1":{"name":"keyword.control.other.liquid"}},"match":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(else|break|continue)\\\\b"}]},"tag_for":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(for)\\\\b","beginCaptures":{"1":{"name":"keyword.control.for.liquid"}},"end":"(?=%})","name":"meta.entity.tag.for.liquid","patterns":[{"include":"#tag_for_body"}]},"tag_for_body":{"patterns":[{"match":"\\\\b(in|reversed)\\\\b","name":"keyword.control.liquid"},{"match":"\\\\b(offset|limit):","name":"keyword.control.liquid"},{"include":"#value_expression"}]},"tag_for_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(for)\\\\b","beginCaptures":{"1":{"name":"keyword.control.for.liquid"}},"end":"$","name":"meta.entity.tag.for.liquid","patterns":[{"include":"#tag_for_body"}]},"tag_injection":{"begin":"(?<!comment %})(?<!comment -%})(?<!comment%})(?<!comment-%})(?<!raw %})(?<!raw -%})(?<!raw%})(?<!raw-%})\\\\{%-?(?!-?\\\\s*(end(?:style|javascript|comment|raw)))","beginCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"end":"-?%}","endCaptures":{"0":{"name":"punctuation.definition.tag.end.liquid"}},"name":"meta.tag.liquid","patterns":[{"include":"#tag_body"}]},"tag_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(liquid)\\\\b","beginCaptures":{"1":{"name":"keyword.control.liquid.liquid"}},"end":"(?=%})","name":"meta.entity.tag.liquid.liquid","patterns":[{"include":"#tag_comment_block_liquid"},{"include":"#tag_comment_inline_liquid"},{"include":"#tag_assign_liquid"},{"include":"#tag_case_liquid"},{"include":"#tag_conditional_liquid"},{"include":"#tag_for_liquid"},{"include":"#tag_paginate_liquid"},{"include":"#tag_render_liquid"},{"include":"#tag_tablerow_liquid"},{"include":"#tag_expression_liquid"}]},"tag_paginate":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(paginate)\\\\b","beginCaptures":{"1":{"name":"keyword.control.paginate.liquid"}},"end":"(?=%})","name":"meta.entity.tag.paginate.liquid","patterns":[{"include":"#tag_paginate_body"}]},"tag_paginate_body":{"patterns":[{"match":"\\\\b(by)\\\\b","name":"keyword.control.liquid"},{"include":"#value_expression"}]},"tag_paginate_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(paginate)\\\\b","beginCaptures":{"1":{"name":"keyword.control.paginate.liquid"}},"end":"$","name":"meta.entity.tag.paginate.liquid","patterns":[{"include":"#tag_paginate_body"}]},"tag_render":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(render)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.render.liquid"}},"end":"(?=%})","name":"meta.entity.tag.render.liquid","patterns":[{"include":"#tag_render_special_keywords"},{"include":"#attribute"},{"include":"#value_expression"}]},"tag_render_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(render)\\\\b","beginCaptures":{"1":{"name":"entity.name.tag.render.liquid"}},"end":"$","name":"meta.entity.tag.render.liquid","patterns":[{"include":"#tag_render_special_keywords"},{"include":"#attribute_liquid"},{"include":"#value_expression"}]},"tag_render_special_keywords":{"match":"\\\\b(with|as|for)\\\\b","name":"keyword.control.other.liquid"},"tag_tablerow":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(tablerow)\\\\b","beginCaptures":{"1":{"name":"keyword.control.tablerow.liquid"}},"end":"(?=%})","name":"meta.entity.tag.tablerow.liquid","patterns":[{"include":"#tag_tablerow_body"}]},"tag_tablerow_body":{"patterns":[{"match":"\\\\b(in)\\\\b","name":"keyword.control.liquid"},{"match":"\\\\b(cols|offset|limit):","name":"keyword.control.liquid"},{"include":"#value_expression"}]},"tag_tablerow_liquid":{"begin":"(?:(?<=\\\\{%)|(?<=\\\\{%-)|^)\\\\s*(tablerow)\\\\b","beginCaptures":{"1":{"name":"keyword.control.tablerow.liquid"}},"end":"$","name":"meta.entity.tag.tablerow.liquid","patterns":[{"include":"#tag_tablerow_body"}]},"value_expression":{"patterns":[{"captures":{"2":{"name":"invalid.illegal.filter.liquid"},"3":{"name":"invalid.illegal.filter.liquid"}},"match":"(\\\\[)(\\\\|)(?=[^]]*)(?=])"},{"match":"(?<=\\\\s)([-*+/])(?=\\\\s)","name":"invalid.illegal.filter.liquid"},{"include":"#language_constant"},{"include":"#operator"},{"include":"#invalid_range"},{"include":"#range"},{"include":"#number"},{"include":"#string"},{"include":"#variable_lookup"}]},"variable_lookup":{"patterns":[{"match":"\\\\b(additional_checkout_buttons|address|all_country_option_tags|all_products|articles??|block|blogs??|canonical_url|cart|checkout|collections??|comment|content_for_additional_checkout_buttons|content_for_header|content_for_index|content_for_layout|country_option_tags|currency|current_page|current_tags|customer|customer_address|discount_allocation|discount_application|external_video|font|forloop|form|fulfillment|gift_card|handle|images??|line_item|link|linklists??|location|localization|metafield|model|model_source|order|page|page_description|page_image|page_title|pages|paginate|part|policy|powered_by_link|predictive_search|product|product_option|product_variant|recommendations|request|routes|scripts??|search|section|selling_plan|selling_plan_allocation|selling_plan_group|settings|shipping_method|shop|shop_locale|store_availability|tablerow|tax_line|template|theme|transaction|unit_price_measurement|variant|video|video_source)\\\\b","name":"variable.language.liquid"},{"match":"((?<=\\\\w:\\\\s)\\\\w+)","name":"variable.parameter.liquid"},{"begin":"(?<=\\\\w)\\\\[","beginCaptures":{"0":{"name":"punctuation.section.brackets.begin.liquid"}},"end":"]","endCaptures":{"0":{"name":"punctuation.section.brackets.end.liquid"}},"name":"meta.brackets.liquid","patterns":[{"include":"#string"}]},{"match":"(?<=([]\\\\w])\\\\.)([-\\\\w]+\\\\??)","name":"variable.other.member.liquid"},{"match":"(?<=\\\\w)\\\\.(?=\\\\w)","name":"punctuation.accessor.liquid"},{"match":"(?i)[_a-z](\\\\w|-(?!}}))*","name":"variable.other.liquid"}]}},"scopeName":"text.html.liquid","embeddedLangs":["html","css","json","javascript"]}`)),m=[...t,...i,...a,...n,d];export{m as default};
|
|
2
|
+
//# sourceMappingURL=liquid-S4LVU77Y.js.map
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -324,7 +324,7 @@ interface TrackingClient {
|
|
|
324
324
|
}
|
|
325
325
|
|
|
326
326
|
/**
|
|
327
|
-
* A request-scoped
|
|
327
|
+
* A request-scoped Waniwani client with meta pre-attached.
|
|
328
328
|
*
|
|
329
329
|
* Available as `context.waniwani` inside `createTool` handlers and flow nodes
|
|
330
330
|
* when the server is wrapped with `withWaniwani()`.
|
|
@@ -397,7 +397,7 @@ type ToolHandlerContext = {
|
|
|
397
397
|
extra?: {
|
|
398
398
|
_meta?: Record<string, unknown>;
|
|
399
399
|
};
|
|
400
|
-
/** Session-scoped
|
|
400
|
+
/** Session-scoped Waniwani client — available when the server is wrapped with withWaniwani() */
|
|
401
401
|
waniwani?: ScopedWaniWaniClient;
|
|
402
402
|
};
|
|
403
403
|
type ToolConfig<TInput extends ZodRawShapeCompat> = {
|
|
@@ -464,7 +464,7 @@ type FieldSchemaInfo = {
|
|
|
464
464
|
};
|
|
465
465
|
|
|
466
466
|
/**
|
|
467
|
-
* Generic key-value store backed by the
|
|
467
|
+
* Generic key-value store backed by the Waniwani API.
|
|
468
468
|
*
|
|
469
469
|
* Values are stored as JSON objects (`Record<string, unknown>`) in the
|
|
470
470
|
* `/api/mcp/redis/*` endpoints. Tenant isolation is handled by the API key.
|
|
@@ -516,7 +516,7 @@ declare class MemoryKvStore<T = Record<string, unknown>> implements KvStore<T> {
|
|
|
516
516
|
/**
|
|
517
517
|
* Server-side flow state store.
|
|
518
518
|
*
|
|
519
|
-
* Flow state is stored via the
|
|
519
|
+
* Flow state is stored via the Waniwani API, keyed by session ID.
|
|
520
520
|
* Config comes from env vars (WANIWANI_API_KEY, WANIWANI_API_URL).
|
|
521
521
|
*/
|
|
522
522
|
|
|
@@ -731,7 +731,7 @@ type NodeContext<TState> = {
|
|
|
731
731
|
interrupt: TypedInterrupt<TState>;
|
|
732
732
|
/** Create a widget signal — pause and show a UI widget */
|
|
733
733
|
showWidget: TypedShowWidget<TState>;
|
|
734
|
-
/** Session-scoped
|
|
734
|
+
/** Session-scoped Waniwani client — available when the server is wrapped with withWaniwani() */
|
|
735
735
|
waniwani?: ScopedWaniWaniClient;
|
|
736
736
|
};
|
|
737
737
|
/**
|
|
@@ -1093,7 +1093,7 @@ declare function createFlow<const TSchema extends Record<string, z.ZodType>>(con
|
|
|
1093
1093
|
|
|
1094
1094
|
/**
|
|
1095
1095
|
* Mark a Zod schema as PII — its value will be replaced with `"REDACTED"` in
|
|
1096
|
-
* any `tool.called` event payload sent to the
|
|
1096
|
+
* any `tool.called` event payload sent to the Waniwani API. The handler still
|
|
1097
1097
|
* receives the original value; only the tracked copy is scrubbed.
|
|
1098
1098
|
*
|
|
1099
1099
|
* Apply at the end of the schema chain so the marker is attached to the final
|
|
@@ -1126,7 +1126,7 @@ declare function createFlowTestHarness(flow: RegisteredFlow, options?: {
|
|
|
1126
1126
|
* Server-side API route handler for widget tracking events.
|
|
1127
1127
|
*
|
|
1128
1128
|
* Receives batched events from the `useWaniwani` React hook and forwards them
|
|
1129
|
-
* to the
|
|
1129
|
+
* to the Waniwani backend using the server-side SDK.
|
|
1130
1130
|
*
|
|
1131
1131
|
* @example Next.js App Router
|
|
1132
1132
|
* ```typescript
|
|
@@ -1142,19 +1142,19 @@ declare function createFlowTestHarness(flow: RegisteredFlow, options?: {
|
|
|
1142
1142
|
* ```
|
|
1143
1143
|
*/
|
|
1144
1144
|
interface TrackingRouteOptions {
|
|
1145
|
-
/** API key for the
|
|
1145
|
+
/** API key for the Waniwani backend. Defaults to WANIWANI_API_KEY env var. */
|
|
1146
1146
|
apiKey?: string;
|
|
1147
|
-
/** Base URL for the
|
|
1147
|
+
/** Base URL for the Waniwani backend. Defaults to https://app.waniwani.ai. */
|
|
1148
1148
|
apiUrl?: string;
|
|
1149
1149
|
}
|
|
1150
1150
|
/**
|
|
1151
1151
|
* Creates a POST handler that receives tracking events from `useWaniwani`
|
|
1152
|
-
* and forwards them to the
|
|
1152
|
+
* and forwards them to the Waniwani backend.
|
|
1153
1153
|
*/
|
|
1154
1154
|
declare function createTrackingRoute(options?: TrackingRouteOptions): (request: Request) => Promise<Response>;
|
|
1155
1155
|
|
|
1156
1156
|
/**
|
|
1157
|
-
*
|
|
1157
|
+
* Waniwani SDK Client
|
|
1158
1158
|
*
|
|
1159
1159
|
* Extends with each module:
|
|
1160
1160
|
* - TrackingClient: track(), flush(), shutdown()
|
|
@@ -1184,7 +1184,7 @@ type UnknownRecord = Record<string, unknown>;
|
|
|
1184
1184
|
*/
|
|
1185
1185
|
type WithWaniwaniOptions = {
|
|
1186
1186
|
/**
|
|
1187
|
-
* The
|
|
1187
|
+
* The Waniwani client instance. When omitted, a client is created
|
|
1188
1188
|
* automatically using the global config registered by `defineConfig()`,
|
|
1189
1189
|
* falling back to env vars.
|
|
1190
1190
|
*/
|
|
@@ -1207,7 +1207,7 @@ type WithWaniwaniOptions = {
|
|
|
1207
1207
|
onError?: (error: Error) => void;
|
|
1208
1208
|
/**
|
|
1209
1209
|
* Inject widget tracking config into tool response `_meta.waniwani` so browser
|
|
1210
|
-
* widgets can send events directly to the
|
|
1210
|
+
* widgets can send events directly to the Waniwani backend.
|
|
1211
1211
|
*
|
|
1212
1212
|
* Always injects `endpoint`. Injects `token` when an API key is configured
|
|
1213
1213
|
* and token minting succeeds.
|
|
@@ -1218,7 +1218,7 @@ type WithWaniwaniOptions = {
|
|
|
1218
1218
|
/**
|
|
1219
1219
|
* List of field names to strip from known location `_meta` entries
|
|
1220
1220
|
* (`openai/userLocation`, `waniwani/geoLocation`, `waniwani/userLocation`)
|
|
1221
|
-
* before events are sent to the
|
|
1221
|
+
* before events are sent to the Waniwani API. Applied to both the
|
|
1222
1222
|
* request-level `_meta` and any `_meta` on the tool response.
|
|
1223
1223
|
*
|
|
1224
1224
|
* Pass e.g. `["latitude", "longitude"]` to drop coordinates only, or
|
|
@@ -1252,7 +1252,7 @@ type WithWaniwaniOptions = {
|
|
|
1252
1252
|
*
|
|
1253
1253
|
* When `injectWidgetToken` is enabled (default), tracking config is injected
|
|
1254
1254
|
* into tool response `_meta.waniwani` so browser widgets can post events
|
|
1255
|
-
* directly to the
|
|
1255
|
+
* directly to the Waniwani backend without a server-side proxy.
|
|
1256
1256
|
*
|
|
1257
1257
|
* Widget metadata declared on the tool **definition** (e.g. skybridge's
|
|
1258
1258
|
* `registerWidget`, raw MCP `_meta["ui/resourceUri"]` / `_meta.ui.resourceUri`,
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var _="__start__",F="__end__",be=Symbol.for("waniwani.flow.interrupt"),Ce=Symbol.for("waniwani.flow.widget");function _e(e,t){let n=t?.context,o=[];for(let[r,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let s=i;o.push({question:s.question,field:r,suggestions:s.suggestions,context:s.context,validate:s.validate})}return{__type:be,questions:o,context:n}}function Fe(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,o=n?e.tool:e,r=n?e:t??{};if(r.description!==void 0){let p=typeof o=="string"?o:o.id;throw new Error(`showWidget("${p}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${p}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=r;return{__type:Ce,tool:typeof o=="string"?o:o.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Pe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===be}function
|
|
1
|
+
var _="__start__",F="__end__",be=Symbol.for("waniwani.flow.interrupt"),Ce=Symbol.for("waniwani.flow.widget");function _e(e,t){let n=t?.context,o=[];for(let[r,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let s=i;o.push({question:s.question,field:r,suggestions:s.suggestions,context:s.context,validate:s.validate})}return{__type:be,questions:o,context:n}}function Fe(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,o=n?e.tool:e,r=n?e:t??{};if(r.description!==void 0){let p=typeof o=="string"?o:o.id;throw new Error(`showWidget("${p}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${p}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=r;return{__type:Ce,tool:typeof o=="string"?o:o.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Pe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===be}function Ne(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ce}import{z as W}from"zod";function G(e){return{priceShown:({amount:t,currency:n,itemId:o,label:r,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:o,label:r},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:o,...r})=>e({event:"option_selected",properties:{id:t,amount:n,currency:o},...r}),lead:t=>{let{source:n,...o}=t??{};return e({event:"lead",properties:{source:n},...o})},converted:({amount:t,currency:n,occurredAt:o,...r})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:o},...r})}}var le="waniwani/client";function Z(e){if(typeof e=="object"&&e!==null)return e[le]}function Ae(e,t,n){let o=r=>e.track({...r,meta:{...t,...r.meta}});return{track:Object.assign(o,G(o)),identify(r,i){return e.identify(r,i,t)},kb:e.kb,_config:n}}function q(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.length>0)return o}}var Ft=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Pt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Nt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],At=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Wt=["correlationId","openai/requestId"];var D="waniwani/flow";function P(e){return e?q(e,Ft):void 0}function Me(e){return e?q(e,Pt):void 0}function Ue(e){return e?q(e,Nt):void 0}function Oe(e){return e?q(e,At):void 0}function De(e){return e?q(e,Wt):void 0}var Mt=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Ut=[{needle:"claude",source:"claude"}];function N(e,t){if(e){let o=e["waniwani/source"];if(typeof o=="string"&&o.length>0)return o;for(let{key:r,source:i}of Mt){let s=e[r];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let o=n.toLowerCase();for(let{needle:r,source:i}of Ut)if(o.includes(r))return i}}function We(e,t){let n=t.toLowerCase(),o=e[t]??e[n];if(o===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){o=e[i];break}}let r=Array.isArray(o)?o[0]:o;return typeof r=="string"&&r.length>0?r:void 0}function Ke(e){if(!e)return;let t=We(e,"user-agent"),n=We(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude"}function je(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function H(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null||typeof o!="object")return;o=o[r]}return o}function Ot(e,t,n){let o=t.split("."),r=o.pop();if(!r)return;let i=e;for(let s of o)(i[s]==null||typeof i[s]!="object"||Array.isArray(i[s]))&&(i[s]={}),i=i[s];i[r]=n}function Le(e,t){let n=t.split("."),o=n.pop();if(!o)return;let r=e;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}r!=null&&typeof r=="object"&&delete r[o]}function J(e){let t={};for(let[n,o]of Object.entries(e))n.includes(".")?Ot(t,n,o):o!==null&&typeof o=="object"&&!Array.isArray(o)?t=A(t,{[n]:o}):t[n]=o;return t}function A(e,t){let n={...e};for(let[o,r]of Object.entries(t))r!==null&&typeof r=="object"&&!Array.isArray(r)&&n[o]!==null&&typeof n[o]=="object"&&!Array.isArray(n[o])?n[o]=A(n[o],r):n[o]=r;return n}function qe(e){return e._zod?.def}function Dt(e){let t=e,n=!1;for(let o=0;o<8;o++){let r=qe(t);if(!r?.innerType)break;if(r.type==="optional"||r.type==="nullable"||r.type==="default"){n=!0,t=r.innerType;continue}break}return{inner:t,optional:n}}function $e(e){let{inner:t,optional:n}=Dt(e),o=t.description??e.description??void 0,r=qe(t),i=r?.type,s={type:"unknown",...o?{description:o}:{},...n?{optional:!0}:{}};return i==="enum"&&r?.entries?{...s,type:"enum",values:Object.keys(r.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function ue(e,t){if(!e||!t)return;if(t.includes(".")){let o=t.indexOf("."),r=t.slice(0,o),i=t.slice(o+1),s=e[r];if(!s)return;let p=je(s)?.[i];return p?$e(p):void 0}let n=e[t];if(n)return $e(n)}function pe(e){return e!=null&&e!==""}async function U(e,t){return e.type==="direct"?e.to:e.condition(t)}function He(e,t,n,o,r){if(e.every(c=>pe(H(o,c.field))))return null;let i=e.filter(c=>!pe(H(o,c.field))).map(c=>{let d=ue(r,c.field);return d?{...c,fieldSchema:d}:c}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:o,...s&&a?{field:a.field}:{}}}}async function B(e,t,n,o,r,i,s,a,p){let c=e,d={...t},l=[],u=50,R=0;for(;R++<u;){if(c===F)return{content:{status:"complete"},flowTokenContent:{state:d},nodesVisited:l};let f=n.get(c);if(!f)return{content:{status:"error",error:`Unknown node: "${c}"`},nodesVisited:l};a?.get(c)?.hideFromFunnel||l.push({id:c,at:new Date().toISOString()});try{let g=await f({state:d,meta:i,interrupt:_e,showWidget:Fe,waniwani:s});if(Pe(g)){for(let S of g.questions)S.validate&&r.set(`${c}:${S.field}`,S.validate);let y=He(g.questions,g.context,c,d,p);if(y)return{...y,nodesVisited:l};for(let S of g.questions){let x=r.get(`${c}:${S.field}`);if(x)try{let E=H(d,S.field),b=await x(E);b&&typeof b=="object"&&(d=A(d,b))}catch(E){let b=E instanceof Error?E.message:String(E);Le(d,S.field);let M=g.questions.map(O=>O.field===S.field?{...O,context:O.context?`ERROR: ${b}
|
|
2
2
|
|
|
3
|
-
${O.context}`:`ERROR: ${b}`}:O),Y=He(M,g.context,c,d,p);if(Y)return{...Y,nodesVisited:l};break}}let w=o.get(c);if(!w)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await U(w,d);continue}if(We(g)){let y=g.field;if(y&&pe(H(d,y))){let x=o.get(c);if(!x)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await U(x,d);continue}let w=y?ue(p,y):void 0,S=g.interactive!==!1;return{content:{status:"widget",tool:g.tool,...g.data!==void 0?{data:g.data}:{},description:S?`IMPORTANT: You MUST now call the ${g.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${g.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${g.tool} has been called, call this flow again with action:"continue".`,interactive:S,...y?{field:y}:{},...w?{fieldSchema:w}:{}},flowTokenContent:{step:c,state:d,field:y,widgetId:g.tool},nodesVisited:l}}d=N(d,g);let I=o.get(c);if(!I)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await U(I,d)}catch(T){return{content:{status:"error",error:T instanceof Error?T.message:String(T)},flowTokenContent:{step:c,state:d},nodesVisited:l}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:l}}function fe(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Be=new Map;async function Ve(e){let t=Be.get(e);if(t)return t;let n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("[WaniWani KV] WANIWANI_ENCRYPTION_KEY must be a base64-encoded 32-byte (256-bit) key.");let o=await globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return Be.set(e,o),o}async function ze(e,t){let n=await Ve(t),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:o},n,r);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(o).toString("base64")}}async function Ye(e,t){let n=await Ve(t),o=Buffer.from(e.ct,"base64"),r=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:r},n,o)}catch{throw new Error("[WaniWani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var Kt={debug:0,warn:1,error:2,none:3};function jt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Kt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function K(e,t){return t??jt()==="debug"?(...o)=>console.log(`[waniwani:${e}]`,...o):()=>{}}var Lt="@waniwani/sdk",$t="https://app.waniwani.ai",qt=K("kv"),j=class{get baseUrl(){return(process.env.WANIWANI_API_URL??$t).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}get encryptionKey(){return process.env.WANIWANI_ENCRYPTION_KEY}async get(t){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let n=await this.request("/api/mcp/redis/get",{key:t});if(n==null)return null;if(fe(n)){if(!this.encryptionKey)throw new Error("[WaniWani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return Ye(n,this.encryptionKey)}return n}async set(t,n,o){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let r=this.encryptionKey;qt(`set "${t}" \u2014 encryption ${r?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=r?await ze(n,r):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:o?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[WaniWani KV] delete failed for key:",t,n)}}async request(t,n){let o=`${this.baseUrl}${t}`,r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":Lt},body:JSON.stringify(n)});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${r.status}`)}return(await r.json()).data}};var X=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,o){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var V=class{store=new j;get(t){return this.store.get(t)}set(t,n,o){return this.store.set(t,n,o)}delete(t){return this.store.delete(t)}};function Ht(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Ge(e,t,n,o){let r=[];for(let[s,a]of t){let p=o.get(s);r.push({id:s,type:Ht(a),label:p?.label??s,...p?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:r,edges:i}}import{z as v}from"zod";var Ze=v.object({type:v.enum(["enum","string","number","boolean","object","array","unknown"]),values:v.array(v.string()).optional(),description:v.string().optional(),optional:v.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Bt=v.object({question:v.string(),field:v.string(),suggestions:v.array(v.string()).optional(),context:v.string().optional(),fieldSchema:Ze.optional()}).describe("One question within a multi-question interrupt."),ge={status:v.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:v.string().optional().describe("Single question to ask the user when status is interrupt."),field:v.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:Ze.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:v.array(v.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:v.array(Bt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:v.string().optional().describe("Private instruction context for the assistant."),tool:v.string().optional().describe("Widget tool to call when status is widget."),data:v.record(v.string(),v.unknown()).optional().describe("Input data to pass to the widget tool."),description:v.string().optional().describe("Instruction for rendering the requested widget."),interactive:v.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:v.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:v.string().optional().describe("Error message when status is error.")};function Je(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
|
|
4
|
-
`)}function we(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xe(e){let t=Qe(e),n=we(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Vt(e){let n=Qe(e).waniwani;return we(n)&&n.redacted===!0}function Qe(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return we(n)?n:{}}function et(e){if(!e)return[];let t=[];for(let[n,o]of Object.entries(e))Vt(o)&&t.push(n);return t}var Q="waniwani/redactedStateUpdateFields";function zt(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"",o=e.state&&Object.keys(e.state).length>0?
|
|
5
|
-
${s}`,p=e.store??Yt(t.id),c=new Map;async function d(f,T,g,I){if(f.action==="start"){let y=typeof f.intent=="string"?f.intent.trim():void 0;if(!y)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};if(f.intent=y,typeof f.context=="string"){let E=f.context.trim();f.context=E||void 0}let w=o.get(_);if(!w)return{content:{status:"error",error:"No start edge"}};let S=J(f.stateUpdates??{}),x=await U(w,S);return B(x,S,n,o,c,g,I,e.nodeOptions,t.state)}if(f.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await p.get(T)}catch(E){let b=E instanceof Error?E.message:String(E);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${b}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let w=y.state,S=y.step;if(!S)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let x=
|
|
6
|
-
`)}var L=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,o){let r=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?o?.label:t.label,a=typeof t=="string"?o?.hideFromFunnel:t.hideFromFunnel;if(r===_||r===F)throw new Error(`"${r}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(r))throw new Error(`Node "${r}" already exists`);return this.nodes.set(r,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(r,{label:s??r,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n,o){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:o,targets:[...n]}),this}graph(){return nt(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),o=new Map(this.edges);return tt({config:this.config,nodes:n,edges:o,store:t?.store,graph:()=>nt(n,o),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(_))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(_);if(t?.type==="direct"&&t.to!==F&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,o]of this.edges){if(n!==_&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(o.type==="direct"&&o.to!==F&&!this.nodes.has(o.to))throw new Error(`Edge from "${n}" references non-existent node: "${o.to}"`);if(o.type==="conditional"&&o.targets){for(let r of o.targets)if(r!==F&&!this.nodes.has(r))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${r}"`)}}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function ot(e){return new L(e)}function me(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function rt(e,t){let n=t?.stateStore,o=[],r=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...c)=>{o.push(c)}};await e.register(i);let s=o[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:r}};async function p(c){return{...c,decodedState:n?await n.get(r):null}}return{async start(c,d,l){let u=await s({action:"start",intent:c,...l?{context:l}:{},...d?{stateUpdates:d}:{}},a);return p(me(u))},async continueWith(c){let d=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return p(me(d))},async resetWith(c){let d=await s({action:"reset",stateUpdates:c},a);return p(me(d))},async lastState(){return n?n.get(r):null}}}var ee=class extends Error{constructor(n,o){super(n);this.status=o;this.name="WaniWaniError"}};var Gt="@waniwani/sdk";function it(e){let{apiUrl:t,apiKey:n}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function r(i,s,a){let p=o(),c=`${t.replace(/\/$/,"")}${s}`,d={Authorization:`Bearer ${p}`,"X-WaniWani-SDK":Gt},l={method:i,headers:d};a!==void 0&&(d["Content-Type"]="application/json",l.body=JSON.stringify(a));let u=await fetch(c,l);if(!u.ok){let f=await u.text().catch(()=>"");throw new ee(f||`KB API error: HTTP ${u.status}`,u.status)}return(await u.json()).data}return{async ingest(i){return r("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){return r("POST","/api/mcp/kb/search",{query:i,...s})},async sources(){return r("GET","/api/mcp/kb/sources")}}}import{existsSync as Zt,readFileSync as Jt}from"fs";import{resolve as Xt}from"path";var Qt="waniwani.json",$;function st(){if($!==void 0)return $;try{let e=Xt(process.cwd(),Qt);if(!Zt(e))return $=null,null;let t=Jt(e,"utf-8");return $=JSON.parse(t),$}catch{return $=null,null}}var en="__waniwani_config__";function at(){return globalThis[en]}var tn="@waniwani/sdk";function ne(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??ct,r=rn(e),i=te(e.meta),s=te(e.metadata),a=sn(e,i),p=C(e.eventId)??o(),c=an(e.timestamp,n),d=C(e.source)??W(i)??t.source??tn,l=he(e)?{...e}:void 0,u={...s};return Object.keys(i).length>0&&(u.meta=i),l&&(u.rawLegacy=l),{id:p,type:"mcp.event",name:r,source:d,timestamp:c,correlation:a,properties:nn(e,r),metadata:u,rawLegacy:l}}function ct(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function nn(e,t){if(!he(e))return te(e.properties);let n=on(e,t),o=te(e.properties);return{...n,...o}}function on(e,t){switch(t){case"tool.called":{let n={};return C(e.toolName)&&(n.name=e.toolName),C(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),C(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return C(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),C(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function rn(e){return he(e)?e.eventType:e.event}function sn(e,t){let n=C(e.requestId)??Me(t),o=C(e.sessionId)??P(t),r=C(e.traceId)??Ue(t),i=C(e.externalUserId)??Oe(t),s=C(e.correlationId)??De(t)??n,a={};return o&&(a.sessionId=o),r&&(a.traceId=r),n&&(a.requestId=n),s&&(a.correlationId=s),i&&(a.externalUserId=i),a}function an(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function te(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function C(e){if(typeof e=="string"&&e.trim().length!==0)return e}function he(e){return"eventType"in e}var cn="/api/mcp/events/v2/batch";var dt="@waniwani/sdk",dn=new Set([401,403]),ln=new Set([408,425,429,500,502,503,504]);function lt(e){return new ye(e)}var ye=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=fn(t.apiUrl,t.endpointPath??cn),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(o=>setTimeout(o,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[WaniWani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,o=this.flush();if(!Number.isFinite(n)||n<=0)return await o,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([o.then(()=>"flushed"),this.sleep(n).then(()=>r)])===r?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,o=t;for(;o.length>0&&!this.isStopped;){this.inFlightCount=o.length;let r=await this.sendBatchOnce(o);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,o.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",o.length,r.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",o.length,r.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}o=r.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":dt},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:gn(i)}}if(dn.has(n.status))return{kind:"auth",status:n.status};if(ln.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await pn(n);if(!o?.rejected||o.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,o.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:dt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let o=new Map(t.map(s=>[s.id,s])),r=[],i=[];for(let s of n){let a=o.get(s.eventId);if(a){if(un(s)){r.push(a);continue}i.push(a)}}return{retryable:r,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let o=this.buffer.length;this.buffer.splice(0,o),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+o)}};function un(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function pn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function fn(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function gn(e){return e instanceof Error?e.message:String(e)}function ut(e){let{apiUrl:t,apiKey:n,tracking:o}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?lt({apiUrl:t,apiKey:n,endpointPath:o.endpointPath,flushIntervalMs:o.flushIntervalMs,maxBatchSize:o.maxBatchSize,maxBufferSize:o.maxBufferSize,maxRetries:o.maxRetries,retryBaseDelayMs:o.retryBaseDelayMs,retryMaxDelayMs:o.retryMaxDelayMs,shutdownTimeoutMs:o.shutdownTimeoutMs}):void 0;function s(d){r();let l=ne(d);return!l.correlation.sessionId&&!l.correlation.externalUserId&&console.warn(`[waniwani] event "${l.name}" has no sessionId or externalUserId; the ingest API requires one and will reject it.`),i?.enqueue(l),{eventId:l.id}}let a=async d=>s(d),p=Object.assign(a,G(a)),c={async identify(d,l,u){r();let R=ne({event:"user.identified",externalUserId:d,properties:l,meta:u});return i?.enqueue(R),{eventId:R.id}},track:p,async flush(){r(),await i?.flush()},async shutdown(d){return r(),await i?.shutdown({timeoutMs:d?.timeoutMs??o.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&wn(c,o.shutdownTimeoutMs),c}function wn(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function oe(e){let n=e??st()??at(),o=n?.apiUrl??"https://app.waniwani.ai",r=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:o,apiKey:r,tracking:i},a=ut(s),p=it(s);return{...a,kb:p,_config:s}}function mn(e){let t=e.event_type??"widget_click",o=t.startsWith("widget_")?t:`widget_${t}`,r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{event:o,properties:r,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function hn(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function o(){return n||(n=oe(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=o(),p=[];for(let c of s.events){let d=mn(c),l=await a.track(d);p.push(l.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:p.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let p=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:p}),{status:500,headers:{"Content-Type":"application/json"}})}}}var Te=K("widget-token"),yn=120*1e3,re=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-yn?this.cached.token:this.pending?this.pending:(this.pending=this.mint(t,n).finally(()=>{this.pending=null}),this.pending)}async mint(t,n){let o=Tn(this.config.apiUrl,"/api/mcp/widget-tokens");Te("minting token from",o);let r={};t&&(r.sessionId=t),n&&(r.traceId=n);try{let i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)});if(Te("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,p=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(p)?null:(this.cached={token:a.token,expiresAt:p},a.token)}catch(i){return Te("mint failed:",i),null}}};function Tn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function pt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function Sn(e){return pt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function ft(e){if(e.length===0)return null;let t=[...e].sort((r,i)=>r.flowId.localeCompare(i.flowId)),n=await pt(JSON.stringify(t.map(r=>({flowId:r.flowId,nodes:r.nodes,edges:r.edges})))),o=await Promise.all(e.map(async r=>({flowId:r.flowId,title:r.title,configHash:await Sn(r),nodes:r.nodes,edges:r.edges})));return{compositeHash:n,flows:o}}var gt="waniwani/sessionId",ie="waniwani/geoLocation",se="waniwani/userLocation",kn="openai/userLocation",vn=[kn,ie,se];function wt(e,t){if(t.length===0)return e;let n;for(let o of vn){let r=e[o];if(!k(r))continue;let i;for(let s of t)s in r&&(i||(i={...r}),delete i[s]);i&&(n||(n={...e}),n[o]=i)}return n??e}function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function z(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function Se(e){if(!k(e))return;let t=e.content;return Array.isArray(t)?t.find(o=>k(o)&&o.type==="text"&&typeof o.text=="string")?.text:void 0}function Rn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ke(e,t,n,o,r,i){let s=Rn(e,n.toolType),a=n.stripLocationFields,p=a&&a.length>0,c=z(t),d=c&&p?wt(c,a):c,l=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,u=p&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:wt(i.output._meta,a)}:i?.output,f=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[D],T=f&&d?{...d,[D]:f}:f?{[D]:f}:d,g=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,I=g&&!P(T??void 0)?{...T??{},"waniwani/sessionId":g}:T;return{event:"tool.called",properties:{name:e,type:s,...o??{},...l!==void 0&&{input:l},...u!==void 0&&{output:u}},meta:I,source:W(I??d,r),metadata:{...n.metadata??{},...r&&{clientInfo:r},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function ve(e,t,n){try{await e.track(t)}catch(o){n?.(xe(o))}}async function Re(e,t){try{await e.flush()}catch(n){t?.(xe(n))}}async function ht(e,t,n,o,r,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s.waniwani)?s.waniwani:void 0,p={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let u=await t.getToken();u&&(p.token=u)}catch(u){r?.(xe(u))}let c=P(s);c&&(p.sessionId||(p.sessionId=c));let d=St(s);d!==void 0&&(p.geoLocation||(p.geoLocation=d));let l=W(z(o),i);l&&!p.source&&(p.source=l),s.waniwani=p}var mt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function yt(e,t){if(!t||!k(e))return;let n=!1;for(let r of mt)if(r in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let o=e._meta;for(let r of mt)r in t&&(r in o||(o[r]=t[r]))}function Tt(e,t){let n=z(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let o=e._meta,r=P(n);r&&!o[gt]&&(o[gt]=r);let i=St(n);i&&(o[ie]||(o[ie]=i),o[se]||(o[se]=i))}function St(e){if(!e)return;let t=e[ie]??e[se];if(k(t)||typeof t=="string")return t}function xe(e){return e instanceof Error?e:new Error(String(e))}function kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(kt(e.requestInfo)){let t=e.requestInfo.headers;if(kt(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let o=n["mcp-session-id"];if(typeof o=="string"&&o)return o;let r=n["x-waniwani-session-id"];if(typeof r=="string"&&r)return r}}}var xt=Symbol.for("waniwani.wrappedHandler"),ae=K("mcp"),It="https://app.waniwani.ai",xn="REDACTED";function In(e){if(!e)return;let t=e[Q];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(o=>typeof o=="string"));if(n.size!==0)return o=>{if(!k(o))return o;let r=o.stateUpdates;if(!k(r))return o;let i=!1,s={...r};for(let a of n)a in s&&(s[a]=xn,i=!0);return i?{...o,stateUpdates:s}:o}}function Rt(e,t,n,o){let{server:r,tracker:i,opts:s,tokenCache:a,injectToken:p}=n,c=s.applyFieldRedactions===!0?In(o):void 0,d=async(l,u)=>{let R=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},f=z(u)??{},T=r.server?.getClientVersion?.();if(!P(f)&&k(u)){let w=vt(u);w&&(f["waniwani/sessionId"]=w,u._meta=f)}if(!W(f)&&k(u)){let w=u.requestInfo?.headers,S=W(f,T)??Ke(w);S&&(f["waniwani/source"]=S,u._meta=f)}let I=Ne(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(u)&&(u[le]=I);let y=performance.now();try{let w=await t(l,u),S=Math.round(performance.now()-y);ae(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let x=k(w)&&w.isError===!0;if(x){let E=Se(w);console.error(`[waniwani] Tool "${e}" returned error${E?`: ${E}`:""}`)}return await ve(i,ke(e,u,R,{durationMs:S,status:x?"error":"ok",...x&&{errorMessage:Se(w)??"Unknown tool error"}},T,{input:l,output:w}),s.onError),ae(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Re(i,s.onError),Tt(w,u),yt(w,o),p&&(await ht(w,a,i._config.apiUrl??It,u,s.onError,T),ae(`tool "${e}" widget config injected`)),ae(`tool "${e}" post-processing complete, returning result`),w}catch(w){let S=Math.round(performance.now()-y);throw await ve(i,ke(e,u,R,{durationMs:S,status:"error",errorMessage:w instanceof Error?w.message:String(w)},T,{input:l}),s.onError),s.flushAfterToolCall&&await Re(i,s.onError),w}};return d[xt]=!0,d}async function En(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let o=t??{},r=o.client??oe(),i=o.injectWidgetToken!==!1,s=r._config.apiKey?new re({apiUrl:r._config.apiUrl??It,apiKey:r._config.apiKey}):null,a={server:e,tracker:r,opts:o,tokenCache:s,injectToken:i,funnelSync:null},p=e.registerTool.bind(e);n.registerTool=((...d)=>{let[l,u,R]=d;if(typeof R!="function")return p(...d);let f=typeof l=="string"&&l.trim().length>0?l:"unknown",T=k(u)&&k(u._meta)?u._meta:void 0,g=Rt(f,R,a,T);return p(l,u,g)});let c=e._registeredTools;if(k(c))for(let[d,l]of Object.entries(c)){if(!k(l))continue;let u=l.handler;if(typeof u!="function"||u[xt])continue;let R=k(l._meta)?l._meta:void 0;l.handler=Rt(d,u,a,R)}if(r._config.apiKey){let d=e._registeredTools,l=[];if(d&&typeof d=="object"){for(let u of Object.values(d))if(u&&typeof u=="object"){let R=u._meta,f=R&&typeof R=="object"?R._flowGraph:void 0;f?.nodes?.length&&l.push(f)}}l.length>0&&(a.funnelSync=await ft(l))}return n}function Ie(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function bn(){return Ie()==="openai"}function Cn(){return Ie()==="mcp-apps"}var ce="text/html+skybridge",de="text/html;profile=mcp-app",Et=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function bt(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Ct(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function Ee(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function _t(e){let{id:t,title:n,description:o,baseUrl:r,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:p=!0}=e,c=e.widgetCSP??{connect_domains:[r],resource_domains:[r]};if(process.env.NODE_ENV==="development")try{let{hostname:g}=new URL(r);(g==="localhost"||g==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${g}:*`,`wss://${g}:*`],resource_domains:[...c.resource_domains||[],`http://${g}:*`]})}catch{}let d=`ui://widgets/apps-sdk/${t}.html`,l=`ui://widgets/ext-apps/${t}.html`,u=null,R=()=>(u||(u=Et(r,i)),u),f=o;async function T(g){let I=await R();g.registerResource(`${t}-openai-widget`,d,{title:n,description:f,mimeType:ce,_meta:{"openai/widgetDescription":f,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:ce,text:I,_meta:bt({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),g.registerResource(`${t}-mcp-widget`,l,{title:n,description:f,mimeType:de,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:de,text:I,_meta:Ct({description:f,prefersBorder:a,widgetCSP:c})}]}))}return{id:t,title:n,description:o,openaiUri:d,mcpUri:l,autoHeight:p,register:T}}function _n(e,t){let{resource:n,description:o,inputSchema:r,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,p=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!p)throw new Error("createTool: `title` is required when no resource is provided");let c=n?Ee({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:p,description:o,async register(d){d.registerTool(a,{title:p,description:o,inputSchema:r,annotations:i,...c&&{_meta:c}},(async(l,u)=>{let R=u,f=R._meta??{},T=Z(R),g=await t(l,{extra:{_meta:f},waniwani:T});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...c,...f,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:g.text}],...g.data?{structuredContent:g.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Fn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{F as END,X as MemoryKvStore,_ as START,L as StateGraph,j as WaniwaniKvStore,ot as createFlow,rt as createFlowTestHarness,_t as createResource,_n as createTool,hn as createTrackingRoute,Ie as detectPlatform,Cn as isMCPApps,bn as isOpenAI,Xe as redacted,Fn as registerTools,En as withWaniwani};
|
|
3
|
+
${O.context}`:`ERROR: ${b}`}:O),Y=He(M,g.context,c,d,p);if(Y)return{...Y,nodesVisited:l};break}}let w=o.get(c);if(!w)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await U(w,d);continue}if(Ne(g)){let y=g.field;if(y&&pe(H(d,y))){let x=o.get(c);if(!x)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await U(x,d);continue}let w=y?ue(p,y):void 0,S=g.interactive!==!1;return{content:{status:"widget",tool:g.tool,...g.data!==void 0?{data:g.data}:{},description:S?`IMPORTANT: You MUST now call the ${g.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${g.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${g.tool} has been called, call this flow again with action:"continue".`,interactive:S,...y?{field:y}:{},...w?{fieldSchema:w}:{}},flowTokenContent:{step:c,state:d,field:y,widgetId:g.tool},nodesVisited:l}}d=A(d,g);let I=o.get(c);if(!I)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await U(I,d)}catch(T){return{content:{status:"error",error:T instanceof Error?T.message:String(T)},flowTokenContent:{step:c,state:d},nodesVisited:l}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:l}}function fe(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Be=new Map;async function Ve(e){let t=Be.get(e);if(t)return t;let n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("[Waniwani KV] WANIWANI_ENCRYPTION_KEY must be a base64-encoded 32-byte (256-bit) key.");let o=await globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return Be.set(e,o),o}async function ze(e,t){let n=await Ve(t),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:o},n,r);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(o).toString("base64")}}async function Ye(e,t){let n=await Ve(t),o=Buffer.from(e.ct,"base64"),r=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:r},n,o)}catch{throw new Error("[Waniwani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var Kt={debug:0,warn:1,error:2,none:3};function jt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Kt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function K(e,t){return t??jt()==="debug"?(...o)=>console.log(`[waniwani:${e}]`,...o):()=>{}}var Lt="@waniwani/sdk",$t="https://app.waniwani.ai",qt=K("kv"),j=class{get baseUrl(){return(process.env.WANIWANI_API_URL??$t).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}get encryptionKey(){return process.env.WANIWANI_ENCRYPTION_KEY}async get(t){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let n=await this.request("/api/mcp/redis/get",{key:t});if(n==null)return null;if(fe(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return Ye(n,this.encryptionKey)}return n}async set(t,n,o){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let r=this.encryptionKey;qt(`set "${t}" \u2014 encryption ${r?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=r?await ze(n,r):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:o?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[Waniwani KV] delete failed for key:",t,n)}}async request(t,n){let o=`${this.baseUrl}${t}`,r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":Lt},body:JSON.stringify(n)});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${r.status}`)}return(await r.json()).data}};var X=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,o){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var V=class{store=new j;get(t){return this.store.get(t)}set(t,n,o){return this.store.set(t,n,o)}delete(t){return this.store.delete(t)}};function Ht(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Ge(e,t,n,o){let r=[];for(let[s,a]of t){let p=o.get(s);r.push({id:s,type:Ht(a),label:p?.label??s,...p?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:r,edges:i}}import{z as v}from"zod";var Ze=v.object({type:v.enum(["enum","string","number","boolean","object","array","unknown"]),values:v.array(v.string()).optional(),description:v.string().optional(),optional:v.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Bt=v.object({question:v.string(),field:v.string(),suggestions:v.array(v.string()).optional(),context:v.string().optional(),fieldSchema:Ze.optional()}).describe("One question within a multi-question interrupt."),ge={status:v.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:v.string().optional().describe("Single question to ask the user when status is interrupt."),field:v.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:Ze.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:v.array(v.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:v.array(Bt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:v.string().optional().describe("Private instruction context for the assistant."),tool:v.string().optional().describe("Widget tool to call when status is widget."),data:v.record(v.string(),v.unknown()).optional().describe("Input data to pass to the widget tool."),description:v.string().optional().describe("Instruction for rendering the requested widget."),interactive:v.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:v.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:v.string().optional().describe("Error message when status is error.")};function Je(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
|
|
4
|
+
`)}function we(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xe(e){let t=Qe(e),n=we(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Vt(e){let n=Qe(e).waniwani;return we(n)&&n.redacted===!0}function Qe(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return we(n)?n:{}}function et(e){if(!e)return[];let t=[];for(let[n,o]of Object.entries(e))Vt(o)&&t.push(n);return t}var Q="waniwani/redactedStateUpdateFields";function zt(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"",o=e.state&&Object.keys(e.state).length>0?W.object(e.state).partial().passthrough():W.record(W.string(),W.unknown());return{action:W.enum(["start","continue","reset"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget), "reset" to restart from the beginning with a correction to a previously-collected field'),intent:W.string().optional().describe(`Required when action is "start". Provide a brief summary of the user's goal for this flow. Do not invent missing intent.${t}`),context:W.string().optional().describe(`Optional when action is "start". Describe the situation or environment that led the user to start this flow \u2014 e.g. what page they are on, what they were doing, or what triggered the request. Do not invent missing context.${t}`),stateUpdates:o.optional().describe(`State field values to set before processing the next node. Pass the user's answer (keyed by the field name from the response) and any other values the user mentioned. For nested state fields, use dot-paths like "driver.name".`),sessionId:W.string().optional().describe('Session identifier. If the response includes a `sessionId`, pass it back on every subsequent "continue" and "reset" call for this flow.')}}function Yt(e){if(process.env.WANIWANI_API_KEY)return new V;throw new Error(`[waniwani] createFlow "${e}": no flow store configured. Pass { store } to .compile() \u2014 use MemoryKvStore from "@waniwani/sdk/mcp" for local development, or plug in a Redis/Upstash/Cloudflare KV adapter for production. Alternatively, set WANIWANI_API_KEY to use hosted flow state on app.waniwani.ai.`)}function tt(e){let{config:t,nodes:n,edges:o}=e,r=zt(t),i=Ge(t,n,o,e.nodeOptions),s=Je(t),a=`${t.description}
|
|
5
|
+
${s}`,p=e.store??Yt(t.id),c=new Map;async function d(f,T,g,I){if(f.action==="start"){let y=typeof f.intent=="string"?f.intent.trim():void 0;if(!y)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};if(f.intent=y,typeof f.context=="string"){let E=f.context.trim();f.context=E||void 0}let w=o.get(_);if(!w)return{content:{status:"error",error:"No start edge"}};let S=J(f.stateUpdates??{}),x=await U(w,S);return B(x,S,n,o,c,g,I,e.nodeOptions,t.state)}if(f.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await p.get(T)}catch(E){let b=E instanceof Error?E.message:String(E);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${b}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let w=y.state,S=y.step;if(!S)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let x=A(w,J(f.stateUpdates??{}));if(y.widgetId){let E=o.get(S);if(!E)return{content:{status:"error",error:`No edge from step "${S}"`}};let b=await U(E,x);return B(b,x,n,o,c,g,I,e.nodeOptions,t.state)}return B(S,x,n,o,c,g,I,e.nodeOptions,t.state)}if(f.action==="reset"){if(!T)return{content:{status:"error",error:"No session ID available for reset action."}};let y;try{y=await p.get(T)}catch(b){let M=b instanceof Error?b.message:String(b);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${M}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!y.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!f.stateUpdates||Object.keys(f.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let w=o.get(_);if(!w)return{content:{status:"error",error:"No start edge"}};let S=y.state,x=A(S,J(f.stateUpdates)),E=await U(w,x);return B(E,x,n,o,c,g,I,e.nodeOptions,t.state)}return{content:{status:"error",error:`Unknown action: "${f.action}"`}}}let l=et(t.state),u={title:t.title,description:a,inputSchema:r,outputSchema:ge,annotations:t.annotations,...l.length>0&&{_meta:{[Q]:l}}},R=(async(f,T)=>{let g=T,I=g._meta??{},y=P(I),w=y??f.sessionId;!w&&f.action==="start"&&(w=crypto.randomUUID()),w&&!y&&(I["waniwani/sessionId"]=w);let S=Z(g),x=await d(f,w,I,S);if(w&&x.flowTokenContent)try{await p.set(w,x.flowTokenContent)}catch(M){let Y=M instanceof Error?M.message:String(M);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${w}"): ${Y}`},null,2)}],_meta:I,isError:!0}}let E=!y&&w?{...x.content,sessionId:w}:x.content,b=[{type:"text",text:JSON.stringify(E,null,2)}];return x.nodesVisited?.length&&(I[D]={flowId:t.id,nodesVisited:x.nodesVisited}),{content:b,structuredContent:E,_meta:I,...x.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:u,handler:R,async register(f){let T={...u,_meta:{...u._meta,_flowGraph:i}};f.registerTool(t.id,T,R)},graph:e.graph,flowGraph:i}}function nt(e,t){let n=["flowchart TD"];n.push(` ${_}((Start))`);for(let[o]of e)n.push(` ${o}[${o}]`);n.push(` ${F}((End))`);for(let[o,r]of t)if(r.type==="direct")n.push(` ${o} --> ${r.to}`);else for(let i of r.targets)n.push(` ${o} -.-> ${i}`);return n.join(`
|
|
6
|
+
`)}var L=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,o){let r=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?o?.label:t.label,a=typeof t=="string"?o?.hideFromFunnel:t.hideFromFunnel;if(r===_||r===F)throw new Error(`"${r}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(r))throw new Error(`Node "${r}" already exists`);return this.nodes.set(r,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(r,{label:s??r,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n,o){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:o,targets:[...n]}),this}graph(){return nt(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),o=new Map(this.edges);return tt({config:this.config,nodes:n,edges:o,store:t?.store,graph:()=>nt(n,o),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(_))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(_);if(t?.type==="direct"&&t.to!==F&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,o]of this.edges){if(n!==_&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(o.type==="direct"&&o.to!==F&&!this.nodes.has(o.to))throw new Error(`Edge from "${n}" references non-existent node: "${o.to}"`);if(o.type==="conditional"&&o.targets){for(let r of o.targets)if(r!==F&&!this.nodes.has(r))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${r}"`)}}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function ot(e){return new L(e)}function me(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function rt(e,t){let n=t?.stateStore,o=[],r=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...c)=>{o.push(c)}};await e.register(i);let s=o[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:r}};async function p(c){return{...c,decodedState:n?await n.get(r):null}}return{async start(c,d,l){let u=await s({action:"start",intent:c,...l?{context:l}:{},...d?{stateUpdates:d}:{}},a);return p(me(u))},async continueWith(c){let d=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return p(me(d))},async resetWith(c){let d=await s({action:"reset",stateUpdates:c},a);return p(me(d))},async lastState(){return n?n.get(r):null}}}var ee=class extends Error{constructor(n,o){super(n);this.status=o;this.name="WaniWaniError"}};var Gt="@waniwani/sdk";function it(e){let{apiUrl:t,apiKey:n}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function r(i,s,a){let p=o(),c=`${t.replace(/\/$/,"")}${s}`,d={Authorization:`Bearer ${p}`,"X-WaniWani-SDK":Gt},l={method:i,headers:d};a!==void 0&&(d["Content-Type"]="application/json",l.body=JSON.stringify(a));let u=await fetch(c,l);if(!u.ok){let f=await u.text().catch(()=>"");throw new ee(f||`KB API error: HTTP ${u.status}`,u.status)}return(await u.json()).data}return{async ingest(i){return r("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){return r("POST","/api/mcp/kb/search",{query:i,...s})},async sources(){return r("GET","/api/mcp/kb/sources")}}}import{existsSync as Zt,readFileSync as Jt}from"fs";import{resolve as Xt}from"path";var Qt="waniwani.json",$;function st(){if($!==void 0)return $;try{let e=Xt(process.cwd(),Qt);if(!Zt(e))return $=null,null;let t=Jt(e,"utf-8");return $=JSON.parse(t),$}catch{return $=null,null}}var en="__waniwani_config__";function at(){return globalThis[en]}var tn="@waniwani/sdk";function ne(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??ct,r=rn(e),i=te(e.meta),s=te(e.metadata),a=sn(e,i),p=C(e.eventId)??o(),c=an(e.timestamp,n),d=C(e.source)??N(i)??t.source??tn,l=he(e)?{...e}:void 0,u={...s};return Object.keys(i).length>0&&(u.meta=i),l&&(u.rawLegacy=l),{id:p,type:"mcp.event",name:r,source:d,timestamp:c,correlation:a,properties:nn(e,r),metadata:u,rawLegacy:l}}function ct(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function nn(e,t){if(!he(e))return te(e.properties);let n=on(e,t),o=te(e.properties);return{...n,...o}}function on(e,t){switch(t){case"tool.called":{let n={};return C(e.toolName)&&(n.name=e.toolName),C(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),C(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return C(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),C(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function rn(e){return he(e)?e.eventType:e.event}function sn(e,t){let n=C(e.requestId)??Me(t),o=C(e.sessionId)??P(t),r=C(e.traceId)??Ue(t),i=C(e.externalUserId)??Oe(t),s=C(e.correlationId)??De(t)??n,a={};return o&&(a.sessionId=o),r&&(a.traceId=r),n&&(a.requestId=n),s&&(a.correlationId=s),i&&(a.externalUserId=i),a}function an(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function te(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function C(e){if(typeof e=="string"&&e.trim().length!==0)return e}function he(e){return"eventType"in e}var cn="/api/mcp/events/v2/batch";var dt="@waniwani/sdk",dn=new Set([401,403]),ln=new Set([408,425,429,500,502,503,504]);function lt(e){return new ye(e)}var ye=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=fn(t.apiUrl,t.endpointPath??cn),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(o=>setTimeout(o,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,o=this.flush();if(!Number.isFinite(n)||n<=0)return await o,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([o.then(()=>"flushed"),this.sleep(n).then(()=>r)])===r?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,o=t;for(;o.length>0&&!this.isStopped;){this.inFlightCount=o.length;let r=await this.sendBatchOnce(o);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,o.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",o.length,r.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",o.length,r.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}o=r.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":dt},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:gn(i)}}if(dn.has(n.status))return{kind:"auth",status:n.status};if(ln.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await pn(n);if(!o?.rejected||o.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,o.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:dt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let o=new Map(t.map(s=>[s.id,s])),r=[],i=[];for(let s of n){let a=o.get(s.eventId);if(a){if(un(s)){r.push(a);continue}i.push(a)}}return{retryable:r,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let o=this.buffer.length;this.buffer.splice(0,o),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+o)}};function un(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function pn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function fn(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function gn(e){return e instanceof Error?e.message:String(e)}function ut(e){let{apiUrl:t,apiKey:n,tracking:o}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?lt({apiUrl:t,apiKey:n,endpointPath:o.endpointPath,flushIntervalMs:o.flushIntervalMs,maxBatchSize:o.maxBatchSize,maxBufferSize:o.maxBufferSize,maxRetries:o.maxRetries,retryBaseDelayMs:o.retryBaseDelayMs,retryMaxDelayMs:o.retryMaxDelayMs,shutdownTimeoutMs:o.shutdownTimeoutMs}):void 0;function s(d){r();let l=ne(d);return!l.correlation.sessionId&&!l.correlation.externalUserId&&console.warn(`[waniwani] event "${l.name}" has no sessionId or externalUserId; the ingest API requires one and will reject it.`),i?.enqueue(l),{eventId:l.id}}let a=async d=>s(d),p=Object.assign(a,G(a)),c={async identify(d,l,u){r();let R=ne({event:"user.identified",externalUserId:d,properties:l,meta:u});return i?.enqueue(R),{eventId:R.id}},track:p,async flush(){r(),await i?.flush()},async shutdown(d){return r(),await i?.shutdown({timeoutMs:d?.timeoutMs??o.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&wn(c,o.shutdownTimeoutMs),c}function wn(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function oe(e){let n=e??st()??at(),o=n?.apiUrl??"https://app.waniwani.ai",r=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:o,apiKey:r,tracking:i},a=ut(s),p=it(s);return{...a,kb:p,_config:s}}function mn(e){let t=e.event_type??"widget_click",o=t.startsWith("widget_")?t:`widget_${t}`,r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{event:o,properties:r,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function hn(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function o(){return n||(n=oe(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=o(),p=[];for(let c of s.events){let d=mn(c),l=await a.track(d);p.push(l.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:p.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let p=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:p}),{status:500,headers:{"Content-Type":"application/json"}})}}}var Te=K("widget-token"),yn=120*1e3,re=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-yn?this.cached.token:this.pending?this.pending:(this.pending=this.mint(t,n).finally(()=>{this.pending=null}),this.pending)}async mint(t,n){let o=Tn(this.config.apiUrl,"/api/mcp/widget-tokens");Te("minting token from",o);let r={};t&&(r.sessionId=t),n&&(r.traceId=n);try{let i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)});if(Te("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,p=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(p)?null:(this.cached={token:a.token,expiresAt:p},a.token)}catch(i){return Te("mint failed:",i),null}}};function Tn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function pt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function Sn(e){return pt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function ft(e){if(e.length===0)return null;let t=[...e].sort((r,i)=>r.flowId.localeCompare(i.flowId)),n=await pt(JSON.stringify(t.map(r=>({flowId:r.flowId,nodes:r.nodes,edges:r.edges})))),o=await Promise.all(e.map(async r=>({flowId:r.flowId,title:r.title,configHash:await Sn(r),nodes:r.nodes,edges:r.edges})));return{compositeHash:n,flows:o}}var gt="waniwani/sessionId",ie="waniwani/geoLocation",se="waniwani/userLocation",kn="openai/userLocation",vn=[kn,ie,se];function wt(e,t){if(t.length===0)return e;let n;for(let o of vn){let r=e[o];if(!k(r))continue;let i;for(let s of t)s in r&&(i||(i={...r}),delete i[s]);i&&(n||(n={...e}),n[o]=i)}return n??e}function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function z(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function Se(e){if(!k(e))return;let t=e.content;return Array.isArray(t)?t.find(o=>k(o)&&o.type==="text"&&typeof o.text=="string")?.text:void 0}function Rn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ke(e,t,n,o,r,i){let s=Rn(e,n.toolType),a=n.stripLocationFields,p=a&&a.length>0,c=z(t),d=c&&p?wt(c,a):c,l=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,u=p&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:wt(i.output._meta,a)}:i?.output,f=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[D],T=f&&d?{...d,[D]:f}:f?{[D]:f}:d,g=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,I=g&&!P(T??void 0)?{...T??{},"waniwani/sessionId":g}:T;return{event:"tool.called",properties:{name:e,type:s,...o??{},...l!==void 0&&{input:l},...u!==void 0&&{output:u}},meta:I,source:N(I??d,r),metadata:{...n.metadata??{},...r&&{clientInfo:r},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function ve(e,t,n){try{await e.track(t)}catch(o){n?.(xe(o))}}async function Re(e,t){try{await e.flush()}catch(n){t?.(xe(n))}}async function ht(e,t,n,o,r,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s.waniwani)?s.waniwani:void 0,p={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let u=await t.getToken();u&&(p.token=u)}catch(u){r?.(xe(u))}let c=P(s);c&&(p.sessionId||(p.sessionId=c));let d=St(s);d!==void 0&&(p.geoLocation||(p.geoLocation=d));let l=N(z(o),i);l&&!p.source&&(p.source=l),s.waniwani=p}var mt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function yt(e,t){if(!t||!k(e))return;let n=!1;for(let r of mt)if(r in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let o=e._meta;for(let r of mt)r in t&&(r in o||(o[r]=t[r]))}function Tt(e,t){let n=z(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let o=e._meta,r=P(n);r&&!o[gt]&&(o[gt]=r);let i=St(n);i&&(o[ie]||(o[ie]=i),o[se]||(o[se]=i))}function St(e){if(!e)return;let t=e[ie]??e[se];if(k(t)||typeof t=="string")return t}function xe(e){return e instanceof Error?e:new Error(String(e))}function kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(kt(e.requestInfo)){let t=e.requestInfo.headers;if(kt(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let o=n["mcp-session-id"];if(typeof o=="string"&&o)return o;let r=n["x-waniwani-session-id"];if(typeof r=="string"&&r)return r}}}var xt=Symbol.for("waniwani.wrappedHandler"),ae=K("mcp"),It="https://app.waniwani.ai",xn="REDACTED";function In(e){if(!e)return;let t=e[Q];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(o=>typeof o=="string"));if(n.size!==0)return o=>{if(!k(o))return o;let r=o.stateUpdates;if(!k(r))return o;let i=!1,s={...r};for(let a of n)a in s&&(s[a]=xn,i=!0);return i?{...o,stateUpdates:s}:o}}function Rt(e,t,n,o){let{server:r,tracker:i,opts:s,tokenCache:a,injectToken:p}=n,c=s.applyFieldRedactions===!0?In(o):void 0,d=async(l,u)=>{let R=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},f=z(u)??{},T=r.server?.getClientVersion?.();if(!P(f)&&k(u)){let w=vt(u);w&&(f["waniwani/sessionId"]=w,u._meta=f)}if(!N(f)&&k(u)){let w=u.requestInfo?.headers,S=N(f,T)??Ke(w);S&&(f["waniwani/source"]=S,u._meta=f)}let I=Ae(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(u)&&(u[le]=I);let y=performance.now();try{let w=await t(l,u),S=Math.round(performance.now()-y);ae(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let x=k(w)&&w.isError===!0;if(x){let E=Se(w);console.error(`[waniwani] Tool "${e}" returned error${E?`: ${E}`:""}`)}return await ve(i,ke(e,u,R,{durationMs:S,status:x?"error":"ok",...x&&{errorMessage:Se(w)??"Unknown tool error"}},T,{input:l,output:w}),s.onError),ae(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Re(i,s.onError),Tt(w,u),yt(w,o),p&&(await ht(w,a,i._config.apiUrl??It,u,s.onError,T),ae(`tool "${e}" widget config injected`)),ae(`tool "${e}" post-processing complete, returning result`),w}catch(w){let S=Math.round(performance.now()-y);throw await ve(i,ke(e,u,R,{durationMs:S,status:"error",errorMessage:w instanceof Error?w.message:String(w)},T,{input:l}),s.onError),s.flushAfterToolCall&&await Re(i,s.onError),w}};return d[xt]=!0,d}async function En(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let o=t??{},r=o.client??oe(),i=o.injectWidgetToken!==!1,s=r._config.apiKey?new re({apiUrl:r._config.apiUrl??It,apiKey:r._config.apiKey}):null,a={server:e,tracker:r,opts:o,tokenCache:s,injectToken:i,funnelSync:null},p=e.registerTool.bind(e);n.registerTool=((...d)=>{let[l,u,R]=d;if(typeof R!="function")return p(...d);let f=typeof l=="string"&&l.trim().length>0?l:"unknown",T=k(u)&&k(u._meta)?u._meta:void 0,g=Rt(f,R,a,T);return p(l,u,g)});let c=e._registeredTools;if(k(c))for(let[d,l]of Object.entries(c)){if(!k(l))continue;let u=l.handler;if(typeof u!="function"||u[xt])continue;let R=k(l._meta)?l._meta:void 0;l.handler=Rt(d,u,a,R)}if(r._config.apiKey){let d=e._registeredTools,l=[];if(d&&typeof d=="object"){for(let u of Object.values(d))if(u&&typeof u=="object"){let R=u._meta,f=R&&typeof R=="object"?R._flowGraph:void 0;f?.nodes?.length&&l.push(f)}}l.length>0&&(a.funnelSync=await ft(l))}return n}function Ie(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function bn(){return Ie()==="openai"}function Cn(){return Ie()==="mcp-apps"}var ce="text/html+skybridge",de="text/html;profile=mcp-app",Et=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function bt(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Ct(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function Ee(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function _t(e){let{id:t,title:n,description:o,baseUrl:r,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:p=!0}=e,c=e.widgetCSP??{connect_domains:[r],resource_domains:[r]};if(process.env.NODE_ENV==="development")try{let{hostname:g}=new URL(r);(g==="localhost"||g==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${g}:*`,`wss://${g}:*`],resource_domains:[...c.resource_domains||[],`http://${g}:*`]})}catch{}let d=`ui://widgets/apps-sdk/${t}.html`,l=`ui://widgets/ext-apps/${t}.html`,u=null,R=()=>(u||(u=Et(r,i)),u),f=o;async function T(g){let I=await R();g.registerResource(`${t}-openai-widget`,d,{title:n,description:f,mimeType:ce,_meta:{"openai/widgetDescription":f,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:ce,text:I,_meta:bt({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),g.registerResource(`${t}-mcp-widget`,l,{title:n,description:f,mimeType:de,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:de,text:I,_meta:Ct({description:f,prefersBorder:a,widgetCSP:c})}]}))}return{id:t,title:n,description:o,openaiUri:d,mcpUri:l,autoHeight:p,register:T}}function _n(e,t){let{resource:n,description:o,inputSchema:r,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,p=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!p)throw new Error("createTool: `title` is required when no resource is provided");let c=n?Ee({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:p,description:o,async register(d){d.registerTool(a,{title:p,description:o,inputSchema:r,annotations:i,...c&&{_meta:c}},(async(l,u)=>{let R=u,f=R._meta??{},T=Z(R),g=await t(l,{extra:{_meta:f},waniwani:T});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...c,...f,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:g.text}],...g.data?{structuredContent:g.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Fn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{F as END,X as MemoryKvStore,_ as START,L as StateGraph,j as WaniwaniKvStore,ot as createFlow,rt as createFlowTestHarness,_t as createResource,_n as createTool,hn as createTrackingRoute,Ie as detectPlatform,Cn as isMCPApps,bn as isOpenAI,Xe as redacted,Fn as registerTools,En as withWaniwani};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|