@latticexyz/store 3.0.0-main-69eb63b59 → 3.0.0-main-93749bdb6

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,2 +1,2 @@
1
- function a(e,t){return typeof e=="object"&&e!=null&&s(e,t)?e[t]:void 0}function M(e,t){return t.length?M(a(e,t[0]),t.slice(1)):e}function s(e,t){return typeof e=="object"&&e!==null&&e.hasOwnProperty(t)}function p(e){return e!=null&&typeof e=="object"}function c(e,t){let o=[...new Set([...Object.keys(e),...Object.keys(t)])];return Object.fromEntries(o.map(n=>[n,typeof e[n]>"u"?t[n]:e[n]]))}var T={storeImportPath:"@latticexyz/store/src",userTypesFilename:"common.sol",outputDirectory:"codegen",namespaceDirectories:!1,indexFilename:"index.sol"},m={outputDirectory:"tables",tableIdArgument:!1,storeArgument:!1},D={disabled:!1},S={namespace:"",type:"table"},h={sourceDirectory:"src",namespace:""};import{schemaAbiTypes as V}from"@latticexyz/schema-type/internal";var de={types:{}},r={types:Object.fromEntries(V.map(e=>[e,e]))};function u(e,t){return{types:{...e.types,...t}}}import{fixedArrayToArray as W,isFixedArrayAbiType as k}from"@latticexyz/schema-type/internal";function g(e,t=r){if(!p(e))throw new Error(`Expected schema, received ${JSON.stringify(e)}`);for(let o of Object.values(e))if(!k(o)&&!s(t.types,o))throw new Error(`"${String(o)}" is not a valid type in this scope.`)}function v(e,t=r){return Object.fromEntries(Object.entries(e).map(([o,n])=>[o,{type:k(n)?W(n):t.types[n],internalType:n}]))}function Se(e,t=r){return g(e,t),v(e,t)}function E(e,t=r){return typeof e=="object"&&e!=null&&Object.values(e).every(o=>k(o)||s(t.types,o))}import{isStaticAbiType as U}from"@latticexyz/schema-type/internal";import{resourceToHex as Y}from"@latticexyz/common";function q(e,t=r){return Object.entries(e).filter(([,o])=>s(t.types,o)&&U(t.types[o])).map(([o])=>o)}function J(e,t,o=r){return Array.isArray(e)&&e.every(n=>s(t,n)&&s(o.types,t[n])&&U(o.types[t[n]]))}function A(e,t=r,o={inStoreContext:!1}){if(typeof e!="object"||e==null)throw new Error(`Expected full table config, got \`${JSON.stringify(e)}\``);if(!s(e,"schema"))throw new Error("Missing schema input");if(g(e.schema,t),!s(e,"key")||!J(e.key,e.schema,t))throw new Error(`Invalid key. Expected \`(${q(e.schema,t).map(n=>`"${String(n)}"`).join(" | ")})[]\`, received \`${s(e,"key")&&Array.isArray(e.key)?`[${e.key.map(n=>`"${n}"`).join(", ")}]`:String(a(e,"key"))}\``);if(s(e,"namespace")&&typeof e.namespace=="string"&&e.namespace.length>14)throw new Error(`Table \`namespace\` must fit into a \`bytes14\`, but "${e.namespace}" is too long.`);if(s(e,"name")&&typeof e.name=="string"&&e.name.length>16)throw new Error(`Table \`name\` must fit into a \`bytes16\`, but "${e.name}" is too long.`);if(o.inStoreContext&&(s(e,"label")||s(e,"namespace")))throw new Error("Overrides of `label` and `namespace` are not allowed for tables in a store config.")}function H(e){let t=e.codegen;return{outputDirectory:a(t,"outputDirectory")??m.outputDirectory,tableIdArgument:a(t,"tableIdArgument")??m.tableIdArgument,storeArgument:a(t,"storeArgument")??m.storeArgument,dataStruct:a(t,"dataStruct")??Object.keys(e.schema).length-e.key.length>1}}function I(e,t=r){let o=e.label,n=e.type??S.type,i=e.namespace??S.namespace,l=e.name??o.slice(0,16),f=Y({type:n,namespace:i,name:l});return{label:o,type:n,namespace:i,name:l,tableId:f,schema:v(e.schema,t),key:e.key,codegen:H(e),deploy:c(e.deploy??{},D)}}function De(e,t=r){return A(e,t),I(e,t)}import{isFixedArrayAbiType as R,isStaticAbiType as z}from"@latticexyz/schema-type/internal";var $e="Invalid schema. Expected an `id` field with a static ABI type or an explicit `key` option.";function L(e){return typeof e=="string"||p(e)&&Object.values(e).every(t=>typeof t=="string")}function w(e,t=r){if(typeof e=="string"){if(R(e)||s(t.types,e))return;throw new Error(`Invalid ABI type. \`${e}\` not found in scope.`)}if(typeof e=="object"&&e!==null){if(E(e,t)){if(s(e,"id")&&z(t.types[e.id]))return;throw new Error("Invalid schema. Expected an `id` field with a static ABI type or an explicit `key` option.")}throw new Error("Invalid schema. Are you using invalid types or missing types in your scope?")}throw new Error("Invalid table shorthand.")}function y(e,t){return typeof e=="string"?{schema:{id:"bytes32",value:e},key:["id"]}:E(e,t)?{schema:e,key:["id"]}:e}function Be(e,t=r){return w(e,t),y(e,t)}function b(e,t){if(p(e)){for(let o of Object.values(e))L(o)?w(o,t):A(o,t,{inStoreContext:!0});return}throw new Error(`Expected tables config, received ${JSON.stringify(e)}`)}function d(e,t){return Object.fromEntries(Object.entries(e).map(([o,n])=>[o,I(c(y(n,t),{label:o}),t)]))}function qe(e,t=r){return b(e,t),d(e,t)}import{mapObject as Q}from"@latticexyz/common/utils";import{isSchemaAbiType as X}from"@latticexyz/schema-type/internal";function Z(e){return Q(e,t=>t.type)}function ee(e){return p(e)&&Object.values(e).every(t=>X(t.type))}function N(e,t=r){return ee(e)?u(t,Z(e)):t}function F(e){if(!p(e))throw new Error(`Expected userTypes, received ${JSON.stringify(e)}`);for(let{type:t}of Object.values(e))if(!s(r.types,t))throw new Error(`"${String(t)}" is not a valid ABI type.`)}import{flatMorph as C}from"@arktype/util";function te(e){return typeof e=="object"&&e!=null&&Object.values(e).every(t=>Array.isArray(t)&&t.every(o=>typeof o=="string"))}function _(e,t=r){if(te(e)){let o=Object.fromEntries(Object.keys(e).map(n=>[n,"uint8"]));return u(t,o)}return t}function oe(e){return e}function j(e){return C(e,(t,o)=>[t,C(o,(n,i)=>[i,n])])}function K(e){return p(e)?c(e,T):T}import{flatMorph as ne}from"@arktype/util";function $(e,t){return ne(e,(o,n)=>[t===""?o:`${t}__${o}`,n])}import{flatMorph as re}from"@arktype/util";import{flatMorph as se}from"@arktype/util";function B(e,t){let o=e.label,n=e.namespace??o.slice(0,14);return{label:o,namespace:n,tables:d(se(e.tables??{},(i,l)=>[i,c(y(l,t),{namespace:n})]),t)}}function G(e){return _(a(e,"enums"),N(a(e,"userTypes")))}function pe(e){let t=G(e);if(s(e,"namespace")&&typeof e.namespace=="string"&&e.namespace.length>14)throw new Error(`\`namespace\` must fit into a \`bytes14\`, but "${e.namespace}" is too long.`);s(e,"tables")&&b(e.tables,t),s(e,"userTypes")&&F(e.userTypes)}function ae(e){let t=G(e),o=e.namespace??h.namespace,n=K(e.codegen),i=re(e.tables??{},(O,P)=>{let x=y(P,t);return[O,{...x,label:O,namespace:o,codegen:{...x.codegen,outputDirectory:x.codegen?.outputDirectory??(n.namespaceDirectories&&o!==""?`${o}/tables`:"tables")}}]}),l={[o]:B({label:o,tables:i},t)},f=d(i,t);return{namespace:o,tables:$(f,o),namespaces:l,sourceDirectory:e.sourceDirectory??h.sourceDirectory,userTypes:e.userTypes??{},enums:e.enums??{},enumValues:j(e.enums??{}),codegen:n}}function Ot(e){return pe(e),ae(e)}export{a,M as b,s as c,p as d,c as e,T as f,m as g,D as h,S as i,h as j,de as k,r as l,u as m,g as n,v as o,Se as p,E as q,J as r,A as s,H as t,I as u,De as v,$e as w,L as x,w as y,y as z,Be as A,b as B,d as C,qe as D,Z as E,ee as F,N as G,F as H,_ as I,oe as J,j as K,K as L,$ as M,G as N,pe as O,ae as P,Ot as Q};
2
- //# sourceMappingURL=chunk-3PAPLPW2.js.map
1
+ function a(e,t){return typeof e=="object"&&e!=null&&s(e,t)?e[t]:void 0}function M(e,t){return t.length?M(a(e,t[0]),t.slice(1)):e}function s(e,t){return typeof e=="object"&&e!==null&&e.hasOwnProperty(t)}function p(e){return e!=null&&typeof e=="object"}function c(e,t){let o=[...new Set([...Object.keys(e),...Object.keys(t)])];return Object.fromEntries(o.map(n=>[n,typeof e[n]>"u"?t[n]:e[n]]))}var T={storeImportPath:"@latticexyz/store/src",userTypesFilename:"common.sol",outputDirectory:"codegen",namespaceDirectories:!1,indexFilename:"index.sol"},u={outputDirectory:"tables",tableIdArgument:!1,storeArgument:!1},D={disabled:!1},S={namespace:"",type:"table"},h={sourceDirectory:"src",namespace:""};import{schemaAbiTypes as V}from"@latticexyz/schema-type/internal";var de={types:{}},r={types:Object.fromEntries(V.map(e=>[e,e]))};function b(e,t){return{types:{...e.types,...t}}}import{fixedArrayToArray as W,isFixedArrayAbiType as k}from"@latticexyz/schema-type/internal";function g(e,t=r){if(!p(e))throw new Error(`Expected schema, received ${JSON.stringify(e)}`);for(let o of Object.values(e))if(!k(o)&&!s(t.types,o))throw new Error(`"${String(o)}" is not a valid type in this scope.`)}function v(e,t=r){return Object.fromEntries(Object.entries(e).map(([o,n])=>[o,{type:k(n)?W(n):t.types[n],internalType:n}]))}function Se(e,t=r){return g(e,t),v(e,t)}function E(e,t=r){return typeof e=="object"&&e!=null&&Object.values(e).every(o=>k(o)||s(t.types,o))}import{isStaticAbiType as U}from"@latticexyz/schema-type/internal";import{resourceToHex as Y}from"@latticexyz/common";function q(e,t=r){return Object.entries(e).filter(([,o])=>s(t.types,o)&&U(t.types[o])).map(([o])=>o)}function J(e,t,o=r){return Array.isArray(e)&&e.every(n=>s(t,n)&&s(o.types,t[n])&&U(o.types[t[n]]))}function A(e,t=r,o={inStoreContext:!1}){if(typeof e!="object"||e==null)throw new Error(`Expected full table config, got \`${JSON.stringify(e)}\``);if(!s(e,"schema"))throw new Error("Missing schema input");if(g(e.schema,t),!s(e,"key")||!J(e.key,e.schema,t))throw new Error(`Invalid key. Expected \`(${q(e.schema,t).map(n=>`"${String(n)}"`).join(" | ")})[]\`, received \`${s(e,"key")&&Array.isArray(e.key)?`[${e.key.map(n=>`"${n}"`).join(", ")}]`:String(a(e,"key"))}\``);if(s(e,"namespace")&&typeof e.namespace=="string"&&e.namespace.length>14)throw new Error(`Table \`namespace\` must fit into a \`bytes14\`, but "${e.namespace}" is too long.`);if(s(e,"name")&&typeof e.name=="string"&&e.name.length>16)throw new Error(`Table \`name\` must fit into a \`bytes16\`, but "${e.name}" is too long.`);if(o.inStoreContext&&(s(e,"label")||s(e,"namespace")))throw new Error("Overrides of `label` and `namespace` are not allowed for tables in a store config.")}function H(e){let t=e.codegen;return{outputDirectory:a(t,"outputDirectory")??u.outputDirectory,tableIdArgument:a(t,"tableIdArgument")??u.tableIdArgument,storeArgument:a(t,"storeArgument")??u.storeArgument,dataStruct:a(t,"dataStruct")??Object.keys(e.schema).length-e.key.length>1}}function I(e,t=r){let o=e.label,n=e.type??S.type,i=e.namespace??S.namespace,l=e.name??o.slice(0,16),f=Y({type:n,namespace:i,name:l});return{label:o,type:n,namespace:i,name:l,tableId:f,schema:v(e.schema,t),key:e.key,codegen:H(e),deploy:c(e.deploy??{},D)}}function De(e,t=r){return A(e,t),I(e,t)}import{isFixedArrayAbiType as R,isStaticAbiType as z}from"@latticexyz/schema-type/internal";var $e="Invalid schema. Expected an `id` field with a static ABI type or an explicit `key` option.";function L(e){return typeof e=="string"||p(e)&&Object.values(e).every(t=>typeof t=="string")}function w(e,t=r){if(typeof e=="string"){if(R(e)||s(t.types,e))return;throw new Error(`Invalid ABI type. \`${e}\` not found in scope.`)}if(typeof e=="object"&&e!==null){if(E(e,t)){if(s(e,"id")&&z(t.types[e.id]))return;throw new Error("Invalid schema. Expected an `id` field with a static ABI type or an explicit `key` option.")}throw new Error("Invalid schema. Are you using invalid types or missing types in your scope?")}throw new Error("Invalid table shorthand.")}function y(e,t){return typeof e=="string"?{schema:{id:"bytes32",value:e},key:["id"]}:E(e,t)?{schema:e,key:["id"]}:e}function Be(e,t=r){return w(e,t),y(e,t)}function d(e,t){if(p(e)){for(let o of Object.values(e))L(o)?w(o,t):A(o,t,{inStoreContext:!0});return}throw new Error(`Expected tables config, received ${JSON.stringify(e)}`)}function m(e,t){return Object.fromEntries(Object.entries(e).map(([o,n])=>[o,I(c(y(n,t),{label:o}),t)]))}function qe(e,t=r){return d(e,t),m(e,t)}import{mapObject as Q}from"@latticexyz/common/utils";import{isSchemaAbiType as X}from"@latticexyz/schema-type/internal";function Z(e){return Q(e,t=>t.type)}function ee(e){return p(e)&&Object.values(e).every(t=>X(t.type))}function N(e,t=r){return ee(e)?b(t,Z(e)):t}function F(e){if(!p(e))throw new Error(`Expected userTypes, received ${JSON.stringify(e)}`);for(let{type:t}of Object.values(e))if(!s(r.types,t))throw new Error(`"${String(t)}" is not a valid ABI type.`)}import{flatMorph as C}from"@arktype/util";function te(e){return typeof e=="object"&&e!=null&&Object.values(e).every(t=>Array.isArray(t)&&t.every(o=>typeof o=="string"))}function _(e,t=r){if(te(e)){let o=Object.fromEntries(Object.keys(e).map(n=>[n,"uint8"]));return b(t,o)}return t}function oe(e){return e}function j(e){return C(e,(t,o)=>[t,C(o,(n,i)=>[i,n])])}function K(e){return p(e)?c(e,T):T}import{flatMorph as ne}from"@arktype/util";function $(e,t){return ne(e,(o,n)=>[t===""?o:`${t}__${o}`,n])}import{flatMorph as se}from"@arktype/util";function bt(e,t){if(s(e,"namespace")&&typeof e.namespace=="string"&&e.namespace.length>14)throw new Error(`\`namespace\` must fit into a \`bytes14\`, but "${e.namespace}" is too long.`);s(e,"tables")&&d(e.tables,t)}function B(e,t=r){let o=e.label,n=e.namespace??o.slice(0,14);return{label:o,namespace:n,tables:m(se(e.tables??{},(i,l)=>[i,c(y(l,t),{namespace:n})]),t)}}import{flatMorph as re}from"@arktype/util";function G(e){return _(a(e,"enums"),N(a(e,"userTypes")))}function pe(e){let t=G(e);if(s(e,"namespace")&&typeof e.namespace=="string"&&e.namespace.length>14)throw new Error(`\`namespace\` must fit into a \`bytes14\`, but "${e.namespace}" is too long.`);s(e,"tables")&&d(e.tables,t),s(e,"userTypes")&&F(e.userTypes)}function ae(e){let t=G(e),o=e.namespace??h.namespace,n=K(e.codegen),i=re(e.tables??{},(O,P)=>{let x=y(P,t);return[O,{...x,label:O,namespace:o,codegen:{...x.codegen,outputDirectory:x.codegen?.outputDirectory??(n.namespaceDirectories&&o!==""?`${o}/tables`:"tables")}}]}),l={[o]:B({label:o,tables:i},t)},f=m(i,t);return{namespace:o,tables:$(f,o),namespaces:l,sourceDirectory:e.sourceDirectory??h.sourceDirectory,userTypes:e.userTypes??{},enums:e.enums??{},enumValues:j(e.enums??{}),codegen:n}}function Lt(e){return pe(e),ae(e)}export{a,M as b,s as c,p as d,c as e,T as f,u as g,D as h,S as i,h as j,de as k,r as l,b as m,g as n,v as o,Se as p,E as q,J as r,A as s,H as t,I as u,De as v,$e as w,L as x,w as y,y as z,Be as A,d as B,m as C,qe as D,Z as E,ee as F,N as G,F as H,_ as I,oe as J,j as K,K as L,$ as M,bt as N,B as O,G as P,pe as Q,ae as R,Lt as S};
2
+ //# sourceMappingURL=chunk-7BUS2KVD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../ts/config/v2/generics.ts","../ts/config/v2/defaults.ts","../ts/config/v2/scope.ts","../ts/config/v2/schema.ts","../ts/config/v2/table.ts","../ts/config/v2/tableShorthand.ts","../ts/config/v2/tables.ts","../ts/config/v2/userTypes.ts","../ts/config/v2/enums.ts","../ts/config/v2/codegen.ts","../ts/config/v2/namespacedTables.ts","../ts/config/v2/store.ts","../ts/config/v2/namespace.ts"],"sourcesContent":["export type get<input, key> = key extends keyof input ? input[key] : undefined;\n\nexport function get<input, key extends PropertyKey>(input: input, key: key): get<input, key> {\n return (typeof input === \"object\" && input != null && hasOwnKey(input, key) ? input[key] : undefined) as never;\n}\n\nexport type getPath<input, path extends readonly PropertyKey[]> = path extends readonly [\n infer head,\n ...infer tail extends PropertyKey[],\n]\n ? head extends keyof input\n ? getPath<input[head], tail>\n : undefined\n : input;\n\nexport function getPath<input, path extends readonly PropertyKey[]>(input: input, path: path): getPath<input, path> {\n return path.length ? (getPath(get(input, path[0]), path.slice(1)) as never) : (input as never);\n}\n\nexport function hasOwnKey<obj, const key extends PropertyKey>(\n object: obj,\n key: key,\n): object is { [k in key]: k extends keyof obj ? obj[k] : unknown } & obj {\n // eslint-disable-next-line no-prototype-builtins\n return typeof object === \"object\" && object !== null && object.hasOwnProperty(key);\n}\n\nexport function isObject<input>(input: input): input is input & object {\n return input != null && typeof input === \"object\";\n}\n\nexport type mergeIfUndefined<base, defaults> = {\n readonly [key in keyof base | keyof defaults]: key extends keyof base\n ? undefined extends base[key]\n ? key extends keyof defaults\n ? defaults[key]\n : base[key]\n : base[key]\n : key extends keyof defaults\n ? defaults[key]\n : never;\n};\n\nexport function mergeIfUndefined<base extends object, defaults extends object>(\n base: base,\n defaults: defaults,\n): mergeIfUndefined<base, defaults> {\n const keys = [...new Set([...Object.keys(base), ...Object.keys(defaults)])];\n return Object.fromEntries(\n keys.map((key) => [\n key,\n typeof base[key as keyof base] === \"undefined\" ? defaults[key as keyof defaults] : base[key as keyof base],\n ]),\n ) as never;\n}\n\nexport type parseNumber<T> = T extends `${infer N extends number}` ? N : never;\n","import { CodegenInput, StoreInput, TableCodegenInput, TableDeployInput, TableInput } from \"./input\";\n\nexport const CODEGEN_DEFAULTS = {\n storeImportPath: \"@latticexyz/store/src\",\n userTypesFilename: \"common.sol\",\n outputDirectory: \"codegen\",\n // TODO: default to true if using top-level `namespaces` key (once its migrated to store)\n namespaceDirectories: false,\n indexFilename: \"index.sol\",\n} as const satisfies CodegenInput;\n\nexport type CODEGEN_DEFAULTS = typeof CODEGEN_DEFAULTS;\n\nexport const TABLE_CODEGEN_DEFAULTS = {\n outputDirectory: \"tables\" as string,\n tableIdArgument: false,\n storeArgument: false,\n} as const satisfies TableCodegenInput;\n\nexport type TABLE_CODEGEN_DEFAULTS = typeof TABLE_CODEGEN_DEFAULTS;\n\nexport const TABLE_DEPLOY_DEFAULTS = {\n disabled: false,\n} as const satisfies TableDeployInput;\n\nexport type TABLE_DEPLOY_DEFAULTS = typeof TABLE_DEPLOY_DEFAULTS;\n\nexport const TABLE_DEFAULTS = {\n namespace: \"\",\n type: \"table\",\n} as const satisfies Pick<TableInput, \"namespace\" | \"type\">;\n\nexport type TABLE_DEFAULTS = typeof TABLE_DEFAULTS;\n\nexport const CONFIG_DEFAULTS = {\n sourceDirectory: \"src\",\n namespace: \"\",\n} as const satisfies StoreInput;\n\nexport type CONFIG_DEFAULTS = typeof CONFIG_DEFAULTS;\n","import { Dict, show } from \"@arktype/util\";\nimport { SchemaInput } from \"./input\";\nimport { StaticAbiType, schemaAbiTypes } from \"@latticexyz/schema-type/internal\";\nimport { AbiType } from \"./output\";\n\nexport const Scope = { types: {} } as const satisfies ScopeOptions;\nexport type Scope = typeof Scope;\n\nexport type AbiTypeScope = ScopeOptions<{ [t in AbiType]: t }>;\nexport const AbiTypeScope = {\n types: Object.fromEntries(schemaAbiTypes.map((abiType) => [abiType, abiType])),\n} as AbiTypeScope;\n\nexport type ScopeOptions<types extends Dict<string, AbiType> = Dict<string, AbiType>> = {\n types: types;\n};\n\nexport type getStaticAbiTypeKeys<\n schema extends SchemaInput,\n scope extends Scope = AbiTypeScope,\n> = SchemaInput extends schema\n ? string\n : {\n [key in keyof schema]: scope[\"types\"] extends { [_ in schema[key]]: StaticAbiType } ? key : never;\n }[keyof schema];\n\nexport type extendScope<scope extends ScopeOptions, additionalTypes extends Dict<string, AbiType>> = show<\n ScopeOptions<show<scope[\"types\"] & additionalTypes>>\n>;\n\nexport function extendScope<scope extends ScopeOptions, additionalTypes extends Dict<string, AbiType>>(\n scope: scope,\n additionalTypes: additionalTypes,\n): extendScope<scope, additionalTypes> {\n return {\n types: {\n ...scope.types,\n ...additionalTypes,\n },\n };\n}\n","import { conform, show } from \"@arktype/util\";\nimport { AbiTypeScope, Scope } from \"./scope\";\nimport { hasOwnKey, isObject } from \"./generics\";\nimport { SchemaInput } from \"./input\";\nimport { FixedArrayAbiType, fixedArrayToArray, isFixedArrayAbiType } from \"@latticexyz/schema-type/internal\";\n\nexport type validateSchema<schema, scope extends Scope = AbiTypeScope> = schema extends string\n ? SchemaInput\n : {\n [key in keyof schema]: schema[key] extends FixedArrayAbiType\n ? schema[key]\n : conform<schema[key], keyof scope[\"types\"]>;\n };\n\nexport function validateSchema<scope extends Scope = AbiTypeScope>(\n schema: unknown,\n scope: scope = AbiTypeScope as never,\n): asserts schema is SchemaInput {\n if (!isObject(schema)) {\n throw new Error(`Expected schema, received ${JSON.stringify(schema)}`);\n }\n\n for (const internalType of Object.values(schema)) {\n if (isFixedArrayAbiType(internalType)) continue;\n if (hasOwnKey(scope.types, internalType)) continue;\n throw new Error(`\"${String(internalType)}\" is not a valid type in this scope.`);\n }\n}\n\nexport type resolveSchema<schema, scope extends Scope> = show<{\n readonly [key in keyof schema]: {\n /** the Solidity primitive ABI type */\n readonly type: schema[key] extends FixedArrayAbiType\n ? fixedArrayToArray<schema[key]>\n : scope[\"types\"][schema[key] & keyof scope[\"types\"]];\n /** the user defined type or Solidity primitive ABI type */\n readonly internalType: schema[key];\n };\n}>;\n\nexport function resolveSchema<schema extends SchemaInput, scope extends Scope = AbiTypeScope>(\n schema: schema,\n scope: scope = AbiTypeScope as unknown as scope,\n): resolveSchema<schema, scope> {\n return Object.fromEntries(\n Object.entries(schema).map(([key, internalType]) => [\n key,\n {\n type: isFixedArrayAbiType(internalType) ? fixedArrayToArray(internalType) : scope.types[internalType as never],\n internalType,\n },\n ]),\n ) as never;\n}\n\nexport function defineSchema<schema, scope extends AbiTypeScope = AbiTypeScope>(\n schema: validateSchema<schema, scope>,\n scope: scope = AbiTypeScope as scope,\n): resolveSchema<schema, scope> {\n validateSchema(schema, scope);\n return resolveSchema(schema, scope) as never;\n}\n\nexport function isSchemaInput<scope extends Scope = AbiTypeScope>(\n input: unknown,\n scope: scope = AbiTypeScope as never,\n): input is SchemaInput {\n return (\n typeof input === \"object\" &&\n input != null &&\n Object.values(input).every((fieldType) => isFixedArrayAbiType(fieldType) || hasOwnKey(scope.types, fieldType))\n );\n}\n","import { ErrorMessage, conform, show, narrow, requiredKeyOf } from \"@arktype/util\";\nimport { isStaticAbiType } from \"@latticexyz/schema-type/internal\";\nimport { Hex } from \"viem\";\nimport { get, hasOwnKey, mergeIfUndefined } from \"./generics\";\nimport { resolveSchema, validateSchema } from \"./schema\";\nimport { AbiTypeScope, Scope, getStaticAbiTypeKeys } from \"./scope\";\nimport { TableCodegen } from \"./output\";\nimport { TABLE_CODEGEN_DEFAULTS, TABLE_DEFAULTS, TABLE_DEPLOY_DEFAULTS } from \"./defaults\";\nimport { resourceToHex } from \"@latticexyz/common\";\nimport { SchemaInput, TableInput } from \"./input\";\n\nexport type ValidKeys<schema extends SchemaInput, scope extends Scope> = readonly [\n getStaticAbiTypeKeys<schema, scope>,\n ...getStaticAbiTypeKeys<schema, scope>[],\n];\n\nfunction getValidKeys<schema extends SchemaInput, scope extends Scope = AbiTypeScope>(\n schema: schema,\n scope: scope = AbiTypeScope as unknown as scope,\n): ValidKeys<schema, scope> {\n return Object.entries(schema)\n .filter(([, internalType]) => hasOwnKey(scope.types, internalType) && isStaticAbiType(scope.types[internalType]))\n .map(([key]) => key) as never;\n}\n\nexport function isValidPrimaryKey<schema extends SchemaInput, scope extends Scope>(\n key: unknown,\n schema: schema,\n scope: scope = AbiTypeScope as unknown as scope,\n): key is ValidKeys<schema, scope> {\n return (\n Array.isArray(key) &&\n key.every(\n (key) =>\n hasOwnKey(schema, key) && hasOwnKey(scope.types, schema[key]) && isStaticAbiType(scope.types[schema[key]]),\n )\n );\n}\n\nexport type validateKeys<validKeys extends PropertyKey, keys> = keys extends readonly string[]\n ? {\n readonly [i in keyof keys]: keys[i] extends validKeys ? keys[i] : validKeys;\n }\n : readonly string[];\n\nexport type ValidateTableOptions = { inStoreContext: boolean };\n\nexport type requiredTableKey<inStoreContext extends boolean> = Exclude<\n requiredKeyOf<TableInput>,\n inStoreContext extends true ? \"label\" | \"namespace\" : \"\"\n>;\n\nexport type validateTable<\n input,\n scope extends Scope = AbiTypeScope,\n options extends ValidateTableOptions = { inStoreContext: false },\n> = {\n [key in keyof input | requiredTableKey<options[\"inStoreContext\"]>]: key extends \"key\"\n ? validateKeys<getStaticAbiTypeKeys<conform<get<input, \"schema\">, SchemaInput>, scope>, get<input, key>>\n : key extends \"schema\"\n ? validateSchema<get<input, key>, scope>\n : key extends \"label\" | \"namespace\"\n ? options[\"inStoreContext\"] extends true\n ? ErrorMessage<\"Overrides of `label` and `namespace` are not allowed for tables in a store config\">\n : key extends keyof input\n ? narrow<input[key]>\n : never\n : key extends keyof TableInput\n ? TableInput[key]\n : ErrorMessage<`Key \\`${key & string}\\` does not exist in TableInput`>;\n};\n\nexport function validateTable<input, scope extends Scope = AbiTypeScope>(\n input: input,\n scope: scope = AbiTypeScope as unknown as scope,\n options: ValidateTableOptions = { inStoreContext: false },\n): asserts input is TableInput & input {\n if (typeof input !== \"object\" || input == null) {\n throw new Error(`Expected full table config, got \\`${JSON.stringify(input)}\\``);\n }\n\n if (!hasOwnKey(input, \"schema\")) {\n throw new Error(\"Missing schema input\");\n }\n validateSchema(input.schema, scope);\n\n if (!hasOwnKey(input, \"key\") || !isValidPrimaryKey(input[\"key\"], input[\"schema\"], scope)) {\n throw new Error(\n `Invalid key. Expected \\`(${getValidKeys(input[\"schema\"], scope)\n .map((item) => `\"${String(item)}\"`)\n .join(\" | \")})[]\\`, received \\`${\n hasOwnKey(input, \"key\") && Array.isArray(input.key)\n ? `[${input.key.map((item) => `\"${item}\"`).join(\", \")}]`\n : String(get(input, \"key\"))\n }\\``,\n );\n }\n\n if (hasOwnKey(input, \"namespace\") && typeof input.namespace === \"string\" && input.namespace.length > 14) {\n throw new Error(`Table \\`namespace\\` must fit into a \\`bytes14\\`, but \"${input.namespace}\" is too long.`);\n }\n if (hasOwnKey(input, \"name\") && typeof input.name === \"string\" && input.name.length > 16) {\n throw new Error(`Table \\`name\\` must fit into a \\`bytes16\\`, but \"${input.name}\" is too long.`);\n }\n\n if (options.inStoreContext && (hasOwnKey(input, \"label\") || hasOwnKey(input, \"namespace\"))) {\n throw new Error(\"Overrides of `label` and `namespace` are not allowed for tables in a store config.\");\n }\n}\n\nexport type resolveTableCodegen<input extends TableInput> = show<{\n [key in keyof TableCodegen]-?: key extends keyof input[\"codegen\"]\n ? undefined extends input[\"codegen\"][key]\n ? key extends \"dataStruct\"\n ? boolean\n : key extends keyof TABLE_CODEGEN_DEFAULTS\n ? TABLE_CODEGEN_DEFAULTS[key]\n : never\n : input[\"codegen\"][key]\n : // dataStruct isn't narrowed, because its value is conditional on the number of value schema fields\n key extends \"dataStruct\"\n ? boolean\n : key extends keyof TABLE_CODEGEN_DEFAULTS\n ? TABLE_CODEGEN_DEFAULTS[key]\n : never;\n}>;\n\nexport function resolveTableCodegen<input extends TableInput>(input: input): resolveTableCodegen<input> {\n const options = input.codegen;\n return {\n outputDirectory: get(options, \"outputDirectory\") ?? TABLE_CODEGEN_DEFAULTS.outputDirectory,\n tableIdArgument: get(options, \"tableIdArgument\") ?? TABLE_CODEGEN_DEFAULTS.tableIdArgument,\n storeArgument: get(options, \"storeArgument\") ?? TABLE_CODEGEN_DEFAULTS.storeArgument,\n // dataStruct is true if there are at least 2 value fields\n dataStruct: get(options, \"dataStruct\") ?? Object.keys(input.schema).length - input.key.length > 1,\n } satisfies TableCodegen as never;\n}\n\nexport type resolveTable<input, scope extends Scope = Scope> = input extends TableInput\n ? {\n readonly label: input[\"label\"];\n readonly type: undefined extends input[\"type\"] ? typeof TABLE_DEFAULTS.type : input[\"type\"];\n readonly namespace: string;\n readonly name: string;\n readonly tableId: Hex;\n readonly schema: resolveSchema<input[\"schema\"], scope>;\n readonly key: Readonly<input[\"key\"]>;\n readonly codegen: resolveTableCodegen<input>;\n readonly deploy: mergeIfUndefined<\n undefined extends input[\"deploy\"] ? {} : input[\"deploy\"],\n TABLE_DEPLOY_DEFAULTS\n >;\n }\n : never;\n\nexport function resolveTable<input extends TableInput, scope extends Scope = AbiTypeScope>(\n input: input,\n scope: scope = AbiTypeScope as unknown as scope,\n): resolveTable<input, scope> {\n const label = input.label;\n const type = input.type ?? TABLE_DEFAULTS.type;\n const namespace = input.namespace ?? TABLE_DEFAULTS.namespace;\n const name = input.name ?? label.slice(0, 16);\n const tableId = resourceToHex({ type, namespace, name });\n\n return {\n label,\n type,\n namespace,\n name,\n tableId,\n schema: resolveSchema(input.schema, scope),\n key: input.key,\n codegen: resolveTableCodegen(input),\n deploy: mergeIfUndefined(input.deploy ?? {}, TABLE_DEPLOY_DEFAULTS),\n } as never;\n}\n\nexport function defineTable<input, scope extends Scope = AbiTypeScope>(\n input: validateTable<input, scope>,\n scope: scope = AbiTypeScope as unknown as scope,\n): resolveTable<input, scope> {\n validateTable(input, scope);\n return resolveTable(input, scope) as never;\n}\n","import { FixedArrayAbiType, isFixedArrayAbiType, isStaticAbiType } from \"@latticexyz/schema-type/internal\";\nimport { hasOwnKey, isObject } from \"./generics\";\nimport { SchemaInput, ScopedSchemaInput, TableShorthandInput } from \"./input\";\nimport { isSchemaInput } from \"./schema\";\nimport { AbiTypeScope, Scope, getStaticAbiTypeKeys } from \"./scope\";\nimport { ErrorMessage, conform } from \"@arktype/util\";\n\nexport const NoStaticKeyFieldError =\n \"Invalid schema. Expected an `id` field with a static ABI type or an explicit `key` option.\";\n\nexport type NoStaticKeyFieldError = ErrorMessage<typeof NoStaticKeyFieldError>;\n\nexport function isTableShorthandInput(shorthand: unknown): shorthand is TableShorthandInput {\n return (\n typeof shorthand === \"string\" ||\n (isObject(shorthand) && Object.values(shorthand).every((value) => typeof value === \"string\"))\n );\n}\n\n// We don't use `conform` here because the restrictions we're imposing here are not native to typescript\nexport type validateTableShorthand<input, scope extends Scope = AbiTypeScope> = input extends SchemaInput\n ? // If a shorthand schema is provided, require it to have a static `id` field\n \"id\" extends getStaticAbiTypeKeys<input, scope>\n ? // Require all values to be valid types in this scope\n conform<input, ScopedSchemaInput<scope>>\n : NoStaticKeyFieldError\n : // If a fixed array type or a valid type from the scope is provided, accept it\n input extends FixedArrayAbiType | keyof scope[\"types\"]\n ? input\n : // If the input is not a valid shorthand, return the expected type\n input extends string\n ? keyof scope[\"types\"]\n : ScopedSchemaInput<scope>;\n\nexport function validateTableShorthand<scope extends Scope = AbiTypeScope>(\n shorthand: unknown,\n scope: scope = AbiTypeScope as never,\n): asserts shorthand is TableShorthandInput {\n if (typeof shorthand === \"string\") {\n if (isFixedArrayAbiType(shorthand) || hasOwnKey(scope.types, shorthand)) {\n return;\n }\n throw new Error(`Invalid ABI type. \\`${shorthand}\\` not found in scope.`);\n }\n if (typeof shorthand === \"object\" && shorthand !== null) {\n if (isSchemaInput(shorthand, scope)) {\n if (hasOwnKey(shorthand, \"id\") && isStaticAbiType(scope.types[shorthand.id as keyof typeof scope.types])) {\n return;\n }\n throw new Error(`Invalid schema. Expected an \\`id\\` field with a static ABI type or an explicit \\`key\\` option.`);\n }\n throw new Error(`Invalid schema. Are you using invalid types or missing types in your scope?`);\n }\n throw new Error(`Invalid table shorthand.`);\n}\n\nexport type expandTableShorthand<shorthand> = shorthand extends string\n ? {\n readonly schema: {\n readonly id: \"bytes32\";\n readonly value: shorthand;\n };\n readonly key: [\"id\"];\n }\n : shorthand extends SchemaInput\n ? {\n readonly schema: shorthand;\n readonly key: [\"id\"];\n }\n : shorthand;\n\nexport function expandTableShorthand<shorthand, scope extends Scope = AbiTypeScope>(\n shorthand: shorthand,\n scope: scope,\n): expandTableShorthand<shorthand> {\n if (typeof shorthand === \"string\") {\n return {\n schema: {\n id: \"bytes32\",\n value: shorthand,\n },\n key: [\"id\"],\n } as never;\n }\n\n if (isSchemaInput(shorthand, scope)) {\n return {\n schema: shorthand,\n key: [\"id\"],\n } as never;\n }\n\n return shorthand as never;\n}\n\nexport function defineTableShorthand<input, scope extends Scope = AbiTypeScope>(\n input: validateTableShorthand<input, scope>,\n scope: scope = AbiTypeScope as unknown as scope,\n): expandTableShorthand<input> {\n validateTableShorthand(input, scope);\n return expandTableShorthand(input, scope) as never;\n}\n","import { ErrorMessage, show } from \"@arktype/util\";\nimport { isObject, mergeIfUndefined } from \"./generics\";\nimport { TableShorthandInput, TablesInput } from \"./input\";\nimport { Scope, AbiTypeScope } from \"./scope\";\nimport { validateTable, resolveTable } from \"./table\";\nimport { expandTableShorthand, isTableShorthandInput, validateTableShorthand } from \"./tableShorthand\";\n\nexport type validateTables<tables, scope extends Scope = AbiTypeScope> = {\n [label in keyof tables]: tables[label] extends TableShorthandInput\n ? validateTableShorthand<tables[label], scope>\n : tables[label] extends object\n ? validateTable<tables[label], scope, { inStoreContext: true }>\n : ErrorMessage<`Expected tables config.`>;\n};\n\nexport function validateTables<scope extends Scope = AbiTypeScope>(\n input: unknown,\n scope: scope,\n): asserts input is TablesInput {\n if (isObject(input)) {\n for (const table of Object.values(input)) {\n if (isTableShorthandInput(table)) {\n validateTableShorthand(table, scope);\n } else {\n validateTable(table, scope, { inStoreContext: true });\n }\n }\n return;\n }\n throw new Error(`Expected tables config, received ${JSON.stringify(input)}`);\n}\n\nexport type resolveTables<tables, scope extends Scope = AbiTypeScope> = {\n readonly [label in keyof tables]: resolveTable<\n mergeIfUndefined<expandTableShorthand<tables[label]>, { readonly label: label }>,\n scope\n >;\n};\n\nexport function resolveTables<tables extends TablesInput, scope extends Scope = AbiTypeScope>(\n tables: tables,\n scope: scope,\n): resolveTables<tables, scope> {\n return Object.fromEntries(\n Object.entries(tables).map(([label, table]) => {\n return [label, resolveTable(mergeIfUndefined(expandTableShorthand(table, scope), { label }), scope)];\n }),\n ) as never;\n}\n\nexport function defineTables<input, scope extends Scope = AbiTypeScope>(\n input: validateTables<input, scope>,\n scope: scope = AbiTypeScope as never,\n): show<resolveTables<input, scope>> {\n validateTables(input, scope);\n return resolveTables(input, scope) as never;\n}\n","import { mapObject } from \"@latticexyz/common/utils\";\nimport { UserTypes } from \"./output\";\nimport { isSchemaAbiType } from \"@latticexyz/schema-type/internal\";\nimport { AbiTypeScope, extendScope } from \"./scope\";\nimport { hasOwnKey, isObject } from \"./generics\";\n\nexport type extractInternalType<userTypes extends UserTypes> = { [key in keyof userTypes]: userTypes[key][\"type\"] };\n\nexport function extractInternalType<userTypes extends UserTypes>(userTypes: userTypes): extractInternalType<userTypes> {\n return mapObject(userTypes, (userType) => userType.type);\n}\n\nexport function isUserTypes(userTypes: unknown): userTypes is UserTypes {\n return isObject(userTypes) && Object.values(userTypes).every((userType) => isSchemaAbiType(userType.type));\n}\n\nexport type scopeWithUserTypes<userTypes, scope extends AbiTypeScope = AbiTypeScope> = UserTypes extends userTypes\n ? scope\n : userTypes extends UserTypes\n ? extendScope<scope, extractInternalType<userTypes>>\n : scope;\n\nexport function scopeWithUserTypes<userTypes, scope extends AbiTypeScope = AbiTypeScope>(\n userTypes: userTypes,\n scope: scope = AbiTypeScope as scope,\n): scopeWithUserTypes<userTypes, scope> {\n return (isUserTypes(userTypes) ? extendScope(scope, extractInternalType(userTypes)) : scope) as never;\n}\n\nexport function validateUserTypes(userTypes: unknown): asserts userTypes is UserTypes {\n if (!isObject(userTypes)) {\n throw new Error(`Expected userTypes, received ${JSON.stringify(userTypes)}`);\n }\n\n for (const { type } of Object.values(userTypes)) {\n if (!hasOwnKey(AbiTypeScope.types, type)) {\n throw new Error(`\"${String(type)}\" is not a valid ABI type.`);\n }\n }\n}\n","import { flatMorph } from \"@arktype/util\";\nimport { EnumsInput } from \"./input\";\nimport { AbiTypeScope, extendScope } from \"./scope\";\nimport { parseNumber } from \"./generics\";\n\nfunction isEnums(enums: unknown): enums is EnumsInput {\n return (\n typeof enums === \"object\" &&\n enums != null &&\n Object.values(enums).every((item) => Array.isArray(item) && item.every((element) => typeof element === \"string\"))\n );\n}\n\nexport type scopeWithEnums<enums, scope extends AbiTypeScope = AbiTypeScope> = EnumsInput extends enums\n ? scope\n : enums extends EnumsInput\n ? extendScope<scope, { [key in keyof enums]: \"uint8\" }>\n : scope;\n\nexport function scopeWithEnums<enums, scope extends AbiTypeScope = AbiTypeScope>(\n enums: enums,\n scope: scope = AbiTypeScope as scope,\n): scopeWithEnums<enums, scope> {\n if (isEnums(enums)) {\n const enumScope = Object.fromEntries(Object.keys(enums).map((key) => [key, \"uint8\" as const]));\n return extendScope(scope, enumScope) as never;\n }\n return scope as never;\n}\n\nexport type resolveEnums<enums> = {\n readonly [key in keyof enums]: Readonly<enums[key]>;\n};\n\nexport function resolveEnums<enums extends EnumsInput>(enums: enums): resolveEnums<enums> {\n return enums;\n}\n\nexport type mapEnums<enums> = {\n readonly [key in keyof enums]: {\n readonly [element in keyof enums[key] as enums[key][element] & string]: parseNumber<element>;\n };\n};\n\nexport function mapEnums<enums extends EnumsInput>(enums: enums): resolveEnums<enums> {\n return flatMorph(enums as EnumsInput, (enumName, enumElements) => [\n enumName,\n flatMorph(enumElements, (enumIndex, enumElement) => [enumElement, enumIndex]),\n ]) as never;\n}\n","import { CODEGEN_DEFAULTS } from \"./defaults\";\nimport { isObject, mergeIfUndefined } from \"./generics\";\n\nexport type resolveCodegen<codegen> = codegen extends {}\n ? mergeIfUndefined<codegen, CODEGEN_DEFAULTS>\n : CODEGEN_DEFAULTS;\n\nexport function resolveCodegen<codegen>(codegen: codegen): resolveCodegen<codegen> {\n return (\n isObject(codegen) ? mergeIfUndefined(codegen, CODEGEN_DEFAULTS) : CODEGEN_DEFAULTS\n ) as resolveCodegen<codegen>;\n}\n","import { flatMorph, show } from \"@arktype/util\";\nimport { Tables } from \"./output\";\n\n/**\n * @internal Only kept for backwards compatibility\n */\nexport type resolveNamespacedTables<tables, namespace> = {\n readonly [label in keyof tables as namespace extends \"\"\n ? label\n : `${namespace & string}__${label & string}`]: tables[label];\n};\n\n/**\n * @internal Only kept for backwards compatibility\n */\nexport function resolveNamespacedTables<tables, namespace>(\n tables: tables,\n namespace: namespace,\n): show<resolveNamespacedTables<tables, namespace>> {\n return flatMorph(tables as Tables, (label, table) => [\n namespace === \"\" ? label : `${namespace}__${label}`,\n table,\n ]) as never;\n}\n","import { ErrorMessage, show, flatMorph, narrow } from \"@arktype/util\";\nimport { get, hasOwnKey, mergeIfUndefined } from \"./generics\";\nimport { UserTypes } from \"./output\";\nimport { CONFIG_DEFAULTS } from \"./defaults\";\nimport { StoreInput, TableInput } from \"./input\";\nimport { resolveTables, validateTables } from \"./tables\";\nimport { scopeWithUserTypes, validateUserTypes } from \"./userTypes\";\nimport { mapEnums, resolveEnums, scopeWithEnums } from \"./enums\";\nimport { resolveCodegen } from \"./codegen\";\nimport { resolveNamespacedTables } from \"./namespacedTables\";\nimport { resolveTable } from \"./table\";\nimport { resolveNamespace } from \"./namespace\";\nimport { expandTableShorthand } from \"./tableShorthand\";\n\nexport type extendedScope<input> = scopeWithEnums<get<input, \"enums\">, scopeWithUserTypes<get<input, \"userTypes\">>>;\n\nexport function extendedScope<input>(input: input): extendedScope<input> {\n return scopeWithEnums(get(input, \"enums\"), scopeWithUserTypes(get(input, \"userTypes\")));\n}\n\nexport type validateStore<input> = {\n [key in keyof input]: key extends \"tables\"\n ? validateTables<input[key], extendedScope<input>>\n : key extends \"userTypes\"\n ? UserTypes\n : key extends \"enums\"\n ? narrow<input[key]>\n : key extends keyof StoreInput\n ? StoreInput[key]\n : ErrorMessage<`\\`${key & string}\\` is not a valid Store config option.`>;\n};\n\nexport function validateStore(input: unknown): asserts input is StoreInput {\n const scope = extendedScope(input);\n\n if (hasOwnKey(input, \"namespace\") && typeof input.namespace === \"string\" && input.namespace.length > 14) {\n throw new Error(`\\`namespace\\` must fit into a \\`bytes14\\`, but \"${input.namespace}\" is too long.`);\n }\n\n if (hasOwnKey(input, \"tables\")) {\n validateTables(input.tables, scope);\n }\n\n if (hasOwnKey(input, \"userTypes\")) {\n validateUserTypes(input.userTypes);\n }\n}\n\nexport type resolveStore<\n input,\n namespace = \"namespace\" extends keyof input\n ? input[\"namespace\"] extends string\n ? input[\"namespace\"]\n : CONFIG_DEFAULTS[\"namespace\"]\n : CONFIG_DEFAULTS[\"namespace\"],\n> = {\n readonly namespace: string;\n readonly sourceDirectory: \"sourceDirectory\" extends keyof input\n ? input[\"sourceDirectory\"]\n : CONFIG_DEFAULTS[\"sourceDirectory\"];\n readonly tables: \"tables\" extends keyof input\n ? resolveNamespacedTables<\n {\n readonly [label in keyof input[\"tables\"]]: resolveTable<\n mergeIfUndefined<expandTableShorthand<input[\"tables\"][label]>, { label: label; namespace: namespace }>,\n extendedScope<input>\n >;\n },\n namespace\n >\n : {};\n readonly userTypes: \"userTypes\" extends keyof input ? input[\"userTypes\"] : {};\n readonly enums: \"enums\" extends keyof input ? show<resolveEnums<input[\"enums\"]>> : {};\n readonly enumValues: \"enums\" extends keyof input ? show<mapEnums<input[\"enums\"]>> : {};\n readonly codegen: \"codegen\" extends keyof input ? resolveCodegen<input[\"codegen\"]> : resolveCodegen<{}>;\n readonly namespaces: {\n readonly [label in namespace & string]: resolveNamespace<\n {\n readonly label: label;\n readonly tables: \"tables\" extends keyof input ? input[\"tables\"] : undefined;\n },\n extendedScope<input>\n >;\n };\n};\n\nexport function resolveStore<const input extends StoreInput>(input: input): resolveStore<input> {\n const scope = extendedScope(input);\n const namespace = input.namespace ?? CONFIG_DEFAULTS[\"namespace\"];\n const codegen = resolveCodegen(input.codegen);\n\n const tablesInput = flatMorph(input.tables ?? {}, (label, shorthand) => {\n const table = expandTableShorthand(shorthand, scope) as TableInput;\n return [\n label,\n {\n ...table,\n label,\n namespace,\n codegen: {\n ...table.codegen,\n outputDirectory:\n table.codegen?.outputDirectory ??\n (codegen.namespaceDirectories && namespace !== \"\" ? `${namespace}/tables` : \"tables\"),\n },\n },\n ];\n });\n\n const namespaces = {\n [namespace]: resolveNamespace({ label: namespace, tables: tablesInput }, scope),\n };\n\n const tables = resolveTables(tablesInput, scope);\n\n return {\n namespace,\n tables: resolveNamespacedTables(tables, namespace),\n namespaces,\n sourceDirectory: input.sourceDirectory ?? CONFIG_DEFAULTS[\"sourceDirectory\"],\n userTypes: input.userTypes ?? {},\n enums: resolveEnums(input.enums ?? {}),\n enumValues: mapEnums(input.enums ?? {}),\n codegen,\n } as never;\n}\n\nexport function defineStore<const input>(input: validateStore<input>): show<resolveStore<input>> {\n validateStore(input);\n return resolveStore(input) as never;\n}\n","import { ErrorMessage, flatMorph } from \"@arktype/util\";\nimport { hasOwnKey, mergeIfUndefined } from \"./generics\";\nimport { NamespaceInput } from \"./input\";\nimport { resolveTables, validateTables } from \"./tables\";\nimport { AbiTypeScope, Scope } from \"./scope\";\nimport { expandTableShorthand } from \"./tableShorthand\";\n\nexport type validateNamespace<input, scope extends Scope = AbiTypeScope> = {\n [key in keyof input]: key extends \"tables\"\n ? validateTables<input[key], scope>\n : key extends keyof NamespaceInput\n ? NamespaceInput[key]\n : ErrorMessage<`\\`${key & string}\\` is not a valid namespace config option.`>;\n};\n\nexport function validateNamespace<scope extends Scope = AbiTypeScope>(\n input: unknown,\n scope: scope,\n): asserts input is NamespaceInput {\n if (hasOwnKey(input, \"namespace\") && typeof input.namespace === \"string\" && input.namespace.length > 14) {\n throw new Error(`\\`namespace\\` must fit into a \\`bytes14\\`, but \"${input.namespace}\" is too long.`);\n }\n if (hasOwnKey(input, \"tables\")) {\n validateTables(input.tables, scope);\n }\n}\n\nexport type resolveNamespace<input, scope extends Scope = AbiTypeScope> = input extends NamespaceInput\n ? {\n readonly label: input[\"label\"];\n readonly namespace: string;\n readonly tables: undefined extends input[\"tables\"]\n ? {}\n : resolveTables<\n {\n readonly [label in keyof input[\"tables\"]]: mergeIfUndefined<\n expandTableShorthand<input[\"tables\"][label]>,\n { readonly namespace: string }\n >;\n },\n scope\n >;\n }\n : never;\n\nexport function resolveNamespace<const input extends NamespaceInput, scope extends Scope = AbiTypeScope>(\n input: input,\n scope: scope,\n): resolveNamespace<input, scope> {\n const label = input.label;\n const namespace = input.namespace ?? label.slice(0, 14);\n return {\n label,\n namespace,\n tables: resolveTables(\n flatMorph(input.tables ?? {}, (label, table) => {\n return [label, mergeIfUndefined(expandTableShorthand(table, scope), { namespace })];\n }),\n scope,\n ),\n } as never;\n}\n"],"mappings":"AAEO,SAASA,EAAoCC,EAAcC,EAA2B,CAC3F,OAAQ,OAAOD,GAAU,UAAYA,GAAS,MAAQE,EAAUF,EAAOC,CAAG,EAAID,EAAMC,CAAG,EAAI,MAC7F,CAWO,SAASE,EAAoDH,EAAcI,EAAkC,CAClH,OAAOA,EAAK,OAAUD,EAAQJ,EAAIC,EAAOI,EAAK,CAAC,CAAC,EAAGA,EAAK,MAAM,CAAC,CAAC,EAAeJ,CACjF,CAEO,SAASE,EACdG,E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M,QAAU,CAAC,EAAG,CAACgB,EAAOC,IAAc,CACtE,IAAMC,EAAQC,EAAqBF,EAAWZ,CAAK,EACnD,MAAO,CACLW,EACA,CACE,GAAGE,EACH,MAAAF,EACA,UAAAN,EACA,QAAS,CACP,GAAGQ,EAAM,QACT,gBACEA,EAAM,SAAS,kBACdN,EAAQ,sBAAwBF,IAAc,GAAK,GAAGA,WAAqB,SAChF,CACF,CACF,CACF,CAAC,EAEKU,EAAa,CACjB,CAACV,CAAS,EAAGW,EAAiB,CAAE,MAAOX,EAAW,OAAQI,CAAY,EAAGT,CAAK,CAChF,EAEMiB,EAASC,EAAcT,EAAaT,CAAK,EAE/C,MAAO,CACL,UAAAK,EACA,OAAQc,EAAwBF,EAAQZ,CAAS,EACjD,WAAAU,EACA,gBAAiBpB,EAAM,iBAAmBW,EAAgB,gBAC1D,UAAWX,EAAM,WAAa,CAAC,EAC/B,MAAoBA,EAAM,OAAS,CAAC,EACpC,WAAYyB,EAASzB,EAAM,OAAS,CAAC,CAAC,EACtC,QAAAY,CACF,CACF,CAEO,SAASc,GAAyB1B,EAAwD,CAC/F,OAAAI,GAAcJ,CAAK,EACZS,GAAaT,CAAK,CAC3B","names":["get","input","key","hasOwnKey","getPath","path","object","isObject","mergeIfUndefined","base","defaults","keys","CODEGEN_DEFAULTS","TABLE_CODEGEN_DEFAULTS","TABLE_DEPLOY_DEFAULTS","TABLE_DEFAULTS","CONFIG_DEFAULTS","schemaAbiTypes","Scope","AbiTypeScope","abiType","extendScope","scope","additionalTypes","fixedArrayToArray","isFixedArrayAbiType","validateSchema","schema","scope","AbiTypeScope","isObject","internalType","hasOwnKey","resolveSchema","key","defineSchema","isSchemaInput","input","fieldType","isStaticAbiType","resourceToHex","getValidKeys","schema","scope","AbiTypeScope","internalType","hasOwnKey","isStaticAbiType","key","isValidPrimaryKey","validateTable","input","options","validateSchema","item","get","resolveTableCodegen","TABLE_CODEGEN_DEFAULTS","resolveTable","label","type","TABLE_DEFAULTS","namespace","name","tableId","resolveSchema","mergeIfUndefined","TABLE_DEPLOY_DEFAULTS","defineTable","isFixedArrayAbiType","isStaticAbiType","NoStaticKeyFieldError","isTableShorthandInput","shorthand","isObject","value","validateTableShorthand","scope","AbiTypeScope","isFixedArrayAbiType","hasOwnKey","isSchemaInput","isStaticAbiType","expandTableShorthand","defineTableShorthand","input","validateTables","input","scope","isObject","table","isTableShorthandInput","validateTableShorthand","validateTable","resolveTables","tables","label","resolveTable","mergeIfUndefined","expandTableShorthand","defineTables","AbiTypeScope","mapObject","isSchemaAbiType","extractInternalType","userTypes","mapObject","userType","isUserTypes","isObject","isSchemaAbiType","scopeWithUserTypes","scope","AbiTypeScope","extendScope","validateUserTypes","type","hasOwnKey","flatMorph","isEnums","enums","item","element","scopeWithEnums","scope","AbiTypeScope","enumScope","key","extendScope","resolveEnums","mapEnums","flatMorph","enumName","enumElements","enumIndex","enumElement","resolveCodegen","codegen","isObject","mergeIfUndefined","CODEGEN_DEFAULTS","flatMorph","resolveNamespacedTables","tables","namespace","label","table","flatMorph","flatMorph","resolveNamespace","input","scope","label","namespace","resolveTables","flatMorph","table","mergeIfUndefined","expandTableShorthand","extendedScope","input","scopeWithEnums","get","scopeWithUserTypes","validateStore","scope","hasOwnKey","validateTables","validateUserTypes","resolveStore","namespace","CONFIG_DEFAULTS","codegen","resolveCodegen","tablesInput","flatMorph","label","shorthand","table","expandTableShorthand","namespaces","resolveNamespace","tables","resolveTables","resolveNamespacedTables","mapEnums","defineStore"]}
1
+ {"version":3,"sources":["../ts/config/v2/generics.ts","../ts/config/v2/defaults.ts","../ts/config/v2/scope.ts","../ts/config/v2/schema.ts","../ts/config/v2/table.ts","../ts/config/v2/tableShorthand.ts","../ts/config/v2/tables.ts","../ts/config/v2/userTypes.ts","../ts/config/v2/enums.ts","../ts/config/v2/codegen.ts","../ts/config/v2/namespacedTables.ts","../ts/config/v2/namespace.ts","../ts/config/v2/store.ts"],"sourcesContent":["export type get<input, key> = key extends keyof input ? input[key] : undefined;\n\nexport function get<input, key extends PropertyKey>(input: input, key: key): get<input, key> {\n return (typeof input === \"object\" && input != null && hasOwnKey(input, key) ? input[key] : undefined) as never;\n}\n\nexport type getPath<input, path extends readonly PropertyKey[]> = path extends readonly [\n infer head,\n ...infer tail extends PropertyKey[],\n]\n ? head extends keyof input\n ? getPath<input[head], tail>\n : undefined\n : input;\n\nexport function getPath<input, path extends readonly PropertyKey[]>(input: input, path: path): getPath<input, path> {\n return path.length ? (getPath(get(input, path[0]), path.slice(1)) as never) : (input as never);\n}\n\nexport function hasOwnKey<obj, const key extends PropertyKey>(\n object: obj,\n key: key,\n): object is { [k in key]: k extends keyof obj ? obj[k] : unknown } & obj {\n // eslint-disable-next-line no-prototype-builtins\n return typeof object === \"object\" && object !== null && object.hasOwnProperty(key);\n}\n\nexport function isObject<input>(input: input): input is input & object {\n return input != null && typeof input === \"object\";\n}\n\nexport type mergeIfUndefined<base, defaults> = {\n readonly [key in keyof base | keyof defaults]: key extends keyof base\n ? undefined extends base[key]\n ? key extends keyof defaults\n ? defaults[key]\n : base[key]\n : base[key]\n : key extends keyof defaults\n ? defaults[key]\n : never;\n};\n\nexport function mergeIfUndefined<base extends object, defaults extends object>(\n base: base,\n defaults: defaults,\n): mergeIfUndefined<base, defaults> {\n const keys = [...new Set([...Object.keys(base), ...Object.keys(defaults)])];\n return Object.fromEntries(\n keys.map((key) => [\n key,\n typeof base[key as keyof base] === \"undefined\" ? defaults[key as keyof defaults] : base[key as keyof base],\n ]),\n ) as never;\n}\n\nexport type parseNumber<T> = T extends `${infer N extends number}` ? N : never;\n","import { CodegenInput, StoreInput, TableCodegenInput, TableDeployInput, TableInput } from \"./input\";\n\nexport const CODEGEN_DEFAULTS = {\n storeImportPath: \"@latticexyz/store/src\",\n userTypesFilename: \"common.sol\",\n outputDirectory: \"codegen\",\n // TODO: default to true if using top-level `namespaces` key (once its migrated to store)\n namespaceDirectories: false,\n indexFilename: \"index.sol\",\n} as const satisfies CodegenInput;\n\nexport type CODEGEN_DEFAULTS = typeof CODEGEN_DEFAULTS;\n\nexport const TABLE_CODEGEN_DEFAULTS = {\n outputDirectory: \"tables\" as string,\n tableIdArgument: false,\n storeArgument: false,\n} as const satisfies TableCodegenInput;\n\nexport type TABLE_CODEGEN_DEFAULTS = typeof TABLE_CODEGEN_DEFAULTS;\n\nexport const TABLE_DEPLOY_DEFAULTS = {\n disabled: false,\n} as const satisfies TableDeployInput;\n\nexport type TABLE_DEPLOY_DEFAULTS = typeof TABLE_DEPLOY_DEFAULTS;\n\nexport const TABLE_DEFAULTS = {\n namespace: \"\",\n type: \"table\",\n} as const satisfies Pick<TableInput, \"namespace\" | \"type\">;\n\nexport type TABLE_DEFAULTS = typeof TABLE_DEFAULTS;\n\nexport const CONFIG_DEFAULTS = {\n sourceDirectory: \"src\",\n namespace: \"\",\n} as const satisfies StoreInput;\n\nexport type CONFIG_DEFAULTS = typeof CONFIG_DEFAULTS;\n","import { Dict, show } from \"@arktype/util\";\nimport { SchemaInput } from \"./input\";\nimport { StaticAbiType, schemaAbiTypes } from \"@latticexyz/schema-type/internal\";\nimport { AbiType } from \"./output\";\n\nexport const Scope = { types: {} } as const satisfies ScopeOptions;\nexport type Scope = typeof Scope;\n\nexport type AbiTypeScope = ScopeOptions<{ [t in AbiType]: t }>;\nexport const AbiTypeScope = {\n types: Object.fromEntries(schemaAbiTypes.map((abiType) => [abiType, abiType])),\n} as AbiTypeScope;\n\nexport type ScopeOptions<types extends Dict<string, AbiType> = Dict<string, AbiType>> = {\n types: types;\n};\n\nexport type getStaticAbiTypeKeys<\n schema extends SchemaInput,\n scope extends Scope = AbiTypeScope,\n> = SchemaInput extends schema\n ? string\n : {\n [key in keyof schema]: scope[\"types\"] extends { [_ in schema[key]]: StaticAbiType } ? key : never;\n }[keyof schema];\n\nexport type extendScope<scope extends ScopeOptions, additionalTypes extends Dict<string, AbiType>> = show<\n ScopeOptions<show<scope[\"types\"] & additionalTypes>>\n>;\n\nexport function extendScope<scope extends ScopeOptions, additionalTypes extends Dict<string, AbiType>>(\n scope: scope,\n additionalTypes: additionalTypes,\n): extendScope<scope, additionalTypes> {\n return {\n types: {\n ...scope.types,\n ...additionalTypes,\n },\n };\n}\n","import { conform, show } from \"@arktype/util\";\nimport { AbiTypeScope, Scope } from \"./scope\";\nimport { hasOwnKey, isObject } from \"./generics\";\nimport { SchemaInput } from \"./input\";\nimport { FixedArrayAbiType, fixedArrayToArray, isFixedArrayAbiType } from \"@latticexyz/schema-type/internal\";\n\nexport type validateSchema<schema, scope extends Scope = AbiTypeScope> = schema extends string\n ? SchemaInput\n : {\n [key in keyof schema]: schema[key] extends FixedArrayAbiType\n ? schema[key]\n : conform<schema[key], keyof scope[\"types\"]>;\n };\n\nexport function validateSchema<scope extends Scope = AbiTypeScope>(\n schema: unknown,\n scope: scope = AbiTypeScope as never,\n): asserts schema is SchemaInput {\n if (!isObject(schema)) {\n throw new Error(`Expected schema, received ${JSON.stringify(schema)}`);\n }\n\n for (const internalType of Object.values(schema)) {\n if (isFixedArrayAbiType(internalType)) continue;\n if (hasOwnKey(scope.types, internalType)) continue;\n throw new Error(`\"${String(internalType)}\" is not a valid type in this scope.`);\n }\n}\n\nexport type resolveSchema<schema, scope extends Scope> = show<{\n readonly [key in keyof schema]: {\n /** the Solidity primitive ABI type */\n readonly type: schema[key] extends FixedArrayAbiType\n ? fixedArrayToArray<schema[key]>\n : scope[\"types\"][schema[key] & keyof scope[\"types\"]];\n /** the user defined type or Solidity primitive ABI type */\n readonly internalType: schema[key];\n };\n}>;\n\nexport function resolveSchema<schema extends SchemaInput, scope extends Scope = AbiTypeScope>(\n schema: schema,\n scope: scope = AbiTypeScope as unknown as scope,\n): resolveSchema<schema, scope> {\n return Object.fromEntries(\n Object.entries(schema).map(([key, internalType]) => [\n key,\n {\n type: isFixedArrayAbiType(internalType) ? fixedArrayToArray(internalType) : scope.types[internalType as never],\n internalType,\n },\n ]),\n ) as never;\n}\n\nexport function defineSchema<schema, scope extends AbiTypeScope = AbiTypeScope>(\n schema: validateSchema<schema, scope>,\n scope: scope = AbiTypeScope as scope,\n): resolveSchema<schema, scope> {\n validateSchema(schema, scope);\n return resolveSchema(schema, scope) as never;\n}\n\nexport function isSchemaInput<scope extends Scope = AbiTypeScope>(\n input: unknown,\n scope: scope = AbiTypeScope as never,\n): input is SchemaInput {\n return (\n typeof input === \"object\" &&\n input != null &&\n Object.values(input).every((fieldType) => isFixedArrayAbiType(fieldType) || hasOwnKey(scope.types, fieldType))\n );\n}\n","import { ErrorMessage, conform, show, narrow, requiredKeyOf } from \"@arktype/util\";\nimport { isStaticAbiType } from \"@latticexyz/schema-type/internal\";\nimport { Hex } from \"viem\";\nimport { get, hasOwnKey, mergeIfUndefined } from \"./generics\";\nimport { resolveSchema, validateSchema } from \"./schema\";\nimport { AbiTypeScope, Scope, getStaticAbiTypeKeys } from \"./scope\";\nimport { TableCodegen } from \"./output\";\nimport { TABLE_CODEGEN_DEFAULTS, TABLE_DEFAULTS, TABLE_DEPLOY_DEFAULTS } from \"./defaults\";\nimport { resourceToHex } from \"@latticexyz/common\";\nimport { SchemaInput, TableInput } from \"./input\";\n\nexport type ValidKeys<schema extends SchemaInput, scope extends Scope> = readonly [\n getStaticAbiTypeKeys<schema, scope>,\n ...getStaticAbiTypeKeys<schema, scope>[],\n];\n\nfunction getValidKeys<schema extends SchemaInput, scope extends Scope = AbiTypeScope>(\n schema: schema,\n scope: scope = AbiTypeScope as unknown as scope,\n): ValidKeys<schema, scope> {\n return Object.entries(schema)\n .filter(([, internalType]) => hasOwnKey(scope.types, internalType) && isStaticAbiType(scope.types[internalType]))\n .map(([key]) => key) as never;\n}\n\nexport function isValidPrimaryKey<schema extends SchemaInput, scope extends Scope>(\n key: unknown,\n schema: schema,\n scope: scope = AbiTypeScope as unknown as scope,\n): key is ValidKeys<schema, scope> {\n return (\n Array.isArray(key) &&\n key.every(\n (key) =>\n hasOwnKey(schema, key) && hasOwnKey(scope.types, schema[key]) && isStaticAbiType(scope.types[schema[key]]),\n )\n );\n}\n\nexport type validateKeys<validKeys extends PropertyKey, keys> = keys extends readonly string[]\n ? {\n readonly [i in keyof keys]: keys[i] extends validKeys ? keys[i] : validKeys;\n }\n : readonly string[];\n\nexport type ValidateTableOptions = { inStoreContext: boolean };\n\nexport type requiredTableKey<inStoreContext extends boolean> = Exclude<\n requiredKeyOf<TableInput>,\n inStoreContext extends true ? \"label\" | \"namespace\" : \"\"\n>;\n\nexport type validateTable<\n input,\n scope extends Scope = AbiTypeScope,\n options extends ValidateTableOptions = { inStoreContext: false },\n> = {\n [key in keyof input | requiredTableKey<options[\"inStoreContext\"]>]: key extends \"key\"\n ? validateKeys<getStaticAbiTypeKeys<conform<get<input, \"schema\">, SchemaInput>, scope>, get<input, key>>\n : key extends \"schema\"\n ? validateSchema<get<input, key>, scope>\n : key extends \"label\" | \"namespace\"\n ? options[\"inStoreContext\"] extends true\n ? ErrorMessage<\"Overrides of `label` and `namespace` are not allowed for tables in a store config\">\n : key extends keyof input\n ? narrow<input[key]>\n : never\n : key extends keyof TableInput\n ? TableInput[key]\n : ErrorMessage<`Key \\`${key & string}\\` does not exist in TableInput`>;\n};\n\nexport function validateTable<input, scope extends Scope = AbiTypeScope>(\n input: input,\n scope: scope = AbiTypeScope as unknown as scope,\n options: ValidateTableOptions = { inStoreContext: false },\n): asserts input is TableInput & input {\n if (typeof input !== \"object\" || input == null) {\n throw new Error(`Expected full table config, got \\`${JSON.stringify(input)}\\``);\n }\n\n if (!hasOwnKey(input, \"schema\")) {\n throw new Error(\"Missing schema input\");\n }\n validateSchema(input.schema, scope);\n\n if (!hasOwnKey(input, \"key\") || !isValidPrimaryKey(input[\"key\"], input[\"schema\"], scope)) {\n throw new Error(\n `Invalid key. Expected \\`(${getValidKeys(input[\"schema\"], scope)\n .map((item) => `\"${String(item)}\"`)\n .join(\" | \")})[]\\`, received \\`${\n hasOwnKey(input, \"key\") && Array.isArray(input.key)\n ? `[${input.key.map((item) => `\"${item}\"`).join(\", \")}]`\n : String(get(input, \"key\"))\n }\\``,\n );\n }\n\n if (hasOwnKey(input, \"namespace\") && typeof input.namespace === \"string\" && input.namespace.length > 14) {\n throw new Error(`Table \\`namespace\\` must fit into a \\`bytes14\\`, but \"${input.namespace}\" is too long.`);\n }\n if (hasOwnKey(input, \"name\") && typeof input.name === \"string\" && input.name.length > 16) {\n throw new Error(`Table \\`name\\` must fit into a \\`bytes16\\`, but \"${input.name}\" is too long.`);\n }\n\n if (options.inStoreContext && (hasOwnKey(input, \"label\") || hasOwnKey(input, \"namespace\"))) {\n throw new Error(\"Overrides of `label` and `namespace` are not allowed for tables in a store config.\");\n }\n}\n\nexport type resolveTableCodegen<input extends TableInput> = show<{\n [key in keyof TableCodegen]-?: key extends keyof input[\"codegen\"]\n ? undefined extends input[\"codegen\"][key]\n ? key extends \"dataStruct\"\n ? boolean\n : key extends keyof TABLE_CODEGEN_DEFAULTS\n ? TABLE_CODEGEN_DEFAULTS[key]\n : never\n : input[\"codegen\"][key]\n : // dataStruct isn't narrowed, because its value is conditional on the number of value schema fields\n key extends \"dataStruct\"\n ? boolean\n : key extends keyof TABLE_CODEGEN_DEFAULTS\n ? TABLE_CODEGEN_DEFAULTS[key]\n : never;\n}>;\n\nexport function resolveTableCodegen<input extends TableInput>(input: input): resolveTableCodegen<input> {\n const options = input.codegen;\n return {\n outputDirectory: get(options, \"outputDirectory\") ?? TABLE_CODEGEN_DEFAULTS.outputDirectory,\n tableIdArgument: get(options, \"tableIdArgument\") ?? TABLE_CODEGEN_DEFAULTS.tableIdArgument,\n storeArgument: get(options, \"storeArgument\") ?? TABLE_CODEGEN_DEFAULTS.storeArgument,\n // dataStruct is true if there are at least 2 value fields\n dataStruct: get(options, \"dataStruct\") ?? Object.keys(input.schema).length - input.key.length > 1,\n } satisfies TableCodegen as never;\n}\n\nexport type resolveTable<input, scope extends Scope = Scope> = input extends TableInput\n ? {\n readonly label: input[\"label\"];\n readonly type: undefined extends input[\"type\"] ? typeof TABLE_DEFAULTS.type : input[\"type\"];\n readonly namespace: string;\n readonly name: string;\n readonly tableId: Hex;\n readonly schema: resolveSchema<input[\"schema\"], scope>;\n readonly key: Readonly<input[\"key\"]>;\n readonly codegen: resolveTableCodegen<input>;\n readonly deploy: mergeIfUndefined<\n undefined extends input[\"deploy\"] ? {} : input[\"deploy\"],\n TABLE_DEPLOY_DEFAULTS\n >;\n }\n : never;\n\nexport function resolveTable<input extends TableInput, scope extends Scope = AbiTypeScope>(\n input: input,\n scope: scope = AbiTypeScope as unknown as scope,\n): resolveTable<input, scope> {\n const label = input.label;\n const type = input.type ?? TABLE_DEFAULTS.type;\n const namespace = input.namespace ?? TABLE_DEFAULTS.namespace;\n const name = input.name ?? label.slice(0, 16);\n const tableId = resourceToHex({ type, namespace, name });\n\n return {\n label,\n type,\n namespace,\n name,\n tableId,\n schema: resolveSchema(input.schema, scope),\n key: input.key,\n codegen: resolveTableCodegen(input),\n deploy: mergeIfUndefined(input.deploy ?? {}, TABLE_DEPLOY_DEFAULTS),\n } as never;\n}\n\nexport function defineTable<input, scope extends Scope = AbiTypeScope>(\n input: validateTable<input, scope>,\n scope: scope = AbiTypeScope as unknown as scope,\n): resolveTable<input, scope> {\n validateTable(input, scope);\n return resolveTable(input, scope) as never;\n}\n","import { FixedArrayAbiType, isFixedArrayAbiType, isStaticAbiType } from \"@latticexyz/schema-type/internal\";\nimport { hasOwnKey, isObject } from \"./generics\";\nimport { SchemaInput, ScopedSchemaInput, TableShorthandInput } from \"./input\";\nimport { isSchemaInput } from \"./schema\";\nimport { AbiTypeScope, Scope, getStaticAbiTypeKeys } from \"./scope\";\nimport { ErrorMessage, conform } from \"@arktype/util\";\n\nexport const NoStaticKeyFieldError =\n \"Invalid schema. Expected an `id` field with a static ABI type or an explicit `key` option.\";\n\nexport type NoStaticKeyFieldError = ErrorMessage<typeof NoStaticKeyFieldError>;\n\nexport function isTableShorthandInput(shorthand: unknown): shorthand is TableShorthandInput {\n return (\n typeof shorthand === \"string\" ||\n (isObject(shorthand) && Object.values(shorthand).every((value) => typeof value === \"string\"))\n );\n}\n\n// We don't use `conform` here because the restrictions we're imposing here are not native to typescript\nexport type validateTableShorthand<input, scope extends Scope = AbiTypeScope> = input extends SchemaInput\n ? // If a shorthand schema is provided, require it to have a static `id` field\n \"id\" extends getStaticAbiTypeKeys<input, scope>\n ? // Require all values to be valid types in this scope\n conform<input, ScopedSchemaInput<scope>>\n : NoStaticKeyFieldError\n : // If a fixed array type or a valid type from the scope is provided, accept it\n input extends FixedArrayAbiType | keyof scope[\"types\"]\n ? input\n : // If the input is not a valid shorthand, return the expected type\n input extends string\n ? keyof scope[\"types\"]\n : ScopedSchemaInput<scope>;\n\nexport function validateTableShorthand<scope extends Scope = AbiTypeScope>(\n shorthand: unknown,\n scope: scope = AbiTypeScope as never,\n): asserts shorthand is TableShorthandInput {\n if (typeof shorthand === \"string\") {\n if (isFixedArrayAbiType(shorthand) || hasOwnKey(scope.types, shorthand)) {\n return;\n }\n throw new Error(`Invalid ABI type. \\`${shorthand}\\` not found in scope.`);\n }\n if (typeof shorthand === \"object\" && shorthand !== null) {\n if (isSchemaInput(shorthand, scope)) {\n if (hasOwnKey(shorthand, \"id\") && isStaticAbiType(scope.types[shorthand.id as keyof typeof scope.types])) {\n return;\n }\n throw new Error(`Invalid schema. Expected an \\`id\\` field with a static ABI type or an explicit \\`key\\` option.`);\n }\n throw new Error(`Invalid schema. Are you using invalid types or missing types in your scope?`);\n }\n throw new Error(`Invalid table shorthand.`);\n}\n\nexport type expandTableShorthand<shorthand> = shorthand extends string\n ? {\n readonly schema: {\n readonly id: \"bytes32\";\n readonly value: shorthand;\n };\n readonly key: [\"id\"];\n }\n : shorthand extends SchemaInput\n ? {\n readonly schema: shorthand;\n readonly key: [\"id\"];\n }\n : shorthand;\n\nexport function expandTableShorthand<shorthand, scope extends Scope = AbiTypeScope>(\n shorthand: shorthand,\n scope: scope,\n): expandTableShorthand<shorthand> {\n if (typeof shorthand === \"string\") {\n return {\n schema: {\n id: \"bytes32\",\n value: shorthand,\n },\n key: [\"id\"],\n } as never;\n }\n\n if (isSchemaInput(shorthand, scope)) {\n return {\n schema: shorthand,\n key: [\"id\"],\n } as never;\n }\n\n return shorthand as never;\n}\n\nexport function defineTableShorthand<input, scope extends Scope = AbiTypeScope>(\n input: validateTableShorthand<input, scope>,\n scope: scope = AbiTypeScope as unknown as scope,\n): expandTableShorthand<input> {\n validateTableShorthand(input, scope);\n return expandTableShorthand(input, scope) as never;\n}\n","import { ErrorMessage, show } from \"@arktype/util\";\nimport { isObject, mergeIfUndefined } from \"./generics\";\nimport { TableShorthandInput, TablesInput } from \"./input\";\nimport { Scope, AbiTypeScope } from \"./scope\";\nimport { validateTable, resolveTable } from \"./table\";\nimport { expandTableShorthand, isTableShorthandInput, validateTableShorthand } from \"./tableShorthand\";\n\nexport type validateTables<tables, scope extends Scope = AbiTypeScope> = {\n [label in keyof tables]: tables[label] extends TableShorthandInput\n ? validateTableShorthand<tables[label], scope>\n : tables[label] extends object\n ? validateTable<tables[label], scope, { inStoreContext: true }>\n : ErrorMessage<`Expected tables config.`>;\n};\n\nexport function validateTables<scope extends Scope = AbiTypeScope>(\n input: unknown,\n scope: scope,\n): asserts input is TablesInput {\n if (isObject(input)) {\n for (const table of Object.values(input)) {\n if (isTableShorthandInput(table)) {\n validateTableShorthand(table, scope);\n } else {\n validateTable(table, scope, { inStoreContext: true });\n }\n }\n return;\n }\n throw new Error(`Expected tables config, received ${JSON.stringify(input)}`);\n}\n\nexport type resolveTables<tables, scope extends Scope = AbiTypeScope> = {\n readonly [label in keyof tables]: resolveTable<\n mergeIfUndefined<expandTableShorthand<tables[label]>, { readonly label: label }>,\n scope\n >;\n};\n\nexport function resolveTables<tables extends TablesInput, scope extends Scope = AbiTypeScope>(\n tables: tables,\n scope: scope,\n): resolveTables<tables, scope> {\n return Object.fromEntries(\n Object.entries(tables).map(([label, table]) => {\n return [label, resolveTable(mergeIfUndefined(expandTableShorthand(table, scope), { label }), scope)];\n }),\n ) as never;\n}\n\nexport function defineTables<input, scope extends Scope = AbiTypeScope>(\n input: validateTables<input, scope>,\n scope: scope = AbiTypeScope as never,\n): show<resolveTables<input, scope>> {\n validateTables(input, scope);\n return resolveTables(input, scope) as never;\n}\n","import { mapObject } from \"@latticexyz/common/utils\";\nimport { UserTypes } from \"./output\";\nimport { isSchemaAbiType } from \"@latticexyz/schema-type/internal\";\nimport { AbiTypeScope, extendScope } from \"./scope\";\nimport { hasOwnKey, isObject } from \"./generics\";\n\nexport type extractInternalType<userTypes extends UserTypes> = { [key in keyof userTypes]: userTypes[key][\"type\"] };\n\nexport function extractInternalType<userTypes extends UserTypes>(userTypes: userTypes): extractInternalType<userTypes> {\n return mapObject(userTypes, (userType) => userType.type);\n}\n\nexport function isUserTypes(userTypes: unknown): userTypes is UserTypes {\n return isObject(userTypes) && Object.values(userTypes).every((userType) => isSchemaAbiType(userType.type));\n}\n\nexport type scopeWithUserTypes<userTypes, scope extends AbiTypeScope = AbiTypeScope> = UserTypes extends userTypes\n ? scope\n : userTypes extends UserTypes\n ? extendScope<scope, extractInternalType<userTypes>>\n : scope;\n\nexport function scopeWithUserTypes<userTypes, scope extends AbiTypeScope = AbiTypeScope>(\n userTypes: userTypes,\n scope: scope = AbiTypeScope as scope,\n): scopeWithUserTypes<userTypes, scope> {\n return (isUserTypes(userTypes) ? extendScope(scope, extractInternalType(userTypes)) : scope) as never;\n}\n\nexport function validateUserTypes(userTypes: unknown): asserts userTypes is UserTypes {\n if (!isObject(userTypes)) {\n throw new Error(`Expected userTypes, received ${JSON.stringify(userTypes)}`);\n }\n\n for (const { type } of Object.values(userTypes)) {\n if (!hasOwnKey(AbiTypeScope.types, type)) {\n throw new Error(`\"${String(type)}\" is not a valid ABI type.`);\n }\n }\n}\n","import { flatMorph } from \"@arktype/util\";\nimport { EnumsInput } from \"./input\";\nimport { AbiTypeScope, extendScope } from \"./scope\";\nimport { parseNumber } from \"./generics\";\n\nfunction isEnums(enums: unknown): enums is EnumsInput {\n return (\n typeof enums === \"object\" &&\n enums != null &&\n Object.values(enums).every((item) => Array.isArray(item) && item.every((element) => typeof element === \"string\"))\n );\n}\n\nexport type scopeWithEnums<enums, scope extends AbiTypeScope = AbiTypeScope> = EnumsInput extends enums\n ? scope\n : enums extends EnumsInput\n ? extendScope<scope, { [key in keyof enums]: \"uint8\" }>\n : scope;\n\nexport function scopeWithEnums<enums, scope extends AbiTypeScope = AbiTypeScope>(\n enums: enums,\n scope: scope = AbiTypeScope as scope,\n): scopeWithEnums<enums, scope> {\n if (isEnums(enums)) {\n const enumScope = Object.fromEntries(Object.keys(enums).map((key) => [key, \"uint8\" as const]));\n return extendScope(scope, enumScope) as never;\n }\n return scope as never;\n}\n\nexport type resolveEnums<enums> = {\n readonly [key in keyof enums]: Readonly<enums[key]>;\n};\n\nexport function resolveEnums<enums extends EnumsInput>(enums: enums): resolveEnums<enums> {\n return enums;\n}\n\nexport type mapEnums<enums> = {\n readonly [key in keyof enums]: {\n readonly [element in keyof enums[key] as enums[key][element] & string]: parseNumber<element>;\n };\n};\n\nexport function mapEnums<enums extends EnumsInput>(enums: enums): resolveEnums<enums> {\n return flatMorph(enums as EnumsInput, (enumName, enumElements) => [\n enumName,\n flatMorph(enumElements, (enumIndex, enumElement) => [enumElement, enumIndex]),\n ]) as never;\n}\n","import { CODEGEN_DEFAULTS } from \"./defaults\";\nimport { isObject, mergeIfUndefined } from \"./generics\";\n\nexport type resolveCodegen<codegen> = codegen extends {}\n ? mergeIfUndefined<codegen, CODEGEN_DEFAULTS>\n : CODEGEN_DEFAULTS;\n\nexport function resolveCodegen<codegen>(codegen: codegen): resolveCodegen<codegen> {\n return (\n isObject(codegen) ? mergeIfUndefined(codegen, CODEGEN_DEFAULTS) : CODEGEN_DEFAULTS\n ) as resolveCodegen<codegen>;\n}\n","import { flatMorph, show } from \"@arktype/util\";\nimport { Tables } from \"./output\";\n\n/**\n * @internal Only kept for backwards compatibility\n */\nexport type resolveNamespacedTables<tables, namespace> = {\n readonly [label in keyof tables as namespace extends \"\"\n ? label\n : `${namespace & string}__${label & string}`]: tables[label];\n};\n\n/**\n * @internal Only kept for backwards compatibility\n */\nexport function resolveNamespacedTables<tables, namespace>(\n tables: tables,\n namespace: namespace,\n): show<resolveNamespacedTables<tables, namespace>> {\n return flatMorph(tables as Tables, (label, table) => [\n namespace === \"\" ? label : `${namespace}__${label}`,\n table,\n ]) as never;\n}\n","import { ErrorMessage, flatMorph } from \"@arktype/util\";\nimport { hasOwnKey, mergeIfUndefined } from \"./generics\";\nimport { NamespaceInput } from \"./input\";\nimport { resolveTables, validateTables } from \"./tables\";\nimport { AbiTypeScope, Scope } from \"./scope\";\nimport { expandTableShorthand } from \"./tableShorthand\";\n\nexport type validateNamespace<input, scope extends Scope = AbiTypeScope> = {\n [key in keyof input]: key extends \"tables\"\n ? validateTables<input[key], scope>\n : key extends keyof NamespaceInput\n ? NamespaceInput[key]\n : ErrorMessage<`\\`${key & string}\\` is not a valid namespace config option.`>;\n};\n\nexport function validateNamespace<scope extends Scope = AbiTypeScope>(\n input: unknown,\n scope: scope,\n): asserts input is NamespaceInput {\n if (hasOwnKey(input, \"namespace\") && typeof input.namespace === \"string\" && input.namespace.length > 14) {\n throw new Error(`\\`namespace\\` must fit into a \\`bytes14\\`, but \"${input.namespace}\" is too long.`);\n }\n if (hasOwnKey(input, \"tables\")) {\n validateTables(input.tables, scope);\n }\n}\n\nexport type resolveNamespace<input, scope extends Scope = AbiTypeScope> = input extends NamespaceInput\n ? {\n readonly label: input[\"label\"];\n readonly namespace: string;\n readonly tables: undefined extends input[\"tables\"]\n ? {}\n : resolveTables<\n {\n readonly [label in keyof input[\"tables\"]]: mergeIfUndefined<\n expandTableShorthand<input[\"tables\"][label]>,\n { readonly namespace: string }\n >;\n },\n scope\n >;\n }\n : never;\n\nexport function resolveNamespace<const input extends NamespaceInput, scope extends Scope = AbiTypeScope>(\n input: input,\n scope: scope = AbiTypeScope as never,\n): resolveNamespace<input, scope> {\n const label = input.label;\n const namespace = input.namespace ?? label.slice(0, 14);\n return {\n label,\n namespace,\n tables: resolveTables(\n flatMorph(input.tables ?? {}, (label, table) => {\n return [label, mergeIfUndefined(expandTableShorthand(table, scope), { namespace })];\n }),\n scope,\n ),\n } as never;\n}\n","import { ErrorMessage, show, flatMorph, narrow } from \"@arktype/util\";\nimport { get, hasOwnKey, mergeIfUndefined } from \"./generics\";\nimport { UserTypes } from \"./output\";\nimport { CONFIG_DEFAULTS } from \"./defaults\";\nimport { StoreInput, TableInput } from \"./input\";\nimport { resolveTables, validateTables } from \"./tables\";\nimport { scopeWithUserTypes, validateUserTypes } from \"./userTypes\";\nimport { mapEnums, resolveEnums, scopeWithEnums } from \"./enums\";\nimport { resolveCodegen } from \"./codegen\";\nimport { resolveNamespacedTables } from \"./namespacedTables\";\nimport { resolveTable } from \"./table\";\nimport { resolveNamespace } from \"./namespace\";\nimport { expandTableShorthand } from \"./tableShorthand\";\n\nexport type extendedScope<input> = scopeWithEnums<get<input, \"enums\">, scopeWithUserTypes<get<input, \"userTypes\">>>;\n\nexport function extendedScope<input>(input: input): extendedScope<input> {\n return scopeWithEnums(get(input, \"enums\"), scopeWithUserTypes(get(input, \"userTypes\")));\n}\n\nexport type validateStore<input> = {\n [key in keyof input]: key extends \"tables\"\n ? validateTables<input[key], extendedScope<input>>\n : key extends \"userTypes\"\n ? UserTypes\n : key extends \"enums\"\n ? narrow<input[key]>\n : key extends keyof StoreInput\n ? StoreInput[key]\n : ErrorMessage<`\\`${key & string}\\` is not a valid Store config option.`>;\n};\n\nexport function validateStore(input: unknown): asserts input is StoreInput {\n const scope = extendedScope(input);\n\n if (hasOwnKey(input, \"namespace\") && typeof input.namespace === \"string\" && input.namespace.length > 14) {\n throw new Error(`\\`namespace\\` must fit into a \\`bytes14\\`, but \"${input.namespace}\" is too long.`);\n }\n\n if (hasOwnKey(input, \"tables\")) {\n validateTables(input.tables, scope);\n }\n\n if (hasOwnKey(input, \"userTypes\")) {\n validateUserTypes(input.userTypes);\n }\n}\n\nexport type resolveStore<\n input,\n namespace = \"namespace\" extends keyof input\n ? input[\"namespace\"] extends string\n ? input[\"namespace\"]\n : CONFIG_DEFAULTS[\"namespace\"]\n : CONFIG_DEFAULTS[\"namespace\"],\n> = {\n readonly namespace: string;\n readonly sourceDirectory: \"sourceDirectory\" extends keyof input\n ? input[\"sourceDirectory\"]\n : CONFIG_DEFAULTS[\"sourceDirectory\"];\n readonly tables: \"tables\" extends keyof input\n ? resolveNamespacedTables<\n {\n readonly [label in keyof input[\"tables\"]]: resolveTable<\n mergeIfUndefined<expandTableShorthand<input[\"tables\"][label]>, { label: label; namespace: namespace }>,\n extendedScope<input>\n >;\n },\n namespace\n >\n : {};\n readonly userTypes: \"userTypes\" extends keyof input ? input[\"userTypes\"] : {};\n readonly enums: \"enums\" extends keyof input ? show<resolveEnums<input[\"enums\"]>> : {};\n readonly enumValues: \"enums\" extends keyof input ? show<mapEnums<input[\"enums\"]>> : {};\n readonly codegen: \"codegen\" extends keyof input ? resolveCodegen<input[\"codegen\"]> : resolveCodegen<{}>;\n readonly namespaces: {\n readonly [label in namespace & string]: resolveNamespace<\n {\n readonly label: label;\n readonly tables: \"tables\" extends keyof input ? input[\"tables\"] : undefined;\n },\n extendedScope<input>\n >;\n };\n};\n\nexport function resolveStore<const input extends StoreInput>(input: input): resolveStore<input> {\n const scope = extendedScope(input);\n const namespace = input.namespace ?? CONFIG_DEFAULTS[\"namespace\"];\n const codegen = resolveCodegen(input.codegen);\n\n const tablesInput = flatMorph(input.tables ?? {}, (label, shorthand) => {\n const table = expandTableShorthand(shorthand, scope) as TableInput;\n return [\n label,\n {\n ...table,\n label,\n namespace,\n codegen: {\n ...table.codegen,\n outputDirectory:\n table.codegen?.outputDirectory ??\n (codegen.namespaceDirectories && namespace !== \"\" ? `${namespace}/tables` : \"tables\"),\n },\n },\n ];\n });\n\n const namespaces = {\n [namespace]: resolveNamespace({ label: namespace, tables: tablesInput }, scope),\n };\n\n const tables = resolveTables(tablesInput, scope);\n\n return {\n namespace,\n tables: resolveNamespacedTables(tables, namespace),\n namespaces,\n sourceDirectory: input.sourceDirectory ?? CONFIG_DEFAULTS[\"sourceDirectory\"],\n userTypes: input.userTypes ?? {},\n enums: resolveEnums(input.enums ?? {}),\n enumValues: mapEnums(input.enums ?? {}),\n codegen,\n } as never;\n}\n\nexport function defineStore<const input>(input: validateStore<input>): show<resolveStore<input>> {\n validateStore(input);\n return resolveStore(input) as never;\n}\n"],"mappings":"AAEO,SAASA,EAAoCC,EAAcC,EAA2B,CAC3F,OAAQ,OAAOD,GAAU,UAAYA,GAAS,MAAQE,EAAUF,EAAOC,CAAG,EAAID,EAAMC,CAAG,EAAI,MAC7F,CAWO,SAASE,EAAoDH,EAAcI,EAAkC,CAClH,OAAOA,EAAK,OAAUD,EAAQJ,EAAIC,EAAOI,EAAK,CAAC,CAAC,EAAGA,EAAK,MAAM,CAAC,CAAC,EAAeJ,CACjF,CAEO,SAASE,EACdG,EACAJ,EACwE,CAExE,OAAO,OAAOI,GAAW,UAAYA,IAAW,MAAQA,EAAO,eAAeJ,CAAG,CACnF,CAEO,SAASK,EAAgBN,EAAuC,CACrE,OAAOA,GAAS,MAAQ,OAAOA,GAAU,QAC3C,CAcO,SAASO,EACdC,EACAC,EACkC,CAClC,IAAMC,EAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAI,EAAG,GAAG,OAAO,KAAKC,CAAQ,CAAC,CAAC,CAAC,EAC1E,OAAO,OAAO,YACZC,EAAK,IAAKT,GAAQ,CAChBA,EACA,OAAOO,EAAKP,CAAiB,EAAM,IAAcQ,EAASR,CAAqB,EAAIO,EAAKP,CAAiB,CAC3G,CAAC,CACH,CACF,CCpDO,IAAMU,EAAmB,CAC9B,gBAAiB,wBACjB,kBAAmB,aACnB,gBAAiB,UAEjB,qBAAsB,GACtB,cAAe,WACjB,EAIaC,EAAyB,CACpC,gBAAiB,SACjB,gBAAiB,GACjB,cAAe,EACjB,EAIaC,EAAwB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AAK,EAE/C,MAAO,CACL,UAAAK,EACA,OAAQc,EAAwBF,EAAQZ,CAAS,EACjD,WAAAU,EACA,gBAAiBpB,EAAM,iBAAmBW,EAAgB,gBAC1D,UAAWX,EAAM,WAAa,CAAC,EAC/B,MAAoBA,EAAM,OAAS,CAAC,EACpC,WAAYyB,EAASzB,EAAM,OAAS,CAAC,CAAC,EACtC,QAAAY,CACF,CACF,CAEO,SAASc,GAAyB1B,EAAwD,CAC/F,OAAAI,GAAcJ,CAAK,EACZS,GAAaT,CAAK,CAC3B","names":["get","input","key","hasOwnKey","getPath","path","object","isObject","mergeIfUndefined","base","defaults","keys","CODEGEN_DEFAULTS","TABLE_CODEGEN_DEFAULTS","TABLE_DEPLOY_DEFAULTS","TABLE_DEFAULTS","CONFIG_DEFAULTS","schemaAbiTypes","Scope","AbiTypeScope","abiType","extendScope","scope","additionalTypes","fixedArrayToArray","isFixedArrayAbiType","validateSchema","schema","scope","AbiTypeScope","isObject","internalType","hasOwnKey","resolveSchema","key","defineSchema","isSchemaInput","input","fieldType","isStaticAbiType","resourceToHex","getValidKeys","schema","scope","AbiTypeScope","internalType","hasOwnKey","isStaticAbiType","key","isValidPrimaryKey","validateTable","input","options","validateSchema","item","get","resolveTableCodegen","TABLE_CODEGEN_DEFAULTS","resolveTable","label","type","TABLE_DEFAULTS","namespace","name","tableId","resolveSchema","mergeIfUndefined","TABLE_DEPLOY_DEFAULTS","defineTable","isFixedArrayAbiType","isStaticAbiType","NoStaticKeyFieldError","isTableShorthandInput","shorthand","isObject","value","validateTableShorthand","scope","AbiTypeScope","isFixedArrayAbiType","hasOwnKey","isSchemaInput","isStaticAbiType","expandTableShorthand","defineTableShorthand","input","validateTables","input","scope","isObject","table","isTableShorthandInput","validateTableShorthand","validateTable","resolveTables","tables","label","resolveTable","mergeIfUndefined","expandTableShorthand","defineTables","AbiTypeScope","mapObject","isSchemaAbiType","extractInternalType","userTypes","mapObject","userType","isUserTypes","isObject","isSchemaAbiType","scopeWithUserTypes","scope","AbiTypeScope","extendScope","validateUserTypes","type","hasOwnKey","flatMorph","isEnums","enums","item","element","scopeWithEnums","scope","AbiTypeScope","enumScope","key","extendScope","resolveEnums","mapEnums","flatMorph","enumName","enumElements","enumIndex","enumElement","resolveCodegen","codegen","isObject","mergeIfUndefined","CODEGEN_DEFAULTS","flatMorph","resolveNamespacedTables","tables","namespace","label","table","flatMorph","validateNamespace","input","scope","hasOwnKey","validateTables","resolveNamespace","AbiTypeScope","label","namespace","resolveTables","flatMorph","table","mergeIfUndefined","expandTableShorthand","flatMorph","extendedScope","input","scopeWithEnums","get","scopeWithUserTypes","validateStore","scope","hasOwnKey","validateTables","validateUserTypes","resolveStore","namespace","CONFIG_DEFAULTS","codegen","resolveCodegen","tablesInput","flatMorph","label","shorthand","table","expandTableShorthand","namespaces","resolveNamespace","tables","resolveTables","resolveNamespacedTables","mapEnums","defineStore"]}
package/dist/codegen.js CHANGED
@@ -213,7 +213,7 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
213
213
  ${t}(
214
214
  SliceLib.getSubslice(_blob, _start, _end).toBytes()
215
215
  )
