@junobuild/functions-tools 0.5.3 → 0.6.0-next-2026-04-03

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.
@@ -1,8 +1,8 @@
1
1
  import { createRequire as topLevelCreateRequire } from 'module';
2
2
  const require = topLevelCreateRequire(import.meta.url);
3
- var Tr=Object.defineProperty;var Ar=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Nr=(r,e)=>{for(var t in e)Tr(r,t,{get:e[t],enumerable:!0})};import{writeFile as Kr}from"node:fs/promises";import*as Er from"@babel/parser";import{isTSAnyKeyword as vr,isTSArrayType as Ir,isTSBigIntKeyword as Cr,isTSBooleanKeyword as Rr,isTSNeverKeyword as Ur,isTSNullKeyword as Or,isTSNumberKeyword as $r,isTSObjectKeyword as Fr,isTSStringKeyword as kr,isTSSymbolKeyword as Br,isTSTupleType as ot,isTSTypeReference as at,isTSUndefinedKeyword as jr,isTSUnknownKeyword as Lr,isTSVoidKeyword as Vr}from"@babel/types";import{isNullish as Se,nonNullish as ct}from"@dfinity/utils";import{readFile as Mr}from"node:fs/promises";var{parse:Pr}=Er,Dr={sourceType:"module",plugins:["typescript"]},ut=async({inputFile:r})=>{let e=await Mr(r,"utf-8"),t=Pr(e,Dr),n=[],s=[],i=[],{default:o}=Ar("@babel/traverse");return o(t,{TSInterfaceDeclaration(a){if(a.node.id.name==="_SERVICE"){let c=a.node.body.body;for(let u of c)if(u.type==="TSMethodSignature"||u.type==="TSPropertySignature"){let h=Hr(u);ct(h)&&n.push(h)}}else s.push(a.node.id.name)},TSTypeAliasDeclaration(a){i.push(a.node.id.name)}}),{methods:n,imports:[...s,...i]}},oe=r=>{if(Se(r))return"unknown";if(at(r)){let e=r.typeName?.name;if(Se(e))return"unknown";if(ct(r.typeParameters?.params?.length)){let t=r.typeParameters.params.map(oe);return`${e}<${t.join(", ")}>`}return e??"unknown"}return kr(r)?"string":$r(r)?"number":Rr(r)?"boolean":Cr(r)?"bigint":Br(r)?"symbol":Or(r)?"null":jr(r)?"undefined":Vr(r)?"void":Ur(r)?"never":Lr(r)?"unknown":vr(r)?"any":Fr(r)?"object":ot(r)?`[${r.elementTypes.map(oe).join(", ")}]`:Ir(r)?`${oe(r.elementType)}[]`:"unknown"},Hr=r=>{let{type:e,key:t}=r,s=(()=>{if(t.type==="Identifier")return t.name;if(t.type==="StringLiteral")return t.value})();if(Se(s)||e!=="TSPropertySignature")return;let i=r.typeAnnotation?.typeAnnotation;if(!at(i)||i.typeName?.name!=="ActorMethod"||Se(i.typeParameters))return;let[a,c]=i.typeParameters.params,u=ot(a)?a.elementTypes.map(oe):[oe(a)];return{name:s,paramsType:u,returnType:oe(c)}};var Te="functions";var Ae=`export const %FUNCTION_NAMESPACE% = {
3
+ var Ar=Object.defineProperty;var Nr=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Er=(r,e)=>{for(var t in e)Ar(r,t,{get:e[t],enumerable:!0})};import{writeFile as Yr}from"node:fs/promises";import*as vr from"@babel/parser";import{isTSAnyKeyword as Ir,isTSArrayType as Cr,isTSBigIntKeyword as $r,isTSBooleanKeyword as Rr,isTSNeverKeyword as Ur,isTSNullKeyword as Or,isTSNumberKeyword as Fr,isTSObjectKeyword as kr,isTSStringKeyword as jr,isTSSymbolKeyword as Br,isTSTupleType as ct,isTSTypeReference as ut,isTSUndefinedKeyword as Lr,isTSUnknownKeyword as Vr,isTSVoidKeyword as Pr}from"@babel/types";import{isNullish as Ae,nonNullish as dt}from"@junobuild/utils";import{readFile as Mr}from"node:fs/promises";var{parse:Dr}=vr,Hr={sourceType:"module",plugins:["typescript"]},lt=async({inputFile:r})=>{let e=await Mr(r,"utf-8"),t=Dr(e,Hr),n=[],s=[],i=[],{default:o}=Nr("@babel/traverse");return o(t,{TSInterfaceDeclaration(a){if(a.node.id.name==="_SERVICE"){let c=a.node.body.body;for(let u of c)if(u.type==="TSMethodSignature"||u.type==="TSPropertySignature"){let m=zr(u);dt(m)&&n.push(m)}}else s.push(a.node.id.name)},TSTypeAliasDeclaration(a){i.push(a.node.id.name)}}),{methods:n,imports:[...s,...i]}},ae=r=>{if(Ae(r))return"unknown";if(ut(r)){let e=r.typeName?.name;if(Ae(e))return"unknown";if(dt(r.typeParameters?.params?.length)){let t=r.typeParameters.params.map(ae);return`${e}<${t.join(", ")}>`}return e??"unknown"}return jr(r)?"string":Fr(r)?"number":Rr(r)?"boolean":$r(r)?"bigint":Br(r)?"symbol":Or(r)?"null":Lr(r)?"undefined":Pr(r)?"void":Ur(r)?"never":Vr(r)?"unknown":Ir(r)?"any":kr(r)?"object":ct(r)?`[${r.elementTypes.map(ae).join(", ")}]`:Cr(r)?`${ae(r.elementType)}[]`:"unknown"},zr=r=>{let{type:e,key:t}=r,s=(()=>{if(t.type==="Identifier")return t.name;if(t.type==="StringLiteral")return t.value})();if(Ae(s)||e!=="TSPropertySignature")return;let i=r.typeAnnotation?.typeAnnotation;if(!ut(i)||i.typeName?.name!=="ActorMethod"||Ae(i.typeParameters))return;let[a,c]=i.typeParameters.params,u=ct(a)?a.elementTypes.map(ae):[ae(a)];return{name:s,paramsType:u,returnType:ae(c)}};var Ne="functions";var Ee=`export const %FUNCTION_NAMESPACE% = {
4
4
  %JS_FUNCTIONS%
5
- };`;var zr=`// This file was automatically generated by the Juno CLI.
5
+ };`;var Jr=`// This file was automatically generated by the Juno CLI.
6
6
  // Any modifications may be overwritten.
7
7
 
8
8
  /* eslint-disable */
@@ -15,28 +15,28 @@ import {getSatelliteExtendedActor} from '@junobuild/%CORE_LIB%';
15
15
  %METHODS%
16
16
 
17
17
  %NAMESPACE%
18
- `,Jr=`const %METHOD_NAME% = async (%PARAMS%): Promise<%METHOD_RESULT%> => {
18
+ `,Gr=`const %METHOD_NAME% = async (%PARAMS%): Promise<%METHOD_RESULT%> => {
19
19
  const {%DID_METHOD_NAME%} = await getSatelliteExtendedActor<SatelliteActor>({
20
20
  idlFactory
21
21
  });
22
22
 
23
23
  return await %DID_METHOD_NAME%(%CALL_PARAMS%);
24
- }`,Gr=`const %METHOD_NAME% = async (%CALL_PARAMS%) => {
24
+ }`,Wr=`const %METHOD_NAME% = async (%CALL_PARAMS%) => {
25
25
  const {%DID_METHOD_NAME%} = await getSatelliteExtendedActor({
26
26
  idlFactory
27
27
  });
28
28
 
29
29
  return await %DID_METHOD_NAME%(%CALL_PARAMS%);
30
- }`,Wr=`
30
+ }`,qr=`
31
31
  import type {_SERVICE as SatelliteActor%IMPORTS%} from './satellite.did';
32
- import type { Principal } from '@icp-sdk/core/principal';`,lt=({methods:r,imports:e,transformerOptions:{coreLib:t,outputLanguage:n}})=>{let s=n==="js"?Gr:Jr,i=r.map(qr),o=i.map(c=>{let u=s;return Object.entries(c).map(([h,d])=>{u=u.replaceAll(`%${h}%`,d)}),u}).join(`
32
+ import type { Principal } from '@icp-sdk/core/principal';`,ft=({methods:r,imports:e,transformerOptions:{coreLib:t,outputLanguage:n}})=>{let s=n==="js"?Wr:Gr,i=r.map(Kr),o=i.map(c=>{let u=s;return Object.entries(c).map(([m,f])=>{u=u.replaceAll(`%${m}%`,f)}),u}).join(`
33
33
 
34
- `),a=Ae.replace("%FUNCTION_NAMESPACE%",Te).replace("%JS_FUNCTIONS%",i.map(({METHOD_NAME:c})=>c).join(`,
35
- `));return zr.replace("%CORE_LIB%",t??"core").replace("%METHODS%",o).replace("%NAMESPACE%",a).replace("%IMPORT%",n==="js"?"":Wr.replace("%IMPORTS%",e.length===0?"":`, ${e.join(", ")}`)).trim()},qr=({name:r,returnType:e,paramsType:t})=>{let s=(c=>c.replace(/_./g,u=>u[1].toUpperCase()))(r),i=t.map((c,u)=>({param:`value${u}`,type:c})),o=`${i.map(({param:c})=>c).join(", ")}`,a=i.map(({param:c,type:u})=>`${c}: ${u}`).join(", ");return{METHOD_NAME:s,DID_METHOD_NAME:r,METHOD_RESULT:e,PARAMS:a,CALL_PARAMS:o}};var ns=async({inputFile:r,outputFile:e,transformerOptions:t})=>{let n=await ut({inputFile:r}),s=lt({...n,transformerOptions:t});await Kr(e,s,"utf-8")};import{writeFile as nn}from"node:fs/promises";import{nonNullish as Ne}from"@dfinity/utils";import{capitalize as Xr,convertCamelToSnake as en}from"@junobuild/utils";import{capitalize as Zr}from"@junobuild/utils";import{ZodSchemaId as dt}from"@junobuild/schema";import*as ft from"zod";var Qr=r=>{if(r.some(i=>i.type!=="object"||i.properties===void 0))return null;let[e,...t]=r,n=e.properties;if(n===void 0)return null;let s=Object.entries(n).find(([i,o])=>typeof o!="boolean"&&o.const!==void 0)?.[0];return s===void 0?null:t.every(i=>i.properties?.[s]!==void 0&&typeof i.properties[s]!="boolean"&&i.properties[s].const!==void 0)?s:null},W=({id:r,zodSchema:e})=>{let t=e.toJSONSchema({unrepresentable:"any",override:i=>{i.zodSchema._zod.def.type==="bigint"&&(i.jsonSchema.type="integer",i.jsonSchema.format="bigint"),i.jsonSchema.id===dt.Principal&&(i.jsonSchema.format="principal"),i.jsonSchema.id===dt.Uint8Array&&(i.jsonSchema.format="uint8array")}}),n=U({schema:t,rootDefs:t.$defs??{}}),s=e._zod.def.type==="optional"&&!("innerType"in e._zod.def&&e._zod.def.innerType instanceof ft.ZodNullable);return{id:r,schema:n,isTopLevelOptional:s}},U=({schema:r,rootDefs:e})=>{if(r.format==="principal")return{kind:"principal"};if(r.format==="uint8array")return{kind:"uint8array"};if("$ref"in r){let t=r.$ref.replace("#/$defs/",""),n=e[t];if(n===void 0)throw new Error(`Unresolved $ref: ${r.$ref}`);return U({schema:n,rootDefs:e})}switch(r.type){case"string":if(r.const!==void 0)return{kind:"variant",tags:[String(r.const)]};if(r.enum!==void 0){if(r.enum.some(t=>typeof t!="string"))throw new Error("Non-string enum values are not supported");return{kind:"variant",tags:r.enum}}return{kind:"text"};case"boolean":return{kind:"bool"};case"number":return{kind:"float64"};case"integer":return r.format==="bigint"?{kind:"nat"}:{kind:"int32"};case"null":throw new Error("null type is not supported");case"array":{if(r.prefixItems!==void 0){if(r.prefixItems.some(t=>typeof t=="boolean"))throw new Error("Boolean schema not supported.");return{kind:"indexedTuple",members:r.prefixItems.map(t=>U({schema:t,rootDefs:e}))}}if(r.items===void 0)throw new Error("Array schema must have items defined");if(Array.isArray(r.items))throw new Error("Tuple-style array items not supported");if(typeof r.items=="boolean")throw new Error("Boolean schema not supported for array items");return{kind:"vec",inner:U({schema:r.items,rootDefs:e})}}case"object":{if(r.properties===void 0&&r.additionalProperties!==void 0){if(typeof r.additionalProperties=="boolean")throw new Error("Boolean additionalProperties not supported");return{kind:"vec",inner:{kind:"tuple",members:[{kind:"text"},U({schema:r.additionalProperties,rootDefs:e})]}}}if(r.properties===void 0)return{kind:"record",fields:[]};if(Object.keys(r.properties).length===0)return{kind:"record",fields:[]};let t=new Set(r.required??[]),n=Object.entries(r.properties);if(n.some(([s,i])=>typeof i=="boolean"))throw new Error("Boolean schema not supported.");return{kind:"record",fields:n.map(([s,i])=>{let o=U({schema:i,rootDefs:e});return{name:s,type:t.has(s)?o:{kind:"opt",inner:o}}})}}}if(r.oneOf!==void 0){let t=r.oneOf.filter(({type:s})=>s!=="null");if(t.length===1)return{kind:"opt",inner:U({schema:t[0],rootDefs:e})};let n=Qr(t);if(n!==null)return{kind:"discriminatedUnion",discriminator:n,members:t.map(s=>U({schema:s,rootDefs:e}))};throw new Error("z.union of objects is not supported. Use z.discriminatedUnion instead.")}if(r.anyOf!==void 0){let t=r.anyOf.filter(i=>typeof i!="boolean");if(t.filter(i=>Object.keys(i).length===0).length>0)throw new Error("Unrepresentable type in union");if(t.every(i=>i.const!==void 0))return{kind:"variant",tags:t.map(i=>String(i.const))};let s=t.filter(i=>i.type!=="null");if(s.length===1)return{kind:"opt",inner:U({schema:s[0],rootDefs:e})};throw new Error("z.union of objects is not supported. Use z.discriminatedUnion instead.")}if(r.allOf!==void 0){if(r.allOf.some(n=>typeof n=="boolean"))throw new Error("Boolean schema not supported in allOf");if(r.allOf.some(n=>typeof n!="boolean"&&(n.type!=="object"||n.properties===void 0)))throw new Error("allOf only supported for object types");return{kind:"record",fields:r.allOf.flatMap(n=>{let s=new Set(n.required??[]);return Object.entries(n.properties??{}).map(([i,o])=>{let a=U({schema:o,rootDefs:e});return{name:i,type:s.has(i)?a:{kind:"opt",inner:a}}})})}}throw Object.keys(r).length===0?new Error("Unsupported type: unrepresentable schema (z.symbol, z.undefined, z.void, z.map, z.set, z.nan, z.custom are not supported)"):new Error(`Unsupported JSON Schema: ${JSON.stringify(r)}`)};var ae=r=>{switch(r.kind){case"text":return"j.string()";case"bool":return"j.boolean()";case"float64":return"j.number()";case"int32":return"j.int()";case"nat":return"j.bigint()";case"principal":return"j.principal()";case"uint8array":return"j.uint8Array()";case"opt":return`j.optional(${ae(r.inner)})`;case"vec":return`j.array(${ae(r.inner)})`;case"tuple":case"indexedTuple":return`j.tuple([${r.members.map(ae).join(", ")}])`;case"record":return`j.strictObject({${r.fields.map(e=>`${e.name}: ${ae(e.type)}`).join(", ")}})`;case"variant":return`j.enum([${r.tags.map(e=>`'${e}'`).join(", ")}])`;case"discriminatedUnion":return`j.discriminatedUnion('${r.discriminator}', [${r.members.map(ae).join(", ")}])`}},Yr=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let s=`${Zr(r)}${n}`,o=ae(t?{kind:"opt",inner:e}:e);return{baseName:s,code:`const ${s}Schema = ${o};`}},He=({id:r,schema:e,suffix:t})=>{let n=W({zodSchema:e,id:r});return Yr({...n,suffix:t})};var pt=`// @ts-expect-error - generated JS file without type declarations
34
+ `),a=Ee.replace("%FUNCTION_NAMESPACE%",Ne).replace("%JS_FUNCTIONS%",i.map(({METHOD_NAME:c})=>c).join(`,
35
+ `));return Jr.replace("%CORE_LIB%",t??"core").replace("%METHODS%",o).replace("%NAMESPACE%",a).replace("%IMPORT%",n==="js"?"":qr.replace("%IMPORTS%",e.length===0?"":`, ${e.join(", ")}`)).trim()},Kr=({name:r,returnType:e,paramsType:t})=>{let s=(c=>c.replace(/_./g,u=>u[1].toUpperCase()))(r),i=t.map((c,u)=>({param:`value${u}`,type:c})),o=`${i.map(({param:c})=>c).join(", ")}`,a=i.map(({param:c,type:u})=>`${c}: ${u}`).join(", ");return{METHOD_NAME:s,DID_METHOD_NAME:r,METHOD_RESULT:e,PARAMS:a,CALL_PARAMS:o}};var fs=async({inputFile:r,outputFile:e,transformerOptions:t})=>{let n=await lt({inputFile:r}),s=ft({...n,transformerOptions:t});await Yr(e,s,"utf-8")};import{writeFile as on}from"node:fs/promises";import{capitalize as tn,convertCamelToSnake as rn,nonNullish as ve}from"@junobuild/utils";import{capitalize as Xr}from"@junobuild/utils";import{JunoSchemaId as Qr,ZodSchemaId as pt}from"@junobuild/schema";import*as ht from"zod";var Zr=r=>{if(r.some(i=>i.type!=="object"||i.properties===void 0))return null;let[e,...t]=r,n=e.properties;if(n===void 0)return null;let s=Object.entries(n).find(([i,o])=>typeof o!="boolean"&&o.const!==void 0)?.[0];return s===void 0?null:t.every(i=>i.properties?.[s]!==void 0&&typeof i.properties[s]!="boolean"&&i.properties[s].const!==void 0)?s:null},q=({id:r,zodSchema:e})=>{let t=e.toJSONSchema({unrepresentable:"any",override:i=>{i.zodSchema._zod.def.type==="bigint"&&(i.jsonSchema.type="integer",i.jsonSchema.format="bigint"),i.jsonSchema.id===Qr.Nat&&(i.jsonSchema.type="integer",i.jsonSchema.format="nat"),i.jsonSchema.id===pt.Principal&&(i.jsonSchema.format="principal"),i.jsonSchema.id===pt.Uint8Array&&(i.jsonSchema.format="uint8array")}}),n=U({schema:t,rootDefs:t.$defs??{}}),s=e._zod.def.type==="optional"&&!("innerType"in e._zod.def&&e._zod.def.innerType instanceof ht.ZodNullable);return{id:r,schema:n,isTopLevelOptional:s}},U=({schema:r,rootDefs:e})=>{if(r.format==="principal")return{kind:"principal"};if(r.format==="uint8array")return{kind:"uint8array"};if("$ref"in r){let t=r.$ref.replace("#/$defs/",""),n=e[t];if(n===void 0)throw new Error(`Unresolved $ref: ${r.$ref}`);return U({schema:n,rootDefs:e})}switch(r.type){case"string":if(r.const!==void 0)return{kind:"variant",tags:[String(r.const)]};if(r.enum!==void 0){if(r.enum.some(t=>typeof t!="string"))throw new Error("Non-string enum values are not supported");return{kind:"variant",tags:r.enum}}return{kind:"text"};case"boolean":return{kind:"bool"};case"number":return{kind:"float64"};case"integer":return r.format==="nat"?{kind:"nat"}:r.format==="bigint"?{kind:"bigint"}:{kind:"int32"};case"null":throw new Error("null type is not supported");case"array":{if(r.prefixItems!==void 0){if(r.prefixItems.some(t=>typeof t=="boolean"))throw new Error("Boolean schema not supported.");return{kind:"indexedTuple",members:r.prefixItems.map(t=>U({schema:t,rootDefs:e}))}}if(r.items===void 0)throw new Error("Array schema must have items defined");if(Array.isArray(r.items))throw new Error("Tuple-style array items not supported");if(typeof r.items=="boolean")throw new Error("Boolean schema not supported for array items");return{kind:"vec",inner:U({schema:r.items,rootDefs:e})}}case"object":{if(r.properties===void 0&&r.additionalProperties!==void 0){if(typeof r.additionalProperties=="boolean")throw new Error("Boolean additionalProperties not supported");return{kind:"vec",inner:{kind:"tuple",members:[{kind:"text"},U({schema:r.additionalProperties,rootDefs:e})]}}}if(r.properties===void 0)return{kind:"record",fields:[]};if(Object.keys(r.properties).length===0)return{kind:"record",fields:[]};let t=new Set(r.required??[]),n=Object.entries(r.properties);if(n.some(([s,i])=>typeof i=="boolean"))throw new Error("Boolean schema not supported.");return{kind:"record",fields:n.map(([s,i])=>{let o=U({schema:i,rootDefs:e});return{name:s,type:t.has(s)?o:{kind:"opt",inner:o}}})}}}if(r.oneOf!==void 0){let t=r.oneOf.filter(({type:s})=>s!=="null");if(t.length===1)return{kind:"opt",inner:U({schema:t[0],rootDefs:e})};let n=Zr(t);if(n!==null)return{kind:"discriminatedUnion",discriminator:n,members:t.map(s=>U({schema:s,rootDefs:e}))};throw new Error("z.union of objects is not supported. Use z.discriminatedUnion instead.")}if(r.anyOf!==void 0){let t=r.anyOf.filter(i=>typeof i!="boolean");if(t.filter(i=>Object.keys(i).length===0).length>0)throw new Error("Unrepresentable type in union");if(t.every(i=>i.const!==void 0))return{kind:"variant",tags:t.map(i=>String(i.const))};let s=t.filter(i=>i.type!=="null");if(s.length===1)return{kind:"opt",inner:U({schema:s[0],rootDefs:e})};throw new Error("z.union of objects is not supported. Use z.discriminatedUnion instead.")}if(r.allOf!==void 0){if(r.allOf.some(n=>typeof n=="boolean"))throw new Error("Boolean schema not supported in allOf");if(r.allOf.some(n=>typeof n!="boolean"&&(n.type!=="object"||n.properties===void 0)))throw new Error("allOf only supported for object types");return{kind:"record",fields:r.allOf.flatMap(n=>{let s=new Set(n.required??[]);return Object.entries(n.properties??{}).map(([i,o])=>{let a=U({schema:o,rootDefs:e});return{name:i,type:s.has(i)?a:{kind:"opt",inner:a}}})})}}throw Object.keys(r).length===0?new Error("Unsupported type: unrepresentable schema (z.symbol, z.undefined, z.void, z.map, z.set, z.nan, z.custom are not supported)"):new Error(`Unsupported JSON Schema: ${JSON.stringify(r)}`)};var ce=r=>{switch(r.kind){case"text":return"j.string()";case"bool":return"j.boolean()";case"float64":return"j.number()";case"int32":return"j.int()";case"bigint":return"j.bigint()";case"nat":return"j.nat()";case"principal":return"j.principal()";case"uint8array":return"j.uint8Array()";case"opt":return`j.optional(${ce(r.inner)})`;case"vec":return`j.array(${ce(r.inner)})`;case"tuple":case"indexedTuple":return`j.tuple([${r.members.map(ce).join(", ")}])`;case"record":return`j.strictObject({${r.fields.map(e=>`${e.name}: ${ce(e.type)}`).join(", ")}})`;case"variant":return`j.enum([${r.tags.map(e=>`'${e}'`).join(", ")}])`;case"discriminatedUnion":return`j.discriminatedUnion('${r.discriminator}', [${r.members.map(ce).join(", ")}])`}},en=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let s=`${Xr(r)}${n}`,o=ce(t?{kind:"opt",inner:e}:e);return{baseName:s,code:`const ${s}Schema = ${o};`}},ze=({id:r,schema:e,suffix:t})=>{let n=q({zodSchema:e,id:r});return en({...n,suffix:t})};var mt=`// @ts-expect-error - generated JS file without type declarations
36
36
  import {idlFactory} from './satellite.factory.did.js';
