@budibase/server 3.3.3 → 3.3.4

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.
@@ -9,8 +9,8 @@
9
9
  <link href="/builder/fonts/source-sans-pro/600.css" rel="stylesheet" />
10
10
  <link href="/builder/fonts/source-sans-pro/700.css" rel="stylesheet" />
11
11
  <link href="/builder/fonts/remixicon.css" rel="stylesheet" />
12
- <script type="module" crossorigin src="/builder/assets/index-5fd1bf1c.js"></script>
13
- <link rel="stylesheet" href="/builder/assets/index-5c106eca.css">
12
+ <script type="module" crossorigin src="/builder/assets/index-3199ca61.js"></script>
13
+ <link rel="stylesheet" href="/builder/assets/index-fae37678.css">
14
14
  </head>
15
15
 
16
16
  <body id="app">
@@ -380,7 +380,7 @@ function print() { __p += __j.call(arguments, '') }
380
380
  </g>
381
381
  </g>
382
382
  </svg>
383
- `;var HTTPMethod=(p=>(p.POST="POST",p.PATCH="PATCH",p.GET="GET",p.PUT="PUT",p.DELETE="DELETE",p))(HTTPMethod||{});const BannedSearchTypes=[FieldType.LINK,FieldType.ATTACHMENT_SINGLE,FieldType.ATTACHMENTS,FieldType.FORMULA,FieldType.JSON,FieldType.ATTACHMENT_SINGLE,FieldType.SIGNATURE_SINGLE,"jsonarray","queryarray"],Cookies={Auth:"budibase:auth",CurrentApp:"budibase:currentapp",ReturnUrl:"budibase:returnurl",AccountReturnUrl:"budibase:account:returnurl",OnboardingProcessCorrelationKey:BpmCorrelationKey.ONBOARDING};var TableNames=(p=>(p.USERS="ta_users",p))(TableNames||{});const BudibaseRoles={AppUser:"appUser",Developer:"developer",Creator:"creator",Admin:"admin",Owner:"owner"},BudibaseRoleOptionsOld=[{label:"Developer",value:BudibaseRoles.Developer}],BudibaseRoleOptions=[{label:"Account admin",value:BudibaseRoles.Admin,subtitle:"Has full access to all apps and settings in your account",sortOrder:1},{label:"Creator",value:BudibaseRoles.Creator,subtitle:"Can create and edit apps they have access to",sortOrder:2},{label:"App user",value:BudibaseRoles.AppUser,subtitle:"Can only use published apps they have access to",sortOrder:3}],ExtendedBudibaseRoleOptions=[{label:"Account holder",value:BudibaseRoles.Owner,sortOrder:0},...BudibaseRoleOptions,...BudibaseRoleOptionsOld],PlanType={FREE:"free",TEAM:"team",PRO:"pro",BUSINESS:"business",PREMIUM:"premium",ENTERPRISE:"enterprise",ENTERPRISE_BASIC_TRIAL:"enterprise_basic_trial"},ApiVersion="1",Roles={ADMIN:"ADMIN",POWER:"POWER",BASIC:"BASIC",PUBLIC:"PUBLIC",BUILDER:"BUILDER",CREATOR:"CREATOR"},EventPublishType={ENV_VAR_UPGRADE_PANEL_OPENED:"environment_variable_upgrade_panel_opened"},ContextScopes={Local:"local",Global:"global"},TypeIconMap={[FieldType.STRING]:"Text",[FieldType.OPTIONS]:"Dropdown",[FieldType.DATETIME]:"Calendar",[FieldType.BARCODEQR]:"Camera",[FieldType.SIGNATURE_SINGLE]:"AnnotatePen",[FieldType.LONGFORM]:"TextAlignLeft",[FieldType.ARRAY]:"Duplicate",[FieldType.NUMBER]:"123",[FieldType.BOOLEAN]:"Boolean",[FieldType.ATTACHMENTS]:"DocumentFragmentGroup",[FieldType.ATTACHMENT_SINGLE]:"DocumentFragment",[FieldType.LINK]:"DataCorrelated",[FieldType.FORMULA]:"Calculator",[FieldType.AI]:"MagicWand",[FieldType.JSON]:"Brackets",[FieldType.BIGINT]:"TagBold",[FieldType.AUTO]:"Shapes",[FieldType.BB_REFERENCE]:{[BBReferenceFieldSubType.USER]:"UserGroup",[BBReferenceFieldSubType.USERS]:"UserGroup"},[FieldType.BB_REFERENCE_SINGLE]:{[BBReferenceFieldSubType.USER]:"User"}},OptionColours=[...new Array(12).keys()].map(p=>`hsla(${(p+1)*222%360}, 90%, 75%, 0.3)`),FilterOperator={ANY:"any",ALL:"all"},OnEmptyFilter={RETURN_ALL:"all",RETURN_NONE:"none"},FilterValueType={BINDING:"Binding",VALUE:"Value"},FieldPermissions={WRITABLE:"writable",READONLY:"readonly",HIDDEN:"hidden"},Constants$2=Object.freeze(Object.defineProperty({__proto__:null,ApiVersion,BannedSearchTypes,BudibaseRoleOptions,BudibaseRoleOptionsOld,BudibaseRoles,ContextScopes,Cookies,DEFAULT_BB_DATASOURCE_ID,EventPublishType,ExtendedBudibaseRoleOptions,Features:Feature,FieldPermissions,FilterOperator,FilterValueType,OnEmptyFilter,OperatorOptions,OptionColours,PlanType,Roles,SqlNumberTypeRangeMap,TableNames,TypeIconMap},Symbol.toStringTag,{value:"Module"})),buildAnalyticsEndpoints=p=>({getAnalyticsStatus:async()=>await p.get({url:"/api/bbtel"}),analyticsPing:async u=>await p.post({url:"/api/bbtel/ping",body:{...u,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})}),buildAIEndpoints=p=>({generateCronExpression:async u=>await p.post({url:"/api/ai/cron",body:{prompt:u}})}),buildAppEndpoints=p=>({fetchAppPackage:async u=>await p.get({url:`/api/applications/${u}/appPackage`}),saveAppMetadata:async(u,f)=>await p.put({url:`/api/applications/${u}`,body:f}),publishAppChanges:async u=>await p.post({url:`/api/applications/${u}/publish`}),revertAppChanges:async u=>await p.post({url:`/api/dev/${u}/revert`}),updateAppClientVersion:async u=>await p.post({url:`/api/applications/${u}/client/update`}),revertAppClientVersion:async u=>await p.post({url:`/api/applications/${u}/client/revert`}),getAppDeployments:async()=>await p.get({url:"/api/deployments"}),createApp:async u=>await p.post({url:"/api/applications",body:u,json:!1}),duplicateApp:async(u,f)=>await p.post({url:`/api/applications/${u}/duplicate`,body:f,json:!1}),updateAppFromExport:async(u,f)=>{const m=getDevAppID(u);return await p.post({url:`/api/applications/${m}/import`,body:f,json:!1})},importApps:async u=>await p.post({url:"/api/cloud/import",body:u,json:!1}),unpublishApp:async u=>await p.post({url:`/api/applications/${u}/unpublish`}),deleteApp:async u=>await p.delete({url:`/api/applications/${u}`}),releaseAppLock:async u=>await p.delete({url:`/api/dev/${u}/lock`}),fetchSystemDebugInfo:async()=>await p.get({url:"/api/debug/diagnostics"}),syncApp:async u=>await p.post({url:`/api/applications/${u}/sync`}),getApps:async()=>await p.get({url:"/api/applications?status=all"}),fetchComponentLibDefinitions:async u=>await p.get({url:`/api/${u}/components/definitions`}),addSampleData:async u=>await p.post({url:`/api/applications/${u}/sample`}),setRevertableVersion:async(u,f)=>await p.post({url:`/api/applications/${u}/setRevertableVersion`,body:{revertableVersion:f}})}),buildAttachmentEndpoints=p=>{const u={getSignedDatasourceURL:async(f,m,v)=>await p.post({url:`/api/attachments/${f}/url`,body:{bucket:m,key:v}})};return{...u,uploadAttachment:async(f,m)=>await p.post({url:`/api/attachments/${f}/upload`,body:m,json:!1}),uploadBuilderAttachment:async f=>await p.post({url:"/api/attachments/process",body:f,json:!1}),externalUpload:async(f,m,v,y)=>{const{signedUrl:w,publicUrl:k}=await u.getSignedDatasourceURL(f,m,v);return w?(await p.put({url:w,body:y,json:!1,external:!0,parseResponse:S=>S}),{publicUrl:k}):{publicUrl:void 0}},downloadAttachment:async(f,m,v)=>await p.get({url:`/api/${f}/rows/${m}/attachment/${v}`,parseResponse:y=>y,suppressErrors:!0})}},buildAuthEndpoints=p=>({logIn:async(u,f,m)=>await p.post({url:`/api/global/auth/${u}/login`,body:{username:f,password:m}}),logOut:async()=>await p.post({url:"/api/global/auth/logout"}),setInitInfo:async u=>await p.post({url:"/api/global/auth/init",body:u}),getInitInfo:async()=>await p.get({url:"/api/global/auth/init"}),requestForgotPassword:async(u,f)=>await p.post({url:`/api/global/auth/${u}/reset`,body:{email:f}}),resetPassword:async(u,f,m)=>await p.post({url:`/api/global/auth/${u}/reset/update`,body:{password:f,resetCode:m}})}),buildAutomationEndpoints=p=>({triggerAutomation:async(u,f,m)=>await p.post({url:`/api/automations/${u}/trigger`,body:{fields:f,timeout:m}}),testAutomation:async(u,f)=>await p.post({url:`/api/automations/${u}/test`,body:f}),getAutomations:async()=>await p.get({url:"/api/automations"}),getAutomationDefinitions:async()=>await p.get({url:"/api/automations/definitions/list"}),createAutomation:async u=>await p.post({url:"/api/automations",body:u}),updateAutomation:async u=>await p.put({url:"/api/automations",body:u}),deleteAutomation:async(u,f)=>await p.delete({url:`/api/automations/${u}/${f}`}),getAutomationLogs:async u=>await p.post({url:"/api/automations/logs/search",body:u}),clearAutomationLogErrors:async(u,f)=>await p.delete({url:"/api/automations/logs",body:{appId:f,automationId:u}})}),buildConfigEndpoints=p=>({saveConfig:async u=>await p.post({url:"/api/global/configs",body:u}),getConfig:async u=>await p.get({url:`/api/global/configs/${u}`}),deleteConfig:async(u,f)=>await p.delete({url:`/api/global/configs/${u}/${f}`}),getTenantConfig:async u=>await p.get({url:`/api/global/configs/public?tenantId=${u}`}),getOIDCConfigs:async u=>await p.get({url:`/api/global/configs/public/oidc?tenantId=${u}`}),getChecklist:async u=>await p.get({url:`/api/global/configs/checklist?tenantId=${u}`}),uploadLogo:async u=>await p.post({url:"/api/global/configs/upload/settings/logoUrl",body:u,json:!1}),uploadFavicon:async u=>await p.post({url:"/api/global/configs/upload/settings/faviconUrl",body:u,json:!1}),uploadOIDCLogo:async(u,f)=>await p.post({url:`/api/global/configs/upload/logos_oidc/${u}`,body:f,json:!1}),getOIDCLogos:async()=>await p.get({url:"/api/global/configs/logos_oidc"})}),buildDatasourceEndpoints=p=>({getDatasources:async()=>await p.get({url:"/api/datasources"}),buildDatasourceSchema:async(u,f)=>await p.post({url:`/api/datasources/${u}/schema`,body:{tablesFilter:f}}),createDatasource:async u=>await p.post({url:"/api/datasources",body:u}),updateDatasource:async u=>await p.put({url:`/api/datasources/${u._id}`,body:u}),deleteDatasource:async(u,f)=>await p.delete({url:`/api/datasources/${u}/${f}`}),validateDatasource:async u=>await p.post({url:"/api/datasources/verify",body:{datasource:u}}),fetchInfoForDatasource:async u=>await p.post({url:"/api/datasources/info",body:{datasource:u}}),fetchExternalSchema:async u=>await p.get({url:`/api/datasources/${u}/schema/external`})}),buildFlagEndpoints=p=>({getFlags:async()=>await p.get({url:"/api/users/flags"}),updateFlag:async(u,f)=>await p.post({url:"/api/users/flags",body:{flag:u,value:f}}),toggleUiFeature:async u=>await p.post({url:`/api/beta/${u}`})}),buildLayoutEndpoints=p=>({saveLayout:async u=>await p.post({url:"/api/layouts",body:u}),deleteLayout:async(u,f)=>await p.delete({url:`/api/layouts/${u}/${f}`})}),buildOtherEndpoints=p=>({getEnvironment:async()=>await p.get({url:"/api/system/environment"}),getSystemStatus:async()=>await p.get({url:"/api/system/status"}),getIntegrations:async()=>await p.get({url:"/api/integrations"}),getBudibaseVersion:async()=>(await p.get({url:"/api/dev/version"})).version,getBasePermissions:async()=>await p.get({url:"/api/permission/builtin"})}),buildPermissionsEndpoints=p=>({getPermissionForResource:async u=>await p.get({url:`/api/permission/${u}`}),updatePermissionForResource:async(u,f,m)=>await p.post({url:`/api/permission/${f}/${u}/${m}`}),removePermissionFromResource:async(u,f,m)=>await p.delete({url:`/api/permission/${f}/${u}/${m}`}),getDependants:async u=>await p.get({url:`/api/permission/${u}/dependants`})}),buildQueryEndpoints=p=>({executeQuery:async(u,{pagination:f,parameters:m}={})=>await p.post({url:`/api/v2/queries/${u}`,body:{parameters:m,pagination:f}}),fetchQueryDefinition:async u=>await p.get({url:`/api/queries/${u}`,cache:!0}),getQueries:async()=>await p.get({url:"/api/queries"}),saveQuery:async u=>await p.post({url:"/api/queries",body:u}),deleteQuery:async(u,f)=>await p.delete({url:`/api/queries/${u}/${f}`}),importQueries:async u=>await p.post({url:"/api/queries/import",body:u}),previewQuery:async u=>await p.post({url:"/api/queries/preview",body:u})}),buildRelationshipEndpoints=p=>({fetchRelationshipData:async(u,f,m)=>{const v=await p.get({url:`/api/${u}/${f}/enrich?field=${m}`});return m?v[m]||[]:[v]}}),buildRoleEndpoints=p=>({deleteRole:async(u,f)=>await p.delete({url:`/api/roles/${u}/${f}`}),saveRole:async u=>await p.post({url:"/api/roles",body:u}),getRoles:async()=>await p.get({url:"/api/roles"}),getRolesForApp:async u=>await p.get({url:`/api/global/roles/${u}`}),getAccessibleRoles:async()=>await p.get({url:"/api/roles/accessible"})}),buildRouteEndpoints=p=>({fetchClientAppRoutes:async()=>await p.get({url:"/api/routing/client"}),fetchAppRoutes:async()=>await p.get({url:"/api/routing"})}),buildRowEndpoints=p=>({fetchRow:async(u,f)=>await p.get({url:`/api/${u}/rows/${f}`}),saveRow:async(u,f=!1)=>{const m=u._viewId||u.tableId;return await p.post({url:`/api/${m}/rows`,body:u,suppressErrors:f})},patchRow:async(u,f=!1)=>{const m=u._viewId||u.tableId;return await p.patch({url:`/api/${m}/rows`,body:u,suppressErrors:f})},deleteRow:async(u,f)=>await p.delete({url:`/api/${u}/rows`,body:{_id:f}}),deleteRows:async(u,f)=>(f.forEach(m=>{typeof m=="object"&&(m==null||delete m._viewId)}),await p.delete({url:`/api/${u}/rows`,body:{rows:f}})),exportRows:async(u,f,m)=>await p.post({url:`/api/${u}/rows/exportRows?format=${f}`,body:m,parseResponse:async v=>await v.text()})}),buildScreenEndpoints=p=>({saveScreen:async u=>await p.post({url:"/api/screens",body:u}),deleteScreen:async(u,f)=>await p.delete({url:`/api/screens/${u}/${f}`})}),buildTableEndpoints=p=>({fetchTableDefinition:async u=>await p.get({url:`/api/tables/${u}`,cache:!0}),fetchTableData:async u=>await p.get({url:`/api/${u}/rows`}),searchTable:async(u,f)=>await p.post({url:`/api/${u}/search`,body:f}),importTableData:async(u,f,m)=>await p.post({url:`/api/tables/${u}/import`,body:{rows:f,identifierFields:m}}),csvToJson:async u=>await p.post({url:"/api/convert/csvToJson",body:{csvString:u}}),getTables:async()=>await p.get({url:"/api/tables"}),getTable:async u=>await p.get({url:`/api/tables/${u}`}),saveTable:async u=>await p.post({url:"/api/tables",body:u}),deleteTable:async(u,f)=>await p.delete({url:`/api/tables/${u}/${f}`}),validateNewTableImport:async(u,f)=>await p.post({url:"/api/tables/validateNewTableImport",body:{rows:u,schema:f}}),validateExistingTableImport:async(u,f)=>await p.post({url:"/api/tables/validateExistingTableImport",body:{rows:u,tableId:f}}),migrateColumn:async(u,f,m)=>await p.post({url:`/api/tables/${u}/migrate`,body:{oldColumn:f,newColumn:m}})}),buildTemplateEndpoints=p=>({getEmailTemplateDefinitions:async()=>await p.get({url:"/api/global/template/definitions"}),getEmailTemplates:async()=>await p.get({url:"/api/global/template/email"}),saveEmailTemplate:async u=>await p.post({url:"/api/global/template",body:u}),getAppTemplates:async()=>await p.get({url:"/api/templates"})}),buildUserEndpoints=p=>({getUsers:async()=>await p.get({url:"/api/global/users"}),searchUsers:async u=>await p.post({url:"/api/global/users/search",body:u}),getUser:async u=>await p.get({url:`/api/global/users/${u}`}),updateOwnMetadata:async u=>await p.post({url:"/api/users/metadata/self",body:u}),createAdminUser:async u=>await p.post({url:"/api/global/users/init",body:u}),saveUser:async u=>await p.post({url:"/api/global/users",body:u}),createUsers:async(u,f)=>(await p.post({url:"/api/global/users/bulk",body:{create:{users:u,groups:f}}})).created,deleteUser:async u=>await p.delete({url:`/api/global/users/${u}`}),deleteUsers:async u=>(await p.post({url:"/api/global/users/bulk",body:{delete:{users:u}}})).deleted,onboardUsers:async u=>await p.post({url:"/api/global/users/onboard",body:u}),updateUserInvite:async(u,f)=>await p.post({url:`/api/global/users/invite/update/${u}`,body:f}),getUserInvite:async u=>await p.get({url:`/api/global/users/invite/${u}`}),getUserInvites:async()=>await p.get({url:"/api/global/users/invites"}),inviteUsers:async u=>await p.post({url:"/api/global/users/multi/invite",body:u}),removeUserInvites:async u=>await p.post({url:"/api/global/users/multi/invite/delete",body:u}),acceptInvite:async u=>await p.post({url:"/api/global/users/invite/accept",body:u}),getUserCountByApp:async u=>(await p.get({url:`/api/global/users/count/${u}`})).userCount,addAppBuilder:async(u,f)=>await p.post({url:`/api/global/users/${u}/app/${f}/builder`}),removeAppBuilder:async(u,f)=>await p.delete({url:`/api/global/users/${u}/app/${f}/builder`}),getAccountHolder:async()=>await p.get({url:"/api/global/users/accountholder"})}),buildSelfEndpoints=p=>({generateAPIKey:async()=>{const u=await p.post({url:"/api/global/self/api_key"});return u==null?void 0:u.apiKey},fetchDeveloperInfo:async()=>p.get({url:"/api/global/self/api_key"}),fetchSelf:async()=>await p.get({url:"/api/self"}),fetchBuilderSelf:async()=>await p.get({url:"/api/global/self"}),updateSelf:async u=>await p.post({url:"/api/global/self",body:u})}),buildViewEndpoints=p=>({fetchViewData:async(u,{field:f,groupBy:m,calculation:v})=>{const y=new URLSearchParams;v&&(f&&y.set("field",f),y.set("calculation",v)),m&&y.set("group",m);const w=f?`/api/views/${encodeURIComponent(u)}?${y}`:`/api/views/${encodeURIComponent(u)}`;return await p.get({url:w})},exportView:async(u,f)=>{const m=encodeURIComponent(u);return await p.get({url:`/api/views/export?view=${m}&format=${f}`,parseResponse:async v=>await v.text()})},saveView:async u=>await p.post({url:"/api/views",body:u}),deleteView:async u=>await p.delete({url:`/api/views/${encodeURIComponent(u)}`})}),buildViewV2Endpoints=p=>({fetchDefinition:async u=>await p.get({url:`/api/v2/views/${encodeURIComponent(u)}`,cache:!0}),create:async u=>await p.post({url:"/api/v2/views",body:u}),update:async u=>await p.put({url:`/api/v2/views/${encodeURIComponent(u.id)}`,body:u}),fetch:async(u,f)=>await p.post({url:`/api/v2/views/${encodeURIComponent(u)}/search`,body:f}),delete:async u=>await p.delete({url:`/api/v2/views/${encodeURIComponent(u)}`})}),buildLicensingEndpoints=p=>({activateLicenseKey:async u=>p.post({url:"/api/global/license/key",body:{licenseKey:u}}),deleteLicenseKey:async()=>p.delete({url:"/api/global/license/key"}),getLicenseKey:async()=>{try{return await p.get({url:"/api/global/license/key"})}catch(u){if(u.status!==404)throw u}},activateOfflineLicense:async u=>p.post({url:"/api/global/license/offline",body:{offlineLicenseToken:u}}),deleteOfflineLicense:async()=>p.delete({url:"/api/global/license/offline"}),getOfflineLicense:async()=>{try{return await p.get({url:"/api/global/license/offline"})}catch(u){if(u.status!==404)throw u}},getOfflineLicenseIdentifier:async()=>await p.get({url:"/api/global/license/offline/identifier"}),refreshLicense:async()=>p.post({url:"/api/global/license/refresh"}),getQuotaUsage:async()=>p.get({url:"/api/global/license/usage"})}),buildGroupsEndpoints=p=>{async function u(f,m,v,y){return await p.post({url:`/api/global/groups/${f}/${m}`,body:{[v]:y}})}return{saveGroup:async f=>await p.post({url:"/api/global/groups",body:f}),getGroups:async()=>(await p.get({url:"/api/global/groups"})).data,getGroup:async f=>await p.get({url:`/api/global/groups/${f}`}),deleteGroup:async(f,m)=>await p.delete({url:`/api/global/groups/${f}/${m}`}),getGroupUsers:async({id:f,bookmark:m,emailSearch:v})=>{let y=`/api/global/groups/${f}/users?`;return m&&(y+=`bookmark=${m}&`),v&&(y+=`emailSearch=${v}`),await p.get({url:y})},addUsersToGroup:async(f,m)=>u(f,"users","add",m),removeUsersFromGroup:async(f,m)=>u(f,"users","remove",m),addAppsToGroup:async(f,m)=>u(f,"apps","add",m),removeAppsFromGroup:async(f,m)=>u(f,"apps","remove",m),addGroupAppBuilder:async(f,m)=>await p.post({url:`/api/global/groups/${f}/app/${m}/builder`}),removeGroupAppBuilder:async(f,m)=>await p.delete({url:`/api/global/groups/${f}/app/${m}/builder`})}},buildPluginEndpoints=p=>({uploadPlugin:async u=>await p.post({url:"/api/plugin/upload",body:u,json:!1}),createPlugin:async u=>await p.post({url:"/api/plugin",body:u}),getPlugins:async()=>await p.get({url:"/api/plugin"}),deletePlugin:async u=>await p.delete({url:`/api/plugin/${u}`})}),buildBackupEndpoints=p=>({createManualBackup:async u=>await p.post({url:`/api/apps/${u}/backups`}),searchBackups:async(u,f)=>await p.post({url:`/api/apps/${u}/backups/search`,body:f}),deleteBackup:async(u,f)=>await p.delete({url:`/api/apps/${u}/backups/${f}`}),restoreBackup:async(u,f,m)=>await p.post({url:`/api/apps/${u}/backups/${f}/import`,body:{name:m}})}),buildEnvironmentVariableEndpoints=p=>({checkEnvironmentVariableStatus:async()=>await p.get({url:"/api/env/variables/status"}),fetchEnvironmentVariables:async()=>await p.get({url:"/api/env/variables",json:!1}),createEnvironmentVariable:async u=>await p.post({url:"/api/env/variables",body:u}),deleteEnvironmentVariable:async u=>await p.delete({url:`/api/env/variables/${u}`}),updateEnvironmentVariable:async(u,f)=>await p.patch({url:`/api/env/variables/${u}`,body:f})}),buildEventEndpoints=p=>({publishEvent:async u=>await p.post({url:"/api/global/event/publish",body:{type:u}})}),buildAuditLogEndpoints=p=>({searchAuditLogs:async u=>await p.post({url:"/api/global/auditlogs/search",body:u}),getEventDefinitions:async()=>await p.get({url:"/api/global/auditlogs/definitions"}),getDownloadUrl:u=>`/api/global/auditlogs/download?query=${encodeURIComponent(JSON.stringify(u))}`}),buildLogsEndpoints=p=>({getSystemLogs:async()=>await p.get({url:"/api/system/logs",json:!1,parseResponse:async u=>u})}),buildMigrationEndpoints=p=>({getMigrationStatus:async()=>await p.get({url:"/api/migrations/status"})}),buildRowActionEndpoints=p=>({fetch:async u=>(await p.get({url:`/api/tables/${u}/actions`})).actions,create:async(u,f)=>await p.post({url:`/api/tables/${u}/actions`,body:{name:f}}),delete:async(u,f)=>await p.delete({url:`/api/tables/${u}/actions/${f}`}),enableView:async(u,f,m)=>await p.post({url:`/api/tables/${u}/actions/${f}/permissions/${m}`}),disableView:async(u,f,m)=>await p.delete({url:`/api/tables/${u}/actions/${f}/permissions/${m}`}),trigger:async(u,f,m)=>await p.post({url:`/api/tables/${u}/actions/${f}/trigger`,body:{rowId:m}})}),APISessionID=uuid(),createAPIClient=(p={})=>{let u={};const f=async(M,T,E=!1)=>{let H=M.statusText,F=null;try{F=await M.json(),F!=null&&F.message?H=F.message:F!=null&&F.error&&(H=JSON.stringify(F.error))}catch{}return{message:H,json:F,status:M.status,url:M.url,method:T,handled:!0,suppressErrors:E}},m=(M,T,E)=>({message:M,json:null,status:400,url:T,method:E,handled:!0,suppressErrors:!1}),v=async M=>{let{json:T,method:E,external:H,body:F,url:Z,parseResponse:$,suppressErrors:J}=M;T=T&&E!==HTTPMethod.GET;let ae={Accept:"application/json"};ae[Header.SESSION_ID]=APISessionID,H||(ae[Header.API_VER]=ApiVersion),T&&(ae["Content-Type"]="application/json"),p!=null&&p.attachHeaders&&p.attachHeaders(ae);let ie=F;if(T)try{ie=JSON.stringify(F)}catch{throw m("Invalid JSON body",Z,E)}let he;try{he=await fetch(Z,{method:E,headers:ae,body:ie,credentials:"same-origin"})}catch{throw delete u[Z],m("Failed to send request",Z,E)}if(he.status>=200&&he.status<400){y(he);try{return he.status===204?void 0:$?await $(he):await he.json()}catch(fe){throw delete u[Z],`Failed to parse response: ${fe}`}}else throw delete u[Z],await f(he,E,J)},y=M=>{if(!p.onMigrationDetected)return;const T=M.headers.get(Header.MIGRATING_APP);T&&p.onMigrationDetected(T)},w=async M=>{const T=M.url;return u[T]||(u[T]=v(M),u[T]=await u[T]),await u[T]},k=M=>async T=>{try{let E={json:!0,external:!1,suppressErrors:!1,cache:!1,method:M,...T},{url:H,cache:F,external:Z}=E;return Z||(E.url=`/${H}`.replace("//","/")),await(F&&(p==null?void 0:p.enableCaching)?w:v)(E)}catch(E){throw p!=null&&p.onError&&p.onError(E),E}};let S={post:k(HTTPMethod.POST),get:k(HTTPMethod.GET),patch:k(HTTPMethod.PATCH),delete:k(HTTPMethod.DELETE),put:k(HTTPMethod.PUT),invalidateCache:()=>{u={}},getAppID:()=>{var T;let M={};return(T=p==null?void 0:p.attachHeaders)==null||T.call(p,M),M==null?void 0:M[Header.APP_ID]}};return{...S,...buildAIEndpoints(S),...buildAnalyticsEndpoints(S),...buildAppEndpoints(S),...buildAttachmentEndpoints(S),...buildAuthEndpoints(S),...buildAutomationEndpoints(S),...buildConfigEndpoints(S),...buildDatasourceEndpoints(S),...buildFlagEndpoints(S),...buildLayoutEndpoints(S),...buildOtherEndpoints(S),...buildPermissionsEndpoints(S),...buildQueryEndpoints(S),...buildRelationshipEndpoints(S),...buildRoleEndpoints(S),...buildRouteEndpoints(S),...buildRowEndpoints(S),...buildScreenEndpoints(S),...buildTableEndpoints(S),...buildTemplateEndpoints(S),...buildUserEndpoints(S),...buildViewEndpoints(S),...buildSelfEndpoints(S),...buildLicensingEndpoints(S),...buildGroupsEndpoints(S),...buildPluginEndpoints(S),...buildBackupEndpoints(S),...buildEnvironmentVariableEndpoints(S),...buildEventEndpoints(S),...buildAuditLogEndpoints(S),...buildLogsEndpoints(S),...buildMigrationEndpoints(S),viewV2:buildViewV2Endpoints(S),rowActions:buildRowActionEndpoints(S)}},getJSONArrayDatasourceSchema=(p,u)=>{let f=p,m=[];u.prefixKeys&&(m=u.prefixKeys.concat(["schema"])),m=m.concat(u.label.split(".").slice(2));for(let v=0;v<m.length;v++)f=f==null?void 0:f[m[v]],f!=null&&f.schema&&(f=f.schema);return convertJSONSchemaToTableSchema(f,{squashObjects:!0,prefixKeys:m})},convertJSONSchemaToTableSchema=(p,u)=>{if(!p)return null;u={squashObjects:!1,prefixKeys:null,...u},p.schema?p=p.schema:p={value:p};const f=extractJSONSchemaKeys(p,u.squashObjects);let m={};return f.forEach(({key:v,type:y})=>{m[v]={type:y,name:v,prefixKeys:u.prefixKeys}}),m},extractJSONSchemaKeys=(p,u=!1)=>{if(!p||!Object.keys(p).length)return[];let f=[];return Object.keys(p).forEach(m=>{const v=p[m].type;if(v==="json"&&u){const y=extractJSONSchemaKeys(p[m].schema,u);f=f.concat(y.map(w=>({key:`${m}.${w.key}`,type:w.type})))}else f.push({key:m,type:v==="array"?"jsonarray":v})}),f},generateQueryArraySchemas=(p,u)=>{var f,m;for(let v in p)((f=p[v])==null?void 0:f.type)==="json"&&((m=p[v])==null?void 0:m.subtype)==="array"&&hasSchema(u[v])&&(p[v]={schema:{schema:Object.entries(u[v]||{}).reduce((y,[w,k])=>(y[w]={name:w,type:k.type,subtype:k.subtype},y),{}),type:"json"},type:"json",subtype:"array"});return p};function setCookie(p,u,f){getCookie(p)&&removeCookie(p);let m=`${p}=${u}; Path=/;`;f&&(m+=` Domain=${f};`),window.document.cookie=m}function getCookie(p){const f=`; ${document.cookie}`.split(`; ${p}=`);if(f.length===2)return f[1].split(";").shift()}function removeCookie(p){getCookie(p)&&(document.cookie=`${p}=; Max-Age=-99999999; Path=/;`)}const RolePriorities={[Roles.ADMIN]:5,[Roles.CREATOR]:4,[Roles.POWER]:3,[Roles.BASIC]:2,[Roles.PUBLIC]:1},getRolePriority=p=>RolePriorities[p]??0,sleep=p=>new Promise(u=>setTimeout(u,p)),debounce=(p,u=1e3)=>{let f;return async(...m)=>new Promise(v=>{f&&clearTimeout(f),f=setTimeout(async()=>{v(await p(...m))},u)})},throttle=(p,u=1e3)=>{let f,m=!1,v=!1;const y=(...w)=>{if(f=w,m){v=!0;return}p(...f),m=!0,setTimeout(()=>{m=!1,v&&(v=!1,y(...f))},u)};return y},domDebounce=p=>{let u=!1,f;return(...m)=>{f=m,u||(u=!0,requestAnimationFrame(()=>{p(...f),u=!1}))}},buildFormBlockButtonConfig=p=>{const{_id:u,actionType:f,dataSource:m,notificationOverride:v,actionUrl:y,showDeleteButton:w,deleteButtonLabel:k,showSaveButton:S,saveButtonLabel:M}=p||{};if(!u)return;const T=`${u}-form`,E=`${u}-repeater`,H=m==null?void 0:m.resourceId,F=w===!1?"":k==null?void 0:k.trim(),Z=S===!1?"":M==null?void 0:M.trim(),$=[{"##eventHandlerType":"Validate Form",parameters:{componentId:T}},{"##eventHandlerType":"Save Row",parameters:{providerId:T,tableId:H,notificationOverride:v,confirm:null}},{"##eventHandlerType":"Close Screen Modal"},{"##eventHandlerType":"Close Side Panel"},{"##eventHandlerType":"Close Modal"},...f!=="Create"?[]:[{"##eventHandlerType":"Clear Form",parameters:{componentId:T}}],...y?[{"##eventHandlerType":"Navigate To",parameters:{url:y}}]:[]],J=[{"##eventHandlerType":"Delete Row",parameters:{confirm:!0,tableId:H,rowId:`{{ ${makePropSafe(E)}.${makePropSafe("_id")} }}`,revId:`{{ ${makePropSafe(E)}.${makePropSafe("_rev")} }}`,notificationOverride:v}},{"##eventHandlerType":"Close Screen Modal"},{"##eventHandlerType":"Close Side Panel"},{"##eventHandlerType":"Close Modal"},...y?[{"##eventHandlerType":"Navigate To",parameters:{url:y}}]:[]],ae=[];return["Update","Create"].includes(f)&&S!==!1&&ae.push({text:Z||"Save",_id:uuid(),_component:"@budibase/standard-components/button",onClick:$,type:"cta"}),f==="Update"&&w!==!1&&ae.push({text:F||"Delete",_id:uuid(),_component:"@budibase/standard-components/button",onClick:J,quiet:!0,type:"warning"}),ae},buildMultiStepFormBlockDefaultProps=p=>{const{_id:u,stepCount:f,currentStep:m,actionType:v,dataSource:y}=p||{};if(!u||!f)return;const w=`Step {{ [${u}-form].[__currentStep] }}`,k=y==null?void 0:y.resourceId,S=`${u}-form`;let M=[];return m!==0&&M.push({_id:uuid(),_component:"@budibase/standard-components/button",_instanceName:uuid(),text:"Back",type:"secondary",size:"M",onClick:[{parameters:{type:"prev",componentId:S},"##eventHandlerType":"Change Form Step"}]}),m!==f-1&&M.push({_id:uuid(),_component:"@budibase/standard-components/button",_instanceName:uuid(),text:"Next",type:"cta",size:"M",onClick:[{"##eventHandlerType":"Validate Form",parameters:{componentId:S}},{parameters:{type:"next",componentId:S},"##eventHandlerType":"Change Form Step"}]}),v!=="View"&&m===f-1&&M.push({_id:uuid(),_component:"@budibase/standard-components/button",_instanceName:uuid(),text:"Save",type:"cta",size:"M",onClick:[{"##eventHandlerType":"Validate Form",parameters:{componentId:S}},{"##eventHandlerType":"Save Row",parameters:{tableId:k,providerId:S}},...v!=="Create"?[]:[{"##eventHandlerType":"Clear Form",parameters:{componentId:S}}]]}),{buttons:M,title:w}};function parseFilter(p){if(!(p!=null&&p.groups))return p;const u=lodashExports.cloneDeep(p);return u.groups=u.groups.map(f=>(f.filters=f.filters.filter(m=>m.field&&m.operator),f.filters.length?f:null)).filter(f=>f),u}const isBetterSample=(p,u)=>{if(u==null&&p!=null)return!0;if(u!=null&&p==null)return!1;const f=typeof u,m=typeof p;return f!==m?!1:m==="string"&&p.length>u.length||m==="object"&&Object.keys(p).length>Object.keys(u).length},generateGoldenSample=p=>{let u={};return p==null||p.slice(0,100).forEach(f=>{Object.keys(f).forEach(m=>{isBetterSample(f[m],u[m])&&(u[m]=f[m])})}),u},getColumnIcon=p=>{if(p.schema.icon)return p.schema.icon;if(p.calculationType)return"Calculator";if(p.schema.autocolumn)return"MagicWand";if(isDeprecatedSingleUserColumn(p.schema))return"User";const{type:u,subtype:f}=p.schema;return(typeof TypeIconMap[u]=="object"&&f?TypeIconMap[u][f]:TypeIconMap[u])||"Text"},memo=p=>{const u=writable(p);let f=JSON.stringify(p);const m=v=>{const y=JSON.stringify(v);y!==f&&(u.set(v),f=y)};return{subscribe:u.subscribe,set:m,update:v=>{let y=JSON.parse(f);const w=v(y);m(w)}}},derivedMemo=(p,u)=>{const f=derived(p,u),m=memo(get_store_value(f));return f.subscribe(m.set),m},PACKET_TYPES=Object.create(null);PACKET_TYPES.open="0",PACKET_TYPES.close="1",PACKET_TYPES.ping="2",PACKET_TYPES.pong="3",PACKET_TYPES.message="4",PACKET_TYPES.upgrade="5",PACKET_TYPES.noop="6";const PACKET_TYPES_REVERSE=Object.create(null);Object.keys(PACKET_TYPES).forEach(p=>{PACKET_TYPES_REVERSE[PACKET_TYPES[p]]=p});const ERROR_PACKET={type:"error",data:"parser error"},withNativeBlob$1=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",withNativeArrayBuffer$2=typeof ArrayBuffer=="function",isView$1=p=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(p):p&&p.buffer instanceof ArrayBuffer,encodePacket=({type:p,data:u},f,m)=>withNativeBlob$1&&u instanceof Blob?f?m(u):encodeBlobAsBase64(u,m):withNativeArrayBuffer$2&&(u instanceof ArrayBuffer||isView$1(u))?f?m(u):encodeBlobAsBase64(new Blob([u]),m):m(PACKET_TYPES[p]+(u||"")),encodeBlobAsBase64=(p,u)=>{const f=new FileReader;return f.onload=function(){const m=f.result.split(",")[1];u("b"+(m||""))},f.readAsDataURL(p)};function toArray(p){return p instanceof Uint8Array?p:p instanceof ArrayBuffer?new Uint8Array(p):new Uint8Array(p.buffer,p.byteOffset,p.byteLength)}let TEXT_ENCODER;function encodePacketToBinary(p,u){if(withNativeBlob$1&&p.data instanceof Blob)return p.data.arrayBuffer().then(toArray).then(u);if(withNativeArrayBuffer$2&&(p.data instanceof ArrayBuffer||isView$1(p.data)))return u(toArray(p.data));encodePacket(p,!1,f=>{TEXT_ENCODER||(TEXT_ENCODER=new TextEncoder),u(TEXT_ENCODER.encode(f))})}const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$2=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let p=0;p<chars.length;p++)lookup$2[chars.charCodeAt(p)]=p;const decode$2=p=>{let u=p.length*.75,f=p.length,m,v=0,y,w,k,S;p[p.length-1]==="="&&(u--,p[p.length-2]==="="&&u--);const M=new ArrayBuffer(u),T=new Uint8Array(M);for(m=0;m<f;m+=4)y=lookup$2[p.charCodeAt(m)],w=lookup$2[p.charCodeAt(m+1)],k=lookup$2[p.charCodeAt(m+2)],S=lookup$2[p.charCodeAt(m+3)],T[v++]=y<<2|w>>4,T[v++]=(w&15)<<4|k>>2,T[v++]=(k&3)<<6|S&63;return M},withNativeArrayBuffer$1=typeof ArrayBuffer=="function",decodePacket=(p,u)=>{if(typeof p!="string")return{type:"message",data:mapBinary(p,u)};const f=p.charAt(0);return f==="b"?{type:"message",data:decodeBase64Packet(p.substring(1),u)}:PACKET_TYPES_REVERSE[f]?p.length>1?{type:PACKET_TYPES_REVERSE[f],data:p.substring(1)}:{type:PACKET_TYPES_REVERSE[f]}:ERROR_PACKET},decodeBase64Packet=(p,u)=>{if(withNativeArrayBuffer$1){const f=decode$2(p);return mapBinary(f,u)}else return{base64:!0,data:p}},mapBinary=(p,u)=>{switch(u){case"blob":return p instanceof Blob?p:new Blob([p]);case"arraybuffer":default:return p instanceof ArrayBuffer?p:p.buffer}},SEPARATOR=String.fromCharCode(30),encodePayload=(p,u)=>{const f=p.length,m=new Array(f);let v=0;p.forEach((y,w)=>{encodePacket(y,!1,k=>{m[w]=k,++v===f&&u(m.join(SEPARATOR))})})},decodePayload=(p,u)=>{const f=p.split(SEPARATOR),m=[];for(let v=0;v<f.length;v++){const y=decodePacket(f[v],u);if(m.push(y),y.type==="error")break}return m};function createPacketEncoderStream(){return new TransformStream({transform(p,u){encodePacketToBinary(p,f=>{const m=f.length;let v;if(m<126)v=new Uint8Array(1),new DataView(v.buffer).setUint8(0,m);else if(m<65536){v=new Uint8Array(3);const y=new DataView(v.buffer);y.setUint8(0,126),y.setUint16(1,m)}else{v=new Uint8Array(9);const y=new DataView(v.buffer);y.setUint8(0,127),y.setBigUint64(1,BigInt(m))}p.data&&typeof p.data!="string"&&(v[0]|=128),u.enqueue(v),u.enqueue(f)})}})}let TEXT_DECODER;function totalLength(p){return p.reduce((u,f)=>u+f.length,0)}function concatChunks(p,u){if(p[0].length===u)return p.shift();const f=new Uint8Array(u);let m=0;for(let v=0;v<u;v++)f[v]=p[0][m++],m===p[0].length&&(p.shift(),m=0);return p.length&&m<p[0].length&&(p[0]=p[0].slice(m)),f}function createPacketDecoderStream(p,u){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const f=[];let m=0,v=-1,y=!1;return new TransformStream({transform(w,k){for(f.push(w);;){if(m===0){if(totalLength(f)<1)break;const S=concatChunks(f,1);y=(S[0]&128)===128,v=S[0]&127,v<126?m=3:v===126?m=1:m=2}else if(m===1){if(totalLength(f)<2)break;const S=concatChunks(f,2);v=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),m=3}else if(m===2){if(totalLength(f)<8)break;const S=concatChunks(f,8),M=new DataView(S.buffer,S.byteOffset,S.length),T=M.getUint32(0);if(T>Math.pow(2,53-32)-1){k.enqueue(ERROR_PACKET);break}v=T*Math.pow(2,32)+M.getUint32(4),m=3}else{if(totalLength(f)<v)break;const S=concatChunks(f,v);k.enqueue(decodePacket(y?S:TEXT_DECODER.decode(S),u)),m=0}if(v===0||v>p){k.enqueue(ERROR_PACKET);break}}}})}const protocol$1=4;function Emitter(p){if(p)return mixin(p)}function mixin(p){for(var u in Emitter.prototype)p[u]=Emitter.prototype[u];return p}Emitter.prototype.on=Emitter.prototype.addEventListener=function(p,u){return this._callbacks=this._callbacks||{},(this._callbacks["$"+p]=this._callbacks["$"+p]||[]).push(u),this},Emitter.prototype.once=function(p,u){function f(){this.off(p,f),u.apply(this,arguments)}return f.fn=u,this.on(p,f),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(p,u){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var f=this._callbacks["$"+p];if(!f)return this;if(arguments.length==1)return delete this._callbacks["$"+p],this;for(var m,v=0;v<f.length;v++)if(m=f[v],m===u||m.fn===u){f.splice(v,1);break}return f.length===0&&delete this._callbacks["$"+p],this},Emitter.prototype.emit=function(p){this._callbacks=this._callbacks||{};for(var u=new Array(arguments.length-1),f=this._callbacks["$"+p],m=1;m<arguments.length;m++)u[m-1]=arguments[m];if(f){f=f.slice(0);for(var m=0,v=f.length;m<v;++m)f[m].apply(this,u)}return this},Emitter.prototype.emitReserved=Emitter.prototype.emit,Emitter.prototype.listeners=function(p){return this._callbacks=this._callbacks||{},this._callbacks["$"+p]||[]},Emitter.prototype.hasListeners=function(p){return!!this.listeners(p).length};const globalThisShim=(()=>typeof self<"u"?self:typeof window<"u"?window:Function("return this")())();function pick(p,...u){return u.reduce((f,m)=>(p.hasOwnProperty(m)&&(f[m]=p[m]),f),{})}const NATIVE_SET_TIMEOUT=globalThisShim.setTimeout,NATIVE_CLEAR_TIMEOUT=globalThisShim.clearTimeout;function installTimerFunctions(p,u){u.useNativeTimers?(p.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThisShim),p.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThisShim)):(p.setTimeoutFn=globalThisShim.setTimeout.bind(globalThisShim),p.clearTimeoutFn=globalThisShim.clearTimeout.bind(globalThisShim))}const BASE64_OVERHEAD=1.33;function byteLength(p){return typeof p=="string"?utf8Length(p):Math.ceil((p.byteLength||p.size)*BASE64_OVERHEAD)}function utf8Length(p){let u=0,f=0;for(let m=0,v=p.length;m<v;m++)u=p.charCodeAt(m),u<128?f+=1:u<2048?f+=2:u<55296||u>=57344?f+=3:(m++,f+=4);return f}function encode$2(p){let u="";for(let f in p)p.hasOwnProperty(f)&&(u.length&&(u+="&"),u+=encodeURIComponent(f)+"="+encodeURIComponent(p[f]));return u}function decode$1(p){let u={},f=p.split("&");for(let m=0,v=f.length;m<v;m++){let y=f[m].split("=");u[decodeURIComponent(y[0])]=decodeURIComponent(y[1])}return u}class TransportError extends Error{constructor(u,f,m){super(u),this.description=f,this.context=m,this.type="TransportError"}}class Transport extends Emitter{constructor(u){super(),this.writable=!1,installTimerFunctions(this,u),this.opts=u,this.query=u.query,this.socket=u.socket}onError(u,f,m){return super.emitReserved("error",new TransportError(u,f,m)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(u){this.readyState==="open"&&this.write(u)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(u){const f=decodePacket(u,this.socket.binaryType);this.onPacket(f)}onPacket(u){super.emitReserved("packet",u)}onClose(u){this.readyState="closed",super.emitReserved("close",u)}pause(u){}createUri(u,f={}){return u+"://"+this._hostname()+this._port()+this.opts.path+this._query(f)}_hostname(){const u=this.opts.hostname;return u.indexOf(":")===-1?u:"["+u+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(u){const f=encode$2(u);return f.length?"?"+f:""}}const alphabet$3="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),length=64,map={};let seed$1=0,i=0,prev;function encode$1(p){let u="";do u=alphabet$3[p%length]+u,p=Math.floor(p/length);while(p>0);return u}function yeast(){const p=encode$1(+new Date);return p!==prev?(seed$1=0,prev=p):p+"."+encode$1(seed$1++)}for(;i<length;i++)map[alphabet$3[i]]=i;let value$1=!1;try{value$1=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch(p){}const hasCORS=value$1;function XHR(p){const u=p.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!u||hasCORS))return new XMLHttpRequest}catch{}if(!u)try{return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}function createCookieJar(){}function empty(){}const hasXHR2=function(){return new XHR({xdomain:!1}).responseType!=null}();class Polling extends Transport{constructor(u){if(super(u),this.polling=!1,typeof location<"u"){const m=location.protocol==="https:";let v=location.port;v||(v=m?"443":"80"),this.xd=typeof location<"u"&&u.hostname!==location.hostname||v!==u.port}const f=u&&u.forceBase64;this.supportsBinary=hasXHR2&&!f,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(u){this.readyState="pausing";const f=()=>{this.readyState="paused",u()};if(this.polling||!this.writable){let m=0;this.polling&&(m++,this.once("pollComplete",function(){--m||f()})),this.writable||(m++,this.once("drain",function(){--m||f()}))}else f()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(u){const f=m=>{if(this.readyState==="opening"&&m.type==="open"&&this.onOpen(),m.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(m)};decodePayload(u,this.socket.binaryType).forEach(f),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const u=()=>{this.write([{type:"close"}])};this.readyState==="open"?u():this.once("open",u)}write(u){this.writable=!1,encodePayload(u,f=>{this.doWrite(f,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const u=this.opts.secure?"https":"http",f=this.query||{};return this.opts.timestampRequests!==!1&&(f[this.opts.timestampParam]=yeast()),!this.supportsBinary&&!f.sid&&(f.b64=1),this.createUri(u,f)}request(u={}){return Object.assign(u,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Request(this.uri(),u)}doWrite(u,f){const m=this.request({method:"POST",data:u});m.on("success",f),m.on("error",(v,y)=>{this.onError("xhr post error",v,y)})}doPoll(){const u=this.request();u.on("data",this.onData.bind(this)),u.on("error",(f,m)=>{this.onError("xhr poll error",f,m)}),this.pollXhr=u}}class Request extends Emitter{constructor(u,f){super(),installTimerFunctions(this,f),this.opts=f,this.method=f.method||"GET",this.uri=u,this.data=f.data!==void 0?f.data:null,this.create()}create(){var u;const f=pick(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");f.xdomain=!!this.opts.xd;const m=this.xhr=new XHR(f);try{m.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){m.setDisableHeaderCheck&&m.setDisableHeaderCheck(!0);for(let v in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(v)&&m.setRequestHeader(v,this.opts.extraHeaders[v])}}catch{}if(this.method==="POST")try{m.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{m.setRequestHeader("Accept","*/*")}catch{}(u=this.opts.cookieJar)===null||u===void 0||u.addCookies(m),"withCredentials"in m&&(m.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(m.timeout=this.opts.requestTimeout),m.onreadystatechange=()=>{var v;m.readyState===3&&((v=this.opts.cookieJar)===null||v===void 0||v.parseCookies(m)),m.readyState===4&&(m.status===200||m.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof m.status=="number"?m.status:0)},0))},m.send(this.data)}catch(v){this.setTimeoutFn(()=>{this.onError(v)},0);return}typeof document<"u"&&(this.index=Request.requestsCount++,Request.requests[this.index]=this)}onError(u){this.emitReserved("error",u,this.xhr),this.cleanup(!0)}cleanup(u){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=empty,u)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Request.requests[this.index],this.xhr=null}}onLoad(){const u=this.xhr.responseText;u!==null&&(this.emitReserved("data",u),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Request.requestsCount=0,Request.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",unloadHandler);else if(typeof addEventListener=="function"){const p="onpagehide"in globalThisShim?"pagehide":"unload";addEventListener(p,unloadHandler,!1)}}function unloadHandler(){for(let p in Request.requests)Request.requests.hasOwnProperty(p)&&Request.requests[p].abort()}const nextTick=(()=>typeof Promise=="function"&&typeof Promise.resolve=="function"?u=>Promise.resolve().then(u):(u,f)=>f(u,0))(),WebSocket=globalThisShim.WebSocket||globalThisShim.MozWebSocket,usingBrowserWebSocket=!0,defaultBinaryType="arraybuffer",isReactNative=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class WS extends Transport{constructor(u){super(u),this.supportsBinary=!u.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const u=this.uri(),f=this.opts.protocols,m=isReactNative?{}:pick(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(m.headers=this.opts.extraHeaders);try{this.ws=usingBrowserWebSocket&&!isReactNative?f?new WebSocket(u,f):new WebSocket(u):new WebSocket(u,f,m)}catch(v){return this.emitReserved("error",v)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=u=>this.onClose({description:"websocket connection closed",context:u}),this.ws.onmessage=u=>this.onData(u.data),this.ws.onerror=u=>this.onError("websocket error",u)}write(u){this.writable=!1;for(let f=0;f<u.length;f++){const m=u[f],v=f===u.length-1;encodePacket(m,this.supportsBinary,y=>{const w={};try{usingBrowserWebSocket&&this.ws.send(y)}catch{}v&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const u=this.opts.secure?"wss":"ws",f=this.query||{};return this.opts.timestampRequests&&(f[this.opts.timestampParam]=yeast()),this.supportsBinary||(f.b64=1),this.createUri(u,f)}check(){return!!WebSocket}}class WT extends Transport{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(u=>{this.onError("webtransport error",u)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(u=>{const f=createPacketDecoderStream(Number.MAX_SAFE_INTEGER,this.socket.binaryType),m=u.readable.pipeThrough(f).getReader(),v=createPacketEncoderStream();v.readable.pipeTo(u.writable),this.writer=v.writable.getWriter();const y=()=>{m.read().then(({done:k,value:S})=>{k||(this.onPacket(S),y())}).catch(k=>{})};y();const w={type:"open"};this.query.sid&&(w.data=`{"sid":"${this.query.sid}"}`),this.writer.write(w).then(()=>this.onOpen())})}))}write(u){this.writable=!1;for(let f=0;f<u.length;f++){const m=u[f],v=f===u.length-1;this.writer.write(m).then(()=>{v&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var u;(u=this.transport)===null||u===void 0||u.close()}}const transports={websocket:WS,webtransport:WT,polling:Polling},re=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function parse$6(p){if(p.length>2e3)throw"URI too long";const u=p,f=p.indexOf("["),m=p.indexOf("]");f!=-1&&m!=-1&&(p=p.substring(0,f)+p.substring(f,m).replace(/:/g,";")+p.substring(m,p.length));let v=re.exec(p||""),y={},w=14;for(;w--;)y[parts[w]]=v[w]||"";return f!=-1&&m!=-1&&(y.source=u,y.host=y.host.substring(1,y.host.length-1).replace(/;/g,":"),y.authority=y.authority.replace("[","").replace("]","").replace(/;/g,":"),y.ipv6uri=!0),y.pathNames=pathNames(y,y.path),y.queryKey=queryKey(y,y.query),y}function pathNames(p,u){const f=/\/{2,9}/g,m=u.replace(f,"/").split("/");return(u.slice(0,1)=="/"||u.length===0)&&m.splice(0,1),u.slice(-1)=="/"&&m.splice(m.length-1,1),m}function queryKey(p,u){const f={};return u.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(m,v,y){v&&(f[v]=y)}),f}let Socket$1=class Ec extends Emitter{constructor(u,f={}){super(),this.binaryType=defaultBinaryType,this.writeBuffer=[],u&&typeof u=="object"&&(f=u,u=null),u?(u=parse$6(u),f.hostname=u.host,f.secure=u.protocol==="https"||u.protocol==="wss",f.port=u.port,u.query&&(f.query=u.query)):f.host&&(f.hostname=parse$6(f.host).host),installTimerFunctions(this,f),this.secure=f.secure!=null?f.secure:typeof location<"u"&&location.protocol==="https:",f.hostname&&!f.port&&(f.port=this.secure?"443":"80"),this.hostname=f.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=f.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=f.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},f),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=decode$1(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(u){const f=Object.assign({},this.opts.query);f.EIO=protocol$1,f.transport=u,this.id&&(f.sid=this.id);const m=Object.assign({},this.opts,{query:f,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[u]);return new transports[u](m)}open(){let u;if(this.opts.rememberUpgrade&&Ec.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)u="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else u=this.transports[0];this.readyState="opening";try{u=this.createTransport(u)}catch{this.transports.shift(),this.open();return}u.open(),this.setTransport(u)}setTransport(u){this.transport&&this.transport.removeAllListeners(),this.transport=u,u.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",f=>this.onClose("transport close",f))}probe(u){let f=this.createTransport(u),m=!1;Ec.priorWebsocketSuccess=!1;const v=()=>{m||(f.send([{type:"ping",data:"probe"}]),f.once("packet",E=>{if(!m)if(E.type==="pong"&&E.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",f),!f)return;Ec.priorWebsocketSuccess=f.name==="websocket",this.transport.pause(()=>{m||this.readyState!=="closed"&&(T(),this.setTransport(f),f.send([{type:"upgrade"}]),this.emitReserved("upgrade",f),f=null,this.upgrading=!1,this.flush())})}else{const H=new Error("probe error");H.transport=f.name,this.emitReserved("upgradeError",H)}}))};function y(){m||(m=!0,T(),f.close(),f=null)}const w=E=>{const H=new Error("probe error: "+E);H.transport=f.name,y(),this.emitReserved("upgradeError",H)};function k(){w("transport closed")}function S(){w("socket closed")}function M(E){f&&E.name!==f.name&&y()}const T=()=>{f.removeListener("open",v),f.removeListener("error",w),f.removeListener("close",k),this.off("close",S),this.off("upgrading",M)};f.once("open",v),f.once("error",w),f.once("close",k),this.once("close",S),this.once("upgrading",M),this.upgrades.indexOf("webtransport")!==-1&&u!=="webtransport"?this.setTimeoutFn(()=>{m||f.open()},200):f.open()}onOpen(){if(this.readyState="open",Ec.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let u=0;const f=this.upgrades.length;for(;u<f;u++)this.probe(this.upgrades[u])}}onPacket(u){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",u),this.emitReserved("heartbeat"),this.resetPingTimeout(),u.type){case"open":this.onHandshake(JSON.parse(u.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const f=new Error("server error");f.code=u.data,this.onError(f);break;case"message":this.emitReserved("data",u.data),this.emitReserved("message",u.data);break}}onHandshake(u){this.emitReserved("handshake",u),this.id=u.sid,this.transport.query.sid=u.sid,this.upgrades=this.filterUpgrades(u.upgrades),this.pingInterval=u.pingInterval,this.pingTimeout=u.pingTimeout,this.maxPayload=u.maxPayload,this.onOpen(),this.readyState!=="closed"&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const u=this.getWritablePackets();this.transport.send(u),this.prevBufferLen=u.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let f=1;for(let m=0;m<this.writeBuffer.length;m++){const v=this.writeBuffer[m].data;if(v&&(f+=byteLength(v)),m>0&&f>this.maxPayload)return this.writeBuffer.slice(0,m);f+=2}return this.writeBuffer}write(u,f,m){return this.sendPacket("message",u,f,m),this}send(u,f,m){return this.sendPacket("message",u,f,m),this}sendPacket(u,f,m,v){if(typeof f=="function"&&(v=f,f=void 0),typeof m=="function"&&(v=m,m=null),this.readyState==="closing"||this.readyState==="closed")return;m=m||{},m.compress=m.compress!==!1;const y={type:u,data:f,options:m};this.emitReserved("packetCreate",y),this.writeBuffer.push(y),v&&this.once("flush",v),this.flush()}close(){const u=()=>{this.onClose("forced close"),this.transport.close()},f=()=>{this.off("upgrade",f),this.off("upgradeError",f),u()},m=()=>{this.once("upgrade",f),this.once("upgradeError",f)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?m():u()}):this.upgrading?m():u()),this}onError(u){Ec.priorWebsocketSuccess=!1,this.emitReserved("error",u),this.onClose("transport error",u)}onClose(u,f){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",u,f),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(u){const f=[];let m=0;const v=u.length;for(;m<v;m++)~this.transports.indexOf(u[m])&&f.push(u[m]);return f}};Socket$1.protocol=protocol$1;function url(p,u="",f){let m=p;f=f||typeof location<"u"&&location,p==null&&(p=f.protocol+"//"+f.host),typeof p=="string"&&(p.charAt(0)==="/"&&(p.charAt(1)==="/"?p=f.protocol+p:p=f.host+p),/^(https?|wss?):\/\//.test(p)||(typeof f<"u"?p=f.protocol+"//"+p:p="https://"+p),m=parse$6(p)),m.port||(/^(http|ws)$/.test(m.protocol)?m.port="80":/^(http|ws)s$/.test(m.protocol)&&(m.port="443")),m.path=m.path||"/";const y=m.host.indexOf(":")!==-1?"["+m.host+"]":m.host;return m.id=m.protocol+"://"+y+":"+m.port+u,m.href=m.protocol+"://"+y+(f&&f.port===m.port?"":":"+m.port),m}const withNativeArrayBuffer=typeof ArrayBuffer=="function",isView=p=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(p):p.buffer instanceof ArrayBuffer,toString=Object.prototype.toString,withNativeBlob=typeof Blob=="function"||typeof Blob<"u"&&toString.call(Blob)==="[object BlobConstructor]",withNativeFile=typeof File=="function"||typeof File<"u"&&toString.call(File)==="[object FileConstructor]";function isBinary(p){return withNativeArrayBuffer&&(p instanceof ArrayBuffer||isView(p))||withNativeBlob&&p instanceof Blob||withNativeFile&&p instanceof File}function hasBinary(p,u){if(!p||typeof p!="object")return!1;if(Array.isArray(p)){for(let f=0,m=p.length;f<m;f++)if(hasBinary(p[f]))return!0;return!1}if(isBinary(p))return!0;if(p.toJSON&&typeof p.toJSON=="function"&&arguments.length===1)return hasBinary(p.toJSON(),!0);for(const f in p)if(Object.prototype.hasOwnProperty.call(p,f)&&hasBinary(p[f]))return!0;return!1}function deconstructPacket(p){const u=[],f=p.data,m=p;return m.data=_deconstructPacket(f,u),m.attachments=u.length,{packet:m,buffers:u}}function _deconstructPacket(p,u){if(!p)return p;if(isBinary(p)){const f={_placeholder:!0,num:u.length};return u.push(p),f}else if(Array.isArray(p)){const f=new Array(p.length);for(let m=0;m<p.length;m++)f[m]=_deconstructPacket(p[m],u);return f}else if(typeof p=="object"&&!(p instanceof Date)){const f={};for(const m in p)Object.prototype.hasOwnProperty.call(p,m)&&(f[m]=_deconstructPacket(p[m],u));return f}return p}function reconstructPacket(p,u){return p.data=_reconstructPacket(p.data,u),delete p.attachments,p}function _reconstructPacket(p,u){if(!p)return p;if(p&&p._placeholder===!0){if(typeof p.num=="number"&&p.num>=0&&p.num<u.length)return u[p.num];throw new Error("illegal attachments")}else if(Array.isArray(p))for(let f=0;f<p.length;f++)p[f]=_reconstructPacket(p[f],u);else if(typeof p=="object")for(const f in p)Object.prototype.hasOwnProperty.call(p,f)&&(p[f]=_reconstructPacket(p[f],u));return p}const RESERVED_EVENTS$1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],protocol=5;var PacketType;(function(p){p[p.CONNECT=0]="CONNECT",p[p.DISCONNECT=1]="DISCONNECT",p[p.EVENT=2]="EVENT",p[p.ACK=3]="ACK",p[p.CONNECT_ERROR=4]="CONNECT_ERROR",p[p.BINARY_EVENT=5]="BINARY_EVENT",p[p.BINARY_ACK=6]="BINARY_ACK"})(PacketType||(PacketType={}));class Encoder{constructor(u){this.replacer=u}encode(u){return(u.type===PacketType.EVENT||u.type===PacketType.ACK)&&hasBinary(u)?this.encodeAsBinary({type:u.type===PacketType.EVENT?PacketType.BINARY_EVENT:PacketType.BINARY_ACK,nsp:u.nsp,data:u.data,id:u.id}):[this.encodeAsString(u)]}encodeAsString(u){let f=""+u.type;return(u.type===PacketType.BINARY_EVENT||u.type===PacketType.BINARY_ACK)&&(f+=u.attachments+"-"),u.nsp&&u.nsp!=="/"&&(f+=u.nsp+","),u.id!=null&&(f+=u.id),u.data!=null&&(f+=JSON.stringify(u.data,this.replacer)),f}encodeAsBinary(u){const f=deconstructPacket(u),m=this.encodeAsString(f.packet),v=f.buffers;return v.unshift(m),v}}function isObject$1(p){return Object.prototype.toString.call(p)==="[object Object]"}class Decoder extends Emitter{constructor(u){super(),this.reviver=u}add(u){let f;if(typeof u=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");f=this.decodeString(u);const m=f.type===PacketType.BINARY_EVENT;m||f.type===PacketType.BINARY_ACK?(f.type=m?PacketType.EVENT:PacketType.ACK,this.reconstructor=new BinaryReconstructor(f),f.attachments===0&&super.emitReserved("decoded",f)):super.emitReserved("decoded",f)}else if(isBinary(u)||u.base64)if(this.reconstructor)f=this.reconstructor.takeBinaryData(u),f&&(this.reconstructor=null,super.emitReserved("decoded",f));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+u)}decodeString(u){let f=0;const m={type:Number(u.charAt(0))};if(PacketType[m.type]===void 0)throw new Error("unknown packet type "+m.type);if(m.type===PacketType.BINARY_EVENT||m.type===PacketType.BINARY_ACK){const y=f+1;for(;u.charAt(++f)!=="-"&&f!=u.length;);const w=u.substring(y,f);if(w!=Number(w)||u.charAt(f)!=="-")throw new Error("Illegal attachments");m.attachments=Number(w)}if(u.charAt(f+1)==="/"){const y=f+1;for(;++f&&!(u.charAt(f)===","||f===u.length););m.nsp=u.substring(y,f)}else m.nsp="/";const v=u.charAt(f+1);if(v!==""&&Number(v)==v){const y=f+1;for(;++f;){const w=u.charAt(f);if(w==null||Number(w)!=w){--f;break}if(f===u.length)break}m.id=Number(u.substring(y,f+1))}if(u.charAt(++f)){const y=this.tryParse(u.substr(f));if(Decoder.isPayloadValid(m.type,y))m.data=y;else throw new Error("invalid payload")}return m}tryParse(u){try{return JSON.parse(u,this.reviver)}catch{return!1}}static isPayloadValid(u,f){switch(u){case PacketType.CONNECT:return isObject$1(f);case PacketType.DISCONNECT:return f===void 0;case PacketType.CONNECT_ERROR:return typeof f=="string"||isObject$1(f);case PacketType.EVENT:case PacketType.BINARY_EVENT:return Array.isArray(f)&&(typeof f[0]=="number"||typeof f[0]=="string"&&RESERVED_EVENTS$1.indexOf(f[0])===-1);case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(f)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BinaryReconstructor{constructor(u){this.packet=u,this.buffers=[],this.reconPack=u}takeBinaryData(u){if(this.buffers.push(u),this.buffers.length===this.reconPack.attachments){const f=reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),f}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const parser$1=Object.freeze(Object.defineProperty({__proto__:null,Decoder,Encoder,get PacketType(){return PacketType},protocol},Symbol.toStringTag,{value:"Module"}));function on(p,u,f){return p.on(u,f),function(){p.off(u,f)}}const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends Emitter{constructor(u,f,m){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=u,this.nsp=f,m&&m.auth&&(this.auth=m.auth),this._opts=Object.assign({},m),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const u=this.io;this.subs=[on(u,"open",this.onopen.bind(this)),on(u,"packet",this.onpacket.bind(this)),on(u,"error",this.onerror.bind(this)),on(u,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...u){return u.unshift("message"),this.emit.apply(this,u),this}emit(u,...f){if(RESERVED_EVENTS.hasOwnProperty(u))throw new Error('"'+u.toString()+'" is a reserved event name');if(f.unshift(u),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(f),this;const m={type:PacketType.EVENT,data:f};if(m.options={},m.options.compress=this.flags.compress!==!1,typeof f[f.length-1]=="function"){const w=this.ids++,k=f.pop();this._registerAckCallback(w,k),m.id=w}const v=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!v||!this.connected)||(this.connected?(this.notifyOutgoingListeners(m),this.packet(m)):this.sendBuffer.push(m)),this.flags={},this}_registerAckCallback(u,f){var m;const v=(m=this.flags.timeout)!==null&&m!==void 0?m:this._opts.ackTimeout;if(v===void 0){this.acks[u]=f;return}const y=this.io.setTimeoutFn(()=>{delete this.acks[u];for(let k=0;k<this.sendBuffer.length;k++)this.sendBuffer[k].id===u&&this.sendBuffer.splice(k,1);f.call(this,new Error("operation has timed out"))},v),w=(...k)=>{this.io.clearTimeoutFn(y),f.apply(this,k)};w.withError=!0,this.acks[u]=w}emitWithAck(u,...f){return new Promise((m,v)=>{const y=(w,k)=>w?v(w):m(k);y.withError=!0,f.push(y),this.emit(u,...f)})}_addToQueue(u){let f;typeof u[u.length-1]=="function"&&(f=u.pop());const m={id:this._queueSeq++,tryCount:0,pending:!1,args:u,flags:Object.assign({fromQueue:!0},this.flags)};u.push((v,...y)=>m!==this._queue[0]?void 0:(v!==null?m.tryCount>this._opts.retries&&(this._queue.shift(),f&&f(v)):(this._queue.shift(),f&&f(null,...y)),m.pending=!1,this._drainQueue())),this._queue.push(m),this._drainQueue()}_drainQueue(u=!1){if(!this.connected||this._queue.length===0)return;const f=this._queue[0];f.pending&&!u||(f.pending=!0,f.tryCount++,this.flags=f.flags,this.emit.apply(this,f.args))}packet(u){u.nsp=this.nsp,this.io._packet(u)}onopen(){typeof this.auth=="function"?this.auth(u=>{this._sendConnectPacket(u)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(u){this.packet({type:PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},u):u})}onerror(u){this.connected||this.emitReserved("connect_error",u)}onclose(u,f){this.connected=!1,delete this.id,this.emitReserved("disconnect",u,f),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(u=>{if(!this.sendBuffer.some(m=>String(m.id)===u)){const m=this.acks[u];delete this.acks[u],m.withError&&m.call(this,new Error("socket has been disconnected"))}})}onpacket(u){if(u.nsp===this.nsp)switch(u.type){case PacketType.CONNECT:u.data&&u.data.sid?this.onconnect(u.data.sid,u.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case PacketType.EVENT:case PacketType.BINARY_EVENT:this.onevent(u);break;case PacketType.ACK:case PacketType.BINARY_ACK:this.onack(u);break;case PacketType.DISCONNECT:this.ondisconnect();break;case PacketType.CONNECT_ERROR:this.destroy();const m=new Error(u.data.message);m.data=u.data.data,this.emitReserved("connect_error",m);break}}onevent(u){const f=u.data||[];u.id!=null&&f.push(this.ack(u.id)),this.connected?this.emitEvent(f):this.receiveBuffer.push(Object.freeze(f))}emitEvent(u){if(this._anyListeners&&this._anyListeners.length){const f=this._anyListeners.slice();for(const m of f)m.apply(this,u)}super.emit.apply(this,u),this._pid&&u.length&&typeof u[u.length-1]=="string"&&(this._lastOffset=u[u.length-1])}ack(u){const f=this;let m=!1;return function(...v){m||(m=!0,f.packet({type:PacketType.ACK,id:u,data:v}))}}onack(u){const f=this.acks[u.id];typeof f=="function"&&(delete this.acks[u.id],f.withError&&u.data.unshift(null),f.apply(this,u.data))}onconnect(u,f){this.id=u,this.recovered=f&&this._pid===f,this._pid=f,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(u=>this.emitEvent(u)),this.receiveBuffer=[],this.sendBuffer.forEach(u=>{this.notifyOutgoingListeners(u),this.packet(u)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(u=>u()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(u){return this.flags.compress=u,this}get volatile(){return this.flags.volatile=!0,this}timeout(u){return this.flags.timeout=u,this}onAny(u){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(u),this}prependAny(u){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(u),this}offAny(u){if(!this._anyListeners)return this;if(u){const f=this._anyListeners;for(let m=0;m<f.length;m++)if(u===f[m])return f.splice(m,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(u){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(u),this}prependAnyOutgoing(u){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(u),this}offAnyOutgoing(u){if(!this._anyOutgoingListeners)return this;if(u){const f=this._anyOutgoingListeners;for(let m=0;m<f.length;m++)if(u===f[m])return f.splice(m,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(u){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const f=this._anyOutgoingListeners.slice();for(const m of f)m.apply(this,u.data)}}}function Backoff(p){p=p||{},this.ms=p.min||100,this.max=p.max||1e4,this.factor=p.factor||2,this.jitter=p.jitter>0&&p.jitter<=1?p.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var p=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var u=Math.random(),f=Math.floor(u*this.jitter*p);p=Math.floor(u*10)&1?p+f:p-f}return Math.min(p,this.max)|0},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(p){this.ms=p},Backoff.prototype.setMax=function(p){this.max=p},Backoff.prototype.setJitter=function(p){this.jitter=p};class Manager extends Emitter{constructor(u,f){var m;super(),this.nsps={},this.subs=[],u&&typeof u=="object"&&(f=u,u=void 0),f=f||{},f.path=f.path||"/socket.io",this.opts=f,installTimerFunctions(this,f),this.reconnection(f.reconnection!==!1),this.reconnectionAttempts(f.reconnectionAttempts||1/0),this.reconnectionDelay(f.reconnectionDelay||1e3),this.reconnectionDelayMax(f.reconnectionDelayMax||5e3),this.randomizationFactor((m=f.randomizationFactor)!==null&&m!==void 0?m:.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(f.timeout==null?2e4:f.timeout),this._readyState="closed",this.uri=u;const v=f.parser||parser$1;this.encoder=new v.Encoder,this.decoder=new v.Decoder,this._autoConnect=f.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(u){return arguments.length?(this._reconnection=!!u,this):this._reconnection}reconnectionAttempts(u){return u===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=u,this)}reconnectionDelay(u){var f;return u===void 0?this._reconnectionDelay:(this._reconnectionDelay=u,(f=this.backoff)===null||f===void 0||f.setMin(u),this)}randomizationFactor(u){var f;return u===void 0?this._randomizationFactor:(this._randomizationFactor=u,(f=this.backoff)===null||f===void 0||f.setJitter(u),this)}reconnectionDelayMax(u){var f;return u===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=u,(f=this.backoff)===null||f===void 0||f.setMax(u),this)}timeout(u){return arguments.length?(this._timeout=u,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(u){if(~this._readyState.indexOf("open"))return this;this.engine=new Socket$1(this.uri,this.opts);const f=this.engine,m=this;this._readyState="opening",this.skipReconnect=!1;const v=on(f,"open",function(){m.onopen(),u&&u()}),y=k=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",k),u?u(k):this.maybeReconnectOnOpen()},w=on(f,"error",y);if(this._timeout!==!1){const k=this._timeout,S=this.setTimeoutFn(()=>{v(),y(new Error("timeout")),f.close()},k);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(v),this.subs.push(w),this}connect(u){return this.open(u)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const u=this.engine;this.subs.push(on(u,"ping",this.onping.bind(this)),on(u,"data",this.ondata.bind(this)),on(u,"error",this.onerror.bind(this)),on(u,"close",this.onclose.bind(this)),on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(u){try{this.decoder.add(u)}catch(f){this.onclose("parse error",f)}}ondecoded(u){nextTick(()=>{this.emitReserved("packet",u)},this.setTimeoutFn)}onerror(u){this.emitReserved("error",u)}socket(u,f){let m=this.nsps[u];return m?this._autoConnect&&!m.active&&m.connect():(m=new Socket(this,u,f),this.nsps[u]=m),m}_destroy(u){const f=Object.keys(this.nsps);for(const m of f)if(this.nsps[m].active)return;this._close()}_packet(u){const f=this.encoder.encode(u);for(let m=0;m<f.length;m++)this.engine.write(f[m],u.options)}cleanup(){this.subs.forEach(u=>u()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(u,f){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",u,f),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const u=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const f=this.backoff.duration();this._reconnecting=!0;const m=this.setTimeoutFn(()=>{u.skipReconnect||(this.emitReserved("reconnect_attempt",u.backoff.attempts),!u.skipReconnect&&u.open(v=>{v?(u._reconnecting=!1,u.reconnect(),this.emitReserved("reconnect_error",v)):u.onreconnect()}))},f);this.opts.autoUnref&&m.unref(),this.subs.push(()=>{this.clearTimeoutFn(m)})}}onreconnect(){const u=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",u)}}const cache={};function lookup$1(p,u){typeof p=="object"&&(u=p,p=void 0),u=u||{};const f=url(p,u.path||"/socket.io"),m=f.source,v=f.id,y=f.path,w=cache[v]&&y in cache[v].nsps,k=u.forceNew||u["force new connection"]||u.multiplex===!1||w;let S;return k?S=new Manager(m,u):(cache[v]||(cache[v]=new Manager(m,u)),S=cache[v]),f.query&&!u.query&&(u.query=f.queryKey),S.socket(f.path,u)}Object.assign(lookup$1,{Manager,Socket,io:lookup$1,connect:lookup$1});const DefaultOptions={heartbeat:!0},createWebsocket=(p,u=DefaultOptions)=>{if(!p)throw"A websocket path must be provided";const{heartbeat:f}={...DefaultOptions,...u},m=location.protocol==="https:",v=m?"wss:":"ws:",y=location.hostname,w=location.port||(m?443:80);let k=lookup$1(`${v}//${y}:${w}`,{path:p,reconnectionAttempts:3,reconnectionDelay:5e3,reconnectionDelayMax:5e3,timeout:4e3,transports:["websocket"]}),S;return f&&(S=setInterval(()=>{k.emit(SocketEvent.Heartbeat)},SocketSessionTTL*500)),k.on("disconnect",()=>{clearInterval(S)}),k.onOther=(M,T)=>{k.on(M,E=>{(E==null?void 0:E.apiSessionId)!==APISessionID&&T(E)})},k},extractFileNameRegex=/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;async function downloadStream(p){const u=await p.blob(),f=p.headers.get("Content-Disposition"),v=extractFileNameRegex.exec(f)[1].replace(/['"]/g,""),y=new Blob([u]),w=URL.createObjectURL(y),k=document.createElement("a");k.href=w,k.download=v,k.click(),URL.revokeObjectURL(w)}const shouldDisplaySetting=(p,u)=>{let f=u.dependsOn;return f&&!Array.isArray(f)&&(f=[f]),f!=null&&f.length?f.every(m=>{let v=m,y=null,w=!!m.invert;if(typeof m=="object"&&(v=m.setting,y=m.value),!v)return!1;Array.isArray(y)||(y=[y]);const k=deepGet$1(p,v);return y.some(M=>M==null?k!=null&&k!==!1&&k!=="":M===k)!==w}):!0},columnTypeManyTypeOverrides={[FieldType.DATETIME]:FieldType.STRING,[FieldType.BOOLEAN]:FieldType.STRING,[FieldType.SIGNATURE_SINGLE]:FieldType.ATTACHMENTS},columnTypeManyParser={[FieldType.DATETIME]:(p,u)=>{function f(m){const{timeOnly:v,dateOnly:y}=u||{},w=!y,k=parseDate(m,{enableTime:w});return getDateDisplayValue(k,{enableTime:w,timeOnly:v})}return p.map(m=>f(m))},[FieldType.BOOLEAN]:p=>p.map(u=>!!u),[FieldType.BB_REFERENCE_SINGLE]:p=>[...new Map(p.map(u=>[u._id,u])).values()],[FieldType.BB_REFERENCE]:p=>[...new Map(p.map(u=>[u._id,u])).values()],[FieldType.ARRAY]:p=>Array.from(new Set(p))};function enrichSchemaWithRelColumns(p){return Object.keys(p).reduce((f,m)=>{const v=p[m];if(f[m]=v,v.visible!==!1&&isRelationshipField(v)&&v.columns){const y=(v==null?void 0:v.relationshipType)===RelationshipType.ONE_TO_MANY;for(const w of Object.keys(v.columns)){const k=v.columns[w];if(!k.visible)continue;const S=`${v.name}.${w}`;f[S]={...k,type:k.type,name:S,related:{field:m,subField:w},cellRenderType:!y&&columnTypeManyTypeOverrides[k.type]||k.type}}}return f},{})}function getRelatedTableValues(p,u,f){var y,w,k,S;const m=isRelationshipField(f)&&(f==null?void 0:f.relationshipType)===RelationshipType.ONE_TO_MANY;let v="";if(m)v=(w=(y=p[u.related.field])==null?void 0:y[0])==null?void 0:w[u.related.subField];else{const M=columnTypeManyParser[u.type]||(H=>H),T=(S=(k=p[u.related.field])==null?void 0:k.flatMap(H=>H[u.related.subField]))==null?void 0:S.filter(H=>H!=null),E=M(T||[],u);v=E,[FieldType.STRING,FieldType.NUMBER,FieldType.BIGINT,FieldType.BOOLEAN,FieldType.DATETIME,FieldType.LONGFORM,FieldType.BARCODEQR].includes(u.type)&&(v=E==null?void 0:E.join(", "))}return v}function canBeDisplayColumn(p){return!(!canBeDisplayColumn$1(p.type)||p.related)}function canBeSortColumn(p){return p.calculationType?!0:!(!canBeSortColumn$1(p.type)||p.related)}const{buildQuery,limit:queryLimit,runQuery,sort}=QueryUtils;class BaseDataFetch{constructor(u){ha(this,"API");ha(this,"features");ha(this,"options");ha(this,"store");ha(this,"derivedStore");if(this.features={supportsSearch:!1,supportsSort:!1,supportsPagination:!1},this.options={datasource:u.datasource,limit:10,filter:null,query:u.query,sortColumn:null,sortOrder:SortOrder.ASCENDING,sortType:null,paginate:!0,clientSideSearching:!0,clientSideSorting:!0,clientSideLimiting:!0},this.store=writable({rows:[],info:null,schema:null,loading:!1,loaded:!1,query:u.query,pageNumber:0,cursor:null,cursors:[],resetKey:Math.random().toString(),error:null}),this.API=u==null?void 0:u.API,this.options={...this.options,...u},!this.API)throw"An API client is required for fetching data";if(this.getData=this.getData.bind(this),this.getPage=this.getPage.bind(this),this.getInitialData=this.getInitialData.bind(this),this.determineFeatureFlags=this.determineFeatureFlags.bind(this),this.refresh=this.refresh.bind(this),this.update=this.update.bind(this),this.hasNextPage=this.hasNextPage.bind(this),this.hasPrevPage=this.hasPrevPage.bind(this),this.nextPage=this.nextPage.bind(this),this.prevPage=this.prevPage.bind(this),this.derivedStore=derived(this.store,f=>({...f,...this.features,hasNextPage:this.hasNextPage(f),hasPrevPage:this.hasPrevPage(f)})),!this.options.datasource){this.store.update(f=>({...f,loaded:!0}));return}}get subscribe(){return this.derivedStore.subscribe}getDefaultSortColumn(u,f){return u!=null&&u.primaryDisplay&&f[u.primaryDisplay]?u.primaryDisplay:Object.keys(f)[0]}async getInitialData(){const{filter:u,paginate:f}=this.options,m=await this.getDefinition(),v=await this.determineFeatureFlags();this.features={supportsSearch:!!(v!=null&&v.supportsSearch),supportsSort:!!(v!=null&&v.supportsSort),supportsPagination:f&&!!(v!=null&&v.supportsPagination)};let y=this.getSchema(m);if(!y)return;if(y=this.enrichSchema(y),this.options.sortColumn&&!y[this.options.sortColumn]&&(this.options.sortColumn=null),this.options.sortColumn||(this.options.sortColumn=this.getDefaultSortColumn(m,y)),!this.options.sortColumn)this.options.sortOrder=SortOrder.ASCENDING,this.options.sortType=null;else{this.options.sortType=SortType.STRING;const S=y==null?void 0:y[this.options.sortColumn];((S==null?void 0:S.type)===FieldType.NUMBER||(S==null?void 0:S.type)===FieldType.BIGINT||"calculationType"in S&&(S!=null&&S.calculationType))&&(this.options.sortType=SortType.NUMBER),this.options.sortOrder?this.options.sortOrder=this.options.sortOrder.toLowerCase():this.options.sortOrder=SortOrder.ASCENDING}let w=this.options.query;w||(w=buildQuery(u??void 0)),this.store.update(S=>({...S,definition:m,schema:y,query:w,loading:!0,cursors:[],cursor:null}));const k=await this.getPage();this.store.update(S=>({...S,loading:!1,loaded:!0,pageNumber:0,rows:k.rows,info:k.info,cursors:f&&k.hasNextPage?[null,k.cursor]:[null],error:k.error,resetKey:Math.random().toString()}))}async getPage(){const{sortColumn:u,sortOrder:f,sortType:m,limit:v,clientSideSearching:y,clientSideSorting:w,clientSideLimiting:k}=this.options,{query:S}=get_store_value(this.store);let{rows:M,info:T,hasNextPage:E,cursor:H,error:F}=await this.getData();return!this.features.supportsSearch&&y&&(M=runQuery(M,S)),!this.features.supportsSort&&w&&m&&(M=sort(M,u,f,m)),!this.features.supportsPagination&&k&&(M=queryLimit(M,v)),{rows:M,info:T,hasNextPage:E,cursor:H,error:F}}getSchema(u){return(u==null?void 0:u.schema)??void 0}enrichSchema(u){let f={};for(const v of Object.keys(u)){const y=u[v];if(y.type===FieldType.JSON){const w=convertJSONSchemaToTableSchema(y,{squashObjects:!0});if(w)for(const k of Object.keys(w))f[`${v}.${k}`]={type:w[k].type,nestedJSON:!0}}}let m={};return Object.entries({...u,...f}).forEach(([v,y])=>{typeof y=="string"?m[v]={type:y,name:v}:m[v]={...y,type:y.type,name:v}}),m}async determineFeatureFlags(){return{supportsSearch:!1,supportsSort:!1,supportsPagination:!1}}async update(u){let f=!1;for(const[m,v]of Object.entries(u||{})){const y=this.options[m]??null;if(JSON.stringify(v??null)!==JSON.stringify(y)){f=!0;break}}f&&(this.options={...this.options,...fp$1.cloneDeep(u)},await this.getInitialData())}async refresh(){if(get_store_value(this.store).loading)return;this.store.update(S=>({...S,loading:!0}));const{rows:u,info:f,error:m,cursor:v}=await this.getPage();let{cursors:y}=get_store_value(this.store);const{pageNumber:w}=get_store_value(this.store);if(!u.length&&w>0)return this.store.update(S=>({...S,loading:!1,cursors:y.slice(0,w)})),await this.prevPage();y[w+1]!=v&&(y=y.slice(0,w+1),y[w+1]=v),this.store.update(S=>({...S,rows:u,info:f,loading:!1,error:m,cursors:y}))}hasNextPage(u){return u.cursors[u.pageNumber+1]!=null}hasPrevPage(u){return u.pageNumber>0}async nextPage(){const u=get_store_value(this.derivedStore);if(u.loading||!this.options.paginate||!u.hasNextPage)return;const f=u.cursors[u.pageNumber+1];this.store.update(S=>({...S,loading:!0,cursor:f,pageNumber:S.pageNumber+1}));const{rows:m,info:v,hasNextPage:y,cursor:w,error:k}=await this.getPage();this.store.update(S=>{let{cursors:M,pageNumber:T}=S;return y&&(M[T+1]=w),{...S,rows:m,info:v,cursors:M,loading:!1,error:k}})}async prevPage(){const u=get_store_value(this.derivedStore);if(u.loading||!this.options.paginate||!u.hasPrevPage)return;const f=u.cursors[u.pageNumber-1];this.store.update(w=>({...w,loading:!0,cursor:f,pageNumber:w.pageNumber-1}));const{rows:m,info:v,error:y}=await this.getPage();this.store.update(w=>({...w,rows:m,info:v,loading:!1,error:y}))}}class TableFetch extends BaseDataFetch{async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!0,supportsPagination:!0}}async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u.tableId))return null;try{return await this.API.fetchTableDefinition(u.tableId)}catch(f){return this.store.update(m=>({...m,error:f})),null}}async getData(){const{datasource:u,limit:f,sortColumn:m,sortOrder:v,sortType:y,paginate:w}=this.options,{tableId:k}=u,{cursor:S,query:M}=get_store_value(this.store);try{const T=await this.API.searchTable(k,{query:M,limit:f,sort:m,sortOrder:v??SortOrder.ASCENDING,sortType:y,paginate:w,bookmark:S});return{rows:(T==null?void 0:T.rows)||[],hasNextPage:(T==null?void 0:T.hasNextPage)||!1,cursor:(T==null?void 0:T.bookmark)||null}}catch(T){return{rows:[],hasNextPage:!1,error:T}}}}class ViewFetch extends BaseDataFetch{async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u.tableId))return null;try{return await this.API.fetchTableDefinition(u.tableId)}catch(f){return this.store.update(m=>({...m,error:f})),null}}getSchema(u){var m,v;const{datasource:f}=this.options;return(v=(m=u==null?void 0:u.views)==null?void 0:m[f==null?void 0:f.name])==null?void 0:v.schema}async getData(){const{datasource:u}=this.options;try{return{rows:await this.API.fetchViewData(u.name,{calculation:u.calculation,field:u.field,groupBy:u.groupBy,tableId:u.tableId})||[]}}catch(f){return console.error(f,{datasource:u}),{rows:[]}}}}class ViewV2Fetch extends BaseDataFetch{async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!0,supportsPagination:!0}}async getDefinition(){const{datasource:u}=this.options;try{const f=await this.API.viewV2.fetchDefinition(u.id);return f==null?void 0:f.data}catch(f){return this.store.update(m=>({...m,error:f})),null}}getDefaultSortColumn(){return null}async getData(){var T;const{datasource:u,limit:f,sortColumn:m,sortOrder:v,sortType:y,paginate:w}=this.options,{cursor:k,query:S,definition:M}=get_store_value(this.store);if((M==null?void 0:M.type)===ViewV2Type.CALCULATION&&!Object.values(M.schema||{}).some(isCalculationField))return{rows:[],hasNextPage:!1,cursor:null,error:null};!m&&((T=M==null?void 0:M.sort)!=null&&T.field)&&(this.options.sortColumn=M.sort.field,this.options.sortOrder=M.sort.order||SortOrder.ASCENDING);try{const E={query:S,paginate:w,limit:f,bookmark:k,sort:m,sortOrder:v,sortType:y};if(w){const H=await this.API.viewV2.fetch(u.id,{...E,paginate:w});return{rows:(H==null?void 0:H.rows)||[],hasNextPage:(H==null?void 0:H.hasNextPage)||!1,cursor:(H==null?void 0:H.bookmark)||null}}else{const H=await this.API.viewV2.fetch(u.id,{...E,paginate:w});return{rows:(H==null?void 0:H.rows)||[],hasNextPage:!1,cursor:null}}}catch(E){return{rows:[],hasNextPage:!1,cursor:null,error:E}}}}class QueryFetch extends BaseDataFetch{async determineFeatureFlags(){var m,v,y,w,k,S;const u=await this.getDefinition();return{supportsPagination:!!((v=(m=u==null?void 0:u.fields)==null?void 0:m.pagination)!=null&&v.type)&&!!((w=(y=u==null?void 0:u.fields)==null?void 0:y.pagination)!=null&&w.location)&&!!((S=(k=u==null?void 0:u.fields)==null?void 0:k.pagination)!=null&&S.pageParam)}}async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u._id))return null;try{const f=await this.API.fetchQueryDefinition(u._id);return f.fields||(f.fields=u.fields),f}catch{return null}}getDefaultSortColumn(){return null}async getData(){var T,E;const{datasource:u,limit:f,paginate:m}=this.options,{supportsPagination:v}=this.features,{cursor:y,definition:w}=get_store_value(this.store),k=(E=(T=w==null?void 0:w.fields)==null?void 0:T.pagination)==null?void 0:E.type,S=cloneDeep$1(u.queryParams||{});for(const H of(u==null?void 0:u.parameters)||[])S[H.name]||(S[H.name]=H.default);const M={parameters:S};if(m&&v){const H=k==="page"?parseInt(y||"1"):y;M.pagination={page:H,limit:f}}try{const H=await this.API.executeQuery(u==null?void 0:u._id,M),{data:F,pagination:Z,...$}=H;let J=null,ae=!1;return m&&v&&(k==="page"?(J=M.pagination.page+1,ae=(F==null?void 0:F.length)===f&&f>0):(J=Z==null?void 0:Z.cursor,ae=J!=null)),{rows:F||[],info:$,cursor:J,hasNextPage:ae}}catch{return{rows:[],hasNextPage:!1}}}}class RelationshipFetch extends BaseDataFetch{async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u.tableId))return null;try{return await this.API.fetchTableDefinition(u.tableId)}catch(f){return this.store.update(m=>({...m,error:f})),null}}async getData(){const{datasource:u}=this.options;if(!(u!=null&&u.rowId)||!(u!=null&&u.rowTableId))return{rows:[]};try{return{rows:await this.API.fetchRelationshipData(u.rowTableId,u.rowId,u.fieldName)}}catch{return{rows:[]}}}}class NestedProviderFetch extends BaseDataFetch{async getDefinition(){var f,m;const{datasource:u}=this.options;return{schema:(f=u==null?void 0:u.value)==null?void 0:f.schema,primaryDisplay:(m=u==null?void 0:u.value)==null?void 0:m.primaryDisplay}}async getData(){var f;const{datasource:u}=this.options;return{rows:((f=u==null?void 0:u.value)==null?void 0:f.rows)||[],hasNextPage:!1,cursor:null}}}function isArrayOfStrings(p){return Array.isArray(p)&&!!p[0]&&typeof p[0]!="object"}class FieldFetch extends BaseDataFetch{async getDefinition(){const{datasource:u}=this.options;let f;return u.fieldType==="attachment"?f={url:{type:"string"},name:{type:"string"}}:u.fieldType==="array"&&(f={value:{type:"string"}}),{schema:f}}async getData(){const{datasource:u}=this.options,f=(u==null?void 0:u.value)||[];let m;return isArrayOfStrings(f)?m=f.map(v=>({value:v})):m=f,{rows:m||[],hasNextPage:!1,cursor:null}}}class JSONArrayFetch extends FieldFetch{async getDefinition(){const{datasource:u}=this.options;try{const f=await this.API.fetchTableDefinition(u.tableId);return{schema:getJSONArrayDatasourceSchema(f==null?void 0:f.schema,u)}}catch{return null}}}class UserFetch extends BaseDataFetch{constructor(u){super({...u,datasource:{type:"user",tableId:InternalTable.USER_METADATA}})}async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!1,supportsPagination:!0}}async getDefinition(){return{schema:{}}}async getData(){const{limit:u,paginate:f}=this.options,{cursor:m,query:v}=get_store_value(this.store),{appId:y,paginated:w,...k}=v,S=isSupportedUserSearch(k)?k:{};try{const M={bookmark:m??void 0,query:S??void 0,appId:y,paginate:w||f,limit:u},T=await this.API.searchUsers(M);return{rows:(T==null?void 0:T.data)||[],hasNextPage:(T==null?void 0:T.hasNextPage)||!1,cursor:(T==null?void 0:T.nextPage)||null}}catch(M){return{rows:[],hasNextPage:!1,error:M}}}}class GroupUserFetch extends BaseDataFetch{constructor(u){super({...u,datasource:{type:"groupUser",tableId:InternalTable.USER_METADATA}})}async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!1,supportsPagination:!0}}async getDefinition(){return{schema:{}}}async getData(){const{query:u,cursor:f}=get_store_value(this.store);try{const m=await this.API.getGroupUsers({id:u.groupId,emailSearch:u.emailSearch,bookmark:f??void 0});return{rows:(m==null?void 0:m.users)||[],hasNextPage:(m==null?void 0:m.hasNextPage)||!1,cursor:(m==null?void 0:m.bookmark)||null}}catch(m){return{rows:[],hasNextPage:!1,error:m}}}}class CustomFetch extends BaseDataFetch{getType(u){return u==null?"string":typeof u==="object"?Array.isArray(u)?"array":"json":isNaN(u)?"string":"number"}parseCustomData(u){if(!u)return[];if(Array.isArray(u))return u;if(typeof u=="string"){try{const f=JSON.parse(u);return Array.isArray(f)?f:[f]}catch{}return u.includes(`
383
+ `;var HTTPMethod=(p=>(p.POST="POST",p.PATCH="PATCH",p.GET="GET",p.PUT="PUT",p.DELETE="DELETE",p))(HTTPMethod||{});const BannedSearchTypes=[FieldType.LINK,FieldType.ATTACHMENT_SINGLE,FieldType.ATTACHMENTS,FieldType.FORMULA,FieldType.JSON,FieldType.ATTACHMENT_SINGLE,FieldType.SIGNATURE_SINGLE,"jsonarray","queryarray"],Cookies={Auth:"budibase:auth",CurrentApp:"budibase:currentapp",ReturnUrl:"budibase:returnurl",AccountReturnUrl:"budibase:account:returnurl",OnboardingProcessCorrelationKey:BpmCorrelationKey.ONBOARDING};var TableNames=(p=>(p.USERS="ta_users",p))(TableNames||{});const BudibaseRoles={AppUser:"appUser",Developer:"developer",Creator:"creator",Admin:"admin",Owner:"owner"},BudibaseRoleOptionsOld=[{label:"Developer",value:BudibaseRoles.Developer}],BudibaseRoleOptions=[{label:"Account admin",value:BudibaseRoles.Admin,subtitle:"Has full access to all apps and settings in your account",sortOrder:1},{label:"Creator",value:BudibaseRoles.Creator,subtitle:"Can create and edit apps they have access to",sortOrder:2},{label:"App user",value:BudibaseRoles.AppUser,subtitle:"Can only use published apps they have access to",sortOrder:3}],ExtendedBudibaseRoleOptions=[{label:"Account holder",value:BudibaseRoles.Owner,sortOrder:0},...BudibaseRoleOptions,...BudibaseRoleOptionsOld],PlanType={FREE:"free",TEAM:"team",PRO:"pro",BUSINESS:"business",PREMIUM:"premium",ENTERPRISE:"enterprise",ENTERPRISE_BASIC_TRIAL:"enterprise_basic_trial"},ApiVersion="1",Roles={ADMIN:"ADMIN",POWER:"POWER",BASIC:"BASIC",PUBLIC:"PUBLIC",BUILDER:"BUILDER",CREATOR:"CREATOR"},EventPublishType={ENV_VAR_UPGRADE_PANEL_OPENED:"environment_variable_upgrade_panel_opened"},ContextScopes={Local:"local",Global:"global"},TypeIconMap={[FieldType.STRING]:"Text",[FieldType.OPTIONS]:"Dropdown",[FieldType.DATETIME]:"Calendar",[FieldType.BARCODEQR]:"Camera",[FieldType.SIGNATURE_SINGLE]:"AnnotatePen",[FieldType.LONGFORM]:"TextAlignLeft",[FieldType.ARRAY]:"Duplicate",[FieldType.NUMBER]:"123",[FieldType.BOOLEAN]:"Boolean",[FieldType.ATTACHMENTS]:"DocumentFragmentGroup",[FieldType.ATTACHMENT_SINGLE]:"DocumentFragment",[FieldType.LINK]:"DataCorrelated",[FieldType.FORMULA]:"Calculator",[FieldType.AI]:"MagicWand",[FieldType.JSON]:"Brackets",[FieldType.BIGINT]:"TagBold",[FieldType.AUTO]:"Shapes",[FieldType.BB_REFERENCE]:{[BBReferenceFieldSubType.USER]:"UserGroup",[BBReferenceFieldSubType.USERS]:"UserGroup"},[FieldType.BB_REFERENCE_SINGLE]:{[BBReferenceFieldSubType.USER]:"User"}},OptionColours=[...new Array(12).keys()].map(p=>`hsla(${(p+1)*222%360}, 90%, 75%, 0.3)`),FilterOperator={ANY:"any",ALL:"all"},OnEmptyFilter={RETURN_ALL:"all",RETURN_NONE:"none"},FilterValueType={BINDING:"Binding",VALUE:"Value"},FieldPermissions={WRITABLE:"writable",READONLY:"readonly",HIDDEN:"hidden"},Constants$2=Object.freeze(Object.defineProperty({__proto__:null,ApiVersion,BannedSearchTypes,BudibaseRoleOptions,BudibaseRoleOptionsOld,BudibaseRoles,ContextScopes,Cookies,DEFAULT_BB_DATASOURCE_ID,EventPublishType,ExtendedBudibaseRoleOptions,Features:Feature,FieldPermissions,FilterOperator,FilterValueType,OnEmptyFilter,OperatorOptions,OptionColours,PlanType,Roles,SqlNumberTypeRangeMap,TableNames,TypeIconMap},Symbol.toStringTag,{value:"Module"})),buildAnalyticsEndpoints=p=>({getAnalyticsStatus:async()=>await p.get({url:"/api/bbtel"}),analyticsPing:async u=>await p.post({url:"/api/bbtel/ping",body:{...u,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})}),buildAIEndpoints=p=>({generateCronExpression:async u=>await p.post({url:"/api/ai/cron",body:{prompt:u}})}),buildAppEndpoints=p=>({fetchAppPackage:async u=>await p.get({url:`/api/applications/${u}/appPackage`}),saveAppMetadata:async(u,f)=>await p.put({url:`/api/applications/${u}`,body:f}),publishAppChanges:async u=>await p.post({url:`/api/applications/${u}/publish`}),revertAppChanges:async u=>await p.post({url:`/api/dev/${u}/revert`}),updateAppClientVersion:async u=>await p.post({url:`/api/applications/${u}/client/update`}),revertAppClientVersion:async u=>await p.post({url:`/api/applications/${u}/client/revert`}),getAppDeployments:async()=>await p.get({url:"/api/deployments"}),createApp:async u=>await p.post({url:"/api/applications",body:u,json:!1}),duplicateApp:async(u,f)=>await p.post({url:`/api/applications/${u}/duplicate`,body:f,json:!1}),updateAppFromExport:async(u,f)=>{const m=getDevAppID(u);return await p.post({url:`/api/applications/${m}/import`,body:f,json:!1})},importApps:async u=>await p.post({url:"/api/cloud/import",body:u,json:!1}),unpublishApp:async u=>await p.post({url:`/api/applications/${u}/unpublish`}),deleteApp:async u=>await p.delete({url:`/api/applications/${u}`}),releaseAppLock:async u=>await p.delete({url:`/api/dev/${u}/lock`}),fetchSystemDebugInfo:async()=>await p.get({url:"/api/debug/diagnostics"}),syncApp:async u=>await p.post({url:`/api/applications/${u}/sync`}),getApps:async()=>await p.get({url:"/api/applications?status=all"}),fetchComponentLibDefinitions:async u=>await p.get({url:`/api/${u}/components/definitions`}),addSampleData:async u=>await p.post({url:`/api/applications/${u}/sample`}),setRevertableVersion:async(u,f)=>await p.post({url:`/api/applications/${u}/setRevertableVersion`,body:{revertableVersion:f}})}),buildAttachmentEndpoints=p=>{const u={getSignedDatasourceURL:async(f,m,v)=>await p.post({url:`/api/attachments/${f}/url`,body:{bucket:m,key:v}})};return{...u,uploadAttachment:async(f,m)=>await p.post({url:`/api/attachments/${f}/upload`,body:m,json:!1}),uploadBuilderAttachment:async f=>await p.post({url:"/api/attachments/process",body:f,json:!1}),externalUpload:async(f,m,v,y)=>{const{signedUrl:w,publicUrl:k}=await u.getSignedDatasourceURL(f,m,v);return w?(await p.put({url:w,body:y,json:!1,external:!0,parseResponse:S=>S}),{publicUrl:k}):{publicUrl:void 0}},downloadAttachment:async(f,m,v)=>await p.get({url:`/api/${f}/rows/${m}/attachment/${v}`,parseResponse:y=>y,suppressErrors:!0})}},buildAuthEndpoints=p=>({logIn:async(u,f,m)=>await p.post({url:`/api/global/auth/${u}/login`,body:{username:f,password:m}}),logOut:async()=>await p.post({url:"/api/global/auth/logout"}),setInitInfo:async u=>await p.post({url:"/api/global/auth/init",body:u}),getInitInfo:async()=>await p.get({url:"/api/global/auth/init"}),requestForgotPassword:async(u,f)=>await p.post({url:`/api/global/auth/${u}/reset`,body:{email:f}}),resetPassword:async(u,f,m)=>await p.post({url:`/api/global/auth/${u}/reset/update`,body:{password:f,resetCode:m}})}),buildAutomationEndpoints=p=>({triggerAutomation:async(u,f,m)=>await p.post({url:`/api/automations/${u}/trigger`,body:{fields:f,timeout:m}}),testAutomation:async(u,f)=>await p.post({url:`/api/automations/${u}/test`,body:f}),getAutomations:async()=>await p.get({url:"/api/automations"}),getAutomationDefinitions:async()=>await p.get({url:"/api/automations/definitions/list"}),createAutomation:async u=>await p.post({url:"/api/automations",body:u}),updateAutomation:async u=>await p.put({url:"/api/automations",body:u}),deleteAutomation:async(u,f)=>await p.delete({url:`/api/automations/${u}/${f}`}),getAutomationLogs:async u=>await p.post({url:"/api/automations/logs/search",body:u}),clearAutomationLogErrors:async(u,f)=>await p.delete({url:"/api/automations/logs",body:{appId:f,automationId:u}})}),buildConfigEndpoints=p=>({saveConfig:async u=>await p.post({url:"/api/global/configs",body:u}),getConfig:async u=>await p.get({url:`/api/global/configs/${u}`}),deleteConfig:async(u,f)=>await p.delete({url:`/api/global/configs/${u}/${f}`}),getTenantConfig:async u=>await p.get({url:`/api/global/configs/public?tenantId=${u}`}),getOIDCConfigs:async u=>await p.get({url:`/api/global/configs/public/oidc?tenantId=${u}`}),getChecklist:async u=>await p.get({url:`/api/global/configs/checklist?tenantId=${u}`}),uploadLogo:async u=>await p.post({url:"/api/global/configs/upload/settings/logoUrl",body:u,json:!1}),uploadFavicon:async u=>await p.post({url:"/api/global/configs/upload/settings/faviconUrl",body:u,json:!1}),uploadOIDCLogo:async(u,f)=>await p.post({url:`/api/global/configs/upload/logos_oidc/${u}`,body:f,json:!1}),getOIDCLogos:async()=>await p.get({url:"/api/global/configs/logos_oidc"})}),buildDatasourceEndpoints=p=>({getDatasources:async()=>await p.get({url:"/api/datasources"}),buildDatasourceSchema:async(u,f)=>await p.post({url:`/api/datasources/${u}/schema`,body:{tablesFilter:f}}),createDatasource:async u=>await p.post({url:"/api/datasources",body:u}),updateDatasource:async u=>await p.put({url:`/api/datasources/${u._id}`,body:u}),deleteDatasource:async(u,f)=>await p.delete({url:`/api/datasources/${u}/${f}`}),validateDatasource:async u=>await p.post({url:"/api/datasources/verify",body:{datasource:u}}),fetchInfoForDatasource:async u=>await p.post({url:"/api/datasources/info",body:{datasource:u}}),fetchExternalSchema:async u=>await p.get({url:`/api/datasources/${u}/schema/external`})}),buildFlagEndpoints=p=>({getFlags:async()=>await p.get({url:"/api/users/flags"}),updateFlag:async(u,f)=>await p.post({url:"/api/users/flags",body:{flag:u,value:f}}),toggleUiFeature:async u=>await p.post({url:`/api/beta/${u}`})}),buildLayoutEndpoints=p=>({saveLayout:async u=>await p.post({url:"/api/layouts",body:u}),deleteLayout:async(u,f)=>await p.delete({url:`/api/layouts/${u}/${f}`})}),buildOtherEndpoints=p=>({getEnvironment:async()=>await p.get({url:"/api/system/environment"}),getSystemStatus:async()=>await p.get({url:"/api/system/status"}),getIntegrations:async()=>await p.get({url:"/api/integrations"}),getBudibaseVersion:async()=>(await p.get({url:"/api/dev/version"})).version,getBasePermissions:async()=>await p.get({url:"/api/permission/builtin"})}),buildPermissionsEndpoints=p=>({getPermissionForResource:async u=>await p.get({url:`/api/permission/${u}`}),updatePermissionForResource:async(u,f,m)=>await p.post({url:`/api/permission/${f}/${u}/${m}`}),removePermissionFromResource:async(u,f,m)=>await p.delete({url:`/api/permission/${f}/${u}/${m}`}),getDependants:async u=>await p.get({url:`/api/permission/${u}/dependants`})}),buildQueryEndpoints=p=>({executeQuery:async(u,{pagination:f,parameters:m}={})=>await p.post({url:`/api/v2/queries/${u}`,body:{parameters:m,pagination:f}}),fetchQueryDefinition:async u=>await p.get({url:`/api/queries/${u}`,cache:!0}),getQueries:async()=>await p.get({url:"/api/queries"}),saveQuery:async u=>await p.post({url:"/api/queries",body:u}),deleteQuery:async(u,f)=>await p.delete({url:`/api/queries/${u}/${f}`}),importQueries:async u=>await p.post({url:"/api/queries/import",body:u}),previewQuery:async u=>await p.post({url:"/api/queries/preview",body:u})}),buildRelationshipEndpoints=p=>({fetchRelationshipData:async(u,f,m)=>{const v=await p.get({url:`/api/${u}/${f}/enrich?field=${m}`});return m?v[m]||[]:[v]}}),buildRoleEndpoints=p=>({deleteRole:async(u,f)=>await p.delete({url:`/api/roles/${u}/${f}`}),saveRole:async u=>await p.post({url:"/api/roles",body:u}),getRoles:async()=>await p.get({url:"/api/roles"}),getRolesForApp:async u=>await p.get({url:`/api/global/roles/${u}`}),getAccessibleRoles:async()=>await p.get({url:"/api/roles/accessible"})}),buildRouteEndpoints=p=>({fetchClientAppRoutes:async()=>await p.get({url:"/api/routing/client"}),fetchAppRoutes:async()=>await p.get({url:"/api/routing"})}),buildRowEndpoints=p=>({fetchRow:async(u,f)=>await p.get({url:`/api/${u}/rows/${f}`}),saveRow:async(u,f=!1)=>{const m=u._viewId||u.tableId;return await p.post({url:`/api/${m}/rows`,body:u,suppressErrors:f})},patchRow:async(u,f=!1)=>{const m=u._viewId||u.tableId;return await p.patch({url:`/api/${m}/rows`,body:u,suppressErrors:f})},deleteRow:async(u,f)=>await p.delete({url:`/api/${u}/rows`,body:{_id:f}}),deleteRows:async(u,f)=>(f.forEach(m=>{typeof m=="object"&&(m==null||delete m._viewId)}),await p.delete({url:`/api/${u}/rows`,body:{rows:f}})),exportRows:async(u,f,m)=>await p.post({url:`/api/${u}/rows/exportRows?format=${f}`,body:m,parseResponse:async v=>await v.text()})}),buildScreenEndpoints=p=>({saveScreen:async u=>await p.post({url:"/api/screens",body:u}),deleteScreen:async(u,f)=>await p.delete({url:`/api/screens/${u}/${f}`})}),buildTableEndpoints=p=>({fetchTableDefinition:async u=>await p.get({url:`/api/tables/${u}`,cache:!0}),fetchTableData:async u=>await p.get({url:`/api/${u}/rows`}),searchTable:async(u,f)=>await p.post({url:`/api/${u}/search`,body:f}),importTableData:async(u,f,m)=>await p.post({url:`/api/tables/${u}/import`,body:{rows:f,identifierFields:m}}),csvToJson:async u=>await p.post({url:"/api/convert/csvToJson",body:{csvString:u}}),getTables:async()=>await p.get({url:"/api/tables"}),getTable:async u=>await p.get({url:`/api/tables/${u}`}),saveTable:async u=>await p.post({url:"/api/tables",body:u}),deleteTable:async(u,f)=>await p.delete({url:`/api/tables/${u}/${f}`}),validateNewTableImport:async(u,f)=>await p.post({url:"/api/tables/validateNewTableImport",body:{rows:u,schema:f}}),validateExistingTableImport:async(u,f)=>await p.post({url:"/api/tables/validateExistingTableImport",body:{rows:u,tableId:f}}),migrateColumn:async(u,f,m)=>await p.post({url:`/api/tables/${u}/migrate`,body:{oldColumn:f,newColumn:m}})}),buildTemplateEndpoints=p=>({getEmailTemplateDefinitions:async()=>await p.get({url:"/api/global/template/definitions"}),getEmailTemplates:async()=>await p.get({url:"/api/global/template/email"}),saveEmailTemplate:async u=>await p.post({url:"/api/global/template",body:u}),getAppTemplates:async()=>await p.get({url:"/api/templates"})}),buildUserEndpoints=p=>({getUsers:async()=>await p.get({url:"/api/global/users"}),searchUsers:async u=>await p.post({url:"/api/global/users/search",body:u}),getUser:async u=>await p.get({url:`/api/global/users/${u}`}),updateOwnMetadata:async u=>await p.post({url:"/api/users/metadata/self",body:u}),createAdminUser:async u=>await p.post({url:"/api/global/users/init",body:u}),saveUser:async u=>await p.post({url:"/api/global/users",body:u}),createUsers:async(u,f)=>(await p.post({url:"/api/global/users/bulk",body:{create:{users:u,groups:f}}})).created,deleteUser:async u=>await p.delete({url:`/api/global/users/${u}`}),deleteUsers:async u=>(await p.post({url:"/api/global/users/bulk",body:{delete:{users:u}}})).deleted,onboardUsers:async u=>await p.post({url:"/api/global/users/onboard",body:u}),updateUserInvite:async(u,f)=>await p.post({url:`/api/global/users/invite/update/${u}`,body:f}),getUserInvite:async u=>await p.get({url:`/api/global/users/invite/${u}`}),getUserInvites:async()=>await p.get({url:"/api/global/users/invites"}),inviteUsers:async u=>await p.post({url:"/api/global/users/multi/invite",body:u}),removeUserInvites:async u=>await p.post({url:"/api/global/users/multi/invite/delete",body:u}),acceptInvite:async u=>await p.post({url:"/api/global/users/invite/accept",body:u}),getUserCountByApp:async u=>(await p.get({url:`/api/global/users/count/${u}`})).userCount,addAppBuilder:async(u,f)=>await p.post({url:`/api/global/users/${u}/app/${f}/builder`}),removeAppBuilder:async(u,f)=>await p.delete({url:`/api/global/users/${u}/app/${f}/builder`}),getAccountHolder:async()=>await p.get({url:"/api/global/users/accountholder"})}),buildSelfEndpoints=p=>({generateAPIKey:async()=>{const u=await p.post({url:"/api/global/self/api_key"});return u==null?void 0:u.apiKey},fetchDeveloperInfo:async()=>p.get({url:"/api/global/self/api_key"}),fetchSelf:async()=>await p.get({url:"/api/self"}),fetchBuilderSelf:async()=>await p.get({url:"/api/global/self"}),updateSelf:async u=>await p.post({url:"/api/global/self",body:u})}),buildViewEndpoints=p=>({fetchViewData:async(u,{field:f,groupBy:m,calculation:v})=>{const y=new URLSearchParams;v&&(f&&y.set("field",f),y.set("calculation",v)),m&&y.set("group",m);const w=f?`/api/views/${encodeURIComponent(u)}?${y}`:`/api/views/${encodeURIComponent(u)}`;return await p.get({url:w})},exportView:async(u,f)=>{const m=encodeURIComponent(u);return await p.get({url:`/api/views/export?view=${m}&format=${f}`,parseResponse:async v=>await v.text()})},saveView:async u=>await p.post({url:"/api/views",body:u}),deleteView:async u=>await p.delete({url:`/api/views/${encodeURIComponent(u)}`})}),buildViewV2Endpoints=p=>({fetchDefinition:async u=>await p.get({url:`/api/v2/views/${encodeURIComponent(u)}`,cache:!0}),create:async u=>await p.post({url:"/api/v2/views",body:u}),update:async u=>await p.put({url:`/api/v2/views/${encodeURIComponent(u.id)}`,body:u}),fetch:async(u,f)=>await p.post({url:`/api/v2/views/${encodeURIComponent(u)}/search`,body:f}),delete:async u=>await p.delete({url:`/api/v2/views/${encodeURIComponent(u)}`})}),buildLicensingEndpoints=p=>({activateLicenseKey:async u=>p.post({url:"/api/global/license/key",body:{licenseKey:u}}),deleteLicenseKey:async()=>p.delete({url:"/api/global/license/key"}),getLicenseKey:async()=>{try{return await p.get({url:"/api/global/license/key"})}catch(u){if(u.status!==404)throw u}},activateOfflineLicense:async u=>p.post({url:"/api/global/license/offline",body:{offlineLicenseToken:u}}),deleteOfflineLicense:async()=>p.delete({url:"/api/global/license/offline"}),getOfflineLicense:async()=>{try{return await p.get({url:"/api/global/license/offline"})}catch(u){if(u.status!==404)throw u}},getOfflineLicenseIdentifier:async()=>await p.get({url:"/api/global/license/offline/identifier"}),refreshLicense:async()=>p.post({url:"/api/global/license/refresh"}),getQuotaUsage:async()=>p.get({url:"/api/global/license/usage"})}),buildGroupsEndpoints=p=>{async function u(f,m,v,y){return await p.post({url:`/api/global/groups/${f}/${m}`,body:{[v]:y}})}return{saveGroup:async f=>await p.post({url:"/api/global/groups",body:f}),getGroups:async()=>(await p.get({url:"/api/global/groups"})).data,getGroup:async f=>await p.get({url:`/api/global/groups/${f}`}),deleteGroup:async(f,m)=>await p.delete({url:`/api/global/groups/${f}/${m}`}),getGroupUsers:async({id:f,bookmark:m,emailSearch:v})=>{let y=`/api/global/groups/${f}/users?`;return m&&(y+=`bookmark=${m}&`),v&&(y+=`emailSearch=${v}`),await p.get({url:y})},addUsersToGroup:async(f,m)=>u(f,"users","add",m),removeUsersFromGroup:async(f,m)=>u(f,"users","remove",m),addAppsToGroup:async(f,m)=>u(f,"apps","add",m),removeAppsFromGroup:async(f,m)=>u(f,"apps","remove",m),addGroupAppBuilder:async(f,m)=>await p.post({url:`/api/global/groups/${f}/app/${m}/builder`}),removeGroupAppBuilder:async(f,m)=>await p.delete({url:`/api/global/groups/${f}/app/${m}/builder`})}},buildPluginEndpoints=p=>({uploadPlugin:async u=>await p.post({url:"/api/plugin/upload",body:u,json:!1}),createPlugin:async u=>await p.post({url:"/api/plugin",body:u}),getPlugins:async()=>await p.get({url:"/api/plugin"}),deletePlugin:async u=>await p.delete({url:`/api/plugin/${u}`})}),buildBackupEndpoints=p=>({createManualBackup:async u=>await p.post({url:`/api/apps/${u}/backups`}),searchBackups:async(u,f)=>await p.post({url:`/api/apps/${u}/backups/search`,body:f}),deleteBackup:async(u,f)=>await p.delete({url:`/api/apps/${u}/backups/${f}`}),restoreBackup:async(u,f,m)=>await p.post({url:`/api/apps/${u}/backups/${f}/import`,body:{name:m}})}),buildEnvironmentVariableEndpoints=p=>({checkEnvironmentVariableStatus:async()=>await p.get({url:"/api/env/variables/status"}),fetchEnvironmentVariables:async()=>await p.get({url:"/api/env/variables",json:!1}),createEnvironmentVariable:async u=>await p.post({url:"/api/env/variables",body:u}),deleteEnvironmentVariable:async u=>await p.delete({url:`/api/env/variables/${u}`}),updateEnvironmentVariable:async(u,f)=>await p.patch({url:`/api/env/variables/${u}`,body:f})}),buildEventEndpoints=p=>({publishEvent:async u=>await p.post({url:"/api/global/event/publish",body:{type:u}})}),buildAuditLogEndpoints=p=>({searchAuditLogs:async u=>await p.post({url:"/api/global/auditlogs/search",body:u}),getEventDefinitions:async()=>await p.get({url:"/api/global/auditlogs/definitions"}),getDownloadUrl:u=>`/api/global/auditlogs/download?query=${encodeURIComponent(JSON.stringify(u))}`}),buildLogsEndpoints=p=>({getSystemLogs:async()=>await p.get({url:"/api/system/logs",json:!1,parseResponse:async u=>u})}),buildMigrationEndpoints=p=>({getMigrationStatus:async()=>await p.get({url:"/api/migrations/status"})}),buildRowActionEndpoints=p=>({fetch:async u=>(await p.get({url:`/api/tables/${u}/actions`})).actions,create:async(u,f)=>await p.post({url:`/api/tables/${u}/actions`,body:{name:f}}),delete:async(u,f)=>await p.delete({url:`/api/tables/${u}/actions/${f}`}),enableView:async(u,f,m)=>await p.post({url:`/api/tables/${u}/actions/${f}/permissions/${m}`}),disableView:async(u,f,m)=>await p.delete({url:`/api/tables/${u}/actions/${f}/permissions/${m}`}),trigger:async(u,f,m)=>await p.post({url:`/api/tables/${u}/actions/${f}/trigger`,body:{rowId:m}})}),APISessionID=uuid(),createAPIClient=(p={})=>{let u={};const f=async(M,T,E=!1)=>{let H=M.statusText,F=null;try{F=await M.json(),F!=null&&F.message?H=F.message:F!=null&&F.error&&(H=JSON.stringify(F.error))}catch{}return{message:H,json:F,status:M.status,url:M.url,method:T,handled:!0,suppressErrors:E}},m=(M,T,E)=>({message:M,json:null,status:400,url:T,method:E,handled:!0,suppressErrors:!1}),v=async M=>{let{json:T,method:E,external:H,body:F,url:Z,parseResponse:$,suppressErrors:J}=M;T=T&&E!==HTTPMethod.GET;let ae={Accept:"application/json"};ae[Header.SESSION_ID]=APISessionID,H||(ae[Header.API_VER]=ApiVersion),T&&(ae["Content-Type"]="application/json"),p!=null&&p.attachHeaders&&p.attachHeaders(ae);let ie=F;if(T)try{ie=JSON.stringify(F)}catch{throw m("Invalid JSON body",Z,E)}let he;try{he=await fetch(Z,{method:E,headers:ae,body:ie,credentials:"same-origin"})}catch{throw delete u[Z],m("Failed to send request",Z,E)}if(he.status>=200&&he.status<400){y(he);try{return he.status===204?void 0:$?await $(he):await he.json()}catch(fe){throw delete u[Z],`Failed to parse response: ${fe}`}}else throw delete u[Z],await f(he,E,J)},y=M=>{if(!p.onMigrationDetected)return;const T=M.headers.get(Header.MIGRATING_APP);T&&p.onMigrationDetected(T)},w=async M=>{const T=M.url;return u[T]||(u[T]=v(M),u[T]=await u[T]),await u[T]},k=M=>async T=>{try{let E={json:!0,external:!1,suppressErrors:!1,cache:!1,method:M,...T},{url:H,cache:F,external:Z}=E;return Z||(E.url=`/${H}`.replace("//","/")),await(F&&(p==null?void 0:p.enableCaching)?w:v)(E)}catch(E){throw p!=null&&p.onError&&p.onError(E),E}};let S={post:k(HTTPMethod.POST),get:k(HTTPMethod.GET),patch:k(HTTPMethod.PATCH),delete:k(HTTPMethod.DELETE),put:k(HTTPMethod.PUT),invalidateCache:()=>{u={}},getAppID:()=>{var T;let M={};return(T=p==null?void 0:p.attachHeaders)==null||T.call(p,M),M==null?void 0:M[Header.APP_ID]}};return{...S,...buildAIEndpoints(S),...buildAnalyticsEndpoints(S),...buildAppEndpoints(S),...buildAttachmentEndpoints(S),...buildAuthEndpoints(S),...buildAutomationEndpoints(S),...buildConfigEndpoints(S),...buildDatasourceEndpoints(S),...buildFlagEndpoints(S),...buildLayoutEndpoints(S),...buildOtherEndpoints(S),...buildPermissionsEndpoints(S),...buildQueryEndpoints(S),...buildRelationshipEndpoints(S),...buildRoleEndpoints(S),...buildRouteEndpoints(S),...buildRowEndpoints(S),...buildScreenEndpoints(S),...buildTableEndpoints(S),...buildTemplateEndpoints(S),...buildUserEndpoints(S),...buildViewEndpoints(S),...buildSelfEndpoints(S),...buildLicensingEndpoints(S),...buildGroupsEndpoints(S),...buildPluginEndpoints(S),...buildBackupEndpoints(S),...buildEnvironmentVariableEndpoints(S),...buildEventEndpoints(S),...buildAuditLogEndpoints(S),...buildLogsEndpoints(S),...buildMigrationEndpoints(S),viewV2:buildViewV2Endpoints(S),rowActions:buildRowActionEndpoints(S)}},getJSONArrayDatasourceSchema=(p,u)=>{let f=p,m=[];u.prefixKeys&&(m=u.prefixKeys.concat(["schema"])),m=m.concat(u.label.split(".").slice(2));for(let v=0;v<m.length;v++)f=f==null?void 0:f[m[v]],f!=null&&f.schema&&(f=f.schema);return convertJSONSchemaToTableSchema(f,{squashObjects:!0,prefixKeys:m})},convertJSONSchemaToTableSchema=(p,u)=>{if(!p)return null;u={squashObjects:!1,prefixKeys:null,...u},p.schema?p=p.schema:p={value:p};const f=extractJSONSchemaKeys(p,u.squashObjects);let m={};return f.forEach(({key:v,type:y})=>{m[v]={type:y,name:v,prefixKeys:u.prefixKeys}}),m},extractJSONSchemaKeys=(p,u=!1)=>{if(!p||!Object.keys(p).length)return[];let f=[];return Object.keys(p).forEach(m=>{const v=p[m].type;if(v==="json"&&u){const y=extractJSONSchemaKeys(p[m].schema,u);f=f.concat(y.map(w=>({key:`${m}.${w.key}`,type:w.type})))}else f.push({key:m,type:v==="array"?"jsonarray":v})}),f},generateQueryArraySchemas=(p,u)=>{var f,m;for(let v in p)((f=p[v])==null?void 0:f.type)==="json"&&((m=p[v])==null?void 0:m.subtype)==="array"&&hasSchema(u[v])&&(p[v]={schema:{schema:Object.entries(u[v]||{}).reduce((y,[w,k])=>(y[w]={name:w,type:k.type,subtype:k.subtype},y),{}),type:"json"},type:"json",subtype:"array"});return p};function setCookie(p,u,f){getCookie(p)&&removeCookie(p);let m=`${p}=${u}; Path=/;`;f&&(m+=` Domain=${f};`),window.document.cookie=m}function getCookie(p){const f=`; ${document.cookie}`.split(`; ${p}=`);if(f.length===2)return f[1].split(";").shift()}function removeCookie(p){getCookie(p)&&(document.cookie=`${p}=; Max-Age=-99999999; Path=/;`)}const RolePriorities={[Roles.ADMIN]:5,[Roles.CREATOR]:4,[Roles.POWER]:3,[Roles.BASIC]:2,[Roles.PUBLIC]:1},getRolePriority=p=>RolePriorities[p]??0,sleep=p=>new Promise(u=>setTimeout(u,p)),debounce=(p,u=1e3)=>{let f;return async(...m)=>new Promise(v=>{f&&clearTimeout(f),f=setTimeout(async()=>{v(await p(...m))},u)})},throttle=(p,u=1e3)=>{let f,m=!1,v=!1;const y=(...w)=>{if(f=w,m){v=!0;return}p(...f),m=!0,setTimeout(()=>{m=!1,v&&(v=!1,y(...f))},u)};return y},domDebounce=p=>{let u=!1,f;return(...m)=>{f=m,u||(u=!0,requestAnimationFrame(()=>{p(...f),u=!1}))}},buildFormBlockButtonConfig=p=>{const{_id:u,actionType:f,dataSource:m,notificationOverride:v,actionUrl:y,showDeleteButton:w,deleteButtonLabel:k,showSaveButton:S,saveButtonLabel:M}=p||{};if(!u)return;const T=`${u}-form`,E=`${u}-repeater`,H=m==null?void 0:m.resourceId,F=w===!1?"":k==null?void 0:k.trim(),Z=S===!1?"":M==null?void 0:M.trim(),$=[{"##eventHandlerType":"Validate Form",parameters:{componentId:T}},{"##eventHandlerType":"Save Row",parameters:{providerId:T,tableId:H,notificationOverride:v,confirm:null}},{"##eventHandlerType":"Close Screen Modal"},{"##eventHandlerType":"Close Side Panel"},{"##eventHandlerType":"Close Modal"},...f!=="Create"?[]:[{"##eventHandlerType":"Clear Form",parameters:{componentId:T}}],...y?[{"##eventHandlerType":"Navigate To",parameters:{url:y}}]:[]],J=[{"##eventHandlerType":"Delete Row",parameters:{confirm:!0,tableId:H,rowId:`{{ ${makePropSafe(E)}.${makePropSafe("_id")} }}`,revId:`{{ ${makePropSafe(E)}.${makePropSafe("_rev")} }}`,notificationOverride:v}},{"##eventHandlerType":"Close Screen Modal"},{"##eventHandlerType":"Close Side Panel"},{"##eventHandlerType":"Close Modal"},...y?[{"##eventHandlerType":"Navigate To",parameters:{url:y}}]:[]],ae=[];return f&&["Update","Create"].includes(f)&&S!==!1&&ae.push({text:Z||"Save",_id:uuid(),_component:"@budibase/standard-components/button",onClick:$,type:"cta"}),f==="Update"&&w!==!1&&ae.push({text:F||"Delete",_id:uuid(),_component:"@budibase/standard-components/button",onClick:J,quiet:!0,type:"warning"}),ae},buildMultiStepFormBlockDefaultProps=p=>{const{_id:u,stepCount:f,currentStep:m,actionType:v,dataSource:y}=p||{};if(!u||!f)return;const w=`Step {{ [${u}-form].[__currentStep] }}`,k=y==null?void 0:y.resourceId,S=`${u}-form`;let M=[];return m!==0&&M.push({_id:uuid(),_component:"@budibase/standard-components/button",_instanceName:uuid(),text:"Back",type:"secondary",size:"M",onClick:[{parameters:{type:"prev",componentId:S},"##eventHandlerType":"Change Form Step"}]}),m!==f-1&&M.push({_id:uuid(),_component:"@budibase/standard-components/button",_instanceName:uuid(),text:"Next",type:"cta",size:"M",onClick:[{"##eventHandlerType":"Validate Form",parameters:{componentId:S}},{parameters:{type:"next",componentId:S},"##eventHandlerType":"Change Form Step"}]}),v!=="View"&&m===f-1&&M.push({_id:uuid(),_component:"@budibase/standard-components/button",_instanceName:uuid(),text:"Save",type:"cta",size:"M",onClick:[{"##eventHandlerType":"Validate Form",parameters:{componentId:S}},{"##eventHandlerType":"Save Row",parameters:{tableId:k,providerId:S}},...v!=="Create"?[]:[{"##eventHandlerType":"Clear Form",parameters:{componentId:S}}]]}),{buttons:M,title:w}};function parseFilter(p){var f;if(!(p!=null&&p.groups))return p;const u=lodashExports.cloneDeep(p);return u.groups=(f=u.groups)==null?void 0:f.map(m=>{var v,y;return m.filters=(v=m.filters)==null?void 0:v.filter(w=>w.field&&w.operator),(y=m.filters)!=null&&y.length?m:null}).filter(m=>!!m),u}const isBetterSample=(p,u)=>{if(u==null&&p!=null)return!0;if(u!=null&&p==null)return!1;const f=typeof u,m=typeof p;return f!==m?!1:m==="string"&&p.length>u.length||m==="object"&&Object.keys(p).length>Object.keys(u).length},generateGoldenSample=p=>{let u={};return p==null||p.slice(0,100).forEach(f=>{Object.keys(f).forEach(m=>{isBetterSample(f[m],u[m])&&(u[m]=f[m])})}),u},getColumnIcon=p=>{if(p.schema.icon)return p.schema.icon;if(p.calculationType)return"Calculator";if(p.schema.autocolumn)return"MagicWand";if(isDeprecatedSingleUserColumn(p.schema))return"User";const{type:u,subtype:f}=p.schema;return(typeof TypeIconMap[u]=="object"&&f?TypeIconMap[u][f]:TypeIconMap[u])||"Text"},memo=p=>{const u=writable(p);let f=JSON.stringify(p);const m=v=>{const y=JSON.stringify(v);y!==f&&(u.set(v),f=y)};return{subscribe:u.subscribe,set:m,update:v=>{let y=JSON.parse(f);const w=v(y);m(w)}}},derivedMemo=(p,u)=>{const f=derived(p,u),m=memo(get_store_value(f));return f.subscribe(m.set),m},PACKET_TYPES=Object.create(null);PACKET_TYPES.open="0",PACKET_TYPES.close="1",PACKET_TYPES.ping="2",PACKET_TYPES.pong="3",PACKET_TYPES.message="4",PACKET_TYPES.upgrade="5",PACKET_TYPES.noop="6";const PACKET_TYPES_REVERSE=Object.create(null);Object.keys(PACKET_TYPES).forEach(p=>{PACKET_TYPES_REVERSE[PACKET_TYPES[p]]=p});const ERROR_PACKET={type:"error",data:"parser error"},withNativeBlob$1=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",withNativeArrayBuffer$2=typeof ArrayBuffer=="function",isView$1=p=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(p):p&&p.buffer instanceof ArrayBuffer,encodePacket=({type:p,data:u},f,m)=>withNativeBlob$1&&u instanceof Blob?f?m(u):encodeBlobAsBase64(u,m):withNativeArrayBuffer$2&&(u instanceof ArrayBuffer||isView$1(u))?f?m(u):encodeBlobAsBase64(new Blob([u]),m):m(PACKET_TYPES[p]+(u||"")),encodeBlobAsBase64=(p,u)=>{const f=new FileReader;return f.onload=function(){const m=f.result.split(",")[1];u("b"+(m||""))},f.readAsDataURL(p)};function toArray(p){return p instanceof Uint8Array?p:p instanceof ArrayBuffer?new Uint8Array(p):new Uint8Array(p.buffer,p.byteOffset,p.byteLength)}let TEXT_ENCODER;function encodePacketToBinary(p,u){if(withNativeBlob$1&&p.data instanceof Blob)return p.data.arrayBuffer().then(toArray).then(u);if(withNativeArrayBuffer$2&&(p.data instanceof ArrayBuffer||isView$1(p.data)))return u(toArray(p.data));encodePacket(p,!1,f=>{TEXT_ENCODER||(TEXT_ENCODER=new TextEncoder),u(TEXT_ENCODER.encode(f))})}const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup$2=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let p=0;p<chars.length;p++)lookup$2[chars.charCodeAt(p)]=p;const decode$2=p=>{let u=p.length*.75,f=p.length,m,v=0,y,w,k,S;p[p.length-1]==="="&&(u--,p[p.length-2]==="="&&u--);const M=new ArrayBuffer(u),T=new Uint8Array(M);for(m=0;m<f;m+=4)y=lookup$2[p.charCodeAt(m)],w=lookup$2[p.charCodeAt(m+1)],k=lookup$2[p.charCodeAt(m+2)],S=lookup$2[p.charCodeAt(m+3)],T[v++]=y<<2|w>>4,T[v++]=(w&15)<<4|k>>2,T[v++]=(k&3)<<6|S&63;return M},withNativeArrayBuffer$1=typeof ArrayBuffer=="function",decodePacket=(p,u)=>{if(typeof p!="string")return{type:"message",data:mapBinary(p,u)};const f=p.charAt(0);return f==="b"?{type:"message",data:decodeBase64Packet(p.substring(1),u)}:PACKET_TYPES_REVERSE[f]?p.length>1?{type:PACKET_TYPES_REVERSE[f],data:p.substring(1)}:{type:PACKET_TYPES_REVERSE[f]}:ERROR_PACKET},decodeBase64Packet=(p,u)=>{if(withNativeArrayBuffer$1){const f=decode$2(p);return mapBinary(f,u)}else return{base64:!0,data:p}},mapBinary=(p,u)=>{switch(u){case"blob":return p instanceof Blob?p:new Blob([p]);case"arraybuffer":default:return p instanceof ArrayBuffer?p:p.buffer}},SEPARATOR=String.fromCharCode(30),encodePayload=(p,u)=>{const f=p.length,m=new Array(f);let v=0;p.forEach((y,w)=>{encodePacket(y,!1,k=>{m[w]=k,++v===f&&u(m.join(SEPARATOR))})})},decodePayload=(p,u)=>{const f=p.split(SEPARATOR),m=[];for(let v=0;v<f.length;v++){const y=decodePacket(f[v],u);if(m.push(y),y.type==="error")break}return m};function createPacketEncoderStream(){return new TransformStream({transform(p,u){encodePacketToBinary(p,f=>{const m=f.length;let v;if(m<126)v=new Uint8Array(1),new DataView(v.buffer).setUint8(0,m);else if(m<65536){v=new Uint8Array(3);const y=new DataView(v.buffer);y.setUint8(0,126),y.setUint16(1,m)}else{v=new Uint8Array(9);const y=new DataView(v.buffer);y.setUint8(0,127),y.setBigUint64(1,BigInt(m))}p.data&&typeof p.data!="string"&&(v[0]|=128),u.enqueue(v),u.enqueue(f)})}})}let TEXT_DECODER;function totalLength(p){return p.reduce((u,f)=>u+f.length,0)}function concatChunks(p,u){if(p[0].length===u)return p.shift();const f=new Uint8Array(u);let m=0;for(let v=0;v<u;v++)f[v]=p[0][m++],m===p[0].length&&(p.shift(),m=0);return p.length&&m<p[0].length&&(p[0]=p[0].slice(m)),f}function createPacketDecoderStream(p,u){TEXT_DECODER||(TEXT_DECODER=new TextDecoder);const f=[];let m=0,v=-1,y=!1;return new TransformStream({transform(w,k){for(f.push(w);;){if(m===0){if(totalLength(f)<1)break;const S=concatChunks(f,1);y=(S[0]&128)===128,v=S[0]&127,v<126?m=3:v===126?m=1:m=2}else if(m===1){if(totalLength(f)<2)break;const S=concatChunks(f,2);v=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),m=3}else if(m===2){if(totalLength(f)<8)break;const S=concatChunks(f,8),M=new DataView(S.buffer,S.byteOffset,S.length),T=M.getUint32(0);if(T>Math.pow(2,53-32)-1){k.enqueue(ERROR_PACKET);break}v=T*Math.pow(2,32)+M.getUint32(4),m=3}else{if(totalLength(f)<v)break;const S=concatChunks(f,v);k.enqueue(decodePacket(y?S:TEXT_DECODER.decode(S),u)),m=0}if(v===0||v>p){k.enqueue(ERROR_PACKET);break}}}})}const protocol$1=4;function Emitter(p){if(p)return mixin(p)}function mixin(p){for(var u in Emitter.prototype)p[u]=Emitter.prototype[u];return p}Emitter.prototype.on=Emitter.prototype.addEventListener=function(p,u){return this._callbacks=this._callbacks||{},(this._callbacks["$"+p]=this._callbacks["$"+p]||[]).push(u),this},Emitter.prototype.once=function(p,u){function f(){this.off(p,f),u.apply(this,arguments)}return f.fn=u,this.on(p,f),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(p,u){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var f=this._callbacks["$"+p];if(!f)return this;if(arguments.length==1)return delete this._callbacks["$"+p],this;for(var m,v=0;v<f.length;v++)if(m=f[v],m===u||m.fn===u){f.splice(v,1);break}return f.length===0&&delete this._callbacks["$"+p],this},Emitter.prototype.emit=function(p){this._callbacks=this._callbacks||{};for(var u=new Array(arguments.length-1),f=this._callbacks["$"+p],m=1;m<arguments.length;m++)u[m-1]=arguments[m];if(f){f=f.slice(0);for(var m=0,v=f.length;m<v;++m)f[m].apply(this,u)}return this},Emitter.prototype.emitReserved=Emitter.prototype.emit,Emitter.prototype.listeners=function(p){return this._callbacks=this._callbacks||{},this._callbacks["$"+p]||[]},Emitter.prototype.hasListeners=function(p){return!!this.listeners(p).length};const globalThisShim=(()=>typeof self<"u"?self:typeof window<"u"?window:Function("return this")())();function pick(p,...u){return u.reduce((f,m)=>(p.hasOwnProperty(m)&&(f[m]=p[m]),f),{})}const NATIVE_SET_TIMEOUT=globalThisShim.setTimeout,NATIVE_CLEAR_TIMEOUT=globalThisShim.clearTimeout;function installTimerFunctions(p,u){u.useNativeTimers?(p.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThisShim),p.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThisShim)):(p.setTimeoutFn=globalThisShim.setTimeout.bind(globalThisShim),p.clearTimeoutFn=globalThisShim.clearTimeout.bind(globalThisShim))}const BASE64_OVERHEAD=1.33;function byteLength(p){return typeof p=="string"?utf8Length(p):Math.ceil((p.byteLength||p.size)*BASE64_OVERHEAD)}function utf8Length(p){let u=0,f=0;for(let m=0,v=p.length;m<v;m++)u=p.charCodeAt(m),u<128?f+=1:u<2048?f+=2:u<55296||u>=57344?f+=3:(m++,f+=4);return f}function encode$2(p){let u="";for(let f in p)p.hasOwnProperty(f)&&(u.length&&(u+="&"),u+=encodeURIComponent(f)+"="+encodeURIComponent(p[f]));return u}function decode$1(p){let u={},f=p.split("&");for(let m=0,v=f.length;m<v;m++){let y=f[m].split("=");u[decodeURIComponent(y[0])]=decodeURIComponent(y[1])}return u}class TransportError extends Error{constructor(u,f,m){super(u),this.description=f,this.context=m,this.type="TransportError"}}class Transport extends Emitter{constructor(u){super(),this.writable=!1,installTimerFunctions(this,u),this.opts=u,this.query=u.query,this.socket=u.socket}onError(u,f,m){return super.emitReserved("error",new TransportError(u,f,m)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(u){this.readyState==="open"&&this.write(u)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(u){const f=decodePacket(u,this.socket.binaryType);this.onPacket(f)}onPacket(u){super.emitReserved("packet",u)}onClose(u){this.readyState="closed",super.emitReserved("close",u)}pause(u){}createUri(u,f={}){return u+"://"+this._hostname()+this._port()+this.opts.path+this._query(f)}_hostname(){const u=this.opts.hostname;return u.indexOf(":")===-1?u:"["+u+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(u){const f=encode$2(u);return f.length?"?"+f:""}}const alphabet$3="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),length=64,map={};let seed$1=0,i=0,prev;function encode$1(p){let u="";do u=alphabet$3[p%length]+u,p=Math.floor(p/length);while(p>0);return u}function yeast(){const p=encode$1(+new Date);return p!==prev?(seed$1=0,prev=p):p+"."+encode$1(seed$1++)}for(;i<length;i++)map[alphabet$3[i]]=i;let value$1=!1;try{value$1=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch(p){}const hasCORS=value$1;function XHR(p){const u=p.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!u||hasCORS))return new XMLHttpRequest}catch{}if(!u)try{return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}function createCookieJar(){}function empty(){}const hasXHR2=function(){return new XHR({xdomain:!1}).responseType!=null}();class Polling extends Transport{constructor(u){if(super(u),this.polling=!1,typeof location<"u"){const m=location.protocol==="https:";let v=location.port;v||(v=m?"443":"80"),this.xd=typeof location<"u"&&u.hostname!==location.hostname||v!==u.port}const f=u&&u.forceBase64;this.supportsBinary=hasXHR2&&!f,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(u){this.readyState="pausing";const f=()=>{this.readyState="paused",u()};if(this.polling||!this.writable){let m=0;this.polling&&(m++,this.once("pollComplete",function(){--m||f()})),this.writable||(m++,this.once("drain",function(){--m||f()}))}else f()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(u){const f=m=>{if(this.readyState==="opening"&&m.type==="open"&&this.onOpen(),m.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(m)};decodePayload(u,this.socket.binaryType).forEach(f),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const u=()=>{this.write([{type:"close"}])};this.readyState==="open"?u():this.once("open",u)}write(u){this.writable=!1,encodePayload(u,f=>{this.doWrite(f,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const u=this.opts.secure?"https":"http",f=this.query||{};return this.opts.timestampRequests!==!1&&(f[this.opts.timestampParam]=yeast()),!this.supportsBinary&&!f.sid&&(f.b64=1),this.createUri(u,f)}request(u={}){return Object.assign(u,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Request(this.uri(),u)}doWrite(u,f){const m=this.request({method:"POST",data:u});m.on("success",f),m.on("error",(v,y)=>{this.onError("xhr post error",v,y)})}doPoll(){const u=this.request();u.on("data",this.onData.bind(this)),u.on("error",(f,m)=>{this.onError("xhr poll error",f,m)}),this.pollXhr=u}}class Request extends Emitter{constructor(u,f){super(),installTimerFunctions(this,f),this.opts=f,this.method=f.method||"GET",this.uri=u,this.data=f.data!==void 0?f.data:null,this.create()}create(){var u;const f=pick(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");f.xdomain=!!this.opts.xd;const m=this.xhr=new XHR(f);try{m.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){m.setDisableHeaderCheck&&m.setDisableHeaderCheck(!0);for(let v in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(v)&&m.setRequestHeader(v,this.opts.extraHeaders[v])}}catch{}if(this.method==="POST")try{m.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{m.setRequestHeader("Accept","*/*")}catch{}(u=this.opts.cookieJar)===null||u===void 0||u.addCookies(m),"withCredentials"in m&&(m.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(m.timeout=this.opts.requestTimeout),m.onreadystatechange=()=>{var v;m.readyState===3&&((v=this.opts.cookieJar)===null||v===void 0||v.parseCookies(m)),m.readyState===4&&(m.status===200||m.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof m.status=="number"?m.status:0)},0))},m.send(this.data)}catch(v){this.setTimeoutFn(()=>{this.onError(v)},0);return}typeof document<"u"&&(this.index=Request.requestsCount++,Request.requests[this.index]=this)}onError(u){this.emitReserved("error",u,this.xhr),this.cleanup(!0)}cleanup(u){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=empty,u)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Request.requests[this.index],this.xhr=null}}onLoad(){const u=this.xhr.responseText;u!==null&&(this.emitReserved("data",u),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Request.requestsCount=0,Request.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",unloadHandler);else if(typeof addEventListener=="function"){const p="onpagehide"in globalThisShim?"pagehide":"unload";addEventListener(p,unloadHandler,!1)}}function unloadHandler(){for(let p in Request.requests)Request.requests.hasOwnProperty(p)&&Request.requests[p].abort()}const nextTick=(()=>typeof Promise=="function"&&typeof Promise.resolve=="function"?u=>Promise.resolve().then(u):(u,f)=>f(u,0))(),WebSocket=globalThisShim.WebSocket||globalThisShim.MozWebSocket,usingBrowserWebSocket=!0,defaultBinaryType="arraybuffer",isReactNative=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class WS extends Transport{constructor(u){super(u),this.supportsBinary=!u.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const u=this.uri(),f=this.opts.protocols,m=isReactNative?{}:pick(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(m.headers=this.opts.extraHeaders);try{this.ws=usingBrowserWebSocket&&!isReactNative?f?new WebSocket(u,f):new WebSocket(u):new WebSocket(u,f,m)}catch(v){return this.emitReserved("error",v)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=u=>this.onClose({description:"websocket connection closed",context:u}),this.ws.onmessage=u=>this.onData(u.data),this.ws.onerror=u=>this.onError("websocket error",u)}write(u){this.writable=!1;for(let f=0;f<u.length;f++){const m=u[f],v=f===u.length-1;encodePacket(m,this.supportsBinary,y=>{const w={};try{usingBrowserWebSocket&&this.ws.send(y)}catch{}v&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const u=this.opts.secure?"wss":"ws",f=this.query||{};return this.opts.timestampRequests&&(f[this.opts.timestampParam]=yeast()),this.supportsBinary||(f.b64=1),this.createUri(u,f)}check(){return!!WebSocket}}class WT extends Transport{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(u=>{this.onError("webtransport error",u)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(u=>{const f=createPacketDecoderStream(Number.MAX_SAFE_INTEGER,this.socket.binaryType),m=u.readable.pipeThrough(f).getReader(),v=createPacketEncoderStream();v.readable.pipeTo(u.writable),this.writer=v.writable.getWriter();const y=()=>{m.read().then(({done:k,value:S})=>{k||(this.onPacket(S),y())}).catch(k=>{})};y();const w={type:"open"};this.query.sid&&(w.data=`{"sid":"${this.query.sid}"}`),this.writer.write(w).then(()=>this.onOpen())})}))}write(u){this.writable=!1;for(let f=0;f<u.length;f++){const m=u[f],v=f===u.length-1;this.writer.write(m).then(()=>{v&&nextTick(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var u;(u=this.transport)===null||u===void 0||u.close()}}const transports={websocket:WS,webtransport:WT,polling:Polling},re=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function parse$6(p){if(p.length>2e3)throw"URI too long";const u=p,f=p.indexOf("["),m=p.indexOf("]");f!=-1&&m!=-1&&(p=p.substring(0,f)+p.substring(f,m).replace(/:/g,";")+p.substring(m,p.length));let v=re.exec(p||""),y={},w=14;for(;w--;)y[parts[w]]=v[w]||"";return f!=-1&&m!=-1&&(y.source=u,y.host=y.host.substring(1,y.host.length-1).replace(/;/g,":"),y.authority=y.authority.replace("[","").replace("]","").replace(/;/g,":"),y.ipv6uri=!0),y.pathNames=pathNames(y,y.path),y.queryKey=queryKey(y,y.query),y}function pathNames(p,u){const f=/\/{2,9}/g,m=u.replace(f,"/").split("/");return(u.slice(0,1)=="/"||u.length===0)&&m.splice(0,1),u.slice(-1)=="/"&&m.splice(m.length-1,1),m}function queryKey(p,u){const f={};return u.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(m,v,y){v&&(f[v]=y)}),f}let Socket$1=class Ec extends Emitter{constructor(u,f={}){super(),this.binaryType=defaultBinaryType,this.writeBuffer=[],u&&typeof u=="object"&&(f=u,u=null),u?(u=parse$6(u),f.hostname=u.host,f.secure=u.protocol==="https"||u.protocol==="wss",f.port=u.port,u.query&&(f.query=u.query)):f.host&&(f.hostname=parse$6(f.host).host),installTimerFunctions(this,f),this.secure=f.secure!=null?f.secure:typeof location<"u"&&location.protocol==="https:",f.hostname&&!f.port&&(f.port=this.secure?"443":"80"),this.hostname=f.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=f.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=f.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},f),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=decode$1(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(u){const f=Object.assign({},this.opts.query);f.EIO=protocol$1,f.transport=u,this.id&&(f.sid=this.id);const m=Object.assign({},this.opts,{query:f,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[u]);return new transports[u](m)}open(){let u;if(this.opts.rememberUpgrade&&Ec.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)u="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else u=this.transports[0];this.readyState="opening";try{u=this.createTransport(u)}catch{this.transports.shift(),this.open();return}u.open(),this.setTransport(u)}setTransport(u){this.transport&&this.transport.removeAllListeners(),this.transport=u,u.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",f=>this.onClose("transport close",f))}probe(u){let f=this.createTransport(u),m=!1;Ec.priorWebsocketSuccess=!1;const v=()=>{m||(f.send([{type:"ping",data:"probe"}]),f.once("packet",E=>{if(!m)if(E.type==="pong"&&E.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",f),!f)return;Ec.priorWebsocketSuccess=f.name==="websocket",this.transport.pause(()=>{m||this.readyState!=="closed"&&(T(),this.setTransport(f),f.send([{type:"upgrade"}]),this.emitReserved("upgrade",f),f=null,this.upgrading=!1,this.flush())})}else{const H=new Error("probe error");H.transport=f.name,this.emitReserved("upgradeError",H)}}))};function y(){m||(m=!0,T(),f.close(),f=null)}const w=E=>{const H=new Error("probe error: "+E);H.transport=f.name,y(),this.emitReserved("upgradeError",H)};function k(){w("transport closed")}function S(){w("socket closed")}function M(E){f&&E.name!==f.name&&y()}const T=()=>{f.removeListener("open",v),f.removeListener("error",w),f.removeListener("close",k),this.off("close",S),this.off("upgrading",M)};f.once("open",v),f.once("error",w),f.once("close",k),this.once("close",S),this.once("upgrading",M),this.upgrades.indexOf("webtransport")!==-1&&u!=="webtransport"?this.setTimeoutFn(()=>{m||f.open()},200):f.open()}onOpen(){if(this.readyState="open",Ec.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let u=0;const f=this.upgrades.length;for(;u<f;u++)this.probe(this.upgrades[u])}}onPacket(u){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",u),this.emitReserved("heartbeat"),this.resetPingTimeout(),u.type){case"open":this.onHandshake(JSON.parse(u.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const f=new Error("server error");f.code=u.data,this.onError(f);break;case"message":this.emitReserved("data",u.data),this.emitReserved("message",u.data);break}}onHandshake(u){this.emitReserved("handshake",u),this.id=u.sid,this.transport.query.sid=u.sid,this.upgrades=this.filterUpgrades(u.upgrades),this.pingInterval=u.pingInterval,this.pingTimeout=u.pingTimeout,this.maxPayload=u.maxPayload,this.onOpen(),this.readyState!=="closed"&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const u=this.getWritablePackets();this.transport.send(u),this.prevBufferLen=u.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let f=1;for(let m=0;m<this.writeBuffer.length;m++){const v=this.writeBuffer[m].data;if(v&&(f+=byteLength(v)),m>0&&f>this.maxPayload)return this.writeBuffer.slice(0,m);f+=2}return this.writeBuffer}write(u,f,m){return this.sendPacket("message",u,f,m),this}send(u,f,m){return this.sendPacket("message",u,f,m),this}sendPacket(u,f,m,v){if(typeof f=="function"&&(v=f,f=void 0),typeof m=="function"&&(v=m,m=null),this.readyState==="closing"||this.readyState==="closed")return;m=m||{},m.compress=m.compress!==!1;const y={type:u,data:f,options:m};this.emitReserved("packetCreate",y),this.writeBuffer.push(y),v&&this.once("flush",v),this.flush()}close(){const u=()=>{this.onClose("forced close"),this.transport.close()},f=()=>{this.off("upgrade",f),this.off("upgradeError",f),u()},m=()=>{this.once("upgrade",f),this.once("upgradeError",f)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?m():u()}):this.upgrading?m():u()),this}onError(u){Ec.priorWebsocketSuccess=!1,this.emitReserved("error",u),this.onClose("transport error",u)}onClose(u,f){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",u,f),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(u){const f=[];let m=0;const v=u.length;for(;m<v;m++)~this.transports.indexOf(u[m])&&f.push(u[m]);return f}};Socket$1.protocol=protocol$1;function url(p,u="",f){let m=p;f=f||typeof location<"u"&&location,p==null&&(p=f.protocol+"//"+f.host),typeof p=="string"&&(p.charAt(0)==="/"&&(p.charAt(1)==="/"?p=f.protocol+p:p=f.host+p),/^(https?|wss?):\/\//.test(p)||(typeof f<"u"?p=f.protocol+"//"+p:p="https://"+p),m=parse$6(p)),m.port||(/^(http|ws)$/.test(m.protocol)?m.port="80":/^(http|ws)s$/.test(m.protocol)&&(m.port="443")),m.path=m.path||"/";const y=m.host.indexOf(":")!==-1?"["+m.host+"]":m.host;return m.id=m.protocol+"://"+y+":"+m.port+u,m.href=m.protocol+"://"+y+(f&&f.port===m.port?"":":"+m.port),m}const withNativeArrayBuffer=typeof ArrayBuffer=="function",isView=p=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(p):p.buffer instanceof ArrayBuffer,toString=Object.prototype.toString,withNativeBlob=typeof Blob=="function"||typeof Blob<"u"&&toString.call(Blob)==="[object BlobConstructor]",withNativeFile=typeof File=="function"||typeof File<"u"&&toString.call(File)==="[object FileConstructor]";function isBinary(p){return withNativeArrayBuffer&&(p instanceof ArrayBuffer||isView(p))||withNativeBlob&&p instanceof Blob||withNativeFile&&p instanceof File}function hasBinary(p,u){if(!p||typeof p!="object")return!1;if(Array.isArray(p)){for(let f=0,m=p.length;f<m;f++)if(hasBinary(p[f]))return!0;return!1}if(isBinary(p))return!0;if(p.toJSON&&typeof p.toJSON=="function"&&arguments.length===1)return hasBinary(p.toJSON(),!0);for(const f in p)if(Object.prototype.hasOwnProperty.call(p,f)&&hasBinary(p[f]))return!0;return!1}function deconstructPacket(p){const u=[],f=p.data,m=p;return m.data=_deconstructPacket(f,u),m.attachments=u.length,{packet:m,buffers:u}}function _deconstructPacket(p,u){if(!p)return p;if(isBinary(p)){const f={_placeholder:!0,num:u.length};return u.push(p),f}else if(Array.isArray(p)){const f=new Array(p.length);for(let m=0;m<p.length;m++)f[m]=_deconstructPacket(p[m],u);return f}else if(typeof p=="object"&&!(p instanceof Date)){const f={};for(const m in p)Object.prototype.hasOwnProperty.call(p,m)&&(f[m]=_deconstructPacket(p[m],u));return f}return p}function reconstructPacket(p,u){return p.data=_reconstructPacket(p.data,u),delete p.attachments,p}function _reconstructPacket(p,u){if(!p)return p;if(p&&p._placeholder===!0){if(typeof p.num=="number"&&p.num>=0&&p.num<u.length)return u[p.num];throw new Error("illegal attachments")}else if(Array.isArray(p))for(let f=0;f<p.length;f++)p[f]=_reconstructPacket(p[f],u);else if(typeof p=="object")for(const f in p)Object.prototype.hasOwnProperty.call(p,f)&&(p[f]=_reconstructPacket(p[f],u));return p}const RESERVED_EVENTS$1=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],protocol=5;var PacketType;(function(p){p[p.CONNECT=0]="CONNECT",p[p.DISCONNECT=1]="DISCONNECT",p[p.EVENT=2]="EVENT",p[p.ACK=3]="ACK",p[p.CONNECT_ERROR=4]="CONNECT_ERROR",p[p.BINARY_EVENT=5]="BINARY_EVENT",p[p.BINARY_ACK=6]="BINARY_ACK"})(PacketType||(PacketType={}));class Encoder{constructor(u){this.replacer=u}encode(u){return(u.type===PacketType.EVENT||u.type===PacketType.ACK)&&hasBinary(u)?this.encodeAsBinary({type:u.type===PacketType.EVENT?PacketType.BINARY_EVENT:PacketType.BINARY_ACK,nsp:u.nsp,data:u.data,id:u.id}):[this.encodeAsString(u)]}encodeAsString(u){let f=""+u.type;return(u.type===PacketType.BINARY_EVENT||u.type===PacketType.BINARY_ACK)&&(f+=u.attachments+"-"),u.nsp&&u.nsp!=="/"&&(f+=u.nsp+","),u.id!=null&&(f+=u.id),u.data!=null&&(f+=JSON.stringify(u.data,this.replacer)),f}encodeAsBinary(u){const f=deconstructPacket(u),m=this.encodeAsString(f.packet),v=f.buffers;return v.unshift(m),v}}function isObject$1(p){return Object.prototype.toString.call(p)==="[object Object]"}class Decoder extends Emitter{constructor(u){super(),this.reviver=u}add(u){let f;if(typeof u=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");f=this.decodeString(u);const m=f.type===PacketType.BINARY_EVENT;m||f.type===PacketType.BINARY_ACK?(f.type=m?PacketType.EVENT:PacketType.ACK,this.reconstructor=new BinaryReconstructor(f),f.attachments===0&&super.emitReserved("decoded",f)):super.emitReserved("decoded",f)}else if(isBinary(u)||u.base64)if(this.reconstructor)f=this.reconstructor.takeBinaryData(u),f&&(this.reconstructor=null,super.emitReserved("decoded",f));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+u)}decodeString(u){let f=0;const m={type:Number(u.charAt(0))};if(PacketType[m.type]===void 0)throw new Error("unknown packet type "+m.type);if(m.type===PacketType.BINARY_EVENT||m.type===PacketType.BINARY_ACK){const y=f+1;for(;u.charAt(++f)!=="-"&&f!=u.length;);const w=u.substring(y,f);if(w!=Number(w)||u.charAt(f)!=="-")throw new Error("Illegal attachments");m.attachments=Number(w)}if(u.charAt(f+1)==="/"){const y=f+1;for(;++f&&!(u.charAt(f)===","||f===u.length););m.nsp=u.substring(y,f)}else m.nsp="/";const v=u.charAt(f+1);if(v!==""&&Number(v)==v){const y=f+1;for(;++f;){const w=u.charAt(f);if(w==null||Number(w)!=w){--f;break}if(f===u.length)break}m.id=Number(u.substring(y,f+1))}if(u.charAt(++f)){const y=this.tryParse(u.substr(f));if(Decoder.isPayloadValid(m.type,y))m.data=y;else throw new Error("invalid payload")}return m}tryParse(u){try{return JSON.parse(u,this.reviver)}catch{return!1}}static isPayloadValid(u,f){switch(u){case PacketType.CONNECT:return isObject$1(f);case PacketType.DISCONNECT:return f===void 0;case PacketType.CONNECT_ERROR:return typeof f=="string"||isObject$1(f);case PacketType.EVENT:case PacketType.BINARY_EVENT:return Array.isArray(f)&&(typeof f[0]=="number"||typeof f[0]=="string"&&RESERVED_EVENTS$1.indexOf(f[0])===-1);case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(f)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BinaryReconstructor{constructor(u){this.packet=u,this.buffers=[],this.reconPack=u}takeBinaryData(u){if(this.buffers.push(u),this.buffers.length===this.reconPack.attachments){const f=reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),f}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const parser$1=Object.freeze(Object.defineProperty({__proto__:null,Decoder,Encoder,get PacketType(){return PacketType},protocol},Symbol.toStringTag,{value:"Module"}));function on(p,u,f){return p.on(u,f),function(){p.off(u,f)}}const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends Emitter{constructor(u,f,m){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=u,this.nsp=f,m&&m.auth&&(this.auth=m.auth),this._opts=Object.assign({},m),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const u=this.io;this.subs=[on(u,"open",this.onopen.bind(this)),on(u,"packet",this.onpacket.bind(this)),on(u,"error",this.onerror.bind(this)),on(u,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...u){return u.unshift("message"),this.emit.apply(this,u),this}emit(u,...f){if(RESERVED_EVENTS.hasOwnProperty(u))throw new Error('"'+u.toString()+'" is a reserved event name');if(f.unshift(u),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(f),this;const m={type:PacketType.EVENT,data:f};if(m.options={},m.options.compress=this.flags.compress!==!1,typeof f[f.length-1]=="function"){const w=this.ids++,k=f.pop();this._registerAckCallback(w,k),m.id=w}const v=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!v||!this.connected)||(this.connected?(this.notifyOutgoingListeners(m),this.packet(m)):this.sendBuffer.push(m)),this.flags={},this}_registerAckCallback(u,f){var m;const v=(m=this.flags.timeout)!==null&&m!==void 0?m:this._opts.ackTimeout;if(v===void 0){this.acks[u]=f;return}const y=this.io.setTimeoutFn(()=>{delete this.acks[u];for(let k=0;k<this.sendBuffer.length;k++)this.sendBuffer[k].id===u&&this.sendBuffer.splice(k,1);f.call(this,new Error("operation has timed out"))},v),w=(...k)=>{this.io.clearTimeoutFn(y),f.apply(this,k)};w.withError=!0,this.acks[u]=w}emitWithAck(u,...f){return new Promise((m,v)=>{const y=(w,k)=>w?v(w):m(k);y.withError=!0,f.push(y),this.emit(u,...f)})}_addToQueue(u){let f;typeof u[u.length-1]=="function"&&(f=u.pop());const m={id:this._queueSeq++,tryCount:0,pending:!1,args:u,flags:Object.assign({fromQueue:!0},this.flags)};u.push((v,...y)=>m!==this._queue[0]?void 0:(v!==null?m.tryCount>this._opts.retries&&(this._queue.shift(),f&&f(v)):(this._queue.shift(),f&&f(null,...y)),m.pending=!1,this._drainQueue())),this._queue.push(m),this._drainQueue()}_drainQueue(u=!1){if(!this.connected||this._queue.length===0)return;const f=this._queue[0];f.pending&&!u||(f.pending=!0,f.tryCount++,this.flags=f.flags,this.emit.apply(this,f.args))}packet(u){u.nsp=this.nsp,this.io._packet(u)}onopen(){typeof this.auth=="function"?this.auth(u=>{this._sendConnectPacket(u)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(u){this.packet({type:PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},u):u})}onerror(u){this.connected||this.emitReserved("connect_error",u)}onclose(u,f){this.connected=!1,delete this.id,this.emitReserved("disconnect",u,f),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(u=>{if(!this.sendBuffer.some(m=>String(m.id)===u)){const m=this.acks[u];delete this.acks[u],m.withError&&m.call(this,new Error("socket has been disconnected"))}})}onpacket(u){if(u.nsp===this.nsp)switch(u.type){case PacketType.CONNECT:u.data&&u.data.sid?this.onconnect(u.data.sid,u.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case PacketType.EVENT:case PacketType.BINARY_EVENT:this.onevent(u);break;case PacketType.ACK:case PacketType.BINARY_ACK:this.onack(u);break;case PacketType.DISCONNECT:this.ondisconnect();break;case PacketType.CONNECT_ERROR:this.destroy();const m=new Error(u.data.message);m.data=u.data.data,this.emitReserved("connect_error",m);break}}onevent(u){const f=u.data||[];u.id!=null&&f.push(this.ack(u.id)),this.connected?this.emitEvent(f):this.receiveBuffer.push(Object.freeze(f))}emitEvent(u){if(this._anyListeners&&this._anyListeners.length){const f=this._anyListeners.slice();for(const m of f)m.apply(this,u)}super.emit.apply(this,u),this._pid&&u.length&&typeof u[u.length-1]=="string"&&(this._lastOffset=u[u.length-1])}ack(u){const f=this;let m=!1;return function(...v){m||(m=!0,f.packet({type:PacketType.ACK,id:u,data:v}))}}onack(u){const f=this.acks[u.id];typeof f=="function"&&(delete this.acks[u.id],f.withError&&u.data.unshift(null),f.apply(this,u.data))}onconnect(u,f){this.id=u,this.recovered=f&&this._pid===f,this._pid=f,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(u=>this.emitEvent(u)),this.receiveBuffer=[],this.sendBuffer.forEach(u=>{this.notifyOutgoingListeners(u),this.packet(u)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(u=>u()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:PacketType.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(u){return this.flags.compress=u,this}get volatile(){return this.flags.volatile=!0,this}timeout(u){return this.flags.timeout=u,this}onAny(u){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(u),this}prependAny(u){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(u),this}offAny(u){if(!this._anyListeners)return this;if(u){const f=this._anyListeners;for(let m=0;m<f.length;m++)if(u===f[m])return f.splice(m,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(u){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(u),this}prependAnyOutgoing(u){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(u),this}offAnyOutgoing(u){if(!this._anyOutgoingListeners)return this;if(u){const f=this._anyOutgoingListeners;for(let m=0;m<f.length;m++)if(u===f[m])return f.splice(m,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(u){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const f=this._anyOutgoingListeners.slice();for(const m of f)m.apply(this,u.data)}}}function Backoff(p){p=p||{},this.ms=p.min||100,this.max=p.max||1e4,this.factor=p.factor||2,this.jitter=p.jitter>0&&p.jitter<=1?p.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var p=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var u=Math.random(),f=Math.floor(u*this.jitter*p);p=Math.floor(u*10)&1?p+f:p-f}return Math.min(p,this.max)|0},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(p){this.ms=p},Backoff.prototype.setMax=function(p){this.max=p},Backoff.prototype.setJitter=function(p){this.jitter=p};class Manager extends Emitter{constructor(u,f){var m;super(),this.nsps={},this.subs=[],u&&typeof u=="object"&&(f=u,u=void 0),f=f||{},f.path=f.path||"/socket.io",this.opts=f,installTimerFunctions(this,f),this.reconnection(f.reconnection!==!1),this.reconnectionAttempts(f.reconnectionAttempts||1/0),this.reconnectionDelay(f.reconnectionDelay||1e3),this.reconnectionDelayMax(f.reconnectionDelayMax||5e3),this.randomizationFactor((m=f.randomizationFactor)!==null&&m!==void 0?m:.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(f.timeout==null?2e4:f.timeout),this._readyState="closed",this.uri=u;const v=f.parser||parser$1;this.encoder=new v.Encoder,this.decoder=new v.Decoder,this._autoConnect=f.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(u){return arguments.length?(this._reconnection=!!u,this):this._reconnection}reconnectionAttempts(u){return u===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=u,this)}reconnectionDelay(u){var f;return u===void 0?this._reconnectionDelay:(this._reconnectionDelay=u,(f=this.backoff)===null||f===void 0||f.setMin(u),this)}randomizationFactor(u){var f;return u===void 0?this._randomizationFactor:(this._randomizationFactor=u,(f=this.backoff)===null||f===void 0||f.setJitter(u),this)}reconnectionDelayMax(u){var f;return u===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=u,(f=this.backoff)===null||f===void 0||f.setMax(u),this)}timeout(u){return arguments.length?(this._timeout=u,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(u){if(~this._readyState.indexOf("open"))return this;this.engine=new Socket$1(this.uri,this.opts);const f=this.engine,m=this;this._readyState="opening",this.skipReconnect=!1;const v=on(f,"open",function(){m.onopen(),u&&u()}),y=k=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",k),u?u(k):this.maybeReconnectOnOpen()},w=on(f,"error",y);if(this._timeout!==!1){const k=this._timeout,S=this.setTimeoutFn(()=>{v(),y(new Error("timeout")),f.close()},k);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(v),this.subs.push(w),this}connect(u){return this.open(u)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const u=this.engine;this.subs.push(on(u,"ping",this.onping.bind(this)),on(u,"data",this.ondata.bind(this)),on(u,"error",this.onerror.bind(this)),on(u,"close",this.onclose.bind(this)),on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(u){try{this.decoder.add(u)}catch(f){this.onclose("parse error",f)}}ondecoded(u){nextTick(()=>{this.emitReserved("packet",u)},this.setTimeoutFn)}onerror(u){this.emitReserved("error",u)}socket(u,f){let m=this.nsps[u];return m?this._autoConnect&&!m.active&&m.connect():(m=new Socket(this,u,f),this.nsps[u]=m),m}_destroy(u){const f=Object.keys(this.nsps);for(const m of f)if(this.nsps[m].active)return;this._close()}_packet(u){const f=this.encoder.encode(u);for(let m=0;m<f.length;m++)this.engine.write(f[m],u.options)}cleanup(){this.subs.forEach(u=>u()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(u,f){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",u,f),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const u=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const f=this.backoff.duration();this._reconnecting=!0;const m=this.setTimeoutFn(()=>{u.skipReconnect||(this.emitReserved("reconnect_attempt",u.backoff.attempts),!u.skipReconnect&&u.open(v=>{v?(u._reconnecting=!1,u.reconnect(),this.emitReserved("reconnect_error",v)):u.onreconnect()}))},f);this.opts.autoUnref&&m.unref(),this.subs.push(()=>{this.clearTimeoutFn(m)})}}onreconnect(){const u=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",u)}}const cache={};function lookup$1(p,u){typeof p=="object"&&(u=p,p=void 0),u=u||{};const f=url(p,u.path||"/socket.io"),m=f.source,v=f.id,y=f.path,w=cache[v]&&y in cache[v].nsps,k=u.forceNew||u["force new connection"]||u.multiplex===!1||w;let S;return k?S=new Manager(m,u):(cache[v]||(cache[v]=new Manager(m,u)),S=cache[v]),f.query&&!u.query&&(u.query=f.queryKey),S.socket(f.path,u)}Object.assign(lookup$1,{Manager,Socket,io:lookup$1,connect:lookup$1});const DefaultOptions={heartbeat:!0},createWebsocket=(p,u=DefaultOptions)=>{if(!p)throw"A websocket path must be provided";const{heartbeat:f}={...DefaultOptions,...u},m=location.protocol==="https:",v=m?"wss:":"ws:",y=location.hostname,w=location.port||(m?443:80);let k=lookup$1(`${v}//${y}:${w}`,{path:p,reconnectionAttempts:3,reconnectionDelay:5e3,reconnectionDelayMax:5e3,timeout:4e3,transports:["websocket"]}),S;return f&&(S=setInterval(()=>{k.emit(SocketEvent.Heartbeat)},SocketSessionTTL*500)),k.on("disconnect",()=>{clearInterval(S)}),k.onOther=(M,T)=>{k.on(M,E=>{(E==null?void 0:E.apiSessionId)!==APISessionID&&T(E)})},k},extractFileNameRegex=/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;async function downloadStream(p){const u=await p.blob(),f=p.headers.get("Content-Disposition"),v=extractFileNameRegex.exec(f)[1].replace(/['"]/g,""),y=new Blob([u]),w=URL.createObjectURL(y),k=document.createElement("a");k.href=w,k.download=v,k.click(),URL.revokeObjectURL(w)}const shouldDisplaySetting=(p,u)=>{let f=u.dependsOn;return f&&!Array.isArray(f)&&(f=[f]),f!=null&&f.length?f.every(m=>{let v=m,y=null,w=!!m.invert;if(typeof m=="object"&&(v=m.setting,y=m.value),!v)return!1;Array.isArray(y)||(y=[y]);const k=deepGet$1(p,v);return y.some(M=>M==null?k!=null&&k!==!1&&k!=="":M===k)!==w}):!0},columnTypeManyTypeOverrides={[FieldType.DATETIME]:FieldType.STRING,[FieldType.BOOLEAN]:FieldType.STRING,[FieldType.SIGNATURE_SINGLE]:FieldType.ATTACHMENTS},columnTypeManyParser={[FieldType.DATETIME]:(p,u)=>{function f(m){const{timeOnly:v,dateOnly:y}=u||{},w=!y,k=parseDate(m,{enableTime:w});return getDateDisplayValue(k,{enableTime:w,timeOnly:v})}return p.map(m=>f(m))},[FieldType.BOOLEAN]:p=>p.map(u=>!!u),[FieldType.BB_REFERENCE_SINGLE]:p=>[...new Map(p.map(u=>[u._id,u])).values()],[FieldType.BB_REFERENCE]:p=>[...new Map(p.map(u=>[u._id,u])).values()],[FieldType.ARRAY]:p=>Array.from(new Set(p))};function enrichSchemaWithRelColumns(p){return Object.keys(p).reduce((f,m)=>{const v=p[m];if(f[m]=v,v.visible!==!1&&isRelationshipField(v)&&v.columns){const y=(v==null?void 0:v.relationshipType)===RelationshipType.ONE_TO_MANY;for(const w of Object.keys(v.columns)){const k=v.columns[w];if(!k.visible)continue;const S=`${v.name}.${w}`;f[S]={...k,type:k.type,name:S,related:{field:m,subField:w},cellRenderType:!y&&columnTypeManyTypeOverrides[k.type]||k.type}}}return f},{})}function getRelatedTableValues(p,u,f){var y,w,k,S;const m=isRelationshipField(f)&&(f==null?void 0:f.relationshipType)===RelationshipType.ONE_TO_MANY;let v="";if(m)v=(w=(y=p[u.related.field])==null?void 0:y[0])==null?void 0:w[u.related.subField];else{const M=columnTypeManyParser[u.type]||(H=>H),T=(S=(k=p[u.related.field])==null?void 0:k.flatMap(H=>H[u.related.subField]))==null?void 0:S.filter(H=>H!=null),E=M(T||[],u);v=E,[FieldType.STRING,FieldType.NUMBER,FieldType.BIGINT,FieldType.BOOLEAN,FieldType.DATETIME,FieldType.LONGFORM,FieldType.BARCODEQR].includes(u.type)&&(v=E==null?void 0:E.join(", "))}return v}function canBeDisplayColumn(p){return!(!canBeDisplayColumn$1(p.type)||p.related)}function canBeSortColumn(p){return p.calculationType?!0:!(!canBeSortColumn$1(p.type)||p.related)}const{buildQuery,limit:queryLimit,runQuery,sort}=QueryUtils;class BaseDataFetch{constructor(u){ha(this,"API");ha(this,"features");ha(this,"options");ha(this,"store");ha(this,"derivedStore");if(this.features={supportsSearch:!1,supportsSort:!1,supportsPagination:!1},this.options={datasource:u.datasource,limit:10,filter:null,query:u.query,sortColumn:null,sortOrder:SortOrder.ASCENDING,sortType:null,paginate:!0,clientSideSearching:!0,clientSideSorting:!0,clientSideLimiting:!0},this.store=writable({rows:[],info:null,schema:null,loading:!1,loaded:!1,query:u.query,pageNumber:0,cursor:null,cursors:[],resetKey:Math.random().toString(),error:null}),this.API=u==null?void 0:u.API,this.options={...this.options,...u},!this.API)throw"An API client is required for fetching data";if(this.getData=this.getData.bind(this),this.getPage=this.getPage.bind(this),this.getInitialData=this.getInitialData.bind(this),this.determineFeatureFlags=this.determineFeatureFlags.bind(this),this.refresh=this.refresh.bind(this),this.update=this.update.bind(this),this.hasNextPage=this.hasNextPage.bind(this),this.hasPrevPage=this.hasPrevPage.bind(this),this.nextPage=this.nextPage.bind(this),this.prevPage=this.prevPage.bind(this),this.derivedStore=derived(this.store,f=>({...f,...this.features,hasNextPage:this.hasNextPage(f),hasPrevPage:this.hasPrevPage(f)})),!this.options.datasource){this.store.update(f=>({...f,loaded:!0}));return}}get subscribe(){return this.derivedStore.subscribe}getDefaultSortColumn(u,f){return u!=null&&u.primaryDisplay&&f[u.primaryDisplay]?u.primaryDisplay:Object.keys(f)[0]}async getInitialData(){const{filter:u,paginate:f}=this.options,m=await this.getDefinition(),v=await this.determineFeatureFlags();this.features={supportsSearch:!!(v!=null&&v.supportsSearch),supportsSort:!!(v!=null&&v.supportsSort),supportsPagination:f&&!!(v!=null&&v.supportsPagination)};let y=this.getSchema(m);if(!y)return;if(y=this.enrichSchema(y),this.options.sortColumn&&!y[this.options.sortColumn]&&(this.options.sortColumn=null),this.options.sortColumn||(this.options.sortColumn=this.getDefaultSortColumn(m,y)),!this.options.sortColumn)this.options.sortOrder=SortOrder.ASCENDING,this.options.sortType=null;else{this.options.sortType=SortType.STRING;const S=y==null?void 0:y[this.options.sortColumn];((S==null?void 0:S.type)===FieldType.NUMBER||(S==null?void 0:S.type)===FieldType.BIGINT||"calculationType"in S&&(S!=null&&S.calculationType))&&(this.options.sortType=SortType.NUMBER),this.options.sortOrder?this.options.sortOrder=this.options.sortOrder.toLowerCase():this.options.sortOrder=SortOrder.ASCENDING}let w=this.options.query;w||(w=buildQuery(u??void 0)),this.store.update(S=>({...S,definition:m,schema:y,query:w,loading:!0,cursors:[],cursor:null}));const k=await this.getPage();this.store.update(S=>({...S,loading:!1,loaded:!0,pageNumber:0,rows:k.rows,info:k.info,cursors:f&&k.hasNextPage?[null,k.cursor]:[null],error:k.error,resetKey:Math.random().toString()}))}async getPage(){const{sortColumn:u,sortOrder:f,sortType:m,limit:v,clientSideSearching:y,clientSideSorting:w,clientSideLimiting:k}=this.options,{query:S}=get_store_value(this.store);let{rows:M,info:T,hasNextPage:E,cursor:H,error:F}=await this.getData();return!this.features.supportsSearch&&y&&(M=runQuery(M,S)),!this.features.supportsSort&&w&&m&&(M=sort(M,u,f,m)),!this.features.supportsPagination&&k&&(M=queryLimit(M,v)),{rows:M,info:T,hasNextPage:E,cursor:H,error:F}}getSchema(u){return(u==null?void 0:u.schema)??void 0}enrichSchema(u){let f={};for(const v of Object.keys(u)){const y=u[v];if(y.type===FieldType.JSON){const w=convertJSONSchemaToTableSchema(y,{squashObjects:!0});if(w)for(const k of Object.keys(w))f[`${v}.${k}`]={type:w[k].type,nestedJSON:!0}}}let m={};return Object.entries({...u,...f}).forEach(([v,y])=>{typeof y=="string"?m[v]={type:y,name:v}:m[v]={...y,type:y.type,name:v}}),m}async determineFeatureFlags(){return{supportsSearch:!1,supportsSort:!1,supportsPagination:!1}}async update(u){let f=!1;for(const[m,v]of Object.entries(u||{})){const y=this.options[m]??null;if(JSON.stringify(v??null)!==JSON.stringify(y)){f=!0;break}}f&&(this.options={...this.options,...fp$1.cloneDeep(u)},await this.getInitialData())}async refresh(){if(get_store_value(this.store).loading)return;this.store.update(S=>({...S,loading:!0}));const{rows:u,info:f,error:m,cursor:v}=await this.getPage();let{cursors:y}=get_store_value(this.store);const{pageNumber:w}=get_store_value(this.store);if(!u.length&&w>0)return this.store.update(S=>({...S,loading:!1,cursors:y.slice(0,w)})),await this.prevPage();y[w+1]!=v&&(y=y.slice(0,w+1),y[w+1]=v),this.store.update(S=>({...S,rows:u,info:f,loading:!1,error:m,cursors:y}))}hasNextPage(u){return u.cursors[u.pageNumber+1]!=null}hasPrevPage(u){return u.pageNumber>0}async nextPage(){const u=get_store_value(this.derivedStore);if(u.loading||!this.options.paginate||!u.hasNextPage)return;const f=u.cursors[u.pageNumber+1];this.store.update(S=>({...S,loading:!0,cursor:f,pageNumber:S.pageNumber+1}));const{rows:m,info:v,hasNextPage:y,cursor:w,error:k}=await this.getPage();this.store.update(S=>{let{cursors:M,pageNumber:T}=S;return y&&(M[T+1]=w),{...S,rows:m,info:v,cursors:M,loading:!1,error:k}})}async prevPage(){const u=get_store_value(this.derivedStore);if(u.loading||!this.options.paginate||!u.hasPrevPage)return;const f=u.cursors[u.pageNumber-1];this.store.update(w=>({...w,loading:!0,cursor:f,pageNumber:w.pageNumber-1}));const{rows:m,info:v,error:y}=await this.getPage();this.store.update(w=>({...w,rows:m,info:v,loading:!1,error:y}))}}class TableFetch extends BaseDataFetch{async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!0,supportsPagination:!0}}async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u.tableId))return null;try{return await this.API.fetchTableDefinition(u.tableId)}catch(f){return this.store.update(m=>({...m,error:f})),null}}async getData(){const{datasource:u,limit:f,sortColumn:m,sortOrder:v,sortType:y,paginate:w}=this.options,{tableId:k}=u,{cursor:S,query:M}=get_store_value(this.store);try{const T=await this.API.searchTable(k,{query:M,limit:f,sort:m,sortOrder:v??SortOrder.ASCENDING,sortType:y,paginate:w,bookmark:S});return{rows:(T==null?void 0:T.rows)||[],hasNextPage:(T==null?void 0:T.hasNextPage)||!1,cursor:(T==null?void 0:T.bookmark)||null}}catch(T){return{rows:[],hasNextPage:!1,error:T}}}}class ViewFetch extends BaseDataFetch{async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u.tableId))return null;try{return await this.API.fetchTableDefinition(u.tableId)}catch(f){return this.store.update(m=>({...m,error:f})),null}}getSchema(u){var m,v;const{datasource:f}=this.options;return(v=(m=u==null?void 0:u.views)==null?void 0:m[f==null?void 0:f.name])==null?void 0:v.schema}async getData(){const{datasource:u}=this.options;try{return{rows:await this.API.fetchViewData(u.name,{calculation:u.calculation,field:u.field,groupBy:u.groupBy,tableId:u.tableId})||[]}}catch(f){return console.error(f,{datasource:u}),{rows:[]}}}}class ViewV2Fetch extends BaseDataFetch{async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!0,supportsPagination:!0}}async getDefinition(){const{datasource:u}=this.options;try{const f=await this.API.viewV2.fetchDefinition(u.id);return f==null?void 0:f.data}catch(f){return this.store.update(m=>({...m,error:f})),null}}getDefaultSortColumn(){return null}async getData(){var T;const{datasource:u,limit:f,sortColumn:m,sortOrder:v,sortType:y,paginate:w}=this.options,{cursor:k,query:S,definition:M}=get_store_value(this.store);if((M==null?void 0:M.type)===ViewV2Type.CALCULATION&&!Object.values(M.schema||{}).some(isCalculationField))return{rows:[],hasNextPage:!1,cursor:null,error:null};!m&&((T=M==null?void 0:M.sort)!=null&&T.field)&&(this.options.sortColumn=M.sort.field,this.options.sortOrder=M.sort.order||SortOrder.ASCENDING);try{const E={query:S,paginate:w,limit:f,bookmark:k,sort:m,sortOrder:v,sortType:y};if(w){const H=await this.API.viewV2.fetch(u.id,{...E,paginate:w});return{rows:(H==null?void 0:H.rows)||[],hasNextPage:(H==null?void 0:H.hasNextPage)||!1,cursor:(H==null?void 0:H.bookmark)||null}}else{const H=await this.API.viewV2.fetch(u.id,{...E,paginate:w});return{rows:(H==null?void 0:H.rows)||[],hasNextPage:!1,cursor:null}}}catch(E){return{rows:[],hasNextPage:!1,cursor:null,error:E}}}}class QueryFetch extends BaseDataFetch{async determineFeatureFlags(){var m,v,y,w,k,S;const u=await this.getDefinition();return{supportsPagination:!!((v=(m=u==null?void 0:u.fields)==null?void 0:m.pagination)!=null&&v.type)&&!!((w=(y=u==null?void 0:u.fields)==null?void 0:y.pagination)!=null&&w.location)&&!!((S=(k=u==null?void 0:u.fields)==null?void 0:k.pagination)!=null&&S.pageParam)}}async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u._id))return null;try{const f=await this.API.fetchQueryDefinition(u._id);return f.fields||(f.fields=u.fields),f}catch{return null}}getDefaultSortColumn(){return null}async getData(){var T,E;const{datasource:u,limit:f,paginate:m}=this.options,{supportsPagination:v}=this.features,{cursor:y,definition:w}=get_store_value(this.store),k=(E=(T=w==null?void 0:w.fields)==null?void 0:T.pagination)==null?void 0:E.type,S=cloneDeep$1(u.queryParams||{});for(const H of(u==null?void 0:u.parameters)||[])S[H.name]||(S[H.name]=H.default);const M={parameters:S};if(m&&v){const H=k==="page"?parseInt(y||"1"):y;M.pagination={page:H,limit:f}}try{const H=await this.API.executeQuery(u==null?void 0:u._id,M),{data:F,pagination:Z,...$}=H;let J=null,ae=!1;return m&&v&&(k==="page"?(J=M.pagination.page+1,ae=(F==null?void 0:F.length)===f&&f>0):(J=Z==null?void 0:Z.cursor,ae=J!=null)),{rows:F||[],info:$,cursor:J,hasNextPage:ae}}catch{return{rows:[],hasNextPage:!1}}}}class RelationshipFetch extends BaseDataFetch{async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u.tableId))return null;try{return await this.API.fetchTableDefinition(u.tableId)}catch(f){return this.store.update(m=>({...m,error:f})),null}}async getData(){const{datasource:u}=this.options;if(!(u!=null&&u.rowId)||!(u!=null&&u.rowTableId))return{rows:[]};try{return{rows:await this.API.fetchRelationshipData(u.rowTableId,u.rowId,u.fieldName)}}catch{return{rows:[]}}}}class NestedProviderFetch extends BaseDataFetch{async getDefinition(){var f,m;const{datasource:u}=this.options;return{schema:(f=u==null?void 0:u.value)==null?void 0:f.schema,primaryDisplay:(m=u==null?void 0:u.value)==null?void 0:m.primaryDisplay}}async getData(){var f;const{datasource:u}=this.options;return{rows:((f=u==null?void 0:u.value)==null?void 0:f.rows)||[],hasNextPage:!1,cursor:null}}}function isArrayOfStrings(p){return Array.isArray(p)&&!!p[0]&&typeof p[0]!="object"}class FieldFetch extends BaseDataFetch{async getDefinition(){const{datasource:u}=this.options;let f;return u.fieldType==="attachment"?f={url:{type:"string"},name:{type:"string"}}:u.fieldType==="array"&&(f={value:{type:"string"}}),{schema:f}}async getData(){const{datasource:u}=this.options,f=(u==null?void 0:u.value)||[];let m;return isArrayOfStrings(f)?m=f.map(v=>({value:v})):m=f,{rows:m||[],hasNextPage:!1,cursor:null}}}class JSONArrayFetch extends FieldFetch{async getDefinition(){const{datasource:u}=this.options;try{const f=await this.API.fetchTableDefinition(u.tableId);return{schema:getJSONArrayDatasourceSchema(f==null?void 0:f.schema,u)}}catch{return null}}}class UserFetch extends BaseDataFetch{constructor(u){super({...u,datasource:{type:"user",tableId:InternalTable.USER_METADATA}})}async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!1,supportsPagination:!0}}async getDefinition(){return{schema:{}}}async getData(){const{limit:u,paginate:f}=this.options,{cursor:m,query:v}=get_store_value(this.store),{appId:y,paginated:w,...k}=v,S=isSupportedUserSearch(k)?k:{};try{const M={bookmark:m??void 0,query:S??void 0,appId:y,paginate:w||f,limit:u},T=await this.API.searchUsers(M);return{rows:(T==null?void 0:T.data)||[],hasNextPage:(T==null?void 0:T.hasNextPage)||!1,cursor:(T==null?void 0:T.nextPage)||null}}catch(M){return{rows:[],hasNextPage:!1,error:M}}}}class GroupUserFetch extends BaseDataFetch{constructor(u){super({...u,datasource:{type:"groupUser",tableId:InternalTable.USER_METADATA}})}async determineFeatureFlags(){return{supportsSearch:!0,supportsSort:!1,supportsPagination:!0}}async getDefinition(){return{schema:{}}}async getData(){const{query:u,cursor:f}=get_store_value(this.store);try{const m=await this.API.getGroupUsers({id:u.groupId,emailSearch:u.emailSearch,bookmark:f??void 0});return{rows:(m==null?void 0:m.users)||[],hasNextPage:(m==null?void 0:m.hasNextPage)||!1,cursor:(m==null?void 0:m.bookmark)||null}}catch(m){return{rows:[],hasNextPage:!1,error:m}}}}class CustomFetch extends BaseDataFetch{getType(u){return u==null?"string":typeof u==="object"?Array.isArray(u)?"array":"json":isNaN(u)?"string":"number"}parseCustomData(u){if(!u)return[];if(Array.isArray(u))return u;if(typeof u=="string"){try{const f=JSON.parse(u);return Array.isArray(f)?f:[f]}catch{}return u.includes(`
384
384
  `)?u.split(`