216
- )`}import{renderArguments as b,renderCommonData as $e,renderList as C,renderImports as ge,renderTableId as Te,renderTypeHelpers as be,renderWithStore as _e,renderedSolidityHeader as Le,renderImportPath as T}from"@latticexyz/common/codegen";var O={TOTAL_LENGTH:240,NUM_STATIC_FIELDS:232,NUM_DYNAMIC_FIELDS:224};function J(e){return`FieldLayout constant _fieldLayout = FieldLayout.wrap(${fe(e)});`}function fe(e){let t=e.filter(({isDynamic:i})=>!i),n=e.length-t.length,r=0n,s=0;if(e.length>28)throw new Error("FieldLayout: too many fields");if(n>5)throw new Error("FieldLayout: too many dynamic fields");for(let i=0;i<t.length;i++){let{isDynamic:d,staticByteLength:y}=e[i];if(d)throw new Error("FieldLayout: static type after dynamic type");s+=y,r|=BigInt(y)<<BigInt((31-4-i)*8)}return r|=BigInt(s)<<BigInt(O.TOTAL_LENGTH),r|=BigInt(t.length)<<BigInt(O.NUM_STATIC_FIELDS),r|=BigInt(n)<<BigInt(O.NUM_DYNAMIC_FIELDS),`0x${r.toString(16).padStart(64,"0")}`}import{keySchemaToHex as Se,valueSchemaToHex as De}from"@latticexyz/protocol-parser/internal";function Q(e){let{imports:t,libraryName:n,structName:r,staticResourceData:s,storeImportPath:a,fields:i,staticFields:d,dynamicFields:y,withRecordMethods:o,storeArgument:c,keyTuple:p}=e,{_typedTableId:l,_typedKeyArgs:h,_keyTupleDefinition:f}=$e(e);return`
216
+ )`}import{renderArguments as b,renderCommonData as $e,renderList as P,renderImports as ge,renderTableId as Te,renderTypeHelpers as be,renderWithStore as _e,renderedSolidityHeader as Le,renderImportPath as T}from"@latticexyz/common/codegen";var O={TOTAL_LENGTH:240,NUM_STATIC_FIELDS:232,NUM_DYNAMIC_FIELDS:224};function J(e){return`FieldLayout constant _fieldLayout = FieldLayout.wrap(${fe(e)});`}function fe(e){let t=e.filter(({isDynamic:i})=>!i),n=e.length-t.length,r=0n,s=0;if(e.length>28)throw new Error("FieldLayout: too many fields");if(n>5)throw new Error("FieldLayout: too many dynamic fields");for(let i=0;i<t.length;i++){let{isDynamic:d,staticByteLength:y}=e[i];if(d)throw new Error("FieldLayout: static type after dynamic type");s+=y,r|=BigInt(y)<<BigInt((31-4-i)*8)}return r|=BigInt(s)<<BigInt(O.TOTAL_LENGTH),r|=BigInt(t.length)<<BigInt(O.NUM_STATIC_FIELDS),r|=BigInt(n)<<BigInt(O.NUM_DYNAMIC_FIELDS),`0x${r.toString(16).padStart(64,"0")}`}import{keySchemaToHex as Se,valueSchemaToHex as De}from"@latticexyz/protocol-parser/internal";function Q(e){let{imports:t,libraryName:n,structName:r,staticResourceData:s,storeImportPath:a,fields:i,staticFields:d,dynamicFields:y,withRecordMethods:o,storeArgument:c,keyTuple:p}=e,{_typedTableId:l,_typedKeyArgs:h,_keyTupleDefinition:f}=$e(e);return`
217
217
  ${Le}
