@apostlejs/flows 0.0.18 → 0.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("zod"),t=require("@apostlejs/whatsapp"),n=Object.defineProperty,a={"*":["name","type","on-click-action","on-select-action","on-unselect-action","input-type","markdown","media-size","font-weight","Then","Else","Cases","children","max-file-size-kb"],Footer:["center-caption","left-caption","right-caption"],PhotoPicker:["min-uploaded-photos","max-uploaded-photos","photo-source","required"],Image:["scale-type"],TextArea:["max-length","label-variant"],TextInput:["label-variant"]},o=Object.values(a).flat(),i=t=>{const n=e.toJSONSchema(t),a=(e,t=0)=>{if("object"!=typeof e||null===e)return e;const n=new Set([...o,"additionalProperties","required","enum","$schema"]),i=Object.fromEntries(Object.entries(e).filter((([e])=>!n.has(e))));if(i.properties&&"object"==typeof i.properties){const e={};for(const[n,o]of Object.entries(i.properties))e[n]=a(o,t+1);i.properties=e}i.items&&(i.items=a(i.items,t+1));const r=e.type??"object",s={string:"example",boolean:!0,number:42,integer:1,array:[],object:{}}[r]??null;return 0===t?{type:r,...i,__example__:s}:{type:r,...i}};return a(n)},r={Title:e.z.object({type:e.z.literal("Title"),id:e.z.string(),text:e.z.string()})},s=e.z.enum(["data_exchange","navigate","complete","update_data","open_url"]),l=e.z.object({name:s,payload:e.z.record(e.z.string(),e.z.any()).optional(),next:e.z.object({type:e.z.literal("screen"),name:e.z.string()}).optional(),url:e.z.string().optional()}),c=e.z.object({...l.shape,name:e.z.union([e.z.literal("update_data"),e.z.literal("data_exchange")])}),p=e.z.object({...l.shape,name:e.z.literal("update_data")}),d=e.z.object({visible:e.z.boolean().optional()}),m=e.z.object({type:e.z.literal("Form"),name:e.z.string().optional(),children:e.z.array(e.z.any()).optional(),"error-messages":e.z.record(e.z.string(),e.z.any()).optional(),"init-values":e.z.record(e.z.string(),e.z.any()).optional()}),u=e.z.object({...d.shape,name:e.z.string(),required:e.z.boolean().optional(),enabled:e.z.boolean().optional(),"error-message":e.z.string().optional(),"init-value":e.z.string().optional()}),z=e.z.object({id:e.z.string(),title:e.z.string(),description:e.z.string().optional(),metadata:e.z.string().optional(),enabled:e.z.boolean().optional(),image:e.z.string().optional(),"alt-text":e.z.string().optional(),color:e.z.string().optional(),"on-click-action":l.optional(),"on-select-action":p.optional(),"on-unselect-action":p.optional()}),g=e.z.object({...u.shape,label:e.z.string(),description:e.z.string().optional(),"data-source":e.z.array(z),"media-size":e.z.enum(["regular","large"]).optional(),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),f=e.z.object({...u.shape,type:e.z.literal("TextInput"),label:e.z.string(),"label-variant":e.z.enum(["large"]).optional(),"input-type":e.z.enum(["text","number","email","password","passcode","phone"]).optional(),pattern:e.z.string().optional(),"helper-text":e.z.string().optional(),"min-chars":e.z.number().optional(),"max-chars":e.z.number().optional()}),b=e.z.object({...u.shape,type:e.z.literal("TextArea"),label:e.z.string(),"label-variant":e.z.enum(["large"]).optional(),"max-length":e.z.number().optional(),"helper-text":e.z.string().optional()}),h=e.z.object({...g.shape,type:e.z.literal("CheckboxGroup"),"min-selected-items":e.z.number().optional(),"max-selected-items":e.z.number().optional()}),y=e.z.object({...g.shape,type:e.z.literal("RadioButtonsGroup")}),x=e.z.object({...u.shape,type:e.z.literal("Dropdown"),label:e.z.string(),"data-source":e.z.array(z),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),w=e.z.object({...u.shape,type:e.z.literal("DatePicker"),label:e.z.string(),"min-date":e.z.string().optional(),"max-date":e.z.string().optional(),"unavailable-dates":e.z.array(e.z.string()).optional(),"helper-text":e.z.string().optional(),"on-select-action":c.optional()}),j=e.z.object({...u.shape,type:e.z.literal("CalendarPicker"),title:e.z.string().optional(),description:e.z.string().optional(),label:e.z.string(),"helper-text":e.z.string().optional(),mode:e.z.enum(["single","range"]).default("single").optional(),"min-date":e.z.string().optional(),"max-date":e.z.string().optional(),"unavailable-dates":e.z.array(e.z.string()).optional(),"include-days":e.z.array(e.z.enum(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])).optional(),"min-days":e.z.number().optional(),"max-days":e.z.number().optional(),"on-select-action":c.optional()}),v=e.z.object({...u.shape,type:e.z.literal("ChipsSelector"),label:e.z.string(),description:e.z.string().optional(),"data-source":e.z.array(z),"min-selected-items":e.z.number().optional(),"max-selected-items":e.z.number().optional(),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),k={Form:m,TextInput:f,TextArea:b,CheckboxGroup:h,RadioButtonsGroup:y,Dropdown:x,DatePicker:w,CalendarPicker:j,OptIn:e.z.object({...u.omit({enabled:!0}).shape,type:e.z.literal("OptIn"),label:e.z.string(),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),NavigationList:e.z.object({type:e.z.literal("NavigationList"),name:e.z.string(),"list-items":e.z.array(e.z.object({id:e.z.string(),"main-content":e.z.object({title:e.z.string(),description:e.z.string().optional(),metadata:e.z.string().optional()}),end:e.z.object({title:e.z.string().optional(),description:e.z.string().optional(),metadata:e.z.string().optional()}).optional(),start:e.z.object({image:e.z.string().optional(),"alt-text":e.z.string().optional()}).optional(),badge:e.z.string().optional(),tags:e.z.array(e.z.string()).optional(),"on-click-action":l.optional()})),label:e.z.string().optional(),description:e.z.string().optional(),"media-size":e.z.enum(["regular","large"]).default("regular").optional(),"on-click-action":l.optional()}),ChipsSelector:v,PhotoPicker:e.z.object({...u.shape,type:e.z.literal("PhotoPicker"),label:e.z.string(),description:e.z.string().max(300).optional(),"photo-source":e.z.enum(["camera_gallery","camera","gallery"]).default("camera_gallery").optional(),"max-file-size-kb":e.z.number().int().min(1).max(25600).default(25600).optional(),"min-uploaded-photos":e.z.number().int().min(0).max(30).default(0).optional(),"max-uploaded-photos":e.z.number().int().min(1).max(30).default(30).optional()}),DocumentPicker:e.z.object({...u.shape,type:e.z.literal("DocumentPicker"),label:e.z.string(),description:e.z.string().max(300).optional(),"max-file-size-kb":e.z.number().int().min(1).max(25600).default(25600).optional(),"min-uploaded-documents":e.z.number().int().min(0).max(30).default(0).optional(),"max-uploaded-documents":e.z.number().int().min(1).max(30).default(30).optional(),"allowed-mime-types":e.z.array(e.z.enum(["application/gzip","application/msword","application/pdf","application/vnd.ms-excel","application/vnd.ms-powerpoint","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/x-7z-compressed","application/zip","image/avif","image/gif","image/heic","image/heif","image/jpeg","image/png","image/tiff","image/webp","text/plain","video/mp4","video/mpeg"])).optional()})},_={Footer:e.z.object({type:e.z.literal("Footer"),label:e.z.string(),enabled:e.z.boolean().optional(),"left-caption":e.z.string().optional(),"center-caption":e.z.string().optional(),"right-caption":e.z.string().optional(),"on-click-action":l.optional()}),If:e.z.object({type:e.z.literal("If"),condition:e.z.string(),Then:e.z.array(e.z.any()),Else:e.z.array(e.z.any()).optional()}),Switch:e.z.object({type:e.z.literal("Switch"),value:e.z.string(),Cases:e.z.record(e.z.string(),e.z.array(e.z.any()))})},$=e.z.object({...d.shape,id:e.z.string(),text:e.z.string()}),C=e.z.enum(["bold","italic","bold_italic","normal"]),O={TextHeading:e.z.object({...$.shape,type:e.z.literal("TextHeading")}),TextSubheading:e.z.object({...$.shape,type:e.z.literal("TextSubheading"),text:e.z.string()}),TextBody:e.z.object({...$.shape,type:e.z.literal("TextBody"),"font-weight":C.optional(),strikethrough:e.z.boolean().optional(),markdown:e.z.boolean().optional()}),TextCaption:e.z.object({...$.shape,type:e.z.literal("TextCaption"),"font-weight":C.optional(),strikethrough:e.z.boolean().optional(),markdown:e.z.boolean().optional()}),RichText:e.z.object({...$.shape,type:e.z.literal("RichText"),id:e.z.string().optional()}),EmbeddedLink:e.z.object({...$.shape,type:e.z.literal("EmbeddedLink"),text:e.z.string(),"on-click-action":l.optional()}),Image:e.z.object({type:e.z.literal("Image"),id:e.z.string(),src:e.z.string(),width:e.z.number().optional(),height:e.z.number().optional(),"scale-type":e.z.enum(["cover","contain"]).default("contain").optional(),"aspect-ratio":e.z.number().default(1).optional(),"alt-text":e.z.string().optional()}),ImageCarousel:e.z.object({type:e.z.literal("ImageCarousel"),images:e.z.array(e.z.object({src:e.z.string(),"alt-text":e.z.string()})),"scale-type":e.z.enum(["cover","contain"]).default("contain").optional(),"aspect-ratio":e.z.enum(["4:3","16:9"]).optional()})},T={...k,..._,...O,...r},I=Object.entries(T).reduce(((e,[t,n])=>(e[t]=i(n),e)),{});function S(e,t){const n={};for(const{identifier:e,type:a}of t){const t=I[a];n[e]=t?.properties?{...t,properties:Object.fromEntries(Object.entries(t.properties).map((([e,t])=>[e.replaceAll("-","_"),t])))}:t}if(e){const t=i(e).properties,a=Object.entries(t).reduce(((e,[t,n])=>{e[t]=n;const a=n=>{e[t].__example__=n};switch(e[t].type){case"number":a(0);break;case"string":default:a("");break;case"array":a([]);break;case"boolean":a(!0);break;case"object":a({})}return e}),{});Object.assign(n,a)}return n}function P(e,t){t in e&&delete e[t]}var F=["If","Switch"],E=["children","Then","Else","Cases"],A=(e,t)=>{const n=[],o=e=>{if(F.includes(e.type))return void i(e);const o=(e=>{const t=Object.keys(k).includes(e.type)?"name":"id";let n="";const a="id"in e?"id":"name"in e?"name":void 0;return a||(n=e.type.toLowerCase()),a&&(n=e[a]),{value:n,key:t}})(e);if(o){Object.assign(e,{[o.key]:o.value});const{properties:t}=I[e.type];for(const n of Object.keys(t)){const t=n,i=e.type;if(a["*"].includes(t))continue;if(a[i]?.includes(t))continue;if(Object.keys(e).includes(n))continue;const r=n.replace(/-/g,"_");Object.assign(e,{[n]:`\${data.${o.value}.${r}}`})}n.push({identifier:o.value,type:e.type})}P(e,"id"),"form"===t&&(P(e,"error-message"),P(e,"init-value")),i(e)},i=e=>{for(const t of E)if(Array.isArray(e[t]))for(const n of e[t])o(n)};for(const t of e)o(t);return{parsedComponents:e,metadata:n}},N={};function R(e){return e}function D(e,t,n,a){return"screen"===e&&t&&n&&a?`\${${e}.${t}.${n}.${a}}`:`\${${e}.${t}}`}((e,t)=>{for(var a in t)n(e,a,{get:t[a],enumerable:!0})})(N,{complete:()=>B,components:()=>K,condition:()=>W,dynamic_action:()=>q,dynamic_navigate:()=>G,dynamic_refresh:()=>Q,form_payload:()=>J,inline:()=>M,navigate:()=>L,parseUniqueId:()=>X,screen:()=>R,state:()=>D,txt:()=>U,uniqueId:()=>V,zod_payload:()=>H});var q={name:"data_exchange",payload:{}},L=(e,t={})=>({name:"navigate",next:{type:"screen",name:e},payload:t});function B(e={}){return{name:"complete",payload:e}}function G(e,t={}){return{name:"data_exchange",payload:{navigate:{screen:e,data:t}}}}var J=(...e)=>e.reduce(((e,t)=>(e[t]=`\${form.${t}}`,e)),{}),H=e=>Object.keys(e.shape).reduce(((e,t)=>(e[t]=`\${form.${t}}`,e)),{});function M(e){return"`"+e+"`"}function U(...e){return e.join("\n")}function W(e){return M(e)}function K(e){return e}function Q(e={}){return{name:"data_exchange",payload:{refresh:e}}}var V=e=>e+"?deduplicate="+Date.now(),X=e=>{const t=e.split("?deduplicate=");return t.length>1?t[0]:e};function Y(e){const t=(e,t)=>({navigate:{data:t??{},screen:e}}),n=t=>({data:t,screen:e.screen});return{...e,init:e=>n(e),navigate:t,first:e=>t(e),refresh:e=>n(e),error:e=>n({form:{error_messages:e}}),success:e=>({data:e??{},screen:"SUCCESS"})}}function Z(e,n){const a=t.createWhatsapp();return"navigate"in e&&(e={data:e.navigate.data??{},screen:e.navigate.screen}),"screen"in e&&(e={data:e.data??{},screen:e.screen}),a.sdk.parsers.toGraph.flowResponse(n,e)}var ee=e.z.array(e.z.object({media_id:e.z.string(),cdn_url:e.z.string(),file_name:e.z.string(),encryption_metadata:e.z.object({encrypted_hash:e.z.string(),iv:e.z.string(),encryption_key:e.z.string(),hmac_key:e.z.string(),plaintext_hash:e.z.string()})}));exports.buildApiResponse=Z,exports.complete=B,exports.componentData=function(e){return Object.entries(e).reduce(((e,[t,n])=>(e[t.replaceAll("-","_")]=n,e)),{})},exports.components=K,exports.condition=W,exports.createDevFlowJson=function(e){const{screens:t,...n}=e,a=[];for(const[e,n]of Object.entries(t)){const{type:t,components:o,...i}=n;let r=o;"form"===t&&(r=[{type:"Form",children:r}]);const{parsedComponents:s,metadata:l}=A(r,t),c=S(i.data,l);a.push({title:"${data.title.text}",...i,id:e,data:c,layout:{type:"SingleColumnLayout",children:s}})}return{...n,screens:a}},exports.createFlowContext=Y,exports.createFlowControllerPool=function(e){return e.reduce(((e,t)=>(Object.assign(e,{[t.name]:t.screenHandlers}),e)),{})},exports.createNativeFlowJson=function(e){const{metadata:t,preview:n,id:a,...o}=e;return JSON.parse((e=>{let t=e;return t=(e=>e.replace(/^\s*"type":\s*"string",?\n(?=\s*"const":\s*"update_data")/gm,""))(t),t=(e=>e.replaceAll(/"(Then|Else|Cases)":/g,((e,t)=>`"${t.toLowerCase()}":`)))(t),t})(JSON.stringify(o,null,2)))},exports.createStoreFactory=function(e){return function(t){return{adapterFactory:e,schema:t}}},exports.dispatchFlowPayload=async function(e,n){const a=function(e){const n=t.createWhatsapp(),{screen:a,action:o,data:i,flow_token:r}=e,{flowName:s,flowIdentifier:l,flowParameters:c,chatId:p}=n.sdk.utils.flows.destructureFlowToken(r),d={action:"first",name:s,context:{chatId:p,screen:a,flow:s,identifier:l,parameters:c},data:i,screen:a};return"data_exchange"===o&&(d.action="submit",i.navigate&&(d.action="init",d.screen=i.navigate.screen,d.data=i.navigate.data),i.refresh&&(d.action="refresh",d.data=i.refresh)),"BACK"===o&&(d.action="back"),d}(n);let o={};if(o=a.screen?e?.[a.name]?.[a.screen]?.[a.action]:e?.[a.name]?.[a.action],!o)throw new Error(`No controller for action '${a.action}' in flow '${a.name}' for screen '${a.screen}'`);let i=await o({ctx:a.context,input:a.data,variables:a.data});if(!i)throw new Error(`No controller response for action '${a.action}' in flow '${a.name}' for screen '${a.screen}'`);if("navigate"in i){const t=i.navigate.screen,n=e[a.name][t];if(!n)throw new Error(`No screen controller for screen '${t}' in flow '${a.name}'`);const o=n.init;a.context.screen=t,i=await o({ctx:a.context,input:i.navigate.data})}return Z(i,n.flow_token)},exports.dynamic_action=q,exports.dynamic_navigate=G,exports.dynamic_refresh=Q,exports.f=N,exports.firstScreen=({define:e,store:t,middleware:n})=>async({ctx:a})=>{const o=Y(a),i=t?.adapterFactory({flow_identifier:a.identifier,flow_name:a.flow,chat_id:a.chatId});let r={};if(i&&t){let e=await i.stash();const n=t.schema;e=0===Object.keys(e).length?n.parse(void 0):n.parse(e),r=new Proxy(e,{get:Reflect.get,set:Reflect.set})}const s={...o,store:r},l=n?await n(s):s;return e(l)},exports.flow=e=>e,exports.flowController=function(e,t){return{screenHandlers:t,name:e.name}},exports.flowMediaInput=ee,exports.form_payload=J,exports.getFlowMetadata=function(e){return{name:e.metadata.name,_typings_routing:null}},exports.getScreenMetadata=e=>null,exports.inline=M,exports.navigate=L,exports.parseUniqueId=X,exports.partialComponentData=function(e){return Object.entries(e).reduce(((e,[t,n])=>(e[t.replaceAll("-","_")]=n,e)),{})},exports.screen=R,exports.screenController=function(t,n){const a=t=>async({ctx:a,input:o,variables:i})=>{const r=Y(a);let s={};const l=n.store?.adapterFactory({flow_identifier:a.identifier,flow_name:a.flow,chat_id:a.chatId});if(n.store&&l){let e=await l.stash();const t=n.store.schema;e=0===Object.keys(e).length?t.parse(void 0):t.parse(e),s=new Proxy(e,{get:Reflect.get,set:Reflect.set})}const c={...r,store:s},p=n.middleware?await n.middleware(c):c;let d;if("init"===t){const e=n.actions?.init;if(!e)throw new Error(`No init handler for screen '${a.screen}' in flow '${a.flow}'`);const t=await e({ctx:p,data:o});d=p.init(t)}if("back"===t){const e=n.actions.back;if(!e)throw new Error(`No back handler for screen '${a.screen}' in flow '${a.flow}'`);d=await e({ctx:p})}if("refresh"===t){const e=n.actions.refresh;if(!e)throw new Error("Refresh handler is not defined");d=await e({ctx:p,variables:i})}if("submit"===t){const t=n.actions.submit;if(!t)throw new Error("Form submit handler is not defined");const a=n.input?n.input.safeParse(o):e.z.object({}).safeParse({});if(a.error){const e=a.error.issues.reduce(((e,t)=>(t.path?.[0]&&(e[t.path[0].toString()]=t.message),e)),{});d=p.error(e)}else d=await t({ctx:p,input:a.data})}return l&&(await(n.store?.schema.parseAsync(s)),await l.flush(s)),d};return{init:a("init"),refresh:a("refresh"),submit:a("submit"),back:a("back")}},exports.state=D,exports.txt=U,exports.uniqueId=V,exports.zod_payload=H;
1
+ "use strict";var e=require("zod"),t=require("@apostlejs/whatsapp"),n=Object.defineProperty,a={"*":["name","type","on-click-action","on-select-action","on-unselect-action","input-type","markdown","media-size","font-weight","Then","Else","Cases","children","max-file-size-kb"],Footer:["center-caption","left-caption","right-caption"],PhotoPicker:["min-uploaded-photos","max-uploaded-photos","photo-source","required"],Image:["scale-type"],TextArea:["max-length","label-variant"],TextInput:["label-variant"]},o=Object.values(a).flat(),i=t=>{const n=e.toJSONSchema(t),a=(e,t=0)=>{if("object"!=typeof e||null===e)return e;const n=new Set([...o,"additionalProperties","required","enum","$schema"]),i=Object.fromEntries(Object.entries(e).filter((([e])=>!n.has(e))));if(i.properties&&"object"==typeof i.properties){const e={};for(const[n,o]of Object.entries(i.properties))e[n]=a(o,t+1);i.properties=e}i.items&&(i.items=a(i.items,t+1));const r=e.type??"object",s={string:"example",boolean:!0,number:42,integer:1,array:[],object:{}}[r]??null;return 0===t?{type:r,...i,__example__:s}:{type:r,...i}};return a(n)},r={Title:e.z.object({type:e.z.literal("Title"),id:e.z.string(),text:e.z.string()})},s=e.z.enum(["data_exchange","navigate","complete","update_data","open_url"]),l=e.z.object({name:s,payload:e.z.record(e.z.string(),e.z.any()).optional(),next:e.z.object({type:e.z.literal("screen"),name:e.z.string()}).optional(),url:e.z.string().optional()}),c=e.z.object({...l.shape,name:e.z.union([e.z.literal("update_data"),e.z.literal("data_exchange")])}),p=e.z.object({...l.shape,name:e.z.literal("update_data")}),d=e.z.object({visible:e.z.boolean().optional()}),m=e.z.object({type:e.z.literal("Form"),name:e.z.string().optional(),children:e.z.array(e.z.any()).optional(),"error-messages":e.z.record(e.z.string(),e.z.any()).optional(),"init-values":e.z.record(e.z.string(),e.z.any()).optional()}),u=e.z.object({...d.shape,name:e.z.string(),required:e.z.boolean().optional(),enabled:e.z.boolean().optional(),"error-message":e.z.string().optional(),"init-value":e.z.string().optional()}),z=e.z.object({id:e.z.string(),title:e.z.string(),description:e.z.string().optional(),metadata:e.z.string().optional(),enabled:e.z.boolean().optional(),image:e.z.string().optional(),"alt-text":e.z.string().optional(),color:e.z.string().optional(),"on-click-action":l.optional(),"on-select-action":p.optional(),"on-unselect-action":p.optional()}),g=e.z.object({...u.shape,label:e.z.string(),description:e.z.string().optional(),"data-source":e.z.array(z),"media-size":e.z.enum(["regular","large"]).optional(),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),f=e.z.object({...u.shape,type:e.z.literal("TextInput"),label:e.z.string(),"label-variant":e.z.enum(["large"]).optional(),"input-type":e.z.enum(["text","number","email","password","passcode","phone"]).optional(),pattern:e.z.string().optional(),"helper-text":e.z.string().optional(),"min-chars":e.z.number().optional(),"max-chars":e.z.number().optional()}),b=e.z.object({...u.shape,type:e.z.literal("TextArea"),label:e.z.string(),"label-variant":e.z.enum(["large"]).optional(),"max-length":e.z.number().optional(),"helper-text":e.z.string().optional()}),h=e.z.object({...g.shape,type:e.z.literal("CheckboxGroup"),"min-selected-items":e.z.number().optional(),"max-selected-items":e.z.number().optional()}),y=e.z.object({...g.shape,type:e.z.literal("RadioButtonsGroup")}),x=e.z.object({...u.shape,type:e.z.literal("Dropdown"),label:e.z.string(),"data-source":e.z.array(z),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),w=e.z.object({...u.shape,type:e.z.literal("DatePicker"),label:e.z.string(),"min-date":e.z.string().optional(),"max-date":e.z.string().optional(),"unavailable-dates":e.z.array(e.z.string()).optional(),"helper-text":e.z.string().optional(),"on-select-action":c.optional()}),j=e.z.object({...u.shape,type:e.z.literal("CalendarPicker"),title:e.z.string().optional(),description:e.z.string().optional(),label:e.z.string(),"helper-text":e.z.string().optional(),mode:e.z.enum(["single","range"]).default("single").optional(),"min-date":e.z.string().optional(),"max-date":e.z.string().optional(),"unavailable-dates":e.z.array(e.z.string()).optional(),"include-days":e.z.array(e.z.enum(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])).optional(),"min-days":e.z.number().optional(),"max-days":e.z.number().optional(),"on-select-action":c.optional()}),v=e.z.object({...u.shape,type:e.z.literal("ChipsSelector"),label:e.z.string(),description:e.z.string().optional(),"data-source":e.z.array(z),"min-selected-items":e.z.number().optional(),"max-selected-items":e.z.number().optional(),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),_={Form:m,TextInput:f,TextArea:b,CheckboxGroup:h,RadioButtonsGroup:y,Dropdown:x,DatePicker:w,CalendarPicker:j,OptIn:e.z.object({...u.omit({enabled:!0}).shape,type:e.z.literal("OptIn"),label:e.z.string(),"on-click-action":l.optional(),"on-select-action":c.optional(),"on-unselect-action":c.optional()}),NavigationList:e.z.object({type:e.z.literal("NavigationList"),name:e.z.string(),"list-items":e.z.array(e.z.object({id:e.z.string(),"main-content":e.z.object({title:e.z.string(),description:e.z.string().optional(),metadata:e.z.string().optional()}),end:e.z.object({title:e.z.string().optional(),description:e.z.string().optional(),metadata:e.z.string().optional()}).optional(),start:e.z.object({image:e.z.string().optional(),"alt-text":e.z.string().optional()}).optional(),badge:e.z.string().optional(),tags:e.z.array(e.z.string()).optional(),"on-click-action":l.optional()})),label:e.z.string().optional(),description:e.z.string().optional(),"media-size":e.z.enum(["regular","large"]).default("regular").optional(),"on-click-action":l.optional()}),ChipsSelector:v,PhotoPicker:e.z.object({...u.shape,type:e.z.literal("PhotoPicker"),label:e.z.string(),description:e.z.string().max(300).optional(),"photo-source":e.z.enum(["camera_gallery","camera","gallery"]).default("camera_gallery").optional(),"max-file-size-kb":e.z.number().int().min(1).max(25600).default(25600).optional(),"min-uploaded-photos":e.z.number().int().min(0).max(30).default(0).optional(),"max-uploaded-photos":e.z.number().int().min(1).max(30).default(30).optional()}),DocumentPicker:e.z.object({...u.shape,type:e.z.literal("DocumentPicker"),label:e.z.string(),description:e.z.string().max(300).optional(),"max-file-size-kb":e.z.number().int().min(1).max(25600).default(25600).optional(),"min-uploaded-documents":e.z.number().int().min(0).max(30).default(0).optional(),"max-uploaded-documents":e.z.number().int().min(1).max(30).default(30).optional(),"allowed-mime-types":e.z.array(e.z.enum(["application/gzip","application/msword","application/pdf","application/vnd.ms-excel","application/vnd.ms-powerpoint","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/x-7z-compressed","application/zip","image/avif","image/gif","image/heic","image/heif","image/jpeg","image/png","image/tiff","image/webp","text/plain","video/mp4","video/mpeg"])).optional()})},k={Footer:e.z.object({type:e.z.literal("Footer"),label:e.z.string(),enabled:e.z.boolean().optional(),"left-caption":e.z.string().optional(),"center-caption":e.z.string().optional(),"right-caption":e.z.string().optional(),"on-click-action":l.optional()}),If:e.z.object({type:e.z.literal("If"),condition:e.z.string(),Then:e.z.array(e.z.any()),Else:e.z.array(e.z.any()).optional()}),Switch:e.z.object({type:e.z.literal("Switch"),value:e.z.string(),Cases:e.z.record(e.z.string(),e.z.array(e.z.any()))})},$=e.z.object({...d.shape,id:e.z.string(),text:e.z.string()}),C=e.z.enum(["bold","italic","bold_italic","normal"]),O={TextHeading:e.z.object({...$.shape,type:e.z.literal("TextHeading")}),TextSubheading:e.z.object({...$.shape,type:e.z.literal("TextSubheading"),text:e.z.string()}),TextBody:e.z.object({...$.shape,type:e.z.literal("TextBody"),"font-weight":C.optional(),strikethrough:e.z.boolean().optional(),markdown:e.z.boolean().optional()}),TextCaption:e.z.object({...$.shape,type:e.z.literal("TextCaption"),"font-weight":C.optional(),strikethrough:e.z.boolean().optional(),markdown:e.z.boolean().optional()}),RichText:e.z.object({...$.shape,type:e.z.literal("RichText"),id:e.z.string().optional()}),EmbeddedLink:e.z.object({...$.shape,type:e.z.literal("EmbeddedLink"),text:e.z.string(),"on-click-action":l.optional()}),Image:e.z.object({type:e.z.literal("Image"),id:e.z.string(),src:e.z.string(),width:e.z.number().optional(),height:e.z.number().optional(),"scale-type":e.z.enum(["cover","contain"]).default("contain").optional(),"aspect-ratio":e.z.number().default(1).optional(),"alt-text":e.z.string().optional()}),ImageCarousel:e.z.object({type:e.z.literal("ImageCarousel"),images:e.z.array(e.z.object({src:e.z.string(),"alt-text":e.z.string()})),"scale-type":e.z.enum(["cover","contain"]).default("contain").optional(),"aspect-ratio":e.z.enum(["4:3","16:9"]).optional()})},T={..._,...k,...O,...r},I=Object.entries(T).reduce(((e,[t,n])=>(e[t]=i(n),e)),{});function S(e,t){const n={};for(const{identifier:e,type:a}of t){const t=I[a];n[e]=t?.properties?{...t,properties:Object.fromEntries(Object.entries(t.properties).map((([e,t])=>[e.replaceAll("-","_"),t])))}:t}if(e){const t=i(e).properties,a=Object.entries(t).reduce(((e,[t,n])=>{e[t]=n;const a=n=>{e[t].__example__=n};switch(e[t].type){case"number":a(0);break;case"string":default:a("");break;case"array":a([]);break;case"boolean":a(!0);break;case"object":a({})}return e}),{});Object.assign(n,a)}return n}function P(e,t){t in e&&delete e[t]}var F=["If","Switch"],E=["children","Then","Else","Cases"],A=(e,t)=>{const n=[],o=e=>{if(F.includes(e.type))return void i(e);const o=(e=>{const t=Object.keys(_).includes(e.type)?"name":"id";let n="";const a="id"in e?"id":"name"in e?"name":void 0;return a||(n=e.type.toLowerCase()),a&&(n=e[a]),{value:n,key:t}})(e);if(o){Object.assign(e,{[o.key]:o.value});const{properties:t}=I[e.type];for(const n of Object.keys(t)){const t=n,i=e.type;if(a["*"].includes(t))continue;if(a[i]?.includes(t))continue;if(Object.keys(e).includes(n))continue;const r=n.replace(/-/g,"_");Object.assign(e,{[n]:`\${data.${o.value}.${r}}`})}n.push({identifier:o.value,type:e.type})}P(e,"id"),"form"===t&&(P(e,"error-message"),P(e,"init-value")),i(e)},i=e=>{for(const t of E)if(Array.isArray(e[t]))for(const n of e[t])o(n)};for(const t of e)o(t);return{parsedComponents:e,metadata:n}},N={};function R(e){return e}function D(e,t,n,a){return"screen"===e&&t&&n&&a?`\${${e}.${t}.${n}.${a}}`:`\${${e}.${t}}`}((e,t)=>{for(var a in t)n(e,a,{get:t[a],enumerable:!0})})(N,{complete:()=>B,components:()=>K,condition:()=>W,dynamic_action:()=>q,dynamic_navigate:()=>G,dynamic_refresh:()=>Q,form_payload:()=>J,inline:()=>M,navigate:()=>L,parseUniqueId:()=>X,screen:()=>R,state:()=>D,txt:()=>U,uniqueId:()=>V,zod_payload:()=>H});var q={name:"data_exchange",payload:{}},L=(e,t={})=>({name:"navigate",next:{type:"screen",name:e},payload:t});function B(e={}){return{name:"complete",payload:e}}function G(e,t={}){return{name:"data_exchange",payload:{navigate:{screen:e,data:t}}}}var J=(...e)=>e.reduce(((e,t)=>(e[t]=`\${form.${t}}`,e)),{}),H=e=>Object.keys(e.shape).reduce(((e,t)=>(e[t]=`\${form.${t}}`,e)),{});function M(e){return"`"+e+"`"}function U(...e){return e.join("\n")}function W(e){return M(e)}function K(e){return e}function Q(e={}){return{name:"data_exchange",payload:{refresh:e}}}var V=e=>e+"?deduplicate="+Date.now(),X=e=>{const t=e.split("?deduplicate=");return t.length>1?t[0]:e};function Y(e){const t=(e,t)=>({navigate:{data:t??{},screen:e}}),n=t=>({data:t,screen:e.screen});return{...e,init:e=>n(e),navigate:t,first:e=>t(e),refresh:e=>n(e),error:e=>n({form:{error_messages:e}}),success:e=>({data:e??{},screen:"SUCCESS"})}}function Z(e,n){const a=t.createWhatsapp();return"navigate"in e&&(e={data:e.navigate.data??{},screen:e.navigate.screen}),"screen"in e&&(e={data:e.data??{},screen:e.screen}),a.sdk.parsers.toGraph.flowResponse(n,e)}var ee=e.z.array(e.z.object({media_id:e.z.string(),cdn_url:e.z.string(),file_name:e.z.string(),encryption_metadata:e.z.object({encrypted_hash:e.z.string(),iv:e.z.string(),encryption_key:e.z.string(),hmac_key:e.z.string(),plaintext_hash:e.z.string()})}));exports.buildApiResponse=Z,exports.complete=B,exports.componentData=function(e){return Object.entries(e).reduce(((e,[t,n])=>(e[t.replaceAll("-","_")]=n,e)),{})},exports.components=K,exports.condition=W,exports.createDevFlowJson=function(e){const{screens:t,...n}=e,a=[];for(const[e,n]of Object.entries(t)){const{type:t,components:o,...i}=n;let r=o;"form"===t&&(r=[{type:"Form",children:r}]);const{parsedComponents:s,metadata:l}=A(r,t),c=S(i.data,l);a.push({title:"${data.title.text}",...i,id:e,data:c,layout:{type:"SingleColumnLayout",children:s}})}return{...n,screens:a}},exports.createFlowContext=Y,exports.createFlowControllerPool=function(e){return e.reduce(((e,t)=>(Object.assign(e,{[t.name]:t.screenHandlers}),e)),{})},exports.createNativeFlowJson=function(e){const{metadata:t,preview:n,id:a,...o}=e;return JSON.parse((e=>{let t=e;return t=(e=>e.replace(/^\s*"type":\s*"string",?\n(?=\s*"const":\s*"update_data")/gm,""))(t),t=(e=>e.replaceAll(/"(Then|Else|Cases)":/g,((e,t)=>`"${t.toLowerCase()}":`)))(t),t})(JSON.stringify(o,null,2)))},exports.createStoreFactory=function(e){return function(t){return{adapterFactory:e,schema:t}}},exports.dispatchFlowPayload=async function(e,n){const a=function(e){const n=t.createWhatsapp(),{screen:a,action:o,data:i,flow_token:r}=e,{flowName:s,flowIdentifier:l,flowParameters:c,chatId:p}=n.sdk.utils.flows.destructureFlowToken(r),d={action:"first",name:s,context:{chatId:p,screen:a,flow:s,identifier:l,parameters:c},data:i,screen:a};return"data_exchange"===o&&(d.action="submit",i.navigate&&(d.action="init",d.screen=i.navigate.screen,d.data=i.navigate.data),i.refresh&&(d.action="refresh",d.data=i.refresh)),"BACK"===o&&(d.action="back"),d}(n);if("submit"===a.action&&a.data.error_message&&""===a.data.error)throw new Error("Flow data_exchange faced an internal error",{cause:a.data.error_message});let o={};if(o=a.screen?e?.[a.name]?.[a.screen]?.[a.action]:e?.[a.name]?.[a.action],!o)throw new Error(`No controller for action '${a.action}' in flow '${a.name}' for screen '${a.screen}'`);let i=await o({ctx:a.context,input:a.data,variables:a.data});if(!i)throw new Error(`No controller response for action '${a.action}' in flow '${a.name}' for screen '${a.screen}'`);if("navigate"in i){const t=i.navigate.screen,n=e[a.name][t];if(!n)throw new Error(`No screen controller for screen '${t}' in flow '${a.name}'`);const o=n.init;a.context.screen=t,i=await o({ctx:a.context,input:i.navigate.data})}return Z(i,n.flow_token)},exports.dynamic_action=q,exports.dynamic_navigate=G,exports.dynamic_refresh=Q,exports.f=N,exports.firstScreen=({define:e,store:t,middleware:n})=>async({ctx:a})=>{const o=Y(a),i=t?.adapterFactory({flow_identifier:a.identifier,flow_name:a.flow,chat_id:a.chatId});let r={};if(i&&t){let e=await i.stash();const n=t.schema;e=0===Object.keys(e).length?n.parse(void 0):n.parse(e),r=new Proxy(e,{get:Reflect.get,set:Reflect.set})}const s={...o,store:r},l=n?await n(s):s;return e(l)},exports.flow=e=>e,exports.flowController=function(e,t){return{screenHandlers:t,name:e.name}},exports.flowMediaInput=ee,exports.form_payload=J,exports.getFlowMetadata=function(e){return{name:e,_typings_routing:null}},exports.getScreenMetadata=()=>null,exports.inline=M,exports.navigate=L,exports.parseUniqueId=X,exports.partialComponentData=function(e){return Object.entries(e).reduce(((e,[t,n])=>(e[t.replaceAll("-","_")]=n,e)),{})},exports.screen=R,exports.screenController=function(t,n){const a=t=>async({ctx:a,input:o,variables:i})=>{const r=Y(a);let s={};const l=n.store?.adapterFactory({flow_identifier:a.identifier,flow_name:a.flow,chat_id:a.chatId});if(n.store&&l){let e=await l.stash();const t=n.store.schema;e=0===Object.keys(e).length?t.parse(void 0):t.parse(e),s=new Proxy(e,{get:Reflect.get,set:Reflect.set})}const c={...r,store:s},p=n.middleware?await n.middleware(c):c;let d;if("init"===t){const e=n.actions?.init;if(!e)throw new Error(`No init handler for screen '${a.screen}' in flow '${a.flow}'`);const t=await e({ctx:p,data:o});d=p.init(t)}if("back"===t){const e=n.actions.back;if(!e)throw new Error(`No back handler for screen '${a.screen}' in flow '${a.flow}'`);d=await e({ctx:p})}if("refresh"===t){const e=n.actions.refresh;if(!e)throw new Error("Refresh handler is not defined");d=await e({ctx:p,variables:i})}if("submit"===t){const t=n.actions.submit;if(!t)throw new Error("Form submit handler is not defined");const a=n.input?n.input.safeParse(o):e.z.object({}).safeParse({});if(a.error){const e=a.error.issues.reduce(((e,t)=>(t.path?.[0]&&(e[t.path[0].toString()]=t.message),e)),{});d=p.error(e)}else d=await t({ctx:p,input:a.data})}return l&&(await(n.store?.schema.parseAsync(s)),await l.flush(s)),d};return{init:a("init"),refresh:a("refresh"),submit:a("submit"),back:a("back")}},exports.state=D,exports.txt=U,exports.uniqueId=V,exports.zod_payload=H;
package/dist/index.d.cts CHANGED
@@ -813,7 +813,7 @@ type TypedFlowJson<Screens extends TypedFlowScreens = TypedFlowScreens, Metadata
813
813
  screens: Screens;
814
814
  };
815
815
 
816
- declare const flow$1: <Screens extends TypedFlowScreens, const Metadata extends FlowMetadata>(flow: TypedFlowJson<Screens, Metadata>) => TypedFlowJson<Screens, Metadata>;
816
+ declare const flow: <Screens extends TypedFlowScreens, const Metadata extends FlowMetadata>(flow: TypedFlowJson<Screens, Metadata>) => TypedFlowJson<Screens, Metadata>;
817
817
 
818
818
  declare function createDevFlowJson<Screens extends TypedFlowScreens, const Metadata extends FlowMetadata>(TypedFlowJson: TypedFlowJson<Screens, Metadata>): {
819
819
  readonly screens: any[];
@@ -962,9 +962,9 @@ type FlowController = {
962
962
  name: string;
963
963
  screenHandlers: AnyType;
964
964
  };
965
- declare function getFlowMetadata<const Flow extends TypedFlowJson<TypedFlowScreens, FlowMetadata>>(flow: Flow): {
966
- readonly name: (typeof flow)["metadata"]["name"];
967
- readonly _typings_routing: Extract<keyof (typeof flow)["routing_model"], string>;
965
+ declare function getFlowMetadata<const Flow extends TypedFlowJson<TypedFlowScreens, FlowMetadata>>(name: Flow["metadata"]["name"]): {
966
+ readonly name: Flow["metadata"]["name"];
967
+ readonly _typings_routing: Extract<keyof Flow["routing_model"], string>;
968
968
  };
969
969
  declare function flowController<const Flow extends TypedFlowJson<TypedFlowScreens, FlowMetadata>, const GetMetadataReturn extends ReturnType<typeof getFlowMetadata<Flow>>>(metadata: GetMetadataReturn, screenHandlers: {
970
970
  [key in GetMetadataReturn["_typings_routing"]]?: ReturnType<typeof screenController<AnyType, AnyType, AnyType, AnyType, AnyType, AnyType>>;
@@ -1023,7 +1023,7 @@ type ComponentKeys<S extends TypedFlowScreen> = StripNonIdentifierKeys<DeepCompo
1023
1023
  type StripNonIdentifierKeys<Keys extends string> = Keys extends `${infer Prefix}.${infer Suffix}` ? Prefix extends "id" | "name" ? Keys : never : never;
1024
1024
  type ExtractIdentifier<Keys extends string, P extends "all" | "id" | "name" = "all"> = P extends "all" ? Keys extends `${infer Prefix}.${infer Suffix}` ? Prefix extends "id" | "name" ? Suffix : never : never : Keys extends `${P}.${infer Suffix}` ? Suffix : never;
1025
1025
 
1026
- declare const getScreenMetadata: <const S extends TypedFlowScreen>(_: S) => ComponentKeys<S>;
1026
+ declare const getScreenMetadata: <const S extends TypedFlowScreen>() => ComponentKeys<S>;
1027
1027
  declare const firstScreen: <ExtendedContext, Context extends FlowHandlerContext<AnyType, Store> & ExtendedContext, StoreSchema extends Store["schema"], StoreAdapter extends ReturnType<Store["adapterFactory"]>, CustomStore extends Store<StoreSchema, StoreAdapter>>({ define, store, middleware, }: {
1028
1028
  define: (context: Context) => Promisable<AnyType>;
1029
1029
  store?: CustomStore | undefined;
@@ -1031,7 +1031,7 @@ declare const firstScreen: <ExtendedContext, Context extends FlowHandlerContext<
1031
1031
  }) => ({ ctx }: {
1032
1032
  ctx: FlowHandlerBaseContext;
1033
1033
  }) => Promise<any>;
1034
- declare function screenController<ScreenKeys extends string, InputSchema extends ZodObject<Record<ExtractIdentifier<ScreenKeys, "name">, AnyType>>, VariablesSchema extends ZodObject, CustomStore extends Store, ExtendedContext, Context extends FlowHandlerContext<ExtractIdentifier<ScreenKeys>, CustomStore> & ExtendedContext>(_: ScreenKeys, controller: {
1034
+ declare function screenController<ScreenKeys extends string, InputSchema extends ZodObject, VariablesSchema extends ZodObject, CustomStore extends Store, ExtendedContext, Context extends FlowHandlerContext<ExtractIdentifier<ScreenKeys>, CustomStore> & ExtendedContext>(_: ScreenKeys, controller: {
1035
1035
  middleware?: (ctx: FlowHandlerContext<ExtractIdentifier<ScreenKeys>, Store>) => Promisable<ExtendedContext>;
1036
1036
  store?: CustomStore | undefined;
1037
1037
  input?: InputSchema;
@@ -1090,4 +1090,4 @@ declare const flowMediaInput: z.ZodArray<z.ZodObject<{
1090
1090
  }, z.core.$strip>>;
1091
1091
  type FlowMediaInput = z.infer<typeof flowMediaInput>;
1092
1092
 
1093
- export { type AdapterFactoryFn, type DevFlowJson, type FlowController, type FlowControllerPool, type FlowDispatchableAction, type FlowHandlerBaseContext, type FlowHandlerContext, type FlowMediaInput, type NativeFlowJSON, type PickFlowComponent, type Store, type StoreAdapter, type TypedComponentData, type TypedFlowJson, type TypedFlowRouting, type TypedFlowScreen, type TypedFlowScreenComponent, type TypedFlowScreens, buildApiResponse, complete, componentData, components, condition, createDevFlowJson, createFlowContext, createFlowControllerPool, createNativeFlowJson, createStoreFactory, dispatchFlowPayload, dynamic_action, dynamic_navigate, dynamic_refresh, snippets as f, firstScreen, flow$1 as flow, flowController, flowMediaInput, form_payload, getFlowMetadata, getScreenMetadata, inline, navigate, parseUniqueId, partialComponentData, screen, screenController, state, txt, uniqueId, zod_payload };
1093
+ export { type AdapterFactoryFn, type DevFlowJson, type FlowController, type FlowControllerPool, type FlowDispatchableAction, type FlowHandlerBaseContext, type FlowHandlerContext, type FlowMediaInput, type NativeFlowJSON, type PickFlowComponent, type Store, type StoreAdapter, type TypedComponentData, type TypedFlowJson, type TypedFlowRouting, type TypedFlowScreen, type TypedFlowScreenComponent, type TypedFlowScreens, buildApiResponse, complete, componentData, components, condition, createDevFlowJson, createFlowContext, createFlowControllerPool, createNativeFlowJson, createStoreFactory, dispatchFlowPayload, dynamic_action, dynamic_navigate, dynamic_refresh, snippets as f, firstScreen, flow, flowController, flowMediaInput, form_payload, getFlowMetadata, getScreenMetadata, inline, navigate, parseUniqueId, partialComponentData, screen, screenController, state, txt, uniqueId, zod_payload };
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "0.0.18",
7
+ "version": "0.0.20",
8
8
  "type": "module",
9
9
  "files": [
10
10
  "dist"
@@ -32,7 +32,7 @@
32
32
  "dependencies": {
33
33
  "ajv": "8.17.1",
34
34
  "ajv-formats": "3.0.1",
35
- "@apostlejs/whatsapp": "0.0.15"
35
+ "@apostlejs/whatsapp": "0.0.17"
36
36
  },
37
37
  "peerDependencies": {
38
38
  "zod": "4.0.14"