385
385
  `).map(f=>f.trim()):u.split(",").map(f=>f.trim())}return[u]}enrichCustomData(u){return u!=null&&u.length?(u=u.filter(f=>f!=null&&f!==""&&!Array.isArray(f)),u.map(f=>{if(typeof f=="object")return f;if(typeof f=="string"){const m=f.split(",").map(y=>y.trim()),v={};for(let y=0;y<m.length;y++){const k=`Value${y===0?"":` ${y+1}`}`;v[k]=m[y]}return v}return{Value:f}})):[]}getCustomData(u){return this.enrichCustomData(this.parseCustomData(u==null?void 0:u.data))}async getDefinition(){const{datasource:u}=this.options,f={},m=this.getCustomData(u);if(!(m!=null&&m.length))return{schema:f};for(const v of m)for(const y of Object.keys(v))if(y!=="_id"&&!f[y]){let w=this.getType(v[y]);const k={};if(w==="string"){const S=[...new Set(m.map(T=>T[y]))];S.length/m.length<=.8&&S.length>1&&(w="options",k.inclusion=S)}else w==="array"&&(k.inclusion=[...new Set(m.map(S=>S[y]).flat())]);f[y]={type:w,constraints:k}}return{schema:f}}async getData(){const{datasource:u}=this.options;return{rows:this.getCustomData(u),hasNextPage:!1,cursor:null}}}class QueryArrayFetch extends FieldFetch{async getDefinition(){const{datasource:u}=this.options;if(!(u!=null&&u.tableId))return null;try{const f=await this.API.fetchQueryDefinition(u.tableId),m=generateQueryArraySchemas(f.schema,f.nestedSchemaFields);return{schema:getJSONArrayDatasourceSchema(m,u)}}catch{return null}}}const DataFetchMap={table:TableFetch,view:ViewFetch,viewV2:ViewV2Fetch,query:QueryFetch,link:RelationshipFetch,user:UserFetch,groupUser:GroupUserFetch,custom:CustomFetch,provider:NestedProviderFetch,field:FieldFetch,jsonarray:JSONArrayFetch,queryarray:QueryArrayFetch},fetchData=({API:p,datasource:u,options:f})=>{const m=DataFetchMap[u==null?void 0:u.type]||TableFetch,v=new m({API:p,datasource:u,...f});return v.getInitialData(),v},createEmptyFetchInstance=({API:p,datasource:u})=>{const f=DataFetchMap[u==null?void 0:u.type];return f?new f({API:p,datasource:u,query:null}):null},getDatasourceDefinition=async({API:p,datasource:u})=>{const f=createEmptyFetchInstance({API:p,datasource:u});return await(f==null?void 0:f.getDefinition())},getDatasourceSchema=({API:p,datasource:u,definition:f})=>{const m=createEmptyFetchInstance({API:p,datasource:u});return m==null?void 0:m.getSchema(f)},createLocalStorageStore=(p,u)=>{const f=writable(u,()=>{y();const w=({key:k})=>k===p&&y();return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)}),m=w=>{f.set(w),localStorage.setItem(p,JSON.stringify(w))},v=w=>m(w(get_store_value(f))),y=()=>{const w=localStorage.getItem(p);if(w==null)m(u);else try{f.set(JSON.parse(w))}catch{m(u)}};return{...f,set:m,update:v}},SplitPage_svelte_svelte_type_style_lang="",Testimonial_svelte_svelte_type_style_lang="",TestimonialPage_svelte_svelte_type_style_lang="",SignatureModal_svelte_svelte_type_style_lang="";function create_default_slot_2$p(p){let u,f,m,v={darkMode:p[3],value:p[1],saveIcon:!1};return f=new Signature({props:v}),p[8](f),f.$on("update",p[9]),{c(){u=element("div"),create_component(f.$$.fragment),attr(u,"class","signature-wrap modal svelte-1jbgrys")},m(y,w){insert(y,u,w),mount_component(f,u,null),m=!0},p(y,w){const k={};w&8&&(k.darkMode=y[3]),w&2&&(k.value=y[1]),f.$set(k)},i(y){m||(transition_in(f.$$.fragment,y),m=!0)},o(y){transition_out(f.$$.fragment,y),m=!1},d(y){y&&detach(u),p[8](null),destroy_component(f)}}}function create_default_slot_1$B(p){let u;return{c(){u=text$1(p[2])},m(f,m){insert(f,u,m)},p(f,m){m&4&&set_data(u,f[2])},d(f){f&&detach(u)}}}function create_header_slot(p){let u,f,m;return f=new Body({props:{$$slots:{default:[create_default_slot_1$B]},$$scope:{ctx:p}}}),{c(){u=element("div"),create_component(f.$$.fragment),attr(u,"slot","header")},m(v,y){insert(v,u,y),mount_component(f,u,null),m=!0},p(v,y){const w={};y&4100&&(w.$$scope={dirty:y,ctx:v}),f.$set(w)},i(v){m||(transition_in(f.$$.fragment,v),m=!0)},o(v){transition_out(f.$$.fragment,v),m=!1},d(v){v&&detach(u),destroy_component(f)}}}function create_default_slot$1m(p){let u,f;return u=new ModalContent({props:{showConfirmButton:!0,showCancelButton:!1,showCloseIcon:!1,custom:!0,disabled:!p[6],showDivider:!1,onConfirm:p[10],$$slots:{header:[create_header_slot],default:[create_default_slot_2$p]},$$scope:{ctx:p}}}),{c(){create_component(u.$$.fragment)},m(m,v){mount_component(u,m,v),f=!0},p(m,v){const y={};v&64&&(y.disabled=!m[6]),v&33&&(y.onConfirm=m[10]),v&4206&&(y.$$scope={dirty:v,ctx:m}),u.$set(y)},i(m){f||(transition_in(u.$$.fragment,m),f=!0)},o(m){transition_out(u.$$.fragment,m),f=!1},d(m){destroy_component(u,m)}}}function create_fragment$2H(p){let u,f,m={$$slots:{default:[create_default_slot$1m]},$$scope:{ctx:p}};return u=new Modal({props:m}),p[11](u),{c(){create_component(u.$$.fragment)},m(v,y){mount_component(u,v,y),f=!0},p(v,[y]){const w={};y&4207&&(w.$$scope={dirty:y,ctx:v}),u.$set(w)},i(v){f||(transition_in(u.$$.fragment,v),f=!0)},o(v){transition_out(u.$$.fragment,v),f=!1},d(v){p[11](null),destroy_component(u,v)}}}function instance$2E(p,u,f){let{onConfirm:m=()=>{}}=u,{value:v}=u,{title:y}=u,{darkMode:w}=u;const k=()=>{f(6,T=!1),S.show()};let S,M,T=!1;function E($){binding_callbacks[$?"unshift":"push"](()=>{M=$,f(5,M)})}const H=()=>{f(6,T=!0)},F=()=>{m(M)};function Z($){binding_callbacks[$?"unshift":"push"](()=>{S=$,f(4,S)})}return p.$$set=$=>{"onConfirm"in $&&f(0,m=$.onConfirm),"value"in $&&f(1,v=$.value),"title"in $&&f(2,y=$.title),"darkMode"in $&&f(3,w=$.darkMode)},[m,v,y,w,S,M,T,k,E,H,F,Z]}class SignatureModal extends SvelteComponent{constructor(u){super(),init$1(this,u,instance$2E,create_fragment$2H,safe_not_equal,{onConfirm:0,value:1,title:2,darkMode:3,show:7})}get show(){return this.$$.ctx[7]}}function create_if_block$1B(p){let u,f;return u=new AbsTooltip({props:{text:p[3]?getUserLabel(p[0]):null,position:p[2],color:getUserColor(p[0]),$$slots:{default:[create_default_slot$1l]},$$scope:{ctx:p}}}),{c(){create_component(u.$$.fragment)},m(m,v){mount_component(u,m,v),f=!0},p(m,v){const y={};v&9&&(y.text=m[3]?getUserLabel(m[0]):null),v&4&&(y.position=m[2]),v&1&&(y.color=getUserColor(m[0])),v&19&&(y.$$scope={dirty:v,ctx:m}),u.$set(y)},i(m){f||(transition_in(u.$$.fragment,m),f=!0)},o(m){transition_out(u.$$.fragment,m),f=!1},d(m){destroy_component(u,m)}}}function create_default_slot$1l(p){let u,f;return u=new Avatar({props:{size:p[1],initials:getUserInitials(p[0]),color:getUserColor(p[0])}}),{c(){create_component(u.$$.fragment)},m(m,v){mount_component(u,m,v),f=!0},p(m,v){const y={};v&2&&(y.size=m[1]),v&1&&(y.initials=getUserInitials(m[0])),v&1&&(y.color=getUserColor(m[0])),u.$set(y)},i(m){f||(transition_in(u.$$.fragment,m),f=!0)},o(m){transition_out(u.$$.fragment,m),f=!1},d(m){destroy_component(u,m)}}}function create_fragment$2G(p){let u,f,m=p[0]&&create_if_block$1B(p);return{c(){m&&m.c(),u=empty$1()},m(v,y){m&&m.m(v,y),insert(v,u,y),f=!0},p(v,[y]){v[0]?m?(m.p(v,y),y&1&&transition_in(m,1)):(m=create_if_block$1B(v),m.c(),transition_in(m,1),m.m(u.parentNode,u)):m&&(group_outros(),transition_out(m,1,1,()=>{m=null}),check_outros())},i(v){f||(transition_in(m),f=!0)},o(v){transition_out(m),f=!1},d(v){v&&detach(u),m&&m.d(v)}}}function instance$2D(p,u,f){let{user:m}=u,{size:v="S"}=u,{tooltipPosition:y=TooltipPosition.Top}=u,{showTooltip:w=!0}=u;return p.$$set=k=>{"user"in k&&f(0,m=k.user),"size"in k&&f(1,v=k.size),"tooltipPosition"in k&&f(2,y=k.tooltipPosition),"showTooltip"in k&&f(3,w=k.showTooltip)},[m,v,y,w]}class UserAvatar extends SvelteComponent{constructor(u){super(),init$1(this,u,instance$2D,create_fragment$2G,safe_not_equal,{user:0,size:1,tooltipPosition:2,showTooltip:3})}}const UserAvatars_svelte_svelte_type_style_lang$1="",Updating_svelte_svelte_type_style_lang="";function create_else_block_1$9(p){let u;return{c(){u=text$1("Something went wrong!")},m(f,m){insert(f,u,m)},d(f){f&&detach(u)}}}function create_if_block_1$O(p){let u;return{c(){u=text$1("System update")},m(f,m){insert(f,u,m)},d(f){f&&detach(u)}}}function create_else_block$u(p){let u,f,m,v,y;return{c(){u=text$1(`An error occurred, please try again later.
386
386
  `),f=element("br"),m=text$1(`