218
218
 
219
219
  // Import store internals
@@ -236,7 +236,7 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
236
236
 
237
237
  ${r?`
238
238
  struct ${r} {
239
- ${C(i,({name:m,typeId:u})=>`${u} ${m};`)}
239
+ ${P(i,({name:m,typeId:u})=>`${u} ${m};`)}
240
240
  }
241
241
  `:""}
242
242
 
@@ -256,7 +256,7 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
256
256
  */
257
257
  function getKeyNames() internal pure returns (string[] memory keyNames) {
258
258
  keyNames = new string[](${p.length});
259
- ${C(p,(m,u)=>`keyNames[${u}] = "${m.name}";`)}
259
+ ${P(p,(m,u)=>`keyNames[${u}] = "${m.name}";`)}
260
260
  }
261
261
 
262
262
  /**
@@ -265,7 +265,7 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
265
265
  */
266
266
  function getFieldNames() internal pure returns (string[] memory fieldNames) {
267
267
  fieldNames = new string[](${i.length});
268
- ${C(i,(m,u)=>`fieldNames[${u}] = "${m.name}";`)}
268
+ ${P(i,(m,u)=>`fieldNames[${u}] = "${m.name}";`)}
269
269
  }
270
270
 
271
271
  ${_e(c,({_typedStore:m,_store:u,_commentSuffix:L,_methodNamePrefix:A})=>`
@@ -340,11 +340,11 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
340
340
  function encodeDynamic(${b(e.map(({name:t,typeWithLocation:n})=>`${n} ${t}`))}) internal pure returns (bytes memory) {
341
341
  return abi.encodePacked(${b(e.map(t=>E(t)))});
342
342
  }
343
- `}import{renderEnums as Ee}from"@latticexyz/common/codegen";function _t(e){return Ee(e.enums)}import Ue from"node:fs/promises";import B from"node:path";import{formatAndWriteSolidity as G,renderEnums as je}from"@latticexyz/common/codegen";import{renderList as Fe,renderedSolidityHeader as Re}from"@latticexyz/common/codegen";import ee from"node:path/posix";function te(e,t){return`
344
- ${Re}
343
+ `}import{renderEnums as Ee}from"@latticexyz/common/codegen";function Lt(e){return Ee(e.enums)}import je from"node:fs/promises";import B from"node:path";import{formatAndWriteSolidity as G,renderEnums as Ge}from"@latticexyz/common/codegen";import{renderImportPath as Fe,renderList as Re,renderedSolidityHeader as ke}from"@latticexyz/common/codegen";import ee from"node:path";function te(e,t){return`
344
+ ${ke}
345
345
 
346
- ${Fe(t,({outputPath:n,tableName:r,renderOptions:{structName:s}})=>{let a=[r];return s&&a.push(s),`import { ${a.join(", ")} } from "./${ee.relative(ee.dirname(e),n)}";`})}
347
- `}import{uniqueBy as Ge}from"@latticexyz/common/utils";import ke from"node:path";function v({config:e}){return ke.join(e.sourceDirectory,e.codegen.outputDirectory,e.codegen.userTypesFilename)}import{groupBy as we}from"@latticexyz/common/utils";function ne({config:e}){let t=Object.keys(e.enums).map(a=>({type:"enum",name:a,abiType:"uint8",importPath:"./"+v({config:e})})),n=Object.entries(e.userTypes).map(([a,i])=>({type:"userType",name:a,abiType:i.type,importPath:i.filePath})),r=[...t,...n],s=Array.from(we(r,a=>a.name).entries()).filter(([,a])=>a.length>1).map(([a])=>a);if(s.length>0)throw new Error(`Found enums and user types sharing the same name: ${s.join(", ")}`);return r}import I from"path";import{SchemaTypeArrayToElement as Ne}from"@latticexyz/schema-type/deprecated";import{AbiTypeToSchemaType as F,getStaticByteLength as P,SchemaType as R,SchemaTypeToAbiType as Oe}from"@latticexyz/schema-type/deprecated";function ve(e){let t=e.match(/^(\w+)\[(\d+)\]$/);return t?{elementType:t[1],staticLength:Number.parseInt(t[2])}:null}function U(e,t){if(e in F){let s=F[e];return{schemaType:s,renderType:j(s)}}let n=ve(e);if(n){if(n.elementType in F)return Me(e,n.elementType,n.staticLength);throw new Error("Static arrays of user types are not supported")}let r=t.find(s=>s.name===e);if(!r)throw new Error(`User type "${e}" not found`);return Be(r)}function j(e){let t=P(e),n=t===0,r=Oe[e];return{typeId:r,typeWithLocation:n?r+" memory":r,enumName:R[e],staticByteLength:t,isDynamic:n,typeWrap:"",typeUnwrap:"",internalTypeId:r}}function Be(e){switch(e.type){case"enum":{let t=R.UINT8,n=P(t),r=n===0;return{schemaType:t,renderType:{typeId:e.name,typeWithLocation:e.name,enumName:R[t],staticByteLength:n,isDynamic:r,typeWrap:e.name,typeUnwrap:e.abiType,internalTypeId:e.abiType}}}case"userType":{let t=F[e.abiType];return{schemaType:t,renderType:{typeId:e.name,typeWithLocation:e.name,enumName:R[t],staticByteLength:P(t),isDynamic:!1,typeWrap:`${e.name}.wrap`,typeUnwrap:`${e.name}.unwrap`,internalTypeId:e.abiType}}}}}function Me(e,t,n){let r=t+"[]",s=F[r];return{schemaType:s,renderType:{typeId:e,typeWithLocation:`${e} memory`,enumName:R[s],staticByteLength:0,isDynamic:!0,typeWrap:`toStaticArray_${t}_${n}`,typeUnwrap:`fromStaticArray_${t}_${n}`,typeWrappingData:{kind:"staticArray",elementType:t,staticLength:n},internalTypeId:r}}}import{getKeySchema as We,getValueSchema as Ce}from"@latticexyz/protocol-parser/internal";import{isDefined as Pe}from"@latticexyz/common/utils";function re({tables:e,rootDir:t,codegenDir:n,userTypes:r,storeImportPath:s}){return e.map(i=>{let d=I.join(t,n,i.codegen.outputDirectory,`${i.label}.sol`),y=We(i),o=Ce(i),c=i.codegen.dataStruct,p=c||i.type==="offchainTable"||Object.keys(o).length>1,l=!p&&Object.keys(o).length===1,h=Object.values(i.schema).map($=>r.find(x=>x.name===$.internalType)).filter(Pe).map($=>({symbol:$.name.replace(/\..*$/,""),path:$.importPath.startsWith(".")?"./"+I.relative(I.dirname(d),I.join(t,$.importPath)):$.importPath})),f=Object.entries(y).map(([$,x])=>{let{renderType:M}=U(x.internalType,r);return{...M,name:$,isDynamic:!1}}),m=Object.entries(o).map(([$,x])=>{let{renderType:M,schemaType:de}=U(x.internalType,r),H=Ne[de];return{...M,arrayElement:H!==void 0?j(H):void 0,name:$}}),u=m.filter(({isDynamic:$})=>!$),L=m.filter(({isDynamic:$})=>$),A=i.codegen.tableIdArgument?void 0:{namespace:i.namespace,name:i.name,offchainOnly:i.type==="offchainTable"};return{outputPath:d,tableName:i.label,renderOptions:{imports:h,libraryName:i.label,structName:c?i.label+"Data":void 0,staticResourceData:A,storeImportPath:s.startsWith(".")?"./"+I.relative(I.dirname(d),I.join(t,s)):s,keyTuple:f,fields:m,staticFields:u,dynamicFields:L,withGetters:i.type==="table",withRecordMethods:p,withDynamicFieldMethods:i.type==="table",withSuffixlessFieldMethods:l,storeArgument:i.codegen.storeArgument}}})}async function Xt({rootDir:e,config:t}){let n=ne({config:t});if(Object.keys(t.enums).length>0){let r=B.join(e,v({config:t})),s=je(t.enums);await G(s,r,"Generated types file with enums")}await Promise.all(Object.values(t.namespaces).map(async r=>{let a=t.sourceDirectory,i=B.join(a,t.codegen.outputDirectory),d=Object.values(r.tables);if(d.length===0)return;let y=re({tables:d,rootDir:e,codegenDir:i,userTypes:n,storeImportPath:t.codegen.storeImportPath}),o=Ge(y.map(({outputPath:l})=>B.dirname(l)),l=>l);await Promise.all(o.map(l=>Ue.rm(l,{recursive:!0,force:!0}))),await Promise.all(y.map(async({outputPath:l,renderOptions:h})=>{let f=Q(h);return await G(f,l,"Generated table")}));let c=B.join(e,i,t.codegen.indexFilename),p=te(c,y);await G(p,c,"Generated table index")}))}import{renderedSolidityHeader as He}from"@latticexyz/common/codegen";import{staticAbiTypeToByteLength as Ke,staticAbiTypes as qe}from"@latticexyz/schema-type/internal";import{getLeftPaddingBits as oe}from"@latticexyz/common/codegen";function ie(e){return`
346
+ ${Re(t,({outputPath:n,tableName:r,renderOptions:{structName:s}})=>{let a=[r];return s&&a.push(s),`import { ${a.join(", ")} } from "${Fe("./"+ee.relative(ee.dirname(e),n))}";`})}
347
+ `}import{uniqueBy as He}from"@latticexyz/common/utils";import we from"node:path";function v({config:e}){return we.join(e.sourceDirectory,e.codegen.outputDirectory,e.codegen.userTypesFilename)}import{groupBy as Oe}from"@latticexyz/common/utils";function ne({config:e}){let t=Object.keys(e.enums).map(a=>({type:"enum",name:a,abiType:"uint8",importPath:"./"+v({config:e})})),n=Object.entries(e.userTypes).map(([a,i])=>({type:"userType",name:a,abiType:i.type,importPath:i.filePath})),r=[...t,...n],s=Array.from(Oe(r,a=>a.name).entries()).filter(([,a])=>a.length>1).map(([a])=>a);if(s.length>0)throw new Error(`Found enums and user types sharing the same name: ${s.join(", ")}`);return r}import I from"path";import{SchemaTypeArrayToElement as We}from"@latticexyz/schema-type/deprecated";import{AbiTypeToSchemaType as F,getStaticByteLength as C,SchemaType as R,SchemaTypeToAbiType as ve}from"@latticexyz/schema-type/deprecated";function Be(e){let t=e.match(/^(\w+)\[(\d+)\]$/);return t?{elementType:t[1],staticLength:Number.parseInt(t[2])}:null}function U(e,t){if(e in F){let s=F[e];return{schemaType:s,renderType:j(s)}}let n=Be(e);if(n){if(n.elementType in F)return Ne(e,n.elementType,n.staticLength);throw new Error("Static arrays of user types are not supported")}let r=t.find(s=>s.name===e);if(!r)throw new Error(`User type "${e}" not found`);return Me(r)}function j(e){let t=C(e),n=t===0,r=ve[e];return{typeId:r,typeWithLocation:n?r+" memory":r,enumName:R[e],staticByteLength:t,isDynamic:n,typeWrap:"",typeUnwrap:"",internalTypeId:r}}function Me(e){switch(e.type){case"enum":{let t=R.UINT8,n=C(t),r=n===0;return{schemaType:t,renderType:{typeId:e.name,typeWithLocation:e.name,enumName:R[t],staticByteLength:n,isDynamic:r,typeWrap:e.name,typeUnwrap:e.abiType,internalTypeId:e.abiType}}}case"userType":{let t=F[e.abiType];return{schemaType:t,renderType:{typeId:e.name,typeWithLocation:e.name,enumName:R[t],staticByteLength:C(t),isDynamic:!1,typeWrap:`${e.name}.wrap`,typeUnwrap:`${e.name}.unwrap`,internalTypeId:e.abiType}}}}}function Ne(e,t,n){let r=t+"[]",s=F[r];return{schemaType:s,renderType:{typeId:e,typeWithLocation:`${e} memory`,enumName:R[s],staticByteLength:0,isDynamic:!0,typeWrap:`toStaticArray_${t}_${n}`,typeUnwrap:`fromStaticArray_${t}_${n}`,typeWrappingData:{kind:"staticArray",elementType:t,staticLength:n},internalTypeId:r}}}import{getKeySchema as Pe,getValueSchema as Ce}from"@latticexyz/protocol-parser/internal";import{isDefined as Ue}from"@latticexyz/common/utils";function re({tables:e,rootDir:t,codegenDir:n,userTypes:r,storeImportPath:s}){return e.map(i=>{let d=I.join(t,n,i.codegen.outputDirectory,`${i.label}.sol`),y=Pe(i),o=Ce(i),c=i.codegen.dataStruct,p=c||i.type==="offchainTable"||Object.keys(o).length>1,l=!p&&Object.keys(o).length===1,h=Object.values(i.schema).map($=>r.find(x=>x.name===$.internalType)).filter(Ue).map($=>({symbol:$.name.replace(/\..*$/,""),path:$.importPath.startsWith(".")?"./"+I.relative(I.dirname(d),I.join(t,$.importPath)):$.importPath})),f=Object.entries(y).map(([$,x])=>{let{renderType:M}=U(x.internalType,r);return{...M,name:$,isDynamic:!1}}),m=Object.entries(o).map(([$,x])=>{let{renderType:M,schemaType:de}=U(x.internalType,r),H=We[de];return{...M,arrayElement:H!==void 0?j(H):void 0,name:$}}),u=m.filter(({isDynamic:$})=>!$),L=m.filter(({isDynamic:$})=>$),A=i.codegen.tableIdArgument?void 0:{namespace:i.namespace,name:i.name,offchainOnly:i.type==="offchainTable"};return{outputPath:d,tableName:i.label,renderOptions:{imports:h,libraryName:i.label,structName:c?i.label+"Data":void 0,staticResourceData:A,storeImportPath:s.startsWith(".")?"./"+I.relative(I.dirname(d),I.join(t,s)):s,keyTuple:f,fields:m,staticFields:u,dynamicFields:L,withGetters:i.type==="table",withRecordMethods:p,withDynamicFieldMethods:i.type==="table",withSuffixlessFieldMethods:l,storeArgument:i.codegen.storeArgument}}})}async function Vt({rootDir:e,config:t}){let n=ne({config:t});if(Object.keys(t.enums).length>0){let r=B.join(e,v({config:t})),s=Ge(t.enums);await G(s,r,"Generated types file with enums")}await Promise.all(Object.values(t.namespaces).map(async r=>{let a=t.sourceDirectory,i=B.join(a,t.codegen.outputDirectory),d=Object.values(r.tables);if(d.length===0)return;let y=re({tables:d,rootDir:e,codegenDir:i,userTypes:n,storeImportPath:t.codegen.storeImportPath}),o=He(y.map(({outputPath:l})=>B.dirname(l)),l=>l);await Promise.all(o.map(l=>je.rm(l,{recursive:!0,force:!0}))),await Promise.all(y.map(async({outputPath:l,renderOptions:h})=>{let f=Q(h);return await G(f,l,"Generated table")}));let c=B.join(e,i,t.codegen.indexFilename),p=te(c,y);await G(p,c,"Generated table index")}))}import{renderedSolidityHeader as Ke}from"@latticexyz/common/codegen";import{staticAbiTypeToByteLength as qe,staticAbiTypes as Ye}from"@latticexyz/schema-type/internal";import{getLeftPaddingBits as oe}from"@latticexyz/common/codegen";function ie(e){return`
348
348
  /**
349
349
  * @notice Decodes a slice into an array of ${e.internalTypeId}.
350
350
  * @dev Uses TightCoder for initial decoding, and then assembly for memory conversion.
@@ -383,8 +383,8 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
383
383
  ${oe(e)}
384
384
  );
385
385
  }
386
- `}function nn(){return`
387
- ${He}
386
+ `}function rn(){return`
387
+ ${Ke}
388
388
  import { TightCoder } from "./TightCoder.sol";
389
389
  import { Slice } from "../Slice.sol";
390
390
 
@@ -395,11 +395,11 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
395
395
  * @dev This library provides functions for decoding slices into arrays of basic uint types.
396
396
  */
397
397
  library DecodeSlice {
398
- ${qe.map(e=>ie({internalTypeId:e,staticByteLength:Ke[e]})).join(`
398
+ ${Ye.map(e=>ie({internalTypeId:e,staticByteLength:qe[e]})).join(`
399
399
  `)}
400
400
  }
401
- `}import{renderedSolidityHeader as Ye}from"@latticexyz/common/codegen";import{staticAbiTypeToByteLength as Xe,staticAbiTypes as Ve}from"@latticexyz/schema-type/internal";function sn(){return`
402
- ${Ye}
401
+ `}import{renderedSolidityHeader as Xe}from"@latticexyz/common/codegen";import{staticAbiTypeToByteLength as Ve,staticAbiTypes as Ze}from"@latticexyz/schema-type/internal";function cn(){return`
402
+ ${Xe}
403
403
  import { TightCoder } from "./TightCoder.sol";
404
404
 
405
405
  /**
@@ -408,10 +408,10 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
408
408
  * @dev This library provides utilities for encoding arrays into tightly packed bytes representations.
409
409
  */
410
410
  library EncodeArray {
411
- ${Ve.map(e=>ae({internalTypeId:e,staticByteLength:Xe[e]})).join(`
411
+ ${Ze.map(e=>ae({internalTypeId:e,staticByteLength:Ve[e]})).join(`
412
412
  `)}
413
413
  }
414
- `}import{renderedSolidityHeader as Ze}from"@latticexyz/common/codegen";import{staticAbiTypes as ze}from"@latticexyz/schema-type/internal";function Je({typeId:e}){return`
414
+ `}import{renderedSolidityHeader as ze}from"@latticexyz/common/codegen";import{staticAbiTypes as Je}from"@latticexyz/schema-type/internal";function Qe({typeId:e}){return`
415
415
  function testEncodeDecodeArray_${e}(
416
416
  ${e} val0,
417
417
  ${e} val1,
@@ -431,15 +431,15 @@ import{renderArguments as S,renderCommonData as se,renderWithFieldSuffix as _,re
431
431
  assertEq(decoded[1], val1);
432
432
  assertEq(decoded[2], val2);
433
433
  }
434
- `}function yn(){return`
435
- ${Ze}
434
+ `}function pn(){return`
435
+ ${ze}
436
436
 
437
437
  import { Test } from "forge-std/Test.sol";
438
438
  import { EncodeArray } from "../../src/tightcoder/EncodeArray.sol";
439
439
  import { SliceLib } from "../../src/Slice.sol";
440
440
 
441
441
  contract TightCoderAutoTest is Test {
442
- ${ze.map(e=>Je({typeId:e})).join("")}
442
+ ${Je.map(e=>Qe({typeId:e})).join("")}
443
443
  }
444
- `}export{j as getSchemaTypeInfo,re as getTableOptions,Be as getUserTypeInfo,nn as renderDecodeSlice,q as renderDecodeValueType,z as renderDeleteRecordMethods,sn as renderEncodeArray,E as renderEncodeFieldSingle,K as renderFieldMethods,w as renderRecordData,Z as renderRecordMethods,Q as renderTable,yn as renderTightCoderAutoTest,Je as renderTightCoderAutoTestFunction,ie as renderTightCoderDecode,ae as renderTightCoderEncode,_t as renderTypesFromConfig,U as resolveAbiOrUserType,Xt as tablegen};
444
+ `}export{j as getSchemaTypeInfo,re as getTableOptions,Me as getUserTypeInfo,rn as renderDecodeSlice,q as renderDecodeValueType,z as renderDeleteRecordMethods,cn as renderEncodeArray,E as renderEncodeFieldSingle,K as renderFieldMethods,w as renderRecordData,Z as renderRecordMethods,Q as renderTable,pn as renderTightCoderAutoTest,Qe as renderTightCoderAutoTestFunction,ie as renderTightCoderDecode,ae as renderTightCoderEncode,Lt as renderTypesFromConfig,U as resolveAbiOrUserType,Vt as tablegen};
445
445
  //# sourceMappingURL=codegen.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../ts/codegen/field.ts","../ts/codegen/record.ts","../ts/codegen/renderTable.ts","../ts/constants.ts","../ts/codegen/renderFieldLayout.ts","../ts/codegen/renderTypesFromConfig.ts","../ts/codegen/tablegen.ts","../ts/codegen/renderTableIndex.ts","../ts/codegen/getUserTypesFilename.ts","../ts/codegen/getUserTypes.ts","../ts/codegen/getTableOptions.ts","../ts/codegen/userType.ts","../ts/codegen/tightcoder/renderDecodeSlice.ts","../ts/codegen/tightcoder/renderFunctions.ts","../ts/codegen/tightcoder/renderEncodeArray.ts","../ts/codegen/tightcoder/renderTightCoderAutoTest.ts"],"sourcesContent":["import {\n renderArguments,\n renderCommonData,\n RenderField,\n RenderType,\n renderWithFieldSuffix,\n renderWithStore,\n} from \"@latticexyz/common/codegen\";\nimport { RenderTableOptions } from \"./types\";\n\n/**\n * Returns Solidity code for all the field-specific table methods (get, set, push, pop, etc.)\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nexport function renderFieldMethods(options: RenderTableOptions): string {\n const storeArgument = options.storeArgument;\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n let result = \"\";\n for (const [schemaIndex, field] of options.fields.entries()) {\n if (!options.withDynamicFieldMethods && field.isDynamic) {\n continue;\n }\n\n // For dynamic fields, compute the field index relative to the end of the static fields\n const _typedFieldName = `${field.typeWithLocation} ${field.name}`;\n\n if (options.withGetters) {\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}get${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal view returns (${_typedFieldName}) {\n ${_keyTupleDefinition}\n ${\n field.isDynamic\n ? `bytes memory _blob = ${_store}.getDynamicField(\n _tableId,\n _keyTuple,\n ${schemaIndex - options.staticFields.length}\n );`\n : `bytes32 _blob = ${_store}.getStaticField(\n _tableId,\n _keyTuple,\n ${schemaIndex},\n _fieldLayout\n );`\n }\n return ${renderDecodeFieldSingle(field)};\n }\n `,\n ),\n );\n }\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(storeArgument, ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => {\n const externalArguments = renderArguments([_typedStore, _typedTableId, _typedKeyArgs, _typedFieldName]);\n const setFieldMethod = field.isDynamic ? \"setDynamicField\" : \"setStaticField\";\n const encodeFieldSingle = renderEncodeFieldSingle(field);\n const internalArguments = field.isDynamic\n ? `_tableId, _keyTuple, ${schemaIndex - options.staticFields.length}, ${encodeFieldSingle}`\n : `_tableId, _keyTuple, ${schemaIndex}, ${encodeFieldSingle}, _fieldLayout`;\n\n return `\n /**\n * @notice Set ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}set${_methodNameSuffix}(${externalArguments}) internal {\n ${_keyTupleDefinition}\n ${_store}.${setFieldMethod}(${internalArguments});\n }\n `;\n }),\n );\n\n if (field.isDynamic) {\n const portionData = fieldPortionData(field);\n const dynamicSchemaIndex = schemaIndex - options.staticFields.length;\n const { typeWrappingData } = field;\n\n if (options.withGetters) {\n if (typeWrappingData && typeWrappingData.kind === \"staticArray\") {\n result += renderWithFieldSuffix(\n options.withSuffixlessFieldMethods,\n field.name,\n (_methodNameSuffix) =>\n `\n // The length of ${field.name}\n uint256 constant length${_methodNameSuffix} = ${typeWrappingData.staticLength};\n `,\n );\n } else {\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get the length of ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}length${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal view returns (uint256) {\n ${_keyTupleDefinition}\n uint256 _byteLength = ${_store}.getDynamicFieldLength(_tableId, _keyTuple, ${dynamicSchemaIndex});\n unchecked {\n return _byteLength / ${portionData.elementLength};\n }\n }\n `,\n ),\n );\n }\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get an item of ${field.name}${_commentSuffix}.\n * @dev Reverts with Store_IndexOutOfBounds if \\`_index\\` is out of bounds for the array.\n */\n function ${_methodNamePrefix}getItem${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n \"uint256 _index\",\n ])}) internal view returns (${portionData.typeWithLocation}) {\n ${_keyTupleDefinition}\n\n ${\n // If the index is within the static length,\n // but ahead of the dynamic length, return zero\n typeWrappingData && typeWrappingData.kind === \"staticArray\" && field.arrayElement\n ? `\n uint256 _byteLength = ${_store}.getDynamicFieldLength(_tableId, _keyTuple, ${dynamicSchemaIndex});\n uint256 dynamicLength = _byteLength / ${portionData.elementLength};\n uint256 staticLength = ${typeWrappingData.staticLength};\n\n if (_index < staticLength && _index >= dynamicLength) {\n return ${renderCastStaticBytesToType(field.arrayElement, `bytes${field.arrayElement.staticByteLength}(new bytes(0))`)};\n }`\n : ``\n }\n\n unchecked {\n bytes memory _blob = ${_store}.getDynamicFieldSlice(\n _tableId,\n _keyTuple,\n ${dynamicSchemaIndex},\n _index * ${portionData.elementLength},\n (_index + 1) * ${portionData.elementLength}\n );\n return ${portionData.decoded};\n }\n }\n `,\n ),\n );\n }\n\n if (!typeWrappingData || typeWrappingData.kind !== \"staticArray\") {\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Push ${portionData.title} to ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}push${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n `${portionData.typeWithLocation} ${portionData.name}`,\n ])}) internal {\n ${_keyTupleDefinition}\n ${_store}.pushToDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.encoded});\n }\n `,\n ),\n );\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Pop ${portionData.title} from ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}pop${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal {\n ${_keyTupleDefinition}\n ${_store}.popFromDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.elementLength});\n }\n `,\n ),\n );\n }\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(storeArgument, ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => {\n const externalArguments = renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n \"uint256 _index\",\n `${portionData.typeWithLocation} ${portionData.name}`,\n ]);\n\n const internalArguments = `\n _tableId,\n _keyTuple,\n ${dynamicSchemaIndex},\n uint40(_index * ${portionData.elementLength}),\n uint40(_encoded.length),\n _encoded \n `;\n\n return `\n /**\n * @notice Update ${portionData.title} of ${field.name}${_commentSuffix} at \\`_index\\`.\n */\n function ${_methodNamePrefix}update${_methodNameSuffix}(${externalArguments}) internal {\n ${_keyTupleDefinition}\n unchecked {\n bytes memory _encoded = ${portionData.encoded};\n ${_store}.spliceDynamicData(${internalArguments});\n }\n }\n `;\n }),\n );\n }\n }\n return result;\n}\n\n/**\n * Returns Solidity code for how to encode a particular field into bytes before storing onchain\n * @param field RenderField\n * @returns string of Solidity code\n */\nexport function renderEncodeFieldSingle(field: RenderField) {\n let func;\n if (field.arrayElement) {\n func = \"EncodeArray.encode\";\n } else if (field.isDynamic) {\n func = \"bytes\";\n } else {\n func = \"abi.encodePacked\";\n }\n return `${func}(${field.typeUnwrap}(${field.name}))`;\n}\n\n/**\n * Returns Solidity code for decoding a bytes value into its Solidity primitive type\n * @param field description of field type\n * @param offset byte-length offset of value in encoded bytes\n * @returns string of Solidity code\n */\nexport function renderDecodeValueType(field: RenderType, offset: number) {\n const { staticByteLength } = field;\n\n const innerSlice = `Bytes.getBytes${staticByteLength}(_blob, ${offset})`;\n\n return renderCastStaticBytesToType(field, innerSlice);\n}\n\n/**\n * Returns Solidity code for how to cast a bytesN value to a particular type, which is assumed to have the same byte length\n * @param field description of resulting field type\n * @param staticBytes bytesN value\n * @returns string of Solidity code\n */\nfunction renderCastStaticBytesToType(field: RenderType, staticBytes: string) {\n const { staticByteLength, internalTypeId } = field;\n const bits = staticByteLength * 8;\n\n let result;\n if (internalTypeId.match(/^uint\\d{1,3}$/) || internalTypeId === \"address\") {\n result = `${internalTypeId}(${staticBytes})`;\n } else if (internalTypeId.match(/^int\\d{1,3}$/)) {\n result = `${internalTypeId}(uint${bits}(${staticBytes}))`;\n } else if (internalTypeId.match(/^bytes\\d{1,2}$/)) {\n result = staticBytes;\n } else if (internalTypeId === \"bool\") {\n result = `_toBool(uint8(${staticBytes}))`;\n } else {\n throw new Error(`Unknown value type id ${internalTypeId}`);\n }\n return `${field.typeWrap}(${result})`;\n}\n\ninterface FieldPortionData {\n /** Fully-qualified name of the user-defined type (may include a library name as prefix), followed by location (none/memory/storage) */\n typeWithLocation: string;\n /** Name of the field portion variable */\n name: string;\n /** Solidity code which encodes the field portion variable into bytes (for storing onchain) */\n encoded: string;\n /** Solidity code which decodes `_blob` variable into the field portion variable's type */\n decoded: string;\n /** Description of the field portion kind (\"an element\" or \"a slice\") */\n title: string;\n /** Byte length of array elements for arrays, 1 otherwise */\n elementLength: number;\n}\n\n/**\n * Returns data to describe either an array element, or a bytes slice, depending on the provided field type\n */\nfunction fieldPortionData(field: RenderField): FieldPortionData {\n if (field.arrayElement) {\n const name = \"_element\";\n const elementFieldData = { ...field.arrayElement, arrayElement: undefined, name };\n return {\n typeWithLocation: field.arrayElement.typeWithLocation,\n name,\n encoded: renderEncodeFieldSingle(elementFieldData),\n decoded: renderDecodeFieldSingle(elementFieldData),\n title: \"an element\",\n elementLength: field.arrayElement.staticByteLength,\n };\n } else {\n const name = \"_slice\";\n const elementFieldData = { ...field, name };\n return {\n typeWithLocation: `${field.typeId} memory`,\n name,\n encoded: renderEncodeFieldSingle(elementFieldData),\n decoded: renderDecodeFieldSingle(elementFieldData),\n title: \"a slice\",\n elementLength: 1,\n };\n }\n}\n\n/**\n * Returns Solidity code for how to decode `_blob` variable into the particular field type\n * @param field RenderField\n * @returns string of Solidity code\n */\nfunction renderDecodeFieldSingle(field: RenderField) {\n const { isDynamic, arrayElement } = field;\n if (arrayElement) {\n // arrays\n return `${field.typeWrap}(\n SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_${arrayElement.internalTypeId}()\n )`;\n } else if (isDynamic) {\n // bytes/string\n return `${field.typeWrap}(${field.internalTypeId}(_blob))`;\n } else {\n return renderCastStaticBytesToType(field, `bytes${field.staticByteLength}(_blob)`);\n }\n}\n","import {\n RenderDynamicField,\n renderArguments,\n renderCommonData,\n renderList,\n renderWithStore,\n} from \"@latticexyz/common/codegen\";\nimport { renderDecodeValueType } from \"./field\";\nimport { RenderTableOptions } from \"./types\";\n\n/**\n * Returns Solidity code for whole-record methods (get, set)\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nexport function renderRecordMethods(options: RenderTableOptions) {\n const { structName, storeArgument } = options;\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n let result = \"\";\n\n if (options.withGetters) {\n result += renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get the full data${_commentSuffix}.\n */\n function ${_methodNamePrefix}get(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal view returns (${renderDecodedRecord(options)}) {\n ${_keyTupleDefinition}\n \n (\n bytes memory _staticData,\n EncodedLengths _encodedLengths,\n bytes memory _dynamicData\n ) = ${_store}.getRecord(_tableId, _keyTuple, _fieldLayout);\n return decode(_staticData, _encodedLengths, _dynamicData);\n }\n `,\n );\n }\n\n result += renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {\n const externalArguments = renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n renderArguments(options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)),\n ]);\n\n const internalArguments =\n \"_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData\" +\n (_useExplicitFieldLayout ? \", _fieldLayout\" : \"\");\n\n return `\n /** \n * @notice Set the full data using individual values${_commentSuffix}.\n */\n function ${_methodNamePrefix}set(${externalArguments}) internal {\n ${renderRecordData(options)}\n\n ${_keyTupleDefinition}\n\n ${_store}.setRecord(${internalArguments});\n }\n `;\n },\n );\n\n if (structName !== undefined) {\n result += renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {\n const externalArguments = renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n `${structName} memory _table`,\n ]);\n\n const internalArguments =\n \"_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData\" +\n (_useExplicitFieldLayout ? \", _fieldLayout\" : \"\");\n\n return `\n /**\n * @notice Set the full data using the data struct${_commentSuffix}.\n */\n function ${_methodNamePrefix}set(${externalArguments}) internal {\n ${renderRecordData(options, \"_table.\")}\n\n ${_keyTupleDefinition}\n\n ${_store}.setRecord(${internalArguments});\n }\n `;\n },\n );\n }\n\n result += renderDecodeFunctions(options);\n\n return result;\n}\n\n/**\n * Returns Solidity code to prepare variables needed to store encoded record on chain\n * @param options RenderTableOptions\n * @param namePrefix optional field name prefix to change how the field is accessed\n * @returns string of Solidity code\n */\nexport function renderRecordData(options: RenderTableOptions, namePrefix = \"\") {\n let result = \"\";\n if (options.staticFields.length > 0) {\n result += `\n bytes memory _staticData = encodeStatic(\n ${renderArguments(options.staticFields.map(({ name }) => `${namePrefix}${name}`))}\n );\n `;\n } else {\n result += `bytes memory _staticData;`;\n }\n\n if (options.dynamicFields.length > 0) {\n result += `\n EncodedLengths _encodedLengths = encodeLengths(\n ${renderArguments(options.dynamicFields.map(({ name }) => `${namePrefix}${name}`))}\n );\n bytes memory _dynamicData = encodeDynamic(\n ${renderArguments(options.dynamicFields.map(({ name }) => `${namePrefix}${name}`))}\n );\n `;\n } else {\n result += `\n EncodedLengths _encodedLengths;\n bytes memory _dynamicData;\n `;\n }\n\n return result;\n}\n\n/**\n * Returns Solidity code for the delete record method\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nexport function renderDeleteRecordMethods(options: RenderTableOptions) {\n const { storeArgument } = options;\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n return renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {\n const externalArguments = renderArguments([_typedStore, _typedTableId, _typedKeyArgs]);\n const internalArguments = \"_tableId, _keyTuple\" + (_useExplicitFieldLayout ? \", _fieldLayout\" : \"\");\n\n return `\n /** \n * @notice Delete all data for given keys${_commentSuffix}.\n */\n function ${_methodNamePrefix}deleteRecord(${externalArguments}) internal {\n ${_keyTupleDefinition}\n ${_store}.deleteRecord(${internalArguments});\n }\n `;\n },\n );\n}\n\n/**\n * Returns Solidity code for the `decode` function that parses a bytes blob into the typed table data\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nfunction renderDecodeFunctions({ structName, fields, staticFields, dynamicFields }: RenderTableOptions) {\n // either set struct properties, or just variables\n const renderedDecodedRecord = structName\n ? `${structName} memory _table`\n : renderArguments(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n const fieldNamePrefix = structName ? \"_table.\" : \"\";\n\n // Static field offsets\n const staticOffsets = staticFields.map(() => 0);\n let _acc = 0;\n for (const [index, field] of staticFields.entries()) {\n staticOffsets[index] = _acc;\n _acc += field.staticByteLength;\n }\n\n let result = \"\";\n\n if (staticFields.length > 0) {\n result += `\n /**\n * @notice Decode the tightly packed blob of static data using this table's field layout.\n */\n function decodeStatic(bytes memory _blob) internal pure returns (${renderArguments(\n staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) {\n ${renderList(\n staticFields,\n (field, index) => `\n ${field.name} = ${renderDecodeValueType(field, staticOffsets[index])};\n `,\n )}\n }\n `;\n }\n\n if (dynamicFields.length > 0) {\n result += `\n /**\n * @notice Decode the tightly packed blob of dynamic data using the encoded lengths.\n */\n function decodeDynamic(EncodedLengths _encodedLengths, bytes memory _blob) internal pure returns (${renderArguments(\n dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) {\n ${renderList(\n dynamicFields,\n // unchecked is only dangerous if _encodedLengths (and _blob) is invalid,\n // but it's assumed to be valid, and this function is meant to be mostly used internally\n (field, index) => {\n if (index === 0) {\n return `\n uint256 _start;\n uint256 _end;\n unchecked {\n _end = _encodedLengths.atIndex(${index});\n }\n ${field.name} = ${renderDecodeDynamicFieldPartial(field)};\n `;\n } else {\n return `\n _start = _end;\n unchecked {\n _end += _encodedLengths.atIndex(${index});\n }\n ${field.name} = ${renderDecodeDynamicFieldPartial(field)};\n `;\n }\n },\n )}\n }\n `;\n }\n\n result += `\n /**\n * @notice Decode the tightly packed blobs using this table's field layout.\n * ${staticFields.length > 0 ? \"@param _staticData Tightly packed static fields.\" : \"\"}\n * ${dynamicFields.length > 0 ? \"@param _encodedLengths Encoded lengths of dynamic fields.\" : \"\"}\n * ${dynamicFields.length > 0 ? \"@param _dynamicData Tightly packed dynamic fields.\" : \"\"}\n */\n function decode(\n bytes memory ${staticFields.length > 0 ? \"_staticData\" : \"\"},\n EncodedLengths ${dynamicFields.length > 0 ? \"_encodedLengths\" : \"\"},\n bytes memory ${dynamicFields.length > 0 ? \"_dynamicData\" : \"\"}\n ) internal pure returns (${renderedDecodedRecord}) {\n `;\n\n if (staticFields.length > 0) {\n result += `\n (${renderArguments(staticFields.map((field) => `${fieldNamePrefix}${field.name}`))}) = decodeStatic(_staticData);\n `;\n }\n if (dynamicFields.length > 0) {\n result += `\n (${renderArguments(\n dynamicFields.map((field) => `${fieldNamePrefix}${field.name}`),\n )}) = decodeDynamic(_encodedLengths, _dynamicData);\n `;\n }\n\n result += `\n }\n `;\n\n return result;\n}\n\n/**\n * Returns Solidity code for the return value of a record getter\n * @param options RenderDynamicField\n * @returns string of Solidity code\n */\nfunction renderDecodedRecord({ structName, fields }: RenderTableOptions) {\n if (structName) {\n return `${structName} memory _table`;\n } else {\n return renderArguments(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n }\n}\n\n/**\n * Returns Solidity code for decoding onchain bytes into typed field data\n * @param options RenderDynamicField\n * @returns string of Solidity code\n */\nfunction renderDecodeDynamicFieldPartial(field: RenderDynamicField) {\n const { typeId, arrayElement, typeWrap } = field;\n if (arrayElement) {\n // arrays\n return `${typeWrap}(\n SliceLib.getSubslice(_blob, _start, _end).decodeArray_${arrayElement.typeId}()\n )`;\n } else {\n // bytes/string\n return `${typeWrap}(\n ${typeId}(\n SliceLib.getSubslice(_blob, _start, _end).toBytes()\n )\n )`;\n }\n}\n","import {\n RenderDynamicField,\n renderArguments,\n renderCommonData,\n renderList,\n renderImports,\n renderTableId,\n renderTypeHelpers,\n renderWithStore,\n renderedSolidityHeader,\n RenderStaticField,\n renderImportPath,\n} from \"@latticexyz/common/codegen\";\nimport { renderEncodeFieldSingle, renderFieldMethods } from \"./field\";\nimport { renderDeleteRecordMethods, renderRecordData, renderRecordMethods } from \"./record\";\nimport { renderFieldLayout } from \"./renderFieldLayout\";\nimport { RenderTableOptions } from \"./types\";\nimport { KeySchema, ValueSchema, keySchemaToHex, valueSchemaToHex } from \"@latticexyz/protocol-parser/internal\";\n\n/**\n * Renders Solidity code for a MUD table library, using the specified options\n * @param options options for rendering the table\n * @returns string of Solidity code\n */\nexport function renderTable(options: RenderTableOptions) {\n const {\n imports,\n libraryName,\n structName,\n staticResourceData,\n storeImportPath,\n fields,\n staticFields,\n dynamicFields,\n withRecordMethods,\n storeArgument,\n keyTuple,\n } = options;\n\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n return `\n ${renderedSolidityHeader}\n\n // Import store internals\n import { IStore } from \"${renderImportPath(storeImportPath, \"IStore.sol\")}\";\n import { StoreSwitch } from \"${renderImportPath(storeImportPath, \"StoreSwitch.sol\")}\";\n import { StoreCore } from \"${renderImportPath(storeImportPath, \"StoreCore.sol\")}\";\n import { Bytes } from \"${renderImportPath(storeImportPath, \"Bytes.sol\")}\";\n import { Memory } from \"${renderImportPath(storeImportPath, \"Memory.sol\")}\";\n import { SliceLib } from \"${renderImportPath(storeImportPath, \"Slice.sol\")}\";\n import { EncodeArray } from \"${renderImportPath(storeImportPath, \"tightcoder/EncodeArray.sol\")}\";\n import { FieldLayout } from \"${renderImportPath(storeImportPath, \"FieldLayout.sol\")}\";\n import { Schema } from \"${renderImportPath(storeImportPath, \"Schema.sol\")}\";\n import { EncodedLengths, EncodedLengthsLib } from \"${renderImportPath(storeImportPath, \"EncodedLengths.sol\")}\";\n import { ResourceId } from \"${renderImportPath(storeImportPath, \"ResourceId.sol\")}\";\n\n ${\n imports.length > 0\n ? `\n // Import user types\n ${renderImports(imports)}\n `\n : \"\"\n }\n\n ${\n !structName\n ? \"\"\n : `\n struct ${structName} {\n ${renderList(fields, ({ name, typeId }) => `${typeId} ${name};`)}\n }\n `\n }\n\n library ${libraryName} {\n ${staticResourceData ? renderTableId(staticResourceData) : \"\"}\n \n ${renderFieldLayout(fields)}\n\n // Hex-encoded key schema of (${keyTuple.map((field) => field.internalTypeId).join(\", \")})\n Schema constant _keySchema = Schema.wrap(${keySchemaToHex(\n Object.fromEntries(keyTuple.map((field) => [field.name, field.internalTypeId])) as KeySchema,\n )});\n // Hex-encoded value schema of (${fields.map((field) => field.internalTypeId).join(\", \")})\n Schema constant _valueSchema = Schema.wrap(${valueSchemaToHex(\n Object.fromEntries(fields.map((field) => [field.name, field.internalTypeId])) as ValueSchema,\n )});\n\n /**\n * @notice Get the table's key field names.\n * @return keyNames An array of strings with the names of key fields.\n */\n function getKeyNames() internal pure returns (string[] memory keyNames) {\n keyNames = new string[](${keyTuple.length});\n ${renderList(keyTuple, (keyElement, index) => `keyNames[${index}] = \"${keyElement.name}\";`)}\n }\n\n /**\n * @notice Get the table's value field names.\n * @return fieldNames An array of strings with the names of value fields.\n */\n function getFieldNames() internal pure returns (string[] memory fieldNames) {\n fieldNames = new string[](${fields.length});\n ${renderList(fields, (field, index) => `fieldNames[${index}] = \"${field.name}\";`)}\n }\n\n ${renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Register the table with its config${_commentSuffix}.\n */\n function ${_methodNamePrefix}register(${renderArguments([_typedStore, _typedTableId])}) internal {\n ${_store}.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames());\n }\n `,\n )}\n\n ${renderFieldMethods(options)}\n\n ${withRecordMethods ? renderRecordMethods(options) : \"\"}\n\n ${renderDeleteRecordMethods(options)}\n\n ${renderEncodeStatic(staticFields)}\n\n ${renderEncodeLengths(dynamicFields)}\n\n ${renderEncodeDynamic(dynamicFields)}\n\n /**\n * @notice Encode all of a record's fields.\n * @return The static (fixed length) data, encoded into a sequence of bytes.\n * @return The lengths of the dynamic fields (packed into a single bytes32 value).\n * @return The dynamic (variable length) data, encoded into a sequence of bytes.\n */\n function encode(${renderArguments(\n options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (bytes memory, EncodedLengths, bytes memory) {\n ${renderRecordData(options)}\n\n return (_staticData, _encodedLengths, _dynamicData);\n }\n \n /**\n * @notice Encode keys as a bytes32 array using this table's field layout.\n */\n function encodeKeyTuple(${renderArguments([_typedKeyArgs])}) internal pure returns (bytes32[] memory) {\n ${_keyTupleDefinition}\n return _keyTuple;\n }\n }\n\n ${renderTypeHelpers(options)}\n `;\n}\n\n/**\n * Renders solidity code for `encodeStatic` method, which encodes the provided fields into a blob for storage\n * (nothing is rendered if static fields array is empty)\n * @param staticFields array of data about static fields to be encoded\n * @returns string of Solidity code\n */\nfunction renderEncodeStatic(staticFields: RenderStaticField[]) {\n if (staticFields.length === 0) return \"\";\n\n return `\n /**\n * @notice Tightly pack static (fixed length) data using this table's schema.\n * @return The static data, encoded into a sequence of bytes.\n */\n function encodeStatic(${renderArguments(\n staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (bytes memory) {\n return abi.encodePacked(${renderArguments(staticFields.map(({ name }) => name))});\n }\n `;\n}\n\n/**\n * Renders solidity code for `encodeLengths` method, which tightly packs the lengths of the provided fields\n * (nothing is rendered if dynamic fields array is empty)\n * @param dynamicFields array of data about dynamic fields to have their lengths encoded\n * @returns string of Solidity code\n */\nfunction renderEncodeLengths(dynamicFields: RenderDynamicField[]) {\n if (dynamicFields.length === 0) return \"\";\n\n return `\n /**\n * @notice Tightly pack dynamic data lengths using this table's schema.\n * @return _encodedLengths The lengths of the dynamic fields (packed into a single bytes32 value).\n */\n function encodeLengths(${renderArguments(\n dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (EncodedLengths _encodedLengths) {\n // Lengths are effectively checked during copy by 2**40 bytes exceeding gas limits\n unchecked {\n _encodedLengths = EncodedLengthsLib.pack(\n ${renderArguments(\n dynamicFields.map(({ name, arrayElement }) => {\n if (arrayElement) {\n return `${name}.length * ${arrayElement.staticByteLength}`;\n } else {\n return `bytes(${name}).length`;\n }\n }),\n )}\n );\n }\n }\n `;\n}\n\n/**\n * Renders solidity code for `encodeDynamic` method, which encodes the provided fields into a blob for storage\n * (nothing is rendered if dynamic fields array is empty)\n * @param dynamicFields array of data about dynamic fields to be encoded\n * @returns string of Solidity code\n */\nfunction renderEncodeDynamic(dynamicFields: RenderDynamicField[]) {\n if (dynamicFields.length === 0) return \"\";\n\n return `\n /**\n * @notice Tightly pack dynamic (variable length) data using this table's schema.\n * @return The dynamic data, encoded into a sequence of bytes.\n */\n function encodeDynamic(${renderArguments(\n dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (bytes memory) {\n return abi.encodePacked(${renderArguments(dynamicFields.map((field) => renderEncodeFieldSingle(field)))});\n }\n `;\n}\n","/* Shared constants */\n// Make sure these stay aligned with @latticexyz/store/src/constants.sol\n\n// Total byte length of an EVM word\nexport const WORD_SIZE = 32;\n// Index of the last byte in an EVM word\nexport const WORD_LAST_INDEX = 31;\n// Conversion for bit shifting\nexport const BYTE_TO_BITS = 8;\n\n// Schema's capacity\nexport const MAX_TOTAL_FIELDS = 28;\n// FieldLayout's capacity\nexport const MAX_STATIC_FIELDS = 28;\n// EncodedLengths's capacity\nexport const MAX_DYNAMIC_FIELDS = 5;\n\n// FieldLayout and Schema have the same offsets for metadata\nexport const LayoutOffsets = {\n TOTAL_LENGTH: (WORD_SIZE - 2) * BYTE_TO_BITS,\n NUM_STATIC_FIELDS: (WORD_SIZE - 2 - 1) * BYTE_TO_BITS,\n NUM_DYNAMIC_FIELDS: (WORD_SIZE - 2 - 1 - 1) * BYTE_TO_BITS,\n};\n","import { RenderType } from \"@latticexyz/common/codegen\";\nimport { BYTE_TO_BITS, LayoutOffsets, MAX_DYNAMIC_FIELDS, MAX_TOTAL_FIELDS, WORD_LAST_INDEX } from \"../constants\";\n\ntype FieldLayoutRenderType = Pick<RenderType, \"isDynamic\" | \"staticByteLength\">;\n\n/**\n * Renders Solidity code that defines and initializes `_fieldLayout` constant\n * @param fields array of field data necessary to construct FieldLayout\n * @returns string of Solidity code\n */\nexport function renderFieldLayout(fields: FieldLayoutRenderType[]): string {\n return `FieldLayout constant _fieldLayout = FieldLayout.wrap(${encodeFieldLayout(fields)});`;\n}\n\n// Make sure this logic stays aligned with @latticexyz/store/src/FieldLayout.sol\n/**\n * Returns Solidity hexadecimal which represents the encoded FieldLayout\n * @param fields array of field data necessary to construct FieldLayout\n * @returns string of Solidity code\n */\nfunction encodeFieldLayout(fields: FieldLayoutRenderType[]): string {\n const staticFields = fields.filter(({ isDynamic }) => !isDynamic);\n const numDynamicFields = fields.length - staticFields.length;\n\n let fieldLayout = 0n;\n let totalLength = 0;\n const totalFields = fields.length;\n\n if (totalFields > MAX_TOTAL_FIELDS) throw new Error(\"FieldLayout: too many fields\");\n if (numDynamicFields > MAX_DYNAMIC_FIELDS) throw new Error(\"FieldLayout: too many dynamic fields\");\n\n for (let i = 0; i < staticFields.length; i++) {\n const { isDynamic, staticByteLength } = fields[i];\n if (isDynamic) throw new Error(`FieldLayout: static type after dynamic type`);\n\n totalLength += staticByteLength;\n fieldLayout |= BigInt(staticByteLength) << BigInt((WORD_LAST_INDEX - 4 - i) * BYTE_TO_BITS);\n }\n\n fieldLayout |= BigInt(totalLength) << BigInt(LayoutOffsets.TOTAL_LENGTH);\n fieldLayout |= BigInt(staticFields.length) << BigInt(LayoutOffsets.NUM_STATIC_FIELDS);\n fieldLayout |= BigInt(numDynamicFields) << BigInt(LayoutOffsets.NUM_DYNAMIC_FIELDS);\n\n return `0x${fieldLayout.toString(16).padStart(64, \"0\")}`;\n}\n","import { renderEnums } from \"@latticexyz/common/codegen\";\nimport { Store } from \"../config/v2\";\n\n/**\n * Renders Solidity code for enums defined in the provided config\n */\nexport function renderTypesFromConfig(config: Store) {\n return renderEnums(config.enums);\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { formatAndWriteSolidity, renderEnums } from \"@latticexyz/common/codegen\";\nimport { renderTable } from \"./renderTable\";\nimport { renderTableIndex } from \"./renderTableIndex\";\nimport { Store as StoreConfig } from \"../config/v2/output\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\nimport { getUserTypes } from \"./getUserTypes\";\nimport { getUserTypesFilename } from \"./getUserTypesFilename\";\nimport { getTableOptions } from \"./getTableOptions\";\n\nexport type TablegenOptions = {\n /**\n * MUD project root directory where all other relative paths are resolved from.\n */\n rootDir: string;\n config: StoreConfig;\n};\n\nexport async function tablegen({ rootDir, config }: TablegenOptions) {\n const userTypes = getUserTypes({ config });\n\n // Write enums to user types file\n if (Object.keys(config.enums).length > 0) {\n const userTypesFilename = path.join(rootDir, getUserTypesFilename({ config }));\n const source = renderEnums(config.enums);\n await formatAndWriteSolidity(source, userTypesFilename, \"Generated types file with enums\");\n }\n\n await Promise.all(\n Object.values(config.namespaces).map(async (namespace) => {\n // TODO: get this value from config once multiple namespaces are supported\n const multipleNamespaces = false;\n const sourceDir = multipleNamespaces\n ? path.join(config.sourceDirectory, \"namespaces\", namespace.label)\n : config.sourceDirectory;\n const codegenDir = path.join(sourceDir, config.codegen.outputDirectory);\n\n const tables = Object.values(namespace.tables);\n if (tables.length === 0) return;\n\n const tableOptions = getTableOptions({\n tables,\n rootDir,\n codegenDir,\n userTypes,\n storeImportPath: config.codegen.storeImportPath,\n });\n\n const tableDirs = uniqueBy(\n tableOptions.map(({ outputPath }) => path.dirname(outputPath)),\n (dir) => dir,\n );\n await Promise.all(tableDirs.map((dir) => fs.rm(dir, { recursive: true, force: true })));\n\n await Promise.all(\n tableOptions.map(async ({ outputPath, renderOptions }) => {\n const source = renderTable(renderOptions);\n return await formatAndWriteSolidity(source, outputPath, \"Generated table\");\n }),\n );\n\n const codegenIndexPath = path.join(rootDir, codegenDir, config.codegen.indexFilename);\n const source = renderTableIndex(codegenIndexPath, tableOptions);\n await formatAndWriteSolidity(source, codegenIndexPath, \"Generated table index\");\n }),\n );\n}\n","import { renderList, renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { TableOptions } from \"./getTableOptions\";\nimport path from \"node:path/posix\";\n\n/**\n * Returns Solidity code for table index file that imports all codegen tables\n * @param options table definitions\n * @returns string of Solidity code\n */\nexport function renderTableIndex(codegenIndexPath: string, options: TableOptions[]) {\n return `\n ${renderedSolidityHeader}\n\n ${renderList(options, ({ outputPath, tableName, renderOptions: { structName } }) => {\n const imports = [tableName];\n if (structName) imports.push(structName);\n\n return `import { ${imports.join(\", \")} } from \"./${path.relative(path.dirname(codegenIndexPath), outputPath)}\";`;\n })}\n `;\n}\n","import path from \"node:path\";\nimport { Store } from \"../config/v2\";\n\n/**\n * @returns File path for codegen'ed user types, relative to source dir\n */\nexport function getUserTypesFilename({ config }: { config: Store }): string {\n return path.join(config.sourceDirectory, config.codegen.outputDirectory, config.codegen.userTypesFilename);\n}\n","import { Store } from \"../config/v2\";\nimport { AbiType } from \"@latticexyz/config\";\nimport { getUserTypesFilename } from \"./getUserTypesFilename\";\nimport { groupBy } from \"@latticexyz/common/utils\";\n\nexport type UserType = {\n readonly type: \"enum\" | \"userType\";\n readonly name: string;\n readonly abiType: AbiType;\n /**\n * Import path relative to the root dir or absolute path if importing from a package.\n * Relative paths must start with a `.` to be treated as a relative path.\n */\n readonly importPath: string;\n};\n\nexport function getUserTypes({ config }: { readonly config: Store }): readonly UserType[] {\n const enums = Object.keys(config.enums).map(\n (name): UserType => ({\n type: \"enum\",\n name,\n abiType: \"uint8\",\n importPath: \"./\" + getUserTypesFilename({ config }),\n }),\n );\n\n const userTypes = Object.entries(config.userTypes).map(\n ([name, userType]): UserType => ({\n type: \"userType\",\n name,\n abiType: userType.type,\n // If `userType.filePath` starts with a `.`, it's relative to the root dir\n importPath: userType.filePath,\n }),\n );\n\n const result = [...enums, ...userTypes];\n\n // TODO: move this to config validation step?\n const duplicates = Array.from(groupBy(result, (userType) => userType.name).entries())\n .filter(([, entries]) => entries.length > 1)\n .map(([name]) => name);\n if (duplicates.length > 0) {\n throw new Error(`Found enums and user types sharing the same name: ${duplicates.join(\", \")}`);\n }\n\n return result;\n}\n","import path from \"path\";\nimport { SchemaTypeArrayToElement } from \"@latticexyz/schema-type/deprecated\";\nimport {\n ImportDatum,\n RenderDynamicField,\n RenderField,\n RenderKeyTuple,\n RenderStaticField,\n} from \"@latticexyz/common/codegen\";\nimport { RenderTableOptions } from \"./types\";\nimport { getSchemaTypeInfo, resolveAbiOrUserType } from \"./userType\";\nimport { Table } from \"../config/v2/output\";\nimport { getKeySchema, getValueSchema } from \"@latticexyz/protocol-parser/internal\";\nimport { UserType } from \"./getUserTypes\";\nimport { isDefined } from \"@latticexyz/common/utils\";\n\nexport interface TableOptions {\n /** Path where the file is expected to be written (relative to project root) */\n outputPath: string;\n /** Name of the table, as used in filename and library name */\n tableName: string;\n /** Options for `renderTable` function */\n renderOptions: RenderTableOptions;\n}\n\n/**\n * Transforms store config and available solidity user types into useful options for `tablegen` and `renderTable`\n */\nexport function getTableOptions({\n tables,\n rootDir,\n codegenDir,\n userTypes,\n storeImportPath,\n}: {\n readonly tables: Table[];\n readonly rootDir: string;\n /** namespace codegen output dir, relative to project root dir */\n readonly codegenDir: string;\n readonly userTypes: readonly UserType[];\n /** absolute import path or, if starting with `.`, relative to project root dir */\n readonly storeImportPath: string;\n}): TableOptions[] {\n const options = tables.map((table): TableOptions => {\n const outputPath = path.join(rootDir, codegenDir, table.codegen.outputDirectory, `${table.label}.sol`);\n\n const keySchema = getKeySchema(table);\n const valueSchema = getValueSchema(table);\n\n // struct adds methods to get/set all values at once\n const withStruct = table.codegen.dataStruct;\n // operate on all fields at once; always render for offchain tables; for only 1 field keep them if struct is also kept\n const withRecordMethods = withStruct || table.type === \"offchainTable\" || Object.keys(valueSchema).length > 1;\n // field methods can include simply get/set if there's only 1 field and no record methods\n const withSuffixlessFieldMethods = !withRecordMethods && Object.keys(valueSchema).length === 1;\n // list of any symbols that need to be imported\n const imports = Object.values(table.schema)\n .map((field) => userTypes.find((type) => type.name === field.internalType))\n .filter(isDefined)\n .map((userType): ImportDatum => {\n return {\n // If it's a fully qualified name, remove trailing references\n // This enables support for user types inside libraries\n symbol: userType.name.replace(/\\..*$/, \"\"),\n path: userType.importPath.startsWith(\".\")\n ? \"./\" + path.relative(path.dirname(outputPath), path.join(rootDir, userType.importPath))\n : userType.importPath,\n };\n });\n\n const keyTuple = Object.entries(keySchema).map(([name, field]): RenderKeyTuple => {\n const { renderType } = resolveAbiOrUserType(field.internalType, userTypes);\n\n return {\n ...renderType,\n name,\n isDynamic: false,\n };\n });\n\n const fields = Object.entries(valueSchema).map(([name, field]): RenderField => {\n const { renderType, schemaType } = resolveAbiOrUserType(field.internalType, userTypes);\n\n const elementType = SchemaTypeArrayToElement[schemaType];\n return {\n ...renderType,\n arrayElement: elementType !== undefined ? getSchemaTypeInfo(elementType) : undefined,\n name,\n };\n });\n\n const staticFields = fields.filter(({ isDynamic }) => !isDynamic) as RenderStaticField[];\n const dynamicFields = fields.filter(({ isDynamic }) => isDynamic) as RenderDynamicField[];\n\n // With tableIdArgument: tableId is a dynamic argument for each method\n // Without tableIdArgument: tableId is a file-level constant generated from `staticResourceData`\n const staticResourceData = table.codegen.tableIdArgument\n ? undefined\n : {\n namespace: table.namespace,\n name: table.name,\n offchainOnly: table.type === \"offchainTable\",\n };\n\n return {\n outputPath,\n tableName: table.label,\n renderOptions: {\n imports,\n libraryName: table.label,\n structName: withStruct ? table.label + \"Data\" : undefined,\n staticResourceData,\n storeImportPath: storeImportPath.startsWith(\".\")\n ? \"./\" + path.relative(path.dirname(outputPath), path.join(rootDir, storeImportPath))\n : storeImportPath,\n keyTuple,\n fields,\n staticFields,\n dynamicFields,\n withGetters: table.type === \"table\",\n withRecordMethods,\n withDynamicFieldMethods: table.type === \"table\",\n withSuffixlessFieldMethods,\n storeArgument: table.codegen.storeArgument,\n },\n };\n });\n\n return options;\n}\n","import {\n AbiTypeToSchemaType,\n getStaticByteLength,\n SchemaType,\n SchemaTypeToAbiType,\n} from \"@latticexyz/schema-type/deprecated\";\nimport { RenderType } from \"@latticexyz/common/codegen\";\nimport { UserType } from \"./getUserTypes\";\n\nfunction parseStaticArray(abiType: string) {\n const matches = abiType.match(/^(\\w+)\\[(\\d+)\\]$/);\n if (!matches) return null;\n return {\n elementType: matches[1],\n staticLength: Number.parseInt(matches[2]),\n };\n}\n\n/**\n * Resolve an abi or user type into a SchemaType and RenderType\n */\nexport function resolveAbiOrUserType(\n abiOrUserType: string,\n userTypes: readonly UserType[],\n): {\n schemaType: SchemaType;\n renderType: RenderType;\n} {\n // abi types which directly mirror a SchemaType\n if (abiOrUserType in AbiTypeToSchemaType) {\n const schemaType = AbiTypeToSchemaType[abiOrUserType];\n return {\n schemaType,\n renderType: getSchemaTypeInfo(schemaType),\n };\n }\n // static arrays\n const staticArray = parseStaticArray(abiOrUserType);\n if (staticArray) {\n if (staticArray.elementType in AbiTypeToSchemaType) {\n return getStaticArrayTypeInfo(abiOrUserType, staticArray.elementType, staticArray.staticLength);\n } else {\n throw new Error(\"Static arrays of user types are not supported\");\n }\n }\n\n // user types\n const userType = userTypes.find((type) => type.name === abiOrUserType);\n if (!userType) {\n throw new Error(`User type \"${abiOrUserType}\" not found`);\n }\n return getUserTypeInfo(userType);\n}\n\nexport function getSchemaTypeInfo(schemaType: SchemaType): RenderType {\n const staticByteLength = getStaticByteLength(schemaType);\n const isDynamic = staticByteLength === 0;\n const typeId = SchemaTypeToAbiType[schemaType];\n return {\n typeId,\n typeWithLocation: isDynamic ? typeId + \" memory\" : typeId,\n enumName: SchemaType[schemaType],\n staticByteLength,\n isDynamic,\n typeWrap: \"\",\n typeUnwrap: \"\",\n internalTypeId: typeId,\n };\n}\n\nexport function getUserTypeInfo(userType: UserType): {\n schemaType: SchemaType;\n renderType: RenderType;\n} {\n switch (userType.type) {\n case \"enum\": {\n const schemaType = SchemaType.UINT8;\n const staticByteLength = getStaticByteLength(schemaType);\n const isDynamic = staticByteLength === 0;\n return {\n schemaType,\n renderType: {\n typeId: userType.name,\n typeWithLocation: userType.name,\n enumName: SchemaType[schemaType],\n staticByteLength,\n isDynamic,\n typeWrap: userType.name,\n typeUnwrap: userType.abiType,\n internalTypeId: userType.abiType,\n },\n };\n }\n case \"userType\": {\n const schemaType = AbiTypeToSchemaType[userType.abiType];\n return {\n schemaType,\n renderType: {\n typeId: userType.name,\n typeWithLocation: userType.name,\n enumName: SchemaType[schemaType],\n staticByteLength: getStaticByteLength(schemaType),\n isDynamic: false,\n typeWrap: `${userType.name}.wrap`,\n typeUnwrap: `${userType.name}.unwrap`,\n internalTypeId: userType.abiType,\n },\n };\n }\n }\n}\n\nfunction getStaticArrayTypeInfo(abiType: string, elementType: string, staticLength: number) {\n const internalTypeId = elementType + \"[]\";\n const schemaType = AbiTypeToSchemaType[internalTypeId];\n return {\n schemaType,\n renderType: {\n typeId: abiType,\n typeWithLocation: `${abiType} memory`,\n enumName: SchemaType[schemaType],\n staticByteLength: 0,\n isDynamic: true,\n typeWrap: `toStaticArray_${elementType}_${staticLength}`,\n typeUnwrap: `fromStaticArray_${elementType}_${staticLength}`,\n typeWrappingData: {\n kind: \"staticArray\",\n elementType,\n staticLength,\n },\n internalTypeId,\n },\n } as const;\n}\n","import { renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { staticAbiTypeToByteLength, staticAbiTypes } from \"@latticexyz/schema-type/internal\";\nimport { renderTightCoderDecode } from \"./renderFunctions\";\n\n/**\n * Renders `DecodeSlice` library with the necessary header and imports,\n * which provides methods for decoding `Slice` into arrays of all primitive types\n * @returns string of Solidity code\n */\nexport function renderDecodeSlice() {\n return `\n ${renderedSolidityHeader}\n import { TightCoder } from \"./TightCoder.sol\";\n import { Slice } from \"../Slice.sol\";\n\n /**\n * @title DecodeSlice Library \n * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz)\n * @notice A library for decoding slices of data into specific data types.\n * @dev This library provides functions for decoding slices into arrays of basic uint types.\n */\n library DecodeSlice {\n ${staticAbiTypes\n .map((staticAbiType) =>\n renderTightCoderDecode({\n internalTypeId: staticAbiType,\n staticByteLength: staticAbiTypeToByteLength[staticAbiType],\n }),\n )\n .join(\"\\n\")}\n }\n `;\n}\n","import { RenderType, getLeftPaddingBits } from \"@latticexyz/common/codegen\";\n\n/**\n * Renders `decodeArray_*` method for decoding `Slice` into the array of provided primitive type\n * @param element name and byte length of the primitive type\n * @returns string of Solidity code\n */\nexport function renderTightCoderDecode(element: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">) {\n return `\n /**\n * @notice Decodes a slice into an array of ${element.internalTypeId}.\n * @dev Uses TightCoder for initial decoding, and then assembly for memory conversion.\n * @param _input The slice to decode.\n * @return _output The decoded array of ${element.internalTypeId}.\n */\n function decodeArray_${element.internalTypeId}(\n Slice _input\n ) internal pure returns (\n ${element.internalTypeId}[] memory _output\n ) {\n bytes32[] memory _genericArray = TightCoder.decode(\n _input,\n ${element.staticByteLength},\n ${getLeftPaddingBits(element)}\n );\n assembly {\n _output := _genericArray\n }\n }\n `;\n}\n\n/**\n * Renders `encode` method for encoding the array of provided primitive type into `Slice`\n * @param element name and byte length of the primitive type\n * @returns string of Solidity code\n */\nexport function renderTightCoderEncode(element: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">) {\n return `\n\n /**\n * @notice Encodes an array of ${element.internalTypeId} into a tightly packed bytes representation.\n * @param _input The array of ${element.internalTypeId} values to be encoded.\n * @return The resulting tightly packed bytes representation of the input array.\n */\n function encode(${element.internalTypeId}[] memory _input) internal pure returns (bytes memory) {\n bytes32[] memory _genericArray;\n assembly {\n _genericArray := _input\n }\n return TightCoder.encode(\n _genericArray,\n ${element.staticByteLength},\n ${getLeftPaddingBits(element)}\n );\n }\n `;\n}\n","import { renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { staticAbiTypeToByteLength, staticAbiTypes } from \"@latticexyz/schema-type/internal\";\nimport { renderTightCoderEncode } from \"./renderFunctions\";\n\n/**\n * Renders `EncodeArray` library with the necessary header and imports,\n * which provides methods for encoding arrays of all primitive types into `Slice`\n * @returns string of Solidity code\n */\nexport function renderEncodeArray() {\n return `\n ${renderedSolidityHeader}\n import { TightCoder } from \"./TightCoder.sol\";\n\n /**\n * @title EncodeArray \n * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz)\n * @dev This library provides utilities for encoding arrays into tightly packed bytes representations.\n */\n library EncodeArray {\n ${staticAbiTypes\n .map((staticAbiType) =>\n renderTightCoderEncode({\n internalTypeId: staticAbiType,\n staticByteLength: staticAbiTypeToByteLength[staticAbiType],\n }),\n )\n .join(\"\\n\")}\n }\n `;\n}\n","import { renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { staticAbiTypes } from \"@latticexyz/schema-type/internal\";\n\nexport function renderTightCoderAutoTestFunction({ typeId }: { typeId: string }) {\n return `\n function testEncodeDecodeArray_${typeId}(\n ${typeId} val0,\n ${typeId} val1,\n ${typeId} val2\n ) public {\n ${typeId}[] memory input = new ${typeId}[](3);\n input[0] = val0;\n input[1] = val1;\n input[2] = val2;\n\n bytes memory encoded = EncodeArray.encode(input);\n assertEq(encoded, abi.encodePacked(val0, val1, val2));\n\n ${typeId}[] memory decoded = SliceLib.fromBytes(encoded).decodeArray_${typeId}();\n assertEq(decoded.length, 3);\n assertEq(decoded[0], val0);\n assertEq(decoded[1], val1);\n assertEq(decoded[2], val2);\n }\n `;\n}\n\nexport function renderTightCoderAutoTest() {\n return `\n ${renderedSolidityHeader}\n\n import { Test } from \"forge-std/Test.sol\";\n import { EncodeArray } from \"../../src/tightcoder/EncodeArray.sol\";\n import { SliceLib } from \"../../src/Slice.sol\";\n\n contract TightCoderAutoTest is Test {\n ${staticAbiTypes.map((staticAbiType) => renderTightCoderAutoTestFunction({ typeId: staticAbiType })).join(\"\")}\n }\n `;\n}\n"],"mappings":"AAAA,OACE,mBAAAA,EACA,oBAAAC,GAGA,yBAAAC,EACA,mBAAAC,MACK,6BAQA,SAASC,EAAmBC,EAAqC,CACtE,IAAMC,EAAgBD,EAAQ,cACxB,CAAE,cAAAE,EAAe,cAAAC,EAAe,oBAAAC,CAAoB,EAAIR,GAAiBI,CAAO,EAElFK,EAAS,GACb,OAAW,CAACC,EAAaC,CAAK,IAAKP,EAAQ,OAAO,QAAQ,EAAG,CAC3D,GAAI,CAACA,EAAQ,yBAA2BO,EAAM,UAC5C,SAIF,IAAMC,EAAkB,GAAGD,EAAM,oBAAoBA,EAAM,OA0D3D,GAxDIP,EAAQ,cACVK,GAAUR,EAAsBG,EAAQ,2BAA4BO,EAAM,KAAOE,GAC/EX,EACEG,EACA,CAAC,CAAE,YAAAS,EAAa,OAAAC,EAAQ,eAAAC,EAAgB,kBAAAC,CAAkB,IAAM;AAAA;AAAA,6BAE7CN,EAAM,OAAOK;AAAA;AAAA,uBAEnBC,OAAuBJ,KAAqBd,EAAgB,CACrEe,EACAR,EACAC,CACF,CAAC,6BAA6BK;AAAA,gBAC1BJ;AAAA,gBAEAG,EAAM,UACF,wBAAwBI;AAAA;AAAA;AAAA,wBAGpBL,EAAcN,EAAQ,aAAa;AAAA,wBAEvC,mBAAmBW;AAAA;AAAA;AAAA,wBAGfL;AAAA;AAAA;AAAA,uBAIDQ,EAAwBP,CAAK;AAAA;AAAA,WAG5C,CACF,GAGFF,GAAUR,EAAsBG,EAAQ,2BAA4BO,EAAM,KAAOE,GAC/EX,EAAgBG,EAAe,CAAC,CAAE,YAAAS,EAAa,OAAAC,EAAQ,eAAAC,EAAgB,kBAAAC,CAAkB,IAAM,CAC7F,I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AA,QAQ/BA,gEAAqEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAO7E,CAEO,SAASC,IAA2B,CACzC,MAAO;AAAA,MACHJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAOEC,GAAe,IAAKI,GAAkBH,GAAiC,CAAE,OAAQG,CAAc,CAAC,CAAC,EAAE,KAAK,EAAE;AAAA;AAAA,GAGlH","names":["renderArguments","renderCommonData","renderWithFieldSuffix","renderWithStore","renderFieldMethods","options","storeArgument","_typedTableId","_typedKeyArgs","_keyTupleDefinition","result","schemaIndex","field","_typedFieldName","_methodNameSuffix","_typedStore","_store","_commentSuffix","_methodNamePrefix","renderDecodeFieldSingle","externalArguments","setFieldMethod","encodeFieldSingle","renderEncodeFieldSingle","internalArguments","portionData","fieldPortionData","dynamicSchemaIndex","typeWrappingData","renderCastStaticBytesToType","func","renderDecodeValueType","offset","staticByteLength","innerSlice","staticBytes","internalTypeId","bits","name","elementFieldData","isDynamic","arrayElement","renderArguments","renderCommonData","renderList","renderWithStore","renderRecordMethods","options","structName","storeArgument","_typedTableId","_typedKeyArgs","_keyTupleDefinition","renderCommonData","result","renderWithStore","_typedStore","_store","_commentSuffix","_methodNamePrefix","renderArguments","renderDecodedRecord","_useExplicitFieldLayout","externalArguments","name","typeWithLocation","internalArguments","renderRecordData","renderDecodeFunctions","namePrefix","renderDeleteRecordMethods","fields","staticFields","dynamicFields","renderedDecodedRecord","fieldNamePrefix","staticOffsets","_acc","index","field","renderList","renderDecodeValueType","renderDecodeDynamicFieldPartial","typeId","arrayElement","typeWrap","renderArguments","renderCommonData","renderList","renderImports","renderTableId","renderTypeHelpers","renderWithStore","renderedSolidityHeader","renderImportPath","LayoutOffsets","renderFieldLayout","fields","encodeFieldLayout","staticFields","isDynamic","numDynamicFields","fieldLayout","totalLength","staticByteLength","LayoutOffsets","keySchemaToHex","valueSchemaToHex","renderTable","options","imports","libraryName","structName","staticResourceData","storeImportPath","fields","staticFields","dynamicFields","withRecordMethods","storeArgument","keyTuple","_typedTableId","_typedKeyArgs","_keyTupleDefinition","renderCommonData","renderedSolidityHeader","renderImportPath","renderImports","renderList","name","typeId","renderTableId","renderFieldLayout","field","keyElement","index","renderWithStore","_typedStore","_store","_commentSuffix","_methodNamePrefix","renderArguments","renderFieldMethods","renderRecordMethods","renderDeleteRecordMethods","renderEncodeStatic","renderEncodeLengths","renderEncodeDynamic","typeWithLocation","renderRecordData","renderTypeHelpers","arrayElement","renderEncodeFieldSingle","renderEnums","renderTypesFromConfig","config","fs","path","formatAndWriteSolidity","renderEnums","renderList","renderedSolidityHeader","path","renderTableIndex","codegenIndexPath","options","outputPath","tableName","structName","imports","uniqueBy","path","getUserTypesFilename","config","groupBy","getUserTypes","config","enums","name","getUserTypesFilename","userTypes","userType","result","duplicates","entries","path","SchemaTypeArrayToElement","AbiTypeToSchemaType","getStaticByteLength","SchemaType","SchemaTypeToAbiType","parseStaticArray","abiType","matches","resolveAbiOrUserType","abiOrUserType","userTypes","schemaType","getSchemaTypeInfo","staticArray","getStaticArrayTypeInfo","userType","type","getUserTypeInfo","staticByteLength","isDynamic","typeId","elementType","staticLength","internalTypeId","getKeySchema","getValueSchema","isDefined","getTableOptions","tables","rootDir","codegenDir","userTypes","storeImportPath","table","outputPath","path","keySchema","valueSchema","withStruct","withRecordMethods","withSuffixlessFieldMethods","imports","field","type","userType","keyTuple","name","renderType","resolveAbiOrUserType","fields","schemaType","elementType","SchemaTypeArrayToElement","getSchemaTypeInfo","staticFields","isDynamic","dynamicFields","staticResourceData","tablegen","rootDir","config","userTypes","getUserTypes","userTypesFilename","path","getUserTypesFilename","source","renderEnums","formatAndWriteSolidity","namespace","sourceDir","codegenDir","tables","tableOptions","getTableOptions","tableDirs","uniqueBy","outputPath","dir","fs","renderOptions","renderTable","codegenIndexPath","renderTableIndex","renderedSolidityHeader","staticAbiTypeToByteLength","staticAbiTypes","getLeftPaddingBits","renderTightCoderDecode","element","renderTightCoderEncode","renderDecodeSlice","renderedSolidityHeader","staticAbiTypes","staticAbiType","renderTightCoderDecode","staticAbiTypeToByteLength","renderedSolidityHeader","staticAbiTypeToByteLength","staticAbiTypes","renderEncodeArray","renderedSolidityHeader","staticAbiTypes","staticAbiType","renderTightCoderEncode","staticAbiTypeToByteLength","renderedSolidityHeader","staticAbiTypes","renderTightCoderAutoTestFunction","typeId","renderTightCoderAutoTest","staticAbiType"]}
1
+ {"version":3,"sources":["../ts/codegen/field.ts","../ts/codegen/record.ts","../ts/codegen/renderTable.ts","../ts/constants.ts","../ts/codegen/renderFieldLayout.ts","../ts/codegen/renderTypesFromConfig.ts","../ts/codegen/tablegen.ts","../ts/codegen/renderTableIndex.ts","../ts/codegen/getUserTypesFilename.ts","../ts/codegen/getUserTypes.ts","../ts/codegen/getTableOptions.ts","../ts/codegen/userType.ts","../ts/codegen/tightcoder/renderDecodeSlice.ts","../ts/codegen/tightcoder/renderFunctions.ts","../ts/codegen/tightcoder/renderEncodeArray.ts","../ts/codegen/tightcoder/renderTightCoderAutoTest.ts"],"sourcesContent":["import {\n renderArguments,\n renderCommonData,\n RenderField,\n RenderType,\n renderWithFieldSuffix,\n renderWithStore,\n} from \"@latticexyz/common/codegen\";\nimport { RenderTableOptions } from \"./types\";\n\n/**\n * Returns Solidity code for all the field-specific table methods (get, set, push, pop, etc.)\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nexport function renderFieldMethods(options: RenderTableOptions): string {\n const storeArgument = options.storeArgument;\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n let result = \"\";\n for (const [schemaIndex, field] of options.fields.entries()) {\n if (!options.withDynamicFieldMethods && field.isDynamic) {\n continue;\n }\n\n // For dynamic fields, compute the field index relative to the end of the static fields\n const _typedFieldName = `${field.typeWithLocation} ${field.name}`;\n\n if (options.withGetters) {\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}get${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal view returns (${_typedFieldName}) {\n ${_keyTupleDefinition}\n ${\n field.isDynamic\n ? `bytes memory _blob = ${_store}.getDynamicField(\n _tableId,\n _keyTuple,\n ${schemaIndex - options.staticFields.length}\n );`\n : `bytes32 _blob = ${_store}.getStaticField(\n _tableId,\n _keyTuple,\n ${schemaIndex},\n _fieldLayout\n );`\n }\n return ${renderDecodeFieldSingle(field)};\n }\n `,\n ),\n );\n }\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(storeArgument, ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => {\n const externalArguments = renderArguments([_typedStore, _typedTableId, _typedKeyArgs, _typedFieldName]);\n const setFieldMethod = field.isDynamic ? \"setDynamicField\" : \"setStaticField\";\n const encodeFieldSingle = renderEncodeFieldSingle(field);\n const internalArguments = field.isDynamic\n ? `_tableId, _keyTuple, ${schemaIndex - options.staticFields.length}, ${encodeFieldSingle}`\n : `_tableId, _keyTuple, ${schemaIndex}, ${encodeFieldSingle}, _fieldLayout`;\n\n return `\n /**\n * @notice Set ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}set${_methodNameSuffix}(${externalArguments}) internal {\n ${_keyTupleDefinition}\n ${_store}.${setFieldMethod}(${internalArguments});\n }\n `;\n }),\n );\n\n if (field.isDynamic) {\n const portionData = fieldPortionData(field);\n const dynamicSchemaIndex = schemaIndex - options.staticFields.length;\n const { typeWrappingData } = field;\n\n if (options.withGetters) {\n if (typeWrappingData && typeWrappingData.kind === \"staticArray\") {\n result += renderWithFieldSuffix(\n options.withSuffixlessFieldMethods,\n field.name,\n (_methodNameSuffix) =>\n `\n // The length of ${field.name}\n uint256 constant length${_methodNameSuffix} = ${typeWrappingData.staticLength};\n `,\n );\n } else {\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get the length of ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}length${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal view returns (uint256) {\n ${_keyTupleDefinition}\n uint256 _byteLength = ${_store}.getDynamicFieldLength(_tableId, _keyTuple, ${dynamicSchemaIndex});\n unchecked {\n return _byteLength / ${portionData.elementLength};\n }\n }\n `,\n ),\n );\n }\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get an item of ${field.name}${_commentSuffix}.\n * @dev Reverts with Store_IndexOutOfBounds if \\`_index\\` is out of bounds for the array.\n */\n function ${_methodNamePrefix}getItem${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n \"uint256 _index\",\n ])}) internal view returns (${portionData.typeWithLocation}) {\n ${_keyTupleDefinition}\n\n ${\n // If the index is within the static length,\n // but ahead of the dynamic length, return zero\n typeWrappingData && typeWrappingData.kind === \"staticArray\" && field.arrayElement\n ? `\n uint256 _byteLength = ${_store}.getDynamicFieldLength(_tableId, _keyTuple, ${dynamicSchemaIndex});\n uint256 dynamicLength = _byteLength / ${portionData.elementLength};\n uint256 staticLength = ${typeWrappingData.staticLength};\n\n if (_index < staticLength && _index >= dynamicLength) {\n return ${renderCastStaticBytesToType(field.arrayElement, `bytes${field.arrayElement.staticByteLength}(new bytes(0))`)};\n }`\n : ``\n }\n\n unchecked {\n bytes memory _blob = ${_store}.getDynamicFieldSlice(\n _tableId,\n _keyTuple,\n ${dynamicSchemaIndex},\n _index * ${portionData.elementLength},\n (_index + 1) * ${portionData.elementLength}\n );\n return ${portionData.decoded};\n }\n }\n `,\n ),\n );\n }\n\n if (!typeWrappingData || typeWrappingData.kind !== \"staticArray\") {\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Push ${portionData.title} to ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}push${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n `${portionData.typeWithLocation} ${portionData.name}`,\n ])}) internal {\n ${_keyTupleDefinition}\n ${_store}.pushToDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.encoded});\n }\n `,\n ),\n );\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Pop ${portionData.title} from ${field.name}${_commentSuffix}.\n */\n function ${_methodNamePrefix}pop${_methodNameSuffix}(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal {\n ${_keyTupleDefinition}\n ${_store}.popFromDynamicField(_tableId, _keyTuple, ${dynamicSchemaIndex}, ${portionData.elementLength});\n }\n `,\n ),\n );\n }\n\n result += renderWithFieldSuffix(options.withSuffixlessFieldMethods, field.name, (_methodNameSuffix) =>\n renderWithStore(storeArgument, ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => {\n const externalArguments = renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n \"uint256 _index\",\n `${portionData.typeWithLocation} ${portionData.name}`,\n ]);\n\n const internalArguments = `\n _tableId,\n _keyTuple,\n ${dynamicSchemaIndex},\n uint40(_index * ${portionData.elementLength}),\n uint40(_encoded.length),\n _encoded \n `;\n\n return `\n /**\n * @notice Update ${portionData.title} of ${field.name}${_commentSuffix} at \\`_index\\`.\n */\n function ${_methodNamePrefix}update${_methodNameSuffix}(${externalArguments}) internal {\n ${_keyTupleDefinition}\n unchecked {\n bytes memory _encoded = ${portionData.encoded};\n ${_store}.spliceDynamicData(${internalArguments});\n }\n }\n `;\n }),\n );\n }\n }\n return result;\n}\n\n/**\n * Returns Solidity code for how to encode a particular field into bytes before storing onchain\n * @param field RenderField\n * @returns string of Solidity code\n */\nexport function renderEncodeFieldSingle(field: RenderField) {\n let func;\n if (field.arrayElement) {\n func = \"EncodeArray.encode\";\n } else if (field.isDynamic) {\n func = \"bytes\";\n } else {\n func = \"abi.encodePacked\";\n }\n return `${func}(${field.typeUnwrap}(${field.name}))`;\n}\n\n/**\n * Returns Solidity code for decoding a bytes value into its Solidity primitive type\n * @param field description of field type\n * @param offset byte-length offset of value in encoded bytes\n * @returns string of Solidity code\n */\nexport function renderDecodeValueType(field: RenderType, offset: number) {\n const { staticByteLength } = field;\n\n const innerSlice = `Bytes.getBytes${staticByteLength}(_blob, ${offset})`;\n\n return renderCastStaticBytesToType(field, innerSlice);\n}\n\n/**\n * Returns Solidity code for how to cast a bytesN value to a particular type, which is assumed to have the same byte length\n * @param field description of resulting field type\n * @param staticBytes bytesN value\n * @returns string of Solidity code\n */\nfunction renderCastStaticBytesToType(field: RenderType, staticBytes: string) {\n const { staticByteLength, internalTypeId } = field;\n const bits = staticByteLength * 8;\n\n let result;\n if (internalTypeId.match(/^uint\\d{1,3}$/) || internalTypeId === \"address\") {\n result = `${internalTypeId}(${staticBytes})`;\n } else if (internalTypeId.match(/^int\\d{1,3}$/)) {\n result = `${internalTypeId}(uint${bits}(${staticBytes}))`;\n } else if (internalTypeId.match(/^bytes\\d{1,2}$/)) {\n result = staticBytes;\n } else if (internalTypeId === \"bool\") {\n result = `_toBool(uint8(${staticBytes}))`;\n } else {\n throw new Error(`Unknown value type id ${internalTypeId}`);\n }\n return `${field.typeWrap}(${result})`;\n}\n\ninterface FieldPortionData {\n /** Fully-qualified name of the user-defined type (may include a library name as prefix), followed by location (none/memory/storage) */\n typeWithLocation: string;\n /** Name of the field portion variable */\n name: string;\n /** Solidity code which encodes the field portion variable into bytes (for storing onchain) */\n encoded: string;\n /** Solidity code which decodes `_blob` variable into the field portion variable's type */\n decoded: string;\n /** Description of the field portion kind (\"an element\" or \"a slice\") */\n title: string;\n /** Byte length of array elements for arrays, 1 otherwise */\n elementLength: number;\n}\n\n/**\n * Returns data to describe either an array element, or a bytes slice, depending on the provided field type\n */\nfunction fieldPortionData(field: RenderField): FieldPortionData {\n if (field.arrayElement) {\n const name = \"_element\";\n const elementFieldData = { ...field.arrayElement, arrayElement: undefined, name };\n return {\n typeWithLocation: field.arrayElement.typeWithLocation,\n name,\n encoded: renderEncodeFieldSingle(elementFieldData),\n decoded: renderDecodeFieldSingle(elementFieldData),\n title: \"an element\",\n elementLength: field.arrayElement.staticByteLength,\n };\n } else {\n const name = \"_slice\";\n const elementFieldData = { ...field, name };\n return {\n typeWithLocation: `${field.typeId} memory`,\n name,\n encoded: renderEncodeFieldSingle(elementFieldData),\n decoded: renderDecodeFieldSingle(elementFieldData),\n title: \"a slice\",\n elementLength: 1,\n };\n }\n}\n\n/**\n * Returns Solidity code for how to decode `_blob` variable into the particular field type\n * @param field RenderField\n * @returns string of Solidity code\n */\nfunction renderDecodeFieldSingle(field: RenderField) {\n const { isDynamic, arrayElement } = field;\n if (arrayElement) {\n // arrays\n return `${field.typeWrap}(\n SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_${arrayElement.internalTypeId}()\n )`;\n } else if (isDynamic) {\n // bytes/string\n return `${field.typeWrap}(${field.internalTypeId}(_blob))`;\n } else {\n return renderCastStaticBytesToType(field, `bytes${field.staticByteLength}(_blob)`);\n }\n}\n","import {\n RenderDynamicField,\n renderArguments,\n renderCommonData,\n renderList,\n renderWithStore,\n} from \"@latticexyz/common/codegen\";\nimport { renderDecodeValueType } from \"./field\";\nimport { RenderTableOptions } from \"./types\";\n\n/**\n * Returns Solidity code for whole-record methods (get, set)\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nexport function renderRecordMethods(options: RenderTableOptions) {\n const { structName, storeArgument } = options;\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n let result = \"\";\n\n if (options.withGetters) {\n result += renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Get the full data${_commentSuffix}.\n */\n function ${_methodNamePrefix}get(${renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n ])}) internal view returns (${renderDecodedRecord(options)}) {\n ${_keyTupleDefinition}\n \n (\n bytes memory _staticData,\n EncodedLengths _encodedLengths,\n bytes memory _dynamicData\n ) = ${_store}.getRecord(_tableId, _keyTuple, _fieldLayout);\n return decode(_staticData, _encodedLengths, _dynamicData);\n }\n `,\n );\n }\n\n result += renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {\n const externalArguments = renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n renderArguments(options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`)),\n ]);\n\n const internalArguments =\n \"_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData\" +\n (_useExplicitFieldLayout ? \", _fieldLayout\" : \"\");\n\n return `\n /** \n * @notice Set the full data using individual values${_commentSuffix}.\n */\n function ${_methodNamePrefix}set(${externalArguments}) internal {\n ${renderRecordData(options)}\n\n ${_keyTupleDefinition}\n\n ${_store}.setRecord(${internalArguments});\n }\n `;\n },\n );\n\n if (structName !== undefined) {\n result += renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {\n const externalArguments = renderArguments([\n _typedStore,\n _typedTableId,\n _typedKeyArgs,\n `${structName} memory _table`,\n ]);\n\n const internalArguments =\n \"_tableId, _keyTuple, _staticData, _encodedLengths, _dynamicData\" +\n (_useExplicitFieldLayout ? \", _fieldLayout\" : \"\");\n\n return `\n /**\n * @notice Set the full data using the data struct${_commentSuffix}.\n */\n function ${_methodNamePrefix}set(${externalArguments}) internal {\n ${renderRecordData(options, \"_table.\")}\n\n ${_keyTupleDefinition}\n\n ${_store}.setRecord(${internalArguments});\n }\n `;\n },\n );\n }\n\n result += renderDecodeFunctions(options);\n\n return result;\n}\n\n/**\n * Returns Solidity code to prepare variables needed to store encoded record on chain\n * @param options RenderTableOptions\n * @param namePrefix optional field name prefix to change how the field is accessed\n * @returns string of Solidity code\n */\nexport function renderRecordData(options: RenderTableOptions, namePrefix = \"\") {\n let result = \"\";\n if (options.staticFields.length > 0) {\n result += `\n bytes memory _staticData = encodeStatic(\n ${renderArguments(options.staticFields.map(({ name }) => `${namePrefix}${name}`))}\n );\n `;\n } else {\n result += `bytes memory _staticData;`;\n }\n\n if (options.dynamicFields.length > 0) {\n result += `\n EncodedLengths _encodedLengths = encodeLengths(\n ${renderArguments(options.dynamicFields.map(({ name }) => `${namePrefix}${name}`))}\n );\n bytes memory _dynamicData = encodeDynamic(\n ${renderArguments(options.dynamicFields.map(({ name }) => `${namePrefix}${name}`))}\n );\n `;\n } else {\n result += `\n EncodedLengths _encodedLengths;\n bytes memory _dynamicData;\n `;\n }\n\n return result;\n}\n\n/**\n * Returns Solidity code for the delete record method\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nexport function renderDeleteRecordMethods(options: RenderTableOptions) {\n const { storeArgument } = options;\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n return renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix, _useExplicitFieldLayout }) => {\n const externalArguments = renderArguments([_typedStore, _typedTableId, _typedKeyArgs]);\n const internalArguments = \"_tableId, _keyTuple\" + (_useExplicitFieldLayout ? \", _fieldLayout\" : \"\");\n\n return `\n /** \n * @notice Delete all data for given keys${_commentSuffix}.\n */\n function ${_methodNamePrefix}deleteRecord(${externalArguments}) internal {\n ${_keyTupleDefinition}\n ${_store}.deleteRecord(${internalArguments});\n }\n `;\n },\n );\n}\n\n/**\n * Returns Solidity code for the `decode` function that parses a bytes blob into the typed table data\n * @param options RenderTableOptions\n * @returns string of Solidity code\n */\nfunction renderDecodeFunctions({ structName, fields, staticFields, dynamicFields }: RenderTableOptions) {\n // either set struct properties, or just variables\n const renderedDecodedRecord = structName\n ? `${structName} memory _table`\n : renderArguments(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n const fieldNamePrefix = structName ? \"_table.\" : \"\";\n\n // Static field offsets\n const staticOffsets = staticFields.map(() => 0);\n let _acc = 0;\n for (const [index, field] of staticFields.entries()) {\n staticOffsets[index] = _acc;\n _acc += field.staticByteLength;\n }\n\n let result = \"\";\n\n if (staticFields.length > 0) {\n result += `\n /**\n * @notice Decode the tightly packed blob of static data using this table's field layout.\n */\n function decodeStatic(bytes memory _blob) internal pure returns (${renderArguments(\n staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) {\n ${renderList(\n staticFields,\n (field, index) => `\n ${field.name} = ${renderDecodeValueType(field, staticOffsets[index])};\n `,\n )}\n }\n `;\n }\n\n if (dynamicFields.length > 0) {\n result += `\n /**\n * @notice Decode the tightly packed blob of dynamic data using the encoded lengths.\n */\n function decodeDynamic(EncodedLengths _encodedLengths, bytes memory _blob) internal pure returns (${renderArguments(\n dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) {\n ${renderList(\n dynamicFields,\n // unchecked is only dangerous if _encodedLengths (and _blob) is invalid,\n // but it's assumed to be valid, and this function is meant to be mostly used internally\n (field, index) => {\n if (index === 0) {\n return `\n uint256 _start;\n uint256 _end;\n unchecked {\n _end = _encodedLengths.atIndex(${index});\n }\n ${field.name} = ${renderDecodeDynamicFieldPartial(field)};\n `;\n } else {\n return `\n _start = _end;\n unchecked {\n _end += _encodedLengths.atIndex(${index});\n }\n ${field.name} = ${renderDecodeDynamicFieldPartial(field)};\n `;\n }\n },\n )}\n }\n `;\n }\n\n result += `\n /**\n * @notice Decode the tightly packed blobs using this table's field layout.\n * ${staticFields.length > 0 ? \"@param _staticData Tightly packed static fields.\" : \"\"}\n * ${dynamicFields.length > 0 ? \"@param _encodedLengths Encoded lengths of dynamic fields.\" : \"\"}\n * ${dynamicFields.length > 0 ? \"@param _dynamicData Tightly packed dynamic fields.\" : \"\"}\n */\n function decode(\n bytes memory ${staticFields.length > 0 ? \"_staticData\" : \"\"},\n EncodedLengths ${dynamicFields.length > 0 ? \"_encodedLengths\" : \"\"},\n bytes memory ${dynamicFields.length > 0 ? \"_dynamicData\" : \"\"}\n ) internal pure returns (${renderedDecodedRecord}) {\n `;\n\n if (staticFields.length > 0) {\n result += `\n (${renderArguments(staticFields.map((field) => `${fieldNamePrefix}${field.name}`))}) = decodeStatic(_staticData);\n `;\n }\n if (dynamicFields.length > 0) {\n result += `\n (${renderArguments(\n dynamicFields.map((field) => `${fieldNamePrefix}${field.name}`),\n )}) = decodeDynamic(_encodedLengths, _dynamicData);\n `;\n }\n\n result += `\n }\n `;\n\n return result;\n}\n\n/**\n * Returns Solidity code for the return value of a record getter\n * @param options RenderDynamicField\n * @returns string of Solidity code\n */\nfunction renderDecodedRecord({ structName, fields }: RenderTableOptions) {\n if (structName) {\n return `${structName} memory _table`;\n } else {\n return renderArguments(fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n }\n}\n\n/**\n * Returns Solidity code for decoding onchain bytes into typed field data\n * @param options RenderDynamicField\n * @returns string of Solidity code\n */\nfunction renderDecodeDynamicFieldPartial(field: RenderDynamicField) {\n const { typeId, arrayElement, typeWrap } = field;\n if (arrayElement) {\n // arrays\n return `${typeWrap}(\n SliceLib.getSubslice(_blob, _start, _end).decodeArray_${arrayElement.typeId}()\n )`;\n } else {\n // bytes/string\n return `${typeWrap}(\n ${typeId}(\n SliceLib.getSubslice(_blob, _start, _end).toBytes()\n )\n )`;\n }\n}\n","import {\n RenderDynamicField,\n renderArguments,\n renderCommonData,\n renderList,\n renderImports,\n renderTableId,\n renderTypeHelpers,\n renderWithStore,\n renderedSolidityHeader,\n RenderStaticField,\n renderImportPath,\n} from \"@latticexyz/common/codegen\";\nimport { renderEncodeFieldSingle, renderFieldMethods } from \"./field\";\nimport { renderDeleteRecordMethods, renderRecordData, renderRecordMethods } from \"./record\";\nimport { renderFieldLayout } from \"./renderFieldLayout\";\nimport { RenderTableOptions } from \"./types\";\nimport { KeySchema, ValueSchema, keySchemaToHex, valueSchemaToHex } from \"@latticexyz/protocol-parser/internal\";\n\n/**\n * Renders Solidity code for a MUD table library, using the specified options\n * @param options options for rendering the table\n * @returns string of Solidity code\n */\nexport function renderTable(options: RenderTableOptions) {\n const {\n imports,\n libraryName,\n structName,\n staticResourceData,\n storeImportPath,\n fields,\n staticFields,\n dynamicFields,\n withRecordMethods,\n storeArgument,\n keyTuple,\n } = options;\n\n const { _typedTableId, _typedKeyArgs, _keyTupleDefinition } = renderCommonData(options);\n\n return `\n ${renderedSolidityHeader}\n\n // Import store internals\n import { IStore } from \"${renderImportPath(storeImportPath, \"IStore.sol\")}\";\n import { StoreSwitch } from \"${renderImportPath(storeImportPath, \"StoreSwitch.sol\")}\";\n import { StoreCore } from \"${renderImportPath(storeImportPath, \"StoreCore.sol\")}\";\n import { Bytes } from \"${renderImportPath(storeImportPath, \"Bytes.sol\")}\";\n import { Memory } from \"${renderImportPath(storeImportPath, \"Memory.sol\")}\";\n import { SliceLib } from \"${renderImportPath(storeImportPath, \"Slice.sol\")}\";\n import { EncodeArray } from \"${renderImportPath(storeImportPath, \"tightcoder/EncodeArray.sol\")}\";\n import { FieldLayout } from \"${renderImportPath(storeImportPath, \"FieldLayout.sol\")}\";\n import { Schema } from \"${renderImportPath(storeImportPath, \"Schema.sol\")}\";\n import { EncodedLengths, EncodedLengthsLib } from \"${renderImportPath(storeImportPath, \"EncodedLengths.sol\")}\";\n import { ResourceId } from \"${renderImportPath(storeImportPath, \"ResourceId.sol\")}\";\n\n ${\n imports.length > 0\n ? `\n // Import user types\n ${renderImports(imports)}\n `\n : \"\"\n }\n\n ${\n !structName\n ? \"\"\n : `\n struct ${structName} {\n ${renderList(fields, ({ name, typeId }) => `${typeId} ${name};`)}\n }\n `\n }\n\n library ${libraryName} {\n ${staticResourceData ? renderTableId(staticResourceData) : \"\"}\n \n ${renderFieldLayout(fields)}\n\n // Hex-encoded key schema of (${keyTuple.map((field) => field.internalTypeId).join(\", \")})\n Schema constant _keySchema = Schema.wrap(${keySchemaToHex(\n Object.fromEntries(keyTuple.map((field) => [field.name, field.internalTypeId])) as KeySchema,\n )});\n // Hex-encoded value schema of (${fields.map((field) => field.internalTypeId).join(\", \")})\n Schema constant _valueSchema = Schema.wrap(${valueSchemaToHex(\n Object.fromEntries(fields.map((field) => [field.name, field.internalTypeId])) as ValueSchema,\n )});\n\n /**\n * @notice Get the table's key field names.\n * @return keyNames An array of strings with the names of key fields.\n */\n function getKeyNames() internal pure returns (string[] memory keyNames) {\n keyNames = new string[](${keyTuple.length});\n ${renderList(keyTuple, (keyElement, index) => `keyNames[${index}] = \"${keyElement.name}\";`)}\n }\n\n /**\n * @notice Get the table's value field names.\n * @return fieldNames An array of strings with the names of value fields.\n */\n function getFieldNames() internal pure returns (string[] memory fieldNames) {\n fieldNames = new string[](${fields.length});\n ${renderList(fields, (field, index) => `fieldNames[${index}] = \"${field.name}\";`)}\n }\n\n ${renderWithStore(\n storeArgument,\n ({ _typedStore, _store, _commentSuffix, _methodNamePrefix }) => `\n /**\n * @notice Register the table with its config${_commentSuffix}.\n */\n function ${_methodNamePrefix}register(${renderArguments([_typedStore, _typedTableId])}) internal {\n ${_store}.registerTable(_tableId, _fieldLayout, _keySchema, _valueSchema, getKeyNames(), getFieldNames());\n }\n `,\n )}\n\n ${renderFieldMethods(options)}\n\n ${withRecordMethods ? renderRecordMethods(options) : \"\"}\n\n ${renderDeleteRecordMethods(options)}\n\n ${renderEncodeStatic(staticFields)}\n\n ${renderEncodeLengths(dynamicFields)}\n\n ${renderEncodeDynamic(dynamicFields)}\n\n /**\n * @notice Encode all of a record's fields.\n * @return The static (fixed length) data, encoded into a sequence of bytes.\n * @return The lengths of the dynamic fields (packed into a single bytes32 value).\n * @return The dynamic (variable length) data, encoded into a sequence of bytes.\n */\n function encode(${renderArguments(\n options.fields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (bytes memory, EncodedLengths, bytes memory) {\n ${renderRecordData(options)}\n\n return (_staticData, _encodedLengths, _dynamicData);\n }\n \n /**\n * @notice Encode keys as a bytes32 array using this table's field layout.\n */\n function encodeKeyTuple(${renderArguments([_typedKeyArgs])}) internal pure returns (bytes32[] memory) {\n ${_keyTupleDefinition}\n return _keyTuple;\n }\n }\n\n ${renderTypeHelpers(options)}\n `;\n}\n\n/**\n * Renders solidity code for `encodeStatic` method, which encodes the provided fields into a blob for storage\n * (nothing is rendered if static fields array is empty)\n * @param staticFields array of data about static fields to be encoded\n * @returns string of Solidity code\n */\nfunction renderEncodeStatic(staticFields: RenderStaticField[]) {\n if (staticFields.length === 0) return \"\";\n\n return `\n /**\n * @notice Tightly pack static (fixed length) data using this table's schema.\n * @return The static data, encoded into a sequence of bytes.\n */\n function encodeStatic(${renderArguments(\n staticFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (bytes memory) {\n return abi.encodePacked(${renderArguments(staticFields.map(({ name }) => name))});\n }\n `;\n}\n\n/**\n * Renders solidity code for `encodeLengths` method, which tightly packs the lengths of the provided fields\n * (nothing is rendered if dynamic fields array is empty)\n * @param dynamicFields array of data about dynamic fields to have their lengths encoded\n * @returns string of Solidity code\n */\nfunction renderEncodeLengths(dynamicFields: RenderDynamicField[]) {\n if (dynamicFields.length === 0) return \"\";\n\n return `\n /**\n * @notice Tightly pack dynamic data lengths using this table's schema.\n * @return _encodedLengths The lengths of the dynamic fields (packed into a single bytes32 value).\n */\n function encodeLengths(${renderArguments(\n dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (EncodedLengths _encodedLengths) {\n // Lengths are effectively checked during copy by 2**40 bytes exceeding gas limits\n unchecked {\n _encodedLengths = EncodedLengthsLib.pack(\n ${renderArguments(\n dynamicFields.map(({ name, arrayElement }) => {\n if (arrayElement) {\n return `${name}.length * ${arrayElement.staticByteLength}`;\n } else {\n return `bytes(${name}).length`;\n }\n }),\n )}\n );\n }\n }\n `;\n}\n\n/**\n * Renders solidity code for `encodeDynamic` method, which encodes the provided fields into a blob for storage\n * (nothing is rendered if dynamic fields array is empty)\n * @param dynamicFields array of data about dynamic fields to be encoded\n * @returns string of Solidity code\n */\nfunction renderEncodeDynamic(dynamicFields: RenderDynamicField[]) {\n if (dynamicFields.length === 0) return \"\";\n\n return `\n /**\n * @notice Tightly pack dynamic (variable length) data using this table's schema.\n * @return The dynamic data, encoded into a sequence of bytes.\n */\n function encodeDynamic(${renderArguments(\n dynamicFields.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`),\n )}) internal pure returns (bytes memory) {\n return abi.encodePacked(${renderArguments(dynamicFields.map((field) => renderEncodeFieldSingle(field)))});\n }\n `;\n}\n","/* Shared constants */\n// Make sure these stay aligned with @latticexyz/store/src/constants.sol\n\n// Total byte length of an EVM word\nexport const WORD_SIZE = 32;\n// Index of the last byte in an EVM word\nexport const WORD_LAST_INDEX = 31;\n// Conversion for bit shifting\nexport const BYTE_TO_BITS = 8;\n\n// Schema's capacity\nexport const MAX_TOTAL_FIELDS = 28;\n// FieldLayout's capacity\nexport const MAX_STATIC_FIELDS = 28;\n// EncodedLengths's capacity\nexport const MAX_DYNAMIC_FIELDS = 5;\n\n// FieldLayout and Schema have the same offsets for metadata\nexport const LayoutOffsets = {\n TOTAL_LENGTH: (WORD_SIZE - 2) * BYTE_TO_BITS,\n NUM_STATIC_FIELDS: (WORD_SIZE - 2 - 1) * BYTE_TO_BITS,\n NUM_DYNAMIC_FIELDS: (WORD_SIZE - 2 - 1 - 1) * BYTE_TO_BITS,\n};\n","import { RenderType } from \"@latticexyz/common/codegen\";\nimport { BYTE_TO_BITS, LayoutOffsets, MAX_DYNAMIC_FIELDS, MAX_TOTAL_FIELDS, WORD_LAST_INDEX } from \"../constants\";\n\ntype FieldLayoutRenderType = Pick<RenderType, \"isDynamic\" | \"staticByteLength\">;\n\n/**\n * Renders Solidity code that defines and initializes `_fieldLayout` constant\n * @param fields array of field data necessary to construct FieldLayout\n * @returns string of Solidity code\n */\nexport function renderFieldLayout(fields: FieldLayoutRenderType[]): string {\n return `FieldLayout constant _fieldLayout = FieldLayout.wrap(${encodeFieldLayout(fields)});`;\n}\n\n// Make sure this logic stays aligned with @latticexyz/store/src/FieldLayout.sol\n/**\n * Returns Solidity hexadecimal which represents the encoded FieldLayout\n * @param fields array of field data necessary to construct FieldLayout\n * @returns string of Solidity code\n */\nfunction encodeFieldLayout(fields: FieldLayoutRenderType[]): string {\n const staticFields = fields.filter(({ isDynamic }) => !isDynamic);\n const numDynamicFields = fields.length - staticFields.length;\n\n let fieldLayout = 0n;\n let totalLength = 0;\n const totalFields = fields.length;\n\n if (totalFields > MAX_TOTAL_FIELDS) throw new Error(\"FieldLayout: too many fields\");\n if (numDynamicFields > MAX_DYNAMIC_FIELDS) throw new Error(\"FieldLayout: too many dynamic fields\");\n\n for (let i = 0; i < staticFields.length; i++) {\n const { isDynamic, staticByteLength } = fields[i];\n if (isDynamic) throw new Error(`FieldLayout: static type after dynamic type`);\n\n totalLength += staticByteLength;\n fieldLayout |= BigInt(staticByteLength) << BigInt((WORD_LAST_INDEX - 4 - i) * BYTE_TO_BITS);\n }\n\n fieldLayout |= BigInt(totalLength) << BigInt(LayoutOffsets.TOTAL_LENGTH);\n fieldLayout |= BigInt(staticFields.length) << BigInt(LayoutOffsets.NUM_STATIC_FIELDS);\n fieldLayout |= BigInt(numDynamicFields) << BigInt(LayoutOffsets.NUM_DYNAMIC_FIELDS);\n\n return `0x${fieldLayout.toString(16).padStart(64, \"0\")}`;\n}\n","import { renderEnums } from \"@latticexyz/common/codegen\";\nimport { Store } from \"../config/v2\";\n\n/**\n * Renders Solidity code for enums defined in the provided config\n */\nexport function renderTypesFromConfig(config: Store) {\n return renderEnums(config.enums);\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { formatAndWriteSolidity, renderEnums } from \"@latticexyz/common/codegen\";\nimport { renderTable } from \"./renderTable\";\nimport { renderTableIndex } from \"./renderTableIndex\";\nimport { Store as StoreConfig } from \"../config/v2/output\";\nimport { uniqueBy } from \"@latticexyz/common/utils\";\nimport { getUserTypes } from \"./getUserTypes\";\nimport { getUserTypesFilename } from \"./getUserTypesFilename\";\nimport { getTableOptions } from \"./getTableOptions\";\n\nexport type TablegenOptions = {\n /**\n * MUD project root directory where all other relative paths are resolved from.\n */\n rootDir: string;\n config: StoreConfig;\n};\n\nexport async function tablegen({ rootDir, config }: TablegenOptions) {\n const userTypes = getUserTypes({ config });\n\n // Write enums to user types file\n if (Object.keys(config.enums).length > 0) {\n const userTypesFilename = path.join(rootDir, getUserTypesFilename({ config }));\n const source = renderEnums(config.enums);\n await formatAndWriteSolidity(source, userTypesFilename, \"Generated types file with enums\");\n }\n\n await Promise.all(\n Object.values(config.namespaces).map(async (namespace) => {\n // TODO: get this value from config once multiple namespaces are supported\n const multipleNamespaces = false;\n const sourceDir = multipleNamespaces\n ? path.join(config.sourceDirectory, \"namespaces\", namespace.label)\n : config.sourceDirectory;\n const codegenDir = path.join(sourceDir, config.codegen.outputDirectory);\n\n const tables = Object.values(namespace.tables);\n if (tables.length === 0) return;\n\n const tableOptions = getTableOptions({\n tables,\n rootDir,\n codegenDir,\n userTypes,\n storeImportPath: config.codegen.storeImportPath,\n });\n\n const tableDirs = uniqueBy(\n tableOptions.map(({ outputPath }) => path.dirname(outputPath)),\n (dir) => dir,\n );\n await Promise.all(tableDirs.map((dir) => fs.rm(dir, { recursive: true, force: true })));\n\n await Promise.all(\n tableOptions.map(async ({ outputPath, renderOptions }) => {\n const source = renderTable(renderOptions);\n return await formatAndWriteSolidity(source, outputPath, \"Generated table\");\n }),\n );\n\n const codegenIndexPath = path.join(rootDir, codegenDir, config.codegen.indexFilename);\n const source = renderTableIndex(codegenIndexPath, tableOptions);\n await formatAndWriteSolidity(source, codegenIndexPath, \"Generated table index\");\n }),\n );\n}\n","import { renderImportPath, renderList, renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { TableOptions } from \"./getTableOptions\";\nimport path from \"node:path\";\n\n/**\n * Returns Solidity code for table index file that imports all codegen tables\n * @param options table definitions\n * @returns string of Solidity code\n */\nexport function renderTableIndex(codegenIndexPath: string, options: TableOptions[]) {\n return `\n ${renderedSolidityHeader}\n\n ${renderList(options, ({ outputPath, tableName, renderOptions: { structName } }) => {\n const imports = [tableName];\n if (structName) imports.push(structName);\n\n return `import { ${imports.join(\", \")} } from \"${renderImportPath(\"./\" + path.relative(path.dirname(codegenIndexPath), outputPath))}\";`;\n })}\n `;\n}\n","import path from \"node:path\";\nimport { Store } from \"../config/v2\";\n\n/**\n * @returns File path for codegen'ed user types, relative to source dir\n */\nexport function getUserTypesFilename({ config }: { config: Store }): string {\n return path.join(config.sourceDirectory, config.codegen.outputDirectory, config.codegen.userTypesFilename);\n}\n","import { Store } from \"../config/v2\";\nimport { AbiType } from \"@latticexyz/config\";\nimport { getUserTypesFilename } from \"./getUserTypesFilename\";\nimport { groupBy } from \"@latticexyz/common/utils\";\n\nexport type UserType = {\n readonly type: \"enum\" | \"userType\";\n readonly name: string;\n readonly abiType: AbiType;\n /**\n * Import path relative to the root dir or absolute path if importing from a package.\n * Relative paths must start with a `.` to be treated as a relative path.\n */\n readonly importPath: string;\n};\n\nexport function getUserTypes({ config }: { readonly config: Store }): readonly UserType[] {\n const enums = Object.keys(config.enums).map(\n (name): UserType => ({\n type: \"enum\",\n name,\n abiType: \"uint8\",\n importPath: \"./\" + getUserTypesFilename({ config }),\n }),\n );\n\n const userTypes = Object.entries(config.userTypes).map(\n ([name, userType]): UserType => ({\n type: \"userType\",\n name,\n abiType: userType.type,\n // If `userType.filePath` starts with a `.`, it's relative to the root dir\n importPath: userType.filePath,\n }),\n );\n\n const result = [...enums, ...userTypes];\n\n // TODO: move this to config validation step?\n const duplicates = Array.from(groupBy(result, (userType) => userType.name).entries())\n .filter(([, entries]) => entries.length > 1)\n .map(([name]) => name);\n if (duplicates.length > 0) {\n throw new Error(`Found enums and user types sharing the same name: ${duplicates.join(\", \")}`);\n }\n\n return result;\n}\n","import path from \"path\";\nimport { SchemaTypeArrayToElement } from \"@latticexyz/schema-type/deprecated\";\nimport { RenderDynamicField, RenderField, RenderKeyTuple, RenderStaticField } from \"@latticexyz/common/codegen\";\nimport { RenderTableOptions } from \"./types\";\nimport { getSchemaTypeInfo, resolveAbiOrUserType } from \"./userType\";\nimport { Table } from \"../config/v2/output\";\nimport { getKeySchema, getValueSchema } from \"@latticexyz/protocol-parser/internal\";\nimport { UserType } from \"./getUserTypes\";\nimport { isDefined } from \"@latticexyz/common/utils\";\nimport { ImportDatum } from \"@latticexyz/common/codegen\";\n\nexport interface TableOptions {\n /** Path where the file is expected to be written (relative to project root) */\n outputPath: string;\n /** Name of the table, as used in filename and library name */\n tableName: string;\n /** Options for `renderTable` function */\n renderOptions: RenderTableOptions;\n}\n\n/**\n * Transforms store config and available solidity user types into useful options for `tablegen` and `renderTable`\n */\nexport function getTableOptions({\n tables,\n rootDir,\n codegenDir,\n userTypes,\n storeImportPath,\n}: {\n readonly tables: Table[];\n readonly rootDir: string;\n /** namespace codegen output dir, relative to project root dir */\n readonly codegenDir: string;\n readonly userTypes: readonly UserType[];\n /** absolute import path or, if starting with `.`, relative to project root dir */\n readonly storeImportPath: string;\n}): TableOptions[] {\n const options = tables.map((table): TableOptions => {\n const outputPath = path.join(rootDir, codegenDir, table.codegen.outputDirectory, `${table.label}.sol`);\n\n const keySchema = getKeySchema(table);\n const valueSchema = getValueSchema(table);\n\n // struct adds methods to get/set all values at once\n const withStruct = table.codegen.dataStruct;\n // operate on all fields at once; always render for offchain tables; for only 1 field keep them if struct is also kept\n const withRecordMethods = withStruct || table.type === \"offchainTable\" || Object.keys(valueSchema).length > 1;\n // field methods can include simply get/set if there's only 1 field and no record methods\n const withSuffixlessFieldMethods = !withRecordMethods && Object.keys(valueSchema).length === 1;\n // list of any symbols that need to be imported\n const imports = Object.values(table.schema)\n .map((field) => userTypes.find((type) => type.name === field.internalType))\n .filter(isDefined)\n .map((userType): ImportDatum => {\n return {\n // If it's a fully qualified name, remove trailing references\n // This enables support for user types inside libraries\n symbol: userType.name.replace(/\\..*$/, \"\"),\n path: userType.importPath.startsWith(\".\")\n ? \"./\" + path.relative(path.dirname(outputPath), path.join(rootDir, userType.importPath))\n : userType.importPath,\n };\n });\n\n const keyTuple = Object.entries(keySchema).map(([name, field]): RenderKeyTuple => {\n const { renderType } = resolveAbiOrUserType(field.internalType, userTypes);\n\n return {\n ...renderType,\n name,\n isDynamic: false,\n };\n });\n\n const fields = Object.entries(valueSchema).map(([name, field]): RenderField => {\n const { renderType, schemaType } = resolveAbiOrUserType(field.internalType, userTypes);\n\n const elementType = SchemaTypeArrayToElement[schemaType];\n return {\n ...renderType,\n arrayElement: elementType !== undefined ? getSchemaTypeInfo(elementType) : undefined,\n name,\n };\n });\n\n const staticFields = fields.filter(({ isDynamic }) => !isDynamic) as RenderStaticField[];\n const dynamicFields = fields.filter(({ isDynamic }) => isDynamic) as RenderDynamicField[];\n\n // With tableIdArgument: tableId is a dynamic argument for each method\n // Without tableIdArgument: tableId is a file-level constant generated from `staticResourceData`\n const staticResourceData = table.codegen.tableIdArgument\n ? undefined\n : {\n namespace: table.namespace,\n name: table.name,\n offchainOnly: table.type === \"offchainTable\",\n };\n\n return {\n outputPath,\n tableName: table.label,\n renderOptions: {\n imports,\n libraryName: table.label,\n structName: withStruct ? table.label + \"Data\" : undefined,\n staticResourceData,\n storeImportPath: storeImportPath.startsWith(\".\")\n ? \"./\" + path.relative(path.dirname(outputPath), path.join(rootDir, storeImportPath))\n : storeImportPath,\n keyTuple,\n fields,\n staticFields,\n dynamicFields,\n withGetters: table.type === \"table\",\n withRecordMethods,\n withDynamicFieldMethods: table.type === \"table\",\n withSuffixlessFieldMethods,\n storeArgument: table.codegen.storeArgument,\n },\n };\n });\n\n return options;\n}\n","import {\n AbiTypeToSchemaType,\n getStaticByteLength,\n SchemaType,\n SchemaTypeToAbiType,\n} from \"@latticexyz/schema-type/deprecated\";\nimport { RenderType } from \"@latticexyz/common/codegen\";\nimport { UserType } from \"./getUserTypes\";\n\nfunction parseStaticArray(abiType: string) {\n const matches = abiType.match(/^(\\w+)\\[(\\d+)\\]$/);\n if (!matches) return null;\n return {\n elementType: matches[1],\n staticLength: Number.parseInt(matches[2]),\n };\n}\n\n/**\n * Resolve an abi or user type into a SchemaType and RenderType\n */\nexport function resolveAbiOrUserType(\n abiOrUserType: string,\n userTypes: readonly UserType[],\n): {\n schemaType: SchemaType;\n renderType: RenderType;\n} {\n // abi types which directly mirror a SchemaType\n if (abiOrUserType in AbiTypeToSchemaType) {\n const schemaType = AbiTypeToSchemaType[abiOrUserType];\n return {\n schemaType,\n renderType: getSchemaTypeInfo(schemaType),\n };\n }\n // static arrays\n const staticArray = parseStaticArray(abiOrUserType);\n if (staticArray) {\n if (staticArray.elementType in AbiTypeToSchemaType) {\n return getStaticArrayTypeInfo(abiOrUserType, staticArray.elementType, staticArray.staticLength);\n } else {\n throw new Error(\"Static arrays of user types are not supported\");\n }\n }\n\n // user types\n const userType = userTypes.find((type) => type.name === abiOrUserType);\n if (!userType) {\n throw new Error(`User type \"${abiOrUserType}\" not found`);\n }\n return getUserTypeInfo(userType);\n}\n\nexport function getSchemaTypeInfo(schemaType: SchemaType): RenderType {\n const staticByteLength = getStaticByteLength(schemaType);\n const isDynamic = staticByteLength === 0;\n const typeId = SchemaTypeToAbiType[schemaType];\n return {\n typeId,\n typeWithLocation: isDynamic ? typeId + \" memory\" : typeId,\n enumName: SchemaType[schemaType],\n staticByteLength,\n isDynamic,\n typeWrap: \"\",\n typeUnwrap: \"\",\n internalTypeId: typeId,\n };\n}\n\nexport function getUserTypeInfo(userType: UserType): {\n schemaType: SchemaType;\n renderType: RenderType;\n} {\n switch (userType.type) {\n case \"enum\": {\n const schemaType = SchemaType.UINT8;\n const staticByteLength = getStaticByteLength(schemaType);\n const isDynamic = staticByteLength === 0;\n return {\n schemaType,\n renderType: {\n typeId: userType.name,\n typeWithLocation: userType.name,\n enumName: SchemaType[schemaType],\n staticByteLength,\n isDynamic,\n typeWrap: userType.name,\n typeUnwrap: userType.abiType,\n internalTypeId: userType.abiType,\n },\n };\n }\n case \"userType\": {\n const schemaType = AbiTypeToSchemaType[userType.abiType];\n return {\n schemaType,\n renderType: {\n typeId: userType.name,\n typeWithLocation: userType.name,\n enumName: SchemaType[schemaType],\n staticByteLength: getStaticByteLength(schemaType),\n isDynamic: false,\n typeWrap: `${userType.name}.wrap`,\n typeUnwrap: `${userType.name}.unwrap`,\n internalTypeId: userType.abiType,\n },\n };\n }\n }\n}\n\nfunction getStaticArrayTypeInfo(abiType: string, elementType: string, staticLength: number) {\n const internalTypeId = elementType + \"[]\";\n const schemaType = AbiTypeToSchemaType[internalTypeId];\n return {\n schemaType,\n renderType: {\n typeId: abiType,\n typeWithLocation: `${abiType} memory`,\n enumName: SchemaType[schemaType],\n staticByteLength: 0,\n isDynamic: true,\n typeWrap: `toStaticArray_${elementType}_${staticLength}`,\n typeUnwrap: `fromStaticArray_${elementType}_${staticLength}`,\n typeWrappingData: {\n kind: \"staticArray\",\n elementType,\n staticLength,\n },\n internalTypeId,\n },\n } as const;\n}\n","import { renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { staticAbiTypeToByteLength, staticAbiTypes } from \"@latticexyz/schema-type/internal\";\nimport { renderTightCoderDecode } from \"./renderFunctions\";\n\n/**\n * Renders `DecodeSlice` library with the necessary header and imports,\n * which provides methods for decoding `Slice` into arrays of all primitive types\n * @returns string of Solidity code\n */\nexport function renderDecodeSlice() {\n return `\n ${renderedSolidityHeader}\n import { TightCoder } from \"./TightCoder.sol\";\n import { Slice } from \"../Slice.sol\";\n\n /**\n * @title DecodeSlice Library \n * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz)\n * @notice A library for decoding slices of data into specific data types.\n * @dev This library provides functions for decoding slices into arrays of basic uint types.\n */\n library DecodeSlice {\n ${staticAbiTypes\n .map((staticAbiType) =>\n renderTightCoderDecode({\n internalTypeId: staticAbiType,\n staticByteLength: staticAbiTypeToByteLength[staticAbiType],\n }),\n )\n .join(\"\\n\")}\n }\n `;\n}\n","import { RenderType, getLeftPaddingBits } from \"@latticexyz/common/codegen\";\n\n/**\n * Renders `decodeArray_*` method for decoding `Slice` into the array of provided primitive type\n * @param element name and byte length of the primitive type\n * @returns string of Solidity code\n */\nexport function renderTightCoderDecode(element: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">) {\n return `\n /**\n * @notice Decodes a slice into an array of ${element.internalTypeId}.\n * @dev Uses TightCoder for initial decoding, and then assembly for memory conversion.\n * @param _input The slice to decode.\n * @return _output The decoded array of ${element.internalTypeId}.\n */\n function decodeArray_${element.internalTypeId}(\n Slice _input\n ) internal pure returns (\n ${element.internalTypeId}[] memory _output\n ) {\n bytes32[] memory _genericArray = TightCoder.decode(\n _input,\n ${element.staticByteLength},\n ${getLeftPaddingBits(element)}\n );\n assembly {\n _output := _genericArray\n }\n }\n `;\n}\n\n/**\n * Renders `encode` method for encoding the array of provided primitive type into `Slice`\n * @param element name and byte length of the primitive type\n * @returns string of Solidity code\n */\nexport function renderTightCoderEncode(element: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">) {\n return `\n\n /**\n * @notice Encodes an array of ${element.internalTypeId} into a tightly packed bytes representation.\n * @param _input The array of ${element.internalTypeId} values to be encoded.\n * @return The resulting tightly packed bytes representation of the input array.\n */\n function encode(${element.internalTypeId}[] memory _input) internal pure returns (bytes memory) {\n bytes32[] memory _genericArray;\n assembly {\n _genericArray := _input\n }\n return TightCoder.encode(\n _genericArray,\n ${element.staticByteLength},\n ${getLeftPaddingBits(element)}\n );\n }\n `;\n}\n","import { renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { staticAbiTypeToByteLength, staticAbiTypes } from \"@latticexyz/schema-type/internal\";\nimport { renderTightCoderEncode } from \"./renderFunctions\";\n\n/**\n * Renders `EncodeArray` library with the necessary header and imports,\n * which provides methods for encoding arrays of all primitive types into `Slice`\n * @returns string of Solidity code\n */\nexport function renderEncodeArray() {\n return `\n ${renderedSolidityHeader}\n import { TightCoder } from \"./TightCoder.sol\";\n\n /**\n * @title EncodeArray \n * @author MUD (https://mud.dev) by Lattice (https://lattice.xyz)\n * @dev This library provides utilities for encoding arrays into tightly packed bytes representations.\n */\n library EncodeArray {\n ${staticAbiTypes\n .map((staticAbiType) =>\n renderTightCoderEncode({\n internalTypeId: staticAbiType,\n staticByteLength: staticAbiTypeToByteLength[staticAbiType],\n }),\n )\n .join(\"\\n\")}\n }\n `;\n}\n","import { renderedSolidityHeader } from \"@latticexyz/common/codegen\";\nimport { staticAbiTypes } from \"@latticexyz/schema-type/internal\";\n\nexport function renderTightCoderAutoTestFunction({ typeId }: { typeId: string }) {\n return `\n function testEncodeDecodeArray_${typeId}(\n ${typeId} val0,\n ${typeId} val1,\n ${typeId} val2\n ) public {\n ${typeId}[] memory input = new ${typeId}[](3);\n input[0] = val0;\n input[1] = val1;\n input[2] = val2;\n\n bytes memory encoded = EncodeArray.encode(input);\n assertEq(encoded, abi.encodePacked(val0, val1, val2));\n\n ${typeId}[] memory decoded = SliceLib.fromBytes(encoded).decodeArray_${typeId}();\n assertEq(decoded.length, 3);\n assertEq(decoded[0], val0);\n assertEq(decoded[1], val1);\n assertEq(decoded[2], val2);\n }\n `;\n}\n\nexport function renderTightCoderAutoTest() {\n return `\n ${renderedSolidityHeader}\n\n import { Test } from \"forge-std/Test.sol\";\n import { EncodeArray } from \"../../src/tightcoder/EncodeArray.sol\";\n import { SliceLib } from \"../../src/Slice.sol\";\n\n contract TightCoderAutoTest is Test {\n ${staticAbiTypes.map((staticAbiType) => renderTightCoderAutoTestFunction({ typeId: staticAbiType })).join(\"\")}\n }\n `;\n}\n"],"mappings":"AAAA,OACE,mBAAAA,EACA,oBAAAC,GAGA,yBAAAC,EACA,mBAAAC,MACK,6BAQA,SAASC,EAAmBC,EAAqC,CACtE,IAAMC,EAAgBD,EAAQ,cACxB,CAAE,cAAAE,EAAe,cAAAC,EAAe,oBAAAC,CAAoB,EAAIR,GAAiBI,CAAO,EAElFK,EAAS,GACb,OAAW,CAACC,EAAaC,CAAK,IAAKP,EAAQ,OAAO,QAAQ,EAAG,CAC3D,GAAI,CAACA,EAAQ,yBAA2BO,EAAM,UAC5C,SAIF,IAAMC,EAAkB,GAAGD,EAAM,oBAAoBA,EAAM,OA0D3D,GAxDIP,EAAQ,cACVK,GAAUR,EAAsBG,EAAQ,2BAA4BO,EAAM,KAAOE,GAC/EX,EACEG,EACA,CAAC,CAAE,YAAAS,EAAa,OAAAC,EAAQ,eAAAC,EAAgB,kBAAAC,CAAkB,IAAM;AAAA;AAAA,6BAE7CN,EAAM,OAAOK;AAAA;AAAA,uBAEnBC,OAAuBJ,KAAqBd,EAAgB,CACrEe,EACAR,EACAC,CACF,CAAC,6BAA6BK;AAAA,gBAC1BJ;AAAA,gBAEAG,EAAM,UACF,wBAAwBI;AAAA;AAAA;AAAA,wBAGpBL,EAAcN,EAAQ,aAAa;AAAA,wBAEvC,mBAAmBW;AAAA;AAAA;AAAA,wBAGfL;AAAA;AAAA;AAAA,uBAIDQ,EAAwBP,CAAK;AAAA;AAAA,WAG5C,CACF,GAGFF,GAAUR,EAAsBG,EAAQ,2BAA4BO,EAAM,KAAOE,GAC/EX,EAAgBG,EAAe,CAAC,CAAE,YAAAS,EAAa,OAAAC,EAAQ,eAAAC,EAAgB,kBAAAC,CAAkB,IAAM,CAC7F,IAAME,EAAoBpB,EAAgB,CAACe,EAAaR,E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Q/BA,gEAAqEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAO7E,CAEO,SAASC,IAA2B,CACzC,MAAO;AAAA,MACHJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAOEC,GAAe,IAAKI,GAAkBH,GAAiC,CAAE,OAAQG,CAAc,CAAC,CAAC,EAAE,KAAK,EAAE;AAAA;AAAA,GAGlH","names":["renderArguments","renderCommonData","renderWithFieldSuffix","renderWithStore","renderFieldMethods","options","storeArgument","_typedTableId","_typedKeyArgs","_keyTupleDefinition","result","schemaIndex","field","_typedFieldName","_methodNameSuffix","_typedStore","_store","_commentSuffix","_methodNamePrefix","renderDecodeFieldSingle","externalArguments","setFieldMethod","encodeFieldSingle","renderEncodeFieldSingle","internalArguments","portionData","fieldPortionData","dynamicSchemaIndex","typeWrappingData","renderCastStaticBytesToType","func","renderDecodeValueType","offset","staticByteLength","innerSlice","staticBytes","internalTypeId","bits","name","elementFieldData","isDynamic","arrayElement","renderArguments","renderCommonData","renderList","renderWithStore","renderRecordMethods","options","structName","storeArgument","_typedTableId","_typedKeyArgs","_keyTupleDefinition","renderCommonData","result","renderWithStore","_typedStore","_store","_commentSuffix","_methodNamePrefix","renderArguments","renderDecodedRecord","_useExplicitFieldLayout","externalArguments","name","typeWithLocation","internalArguments","renderRecordData","renderDecodeFunctions","namePrefix","renderDeleteRecordMethods","fields","staticFields","dynamicFields","renderedDecodedRecord","fieldNamePrefix","staticOffsets","_acc","index","field","renderList","renderDecodeValueType","renderDecodeDynamicFieldPartial","typeId","arrayElement","typeWrap","renderArguments","renderCommonData","renderList","renderImports","renderTableId","renderTypeHelpers","renderWithStore","renderedSolidityHeader","renderImportPath","LayoutOffsets","renderFieldLayout","fields","encodeFieldLayout","staticFields","isDynamic","numDynamicFields","fieldLayout","totalLength","staticByteLength","LayoutOffsets","keySchemaToHex","valueSchemaToHex","renderTable","options","imports","libraryName","structName","staticResourceData","storeImportPath","fields","staticFields","dynamicFields","withRecordMethods","storeArgument","keyTuple","_typedTableId","_typedKeyArgs","_keyTupleDefinition","renderCommonData","renderedSolidityHeader","renderImportPath","renderImports","renderList","name","typeId","renderTableId","renderFieldLayout","field","keyElement","index","renderWithStore","_typedStore","_store","_commentSuffix","_methodNamePrefix","renderArguments","renderFieldMethods","renderRecordMethods","renderDeleteRecordMethods","renderEncodeStatic","renderEncodeLengths","renderEncodeDynamic","typeWithLocation","renderRecordData","renderTypeHelpers","arrayElement","renderEncodeFieldSingle","renderEnums","renderTypesFromConfig","config","fs","path","formatAndWriteSolidity","renderEnums","renderImportPath","renderList","renderedSolidityHeader","path","renderTableIndex","codegenIndexPath","options","outputPath","tableName","structName","imports","uniqueBy","path","getUserTypesFilename","config","groupBy","getUserTypes","config","enums","name","getUserTypesFilename","userTypes","userType","result","duplicates","entries","path","SchemaTypeArrayToElement","AbiTypeToSchemaType","getStaticByteLength","SchemaType","SchemaTypeToAbiType","parseStaticArray","abiType","matches","resolveAbiOrUserType","abiOrUserType","userTypes","schemaType","getSchemaTypeInfo","staticArray","getStaticArrayTypeInfo","userType","type","getUserTypeInfo","staticByteLength","isDynamic","typeId","elementType","staticLength","internalTypeId","getKeySchema","getValueSchema","isDefined","getTableOptions","tables","rootDir","codegenDir","userTypes","storeImportPath","table","outputPath","path","keySchema","valueSchema","withStruct","withRecordMethods","withSuffixlessFieldMethods","imports","field","type","userType","keyTuple","name","renderType","resolveAbiOrUserType","fields","schemaType","elementType","SchemaTypeArrayToElement","getSchemaTypeInfo","staticFields","isDynamic","dynamicFields","staticResourceData","tablegen","rootDir","config","userTypes","getUserTypes","userTypesFilename","path","getUserTypesFilename","source","renderEnums","formatAndWriteSolidity","namespace","sourceDir","codegenDir","tables","tableOptions","getTableOptions","tableDirs","uniqueBy","outputPath","dir","fs","renderOptions","renderTable","codegenIndexPath","renderTableIndex","renderedSolidityHeader","staticAbiTypeToByteLength","staticAbiTypes","getLeftPaddingBits","renderTightCoderDecode","element","renderTightCoderEncode","renderDecodeSlice","renderedSolidityHeader","staticAbiTypes","staticAbiType","renderTightCoderDecode","staticAbiTypeToByteLength","renderedSolidityHeader","staticAbiTypeToByteLength","staticAbiTypes","renderEncodeArray","renderedSolidityHeader","staticAbiTypes","staticAbiType","renderTightCoderEncode","staticAbiTypeToByteLength","renderedSolidityHeader","staticAbiTypes","renderTightCoderAutoTestFunction","typeId","renderTightCoderAutoTest","staticAbiType"]}
@@ -1,6 +1,6 @@
1
1
  export { C as CODEGEN_DEFAULTS, D as CONFIG_DEFAULTS, N as NoStaticKeyFieldError, T as TABLE_CODEGEN_DEFAULTS, B as TABLE_DEFAULTS, A as TABLE_DEPLOY_DEFAULTS, V as ValidKeys, q as ValidateTableOptions, d as defineSchema, x as defineTable, l as defineTableShorthand, z as defineTables, k as expandTableShorthand, g as get, b as getPath, h as hasOwnKey, i as isObject, e as isSchemaInput, f as isTableShorthandInput, n as isValidPrimaryKey, m as mergeIfUndefined, p as parseNumber, s as requiredTableKey, r as resolveNamespacedTables, c as resolveSchema, w as resolveTable, u as resolveTableCodegen, a as resolveTables, o as validateKeys, v as validateSchema, t as validateTable, j as validateTableShorthand, y as validateTables } from '../namespacedTables-264f21b1.js';
2
2
  export { A as AbiTypeScope, r as Codegen, C as CodegenInput, n as EnumValues, m as Enums, E as EnumsInput, s as Namespace, N as NamespaceInput, t as Namespaces, c as SchemaInput, a as Scope, b as ScopeOptions, d as ScopedSchemaInput, S as Store, l as StoreInput, T as Table, o as TableCodegen, f as TableCodegenInput, p as TableDeploy, h as TableDeployInput, i as TableInput, j as TableShorthandInput, q as Tables, k as TablesInput, U as UserTypes, e as extendScope, g as getStaticAbiTypeKeys } from '../input-e69ffb2f.js';
3
- export { d as defineStore, e as extendedScope, c as extractInternalType, i as isUserTypes, m as mapEnums, a as resolveCodegen, b as resolveEnums, r as resolveStore, s as scopeWithEnums, f as scopeWithUserTypes, v as validateStore, g as validateUserTypes } from '../store-3b37a8c0.js';
3
+ export { d as defineStore, e as extendedScope, c as extractInternalType, i as isUserTypes, m as mapEnums, a as resolveCodegen, b as resolveEnums, j as resolveNamespace, r as resolveStore, s as scopeWithEnums, f as scopeWithUserTypes, h as validateNamespace, v as validateStore, g as validateUserTypes } from '../store-122dc6fd.js';
4
4
  export { AbiType, Schema } from '@latticexyz/config';
5
5
  import '@arktype/util';
6
6
  import 'viem';
package/dist/config/v2.js CHANGED
@@ -1,2 +1,2 @@
1
- import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"../chunk-3PAPLPW2.js";export{d as AbiTypeScope,p as CODEGEN_DEFAULTS,b as CONFIG_DEFAULTS,v as NoStaticKeyFieldError,c as Scope,t as TABLE_CODEGEN_DEFAULTS,a as TABLE_DEFAULTS,x as TABLE_DEPLOY_DEFAULTS,j as defineSchema,Q as defineStore,u as defineTable,A as defineTableShorthand,D as defineTables,z as expandTableShorthand,g as extendScope,N as extendedScope,E as extractInternalType,o as get,r as getPath,e as hasOwnKey,f as isObject,k as isSchemaInput,w as isTableShorthandInput,F as isUserTypes,l as isValidPrimaryKey,K as mapEnums,m as mergeIfUndefined,L as resolveCodegen,J as resolveEnums,M as resolveNamespacedTables,i as resolveSchema,P as resolveStore,s as resolveTable,q as resolveTableCodegen,C as resolveTables,I as scopeWithEnums,G as scopeWithUserTypes,h as validateSchema,O as validateStore,n as validateTable,y as validateTableShorthand,B as validateTables,H as validateUserTypes};
1
+ import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"../chunk-7BUS2KVD.js";export{d as AbiTypeScope,p as CODEGEN_DEFAULTS,b as CONFIG_DEFAULTS,v as NoStaticKeyFieldError,c as Scope,t as TABLE_CODEGEN_DEFAULTS,a as TABLE_DEFAULTS,x as TABLE_DEPLOY_DEFAULTS,j as defineSchema,S as defineStore,u as defineTable,A as defineTableShorthand,D as defineTables,z as expandTableShorthand,g as extendScope,P as extendedScope,E as extractInternalType,o as get,r as getPath,e as hasOwnKey,f as isObject,k as isSchemaInput,w as isTableShorthandInput,F as isUserTypes,l as isValidPrimaryKey,K as mapEnums,m as mergeIfUndefined,L as resolveCodegen,J as resolveEnums,O as resolveNamespace,M as resolveNamespacedTables,i as resolveSchema,R as resolveStore,s as resolveTable,q as resolveTableCodegen,C as resolveTables,I as scopeWithEnums,G as scopeWithUserTypes,N as validateNamespace,h as validateSchema,Q as validateStore,n as validateTable,y as validateTableShorthand,B as validateTables,H as validateUserTypes};
2
2
  //# sourceMappingURL=v2.js.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { d as defineStore } from './store-3b37a8c0.js';