37
37
  import {getSatelliteExtendedActor} from '@junobuild/%CORE_LIB%';
38
38
  import {schemaToIdl, schemaFromIdl} from '@junobuild/schema/utils';
39
- import {j} from '@junobuild/schema';`,ht=`
39
+ import {j} from '@junobuild/schema';`,yt=`
40
40
  %ARGS_ZOD%
41
41
  %RESULT_ZOD%
42
42
 
@@ -49,7 +49,7 @@ const %JS_FUNCTION% = async (args) => {
49
49
 
50
50
  const result = schemaFromIdl({schema: %RESULT_SCHEMA%, value: idlResult});
51
51
  return %RESULT_SCHEMA%.parse(result);
52
- };`,mt=`
52
+ };`,bt=`
53
53
  %ARGS_ZOD%
54
54
 
55
55
  const %JS_FUNCTION% = async (args) => {
@@ -58,7 +58,7 @@ const %JS_FUNCTION% = async (args) => {
58
58
 
59
59
  const {%RS_FUNCTION%} = await getSatelliteExtendedActor({idlFactory});
60
60
  await %RS_FUNCTION%(idlArgs);
61
- };`,yt=`
61
+ };`,xt=`
62
62
  %RESULT_ZOD%
63
63
 
64
64
  const %JS_FUNCTION% = async () => {
@@ -67,16 +67,16 @@ const %JS_FUNCTION% = async () => {
67
67
 
68
68
  const result = schemaFromIdl({schema: %RESULT_SCHEMA%, value: idlResult});
69
69
  return %RESULT_SCHEMA%.parse(result);
70
- };`,bt=`
70
+ };`,gt=`
71
71
  const %JS_FUNCTION% = async () => {
72
72
  const {%RS_FUNCTION%} = await getSatelliteExtendedActor({idlFactory});
73
73
  await %RS_FUNCTION%();
74
- };`;var xt=`import type {_SERVICE as SatelliteActor} from './satellite.did';
74
+ };`;var _t=`import type {_SERVICE as SatelliteActor} from './satellite.did';
75
75
  // @ts-expect-error - generated JS file without type declarations
76
76
  import {idlFactory} from './satellite.factory.did.js';
77
77
  import {getSatelliteExtendedActor} from '@junobuild/%CORE_LIB%';
78
78
  import {schemaToIdl, schemaFromIdl} from '@junobuild/schema/utils';
79
- import {j} from '@junobuild/schema';`,gt=`
79
+ import {j} from '@junobuild/schema';`,wt=`
80
80
  %ARGS_ZOD%
81
81
  %RESULT_ZOD%
82
82
 
@@ -89,7 +89,7 @@ const %JS_FUNCTION% = async (args: j.infer<typeof %ARGS_SCHEMA%>): Promise<j.inf
89
89
 
90
90
  const result = schemaFromIdl({schema: %RESULT_SCHEMA%, value: idlResult});
91
91
  return %RESULT_SCHEMA%.parse(result);
92
- };`,wt=`
92
+ };`,St=`
93
93
  %ARGS_ZOD%
94
94
 
95
95
  const %JS_FUNCTION% = async (args: j.infer<typeof %ARGS_SCHEMA%>): Promise<void> => {
@@ -98,7 +98,7 @@ const %JS_FUNCTION% = async (args: j.infer<typeof %ARGS_SCHEMA%>): Promise<void>
98
98
 
99
99
  const {%RS_FUNCTION%} = await getSatelliteExtendedActor<SatelliteActor>({idlFactory});
100
100
  await %RS_FUNCTION%(idlArgs);
101
- };`,_t=`
101
+ };`,Tt=`
102
102
  %RESULT_ZOD%
103
103
 
104
104
  const %JS_FUNCTION% = async (): Promise<j.infer<typeof %RESULT_SCHEMA%>> => {
@@ -107,11 +107,11 @@ const %JS_FUNCTION% = async (): Promise<j.infer<typeof %RESULT_SCHEMA%>> => {
107
107
 
108
108
  const result = schemaFromIdl({schema: %RESULT_SCHEMA%, value: idlResult});
109
109
  return %RESULT_SCHEMA%.parse(result);
110
- };`,St=`
110
+ };`,At=`
111
111
  const %JS_FUNCTION% = async (): Promise<void> => {
112
112
  const {%RS_FUNCTION%} = await getSatelliteExtendedActor<SatelliteActor>({idlFactory});
113
113
  await %RS_FUNCTION%();
114
- };`;var tn=`// This file was automatically generated by the Juno CLI.
114
+ };`;var nn=`// This file was automatically generated by the Juno CLI.
115
115
  // Any modifications may be overwritten.
116
116
 
117
117
  /* eslint-disable */