1
+ export { d as defineStore } from './store-122dc6fd.js';
2
2
  export { S as Store } from './input-e69ffb2f.js';
3
3
  import '@arktype/util';
4
4
  import './namespacedTables-264f21b1.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{Q as n}from"./chunk-3PAPLPW2.js";var i="event HelloStore(bytes32 indexed storeVersion)",t="event Store_SetRecord(bytes32 indexed tableId, bytes32[] keyTuple, bytes staticData, bytes32 encodedLengths, bytes dynamicData)",o="event Store_SpliceStaticData(bytes32 indexed tableId, bytes32[] keyTuple, uint48 start, bytes data)",r="event Store_SpliceDynamicData(bytes32 indexed tableId, bytes32[] keyTuple, uint8 dynamicFieldIndex, uint48 start, uint40 deleteCount, bytes32 encodedLengths, bytes data)",s="event Store_DeleteRecord(bytes32 indexed tableId, bytes32[] keyTuple)",e=[t,o,r,s];import{parseAbi as a}from"abitype";var p=a(e);export{n as defineStore,i as helloStoreEvent,s as storeDeleteRecordEvent,e as storeEvents,p as storeEventsAbi,t as storeSetRecordEvent,r as storeSpliceDynamicDataEvent,o as storeSpliceStaticDataEvent};
1
+ import{S as n}from"./chunk-7BUS2KVD.js";var i="event HelloStore(bytes32 indexed storeVersion)",t="event Store_SetRecord(bytes32 indexed tableId, bytes32[] keyTuple, bytes staticData, bytes32 encodedLengths, bytes dynamicData)",o="event Store_SpliceStaticData(bytes32 indexed tableId, bytes32[] keyTuple, uint48 start, bytes data)",r="event Store_SpliceDynamicData(bytes32 indexed tableId, bytes32[] keyTuple, uint8 dynamicFieldIndex, uint48 start, uint40 deleteCount, bytes32 encodedLengths, bytes data)",s="event Store_DeleteRecord(bytes32 indexed tableId, bytes32[] keyTuple)",e=[t,o,r,s];import{parseAbi as a}from"abitype";var p=a(e);export{n as defineStore,i as helloStoreEvent,s as storeDeleteRecordEvent,e as storeEvents,p as storeEventsAbi,t as storeSetRecordEvent,r as storeSpliceDynamicDataEvent,o as storeSpliceStaticDataEvent};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{Q as e}from"./chunk-3PAPLPW2.js";var o=e({codegen:{storeImportPath:"./src"},namespace:"store",userTypes:{ResourceId:{filePath:"./src/ResourceId.sol",type:"bytes32"},FieldLayout:{filePath:"./src/FieldLayout.sol",type:"bytes32"},Schema:{filePath:"./src/Schema.sol",type:"bytes32"}},tables:{StoreHooks:{schema:{tableId:"ResourceId",hooks:"bytes21[]"},key:["tableId"]},Tables:{schema:{tableId:"ResourceId",fieldLayout:"FieldLayout",keySchema:"Schema",valueSchema:"Schema",abiEncodedKeyNames:"bytes",abiEncodedFieldNames:"bytes"},key:["tableId"]},ResourceIds:{schema:{resourceId:"ResourceId",exists:"bool"},key:["resourceId"]},Hooks:{schema:{resourceId:"ResourceId",hooks:"bytes21[]"},key:["resourceId"],codegen:{tableIdArgument:!0}}}});export{o as default};
1
+ import{S as e}from"./chunk-7BUS2KVD.js";var o=e({codegen:{storeImportPath:"./src"},namespace:"store",userTypes:{ResourceId:{filePath:"./src/ResourceId.sol",type:"bytes32"},FieldLayout:{filePath:"./src/FieldLayout.sol",type:"bytes32"},Schema:{filePath:"./src/Schema.sol",type:"bytes32"}},tables:{StoreHooks:{schema:{tableId:"ResourceId",hooks:"bytes21[]"},key:["tableId"]},Tables:{schema:{tableId:"ResourceId",fieldLayout:"FieldLayout",keySchema:"Schema",valueSchema:"Schema",abiEncodedKeyNames:"bytes",abiEncodedFieldNames:"bytes"},key:["tableId"]},ResourceIds:{schema:{resourceId:"ResourceId",exists:"bool"},key:["resourceId"]},Hooks:{schema:{resourceId:"ResourceId",hooks:"bytes21[]"},key:["resourceId"],codegen:{tableIdArgument:!0}}}});export{o as default};
2
2
  //# sourceMappingURL=mud.config.js.map
@@ -1,5 +1,5 @@
1
- import { narrow, ErrorMessage, show } from '@arktype/util';
2
- import { p as parseNumber, m as mergeIfUndefined, C as CODEGEN_DEFAULTS, a as resolveTables, k as expandTableShorthand, g as get, y as validateTables, D as CONFIG_DEFAULTS, r as resolveNamespacedTables, w as resolveTable } from './namespacedTables-264f21b1.js';
1
+ import { ErrorMessage, narrow, show } from '@arktype/util';
2
+ import { p as parseNumber, m as mergeIfUndefined, C as CODEGEN_DEFAULTS, y as validateTables, a as resolveTables, k as expandTableShorthand, g as get, D as CONFIG_DEFAULTS, r as resolveNamespacedTables, w as resolveTable } from './namespacedTables-264f21b1.js';
3
3
  import { U as UserTypes, A as AbiTypeScope, e as extendScope, E as EnumsInput, a as Scope, N as NamespaceInput, l as StoreInput } from './input-e69ffb2f.js';
4
4
 
5
5
  type extractInternalType<userTypes extends UserTypes> = {
@@ -29,6 +29,10 @@ declare function mapEnums<enums extends EnumsInput>(enums: enums): resolveEnums<
29
29
  type resolveCodegen<codegen> = codegen extends {} ? mergeIfUndefined<codegen, CODEGEN_DEFAULTS> : CODEGEN_DEFAULTS;
30
30
  declare function resolveCodegen<codegen>(codegen: codegen): resolveCodegen<codegen>;
31
31
 
32
+ type validateNamespace<input, scope extends Scope = AbiTypeScope> = {
33
+ [key in keyof input]: key extends "tables" ? validateTables<input[key], scope> : key extends keyof NamespaceInput ? NamespaceInput[key] : ErrorMessage<`\`${key & string}\` is not a valid namespace config option.`>;
34
+ };
35
+ declare function validateNamespace<scope extends Scope = AbiTypeScope>(input: unknown, scope: scope): asserts input is NamespaceInput;
32
36
  type resolveNamespace<input, scope extends Scope = AbiTypeScope> = input extends NamespaceInput ? {
33
37
  readonly label: input["label"];
34
38
  readonly namespace: string;
@@ -38,7 +42,7 @@ type resolveNamespace<input, scope extends Scope = AbiTypeScope> = input extends
38
42
  }>;
39
43
  }, scope>;
40
44
  } : never;
41
- declare function resolveNamespace<const input extends NamespaceInput, scope extends Scope = AbiTypeScope>(input: input, scope: scope): resolveNamespace<input, scope>;
45
+ declare function resolveNamespace<const input extends NamespaceInput, scope extends Scope = AbiTypeScope>(input: input, scope?: scope): resolveNamespace<input, scope>;
42
46
 
43
47
  type extendedScope<input> = scopeWithEnums<get<input, "enums">, scopeWithUserTypes<get<input, "userTypes">>>;
44
48
  declare function extendedScope<input>(input: input): extendedScope<input>;
@@ -69,4 +73,4 @@ type resolveStore<input, namespace = "namespace" extends keyof input ? input["na
69
73
  declare function resolveStore<const input extends StoreInput>(input: input): resolveStore<input>;
70
74
  declare function defineStore<const input>(input: validateStore<input>): show<resolveStore<input>>;
71
75
 
72
- export { resolveCodegen as a, resolveEnums as b, extractInternalType as c, defineStore as d, extendedScope as e, scopeWithUserTypes as f, validateUserTypes as g, isUserTypes as i, mapEnums as m, resolveStore as r, scopeWithEnums as s, validateStore as v };
76
+ export { resolveCodegen as a, resolveEnums as b, extractInternalType as c, defineStore as d, extendedScope as e, scopeWithUserTypes as f, validateUserTypes as g, validateNamespace as h, isUserTypes as i, resolveNamespace as j, mapEnums as m, resolveStore as r, scopeWithEnums as s, validateStore as v };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@latticexyz/store",
3
- "version": "3.0.0-main-69eb63b59",
3
+ "version": "3.0.0-main-93749bdb6",
4
4
  "description": "Store",
5
5
  "repository": {
6
6
  "type": "git",
@@ -46,10 +46,10 @@
46
46
  "abitype": "1.0.0",
47
47
  "arktype": "1.0.29-alpha",
48
48
  "viem": "2.9.20",
49
- "@latticexyz/common": "3.0.0-main-69eb63b59",
50
- "@latticexyz/config": "3.0.0-main-69eb63b59",
51
- "@latticexyz/protocol-parser": "3.0.0-main-69eb63b59",
52
- "@latticexyz/schema-type": "3.0.0-main-69eb63b59"
49
+ "@latticexyz/common": "3.0.0-main-93749bdb6",
50
+ "@latticexyz/config": "3.0.0-main-93749bdb6",
51
+ "@latticexyz/protocol-parser": "3.0.0-main-93749bdb6",
52
+ "@latticexyz/schema-type": "3.0.0-main-93749bdb6"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@arktype/attest": "0.7.5",
@@ -62,8 +62,8 @@
62
62
  "tsup": "^6.7.0",
63
63
  "tsx": "^3.12.6",
64
64
  "vitest": "0.34.6",
65
- "@latticexyz/abi-ts": "3.0.0-main-69eb63b59",
66
- "@latticexyz/gas-report": "3.0.0-main-69eb63b59"
65
+ "@latticexyz/gas-report": "3.0.0-main-93749bdb6",
66
+ "@latticexyz/abi-ts": "3.0.0-main-93749bdb6"
67
67
  },
68
68
  "scripts": {
69
69
  "build": "pnpm run build:tightcoder && pnpm run build:mud && pnpm run build:abi && pnpm run build:abi-ts && pnpm run build:js",