@@ -121,62 +121,62 @@ const %JS_FUNCTION% = async (): Promise<void> => {
121
121
 
122
122
  %FUNCTIONS%
123
123
 
124
- %NAMESPACE%`,Tt=({functions:r,transformerOptions:{coreLib:e,outputLanguage:t}})=>{let n=r.map(([o,a])=>rn({jsFnName:o,fn:a,outputLanguage:t})).join(`
124
+ %NAMESPACE%`,Nt=({functions:r,transformerOptions:{coreLib:e,outputLanguage:t}})=>{let n=r.map(([o,a])=>sn({jsFnName:o,fn:a,outputLanguage:t})).join(`
125
125
 
126
126
  `).trim(),s=r.map(([o,a])=>o).join(`,
127
- `),i=Ae.replace("%FUNCTION_NAMESPACE%",Te).replace("%JS_FUNCTIONS%",s);return tn.replace("%IMPORTS%",t==="js"?pt:xt).replace("%CORE_LIB%",e??"core").replace("%FUNCTIONS%",n).replace("%NAMESPACE%",i)},rn=({fn:r,jsFnName:e,outputLanguage:t})=>{let n=`${"App"}${Xr(e)}`,s="args"in r?He({id:n,schema:r.args,suffix:"Args"}):void 0,i="result"in r?He({id:n,schema:r.result,suffix:"Result"}):void 0,a=Ne(s)&&Ne(i)?t==="js"?ht:gt:Ne(s)?t==="js"?mt:wt:Ne(i)?t==="js"?yt:_t:t==="js"?bt:St,c=`${"App".toLowerCase()}_${en(e)}`;return a.replace("%JS_FUNCTION%",e).replaceAll("%RS_FUNCTION%",c).replaceAll("%ARGS_SCHEMA%",s?.baseName?`${s.baseName}Schema`:"").replaceAll("%ARGS_ZOD%",s?.code??"").replaceAll("%RESULT_SCHEMA%",i?.baseName?`${i.baseName}Schema`:"").replaceAll("%RESULT_ZOD%",i?.code??"").trim()};var Ss=async({functions:r,outputFile:e,transformerOptions:t})=>{let n=Tt({functions:r,transformerOptions:t});await nn(e,n,"utf-8")};import{capitalize as sn}from"@junobuild/utils";var X=r=>{switch(r.kind){case"text":return"text";case"bool":return"bool";case"float64":return"float64";case"int32":return"int32";case"nat":return"nat";case"principal":return"principal";case"uint8array":return"blob";case"opt":return`opt ${X(r.inner)}`;case"vec":return`vec ${X(r.inner)}`;case"record":return r.fields.length===0?"record {}":`record { ${r.fields.map(e=>`${e.name} : ${X(e.type)}`).join("; ")} }`;case"tuple":return`record { ${r.members.map(X).join("; ")} }`;case"indexedTuple":return`record { ${r.members.map((e,t)=>`${t} : ${X(e)}`).join("; ")} }`;case"variant":return`variant { ${r.tags.join("; ")} }`;case"discriminatedUnion":return`variant { ${r.members.map(e=>{let t=e.kind==="record"&&e.fields.find(i=>i.name===r.discriminator)?.type.kind==="variant"?(e.fields.find(i=>i.name===r.discriminator)?.type).tags[0]:void 0,n=e.kind==="record"?{kind:"record",fields:e.fields.filter(i=>i.name!==r.discriminator)}:e,s=X(n);return t!==void 0?`${t} : ${s}`:s}).join("; ")} }`}},on=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let s=`${sn(r)}${n}`;return{baseName:s,code:`type ${s} = ${X(t?{kind:"opt",inner:e}:e)};`}},ze=({id:r,schema:e,suffix:t})=>{let n=W({zodSchema:e,id:r});return on({...n,suffix:t})};var A={};Nr(A,{Bool:()=>Jt,BoolClass:()=>Be,ConstructType:()=>$,Empty:()=>Ht,EmptyClass:()=>xe,FixedIntClass:()=>H,FixedNatClass:()=>O,Float32:()=>Qt,Float64:()=>Zt,FloatClass:()=>_e,Func:()=>pr,FuncClass:()=>re,Int:()=>qt,Int16:()=>Xt,Int32:()=>er,Int64:()=>tr,Int8:()=>Yt,IntClass:()=>ge,Nat:()=>Kt,Nat16:()=>nr,Nat32:()=>sr,Nat64:()=>ir,Nat8:()=>rr,NatClass:()=>we,Null:()=>Gt,NullClass:()=>ee,Opt:()=>ur,OptClass:()=>Y,PrimitiveType:()=>v,Principal:()=>or,PrincipalClass:()=>Ve,Rec:()=>fr,RecClass:()=>I,Record:()=>lr,RecordClass:()=>te,Reserved:()=>zt,ReservedClass:()=>F,Service:()=>hr,ServiceClass:()=>fe,Text:()=>Wt,TextClass:()=>je,Tuple:()=>ar,TupleClass:()=>Le,Type:()=>ue,Unknown:()=>gn,UnknownClass:()=>ke,Variant:()=>dr,VariantClass:()=>de,Vec:()=>cr,VecClass:()=>le,Visitor:()=>et,decode:()=>xn,encode:()=>bn,resetSubtypeCache:()=>tt,subtype:()=>nt});var Ee="abcdefghijklmnopqrstuvwxyz234567",ce=Object.create(null);for(let r=0;r<Ee.length;r++)ce[Ee[r]]=r;ce[0]=ce.o;ce[1]=ce.i;function At(r){let e=0,t=0,n="";function s(i){return e<0?t|=i>>-e:t=i<<e&248,e>3?(e-=8,1):(e<4&&(n+=Ee[t>>3],e+=5),0)}for(let i=0;i<r.length;)i+=s(r[i]);return n+(e<0?Ee[t>>3]:"")}function Nt(r){let e=0,t=0,n=new Uint8Array(r.length*4/3|0),s=0;function i(o){let a=ce[o.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(o)}`);a<<=3,t|=a>>>e,e+=5,e>=8&&(n[s++]=t,e-=8,e>0?t=a<<5-e&255:t=0)}for(let o of r)i(o);return n.slice(0,s)}var an=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function Et(r){let e=-1;for(let t=0;t<r.length;t++){let s=(r[t]^e)&255;e=an[s]^e>>>8}return(e^-1)>>>0}function cn(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function me(r,...e){if(!cn(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Je(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function It(r,e){me(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function ye(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ie(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function C(r,e){return r<<32-e|r>>>e}var Ct=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",un=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Rt(r){if(me(r),Ct)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=un[r[t]];return e}var j={_0:48,_9:57,A:65,F:70,a:97,f:102};function vt(r){if(r>=j._0&&r<=j._9)return r-j._0;if(r>=j.A&&r<=j.F)return r-(j.A-10);if(r>=j.a&&r<=j.f)return r-(j.a-10)}function Ut(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ct)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,i=0;s<t;s++,i+=2){let o=vt(r.charCodeAt(i)),a=vt(r.charCodeAt(i+1));if(o===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function ln(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ge(r){return typeof r=="string"&&(r=ln(r)),me(r),r}var ve=class{};function Ot(r){let e=n=>r().update(Ge(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function dn(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let s=BigInt(32),i=BigInt(4294967295),o=Number(t>>s&i),a=Number(t&i),c=n?4:0,u=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+u,a,n)}function $t(r,e,t){return r&e^~r&t}function Ft(r,e,t){return r&e^r&t^e&t}var Ce=class extends ve{constructor(e,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ie(this.buffer)}update(e){Je(this),e=Ge(e),me(e);let{view:t,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(s-this.pos,i-o);if(a===s){let c=Ie(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Je(this),It(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:i}=this,{pos:o}=this;t[o++]=128,ye(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let d=o;d<s;d++)t[d]=0;dn(n,s-8,BigInt(this.length*8),i),this.process(n,0);let a=Ie(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,h[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},L=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),V=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var fn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),K=new Uint32Array(64),We=class extends Ce{constructor(e=32){super(64,e,8,!1),this.A=L[0]|0,this.B=L[1]|0,this.C=L[2]|0,this.D=L[3]|0,this.E=L[4]|0,this.F=L[5]|0,this.G=L[6]|0,this.H=L[7]|0}get(){let{A:e,B:t,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,t,n,s,i,o,a,c]}set(e,t,n,s,i,o,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)K[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=K[d-15],f=K[d-2],m=C(l,7)^C(l,18)^l>>>3,g=C(f,17)^C(f,19)^f>>>10;K[d]=g+K[d-7]+m+K[d-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:u,H:h}=this;for(let d=0;d<64;d++){let l=C(a,6)^C(a,11)^C(a,25),f=h+l+$t(a,c,u)+fn[d]+K[d]|0,g=(C(n,2)^C(n,13)^C(n,22))+Ft(n,s,i)|0;h=u,u=c,c=a,a=o+f|0,o=i,i=s,s=n,n=f+g|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(n,s,i,o,a,c,u,h)}roundClean(){ye(K)}destroy(){this.set(0,0,0,0,0,0,0,0),ye(this.buffer)}},qe=class extends We{constructor(){super(28),this.A=V[0]|0,this.B=V[1]|0,this.C=V[2]|0,this.D=V[3]|0,this.E=V[4]|0,this.F=V[5]|0,this.G=V[6]|0,this.H=V[7]|0}};var kt=Ot(()=>new qe);var Re="__principal__",pn=2,Bt=4,hn="aaaaa-aa",Ue=class r{static anonymous(){return new this(new Uint8Array([Bt]))}static managementCanister(){return this.fromText(hn)}static selfAuthenticating(e){let t=kt(e);return new this(new Uint8Array([...t,pn]))}static from(e){if(typeof e=="string")return r.fromText(e);if(Object.getPrototypeOf(e)===Uint8Array.prototype)return new r(e);if(r.isPrincipal(e))return new r(e._arr);throw new Error(`Impossible to convert ${JSON.stringify(e)} to Principal.`)}static fromHex(e){return new this(Ut(e))}static fromText(e){let t=e;if(e.includes(Re)){let o=JSON.parse(e);Re in o&&(t=o[Re])}let n=t.toLowerCase().replace(/-/g,""),s=Nt(n);s=s.slice(4,s.length);let i=new this(s);if(i.toText()!==t)throw new Error(`Principal "${i.toText()}" does not have a valid checksum (original value "${t}" may not be a valid Principal ID).`);return i}static fromUint8Array(e){return new this(e)}static isPrincipal(e){return e instanceof r||typeof e=="object"&&e!==null&&"_isPrincipal"in e&&e._isPrincipal===!0&&"_arr"in e&&e._arr instanceof Uint8Array}constructor(e){this._arr=e,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===Bt}toUint8Array(){return this._arr}toHex(){return Rt(this._arr).toUpperCase()}toText(){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,Et(this._arr));let n=new Uint8Array(e),s=new Uint8Array([...n,...this._arr]),o=At(s).match(/.{1,5}/g);if(!o)throw new Error;return o.join("-")}toString(){return this.toText()}toJSON(){return{[Re]:this.toText()}}compareTo(e){for(let t=0;t<Math.min(this._arr.length,e._arr.length);t++){if(this._arr[t]<e._arr[t])return"lt";if(this._arr[t]>e._arr[t])return"gt"}return this._arr.length<e._arr.length?"lt":this._arr.length>e._arr.length?"gt":"eq"}ltEq(e){let t=this.compareTo(e);return t=="lt"||t=="eq"}gtEq(e){let t=this.compareTo(e);return t=="gt"||t=="eq"}};function y(...r){let e=new Uint8Array(r.reduce((n,s)=>n+s.byteLength,0)),t=0;for(let n of r)e.set(n,t),t+=n.byteLength;return e}var M=class{save(){return this._view}restore(e){if(!(e instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=e}constructor(e,t=e?.byteLength||0){if(e&&!(e instanceof Uint8Array))try{e=jt(e)}catch{throw new Error("Buffer must be a Uint8Array")}if(t<0||!Number.isInteger(t))throw new Error("Length must be a non-negative integer");if(e&&t>e.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=e||new Uint8Array(0),this._view=new Uint8Array(this._buffer.buffer,0,t)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(e){let t=this._view.subarray(0,e);return this._view=this._view.subarray(e),t.slice()}readUint8(){if(this._view.byteLength===0)return;let e=this._view[0];return this._view=this._view.subarray(1),e}write(e){if(!(e instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let t=this._view.byteLength;this._view.byteOffset+this._view.byteLength+e.byteLength>=this._buffer.byteLength?this.alloc(e.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+e.byteLength),this._view.set(e,t)}get end(){return this._view.byteLength===0}alloc(e){if(e<=0||!Number.isInteger(e))throw new Error("Amount must be a positive integer");let t=new Uint8Array((this._buffer.byteLength+e)*1.2|0),n=new Uint8Array(t.buffer,0,this._view.byteLength+e);n.set(this._view),this._buffer=t,this._view=n}};function jt(r){if(!r)throw new Error("Input cannot be null or undefined");return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?new Uint8Array(r):"buffer"in r?jt(r.buffer):new Uint8Array(r)}function Lt(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(r.buffer,r.byteOffset,r.byteLength)}function mn(r){let t=new TextEncoder().encode(r),n=0;for(let s of t)n=(n*223+s)%2**32;return n}function E(r){if(/^_\d+_$/.test(r)||/^_0x[0-9a-fA-F]+_$/.test(r)){let e=+r.slice(1,-1);if(Number.isSafeInteger(e)&&e>=0&&e<2**32)return e}return mn(r)}function Ke(r){let e=BigInt(r);if(r<=0)throw new RangeError("Input must be positive");return e.toString(2).length-1}function Oe(r){let e=BigInt(r);if(r<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<e}function Vt(){throw new Error("unexpected end of buffer")}function Z(r,e){return r.byteLength<e&&Vt(),r.read(e)}function Q(r){let e=r.readUint8();return e===void 0&&Vt(),e}function w(r){if(typeof r=="number"&&(r=BigInt(r)),r<BigInt(0))throw new Error("Cannot leb encode negative values.");let e=(r===BigInt(0)?0:Ke(r))+1,t=new M(new Uint8Array(e),0);for(;;){let n=Number(r&BigInt(127));if(r/=BigInt(128),r===BigInt(0)){t.write(new Uint8Array([n]));break}else t.write(new Uint8Array([n|128]))}return t.buffer}function T(r){let e=BigInt(1),t=BigInt(0),n;do n=Q(r),t+=BigInt(n&127).valueOf()*e,e*=BigInt(128);while(n>=128);return t}function _(r){typeof r=="number"&&(r=BigInt(r));let e=r<BigInt(0);e&&(r=-r-BigInt(1));let t=(r===BigInt(0)?0:Ke(r))+1,n=new M(new Uint8Array(t),0);for(;;){let i=s(r);if(r/=BigInt(128),e&&r===BigInt(0)&&(i&64)!==0||!e&&r===BigInt(0)&&(i&64)===0){n.write(new Uint8Array([i]));break}else n.write(new Uint8Array([i|128]))}function s(i){let o=i%BigInt(128);return Number(e?BigInt(128)-o-BigInt(1):o)}return n.buffer}function P(r){let e=new Uint8Array(r.buffer),t=0;for(;t<e.byteLength;t++)if(e[t]<128){if((e[t]&64)===0)return T(r);break}let n=new Uint8Array(Z(r,t+1)),s=BigInt(0);for(let i=n.byteLength-1;i>=0;i--)s=s*BigInt(128)+BigInt(128-(n[i]&127)-1);return-s-BigInt(1)}function Mt(r,e){if(BigInt(r)<BigInt(0))throw new Error("Cannot write negative values.");return Qe(r,e)}function Qe(r,e){r=BigInt(r);let t=new M(new Uint8Array(Math.min(1,e)),0),n=0,s=BigInt(256),i=BigInt(0),o=Number(r%s);for(t.write(new Uint8Array([o]));++n<e;)r<0&&i===BigInt(0)&&o!==0&&(i=BigInt(1)),o=Number((r/s-i)%BigInt(256)),t.write(new Uint8Array([o])),s*=BigInt(256);return t.buffer}function Ze(r,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let t=BigInt(Q(r)),n=BigInt(1),s=0;for(;++s<e;){n*=BigInt(256);let i=BigInt(Q(r));t=t+n*i}return t}function Pt(r,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let t=Ze(r,e),n=BigInt(2)**(BigInt(8)*BigInt(e-1)+BigInt(7));return t>=n&&(t-=n*BigInt(2)),t}var b;(function(r){r[r.Null=-1]="Null",r[r.Bool=-2]="Bool",r[r.Nat=-3]="Nat",r[r.Int=-4]="Int",r[r.Float32=-13]="Float32",r[r.Float64=-14]="Float64",r[r.Text=-15]="Text",r[r.Reserved=-16]="Reserved",r[r.Empty=-17]="Empty",r[r.Opt=-18]="Opt",r[r.Vector=-19]="Vector",r[r.Record=-20]="Record",r[r.Variant=-21]="Variant",r[r.Func=-22]="Func",r[r.Service=-23]="Service",r[r.Principal=-24]="Principal"})(b||(b={}));var $e="DIDL",yn=new TextEncoder().encode($e),Dt=400;function be(r,e,t){return r.map((n,s)=>t(n,e[s]))}var Xe=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(e){return this._idx.has(e.name)}add(e,t){let n=this._typs.length;this._idx.set(e.name,n),this._idxRefCount.set(n,1),this._typs.push(t)}merge(e,t){let n=this._idx.get(e.name),s=this._idx.get(t);if(n===void 0)throw new Error("Missing type index for "+e);if(s===void 0)throw new Error("Missing type index for "+t);this._typs[n]=this._typs[s];let i=this._getIdxRefCount(n),o=this._getIdxRefCount(s);this._idxRefCount.set(n,i+o),this._idx.set(t,n),this._idxRefCount.set(s,0),this._compactFromEnd()}_getIdxRefCount(e){return this._idxRefCount.get(e)||0}_compactFromEnd(){for(;this._typs.length>0;){let e=this._typs.length-1;if(this._getIdxRefCount(e)>0)break;this._typs.pop(),this._idxRefCount.delete(e)}}encode(){let e=w(this._typs.length),t=y(...this._typs);return y(e,t)}indexOf(e){if(!this._idx.has(e))throw new Error("Missing type index for "+e);return _(this._idx.get(e)||0)}},et=class{visitType(e,t){throw new Error("Not implemented")}visitPrimitive(e,t){return this.visitType(e,t)}visitEmpty(e,t){return this.visitPrimitive(e,t)}visitBool(e,t){return this.visitPrimitive(e,t)}visitNull(e,t){return this.visitPrimitive(e,t)}visitReserved(e,t){return this.visitPrimitive(e,t)}visitText(e,t){return this.visitPrimitive(e,t)}visitNumber(e,t){return this.visitPrimitive(e,t)}visitInt(e,t){return this.visitNumber(e,t)}visitNat(e,t){return this.visitNumber(e,t)}visitFloat(e,t){return this.visitPrimitive(e,t)}visitFixedInt(e,t){return this.visitNumber(e,t)}visitFixedNat(e,t){return this.visitNumber(e,t)}visitPrincipal(e,t){return this.visitPrimitive(e,t)}visitConstruct(e,t){return this.visitType(e,t)}visitVec(e,t,n){return this.visitConstruct(e,n)}visitOpt(e,t,n){return this.visitConstruct(e,n)}visitRecord(e,t,n){return this.visitConstruct(e,n)}visitTuple(e,t,n){let s=t.map((i,o)=>[`_${o}_`,i]);return this.visitRecord(e,s,n)}visitVariant(e,t,n){return this.visitConstruct(e,n)}visitRec(e,t,n){return this.visitConstruct(t,n)}visitFunc(e,t){return this.visitConstruct(e,t)}visitService(e,t){return this.visitConstruct(e,t)}},p;(function(r){r.EmptyClass="__IDL_EmptyClass__",r.UnknownClass="__IDL_UnknownClass__",r.BoolClass="__IDL_BoolClass__",r.NullClass="__IDL_NullClass__",r.ReservedClass="__IDL_ReservedClass__",r.TextClass="__IDL_TextClass__",r.IntClass="__IDL_IntClass__",r.NatClass="__IDL_NatClass__",r.FloatClass="__IDL_FloatClass__",r.FixedIntClass="__IDL_FixedIntClass__",r.FixedNatClass="__IDL_FixedNatClass__",r.VecClass="__IDL_VecClass__",r.OptClass="__IDL_OptClass__",r.RecordClass="__IDL_RecordClass__",r.TupleClass="__IDL_TupleClass__",r.VariantClass="__IDL_VariantClass__",r.RecClass="__IDL_RecClass__",r.PrincipalClass="__IDL_PrincipalClass__",r.FuncClass="__IDL_FuncClass__",r.ServiceClass="__IDL_ServiceClass__"})(p||(p={}));var ue=class{display(){return this.name}valueToString(e){return x(e)}buildTypeTable(e){e.has(this)||this._buildTypeTableImpl(e)}},v=class extends ue{checkType(e){if(this.name!==e.name)throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`);return e}_buildTypeTableImpl(e){}},$=class extends ue{checkType(e){if(e instanceof I){let t=e.getType();if(typeof t>"u")throw new Error("type mismatch with uninitialized type");return t}throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`)}encodeType(e){return e.indexOf(this.name)}},xe=class extends v{get typeName(){return p.EmptyClass}static[Symbol.hasInstance](e){return e.typeName===p.EmptyClass}accept(e,t){return e.visitEmpty(this,t)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return _(b.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},ke=class extends ue{get typeName(){return p.UnknownClass}static[Symbol.hasInstance](e){return e.typeName===p.UnknownClass}checkType(e){throw new Error("Method not implemented for unknown.")}accept(e,t){throw e.visitType(this,t)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(){throw new Error("Unknown cannot appear as a function argument")}valueToString(){throw new Error("Unknown cannot appear as a value")}encodeType(){throw new Error("Unknown cannot be serialized")}decodeValue(e,t){let n=t.decodeValue(e,t);Object(n)!==n&&(n=Object(n));let s;return t instanceof I?s=()=>t.getType():s=()=>t,Object.defineProperty(n,"type",{value:s,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw new Error("Unknown cannot be serialized")}get name(){return"Unknown"}},Be=class extends v{get typeName(){return p.BoolClass}static[Symbol.hasInstance](e){return e.typeName===p.BoolClass}accept(e,t){return e.visitBool(this,t)}covariant(e){if(typeof e=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){return new Uint8Array([e?1:0])}encodeType(){return _(b.Bool)}decodeValue(e,t){switch(this.checkType(t),Q(e)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},ee=class extends v{get typeName(){return p.NullClass}static[Symbol.hasInstance](e){return e.typeName===p.NullClass}accept(e,t){return e.visitNull(this,t)}covariant(e){if(e===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return _(b.Null)}decodeValue(e,t){return this.checkType(t),null}get name(){return"null"}},F=class extends v{get typeName(){return p.ReservedClass}static[Symbol.hasInstance](e){return e.typeName===p.ReservedClass}accept(e,t){return e.visitReserved(this,t)}covariant(e){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return _(b.Reserved)}decodeValue(e,t){return t.name!==this.name&&t.decodeValue(e,t),null}get name(){return"reserved"}},je=class extends v{get typeName(){return p.TextClass}static[Symbol.hasInstance](e){return e.typeName===p.TextClass}accept(e,t){return e.visitText(this,t)}covariant(e){if(typeof e=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){let t=new TextEncoder().encode(e),n=w(t.byteLength);return y(n,t)}encodeType(){return _(b.Text)}decodeValue(e,t){this.checkType(t);let n=T(e),s=Z(e,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(s)}get name(){return"text"}valueToString(e){return'"'+e+'"'}},ge=class extends v{get typeName(){return p.IntClass}static[Symbol.hasInstance](e){return e.typeName===p.IntClass}accept(e,t){return e.visitInt(this,t)}covariant(e){if(typeof e=="bigint"||Number.isInteger(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){return _(e)}encodeType(){return _(b.Int)}decodeValue(e,t){return this.checkType(t),P(e)}get name(){return"int"}valueToString(e){return e.toString()}},we=class extends v{get typeName(){return p.NatClass}static[Symbol.hasInstance](e){return e.typeName===p.NatClass}accept(e,t){return e.visitNat(this,t)}covariant(e){if(typeof e=="bigint"&&e>=BigInt(0)||Number.isInteger(e)&&e>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){return w(e)}encodeType(){return _(b.Nat)}decodeValue(e,t){return this.checkType(t),T(e)}get name(){return"nat"}valueToString(e){return e.toString()}},_e=class extends v{get typeName(){return p.FloatClass}static[Symbol.hasInstance](e){return e.typeName===p.FloatClass}constructor(e){if(super(),this._bits=e,e!==32&&e!==64)throw new Error("not a valid float type")}accept(e,t){return e.visitFloat(this,t)}covariant(e){if(typeof e=="number"||e instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){let t=new ArrayBuffer(this._bits/8),n=new DataView(t);return this._bits===32?n.setFloat32(0,e,!0):n.setFloat64(0,e,!0),new Uint8Array(t)}encodeType(){let e=this._bits===32?b.Float32:b.Float64;return _(e)}decodeValue(e,t){this.checkType(t);let n=Z(e,this._bits/8),s=Lt(n);return this._bits===32?s.getFloat32(0,!0):s.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(e){return e.toString()}},H=class extends v{get typeName(){return p.FixedIntClass}static[Symbol.hasInstance](e){return e.typeName===p.FixedIntClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedInt(this,t)}covariant(e){let t=Oe(this._bits-1)*BigInt(-1),n=Oe(this._bits-1)-BigInt(1),s=!1;if(typeof e=="bigint")s=e>=t&&e<=n;else if(Number.isInteger(e)){let i=BigInt(e);s=i>=t&&i<=n}else s=!1;if(s)return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){return Qe(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return _(-9-e)}decodeValue(e,t){this.checkType(t);let n=Pt(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(e){return e.toString()}},O=class extends v{get typeName(){return p.FixedNatClass}static[Symbol.hasInstance](e){return e.typeName===p.FixedNatClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedNat(this,t)}covariant(e){let t=Oe(this._bits),n=!1;if(typeof e=="bigint"&&e>=BigInt(0)?n=e<t:Number.isInteger(e)&&e>=0?n=BigInt(e)<t:n=!1,n)return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){return Mt(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return _(-5-e)}decodeValue(e,t){this.checkType(t);let n=Ze(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(e){return e.toString()}},le=class r extends ${get typeName(){return p.VecClass}static[Symbol.hasInstance](e){return e.typeName===p.VecClass}constructor(e){super(),this._type=e,this._blobOptimization=!1,e instanceof O&&e._bits===8&&(this._blobOptimization=!0)}accept(e,t){return e.visitVec(this,this._type,t)}covariant(e){let t=this._type instanceof O?this._type._bits:this._type instanceof H?this._type._bits:0;if(ArrayBuffer.isView(e)&&t==e.BYTES_PER_ELEMENT*8||Array.isArray(e)&&e.every((n,s)=>{try{return this._type.covariant(n)}catch(i){throw new Error(`Invalid ${this.display()} argument:
127
+ `),i=Ee.replace("%FUNCTION_NAMESPACE%",Ne).replace("%JS_FUNCTIONS%",s);return nn.replace("%IMPORTS%",t==="js"?mt:_t).replace("%CORE_LIB%",e??"core").replace("%FUNCTIONS%",n).replace("%NAMESPACE%",i)},sn=({fn:r,jsFnName:e,outputLanguage:t})=>{let n=`${"App"}${tn(e)}`,s="args"in r?ze({id:n,schema:r.args,suffix:"Args"}):void 0,i="result"in r?ze({id:n,schema:r.result,suffix:"Result"}):void 0,a=ve(s)&&ve(i)?t==="js"?yt:wt:ve(s)?t==="js"?bt:St:ve(i)?t==="js"?xt:Tt:t==="js"?gt:At,c=`${"App".toLowerCase()}_${rn(e)}`;return a.replace("%JS_FUNCTION%",e).replaceAll("%RS_FUNCTION%",c).replaceAll("%ARGS_SCHEMA%",s?.baseName?`${s.baseName}Schema`:"").replaceAll("%ARGS_ZOD%",s?.code??"").replaceAll("%RESULT_SCHEMA%",i?.baseName?`${i.baseName}Schema`:"").replaceAll("%RESULT_ZOD%",i?.code??"").trim()};var $s=async({functions:r,outputFile:e,transformerOptions:t})=>{let n=Nt({functions:r,transformerOptions:t});await on(e,n,"utf-8")};import{capitalize as an,convertCamelToSnake as cn}from"@junobuild/utils";var ee=r=>{switch(r.kind){case"text":return"text";case"bool":return"bool";case"float64":return"float64";case"int32":return"int32";case"bigint":return"nat64";case"nat":return"nat";case"principal":return"principal";case"uint8array":return"blob";case"opt":return`opt ${ee(r.inner)}`;case"vec":return`vec ${ee(r.inner)}`;case"record":return r.fields.length===0?"record {}":`record { ${r.fields.map(e=>`${cn(e.name)} : ${ee(e.type)}`).join("; ")} }`;case"tuple":return`record { ${r.members.map(ee).join("; ")} }`;case"indexedTuple":return`record { ${r.members.map((e,t)=>`${t} : ${ee(e)}`).join("; ")} }`;case"variant":return`variant { ${r.tags.join("; ")} }`;case"discriminatedUnion":return`variant { ${r.members.map(e=>{let t=e.kind==="record"&&e.fields.find(i=>i.name===r.discriminator)?.type.kind==="variant"?(e.fields.find(i=>i.name===r.discriminator)?.type).tags[0]:void 0,n=e.kind==="record"?{kind:"record",fields:e.fields.filter(i=>i.name!==r.discriminator)}:e,s=ee(n);return t!==void 0?`${t} : ${s}`:s}).join("; ")} }`}},un=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let s=`${an(r)}${n}`;return{baseName:s,code:`type ${s} = ${ee(t?{kind:"opt",inner:e}:e)};`}},Je=({id:r,schema:e,suffix:t})=>{let n=q({zodSchema:e,id:r});return un({...n,suffix:t})};var S={};Er(S,{Bool:()=>Wt,BoolClass:()=>Le,CandidDecodeError:()=>v,ConstructType:()=>F,Empty:()=>Jt,EmptyClass:()=>_e,FixedIntClass:()=>H,FixedNatClass:()=>O,Float32:()=>Zt,Float64:()=>Xt,FloatClass:()=>Te,Func:()=>mr,FuncClass:()=>ne,Int:()=>Yt,Int16:()=>tr,Int32:()=>rr,Int64:()=>nr,Int8:()=>er,IntClass:()=>we,Nat:()=>Qt,Nat16:()=>ir,Nat32:()=>or,Nat64:()=>ar,Nat8:()=>sr,NatClass:()=>Se,Null:()=>qt,NullClass:()=>te,Opt:()=>lr,OptClass:()=>X,PrimitiveType:()=>I,Principal:()=>cr,PrincipalClass:()=>Me,Rec:()=>hr,RecClass:()=>C,Record:()=>fr,RecordClass:()=>re,Reserved:()=>Gt,ReservedClass:()=>k,Service:()=>yr,ServiceClass:()=>pe,Text:()=>Kt,TextClass:()=>Ve,Tuple:()=>ur,TupleClass:()=>Pe,Type:()=>de,Unknown:()=>Sn,UnknownClass:()=>Be,Variant:()=>pr,VariantClass:()=>fe,Vec:()=>dr,VecClass:()=>le,Visitor:()=>tt,decode:()=>wn,encode:()=>_n,resetSubtypeCache:()=>rt,subtype:()=>st});var Ie="abcdefghijklmnopqrstuvwxyz234567",ue=Object.create(null);for(let r=0;r<Ie.length;r++)ue[Ie[r]]=r;ue[0]=ue.o;ue[1]=ue.i;function Et(r){let e=0,t=0,n="";function s(i){return e<0?t|=i>>-e:t=i<<e&248,e>3?(e-=8,1):(e<4&&(n+=Ie[t>>3],e+=5),0)}for(let i=0;i<r.length;)i+=s(r[i]);return n+(e<0?Ie[t>>3]:"")}function vt(r){let e=0,t=0,n=new Uint8Array(r.length*4/3|0),s=0;function i(o){let a=ue[o.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(o)}`);a<<=3,t|=a>>>e,e+=5,e>=8&&(n[s++]=t,e-=8,e>0?t=a<<5-e&255:t=0)}for(let o of r)i(o);return n.slice(0,s)}var dn=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function It(r){let e=-1;for(let t=0;t<r.length;t++){let s=(r[t]^e)&255;e=dn[s]^e>>>8}return(e^-1)>>>0}function ln(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function be(r,...e){if(!ln(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Ge(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function $t(r,e){be(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function xe(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function $e(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function R(r,e){return r<<32-e|r>>>e}var Rt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fn=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ut(r){if(be(r),Rt)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=fn[r[t]];return e}var B={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ct(r){if(r>=B._0&&r<=B._9)return r-B._0;if(r>=B.A&&r<=B.F)return r-(B.A-10);if(r>=B.a&&r<=B.f)return r-(B.a-10)}function Ot(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Rt)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,i=0;s<t;s++,i+=2){let o=Ct(r.charCodeAt(i)),a=Ct(r.charCodeAt(i+1));if(o===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[s]=o*16+a}return n}function pn(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function We(r){return typeof r=="string"&&(r=pn(r)),be(r),r}var Ce=class{};function Ft(r){let e=n=>r().update(We(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function hn(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let s=BigInt(32),i=BigInt(4294967295),o=Number(t>>s&i),a=Number(t&i),c=n?4:0,u=n?0:4;r.setUint32(e+c,o,n),r.setUint32(e+u,a,n)}function kt(r,e,t){return r&e^~r&t}function jt(r,e,t){return r&e^r&t^e&t}var Re=class extends Ce{constructor(e,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=$e(this.buffer)}update(e){Ge(this),e=We(e),be(e);let{view:t,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(s-this.pos,i-o);if(a===s){let c=$e(e);for(;s<=i-o;o+=s)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ge(this),$t(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:i}=this,{pos:o}=this;t[o++]=128,xe(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(n,0),o=0);for(let f=o;f<s;f++)t[f]=0;hn(n,s-8,BigInt(this.length*8),i),this.process(n,0);let a=$e(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,m=this.get();if(u>m.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,m[f],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},L=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),V=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var mn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Y=new Uint32Array(64),qe=class extends Re{constructor(e=32){super(64,e,8,!1),this.A=L[0]|0,this.B=L[1]|0,this.C=L[2]|0,this.D=L[3]|0,this.E=L[4]|0,this.F=L[5]|0,this.G=L[6]|0,this.H=L[7]|0}get(){let{A:e,B:t,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,t,n,s,i,o,a,c]}set(e,t,n,s,i,o,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Y[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Y[f-15],l=Y[f-2],h=R(d,7)^R(d,18)^d>>>3,x=R(l,17)^R(l,19)^l>>>10;Y[f]=x+Y[f-7]+h+Y[f-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:u,H:m}=this;for(let f=0;f<64;f++){let d=R(a,6)^R(a,11)^R(a,25),l=m+d+kt(a,c,u)+mn[f]+Y[f]|0,x=(R(n,2)^R(n,13)^R(n,22))+jt(n,s,i)|0;m=u,u=c,c=a,a=o+l|0,o=i,i=s,s=n,n=l+x|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,m=m+this.H|0,this.set(n,s,i,o,a,c,u,m)}roundClean(){xe(Y)}destroy(){this.set(0,0,0,0,0,0,0,0),xe(this.buffer)}},Ke=class extends qe{constructor(){super(28),this.A=V[0]|0,this.B=V[1]|0,this.C=V[2]|0,this.D=V[3]|0,this.E=V[4]|0,this.F=V[5]|0,this.G=V[6]|0,this.H=V[7]|0}};var Bt=Ft(()=>new Ke);var Ue="__principal__",yn=2,Lt=4,bn="aaaaa-aa",Oe=class r{static anonymous(){return new this(new Uint8Array([Lt]))}static managementCanister(){return this.fromText(bn)}static selfAuthenticating(e){let t=Bt(e);return new this(new Uint8Array([...t,yn]))}static from(e){if(typeof e=="string")return r.fromText(e);if(Object.getPrototypeOf(e)===Uint8Array.prototype)return new r(e);if(r.isPrincipal(e))return new r(e._arr);throw new Error(`Impossible to convert ${JSON.stringify(e)} to Principal.`)}static fromHex(e){return new this(Ot(e))}static fromText(e){let t=e;if(e.includes(Ue)){let o=JSON.parse(e);Ue in o&&(t=o[Ue])}let n=t.toLowerCase().replace(/-/g,""),s=vt(n);s=s.slice(4,s.length);let i=new this(s);if(i.toText()!==t)throw new Error(`Principal "${i.toText()}" does not have a valid checksum (original value "${t}" may not be a valid Principal ID).`);return i}static fromUint8Array(e){return new this(e)}static isPrincipal(e){return e instanceof r||typeof e=="object"&&e!==null&&"_isPrincipal"in e&&e._isPrincipal===!0&&"_arr"in e&&e._arr instanceof Uint8Array}constructor(e){this._arr=e,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===Lt}toUint8Array(){return this._arr}toHex(){return Ut(this._arr).toUpperCase()}toText(){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,It(this._arr));let n=new Uint8Array(e),s=new Uint8Array([...n,...this._arr]),o=Et(s).match(/.{1,5}/g);if(!o)throw new Error;return o.join("-")}toString(){return this.toText()}toJSON(){return{[Ue]:this.toText()}}compareTo(e){for(let t=0;t<Math.min(this._arr.length,e._arr.length);t++){if(this._arr[t]<e._arr[t])return"lt";if(this._arr[t]>e._arr[t])return"gt"}return this._arr.length<e._arr.length?"lt":this._arr.length>e._arr.length?"gt":"eq"}ltEq(e){let t=this.compareTo(e);return t=="lt"||t=="eq"}gtEq(e){let t=this.compareTo(e);return t=="gt"||t=="eq"}};function y(...r){let e=new Uint8Array(r.reduce((n,s)=>n+s.byteLength,0)),t=0;for(let n of r)e.set(n,t),t+=n.byteLength;return e}var P=class{save(){return this._view}restore(e){if(!(e instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=e}constructor(e,t=e?.byteLength||0){if(e&&!(e instanceof Uint8Array))try{e=Vt(e)}catch{throw new Error("Buffer must be a Uint8Array")}if(t<0||!Number.isInteger(t))throw new Error("Length must be a non-negative integer");if(e&&t>e.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=e||new Uint8Array(0),this._view=new Uint8Array(this._buffer.buffer,0,t)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(e){let t=this._view.subarray(0,e);return this._view=this._view.subarray(e),t.slice()}readUint8(){if(this._view.byteLength===0)return;let e=this._view[0];return this._view=this._view.subarray(1),e}write(e){if(!(e instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let t=this._view.byteLength;this._view.byteOffset+this._view.byteLength+e.byteLength>=this._buffer.byteLength?this.alloc(e.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+e.byteLength),this._view.set(e,t)}get end(){return this._view.byteLength===0}alloc(e){if(e<=0||!Number.isInteger(e))throw new Error("Amount must be a positive integer");let t=new Uint8Array((this._buffer.byteLength+e)*1.2|0),n=new Uint8Array(t.buffer,0,this._view.byteLength+e);n.set(this._view),this._buffer=t,this._view=n}};function Vt(r){if(!r)throw new Error("Input cannot be null or undefined");return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):Array.isArray(r)?new Uint8Array(r):"buffer"in r?Vt(r.buffer):new Uint8Array(r)}function Pt(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(r.buffer,r.byteOffset,r.byteLength)}function xn(r){let t=new TextEncoder().encode(r),n=0;for(let s of t)n=(n*223+s)%2**32;return n}function E(r){if(/^_\d+_$/.test(r)||/^_0x[0-9a-fA-F]+_$/.test(r)){let e=+r.slice(1,-1);if(Number.isSafeInteger(e)&&e>=0&&e<2**32)return e}return xn(r)}function Ye(r){let e=BigInt(r);if(r<=0)throw new RangeError("Input must be positive");return e.toString(2).length-1}function Fe(r){let e=BigInt(r);if(r<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<e}function Mt(){throw new Error("unexpected end of buffer")}function Z(r,e){return r.byteLength<e&&Mt(),r.read(e)}function Q(r){let e=r.readUint8();return e===void 0&&Mt(),e}function _(r){if(typeof r=="number"&&(r=BigInt(r)),r<BigInt(0))throw new Error("Cannot leb encode negative values.");let e=(r===BigInt(0)?0:Ye(r))+1,t=new P(new Uint8Array(e),0);for(;;){let n=Number(r&BigInt(127));if(r/=BigInt(128),r===BigInt(0)){t.write(new Uint8Array([n]));break}else t.write(new Uint8Array([n|128]))}return t.buffer}function T(r){let e=BigInt(1),t=BigInt(0),n;do n=Q(r),t+=BigInt(n&127).valueOf()*e,e*=BigInt(128);while(n>=128);return t}function w(r){typeof r=="number"&&(r=BigInt(r));let e=r<BigInt(0);e&&(r=-r-BigInt(1));let t=(r===BigInt(0)?0:Ye(r))+1,n=new P(new Uint8Array(t),0);for(;;){let i=s(r);if(r/=BigInt(128),e&&r===BigInt(0)&&(i&64)!==0||!e&&r===BigInt(0)&&(i&64)===0){n.write(new Uint8Array([i]));break}else n.write(new Uint8Array([i|128]))}function s(i){let o=i%BigInt(128);return Number(e?BigInt(128)-o-BigInt(1):o)}return n.buffer}function M(r){let e=new Uint8Array(r.buffer),t=0;for(;t<e.byteLength;t++)if(e[t]<128){if((e[t]&64)===0)return T(r);break}let n=new Uint8Array(Z(r,t+1)),s=BigInt(0);for(let i=n.byteLength-1;i>=0;i--)s=s*BigInt(128)+BigInt(128-(n[i]&127)-1);return-s-BigInt(1)}function Dt(r,e){if(BigInt(r)<BigInt(0))throw new Error("Cannot write negative values.");return Qe(r,e)}function Qe(r,e){r=BigInt(r);let t=new P(new Uint8Array(Math.min(1,e)),0),n=0,s=BigInt(256),i=BigInt(0),o=Number(r%s);for(t.write(new Uint8Array([o]));++n<e;)r<0&&i===BigInt(0)&&o!==0&&(i=BigInt(1)),o=Number((r/s-i)%BigInt(256)),t.write(new Uint8Array([o])),s*=BigInt(256);return t.buffer}function Ze(r,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let t=BigInt(Q(r)),n=BigInt(1),s=0;for(;++s<e;){n*=BigInt(256);let i=BigInt(Q(r));t=t+n*i}return t}function Ht(r,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let t=Ze(r,e),n=BigInt(2)**(BigInt(8)*BigInt(e-1)+BigInt(7));return t>=n&&(t-=n*BigInt(2)),t}var v=class r extends Error{constructor(e){super(e),this.name="CandidDecodeError",Object.setPrototypeOf(this,r.prototype)}},b;(function(r){r[r.Null=-1]="Null",r[r.Bool=-2]="Bool",r[r.Nat=-3]="Nat",r[r.Int=-4]="Int",r[r.Float32=-13]="Float32",r[r.Float64=-14]="Float64",r[r.Text=-15]="Text",r[r.Reserved=-16]="Reserved",r[r.Empty=-17]="Empty",r[r.Opt=-18]="Opt",r[r.Vector=-19]="Vector",r[r.Record=-20]="Record",r[r.Variant=-21]="Variant",r[r.Func=-22]="Func",r[r.Service=-23]="Service",r[r.Principal=-24]="Principal"})(b||(b={}));var ke="DIDL",gn=new TextEncoder().encode(ke),zt=400;function ge(r,e,t){return r.map((n,s)=>t(n,e[s]))}var et=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(e){return this._idx.has(e.name)}add(e,t){let n=this._typs.length;this._idx.set(e.name,n),this._idxRefCount.set(n,1),this._typs.push(t)}merge(e,t){let n=this._idx.get(e.name),s=this._idx.get(t);if(n===void 0)throw new Error(`Missing type index for ${e}`);if(s===void 0)throw new Error(`Missing type index for ${t}`);this._typs[n]=this._typs[s];let i=this._getIdxRefCount(n),o=this._getIdxRefCount(s);this._idxRefCount.set(n,i+o),this._idx.set(t,n),this._idxRefCount.set(s,0),this._compactFromEnd()}_getIdxRefCount(e){return this._idxRefCount.get(e)||0}_compactFromEnd(){for(;this._typs.length>0;){let e=this._typs.length-1;if(this._getIdxRefCount(e)>0)break;this._typs.pop(),this._idxRefCount.delete(e)}}encode(){let e=_(this._typs.length),t=y(...this._typs);return y(e,t)}indexOf(e){if(!this._idx.has(e))throw new Error(`Missing type index for ${e}`);return w(this._idx.get(e)||0)}},tt=class{visitType(e,t){throw new Error("Not implemented")}visitPrimitive(e,t){return this.visitType(e,t)}visitEmpty(e,t){return this.visitPrimitive(e,t)}visitBool(e,t){return this.visitPrimitive(e,t)}visitNull(e,t){return this.visitPrimitive(e,t)}visitReserved(e,t){return this.visitPrimitive(e,t)}visitText(e,t){return this.visitPrimitive(e,t)}visitNumber(e,t){return this.visitPrimitive(e,t)}visitInt(e,t){return this.visitNumber(e,t)}visitNat(e,t){return this.visitNumber(e,t)}visitFloat(e,t){return this.visitPrimitive(e,t)}visitFixedInt(e,t){return this.visitNumber(e,t)}visitFixedNat(e,t){return this.visitNumber(e,t)}visitPrincipal(e,t){return this.visitPrimitive(e,t)}visitConstruct(e,t){return this.visitType(e,t)}visitVec(e,t,n){return this.visitConstruct(e,n)}visitOpt(e,t,n){return this.visitConstruct(e,n)}visitRecord(e,t,n){return this.visitConstruct(e,n)}visitTuple(e,t,n){let s=t.map((i,o)=>[`_${o}_`,i]);return this.visitRecord(e,s,n)}visitVariant(e,t,n){return this.visitConstruct(e,n)}visitRec(e,t,n){return this.visitConstruct(t,n)}visitFunc(e,t){return this.visitConstruct(e,t)}visitService(e,t){return this.visitConstruct(e,t)}},p;(function(r){r.EmptyClass="__IDL_EmptyClass__",r.UnknownClass="__IDL_UnknownClass__",r.BoolClass="__IDL_BoolClass__",r.NullClass="__IDL_NullClass__",r.ReservedClass="__IDL_ReservedClass__",r.TextClass="__IDL_TextClass__",r.IntClass="__IDL_IntClass__",r.NatClass="__IDL_NatClass__",r.FloatClass="__IDL_FloatClass__",r.FixedIntClass="__IDL_FixedIntClass__",r.FixedNatClass="__IDL_FixedNatClass__",r.VecClass="__IDL_VecClass__",r.OptClass="__IDL_OptClass__",r.RecordClass="__IDL_RecordClass__",r.TupleClass="__IDL_TupleClass__",r.VariantClass="__IDL_VariantClass__",r.RecClass="__IDL_RecClass__",r.PrincipalClass="__IDL_PrincipalClass__",r.FuncClass="__IDL_FuncClass__",r.ServiceClass="__IDL_ServiceClass__"})(p||(p={}));var de=class{display(){return this.name}valueToString(e){return g(e)}buildTypeTable(e){e.has(this)||this._buildTypeTableImpl(e)}},I=class extends de{checkType(e){if(this.name!==e.name)throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`);return e}_buildTypeTableImpl(e){}},F=class extends de{checkType(e){if(e instanceof C){let t=e.getType();if(typeof t>"u")throw new v("Type mismatch: cannot decode from uninitialized recursive type");return t}throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`)}encodeType(e){return e.indexOf(this.name)}},_e=class extends I{get typeName(){return p.EmptyClass}static[Symbol.hasInstance](e){return e.typeName===p.EmptyClass}accept(e,t){return e.visitEmpty(this,t)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return w(b.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},Be=class extends de{get typeName(){return p.UnknownClass}static[Symbol.hasInstance](e){return e.typeName===p.UnknownClass}checkType(e){throw new Error("Method not implemented for unknown.")}accept(e,t){throw e.visitType(this,t)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(){throw new Error("Unknown cannot appear as a function argument")}valueToString(){throw new Error("Unknown cannot appear as a value")}encodeType(){throw new Error("Unknown cannot be serialized")}decodeValue(e,t){let n=t.decodeValue(e,t);Object(n)!==n&&(n=Object(n));let s;return t instanceof C?s=()=>t.getType():s=()=>t,Object.defineProperty(n,"type",{value:s,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw new Error("Unknown cannot be serialized")}get name(){return"Unknown"}},Le=class extends I{get typeName(){return p.BoolClass}static[Symbol.hasInstance](e){return e.typeName===p.BoolClass}accept(e,t){return e.visitBool(this,t)}covariant(e){if(typeof e=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){return new Uint8Array([e?1:0])}encodeType(){return w(b.Bool)}decodeValue(e,t){switch(this.checkType(t),Q(e)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},te=class extends I{get typeName(){return p.NullClass}static[Symbol.hasInstance](e){return e.typeName===p.NullClass}accept(e,t){return e.visitNull(this,t)}covariant(e){if(e===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return w(b.Null)}decodeValue(e,t){return this.checkType(t),null}get name(){return"null"}},k=class extends I{get typeName(){return p.ReservedClass}static[Symbol.hasInstance](e){return e.typeName===p.ReservedClass}accept(e,t){return e.visitReserved(this,t)}covariant(e){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return w(b.Reserved)}decodeValue(e,t){return t.name!==this.name&&t.decodeValue(e,t),null}get name(){return"reserved"}},Ve=class extends I{get typeName(){return p.TextClass}static[Symbol.hasInstance](e){return e.typeName===p.TextClass}accept(e,t){return e.visitText(this,t)}covariant(e){if(typeof e=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){let t=new TextEncoder().encode(e),n=_(t.byteLength);return y(n,t)}encodeType(){return w(b.Text)}decodeValue(e,t){this.checkType(t);let n=T(e),s=Z(e,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(s)}get name(){return"text"}valueToString(e){return`"${e}"`}},we=class extends I{get typeName(){return p.IntClass}static[Symbol.hasInstance](e){return e.typeName===p.IntClass}accept(e,t){return e.visitInt(this,t)}covariant(e){if(typeof e=="bigint"||Number.isInteger(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){return w(e)}encodeType(){return w(b.Int)}decodeValue(e,t){return this.checkType(t),M(e)}get name(){return"int"}valueToString(e){return e.toString()}},Se=class extends I{get typeName(){return p.NatClass}static[Symbol.hasInstance](e){return e.typeName===p.NatClass}accept(e,t){return e.visitNat(this,t)}covariant(e){if(typeof e=="bigint"&&e>=BigInt(0)||Number.isInteger(e)&&e>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){return _(e)}encodeType(){return w(b.Nat)}decodeValue(e,t){return this.checkType(t),T(e)}get name(){return"nat"}valueToString(e){return e.toString()}},Te=class extends I{get typeName(){return p.FloatClass}static[Symbol.hasInstance](e){return e.typeName===p.FloatClass}constructor(e){if(super(),this._bits=e,e!==32&&e!==64)throw new Error("not a valid float type")}accept(e,t){return e.visitFloat(this,t)}covariant(e){if(typeof e=="number"||e instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){let t=new ArrayBuffer(this._bits/8),n=new DataView(t);return this._bits===32?n.setFloat32(0,e,!0):n.setFloat64(0,e,!0),new Uint8Array(t)}encodeType(){let e=this._bits===32?b.Float32:b.Float64;return w(e)}decodeValue(e,t){this.checkType(t);let n=Z(e,this._bits/8),s=Pt(n);return this._bits===32?s.getFloat32(0,!0):s.getFloat64(0,!0)}get name(){return`float${this._bits}`}valueToString(e){return e.toString()}},H=class extends I{get typeName(){return p.FixedIntClass}static[Symbol.hasInstance](e){return e.typeName===p.FixedIntClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedInt(this,t)}covariant(e){let t=Fe(this._bits-1)*BigInt(-1),n=Fe(this._bits-1)-BigInt(1);if(typeof e=="bigint"){if(e>=t&&e<=n)return!0}else if(Number.isInteger(e)){let s=BigInt(e);if(s>=t&&s<=n)return!0}throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){return Qe(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return w(-9-e)}decodeValue(e,t){this.checkType(t);let n=Ht(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(e){return e.toString()}},O=class extends I{get typeName(){return p.FixedNatClass}static[Symbol.hasInstance](e){return e.typeName===p.FixedNatClass}constructor(e){super(),this._bits=e}accept(e,t){return e.visitFixedNat(this,t)}covariant(e){let t=Fe(this._bits);if(typeof e=="bigint"&&e>=BigInt(0)){if(e<t)return!0}else if(Number.isInteger(e)&&e>=0&&BigInt(e)<t)return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){return Dt(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return w(-5-e)}decodeValue(e,t){this.checkType(t);let n=Ze(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(e){return e.toString()}},le=class r extends F{get typeName(){return p.VecClass}static[Symbol.hasInstance](e){return e.typeName===p.VecClass}constructor(e){super(),this._type=e,this._blobOptimization=!1,e instanceof O&&e._bits===8&&(this._blobOptimization=!0)}accept(e,t){return e.visitVec(this,this._type,t)}covariant(e){let t=this._type instanceof O?this._type._bits:this._type instanceof H?this._type._bits:0;if(ArrayBuffer.isView(e)&&t==e.BYTES_PER_ELEMENT*8||Array.isArray(e)&&e.every((n,s)=>{try{return this._type.covariant(n)}catch(i){throw new Error(`Invalid ${this.display()} argument:
128
128
 
129
- index ${s} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){let t=w(e.length);if(this._blobOptimization)return y(t,new Uint8Array(e));if(ArrayBuffer.isView(e))if(e instanceof Int16Array||e instanceof Uint16Array){let s=new DataView(new ArrayBuffer(e.length*2));for(let i=0;i<e.length;i++)e instanceof Int16Array?s.setInt16(i*2,e[i],!0):s.setUint16(i*2,e[i],!0);return y(t,new Uint8Array(s.buffer))}else if(e instanceof Int32Array||e instanceof Uint32Array){let s=new DataView(new ArrayBuffer(e.length*4));for(let i=0;i<e.length;i++)e instanceof Int32Array?s.setInt32(i*4,e[i],!0):s.setUint32(i*4,e[i],!0);return y(t,new Uint8Array(s.buffer))}else if(e instanceof BigInt64Array||e instanceof BigUint64Array){let s=new DataView(new ArrayBuffer(e.length*8));for(let i=0;i<e.length;i++)e instanceof BigInt64Array?s.setBigInt64(i*8,e[i],!0):s.setBigUint64(i*8,e[i],!0);return y(t,new Uint8Array(s.buffer))}else return y(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));let n=new M(new Uint8Array(t.byteLength+e.length),0);n.write(t);for(let s of e){let i=this._type.encodeValue(s);n.write(new Uint8Array(i))}return n.buffer}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=_(b.Vector),n=this._type.encodeType(e);e.add(this,y(t,n))}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new Error("Not a vector type");let s=Number(T(e));if(this._type instanceof O){if(this._type._bits==8)return new Uint8Array(e.read(s));if(this._type._bits==16){let o=e.read(s*2);return new Uint16Array(o.buffer,o.byteOffset,s)}if(this._type._bits==32){let o=e.read(s*4);return new Uint32Array(o.buffer,o.byteOffset,s)}if(this._type._bits==64)return new BigUint64Array(e.read(s*8).buffer)}if(this._type instanceof H){if(this._type._bits==8)return new Int8Array(e.read(s));if(this._type._bits==16){let o=e.read(s*2),a=new DataView(o.buffer,o.byteOffset,o.byteLength),c=new Int16Array(s);for(let u=0;u<s;u++)c[u]=a.getInt16(u*2,!0);return c}if(this._type._bits==32){let o=e.read(s*4),a=new DataView(o.buffer,o.byteOffset,o.byteLength),c=new Int32Array(s);for(let u=0;u<s;u++)c[u]=a.getInt32(u*4,!0);return c}if(this._type._bits==64){let o=e.read(s*8),a=new DataView(o.buffer,o.byteOffset,o.byteLength),c=new BigInt64Array(s);for(let u=0;u<s;u++)c[u]=a.getBigInt64(u*8,!0);return c}}let i=[];for(let o=0;o<s;o++)i.push(this._type.decodeValue(e,n._type));return i}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(e){return"vec {"+e.map(n=>this._type.valueToString(n)).join("; ")+"}"}},Y=class r extends ${get typeName(){return p.OptClass}static[Symbol.hasInstance](e){return e.typeName===p.OptClass}constructor(e){super(),this._type=e}accept(e,t){return e.visitOpt(this,this._type,t)}covariant(e){try{if(Array.isArray(e)&&(e.length===0||e.length===1&&this._type.covariant(e[0])))return!0}catch(t){throw new Error(`Invalid ${this.display()} argument: ${x(e)}
129
+ index ${s} -> ${i.message}`,{cause:i})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){let t=_(e.length);if(this._blobOptimization)return y(t,new Uint8Array(e));if(ArrayBuffer.isView(e)){if(e instanceof Int16Array||e instanceof Uint16Array){let s=new DataView(new ArrayBuffer(e.length*2));for(let i=0;i<e.length;i++)e instanceof Int16Array?s.setInt16(i*2,e[i],!0):s.setUint16(i*2,e[i],!0);return y(t,new Uint8Array(s.buffer))}if(e instanceof Int32Array||e instanceof Uint32Array){let s=new DataView(new ArrayBuffer(e.length*4));for(let i=0;i<e.length;i++)e instanceof Int32Array?s.setInt32(i*4,e[i],!0):s.setUint32(i*4,e[i],!0);return y(t,new Uint8Array(s.buffer))}if(e instanceof BigInt64Array||e instanceof BigUint64Array){let s=new DataView(new ArrayBuffer(e.length*8));for(let i=0;i<e.length;i++)e instanceof BigInt64Array?s.setBigInt64(i*8,e[i],!0):s.setBigUint64(i*8,e[i],!0);return y(t,new Uint8Array(s.buffer))}return y(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}let n=new P(new Uint8Array(t.byteLength+e.length),0);n.write(t);for(let s of e){let i=this._type.encodeValue(s);n.write(new Uint8Array(i))}return n.buffer}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=w(b.Vector),n=this._type.encodeType(e);e.add(this,y(t,n))}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new v(`Expected type '${this.display()}', but received non-vector type '${n.display()}'`);let s=Number(T(e));if(this._type instanceof O){if(this._type._bits==8)return new Uint8Array(e.read(s));if(this._type._bits==16){let o=e.read(s*2);return new Uint16Array(o.buffer,o.byteOffset,s)}if(this._type._bits==32){let o=e.read(s*4);return new Uint32Array(o.buffer,o.byteOffset,s)}if(this._type._bits==64)return new BigUint64Array(e.read(s*8).buffer)}if(this._type instanceof H){if(this._type._bits==8)return new Int8Array(e.read(s));if(this._type._bits==16){let o=e.read(s*2),a=new DataView(o.buffer,o.byteOffset,o.byteLength),c=new Int16Array(s);for(let u=0;u<s;u++)c[u]=a.getInt16(u*2,!0);return c}if(this._type._bits==32){let o=e.read(s*4),a=new DataView(o.buffer,o.byteOffset,o.byteLength),c=new Int32Array(s);for(let u=0;u<s;u++)c[u]=a.getInt32(u*4,!0);return c}if(this._type._bits==64){let o=e.read(s*8),a=new DataView(o.buffer,o.byteOffset,o.byteLength),c=new BigInt64Array(s);for(let u=0;u<s;u++)c[u]=a.getBigInt64(u*8,!0);return c}}let i=[];for(let o=0;o<s;o++)i.push(this._type.decodeValue(e,n._type));return i}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(e){return`vec {${e.map(n=>this._type.valueToString(n)).join("; ")}}`}},X=class r extends F{get typeName(){return p.OptClass}static[Symbol.hasInstance](e){return e.typeName===p.OptClass}constructor(e){super(),this._type=e}accept(e,t){return e.visitOpt(this,this._type,t)}covariant(e){try{if(Array.isArray(e)&&(e.length===0||e.length===1&&this._type.covariant(e[0])))return!0}catch(t){throw new Error(`Invalid ${this.display()} argument: ${g(e)}
130
130
 
131
- -> ${t.message}`)}throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){return e.length===0?new Uint8Array([0]):y(new Uint8Array([1]),this._type.encodeValue(e[0]))}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=_(b.Opt),n=this._type.encodeType(e);e.add(this,y(t,n))}decodeValue(e,t){if(t instanceof ee)return[];if(t instanceof F)return[];let n=t;if(t instanceof I){let s=t.getType();if(typeof s>"u")throw new Error("type mismatch with uninitialized type");n=s}if(n instanceof r)switch(Q(e)){case 0:return[];case 1:{let s=e.save();try{return[this._type.decodeValue(e,n._type)]}catch{return e.restore(s),n._type.decodeValue(e,n._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof ee||this._type instanceof r||this._type instanceof F)return n.decodeValue(e,n),[];{let s=e.save();try{return[this._type.decodeValue(e,t)]}catch{return e.restore(s),n.decodeValue(e,t),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(e){return e.length===0?"null":`opt ${this._type.valueToString(e[0])}`}},te=class r extends ${get typeName(){return p.RecordClass}static[Symbol.hasInstance](e){return e.typeName===p.RecordClass||e.typeName===p.TupleClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((t,n)=>E(t[0])-E(n[0]))}accept(e,t){return e.visitRecord(this,this._fields,t)}tryAsTuple(){let e=[];for(let t=0;t<this._fields.length;t++){let[n,s]=this._fields[t];if(n!==`_${t}_`)return null;e.push(s)}return e}covariant(e){if(typeof e=="object"&&this._fields.every(([t,n])=>{if(!e.hasOwnProperty(t))throw new Error(`Record is missing key "${t}".`);try{return n.covariant(e[t])}catch(s){throw new Error(`Invalid ${this.display()} argument:
131
+ -> ${t.message}`,{cause:t})}throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){return e.length===0?new Uint8Array([0]):y(new Uint8Array([1]),this._type.encodeValue(e[0]))}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let t=w(b.Opt),n=this._type.encodeType(e);e.add(this,y(t,n))}decodeValue(e,t){if(t instanceof te)return[];if(t instanceof k)return[];let n=t;if(t instanceof C){let s=t.getType();if(typeof s>"u")throw new v("Type mismatch: cannot decode from uninitialized recursive type");n=s}if(n instanceof r)switch(Q(e)){case 0:return[];case 1:{let s=e.save();try{return[this._type.decodeValue(e,n._type)]}catch{return e.restore(s),n._type.decodeValue(e,n._type),[]}}default:throw new v(`Invalid option value: expected 0 (None) or 1 (Some) for type '${this.display()}'`)}else{if(this._type instanceof te||this._type instanceof r||this._type instanceof k)return n.decodeValue(e,n),[];{let s=e.save();try{return[this._type.decodeValue(e,t)]}catch{return e.restore(s),n.decodeValue(e,t),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(e){return e.length===0?"null":`opt ${this._type.valueToString(e[0])}`}},re=class r extends F{get typeName(){return p.RecordClass}static[Symbol.hasInstance](e){return e.typeName===p.RecordClass||e.typeName===p.TupleClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((t,n)=>E(t[0])-E(n[0]))}accept(e,t){return e.visitRecord(this,this._fields,t)}tryAsTuple(){let e=[];for(let t=0;t<this._fields.length;t++){let[n,s]=this._fields[t];if(n!==`_${t}_`)return null;e.push(s)}return e}covariant(e){if(typeof e=="object"&&this._fields.every(([t,n])=>{if(!e.hasOwnProperty(t))throw new Error(`Record is missing key "${t}".`);try{return n.covariant(e[t])}catch(s){throw new Error(`Invalid ${this.display()} argument:
132
132
 
133
- field ${t} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){let t=this._fields.map(([s])=>e[s]),n=be(this._fields,t,([,s],i)=>s.encodeValue(i));return y(...n)}_buildTypeTableImpl(e){this._fields.forEach(([i,o])=>o.buildTypeTable(e));let t=_(b.Record),n=w(this._fields.length),s=this._fields.map(([i,o])=>y(w(E(i)),o.encodeType(e)));e.add(this,y(t,n,y(...s)))}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new Error("Not a record type");let s={},i=0,o=0;for(;o<n._fields.length;){let[a,c]=n._fields[o];if(i>=this._fields.length){c.decodeValue(e,c),o++;continue}let[u,h]=this._fields[i],d=E(this._fields[i][0]),l=E(a);if(d===l)s[u]=h.decodeValue(e,c),i++,o++;else if(l>d)if(h instanceof Y||h instanceof F)s[u]=[],i++;else throw new Error("Cannot find required field "+u);else c.decodeValue(e,c),o++}for(let[a,c]of this._fields.slice(i))if(c instanceof Y||c instanceof F)s[a]=[];else throw new Error("Cannot find required field "+a);return s}get fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[E(t)]=n;return e}get name(){return`record {${this._fields.map(([t,n])=>t+":"+n.name).join("; ")}}`}display(){return`record {${this._fields.map(([t,n])=>t+":"+n.display()).join("; ")}}`}valueToString(e){let t=this._fields.map(([s])=>e[s]);return`record {${be(this._fields,t,([s,i],o)=>s+"="+i.valueToString(o)).join("; ")}}`}},Le=class r extends te{get typeName(){return p.TupleClass}static[Symbol.hasInstance](e){return e.typeName===p.TupleClass}constructor(e){let t={};e.forEach((n,s)=>t["_"+s+"_"]=n),super(t),this._components=e}accept(e,t){return e.visitTuple(this,this._components,t)}covariant(e){if(Array.isArray(e)&&e.length>=this._fields.length&&this._components.every((t,n)=>{try{return t.covariant(e[n])}catch(s){throw new Error(`Invalid ${this.display()} argument:
133
+ field ${t} -> ${s.message}`,{cause:s})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){let t=this._fields.map(([s])=>e[s]),n=ge(this._fields,t,([,s],i)=>s.encodeValue(i));return y(...n)}_buildTypeTableImpl(e){this._fields.forEach(([i,o])=>o.buildTypeTable(e));let t=w(b.Record),n=_(this._fields.length),s=this._fields.map(([i,o])=>y(_(E(i)),o.encodeType(e)));e.add(this,y(t,n,y(...s)))}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new v(`Expected type '${this.display()}', but received non-record type '${n.display()}'`);let s={},i=0,o=0;for(;o<n._fields.length;){let[a,c]=n._fields[o];if(i>=this._fields.length){c.decodeValue(e,c),o++;continue}let[u,m]=this._fields[i],f=E(this._fields[i][0]),d=E(a);if(f===d)s[u]=m.decodeValue(e,c),i++,o++;else if(d>f)if(m instanceof X||m instanceof k)s[u]=[],i++;else{let l=this._fields.map(([x])=>x).join(", "),h=n._fields.map(([x])=>x).join(", ");throw new v(`Cannot find required field '${u}' in record, expected fields: [${l}], received fields: [${h}]`)}else c.decodeValue(e,c),o++}for(let[a,c]of this._fields.slice(i))if(c instanceof X||c instanceof k)s[a]=[];else{let u=this._fields.map(([f])=>f).join(", "),m=n._fields.map(([f])=>f).join(", ");throw new v(`Cannot find required field '${a}' in record, expected fields: [${u}], received fields: [${m}]`)}return s}get fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[E(t)]=n;return e}get name(){return`record {${this._fields.map(([t,n])=>`${t}:${n.name}`).join("; ")}}`}display(){return`record {${this._fields.map(([t,n])=>`${t}:${n.display()}`).join("; ")}}`}valueToString(e){let t=this._fields.map(([s])=>e[s]);return`record {${ge(this._fields,t,([s,i],o)=>`${s}=${i.valueToString(o)}`).join("; ")}}`}},Pe=class r extends re{get typeName(){return p.TupleClass}static[Symbol.hasInstance](e){return e.typeName===p.TupleClass}constructor(e){let t={};e.forEach((n,s)=>t[`_${s}_`]=n),super(t),this._components=e}accept(e,t){return e.visitTuple(this,this._components,t)}covariant(e){if(Array.isArray(e)&&e.length>=this._fields.length&&this._components.every((t,n)=>{try{return t.covariant(e[n])}catch(s){throw new Error(`Invalid ${this.display()} argument:
134
134
 
135
- index ${n} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){let t=be(this._components,e,(n,s)=>n.encodeValue(s));return y(...t)}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new Error("not a tuple type");if(n._components.length<this._components.length)throw new Error("tuple mismatch");let s=[];for(let[i,o]of n._components.entries())i>=this._components.length?o.decodeValue(e,o):s.push(this._components[i].decodeValue(e,o));return s}display(){return`record {${this._components.map(t=>t.display()).join("; ")}}`}valueToString(e){return`record {${be(this._components,e,(n,s)=>n.valueToString(s)).join("; ")}}`}},de=class r extends ${get typeName(){return p.VariantClass}static[Symbol.hasInstance](e){return e.typeName===p.VariantClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((t,n)=>E(t[0])-E(n[0]))}accept(e,t){return e.visitVariant(this,this._fields,t)}covariant(e){if(typeof e=="object"&&Object.entries(e).length===1&&this._fields.every(([t,n])=>{try{return!e.hasOwnProperty(t)||n.covariant(e[t])}catch(s){throw new Error(`Invalid ${this.display()} argument:
135
+ index ${n} -> ${s.message}`,{cause:s})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){let t=ge(this._components,e,(n,s)=>n.encodeValue(s));return y(...t)}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new v(`Expected type '${this.display()}', but received non-tuple type '${n.display()}'`);if(n._components.length<this._components.length)throw new v(`Tuple mismatch: expected ${this._components.length} components, but received ${n._components.length}`);let s=[];for(let[i,o]of n._components.entries())i>=this._components.length?o.decodeValue(e,o):s.push(this._components[i].decodeValue(e,o));return s}display(){return`record {${this._components.map(t=>t.display()).join("; ")}}`}valueToString(e){return`record {${ge(this._components,e,(n,s)=>n.valueToString(s)).join("; ")}}`}},fe=class r extends F{get typeName(){return p.VariantClass}static[Symbol.hasInstance](e){return e.typeName===p.VariantClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((t,n)=>E(t[0])-E(n[0]))}accept(e,t){return e.visitVariant(this,this._fields,t)}covariant(e){if(typeof e=="object"&&Object.entries(e).length===1&&this._fields.every(([t,n])=>{try{return!e.hasOwnProperty(t)||n.covariant(e[t])}catch(s){throw new Error(`Invalid ${this.display()} argument:
136
136
 
137
- variant ${t} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){for(let t=0;t<this._fields.length;t++){let[n,s]=this._fields[t];if(e.hasOwnProperty(n)){let i=w(t),o=s.encodeValue(e[n]);return y(i,o)}}throw Error("Variant has no data: "+e)}_buildTypeTableImpl(e){this._fields.forEach(([,i])=>{i.buildTypeTable(e)});let t=_(b.Variant),n=w(this._fields.length),s=this._fields.map(([i,o])=>y(w(E(i)),o.encodeType(e)));e.add(this,y(t,n,...s))}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new Error("Not a variant type");let s=Number(T(e));if(s>=n._fields.length)throw Error("Invalid variant index: "+s);let[i,o]=n._fields[s];for(let[a,c]of this._fields)if(E(i)===E(a)){let u=c.decodeValue(e,o);return{[a]:u}}throw new Error("Cannot find field hash "+i)}get name(){return`variant {${this._fields.map(([t,n])=>t+":"+n.name).join("; ")}}`}display(){return`variant {${this._fields.map(([t,n])=>t+(n.name==="null"?"":`:${n.display()}`)).join("; ")}}`}valueToString(e){for(let[t,n]of this._fields)if(e.hasOwnProperty(t)){let s=n.valueToString(e[t]);return s==="null"?`variant {${t}}`:`variant {${t}=${s}}`}throw new Error("Variant has no data: "+e)}get alternativesAsObject(){let e={};for(let[t,n]of this._fields)e[E(t)]=n;return e}},I=class r extends ${constructor(){super(...arguments),this._id=r._counter++}get typeName(){return p.RecClass}static{this._counter=0}static[Symbol.hasInstance](e){return e.typeName===p.RecClass}accept(e,t){if(!this._type)throw Error("Recursive type uninitialized.");return e.visitRec(this,this._type,t)}fill(e){this._type=e}getType(){return this._type}covariant(e){if(this._type&&this._type.covariant(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(e)}_buildTypeTableImpl(e){if(!this._type)throw Error("Recursive type uninitialized.");e.add(this,new Uint8Array([])),this._type.buildTypeTable(e),e.merge(this,this._type.name)}decodeValue(e,t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(e,t)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(e)}};function rt(r){if(Q(r)!==1)throw new Error("Cannot decode principal");let t=Number(T(r));return Ue.fromUint8Array(new Uint8Array(Z(r,t)))}var Ve=class extends v{get typeName(){return p.PrincipalClass}static[Symbol.hasInstance](e){return e.typeName===p.PrincipalClass}accept(e,t){return e.visitPrincipal(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=w(t.byteLength);return y(new Uint8Array([1]),n,t)}encodeType(){return _(b.Principal)}decodeValue(e,t){return this.checkType(t),rt(e)}get name(){return"principal"}valueToString(e){return`${this.name} "${e.toText()}"`}},re=class extends ${get typeName(){return p.FuncClass}static[Symbol.hasInstance](e){return e.typeName===p.FuncClass}static argsToString(e,t){if(e.length!==t.length)throw new Error("arity mismatch");return"("+e.map((n,s)=>n.valueToString(t[s])).join(", ")+")"}constructor(e,t,n=[]){super(),this.argTypes=e,this.retTypes=t,this.annotations=n}accept(e,t){return e.visitFunc(this,t)}covariant(e){if(Array.isArray(e)&&e.length===2&&e[0]&&e[0]._isPrincipal&&typeof e[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue([e,t]){let n=e.toUint8Array(),s=w(n.byteLength),i=y(new Uint8Array([1]),s,n),o=new TextEncoder().encode(t),a=w(o.byteLength);return y(new Uint8Array([1]),i,a,o)}_buildTypeTableImpl(e){this.argTypes.forEach(u=>u.buildTypeTable(e)),this.retTypes.forEach(u=>u.buildTypeTable(e));let t=_(b.Func),n=w(this.argTypes.length),s=y(...this.argTypes.map(u=>u.encodeType(e))),i=w(this.retTypes.length),o=y(...this.retTypes.map(u=>u.encodeType(e))),a=w(this.annotations.length),c=y(...this.annotations.map(u=>this.encodeAnnotation(u)));e.add(this,y(t,n,s,i,o,a,c))}decodeValue(e,t){let n=t instanceof I?t.getType()??t:t;if(!nt(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Q(e)!==1)throw new Error("Cannot decode function reference");let i=rt(e),o=Number(T(e)),a=Z(e,o),u=new TextDecoder("utf8",{fatal:!0}).decode(a);return[i,u]}get name(){let e=this.argTypes.map(s=>s.name).join(", "),t=this.retTypes.map(s=>s.name).join(", "),n=" "+this.annotations.join(" ");return`(${e}) -> (${t})${n}`}valueToString([e,t]){return`func "${e.toText()}".${t}`}display(){let e=this.argTypes.map(s=>s.display()).join(", "),t=this.retTypes.map(s=>s.display()).join(", "),n=" "+this.annotations.join(" ");return`(${e}) \u2192 (${t})${n}`}encodeAnnotation(e){if(e==="query")return new Uint8Array([1]);if(e==="oneway")return new Uint8Array([2]);if(e==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}},fe=class extends ${get typeName(){return p.ServiceClass}static[Symbol.hasInstance](e){return e.typeName===p.ServiceClass}constructor(e){super(),this._fields=Object.entries(e).sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0)}accept(e,t){return e.visitService(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${x(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=w(t.length);return y(new Uint8Array([1]),n,t)}_buildTypeTableImpl(e){this._fields.forEach(([i,o])=>o.buildTypeTable(e));let t=_(b.Service),n=w(this._fields.length),s=this._fields.map(([i,o])=>{let a=new TextEncoder().encode(i),c=w(a.length);return y(c,a,o.encodeType(e))});e.add(this,y(t,n,...s))}decodeValue(e,t){let n=t instanceof I?t.getType()??t:t;if(!nt(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return rt(e)}get name(){return`service {${this._fields.map(([t,n])=>t+":"+n.name).join("; ")}}`}valueToString(e){return`service "${e.toText()}"`}fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[t]=n;return e}};function x(r){let e=JSON.stringify(r,(t,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return e&&e.length>Dt?e.substring(0,Dt-3)+"...":e}function bn(r,e){if(e.length<r.length)throw Error("Wrong number of message arguments");let t=new Xe;r.forEach(a=>a.buildTypeTable(t));let n=t.encode(),s=w(e.length),i=y(...r.map(a=>a.encodeType(t))),o=y(...be(r,e,(a,c)=>{try{a.covariant(c)}catch(u){throw new Error(u.message+`
137
+ variant ${t} -> ${s.message}`,{cause:s})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){for(let t=0;t<this._fields.length;t++){let[n,s]=this._fields[t];if(e.hasOwnProperty(n)){let i=_(t),o=s.encodeValue(e[n]);return y(i,o)}}throw Error(`Variant has no data: ${e}`)}_buildTypeTableImpl(e){this._fields.forEach(([,i])=>{i.buildTypeTable(e)});let t=w(b.Variant),n=_(this._fields.length),s=this._fields.map(([i,o])=>y(_(E(i)),o.encodeType(e)));e.add(this,y(t,n,...s))}decodeValue(e,t){let n=this.checkType(t);if(!(n instanceof r))throw new v(`Expected type '${this.display()}', but received non-variant type '${n.display()}'`);let s=Number(T(e));if(s>=n._fields.length)throw Error(`Invalid variant index: ${s}`);let[i,o]=n._fields[s];for(let[c,u]of this._fields)if(E(i)===E(c)){let m=u.decodeValue(e,o);return{[c]:m}}let a=this._fields.map(([c])=>c).join(", ");throw new v(`Cannot find field hash ${i} in variant, expected fields: [${a}]`)}get name(){return`variant {${this._fields.map(([t,n])=>`${t}:${n.name}`).join("; ")}}`}display(){return`variant {${this._fields.map(([t,n])=>t+(n.name==="null"?"":`:${n.display()}`)).join("; ")}}`}valueToString(e){for(let[t,n]of this._fields)if(e.hasOwnProperty(t)){let s=n.valueToString(e[t]);return s==="null"?`variant {${t}}`:`variant {${t}=${s}}`}throw new Error(`Variant has no data: ${e}`)}get alternativesAsObject(){let e={};for(let[t,n]of this._fields)e[E(t)]=n;return e}},C=class r extends F{constructor(){super(...arguments),this._id=r._counter++}get typeName(){return p.RecClass}static{this._counter=0}static[Symbol.hasInstance](e){return e.typeName===p.RecClass}accept(e,t){if(!this._type)throw Error("Recursive type uninitialized.");return e.visitRec(this,this._type,t)}fill(e){this._type=e}getType(){return this._type}covariant(e){if(this._type&&this._type.covariant(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(e)}_buildTypeTableImpl(e){if(!this._type)throw Error("Recursive type uninitialized.");e.add(this,new Uint8Array([])),this._type.buildTypeTable(e),e.merge(this,this._type.name)}decodeValue(e,t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(e,t)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(e)}};function nt(r){if(Q(r)!==1)throw new Error("Cannot decode principal");let t=Number(T(r));return Oe.fromUint8Array(new Uint8Array(Z(r,t)))}var Me=class extends I{get typeName(){return p.PrincipalClass}static[Symbol.hasInstance](e){return e.typeName===p.PrincipalClass}accept(e,t){return e.visitPrincipal(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=_(t.byteLength);return y(new Uint8Array([1]),n,t)}encodeType(){return w(b.Principal)}decodeValue(e,t){return this.checkType(t),nt(e)}get name(){return"principal"}valueToString(e){return`${this.name} "${e.toText()}"`}},ne=class extends F{get typeName(){return p.FuncClass}static[Symbol.hasInstance](e){return e.typeName===p.FuncClass}static argsToString(e,t){if(e.length!==t.length)throw new Error("arity mismatch");return`(${e.map((n,s)=>n.valueToString(t[s])).join(", ")})`}constructor(e,t,n=[]){super(),this.argTypes=e,this.retTypes=t,this.annotations=n}accept(e,t){return e.visitFunc(this,t)}covariant(e){if(Array.isArray(e)&&e.length===2&&e[0]&&e[0]._isPrincipal&&typeof e[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue([e,t]){let n=e.toUint8Array(),s=_(n.byteLength),i=y(new Uint8Array([1]),s,n),o=new TextEncoder().encode(t),a=_(o.byteLength);return y(new Uint8Array([1]),i,a,o)}_buildTypeTableImpl(e){this.argTypes.forEach(u=>u.buildTypeTable(e)),this.retTypes.forEach(u=>u.buildTypeTable(e));let t=w(b.Func),n=_(this.argTypes.length),s=y(...this.argTypes.map(u=>u.encodeType(e))),i=_(this.retTypes.length),o=y(...this.retTypes.map(u=>u.encodeType(e))),a=_(this.annotations.length),c=y(...this.annotations.map(u=>this.encodeAnnotation(u)));e.add(this,y(t,n,s,i,o,a,c))}decodeValue(e,t){let n=t instanceof C?t.getType()??t:t;if(!st(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Q(e)!==1)throw new Error("Cannot decode function reference");let i=nt(e),o=Number(T(e)),a=Z(e,o),u=new TextDecoder("utf8",{fatal:!0}).decode(a);return[i,u]}get name(){let e=this.argTypes.map(s=>s.name).join(", "),t=this.retTypes.map(s=>s.name).join(", "),n=` ${this.annotations.join(" ")}`;return`(${e}) -> (${t})${n}`}valueToString([e,t]){return`func "${e.toText()}".${t}`}display(){let e=this.argTypes.map(s=>s.display()).join(", "),t=this.retTypes.map(s=>s.display()).join(", "),n=` ${this.annotations.join(" ")}`;return`(${e}) \u2192 (${t})${n}`}encodeAnnotation(e){if(e==="query")return new Uint8Array([1]);if(e==="oneway")return new Uint8Array([2]);if(e==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}},pe=class extends F{get typeName(){return p.ServiceClass}static[Symbol.hasInstance](e){return e.typeName===p.ServiceClass}constructor(e){super(),this._fields=Object.entries(e).sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0)}accept(e,t){return e.visitService(this,t)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${g(e)}`)}encodeValue(e){let t=e.toUint8Array(),n=_(t.length);return y(new Uint8Array([1]),n,t)}_buildTypeTableImpl(e){this._fields.forEach(([i,o])=>o.buildTypeTable(e));let t=w(b.Service),n=_(this._fields.length),s=this._fields.map(([i,o])=>{let a=new TextEncoder().encode(i),c=_(a.length);return y(c,a,o.encodeType(e))});e.add(this,y(t,n,...s))}decodeValue(e,t){let n=t instanceof C?t.getType()??t:t;if(!st(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return nt(e)}get name(){return`service {${this._fields.map(([t,n])=>`${t}:${n.name}`).join("; ")}}`}valueToString(e){return`service "${e.toText()}"`}fieldsAsObject(){let e={};for(let[t,n]of this._fields)e[t]=n;return e}};function g(r){let e=JSON.stringify(r,(t,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return e&&e.length>zt?`${e.substring(0,zt-3)}...`:e}function _n(r,e){if(e.length<r.length)throw Error("Wrong number of message arguments");let t=new et;r.forEach(a=>a.buildTypeTable(t));let n=t.encode(),s=_(e.length),i=y(...r.map(a=>a.encodeType(t))),o=y(...ge(r,e,(a,c)=>{try{a.covariant(c)}catch(u){throw new Error(`${u.message}
138
138
 
139
- `)}return a.encodeValue(c)}));return y(yn,n,s,i,o)}function xn(r,e){let t=new M(e);if(e.byteLength<$e.length)throw new Error("Message length smaller than magic number");let n=Z(t,$e.length),s=new TextDecoder().decode(n);if(s!==$e)throw new Error("Wrong magic number: "+JSON.stringify(s));function i(l){let f=[],m=Number(T(l));for(let S=0;S<m;S++){let k=Number(P(l));switch(k){case b.Opt:case b.Vector:{let B=Number(P(l));f.push([k,B]);break}case b.Record:case b.Variant:{let B=[],ie=Number(T(l)),z;for(;ie--;){let J=Number(T(l));if(J>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof z=="number"&&z>=J)throw new Error("field id collision or not sorted");z=J;let G=Number(P(l));B.push([J,G])}f.push([k,B]);break}case b.Func:{let B=[],ie=Number(T(l));for(;ie--;)B.push(Number(P(l)));let z=[],J=Number(T(l));for(;J--;)z.push(Number(P(l)));let G=[],Sr=Number(T(l));for(;Sr--;)switch(Number(T(l))){case 1:{G.push("query");break}case 2:{G.push("oneway");break}case 3:{G.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([k,[B,z,G]]);break}case b.Service:{let B=Number(T(l)),ie=[];for(;B--;){let z=Number(T(l)),J=new TextDecoder().decode(Z(l,z)),G=P(l);ie.push([J,G])}f.push([k,ie]);break}default:throw new Error("Illegal op_code: "+k)}}let g=[],N=Number(T(l));for(let S=0;S<N;S++)g.push(Number(P(l)));return[f,g]}let[o,a]=i(t);if(a.length<r.length)throw new Error("Wrong number of return values");let c=o.map(l=>fr());function u(l){if(l<-24)throw new Error("future value not supported");if(l<0)switch(l){case-1:return Gt;case-2:return Jt;case-3:return Kt;case-4:return qt;case-5:return rr;case-6:return nr;case-7:return sr;case-8:return ir;case-9:return Yt;case-10:return Xt;case-11:return er;case-12:return tr;case-13:return Qt;case-14:return Zt;case-15:return Wt;case-16:return zt;case-17:return Ht;case-24:return or;default:throw new Error("Illegal op_code: "+l)}if(l>=o.length)throw new Error("type index out of range");return c[l]}function h(l){switch(l[0]){case b.Vector:{let f=u(l[1]);return cr(f)}case b.Opt:{let f=u(l[1]);return ur(f)}case b.Record:{let f={};for(let[N,S]of l[1]){let k=`_${N}_`;f[k]=u(S)}let m=lr(f),g=m.tryAsTuple();return Array.isArray(g)?ar(...g):m}case b.Variant:{let f={};for(let[m,g]of l[1]){let N=`_${m}_`;f[N]=u(g)}return dr(f)}case b.Func:{let[f,m,g]=l[1];return pr(f.map(N=>u(N)),m.map(N=>u(N)),g)}case b.Service:{let f={},m=l[1];for(let[g,N]of m){let S=u(N);if(S instanceof I&&(S=S.getType()),!(S instanceof re))throw new Error("Illegal service definition: services can only contain functions");f[g]=S}return hr(f)}default:throw new Error("Illegal op_code: "+l[0])}}o.forEach((l,f)=>{if(l[0]===b.Func){let m=h(l);c[f].fill(m)}}),o.forEach((l,f)=>{if(l[0]!==b.Func){let m=h(l);c[f].fill(m)}}),tt();let d=a.map(l=>u(l));try{let l=r.map((f,m)=>f.decodeValue(t,d[m]));for(let f=r.length;f<d.length;f++)d[f].decodeValue(t,d[f]);if(t.byteLength>0)throw new Error("decode: Left-over bytes");return l}finally{tt()}}var Ht=new xe,zt=new F,gn=new ke,Jt=new Be,Gt=new ee,Wt=new je,qt=new ge,Kt=new we,Qt=new _e(32),Zt=new _e(64),Yt=new H(8),Xt=new H(16),er=new H(32),tr=new H(64),rr=new O(8),nr=new O(16),sr=new O(32),ir=new O(64),or=new Ve;function ar(...r){return new Le(r)}function cr(r){return new le(r)}function ur(r){return new Y(r)}function lr(r){return new te(r)}function dr(r){return new de(r)}function fr(){return new I}function pr(r,e,t=[]){return new re(r,e,t)}function hr(r){return new fe(r)}var Me=class r{constructor(e=new Map){this.rels=e}copy(){let e=new Map;for(let[t,n]of this.rels.entries()){let s=new Map(n);e.set(t,s)}return new r(e)}known(e,t){return this.rels.get(e.name)?.get(t.name)}addNegative(e,t){this.addNames(e.name,t.name,!1)}add(e,t){this.addNames(e.name,t.name,!0)}display(){let e="";for(let[t,n]of this.rels)for(let[s,i]of n)e+=`${t} ${i?":<":"!<:"} ${s}
140
- `;return e}addNames(e,t,n){let s=this.rels.get(e);if(s==null){let i=new Map;i.set(t,n),this.rels.set(e,i)}else s.set(t,n)}},Fe=new Me;function tt(){Fe=new Me}function wn(r,e){let t=new Set(r.annotations),n=new Set(e.annotations);if(t.size!==n.size)return!1;for(let s of t)if(!n.has(s))return!1;return!0}function Ye(r){return r instanceof Y||r instanceof ee||r instanceof F}function nt(r,e){let t=Fe.copy(),n=D(t,r,e);return n?Fe.add(r,e):Fe.addNegative(r,e),n}function D(r,e,t){if(e.name===t.name)return!0;let n=r.known(e,t);if(n!==void 0)return n;if(r.add(e,t),t instanceof F||e instanceof xe||e instanceof we&&t instanceof ge)return!0;if(e instanceof le&&t instanceof le)return D(r,e._type,t._type);if(t instanceof Y)return!0;if(e instanceof te&&t instanceof te){let s=e.fieldsAsObject;for(let[i,o]of t._fields){let a=s[E(i)];if(a){if(!D(r,a,o))return!1}else if(!Ye(o))return!1}return!0}if(e instanceof re&&t instanceof re){if(!wn(e,t))return!1;for(let s=0;s<e.argTypes.length;s++){let i=e.argTypes[s];if(s<t.argTypes.length){if(!D(r,t.argTypes[s],i))return!1}else if(!Ye(i))return!1}for(let s=0;s<t.retTypes.length;s++){let i=t.retTypes[s];if(s<e.retTypes.length){if(!D(r,e.retTypes[s],i))return!1}else if(!Ye(i))return!1}return!0}if(e instanceof de&&t instanceof de){let s=t.alternativesAsObject;for(let[i,o]of e._fields){let a=s[E(i)];if(!a||!D(r,o,a))return!1}return!0}if(e instanceof fe&&t instanceof fe){let s=e.fieldsAsObject();for(let[i,o]of t._fields){let a=s[i];if(!a||!D(r,a,o))return!1}return!0}return e instanceof I?D(r,e.getType(),t):t instanceof I?D(r,e,t.getType()):!1}import{capitalize as _n}from"@junobuild/utils";var pe=r=>{switch(r.kind){case"text":return A.Text;case"bool":return A.Bool;case"float64":return A.Float64;case"int32":return A.Int32;case"nat":return A.Nat64;case"principal":return A.Principal;case"uint8array":return A.Vec(A.Nat8);case"opt":return A.Opt(pe(r.inner));case"vec":return A.Vec(pe(r.inner));case"tuple":case"indexedTuple":return A.Tuple(...r.members.map(pe));case"record":return A.Record(Object.fromEntries(r.fields.map(e=>[e.name,pe(e.type)])));case"variant":return A.Variant(Object.fromEntries(r.tags.map(e=>[e,A.Null])));case"discriminatedUnion":return A.Variant(Object.fromEntries(r.members.map((e,t)=>{let n=e.kind==="record"?e.fields.find(i=>i.name===r.discriminator)?.type.kind==="variant"?(e.fields.find(i=>i.name===r.discriminator)?.type).tags[0]:`Variant${t}`:`Variant${t}`,s=e.kind==="record"?{kind:"record",fields:e.fields.filter(i=>i.name!==r.discriminator)}:e;return[n,pe(s)]})))}},Sn=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let i=pe(t?{kind:"opt",inner:e}:e);return{baseName:`${_n(r)}${n}`,idl:i}},fi=({id:r,schema:e,suffix:t})=>{let n=W({zodSchema:e,id:r});return Sn({...n,suffix:t})};import{capitalize as ne}from"@junobuild/utils";var mr="#[derive(CandidType, Serialize, Deserialize, Clone, JsonData)]",Tn="#[derive(CandidType, Serialize, Deserialize, Clone)]",An=new Set(["type","struct","enum","fn","let","match","use","mod","impl","trait","where","move","ref","self","super","crate"]),yr=r=>An.has(r)?{name:`r#${r}`,sanitized:!0}:{name:r,sanitized:!1},R=r=>({kind:"primitive",...r}),he=r=>({kind:"composite",needsJsonData:!0,...r}),st=r=>r.flatMap(e=>e.kind==="composite"?e.structs:[]),se=({schema:r,structName:e})=>{switch(r.kind){case"text":return R({fieldType:"String"});case"bool":return R({fieldType:"bool"});case"float64":return R({fieldType:"f64"});case"int32":return R({fieldType:"i32"});case"nat":return R({fieldType:"u64"});case"principal":return R({fieldType:"Principal"});case"uint8array":return R({fieldType:"Vec<u8>"});case"opt":{let t=se({schema:r.inner,structName:e}),n=`Option<${t.fieldType}>`;return t.kind==="composite"?he({fieldType:n,structs:t.structs}):R({fieldType:n})}case"vec":{let t=se({schema:r.inner,structName:e}),n=`Vec<${t.fieldType}>`;return t.kind==="composite"?he({fieldType:n,structs:t.structs}):R({fieldType:n})}case"tuple":case"indexedTuple":{let t=r.members.map((i,o)=>se({schema:i,structName:`${e}${o}`})),n=`(${t.map(i=>i.fieldType).join(", ")})`,s=st(t);return s.length>0?he({fieldType:n,structs:s}):R({fieldType:n})}case"variant":{if(r.tags.length===1)return R({fieldType:"String"});let t=ne(e),n=r.tags.map(s=>` #[serde(rename = "${s}")]
141
- ${ne(s)},`).join(`
142
- `);return he({fieldType:t,structs:[`${Tn}
139
+ `)}return a.encodeValue(c)}));return y(gn,n,s,i,o)}function wn(r,e){let t=new P(e);if(e.byteLength<ke.length)throw new Error("Message length smaller than magic number");let n=Z(t,ke.length),s=new TextDecoder().decode(n);if(s!==ke)throw new Error(`Wrong magic number: ${JSON.stringify(s)}`);function i(d){let l=[],h=Number(T(d));for(let N=0;N<h;N++){let z=Number(M(d));switch(z){case b.Opt:case b.Vector:{let j=Number(M(d));l.push([z,j]);break}case b.Record:case b.Variant:{let j=[],oe=Number(T(d)),J;for(;oe--;){let G=Number(T(d));if(G>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof J=="number"&&J>=G)throw new Error("field id collision or not sorted");J=G;let W=Number(M(d));j.push([G,W])}l.push([z,j]);break}case b.Func:{let j=[],oe=Number(T(d));for(;oe--;)j.push(Number(M(d)));let J=[],G=Number(T(d));for(;G--;)J.push(Number(M(d)));let W=[],Tr=Number(T(d));for(;Tr--;)switch(Number(T(d))){case 1:{W.push("query");break}case 2:{W.push("oneway");break}case 3:{W.push("composite_query");break}default:throw new Error("unknown annotation")}l.push([z,[j,J,W]]);break}case b.Service:{let j=Number(T(d)),oe=[];for(;j--;){let J=Number(T(d)),G=new TextDecoder().decode(Z(d,J)),W=M(d);oe.push([G,W])}l.push([z,oe]);break}default:throw new Error(`Illegal op_code: ${z}`)}}let x=[],A=Number(T(d));for(let N=0;N<A;N++)x.push(Number(M(d)));return[l,x]}let[o,a]=i(t);if(a.length<r.length)throw new Error("Wrong number of return values");let c=o.map(d=>hr());function u(d){if(d<-24)throw new Error("future value not supported");if(d<0)switch(d){case-1:return qt;case-2:return Wt;case-3:return Qt;case-4:return Yt;case-5:return sr;case-6:return ir;case-7:return or;case-8:return ar;case-9:return er;case-10:return tr;case-11:return rr;case-12:return nr;case-13:return Zt;case-14:return Xt;case-15:return Kt;case-16:return Gt;case-17:return Jt;case-24:return cr;default:throw new Error(`Illegal op_code: ${d}`)}if(d>=o.length)throw new Error("type index out of range");return c[d]}function m(d){switch(d[0]){case b.Vector:{let l=u(d[1]);return dr(l)}case b.Opt:{let l=u(d[1]);return lr(l)}case b.Record:{let l={};for(let[A,N]of d[1]){let z=`_${A}_`;l[z]=u(N)}let h=fr(l),x=h.tryAsTuple();return Array.isArray(x)?ur(...x):h}case b.Variant:{let l={};for(let[h,x]of d[1]){let A=`_${h}_`;l[A]=u(x)}return pr(l)}case b.Func:{let[l,h,x]=d[1];return mr(l.map(A=>u(A)),h.map(A=>u(A)),x)}case b.Service:{let l={},h=d[1];for(let[x,A]of h){let N=u(A);if(N instanceof C&&(N=N.getType()),!(N instanceof ne))throw new Error("Illegal service definition: services can only contain functions");l[x]=N}return yr(l)}default:throw new Error(`Illegal op_code: ${d[0]}`)}}o.forEach((d,l)=>{if(d[0]===b.Func){let h=m(d);c[l].fill(h)}}),o.forEach((d,l)=>{if(d[0]!==b.Func){let h=m(d);c[l].fill(h)}}),rt();let f=a.map(d=>u(d));try{let d=r.map((l,h)=>l.decodeValue(t,f[h]));for(let l=r.length;l<f.length;l++)f[l].decodeValue(t,f[l]);if(t.byteLength>0)throw new Error("decode: Left-over bytes");return d}finally{rt()}}var Jt=new _e,Gt=new k,Sn=new Be,Wt=new Le,qt=new te,Kt=new Ve,Yt=new we,Qt=new Se,Zt=new Te(32),Xt=new Te(64),er=new H(8),tr=new H(16),rr=new H(32),nr=new H(64),sr=new O(8),ir=new O(16),or=new O(32),ar=new O(64),cr=new Me;function ur(...r){return new Pe(r)}function dr(r){return new le(r)}function lr(r){return new X(r)}function fr(r){return new re(r)}function pr(r){return new fe(r)}function hr(){return new C}function mr(r,e,t=[]){return new ne(r,e,t)}function yr(r){return new pe(r)}var De=class r{constructor(e=new Map){this.rels=e}copy(){let e=new Map;for(let[t,n]of this.rels.entries()){let s=new Map(n);e.set(t,s)}return new r(e)}known(e,t){return this.rels.get(e.name)?.get(t.name)}addNegative(e,t){this.addNames(e.name,t.name,!1)}add(e,t){this.addNames(e.name,t.name,!0)}display(){let e="";for(let[t,n]of this.rels)for(let[s,i]of n)e+=`${t} ${i?":<":"!<:"} ${s}
140
+ `;return e}addNames(e,t,n){let s=this.rels.get(e);if(s==null){let i=new Map;i.set(t,n),this.rels.set(e,i)}else s.set(t,n)}},je=new De;function rt(){je=new De}function Tn(r,e){let t=new Set(r.annotations),n=new Set(e.annotations);if(t.size!==n.size)return!1;for(let s of t)if(!n.has(s))return!1;return!0}function Xe(r){return r instanceof X||r instanceof te||r instanceof k}function st(r,e){let t=je.copy(),n=D(t,r,e);return n?je.add(r,e):je.addNegative(r,e),n}function D(r,e,t){if(e.name===t.name)return!0;let n=r.known(e,t);if(n!==void 0)return n;if(r.add(e,t),t instanceof k||e instanceof _e||e instanceof Se&&t instanceof we)return!0;if(e instanceof le&&t instanceof le)return D(r,e._type,t._type);if(t instanceof X)return!0;if(e instanceof re&&t instanceof re){let s=e.fieldsAsObject;for(let[i,o]of t._fields){let a=s[E(i)];if(a){if(!D(r,a,o))return!1}else if(!Xe(o))return!1}return!0}if(e instanceof ne&&t instanceof ne){if(!Tn(e,t))return!1;for(let s=0;s<e.argTypes.length;s++){let i=e.argTypes[s];if(s<t.argTypes.length){if(!D(r,t.argTypes[s],i))return!1}else if(!Xe(i))return!1}for(let s=0;s<t.retTypes.length;s++){let i=t.retTypes[s];if(s<e.retTypes.length){if(!D(r,e.retTypes[s],i))return!1}else if(!Xe(i))return!1}return!0}if(e instanceof fe&&t instanceof fe){let s=t.alternativesAsObject;for(let[i,o]of e._fields){let a=s[E(i)];if(!a||!D(r,o,a))return!1}return!0}if(e instanceof pe&&t instanceof pe){let s=e.fieldsAsObject();for(let[i,o]of t._fields){let a=s[i];if(!a||!D(r,a,o))return!1}return!0}return e instanceof C?D(r,e.getType(),t):t instanceof C?D(r,e,t.getType()):!1}import{capitalize as An,convertCamelToSnake as Nn}from"@junobuild/utils";var he=r=>{switch(r.kind){case"text":return S.Text;case"bool":return S.Bool;case"float64":return S.Float64;case"int32":return S.Int32;case"bigint":return S.Nat64;case"nat":return S.Nat;case"principal":return S.Principal;case"uint8array":return S.Vec(S.Nat8);case"opt":return S.Opt(he(r.inner));case"vec":return S.Vec(he(r.inner));case"tuple":case"indexedTuple":return S.Tuple(...r.members.map(he));case"record":return S.Record(Object.fromEntries(r.fields.map(e=>[Nn(e.name),he(e.type)])));case"variant":return S.Variant(Object.fromEntries(r.tags.map(e=>[e,S.Null])));case"discriminatedUnion":return S.Variant(Object.fromEntries(r.members.map((e,t)=>{let n=e.kind==="record"?e.fields.find(i=>i.name===r.discriminator)?.type.kind==="variant"?(e.fields.find(i=>i.name===r.discriminator)?.type).tags[0]:`Variant${t}`:`Variant${t}`,s=e.kind==="record"?{kind:"record",fields:e.fields.filter(i=>i.name!==r.discriminator)}:e;return[n,he(s)]})))}},En=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let i=he(t?{kind:"opt",inner:e}:e);return{baseName:`${An(r)}${n}`,idl:i}},_i=({id:r,schema:e,suffix:t})=>{let n=q({zodSchema:e,id:r});return En({...n,suffix:t})};import{capitalize as se,convertCamelToSnake as vn}from"@junobuild/utils";var br="#[derive(CandidType, Serialize, Deserialize, Clone, JsonData)]",In="#[derive(CandidType, Serialize, Deserialize, Clone)]",Cn=new Set(["type","struct","enum","fn","let","match","use","mod","impl","trait","where","move","ref","self","super","crate"]),$n=r=>Cn.has(r)?{name:`r#${r}`,sanitized:!0}:{name:r,sanitized:!1},xr=r=>{let{sanitized:e,...t}=$n(r);if(e)return{sanitized:"reserved",...t};let n=vn(r);return{name:n,sanitized:n!==r?"renamed":!1}},$=r=>({kind:"primitive",...r}),me=r=>({kind:"composite",needsJsonData:!0,...r}),it=r=>r.flatMap(e=>e.kind==="composite"?e.structs:[]),ie=({schema:r,structName:e})=>{switch(r.kind){case"text":return $({fieldType:"String"});case"bool":return $({fieldType:"bool"});case"float64":return $({fieldType:"f64"});case"int32":return $({fieldType:"i32"});case"bigint":return $({fieldType:"u64"});case"nat":return $({fieldType:"u128"});case"principal":return $({fieldType:"Principal"});case"uint8array":return $({fieldType:"Vec<u8>"});case"opt":{let t=ie({schema:r.inner,structName:e}),n=`Option<${t.fieldType}>`;return t.kind==="composite"?me({fieldType:n,structs:t.structs}):$({fieldType:n})}case"vec":{let t=ie({schema:r.inner,structName:e}),n=`Vec<${t.fieldType}>`;return t.kind==="composite"?me({fieldType:n,structs:t.structs,needsJsonData:!1}):$({fieldType:n})}case"tuple":case"indexedTuple":{let t=r.members.map((i,o)=>ie({schema:i,structName:`${e}${o}`})),n=`(${t.map(i=>i.fieldType).join(", ")})`,s=it(t);return s.length>0?me({fieldType:n,structs:s}):$({fieldType:n})}case"variant":{if(r.tags.length===1)return $({fieldType:"String"});let t=se(e),n=r.tags.map(s=>` #[serde(rename = "${s}")]
141
+ ${se(s)},`).join(`
142
+ `);return me({fieldType:t,structs:[`${In}
143
143
  pub enum ${t} {
144
144
  ${n}
145
- }`],needsJsonData:!1})}case"discriminatedUnion":{let t=ne(e),n=r.members.map((i,o)=>{if(i.kind==="record"){let c=i.fields.filter(m=>m.name!==r.discriminator),u=c.map(m=>se({schema:m.type,structName:`${e}${ne(m.name)}`})),h=c.map((m,g)=>{let{name:N,sanitized:S}=yr(m.name);return`${S?` #[serde(rename = "${m.name}")]
146
- `:""} ${N}: ${u[g].fieldType},`}).join(`
147
- `),d=i.fields.find(m=>m.name===r.discriminator),l=d?.type.kind==="variant"?d.type.tags[0]:void 0,f=l!==void 0?` #[serde(rename = "${l}")]
148
- `:"";return{variantLine:h.length>0?`${f} Variant${o} {
149
- ${h}
150
- }`:`${f} Variant${o}`,structs:st(u)}}let a=se({schema:i,structName:`${e}Variant${o}`});return{variantLine:` Variant${o}(${a.fieldType})`,structs:a.kind==="composite"?a.structs:[]}}),s=n.map(i=>i.variantLine).join(`,
151
- `);return he({fieldType:t,structs:[...n.flatMap(i=>i.structs),`${mr}
145
+ }`],needsJsonData:!1})}case"discriminatedUnion":{let t=se(e),n=r.members.map((i,o)=>{if(i.kind==="record"){let c=i.fields.filter(h=>h.name!==r.discriminator),u=c.map(h=>ie({schema:h.type,structName:`${e}${se(h.name)}`})),m=c.map((h,x)=>{let A=xr(h.name);return`${A.sanitized==="reserved"?` #[serde(rename = "${h.name}")]
146
+ `:""} ${A.name}: ${u[x].fieldType},`}).join(`
147
+ `),f=i.fields.find(h=>h.name===r.discriminator),d=f?.type.kind==="variant"?f.type.tags[0]:void 0,l=d!==void 0?` #[serde(rename = "${d}")]
148
+ `:"";return{variantLine:m.length>0?`${l} Variant${o} {
149
+ ${m}
150
+ }`:`${l} Variant${o}`,structs:it(u)}}let a=ie({schema:i,structName:`${e}Variant${o}`});return{variantLine:` Variant${o}(${a.fieldType})`,structs:a.kind==="composite"?a.structs:[]}}),s=n.map(i=>i.variantLine).join(`,
151
+ `);return me({fieldType:t,structs:[...n.flatMap(i=>i.structs),`${br}
152
152
  #[json_data(tag = "${r.discriminator}")]
153
153
  pub enum ${t} {
154
154
  ${s}
155
- }`]})}case"record":{let t=ne(e),n=r.fields.map(i=>se({schema:i.type,structName:`${e}${ne(i.name)}`})),s=r.fields.map((i,o)=>{let a=n[o],{name:c,sanitized:u}=yr(i.name),h=u?` #[serde(rename = "${i.name}")]
156
- `:"",d=a.kind==="composite"&&a.needsJsonData?` #[json_data(nested)]
157
- `:"";return`${h}${d} pub ${c}: ${a.fieldType},`}).join(`
158
- `);return he({fieldType:t,structs:[...st(n),`${mr}
155
+ }`]})}case"record":{let t=se(e),n=r.fields.map(i=>ie({schema:i.type,structName:`${e}${se(i.name)}`})),s=r.fields.map((i,o)=>{let a=n[o],c=xr(i.name),u=c.sanitized==="reserved"?` #[serde(rename = "${i.name}")]
156
+ `:"",m=a.kind==="composite"&&a.needsJsonData?` #[json_data(nested)]
157
+ `:"";return`${u}${m} pub ${c.name}: ${a.fieldType},`}).join(`
158
+ `);return me({fieldType:t,structs:[...it(n),`${br}
159
159
  pub struct ${t} {
160
160
  ${s}
161
- }`]})}}},Nn=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let s=`${ne(r)}${n}`,o=se({schema:t?{kind:"opt",inner:e}:e,structName:s});return o.kind==="composite"?{baseName:s,code:o.structs.join(`
161
+ }`]})}}},Rn=({id:r,schema:e,isTopLevelOptional:t,suffix:n})=>{let s=`${se(r)}${n}`,o=ie({schema:t?{kind:"opt",inner:e}:e,structName:s});return o.kind==="composite"?{baseName:s,code:o.structs.join(`
162
162
 
163
- `)}:{baseName:s,code:`pub type ${s} = ${o.fieldType};`}},it=({id:r,schema:e,suffix:t})=>{let n=W({zodSchema:e,id:r});return Nn({...n,suffix:t})};import{writeFile as Cn}from"node:fs/promises";import{nonNullish as Pe}from"@dfinity/utils";import{capitalize as En,convertCamelToSnake as vn}from"@junobuild/utils";var In=`// This file was automatically generated by the Juno CLI.
163
+ `)}:{baseName:s,code:`pub type ${s} = ${o.fieldType};`}},ot=({id:r,schema:e,suffix:t})=>{let n=q({zodSchema:e,id:r});return Rn({...n,suffix:t})};import{writeFile as kn}from"node:fs/promises";import{capitalize as Un,convertCamelToSnake as On,nonNullish as He}from"@junobuild/utils";var Fn=`// This file was automatically generated by the Juno CLI.
164
164
  // Any modifications may be overwritten.
165
165
 
166
166
  %TYPES%service : {
167
167
  %METHODS%
168
- };`,xr=({queries:r,updates:e})=>{let t=r.map(([o,a])=>br({jsFnName:o,fn:a,fnType:"query"})),n=e.map(([o,a])=>br({jsFnName:o,fn:a,fnType:"update"})),[s,i]=[...t,...n].reduce(([o,a],{types:c,method:u})=>[[...o,...c],[...a,u]],[[],[]]);return In.replace("%TYPES%",s.length>0?`${s.join(`
168
+ };`,_r=({queries:r,updates:e})=>{let t=r.map(([o,a])=>gr({jsFnName:o,fn:a,fnType:"query"})),n=e.map(([o,a])=>gr({jsFnName:o,fn:a,fnType:"update"})),[s,i]=[...t,...n].reduce(([o,a],{types:c,method:u})=>[[...o,...c],[...a,u]],[[],[]]);return Fn.replace("%TYPES%",s.length>0?`${s.join(`
169
169
 
170
170
  `)}
171
171
 
172
172
  `:"").replace("%METHODS%",i.join(`
173
- `).trim()).trim()},br=({fn:r,jsFnName:e,fnType:t})=>{let n=`${"App"}${En(e)}`,s="args"in r?ze({id:n,schema:r.args,suffix:"Args"}):void 0,i="result"in r?ze({id:n,schema:r.result,suffix:"Result"}):void 0,o=[...Pe(s)?[s.code]:[],...Pe(i)?[i.code]:[]],a=t==="query"?" query":"",c=Pe(s)?`(${s.baseName})`:"()",u=Pe(i)?`(${i.baseName})`:"()",d=` ${`${"App".toLowerCase()}_${vn(e)}`} : ${c} -> ${u}${a};`;return{types:o,method:d}};var Ii=async({updates:r,queries:e,outputFile:t})=>{let n=xr({queries:e,updates:r});await Cn(t,n,"utf-8")};import{writeFile as Pn}from"node:fs/promises";import{relative as Dn}from"node:path";import{nonNullish as De,notEmptyString as gr}from"@dfinity/utils";import{capitalize as Rn,convertCamelToSnake as Un}from"@junobuild/utils";var On=`// This file was automatically generated by the Juno CLI.
173
+ `).trim()).trim()},gr=({fn:r,jsFnName:e,fnType:t})=>{let n=`${"App"}${Un(e)}`,s="args"in r?Je({id:n,schema:r.args,suffix:"Args"}):void 0,i="result"in r?Je({id:n,schema:r.result,suffix:"Result"}):void 0,o=[...He(s)?[s.code]:[],...He(i)?[i.code]:[]],a=t==="query"?" query":"",c=He(s)?`(${s.baseName})`:"()",u=He(i)?`(${i.baseName})`:"()",f=` ${`${"App".toLowerCase()}_${On(e)}`} : ${c} -> ${u}${a};`;return{types:o,method:f}};var ki=async({updates:r,queries:e,outputFile:t})=>{let n=_r({queries:e,updates:r});await kn(t,n,"utf-8")};import{writeFile as Yn}from"node:fs/promises";import{relative as Qn}from"node:path";import{capitalize as jn,convertCamelToSnake as Bn,nonNullish as ye,notEmptyString as at}from"@junobuild/utils";var Ln=`// This file was automatically generated by the Juno CLI.
174
174
  // Any modifications may be overwritten.
175
175
  #![allow(unused)]
176
176
  #![allow(non_camel_case_types)]
177
177
 
178
178
  use crate::functions::{
179
- execute_async_function, execute_sync_function,
179
+ execute_async_function, execute_sync_guard, execute_sync_function,
180
180
  types::{NoArgs, NoResult},
181
181
  };
182
182
  use candid::{CandidType, Principal};
@@ -186,50 +186,54 @@ use junobuild_shared::ic::UnwrapOrTrapResult;
186
186
  use serde::{Deserialize, Serialize};
187
187
 
188
188
  %FUNCTIONS%
189
- `,$n=`#[ic_cdk::%TYPE%]
189
+ `,Vn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
190
190
  fn %RS_FUNCTION%() {
191
191
  execute_sync_function::<NoArgs, NoResult>("%JS_FUNCTION%", None).unwrap_or_trap();
192
- }`,Fn=`#[ic_cdk::%TYPE%]
192
+ }`,Pn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
193
193
  fn %RS_FUNCTION%() -> %RESULT% {
194
194
  execute_sync_function::<NoArgs, %RESULT%>("%JS_FUNCTION%", None).unwrap_or_trap_result()
195
- }`,kn=`#[ic_cdk::%TYPE%]
195
+ }`,Mn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
196
196
  fn %RS_FUNCTION%(args: %ARGS%) {
197
197
  execute_sync_function::<%ARGS%, NoResult>("%JS_FUNCTION%", Some(args)).unwrap_or_trap();
198
- }`,Bn=`#[ic_cdk::%TYPE%]
198
+ }`,Dn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
199
199
  fn %RS_FUNCTION%(args: %ARGS%) -> %RESULT% {
200
200
  execute_sync_function("%JS_FUNCTION%", Some(args)).unwrap_or_trap_result()
201
- }`,jn=`#[ic_cdk::%TYPE%]
201
+ }`,Hn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
202
202
  async fn %RS_FUNCTION%() {
203
203
  execute_async_function::<NoArgs, NoResult>("%JS_FUNCTION%", None)
204
204
  .await
205
205
  .unwrap_or_trap();
206
- }`,Ln=`#[ic_cdk::%TYPE%]
206
+ }`,zn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
207
207
  async fn %RS_FUNCTION%() -> %RESULT% {
208
208
  execute_async_function::<NoArgs, %RESULT%>("%JS_FUNCTION%", None)
209
209
  .await
210
210
  .unwrap_or_trap_result()
211
- }`,Vn=`#[ic_cdk::%TYPE%]
211
+ }`,Jn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
212
212
  async fn %RS_FUNCTION%(args: %ARGS%) {
213
213
  execute_async_function::<%ARGS%, NoResult>("%JS_FUNCTION%", Some(args))
214
214
  .await
215
215
  .unwrap_or_trap();
216
- }`,Mn=`#[ic_cdk::%TYPE%]
216
+ }`,Gn=`#[ic_cdk::%TYPE%%TYPE_OPTIONS%]
217
217
  async fn %RS_FUNCTION%(args: %ARGS%) -> %RESULT% {
218
218
  execute_async_function("%JS_FUNCTION%", Some(args))
219
219
  .await
220
220
  .unwrap_or_trap_result()
221
- }`,_r=({queries:r,updates:e})=>{let t=r.map(([i,o])=>wr({jsFnName:i,fn:o,fnType:"query"})).join(`
221
+ }`,Wn=`fn %RS_FUNCTION%_guard() -> Result<(), String> {
222
+ execute_sync_guard("%JS_FUNCTION%")
223
+ }`,qn='guard = "%RS_FUNCTION%_guard"',Kn="hidden = true",Sr=({queries:r,updates:e})=>{let t=r.map(([i,o])=>wr({jsFnName:i,fn:o,fnType:"query"})).join(`
222
224
 
223
225
  `),n=e.map(([i,o])=>wr({jsFnName:i,fn:o,fnType:"update"})).join(`
224
226
 
225
227
  `),s=`${t}
226
228
 
227
- ${n}`.trim();return On.replace("%FUNCTIONS%",s)},wr=({fn:r,fnType:e,jsFnName:t})=>{let n=`${"App"}${Rn(t)}`,s="args"in r?it({id:n,schema:r.args,suffix:"Args"}):void 0,i="result"in r?it({id:n,schema:r.result,suffix:"Result"}):void 0,o=r.handler.constructor.name==="AsyncFunction",c=De(s)&&De(i)?o?Mn:Bn:De(s)?o?Vn:kn:De(i)?o?Ln:Fn:o?jn:$n,u=`${"App".toLowerCase()}_${Un(t)}`,h=c.replace("%TYPE%",e).replace("%RS_FUNCTION%",u).replace("%JS_FUNCTION%",t).replaceAll("%ARGS%",s?.baseName??"").replaceAll("%RESULT%",i?.baseName??"").trim(),d=s?.code??"",l=i?.code??"";return`${d}${gr(d)?`
229
+ ${n}`.trim();return Ln.replace("%FUNCTIONS%",s)},wr=({fn:r,fnType:e,jsFnName:t})=>{let n=`${"App"}${jn(t)}`,s=`${"App".toLowerCase()}_${Bn(t)}`,i=ye(r.guard)?{fn:Wn.replace("%RS_FUNCTION%",s).replace("%JS_FUNCTION%",t),type:qn.replace("%RS_FUNCTION%",s)}:void 0,o=[...r.hidden===!0?[Kn]:[],...ye(i)?[i.type]:[]],a="args"in r?ot({id:n,schema:r.args,suffix:"Args"}):void 0,c="result"in r?ot({id:n,schema:r.result,suffix:"Result"}):void 0,u=r.handler.constructor.name==="AsyncFunction",d=(ye(a)&&ye(c)?u?Gn:Dn:ye(a)?u?Jn:Mn:ye(c)?u?zn:Pn:u?Hn:Vn).replace("%TYPE%",e).replace("%TYPE_OPTIONS%",o.length>0?`(${o.join(", ")})`:"").replace("%RS_FUNCTION%",s).replace("%JS_FUNCTION%",t).replaceAll("%ARGS%",a?.baseName??"").replaceAll("%RESULT%",c?.baseName??"").trim(),l=a?.code??"",h=c?.code??"";return`${l}${at(l)?`
230
+
231
+ `:""}${h}${at(h)?`
228
232
 
229
- `:""}${l}${gr(l)?`
233
+ `:""}${at(i?.fn)?`${i.fn}
230
234
 
231
- `:""}${h}`};var Li=async({code:r,outputFile:e})=>{let t=globalThis.console,n=globalThis.Math.random;try{globalThis.__ic_cdk_print=h=>process.stdout.write(`${h}
232
- `);let s=await import(`data:text/javascript;base64,${Buffer.from(r).toString("base64")}`),{QuerySchema:i,UpdateSchema:o}=await import("@junobuild/functions"),[a,c]=Object.entries(s).reduce(([h,d],l)=>{let[f,m]=l,g=typeof m=="function"?m({}):m,N=i.safeParse(g),S=o.safeParse(g);return[[...h,...N.success?[[f,N.data]]:[]],[...d,...S.success?[[f,S.data]]:[]]]},[[],[]]);if(a.length===0&&c.length===0)return null;let u=_r({queries:a,updates:c});return await Pn(e,u,"utf-8"),{outputPath:Dn(process.cwd(),e),queries:a,updates:c}}finally{globalThis.console=t,globalThis.Math.random=n}};export{Ii as generateDid,Li as generateFunctions,ns as generateIdlApi,Ss as generateSchemaApi,ze as zodToCandid,fi as zodToIdl,it as zodToRust};
235
+ `:""}${d}`};var zi=async({code:r,outputFile:e})=>{let t=globalThis.console,n=globalThis.Math.random;try{globalThis.__ic_cdk_print=m=>process.stdout.write(`${m}
236
+ `);let s=await import(`data:text/javascript;base64,${Buffer.from(r).toString("base64")}`),{QuerySchema:i,UpdateSchema:o}=await import("@junobuild/functions"),[a,c]=Object.entries(s).reduce(([m,f],d)=>{let[l,h]=d,x=typeof h=="function"?h({}):h,A=i.safeParse(x),N=o.safeParse(x);return[[...m,...A.success?[[l,A.data]]:[]],[...f,...N.success?[[l,N.data]]:[]]]},[[],[]]);if(a.length===0&&c.length===0)return null;let u=Sr({queries:a,updates:c});return await Yn(e,u,"utf-8"),{outputPath:Qn(process.cwd(),e),queries:a,updates:c}}finally{globalThis.console=t,globalThis.Math.random=n}};export{ki as generateDid,zi as generateFunctions,fs as generateIdlApi,$s as generateSchemaApi,Je as zodToCandid,_i as zodToIdl,ot as zodToRust};
233
237
  /*! Bundled license information:
234
238
 
235
239
  @noble/hashes/esm/utils.js: