{"version":3,"sources":["@webhare/env/src/envbackend.ts","@webhare/dompack/src/tree.ts","@webhare/std/src/quacks.ts","@webhare/std/src/datetime.ts","@webhare/std/src/promises.ts","@webhare/std/src/finmath.ts","@webhare/std/src/money.ts","@webhare/std/src/types.ts","@webhare/std/src/strings.ts","@webhare/std/src/platformbased.ts","@webhare/std/src/collections.ts","@webhare/std/src/utils.ts","@webhare/std/src/localmutex.ts","@webhare/std/src/std.ts","@webhare/env/src/navigation.ts","@webhare/env/src/fetchdebug.ts","@webhare/env/src/whglobal.ts","@webhare/env/src/env.ts","@webhare/gettid/src/hooks.ts","@webhare/gettid/src/internal.ts","@webhare/frontend/src/init.ts","@webhare/env/src/init-browser.ts","@webhare/tsrun/src/polyfills.ts","mod::publisher/js/internal/polyfills/iterator-helpers.ts","@webhare/dompack/src/busy.ts","mod::system/js/dompack/src/events.ts","@webhare/dompack/src/dompack.ts","mod::system/js/dompack/src/tree.ts","mod::system/js/dompack/src/create.ts","mod::system/js/dompack/src/components.ts","@webhare/dompack/src/storage.ts","@webhare/dompack/src/preload.ts","@webhare/dompack/src/browser.ts","mod::publisher/js/internal/polyfills/publisher-integration.ts","mod::consilio/js/pxl.ts","mod::system/js/dompack/index.ts","mod::system/js/wh/integration.ts","mod::publisher/js/pwa/internal/settings.ts","node_modules/idb/build/index.js","mod::publisher/js/pwa/internal/maintenance.ts","mod::publisher/js/pwa/internal/debugmenu.tsx","mod::platform/js/concepts/frontend.ts","mod::publisher/js/pwa/index.ts","@webhare/jsonrpc-client/src/jsonrpc-client.ts","node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js","@webhare/js-api-tools/src/stacktracing.ts","@webhare/js-api-tools/src/levenshtein.ts","@webhare/frontend/src/auth.ts","@webhare/rpc/src/rpc.ts","@webhare/frontend/src/pxl.ts","@webhare/frontend/src/gtm.ts","@webhare/frontend/src/frontend.ts","mod::kiskeya/webdesigns/registrationapp/registrationapp.lang.json","@webhare/gettid/src/gettid.ts","@webhare/upload/src/upload.ts","mod::publisher/js/forms/internal/customvalidation.ts","mod::system/js/dompack/types/datetime.ts","mod::system/js/dompack/browserfix/focus.ts","mod::system/js/dompack/extra/merge.ts","mod::publisher/js/forms/formbase.ts","@webhare/forms/src/registeredfield.ts","mod::publisher/js/forms/fields/arrayfield.ts","@webhare/forms/src/fieldmap.ts","mod::publisher/js/forms/fields/addressfield.ts","@webhare/forms/src/address.ts","@webhare/forms/src/formservice.ts","mod::publisher/js/forms/internal/datehelpers.ts","mod::publisher/js/forms/internal/webharefields.tsx","@webhare/forms/src/jsformelement.ts","@webhare/forms/src/domsupport.ts","mod::publisher/js/forms/internal/form.lang.json","mod::publisher/js/forms/fields/fileeditbase.ts","mod::publisher/js/forms/fields/upload.tsx","mod::publisher/js/forms/fields/imgedit.ts","mod::publisher/js/forms/internal/emailvalidation.tsx","mod::system/js/dompack/src/debug.ts","mod::system/js/dompack/extra/browser.ts","mod::system/js/dompack/extra/keyboard.ts","mod::system/js/dompack/api/dialog.ts","mod::publisher/js/forms/rpc.ts","mod::publisher/js/captcha/__captcha.lang.json","mod::publisher/js/captcha/api.ts","@webhare/forms/src/registration.ts","@webhare/forms/src/forms.ts","mod::publisher/js/forms/internal/datepicker.tsx","mod::publisher/js/captcha/google-recaptcha.tsx","mod::publisher/js/forms/fields/captchafield.ts","mod::publisher/js/forms/index.ts","mod::kiskeya/formcomponents/dateparts/index.ts","mod::tollium/js/gettid.ts","mod::system/js/dompack/components/dialog/index.ts","mod::kiskeya/webdesigns/registrationapp/shared/forms/dialog.tsx","mod::kiskeya/webdesigns/registrationapp/shared/forms/forms.tsx","mod::kiskeya/webdesigns/registrationapp/pages/login/login.ts","mod::kiskeya/node_modules/idb/build/index.js","mod::kiskeya/webdesigns/registrationapp/pages/editregistration/editregistration.tsx","mod::kiskeya/js/crypto.ts","mod::kiskeya/webdesigns/registrationapp/pages/mysettings/mysettings.tsx","mod::kiskeya/webdesigns/registrationapp/pages/myregistrations/myregistrations.tsx","mod::kiskeya/webdesigns/registrationapp/registrationapp_pwa.tsx","/entrypoint.js"],"sourcesContent":["//We implement the backend version of getWHDebugFlags so bridge can access us without going through a recursive dep\n\nimport type { DTAPStage } from \"./concepts\";\n\n/// List global polyfills currently active. This may be needed to align TypeScript hosts configuration\nexport const globalPolyfills: string[] = [];\n\n/// An object with string keys and typed values\nexport interface WellKnownFlags {\n  /** Log RPcs */\n  rpc?: boolean;\n  /** Log web traffic */\n  wrq?: boolean;\n  /** Autoprofile */\n  apr?: boolean;\n  /** IPC */\n  ipc?: boolean;\n  /** async */\n  async?: boolean;\n}\nexport type DebugFlags = WellKnownFlags & { [key: string]: boolean | undefined };\n\nexport type DebugConfig = {\n  tags: readonly string[];\n  outputsession: string;\n  context: string;\n};\n\n/// Empty or no parameter lang is get, otherwise it's a set\nexport type GetSetAssetBase = (assetBase?: string | null) => string | null;\n\nexport type EnvHooks = {\n  currentAssetBase: GetSetAssetBase;\n};\n\n\nconst settingschangedcallbacks = new Array<() => void>;\n\n/* Global debug flags are set by `wh debug`, local flags are prefilled by environment variables.\n   Edits to the debug flags will be applied to the local flags (unless setDebugFlagsOverrideCB returns\n   override records).\n*/\nconst globalDebugFlags: DebugFlags = {}, localDebugFlags: DebugFlags = {};\n\n/** Returns the flag override records. The first record is examined first, then the second, etc. */\nlet debugFlagsOverridesCB: undefined | (() => DebugFlags[]);\n\n/** Override the debug flag override getter. */\nexport function setDebugFlagsOverrideCB(cb: undefined | (() => DebugFlags[])) {\n  debugFlagsOverridesCB = cb;\n}\n\n/* Proxy handler for the published debug flags. Uses the override records (with the first record\n   examined first, then the second, etc.) to override the flags from baseDebugFlags. Setting to `true` sets\n   the flag, `false` disables it and setting to `undefined` has the same effect as deleting the property in the\n   current top record (exposing any value from a lower record, like the debug settings from `wh debug`).\n*/\nclass DebugFlagsProxyHandler implements ProxyHandler<DebugFlags> {\n  private getRecordList(): DebugFlags[] {\n    return [...debugFlagsOverridesCB?.() ?? [], localDebugFlags, globalDebugFlags];\n  }\n\n  get(target: DebugFlags, p: string) {\n    for (const record of this.getRecordList())\n      if (p in record && typeof record[p] !== \"undefined\")\n        return record[p];\n    return undefined;\n  }\n  has(target: DebugFlags, p: string): boolean {\n    return this.get(target, p) !== undefined;\n  }\n  ownKeys(target: DebugFlags): Array<string | symbol> {\n    const keys = new Array<string | symbol>;\n    for (const record of this.getRecordList())\n      for (const key of Reflect.ownKeys(record))\n        if (typeof key === \"string\" && record[key] !== undefined && !keys.includes(key))\n          keys.push(key);\n    return keys;\n  }\n  set(target: DebugFlags, p: string, newValue: boolean | undefined): boolean {\n    const toModify = this.getRecordList()[0];\n    if (typeof newValue === \"boolean\")\n      toModify[p] = newValue;\n    else\n      delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  deleteProperty(target: DebugFlags, p: string): boolean {\n    const toModify = this.getRecordList()[0];\n    delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  getOwnPropertyDescriptor(target: DebugFlags, p: string): PropertyDescriptor | undefined {\n    const value = this.get(target, p);\n    return value !== undefined ? { enumerable: true, value, configurable: true } : undefined;\n  }\n}\n\nexport const debugFlags = new Proxy<DebugFlags>({\n  [Symbol.for('nodejs.util.inspect.custom')]: formatForConsoleLogs\n}, new DebugFlagsProxyHandler());\n\nfunction formatForConsoleLogs() {\n  return `DebugFlags [${[...Object.keys(debugFlags)].filter(key => debugFlags[key]).join(\", \")}]`;\n}\n\nfunction runSettingsCallbacks() {\n  for (const cb of [...settingschangedcallbacks]) {\n    try {\n      cb();\n    } catch (e) {\n      console.error(\"Error invoking settings change callback\", cb?.name, e);\n      //ignore, debugFlags can change due to external updates so they're basically signal handlers and there's no real point in crashing whatever was really running\n    }\n  }\n}\n\n/** Update the debugconfig as present in the system configuration record\n    @param settings - debugconfig cell of the system configuration record\n*/\nexport function updateDebugConfig(settings: DebugConfig | null) {\n  const oldenabledflags = Object.keys(globalDebugFlags).sort();\n  const newenabledflags = settings?.tags ? [...settings.tags].sort() : [];\n\n  if (oldenabledflags.join(\",\") !== newenabledflags.join(\",\")) {\n    for (const flag of newenabledflags)\n      globalDebugFlags[flag] = true;\n    for (const flag of oldenabledflags)\n      if (!newenabledflags.includes(flag))\n        delete globalDebugFlags[flag];\n\n    runSettingsCallbacks();\n  }\n  if (debugFlags.async && Error.stackTraceLimit < 100)\n    Error.stackTraceLimit = 100;\n}\n\nexport function registerDebugConfigChangedCallback(cb: () => void) {\n  settingschangedcallbacks.push(cb);\n}\n\nexport function updateLocalDebugFlags(mode: \"enable\" | \"disable\" | \"clear\", flags: string[]): DebugFlags {\n  switch (mode) {\n    case \"enable\":\n    case \"disable\":\n      for (const flag of flags)\n        localDebugFlags[flag] = mode === \"enable\";\n      break;\n    case \"clear\":\n      for (const flag of Object.keys(localDebugFlags))\n        delete localDebugFlags[flag];\n  }\n  runSettingsCallbacks();\n  return { ...globalDebugFlags, ...localDebugFlags };\n}\n\n/** DTAP stage set for this WebHare */\nlet dtapStage: DTAPStage = \"production\";\n\n/** @deprecated We now recommend checking dtapStage against production/acceptance Explicitly */\nlet isLive: boolean = dtapStage === \"production\" || dtapStage === \"acceptance\";\n\n/** The backend base URL. Used for eg. autoconfiguring JSON/RPC */\nlet backendBase = \"\";\n\n/** The global assetbase */\nlet assetBase: string | null = null;\n\n//deprecated variants\n/** @deprecated For WH5.4 and up use 'dtapStage' */\nlet dtapstage: DTAPStage = dtapStage;\n/** @deprecated For WH5.4 and up compare 'dtapStage' for production or acceptance */\nlet islive: boolean = isLive;\n\nlet hooks: EnvHooks | undefined;\nlet hookFactory: (() => EnvHooks) | undefined;\nlet gotHooks = false;\n\nexport function initEnv(setDtapStage: DTAPStage, setBackendBase: string) {\n  dtapStage = setDtapStage;\n  isLive = dtapStage === \"production\" || dtapStage === \"acceptance\";\n  backendBase = setBackendBase;\n\n  dtapstage = dtapStage;\n  islive = isLive;\n}\n\nexport function setEnvHooksFactory(newHookFactory: () => EnvHooks) {\n  if (gotHooks)\n    throw new Error(`The call to setEnvHooksFactory was too late - hooks have already been retrieved once`);\n  hookFactory = newHookFactory;\n}\n\nexport function getEnvHooks() {\n  gotHooks = true;\n  return hookFactory?.();\n}\n\nfunction ensureHooks(): EnvHooks {\n  return hooks ??= getEnvHooks?.() ?? {\n    currentAssetBase: (newAssetBase) => {\n      if (newAssetBase !== undefined)\n        assetBase = newAssetBase;\n      return assetBase;\n    }\n  };\n}\n\n/** Get the base url for assets. This may point towards eg. a CDN\n * @returns The base url for assets, ending with a '/'. null if not set\n */\nexport function getAssetBase(): string | null {\n  return ensureHooks().currentAssetBase();\n}\n\n/** Get the base url for a module's public assets (those located in the module's `public` folder)\n */\nexport function getModulePublicAssetBase(module: string) {\n  return `${getAssetBase() || \"/\"}.wh/mod/${encodeURIComponent(module)}/public/`;\n}\n\n/** Set the base url for assets */\nexport function setAssetBase(base: string | null): void {\n  if (base && !base.endsWith(\"/\"))\n    throw new Error(`Asset base must end with a '/'`);\n\n  ensureHooks().currentAssetBase(base);\n}\n\nexport { dtapStage, isLive, backendBase, localDebugFlags };\nexport { dtapstage, islive }; //deprecated variants\n","/** Rect describing an elements position */\nexport type Rect = {\n  top: number;\n  bottom: number;\n  left: number;\n  right: number;\n  width: number;\n  height: number;\n};\n\n/** Elements you can set a value on and would have to trigger change and/or input events */\nexport type FormControlElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\n\n/** Types that support querySelector(All) */\ntype QuerySelectorAble = ParentNode | ShadowRoot;\n\nexport function qS<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E | null;\nexport function qS<E extends Element = HTMLElement>(selector: string): E | null;\n\n/** Match the first element using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The first matching element or null\n */\nexport function qS<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E | null {\n  if (typeof node_or_selector === 'string')\n    return document.querySelector<E>(node_or_selector);\n  else if (selector)\n    return node_or_selector.querySelector<E>(selector);\n  return null;\n}\n\n\nexport function qR<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E;\nexport function qR<E extends Element = HTMLElement>(selector: string): E;\n\n/** Match a specific element using a CSS selector, requiring it to exist and be unique\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested element. Throw it the selector doesn't match exactly one element\n */\nexport function qR<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E {\n  const matches = qSA<E>(node_or_selector as QuerySelectorAble, selector as string);\n  if (matches.length === 1)\n    return matches[0];\n\n  if (typeof node_or_selector !== 'string') {\n    console.error(`${matches.length} elements match selector \\`${selector}\\` with startingpoint`, node_or_selector, matches);\n    throw new Error(`${matches.length} elements match selector \\`${selector}\\` given startingpoint '${node_or_selector.nodeName}'`);\n  } else {\n    console.error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`, matches);\n    throw new Error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`);\n  }\n}\n\nexport function qSA<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E[];\nexport function qSA<E extends Element = HTMLElement>(selector: string): E[];\n\n/** Find multiple elements using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested elements.\n */\nexport function qSA<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E[] {\n  if (typeof node_or_selector === 'string')\n    return Array.from(document.querySelectorAll(node_or_selector));\n  else if (selector)\n    return Array.from(node_or_selector.querySelectorAll(selector));\n\n  return [];\n}\n\n/** Return whether the passed element is a FormControlElement */\nexport function isFormControl(field: Element): field is FormControlElement {\n  return isHTMLElement(field) && [\"INPUT\", \"SELECT\", \"TEXTAREA\"].includes(field.tagName);\n}\n\n/** Return whether the passed element is an editable text field */\nexport function isEditControl(field: Element): field is HTMLElement {\n  return isHTMLElement(field) && ([\"INPUT\", \"TEXTAREA\"].includes(field.tagName) || field.isContentEditable);\n}\n\n/** Test whether node is an Element, even if it's in a different iframe */\nexport function isElement(node: unknown): node is Element {\n  //TODO What is actually going on if defaultView is missing?\n  if (!node || typeof node !== \"object\")\n    return false;\n\n  /* Getting the proto doesn't always work:\n  const proto = (node as Element).ownerDocument.defaultView?.Element;\n  (because our iframes derive off about? not sure) so until someone finds the real answer, we'll do a heuristic\n  */\n\n  /** Analyzing node.constructor.name doesn't work because custom elements don't necessarily have their constructor's name ending in Element\n  return Boolean(\"ownerDocument\" in node && node.constructor.name.match(/Element$/));\n  */\n\n  return Boolean(\"ownerDocument\" in node && (node as Element).nodeType === 1);\n\n}\n\n/** Test whether node is a HTMLElement, even if it's in a different iframe */\nexport function isHTMLElement(node: unknown): node is HTMLElement {\n  return isElement(node) && node.namespaceURI === \"http://www.w3.org/1999/xhtml\";\n}\n\n/** Test whether node is a SVGElement, even if it's in a different iframe */\nexport function isSVGElement(node: unknown): node is SVGElement {\n  return isElement(node) && node.namespaceURI === \"http://www.w3.org/2000/svg\";\n}\n\n/**\n * get the relative bound difference between two elements, and return a writable copy\n *\n * @param node - The node for which you need coordinates\n * @param relativeto - Optional reference point. If not set, you just get a 'normal' coordinate object\n */\nexport function getRelativeBounds(node: Element, relativeto?: Element): Rect {\n  if (!relativeto)\n    relativeto = node.ownerDocument.documentElement;\n\n  const nodecoords = node.getBoundingClientRect();\n  const relcoords = relativeto.getBoundingClientRect();\n  return {\n    top: nodecoords.top - relcoords.top,\n    left: nodecoords.left - relcoords.left,\n    right: nodecoords.right - relcoords.left,\n    bottom: nodecoords.bottom - relcoords.top,\n    width: nodecoords.width,\n    height: nodecoords.height\n  };\n}\n\nexport type ParsedLanguageTag = {\n  /** The full tag, eg en-US */\n  tag: string;\n  /** The language code, eg 'en' */\n  language: string;\n  region?: string;\n  /** The script, eg 'Hant' */\n  script?: string;\n};\n\n/** Parse a BCP47 language tag */\nexport function parseLanguageTag(languageTag: string): ParsedLanguageTag {\n  /* https://datatracker.ietf.org/doc/html/rfc5646#section-2.1\n     langtag       = language\n                 [\"-\" script]\n                 [\"-\" region]\n                 *(\"-\" variant)\n                 *(\"-\" extension)\n                 [\"-\" privateuse]\n     BUT: we're limiting ourselves to language, script and region for now\n\n     language      = 2*3ALPHA           ; shortest ISO 639 code\n                    [\"-\" extlang]       ; sometimes followed by\n                                          extended language subtags\n\n                                           extlang       = 3ALPHA              ; selected ISO 639 codes\n                 *2(\"-\" 3ALPHA)      ; permanently reserved\n\n      script        = 4ALPHA              ; ISO 15924 code\n\n      region        = 2ALPHA              ; ISO 3166-1 code\n                    / 3DIGIT              ; UN M.49 code\n\n     Note that we're not yet fully implementing the spec, just the parts we expect to encounter in practice\n  */\n  const match = languageTag.match(/^([a-z]{2,}(-[a-z]{3})?)(-[A-Za-z]{4,})?(-[A-Z]{2}|-\\d{3})?$/);\n  if (!match)\n    throw new Error(`Invalid language tag: ${languageTag}`);\n\n  return {\n    tag: languageTag,\n    language: match[1],\n    ...(match[3] ? { script: match[3].substring(1) } : {}),\n    ...(match[4] ? { region: match[4].substring(1) } : {})\n  };\n}\n\n/** Get the effective language for an element (or the document)\n * @param node - The element for which to get the effective language. If not specified, the documentElement and finally the browser is used\n * @returns The language code, eg. \"nl\" or \"en-GB\"\n */\nexport function getLang(node?: Element): ParsedLanguageTag {\n  if (!node && typeof document !== \"undefined\")\n    node = document.documentElement;\n  const tag = (node?.closest('[lang]')?.getAttribute(\"lang\") || navigator.language || \"en\");\n  return parseLanguageTag(tag);\n}\n","//TODO can we replace ourselves with nodejs util.types in a pure NodeJS environment?\n\nimport type { Money } from \"./money.ts\";\n\nexport function getWHType(obj: unknown): string | null { //not exporting this directly as we hope JS comes up with better solutions for instanceOf not being compatible with realms/reloading\n  // Ideally we'd use symbol but it breaks tree shaking in esbuild, so this is our workaround. Reported as https://github.com/evanw/esbuild/issues/3940\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Can't cleanly type this it seems and it's low level anyway\n  return (obj as any)?.constructor?.[\"__ $whTypeSymbol\"] ?? null;\n}\n\nfunction isCrossRealm(value: unknown): value is object {\n  return Boolean(value // it's not null\n    && typeof value === \"object\" //and it's an object\n    && !(value instanceof Object)); //and it's not an instance of our Object\n}\n\n/** Test whether a value looks like an instance of Money */\nexport function isMoney(value: unknown): value is Money {\n  return getWHType(value) === \"Money\";\n}\n\n/** Test whether a value looks like an instance of Temporal.Instant */\nexport function isTemporalInstant(value: unknown): value is Temporal.Instant {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.Instant');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDateTime */\nexport function isTemporalPlainDateTime(value: unknown): value is Temporal.PlainDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDateTime');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDate */\nexport function isTemporalPlainDate(value: unknown): value is Temporal.PlainDate {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDate');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainTime */\nexport function isTemporalPlainTime(value: unknown): value is Temporal.PlainTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainTime');\n}\n\n/** Test whether a value looks like an instance of Temporal.ZonedDateTime */\nexport function isTemporalZonedDateTime(value: unknown): value is Temporal.ZonedDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.ZonedDateTime');\n}\n\n/** Test whether a value looks like an instance of Date (assumes no subclasses) */\nexport function isDate(value: unknown): value is Date {\n  return value instanceof Date || (isCrossRealm(value) && value.constructor.name === \"Date\");\n}\n\n/** Test whether a value appears to implement the Blob interface */\nexport function isBlob(value: unknown): value is Blob {\n  return value instanceof Blob || Boolean(value && typeof value === \"object\" && \"size\" in value && \"type\" in value && \"slice\" in value && typeof value.slice === \"function\" && \"stream\" in value && typeof value.stream === \"function\");\n}\n\n/** Test whether a value appears to implement the File interface */\nexport function isFile(value: unknown): value is File {\n  return isBlob(value) && \"name\" in value;\n}\n\n/** Check if the object is probably an Error object. Can't use 'instanceof Error' as an Error might come from a different frame */\nexport function isError(e: unknown): e is Error {\n  return e instanceof Error || (isCrossRealm(e) && \"name\" in e && \"stack\" in e && \"message\" in e);\n}\n\n/** Check if the object looks like a promise */\nexport function isPromise<T>(e: T | Promise<T>): e is Promise<Awaited<T>> {\n  return Boolean(e && typeof (e as Promise<unknown>).then === \"function\" && typeof (e as Promise<unknown>).catch === \"function\");\n}\n\n/** Check the type of a value, return its JS or STD type\n * @param value - The value to check\n * @returns The type of the value. If the value is an object but recognized as any of Money, Date, Blob, Temporal.Instant/PlainDate/PlainDateTime, that type is returned.\n */\nexport function stdTypeOf(value: unknown): \"string\" | \"number\" | \"boolean\" | \"null\" | \"symbol\" | \"bigint\" | \"function\" | \"object\" | \"undefined\" | \"Date\" | \"Money\" | \"Array\" | \"Instant\" | \"PlainDate\" | \"PlainDateTime\" | \"PlainTime\" | \"ZonedDateTime\" | \"File\" | \"Blob\" {\n  const t = typeof value;\n  if (t === \"object\") {\n    if (!value)\n      return \"null\";\n    if (Array.isArray(value))\n      return \"Array\";\n    if (isMoney(value))\n      return \"Money\";\n    if (isBlob(value))\n      return isFile(value) ? \"File\" : \"Blob\";\n    if (isDate(value))\n      return \"Date\";\n    if (isTemporalInstant(value))\n      return \"Instant\";\n    if (isTemporalPlainTime(value))\n      return \"PlainTime\";\n    if (isTemporalPlainDate(value))\n      return \"PlainDate\";\n    if (isTemporalPlainDateTime(value))\n      return \"PlainDateTime\";\n    if (isTemporalZonedDateTime(value))\n      return \"ZonedDateTime\";\n  }\n  return t;\n}\n","import { isDate, isTemporalInstant } from \"./quacks.ts\";\n\n/** A tolerant JS date parameter */\nexport type FlexibleInstant = Date | Temporal.Instant | Temporal.ZonedDateTime;\n\n/** A relative (up to a week) or absolute wait period. Use 0 for 'polling' and Infinity to indicate an endless waits. Numbers are interpreted to be in milliseconds, a string is interpreted as a ISO8601 duration */\nexport type WaitPeriod = 0 | number | string | FlexibleInstant;\nexport interface Duration {\n  sign: \"+\" | \"-\";\n  years: number;\n  months: number;\n  weeks: number;\n  days: number;\n  hours: number;\n  minutes: number;\n  seconds: number;\n  milliseconds: number;\n}\n\nfunction parseMS(ms: string): number {\n  if (ms.length === 2) //.5\n    return parseInt(ms.substring(1)) * 100;\n  if (ms.length === 3) //.54\n    return parseInt(ms.substring(1)) * 10;\n  return parseInt(ms.substring(1, 4));\n}\n\n/** Parse an ISO8601 duration\n * @param duration - ISO8601 duration string (e.g. \"P1Y2M3DT4H5M6S\")\n */\nexport function parseDuration(duration: string): Duration {\n  // const matches = duration.match(/(-)?P(?:([.,\\d]+)Y)?(?:([.,\\d]+)M)?(?:([.,\\d]+)W)?(?:([.,\\d]+)D)?T(?:([.,\\d]+)H)?(?:([.,\\d]+)M)?(?:([.,\\d]+)S)?/);\n  const matches = duration.match(/^(-)?P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(\\.\\d+)?S)?)?$/);\n  if (!matches ||\n    (matches[4] && (matches[2] || matches[3] || matches[5])) || //can't have weeks and years/months/days\n    !(matches[2] || matches[3] || matches[4] || matches[5] || matches[6] || matches[7] || matches[8])) //one component must be present\n    throw new Error(`Invalid ISO8601 duration '${duration}'`);\n\n  return {\n    sign: matches[1] ? '-' : '+',\n    years: parseInt(matches[2]) || 0,\n    months: parseInt(matches[3]) || 0,\n    weeks: parseInt(matches[4]) || 0,\n    days: parseInt(matches[5]) || 0,\n    hours: parseInt(matches[6]) || 0,\n    minutes: parseInt(matches[7]) || 0,\n    seconds: parseInt(matches[8]) || 0,\n    milliseconds: matches[9] ? parseMS(matches[9]) : 0\n  };\n}\n\n/** Add a duration (time) to a date\n * @param startingdate - Date to start from\n * @param duration - Duration to add (as object or as ISO8601 duration string, eg \"P1Y2M3DT4H5M6S\")\n */\nexport function addDuration(startingdate: Date, duration: Partial<Duration> | string): Date;\nexport function addDuration(startingdate: Temporal.Instant, duration: Partial<Duration> | string): Temporal.Instant;\n\nexport function addDuration(startingdate: Date | Temporal.Instant, duration: Partial<Duration> | string): Date | Temporal.Instant {\n  if (isTemporalInstant(startingdate))\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- if you pass a Temporal.Instant, we should be able to create new ones from Temporal.\n    return (globalThis as any).Temporal.Instant.fromEpochMilliseconds(addDuration(new Date(startingdate.epochMilliseconds), duration).getTime());\n\n  //we cannot take timezones (flexible instant) yet? as we do not timezone correct day/week/month calculations\n  if (typeof duration === \"string\")\n    duration = parseDuration(duration);\n\n  const direction = duration.sign === \"-\" ? -1 : 1;\n  const date = new Date(startingdate.getTime());\n  if (duration.years)\n    date.setUTCFullYear(date.getUTCFullYear() + direction * duration.years);\n  if (duration.months)\n    date.setUTCMonth(date.getUTCMonth() + direction * duration.months);\n\n  const modifydays = (duration.days ?? 0) + (duration.weeks ?? 0) * 7;\n  if (modifydays)\n    date.setUTCDate(date.getUTCDate() + direction * modifydays);\n\n  const timeoffset = (duration.hours ?? 0) * 60 * 60 * 1000 + (duration.minutes ?? 0) * 60 * 1000 + (duration.seconds ?? 0) * 1000 + (duration.milliseconds ?? 0);\n  date.setTime(date.getTime() + direction * timeoffset);\n\n  return date;\n}\n\n/** Subtract a duration (time) from a date\n * @param startingdate - Date to start from\n * @param duration - Duration to subtract (as object or as ISO8601 duration string, eg \"P1Y2M3DT4H5M6S\")\n */\nexport function subtractDuration(startingdate: Date, duration: Partial<Duration> | string): Date;\nexport function subtractDuration(startingdate: Temporal.Instant, duration: Partial<Duration> | string): Temporal.Instant;\n\nexport function subtractDuration(startingdate: Date | Temporal.Instant, duration: Partial<Duration> | string): Date | Temporal.Instant {\n  if (isTemporalInstant(startingdate))\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- if you pass a Temporal.Instant, we should be able to create new ones from Temporal.\n    return (globalThis as any).Temporal.Instant.fromEpochMilliseconds(subtractDuration(new Date(startingdate.epochMilliseconds), duration).getTime());\n\n  if (typeof duration === \"string\")\n    duration = parseDuration(duration);\n\n  return addDuration(startingdate, { ...duration, sign: duration?.sign === \"-\" ? \"+\" : \"-\" });\n}\n\n/** Convert a flexible instant to a date\n * @param input - Date, Temporal.Instant or Temporal.ZonedDateTime value to convert\n * @returns The converted date (or null if the input is null)\n */\nexport function convertFlexibleInstantToDate(input: FlexibleInstant): Date;\nexport function convertFlexibleInstantToDate(input: null | undefined): null;\nexport function convertFlexibleInstantToDate(input: FlexibleInstant | null | undefined): Date | null;\n\nexport function convertFlexibleInstantToDate(input: FlexibleInstant | null | undefined): Date | null {\n  return input ? \"epochMilliseconds\" in input ? new Date(input.epochMilliseconds) : input : null;\n}\n\nexport function convertWaitPeriodToDate(wait: WaitPeriod, options: { relativeTo: Temporal.Instant }): Temporal.Instant;\nexport function convertWaitPeriodToDate(wait: WaitPeriod, options?: { relativeTo?: Date }): Date;\n\n/** Convert a WaitPeriod parameter to a Date\n * @param wait - Wait time as milliseconds or a Date\n * @param options - Options for conversion\n * @param options.relativeTo - Date to use as a reference for relative waits\n*/\nexport function convertWaitPeriodToDate(wait: WaitPeriod, options?: { relativeTo?: Date | Temporal.Instant }): Date | Temporal.Instant {\n  if (options?.relativeTo && isTemporalInstant(options?.relativeTo)) { //then our caller expects a Temporal.Instant\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- if you pass a Temporal.Instant, we should be able to create new ones from Temporal.\n    return (globalThis as any).Temporal.Instant.fromEpochMilliseconds(\n      convertWaitPeriodToDate(wait, { relativeTo: new Date(options?.relativeTo.epochMilliseconds) }).getTime()\n    );\n  }\n\n  if (isDate(wait)) {\n    return wait;\n  } else if (typeof wait === \"string\") {\n    return addDuration(convertFlexibleInstantToDate(options?.relativeTo) ?? new Date(), wait); //NOTE that \"P1D\" here adds \"24 hours\" which is *not* correct for a TimeZonedDate - which is why convertWaitPeriodToDate cannot yet accept these\n  } else if (typeof wait === \"number\") {\n    if (wait === 0)\n      return new Date(-864000 * 1000 * 10000000);\n    if (wait === Infinity)\n      return new Date(864000 * 1000 * 10000000);\n    if (wait > 0) //note: options?.relativeTo can't be instant, we already eliminated that above\n      return new Date(((options?.relativeTo as Date | undefined)?.getTime() ?? Date.now()) + wait);\n  } else if (wait && \"epochMilliseconds\" in wait) { //Instant or ZonedDateTime\n    return new Date(wait.epochMilliseconds);\n  }\n\n  throw new Error(\"Invalid wait duration - it must either be an absolute date, 0, a number of milliseconds or Infinity\");\n}\n\n/** Check whether the specified parts make a valid and reasonable (usually 1600+) date */\nexport function isValidDate(year: number, month: number, day: number, { minYear = 1601 } = {}) {\n  if (!(year >= minYear && year <= 9999 && month >= 1 && month <= 12 && day >= 1 && day <= 31\n    && Number.isSafeInteger(year) && Number.isSafeInteger(month) && Number.isSafeInteger(day)))\n    return false;\n  if ([4, 6, 9, 11].includes(month) && day > 30) //handle april, june, sep, nov\n    return false;\n  const isleapyear = (year % 400) === 0 || ((year % 100) !== 0 && (year % 4) === 0);\n  if (month === 2 && day > (isleapyear ? 29 : 28))\n    return false;\n  return true;\n}\n\n/** Check whether the specified parts make a reasonable time (does not consider the leap second a valid time) */\nexport function isValidTime(hour: number, minute: number, second: number, msec: number) {\n  return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59 && msec >= 0 && msec <= 999\n    && Number.isSafeInteger(hour) && Number.isSafeInteger(minute) && Number.isSafeInteger(second) && Number.isSafeInteger(msec);\n}\n\n/** Returns a string containing a formatted date and time.\n * @param format  A string that specifies the format of the output string. The string can contain the following:\n%%  Character %\n%a  Abbreviated weekday name\n%A  Full weekday name\n%b  Abbreviated month name\n%B  Full month name\n%d  Two-digit day of month (01 - 31)\n%#d Two-digit day of month, remove any leading zeros\n%H  Hour of the day, 24 hour day\n%#H Hour of the day, 24 hour day, remove any leading zeros\n%I  Two-digit hour, 12 hour day (01 - 12)\n%#I Two-digit hour, 12 hour day, remove any leading zeros\n%j  Three-digit day of year (001 - 366)\n%#j Three-digit day of year, remove any leading zeros\n%m  Two-digit month number (01 - 12)\n%#m Two-digit month number, remove any leading zeros\n%M  2-digit minute (00 - 59)\n%#M 2-digit minute, remove leading any zeros\n%Q  Three-digit millisecond (000-999)\n%#Q Three-digit millisecond, remove any leading zeros\n%p  AM or PM\n%S  Two-digit second (00 - 59)\n%#S Two-digit second, remove leading any zeros\n%V  Two-digot week number (00 - 52)\n%#V One-digit week number (0 - 52)\n%y  Two-digit year without century (00 to 99)\n%#y Two-digit year without century, remove any leading zeros\n%Y  Year with century\n%#Y Year with century, remove any leading zeros\n   @param zdt          The date/time value to format.\n   @example\n// The current date and time in German in the format: 01 Januar 2005\nconst example1 = formatDateTime(\"%d %B %Y\", Temporal.Instant.now(), { locale: \"de-DE\" });\n\n// The current day of the week in the Dutch language, using the\n// parameter datetexts as language switch.\n// The date format is <abbreviated> - <full>.\nconst example2 = formatDateTime(\"%a - %B \", new Date, { locale: \"nl-NL\" });\n*/\n\nexport function formatDateTime(format: string, zdt: Temporal.ZonedDateTime, options?: { locale: string }): string {\n  //TODO consider allowing Date & Instant too? might avoid users going for things like toString().replace(\"T\", \" \").replace(\"Z\", \"\")\n  //const zdt: Temporal.ZonedDateTime = date instanceof Date ? date.toTemporalInstant().toZonedDateTimeISO('UTC') : \"year\" in date ? date : date.toZonedDateTimeISO('UTC');\n  const locale = options?.locale || 'en-US';\n  let stripZeroes = false;\n\n  function formatNumber(num: number, length: number): string {\n    return stripZeroes ? num.toString() : num.toString().padStart(length, '0');\n  }\n\n  function formatPart(spec: string): string {\n    switch (spec) {\n      case 'a': //dayofweek name, abbreviated\n        return zdt.toLocaleString(locale, { weekday: 'short' });\n      case 'A': //dayofweek name, full\n        return zdt.toLocaleString(locale, { weekday: 'long' });\n      case 'b':  //month name, abbreviated\n        return zdt.toLocaleString(locale, { month: 'short' });\n      case 'B': //month name, abbreviated\n        return zdt.toLocaleString(locale, { month: 'long' });\n      case 'C': //century number\n        return formatNumber(Math.floor(zdt.year / 100), 2);\n      case 'd':  //day of month\n        return formatNumber(zdt.day, 2);\n      case 'H':  //hour of the day (24 hours format)\n        return formatNumber(zdt.hour, 2);\n      case 'I'://hour of the day (12 hours format)\n        return formatNumber((zdt.hour % 12) || 12, 2);\n      case 'j'://day of the year (three-digit)\n        return formatNumber(zdt.dayOfYear, 3);\n      case 'M'://two digit minute\n        return formatNumber(zdt.minute, 2);\n      case 'm'://two digit month\n        return formatNumber(zdt.month, 2);\n      case 'p'://am/pm\n        //Unfortunately this doesn't return am/pm: return zdt.toLocaleString(locale, { dayPeriod: 'narrow', hourCycle: \"h12\" });\n        return zdt.hour < 12 ? \"am\" : \"pm\";\n      case 'Q'://three digit millisecond\n        return formatNumber(Math.floor(zdt.millisecond), 3);\n      case 'S'://two digit second\n        return formatNumber(zdt.second, 2);\n      case 'V'://week number\n        if (zdt.weekOfYear === undefined)\n          throw new Error(\"Week of year is not defined for this calendar\");\n        return formatNumber(zdt.weekOfYear, 2);\n      case 'Y'://year, with century\n        return formatNumber(zdt.year, 4);\n      case 'y'://year, without century\n        return formatNumber(zdt.year % 100, 2);\n      default:\n        throw new Error(`Invalid date format specifier '%${spec}'`);\n    }\n  }\n\n  let out = '', inSpecifier = false;\n  for (const spec of [...format]) {\n    if (inSpecifier) {\n      if (spec === '#') {\n        stripZeroes = true;\n        continue; //get the next char\n      }\n\n      inSpecifier = false;\n      if (spec === '%') {\n        out += '%';\n        continue;\n      }\n      out += formatPart(spec);\n    } else {\n      if (spec === '%') {\n        inSpecifier = true;\n        stripZeroes = false; //reset it\n        continue;\n      }\n      out += spec;\n    }\n  }\n  if (inSpecifier)\n    throw new Error(\"Invalid date format string, ends with single %\");\n\n  return out;\n}\n","import { type WaitPeriod, convertWaitPeriodToDate } from \"./datetime.ts\";\nimport { isPromise } from \"./quacks.ts\";\n\n//TODO Deprecate once everyone is WH5.5+\nexport type DeferredPromise<T> = PromiseWithResolvers<T>;\n\n/** A promise that sleeps for the specified number of milliseconds\n *  @param duration - Relative (milliseconds, but not Infinity) or absolute (Date) wait duration. May not be Infinity\n *  @param options - Options - `signal` to set an AbortSignal which will cancel this sleep\n*/\nexport function sleep(duration: WaitPeriod, options?: { signal?: AbortSignal }): Promise<void> {\n  if (duration === Infinity)\n    throw new Error(`A sleep may not be infinite`);\n\n  const until = convertWaitPeriodToDate(duration);\n  return new Promise(resolve => {\n    const timeoutid = setTimeout(resolve, Math.max(0, until.getTime() - Date.now()));\n    if (options?.signal)\n      options.signal.addEventListener(\"abort\", () => clearTimeout(timeoutid));\n  });\n}\n\n/** @deprecated Use Promise.withResolvers instead */\nexport function createDeferred<T>(): PromiseWithResolvers<T> {\n  return Promise.withResolvers<T>();\n}\n\n/** Wrap a promise in a timeout\n * @param promise - Promise to wrap\n * @param timeout - Timeout in milliseconds or as a Date\n * @param rejectWith - Error to reject with if the timeout expires (string, Error, or a callback returning one)\n*/\nexport function wrapInTimeout<T>(promise: Promise<T>, timeout: WaitPeriod, rejectWith: string | Error | (() => string | Error)): Promise<T> {\n  if (timeout === Infinity)\n    return promise;\n\n  const until = convertWaitPeriodToDate(timeout);\n  const timeoutpromise = new Promise<T>((resolve, reject) => {\n    const timer = setTimeout(() => {\n      //this approach allows to delay actual Error object construction\n      const error: string | Error = typeof rejectWith === \"function\" ? rejectWith() : rejectWith;\n      reject(typeof error === \"object\" ? error : new Error(error));\n    }, until.getTime() - Date.now());\n\n    //ensure timer cancellation. No need to wait on this promise\n    promise = promise.finally(() => clearTimeout(timer));\n  });\n\n  return Promise.race([promise, timeoutpromise]);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we need to accept any callback.\ntype CallbackFunctionVariadic<RetType> = (...args: any[]) => Promise<RetType>;\n\nexport interface SerializeOptions {\n  ///Coalescing will ignore intermediate calls if the original call has not completed yet. Eg when invoking functions 1,2,3 in succession, only 3 will run, calls 1 and 2 will be merged into that call\n  coalesce?: boolean;\n}\n\nclass Coalescer<RetVal> {\n  private queue: Array<PromiseWithResolvers<RetVal>> = [];\n  private call: CallbackFunctionVariadic<RetVal> | null = null;\n  private readonly fn: CallbackFunctionVariadic<RetVal>;\n\n  //invoke is the actual entry point for incoming calls (ie C++'s operator() )\n  readonly invoke: CallbackFunctionVariadic<RetVal>;\n\n  constructor(fn: CallbackFunctionVariadic<RetVal>) {\n    this.invoke = this.onInvoke.bind(this);\n    this.fn = fn;\n  }\n  private onInvoke(...args: unknown[]): Promise<RetVal> {\n    //overwrite the call to execute\n    this.call = () => this.fn(...args); //TODO just queueing the parameters might do?\n\n    if (!this.queue.length) //schedule a flush of the queue\n      setTimeout(() => void this.flush(), 0);\n\n    this.queue.push(Promise.withResolvers<RetVal>());\n    return this.queue[this.queue.length - 1].promise;\n  }\n\n  private async flush() {\n    for (let startpos = 0; this.queue && startpos < this.queue?.length;) {\n      const currentpos = this.queue?.length;\n\n      try {\n        //invoke the last known call. *NOTE* new calls may be added to the queue now\n        const result = await this.call!();\n        for (let i = startpos; i < currentpos; i++)\n          this.queue[i].resolve(result);\n      } catch (e) {\n        for (let i = startpos; i < currentpos; i++)\n          this.queue[i].reject(e as Error);\n      }\n      startpos = currentpos;\n    }\n    //empty the queue\n    this.queue.splice(0, this.queue.length);\n  }\n}\n\n// export function<Fn extends (...args: any[]) => Promise<any>>(fn: Fn, options?: SerializeOptions): Fn {\n// type RetVal = ReturnType<Fn>;\n\n/** Wrap a function in a serializer */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we need to accept any callback.\nexport function wrapSerialized<Fn extends (...args: any[]) => Promise<any>>(fn: Fn, options?: SerializeOptions): Fn {\n  type RetVal = ReturnType<Fn>;\n  if (options?.coalesce)\n    return (new Coalescer<RetVal>(fn)).invoke as Fn;\n\n  let queue = Promise.resolve() as Promise<unknown>;\n  return ((...args: unknown[]): Promise<RetVal> => {\n    const res = queue.then(() => fn(...args));\n    queue = res.catch(() => { /* ignore errors */ });\n    return res;\n  }) as Fn;\n}\n\n//TODO abandon the name 'serialize' for now so it's free and safe to use once JS Decorators land (so we can use @serialize there)\n/** @deprecated Use wrapSerialized instead */\nexport function serialize<RetVal>(fn: (...args: unknown[]) => Promise<RetVal>, context: unknown) {\n  return wrapSerialized(fn, undefined);\n}\n\n/** Attempt to run code that may throw. If it throws anything, the fallback is returned\n\n   This allows you to replace:\n   ```\n   let url;\n     try {\n    url = new URL(inurl);\n  } catch (e) {\n    return null;\n  }```\n\n  with\n\n  ```\n  const url = attempt(() => new URL(inurl));\n  ```\n*/\nexport function attempt<T>(toTry: Promise<T> | (() => Promise<T>)): Promise<T | undefined>;\nexport function attempt<T, F>(toTry: Promise<T> | (() => Promise<T>), fallback: F): Promise<T | F>;\nexport function attempt<T>(toTry: () => T): T | undefined;\nexport function attempt<T, F>(toTry: () => T, fallback: F): T | F;\n\nexport function attempt<T, F>(toTry: (() => T) | Promise<T> | (() => Promise<T>), fallback?: F): T | F | Promise<T | F> {\n  try {\n    const retval = typeof toTry === \"function\" ? toTry() : toTry;\n    if (isPromise(retval))\n      return (retval as Promise<T>).catch(() => fallback as F);\n    return retval as T;\n  } catch (e) {\n    return fallback as F;\n  }\n}\n","/* A math library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nexport type FinmathInput = string | number;\n\nexport type RoundMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\n\nexport interface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\n//a 'price' is a string of the form \"nnn[.NNNN]\"\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let num, decimals;\n  ({ num, decimals } = stripUnneededDecimals(amount.num, amount.decimals));\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substr(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substr(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  // insert decimal point if needed\n  if (decimals)\n    astext = astext.substr(0, astext.length - decimals) + decimalpoint + astext.substr(-decimals);\n\n  // add sign if needed\n  astext = (isnegative ? \"-\" : \"\") + astext;\n  return astext;\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: FinmathInput): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\n/** Convert split number into a string\n*/\nfunction joinPrice(parts: SplitNumber): string {\n  return toText(parts, '.', 0);\n}\n\nfunction adjustDecimals(amount: SplitNumber, requiredecimals: number) {\n  const toadd = requiredecimals - amount.decimals;\n  if (toadd <= 0)\n    return;\n\n  let multiplier = 1;\n  for (let idx = 0; idx < toadd; ++idx)\n    multiplier *= 10;\n\n  if (!Number.isSafeInteger(amount.num * multiplier))\n    throw new Error(\"adjustDecimals would overflow the safe value range\");\n\n  amount.num *= multiplier;\n  amount.decimals += toadd;\n}\n\n/** Returns if a price string is valid\n*/\nexport function isValidPrice(money: string) {\n  if (typeof money !== 'string' || !money.match(/[0-9]+(\\.[0-9]{0,5})?$/))\n    return false;\n  return true;\n}\n\nfunction __add(lhs: SplitNumber, rhs: SplitNumber) {\n  //equalize # of decimals, and then it's a simple addition\n  const requiredecimals = Math.max(lhs.decimals, rhs.decimals);\n  adjustDecimals(lhs, requiredecimals);\n  adjustDecimals(rhs, requiredecimals);\n  return { num: lhs.num + rhs.num, decimals: requiredecimals };\n}\n\n/** Adds two numbers together\n*/\nexport function add(amount1: FinmathInput, amount2: FinmathInput): string {\n  return joinPrice(__add(splitValue(amount1), splitValue(amount2)));\n}\n\n/** Subtracts a number from another number\n*/\nexport function subtract(amount: FinmathInput, tosubtract: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(tosubtract);\n  rhs.num = -rhs.num;\n  return joinPrice(__add(lhs, rhs));\n}\n\nfunction __multiply(lhs: SplitNumber, rhs: SplitNumber) {\n  //ADDME the naive 'add decimals, multiple nums' approach gets you out of the safe range real fast. needs tests\n  return { num: lhs.num * rhs.num, decimals: lhs.decimals + rhs.decimals };\n}\n\n/** Multiplies two numbers together\n*/\nexport function multiply(amount1: FinmathInput, amount2: FinmathInput): string {\n  const lhs = splitValue(amount1), rhs = splitValue(amount2);\n  return joinPrice(__multiply(lhs, rhs));\n}\n\n/** Compares two numbers\n    @param amount1 - Left hand value\n    @param amount2 - Right hand value\n    @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n*/\nexport function cmp(amount1: FinmathInput, amount2: FinmathInput) {\n  const diff = __add(splitValue(amount1), __multiply(splitValue(amount2), { num: -1, decimals: 0 }));\n  return diff.num < 0 ? -1 : diff.num === 0 ? 0 : 1;\n}\n\n/** Returns a percentage of an amount\n    @param amount - Original amount\n    @param perc - Percentage of the amount to return\n    @returns Percentage of the amount\n*/\nexport function getPercentageOfAmount(amount: FinmathInput, perc: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(perc);\n  const result = __multiply(lhs, rhs);\n  result.decimals += 2;\n  return joinPrice(normalize(result));\n}\n\nfunction normalize(amount: SplitNumber) {\n  while (amount.decimals && (amount.num % 10) === 0) {\n    amount.num /= 10;\n    --amount.decimals;\n  }\n  return amount;\n}\n\n/// format a price amount. extend # of decimals to specified # if not enough\nexport function formatPrice(money: FinmathInput, decimalpoint: string, decimals: number) {\n  return toText(splitValue(money), decimalpoint, decimals);\n}\n\n/** Rounds integer to multiple, exposed for testing only\n*/\nexport function __roundIntegerToMultiple(value: number, roundunit: number, mode: RoundMode) {\n  switch (mode) {\n    case \"none\":\n      {\n        // no rounding\n      } break;\n    case \"toward-zero\":\n      {\n        value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"down\":\n      {\n        if (value > 0)\n          value = Math.trunc(value / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"half-toward-zero\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-down\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    default:\n      {\n        throw new Error(`Unknown rounding mode ${mode}`);\n      }\n  }\n  return value;\n}\n\n/** Rounds a value to a multiple of a unit, with a specific rounding mode\n    @param value - Value to round\n    @param unit - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n    @param mode - Rounding mode. Possible values:\n      <ul>\n        <li>none: No rounding</li>\n        <li>toward-zero: Round toward zero</li>\n        <li>down: Round toward negative infity</li>\n        <li>up: Round toward positive infity</li>\n        <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n        <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n        <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n      </ul>\n    @returns The rounded value\n*/\nexport function roundToMultiple(value: FinmathInput, unit: FinmathInput, mode: RoundMode) {\n  const split_value = splitValue(value);\n  const split_unit = splitValue(unit);\n\n  const requiredecimals = Math.max(split_value.decimals, split_unit.decimals);\n  adjustDecimals(split_value, requiredecimals);\n  adjustDecimals(split_unit, requiredecimals);\n\n  const result = { num: __roundIntegerToMultiple(split_value.num, split_unit.num, mode), decimals: split_value.decimals };\n  return joinPrice(result);\n}\n\n/** Returns the minimum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The lowest value among amount and amounts\n*/\nexport function min(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) > 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns the maximum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The highest value among amount and amounts\n*/\nexport function max(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) < 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns a power of 10\n    @param exp - Integer power, must be 0 or bigger\n    @returns Requested power of 10\n*/\nfunction getNonNegativePowerOf10(exp: number) {\n  let retval = 1, running_exp = 10;\n  while (exp) {\n    if (exp & 1)\n      retval *= running_exp;\n    running_exp *= running_exp;\n    exp = exp >> 1;\n  }\n  return retval;\n}\n\n/** Divides two values, with 5 decimals of precision\n    @param value - Value To divide\n    @param divisor - Divisor\n    @returns Divided value, with 5 decimals of precision\n*/\nexport function divide(value: FinmathInput, divisor: FinmathInput) {\n  const lhs = splitValue(value), rhs = splitValue(divisor);\n  const mul10exp = lhs.decimals - rhs.decimals - 5;\n  const mulfactor = mul10exp < 0 ? getNonNegativePowerOf10(-mul10exp) : 1;\n  const roundunit = mul10exp > 0 ? getNonNegativePowerOf10(mul10exp) : 1;\n  return joinPrice({ num: __roundIntegerToMultiple(mulfactor * lhs.num / rhs.num, roundunit, \"half-toward-infinity\"), decimals: 5 });\n}\n\nexport function moneyDivide(value: FinmathInput, divisor: FinmathInput) { //divide was added in 5.0. remove this old name eventually\n  return divide(value, divisor);\n}\n\n/** Test whether two values have a specific relation\n    @param lhs - Left hand value\n    @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n    @param rhs - Right hand value\n    @returns TRUE if the relation holds\n    @example\n      console.log(finmath.test(1, '\\<', 2)); // prints 'true'\n*/\nexport function test(lhs: FinmathInput, relation: \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\", rhs: FinmathInput) {\n  const compareresult = cmp(lhs, rhs);\n  switch (relation) {\n    case '<': return compareresult < 0;\n    case '<=': return compareresult <= 0;\n    case '==': return compareresult === 0;\n    case '!=': return compareresult !== 0;\n    case '>': return compareresult > 0;\n    case '>=': return compareresult >= 0;\n  }\n  throw Error(`Cannot test for unknown relation '${relation}'`);\n}\n","/* A Money type library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   We haven't decideded yet what range Money should support. To keep our options open and keep HS compatbility for now\n   we will fix ourselves to 5 digits (HS compat) and not allow values bigger than 900_000_000 (2**53 / 100000 'number' compatbiility clamped to a more readable number)\n\n  Users should not rely on JS Money keeping this smaller range in the future. Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nimport * as finmath from \"./finmath.ts\"; //TODO absorb into us as soon as noone externally depends on finmath anymore\nimport { isMoney } from \"./quacks.ts\";\n\nexport type MoneyRoundingMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\nexport type MoneyTestTypes = \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\";\n\ntype MoneyParameter = Money | string;\n\ninterface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\nexport interface MoneyFormatOptions {\n  //thousand separator. defaults to \"\"\n  thousandsSeparator?: string;\n  //decimal separator. defaults to \".\"\n  decimalSeparator?: string;\n  //minimum # of decimals. defaults to 2\n  minDecimals?: number;\n}\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: MoneyParameter): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number, thousandpoint: string) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let { num, decimals } = stripUnneededDecimals(amount.num, amount.decimals);\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substring(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substring(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  let beforepoint = astext.substring(0, astext.length - decimals);\n  const afterpoint = astext.substring(astext.length - decimals);\n\n  // Add thouands points if neeed\n  if (thousandpoint)\n    beforepoint = beforepoint.replaceAll(/\\B(?=(\\d{3})+(?!\\d))/g, thousandpoint);\n\n  return (isnegative ? \"-\" : \"\") + beforepoint + (afterpoint.length ? decimalpoint + afterpoint : \"\");\n}\n\n/** A decimal based JS money type*/\nexport class Money {\n  /** finmath-compatible value */\n  readonly value: string;\n  private static \"__ $whTypeSymbol\" = \"Money\";\n\n  constructor(value: MoneyParameter = \"0\") {\n    this.value = Money.parseParameter(value);\n\n    const intvalue = parseInt(this.value);\n    //We need the number to be in the safe range even after adding 5 decimals\n    if (intvalue <= (Number.MIN_SAFE_INTEGER / 100000) || intvalue >= (Number.MAX_SAFE_INTEGER / 100000))\n      throw new TypeError(`Money value '${value}' is out of range`);\n  }\n\n  private static parseParameter(param: MoneyParameter): string {\n    if (typeof param === \"string\")\n      return toText(splitValue(param), \".\", 0, \"\");\n    if (Money.isMoney(param))\n      return (param as unknown as { value: string }).value;\n\n    throw new TypeError(`Money cannot be constructed out of a value of type ${typeof param}`);\n  }\n\n  static isMoney(value: unknown): value is Money {\n    return isMoney(value);\n  }\n\n  static fromNumber(value: number): Money {\n    return new Money(String(value));\n  }\n\n  /** Adds numbers together\n  */\n  static add(left: MoneyParameter, ...right: MoneyParameter[]): Money {\n    let sum = Money.parseParameter(left);\n    for (const item of right)\n      sum = finmath.add(sum, Money.parseParameter(item));\n    return new Money(sum);\n  }\n\n  /** Subtracts a number from another number\n  */\n  static subtract(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.subtract(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Rounds a value to a multiple of a unit, with a specific rounding mode\n      @param amount - Value to round\n      @param roundto - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n      @param mode - Rounding mode. Possible values:<br>\n        <ul>\n          <li>none: No rounding</li>\n          <li>toward-zero: Round toward zero</li>\n          <li>down: Round toward negative infity</li>\n          <li>up: Round toward positive infity</li>\n          <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n          <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n          <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n        </ul>\n      @returns The rounded value\n  */\n  static roundToMultiple(amount: MoneyParameter, roundto: MoneyParameter, mode: MoneyRoundingMode): Money {\n    return new Money(finmath.roundToMultiple(Money.parseParameter(amount), Money.parseParameter(roundto), mode));\n  }\n\n  /** Compares two numbers\n      @param lhs - Left hand value\n      @param rhs - Right hand value\n      @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n  */\n  static cmp(lhs: MoneyParameter, rhs: MoneyParameter): -1 | 0 | 1 {\n    return finmath.cmp(Money.parseParameter(lhs), Money.parseParameter(rhs));\n  }\n\n  /** Test whether two values have a specific relation\n      @param lhs - Left hand value\n      @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n      @param rhs - Right hand value\n      @returns TRUE if the relation holds\n      @example\n        console.log(Money.check(1, '\\<', 2)); // prints 'true'\n  */\n  static check(lhs: MoneyParameter, relation: MoneyTestTypes, rhs: MoneyParameter): boolean {\n    return finmath.test(Money.parseParameter(lhs), relation, Money.parseParameter(rhs));\n  }\n\n  /** Multiplies two numbers together\n  */\n  static multiply(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.multiply(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Returns a percentage of an amount\n      @param amount - Original amount\n      @param percentage - Percentage of the amount to return\n      @returns Percentage of the amount\n  */\n  static getPercentage(amount: MoneyParameter, percentage: MoneyParameter): Money {\n    return new Money(finmath.getPercentageOfAmount(Money.parseParameter(amount), Money.parseParameter(percentage)));\n  }\n\n  /** Divides two values, (currently with up to 5 decimals of precision)\n      @param numerator - Value to divide\n      @param divisor - Divisor\n      @returns Divided value\n  */\n  static divide(numerator: MoneyParameter, divisor: MoneyParameter): Money {\n    return new Money(finmath.divide(Money.parseParameter(numerator), Money.parseParameter(divisor)));\n  }\n  /** Returns the minimum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The lowest value among amount and amounts\n  */\n  static min(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.min(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n\n  }\n\n  /** Returns the maximum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The highest value among amount and amounts\n  */\n  static max(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.max(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n  }\n\n  /** format a price amount. extend # of decimals to specified # if not enough */\n  format(format?: MoneyFormatOptions): string {\n    return toText(splitValue(this.value),\n      format?.decimalSeparator ?? \".\",\n      format?.minDecimals ?? 2,\n      format?.thousandsSeparator ?? \"\");\n  }\n\n  toJSON(): string {\n    return this.value;\n  }\n\n  toString(): string {\n    return this.value;\n  }\n\n  toNumber(): number {\n    return parseFloat(this.value);\n  }\n}\n","import { Money } from \"./money.ts\";\nimport { isBlob, isDate, isMoney, isPromise, isTemporalInstant, isTemporalPlainDate, isTemporalPlainDateTime, isTemporalPlainTime, isTemporalZonedDateTime, stdTypeOf } from \"./quacks.ts\";\n\n/// Returns T or a promise resolving to T\nexport type MaybePromise<T> = Promise<T> | T;\n\nexport type ComparableType = number | null | bigint | string | Date | Money | boolean | Uint8Array | Temporal.Instant | Temporal.PlainDate | Temporal.PlainTime | Temporal.ZonedDateTime;\n\ntype CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}`\n  ? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`\n  : Lowercase<S>;\n\ntype KeysToCamelCase<T> = {\n  [K in keyof T as CamelCase<string & K>]: ToCamelCase<T[K]>;\n};\n\ntype CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ?\n  `${T extends Capitalize<T> ? \"_\" : \"\"}${Lowercase<T>}${CamelToSnakeCase<U>}` :\n  S;\n\ntype KeysToSnakeCase<T> = {\n  [K in keyof T as CamelToSnakeCase<string & K>]: ToSnakeCase<T[K]>\n};\n\ntype NonRecordTypes = Date | Money | Blob | Temporal.Instant | Temporal.PlainDate | Temporal.PlainDateTime | Temporal.ZonedDateTime;\n\nexport type ToSnakeCase<T> =\n  T extends unknown[] ? Array<ToSnakeCase<T[number]>> :\n  T extends NonRecordTypes ? T :\n  T extends object ? KeysToSnakeCase<T> :\n  T;\n\nexport type ToCamelCase<T> =\n  T extends unknown[] ? Array<ToCamelCase<T[number]>> :\n  T extends NonRecordTypes ? T :\n  T extends object ? KeysToCamelCase<T> :\n  T;\n\n/** Convert a snake_case_name to its corresponding camelCaseName\n * @param name - Name to convert\n * @returns Converted name\n*/\nexport function nameToCamelCase(name: string) {\n  return name.replaceAll(/_[a-z]/g, c => c[1].toUpperCase());\n}\n\n/** Convert a camelCaseName to corresponding snake_case_name\n * @param name - Name to convert\n * @returns Converted name\n*/\nexport function nameToSnakeCase(name: string) {\n  return name.replaceAll(/[A-Z]/g, c => '_' + c.toLowerCase());\n}\n\n/// Should we rewrite the key/values in this object?\nfunction recodeObject(inp: object) {\n  return !isDate(inp) && !isMoney(inp) && !isBlob(inp) && !isTemporalInstant(inp) && !isTemporalPlainDate(inp) && !isTemporalPlainDateTime(inp) && !isTemporalZonedDateTime(inp);\n}\n\nfunction recursiveToSnakeCase<T>(inp: T): ToSnakeCase<T> {\n  if (Array.isArray(inp))\n    return inp.map(toSnakeCase) as ToSnakeCase<T>;\n  if (inp && typeof inp === \"object\" && recodeObject(inp))\n    return Object.fromEntries(Object.entries(inp).map(([key, value]) => [nameToSnakeCase(key), recursiveToSnakeCase(value)])) as ToSnakeCase<T>;\n  return inp as ToSnakeCase<T>;\n}\n\nfunction recursiveToCamelCase<T>(inp: T): ToCamelCase<T> {\n  if (Array.isArray(inp))\n    return inp.map(toCamelCase) as ToCamelCase<T>;\n  if (inp && typeof inp === \"object\" && recodeObject(inp))\n    return Object.fromEntries(Object.entries(inp).map(([key, value]) => [nameToCamelCase(key), recursiveToCamelCase(value)])) as ToCamelCase<T>;\n  return inp as ToCamelCase<T>;\n}\n\n/** Convert all keys to camel case recursively\n * @param inp - Array or object to convert\n * @returns Converted object\n*/\nexport function toSnakeCase<T extends object | object[] | null | undefined>(inp: T): ToSnakeCase<T> {\n  return recursiveToSnakeCase(inp);\n}\n\n/** Convert all keys to snake case recursively\n * @param inp - Array or object to convert\n * @returns Converted object\n*/\nexport function toCamelCase<T extends object | object[] | null | undefined>(inp: T): ToCamelCase<T> {\n  return recursiveToCamelCase(inp);\n}\n\n// TODO make this a quack if we're sure Uint8array is what we want to support - this is here basically to give Buffer support to be compatible with hscompat' compare\nfunction isUInt8Array(value: unknown): value is Uint8Array {\n  return value !== null && typeof value === \"object\" && \"length\" in value && (value as Uint8Array).BYTES_PER_ELEMENT === 1;\n}\n\ntype AwaitedValues<T extends readonly unknown[]> = { -readonly [K in keyof T]: Awaited<T[K]> };\n\n/** Resolve an array of potential promises, returning an array with resolved results\n * @param array - Array of values or promises\n * @returns An array of resolved values, or a promise resolving to that array if any input was a promise\n*/\nexport function maybePromiseAll<const T extends readonly unknown[]>(array: T): MaybePromise<AwaitedValues<T>> {\n  const resolved: Array<Awaited<T[number]>> = [];\n  for (const item of array) {\n    if (isPromise(item))\n      return Promise.all(array) as Promise<AwaitedValues<T>>;\n    resolved.push(item as Awaited<T[number]>);\n  }\n  return resolved as AwaitedValues<T>;\n}\n\n/** Call a function on the value of a potential promise, return the result\n * @param value - Value or promise\n * @param cb - Callback to call on the value\n * @returns The result of the callback, or a promise resolving to that result if the input was a promise\n*/\nexport function mapMaybePromise<T, U>(value: T, cb: (arg: Awaited<T>) => U): U | Promise<U> {\n  return isPromise(value) ? value.then(t => cb(t as Awaited<T>)) : cb(value as Awaited<T>);\n}\n\n/** Compare two values of std-supported types\n * @param left - First value\n * @param right - Second value\n * @returns -1 if left \\< right, 0 if equal, 1 if left \\> right\n */\nexport function compare(left: ComparableType, right: ComparableType): -1 | 0 | 1 {\n  if (left === null)\n    return right === null ? 0 : -1;\n  else if (right === null)\n    return 1;\n\n  switch (typeof left) {\n    case \"boolean\": {\n      if (typeof right === \"boolean\")\n        return left !== right ? left < right ? -1 : 1 : 0;\n    } break;\n    case \"number\": {\n      switch (typeof right) {\n        case \"bigint\": {\n          const right_number = Number(right);\n          return left !== right_number ? left < right_number ? -1 : 1 : 0;\n        }\n        case \"number\": {\n          return left !== right ? left < right ? -1 : 1 : 0;\n        }\n        case \"object\": {\n          if (Money.isMoney(right))\n            return Money.cmp(left.toString(), right);\n        }\n      }\n    } break;\n    case \"bigint\": {\n      switch (typeof right) {\n        case \"bigint\": {\n          return left !== right ? left < right ? -1 : 1 : 0;\n        }\n        case \"number\": {\n          const left_number = Number(left);\n          return left_number !== right ? left_number < right ? -1 : 1 : 0;\n        }\n        case \"object\": {\n          if (Money.isMoney(right)) {\n            return Money.cmp(left.toString(), right);\n          }\n        }\n      }\n    } break;\n    case \"string\": {\n      if (typeof right === \"string\")\n        return left === right ? 0 : left < right ? -1 : 1;\n    } break;\n    case \"object\": {\n      if (Money.isMoney(left)) {\n        switch (typeof right) {\n          case \"number\":\n          case \"bigint\":\n            return Money.cmp(left, right.toString());\n          case \"object\": {\n            if (right === null) {\n              return 1;\n            } else if (Money.isMoney(right))\n              return Money.cmp(left, right);\n          }\n        }\n      } else if (isDate(left)) {\n        if (isTemporalInstant(right)) {\n          const left_value = Number(left);\n          const right_value = right.epochMilliseconds;\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        } else if (isDate(right)) {\n          const left_value = Number(left);\n          const right_value = Number(right);\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        }\n      } else if (isUInt8Array(left) && isUInt8Array(right)) {\n        const compareLength = Math.min(left.length, right.length);\n        for (let i = 0; i < compareLength; i++) {\n          if (left[i] !== right[i])\n            return left[i] < right[i] ? -1 : 1;\n        }\n        return left.length !== right.length ? left.length < right.length ? -1 : 1 : 0;\n      } else if (isTemporalInstant(left)) {\n        if (isDate(right)) {\n          const left_value = left.epochMilliseconds;\n          const right_value = Number(right);\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        } else if (isTemporalInstant(right)) {\n          const left_value = left.epochMilliseconds;\n          const right_value = right.epochMilliseconds;\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        }\n      } else if (isTemporalPlainDate(left) && isTemporalPlainDate(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.PlainDate.compare(left, right);\n      } else if (isTemporalPlainTime(left) && isTemporalPlainTime(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.PlainTime.compare(left, right);\n      } else if (isTemporalZonedDateTime(left) && isTemporalZonedDateTime(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.ZonedDateTime.compare(left, right);\n      }\n    } break;\n  }\n  throw new Error(`Cannot compare a ${stdTypeOf(left)} with a ${stdTypeOf(right)}`);\n}\n\n/** Returns all property keys of an object type whose value is comparable */\ntype ComparableFields<E extends object, K extends keyof E = keyof E> = K extends keyof E ? E[K] extends ComparableType ? K : never : never;\n\n/** Type of array elements for keys in `compareProperties` */\ntype ComparePropertiesArrayElement<E extends object> = ComparableFields<E> | [ComparableFields<E>, \"asc\" | \"desc\"];\n\n/** All possible types of object keys */\ntype AnyKey = string | symbol | number;\n\n/** Extracts the property name from an array element of CompareProperties */\ntype GetPropertyFromComparePropertiesArrayElement<T> = T extends AnyKey ? T : T extends [infer A, \"asc\" | \"desc\"] ? A : never;\n\n/** Get the list of properties referenced in the `compareProperties` keys list */\ntype GetPropertiesFromComparePropertiesKeys<K extends AnyKey | Array<AnyKey | [AnyKey, \"asc\" | \"desc\"]>> = K extends AnyKey ? K : K extends Array<infer T> ? GetPropertyFromComparePropertiesArrayElement<T> : never;\n\n/** Get all proper prefixes of a tuple, excluding the empty tuple and the source tuple */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TuplePrefixes<K extends AnyKey | [...any[]]> = K extends [any] ? never : K extends [infer A, ...infer B] ? [A] | [A, ...TuplePrefixes<B>] : never;\n\n/** Template for possible keys value (needed to make TS understand that a tuple prefix of the keys is also a valid keys list */\ntype PossibleFields<E extends object> = ComparableFields<E> | [ComparePropertiesArrayElement<E>, ...Array<ComparePropertiesArrayElement<E>>];\n\n/**\n * Build a comparator function for objects using one or more comparable properties.\n * This is extremely useful as a type-safe comparator for sort/toSorted APIs, especially\n * when dealing with multiple or non-string keys.\n *\n * Keys can be provided as:\n * - a single property key\n * - a tuple/array of keys\n * - a tuple/array with sort direction entries in the form [key, \"asc\" | \"desc\"]\n *\n * Comparison is performed in order until the first non-zero result.\n *\n * @param fields - Field selector(s) defining compare priority and optional direction.\n * @returns A compare callback suitable for Array.prototype.sort, extended with\n * `partialCompare(...)` to create a comparator for a prefix of the same key sequence.\n * @throws Error if any configured property is undefined on either compared object.\n * @example\n * ```ts\n * const byName = compareProperties(\"name\");\n * users.sort(byName);\n * ```\n *\n * @example\n * ```ts\n * const byPriorityThenDate = compareProperties([\n *   [\"priority\", \"desc\"],\n *   [\"createdAt\", \"asc\"]\n * ] as const);\n * items.sort(byPriorityThenDate);\n * ```\n *\n * @example\n * ```ts\n * const byCountryCityStreet = compareProperties([\"country\", \"city\", \"street\"] as const);\n * const byCountryCity = byCountryCityStreet.partialCompare([\"country\", \"city\"] as const);\n * addresses.sort(byCountryCity);\n * ```\n */\nexport function compareProperties<const K extends ComparableFields<E> | [...Array<ComparePropertiesArrayElement<E>>], E extends object = Record<GetPropertiesFromComparePropertiesKeys<K>, ComparableType>>(fields: K) {\n  const compareList = (Array.isArray(fields) ? fields : [fields]).map((field): [keyof E, 1 | -1] => Array.isArray(field) ? [field[0], field[1] === \"desc\" ? -1 : 1] : [field, 1]);\n  const retval: (lhs: E, rhs: E) => number = (a, b) => {\n    for (const [field, negate] of compareList) {\n      if (a[field] === undefined || b[field] === undefined)\n        throw new Error(`Property '${String(field)}' does not exist`);\n      const res = negate * compare(a[field] as ComparableType, b[field] as ComparableType);\n      if (res)\n        return res;\n    }\n    return 0;\n  };\n  return Object.assign(retval, {\n    partialCompare: <T extends TuplePrefixes<K> & PossibleFields<E>>(partialFields: T) => compareProperties<T, E>(partialFields)\n  });\n}\n\nlet enumReverseMaps: WeakMap<Record<string, string | number>, Record<string | number, string>> | undefined;\n\ntype EnumEntries<T extends Record<string, string | number>, F extends number, K extends keyof T = keyof T> = K extends keyof T ? T[K] extends F ? [K, T[K]] : never : never;\n\n/** Returns the reverse mapping of a value of an const object used as enum. Can only be used for numbers.\n * @param enumObj - The enum object to reverse map.\n * @param value - The value to look up in the reverse map.\n * @returns The key corresponding to the given value in the enum object.\n * @example\n * ```ts\n * const Color = {\n *   Red: 1,\n *   Green: 2,\n *   Blue: 3\n * } as const;\n * const key = enumReverseMap(Color, 2); // \"Green\"\n * ```\n */\nexport function enumReverseMap<const T extends Record<string, string | number>, const V extends EnumEntries<T, number>[1]>(enumObj: T, value: V): EnumEntries<T, V>[0] {\n  enumReverseMaps ??= new WeakMap<Record<string, string | number>, Record<string | number, string>>();\n  let reverse = enumReverseMaps.get(enumObj);\n  if (!reverse) {\n    reverse = {} as Record<string | number, string>;\n    for (const [key, v] of Object.entries(enumObj))\n      if (typeof v === \"number\")\n        reverse[enumObj[key]] = key;\n    enumReverseMaps.set(enumObj, reverse);\n  }\n  return reverse[value];\n}\n","import { stdTypeOf } from \"./quacks.ts\";\nimport { Money } from \"./money.ts\";\n\nexport type WildcardTypes = \"?*\";\n\n/** Encode string for use in a regexp\n * @param text - Text to encode\n * @param options - Options for encoding\n * @param options.wildcards - Type of wildcards to encode (defaults to none)\n * @returns Encoded for safe use in a RegExp\n*/\nexport function escapeRegExp(text: string, options?: { wildcards?: WildcardTypes }): string {\n  let mask = text.replaceAll(/[/\\-\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); // $& means the whole matched string\n  if (options?.wildcards === \"?*\") {\n    mask = mask.replaceAll(\"\\\\*\", \".*\");\n    mask = mask.replaceAll(\"\\\\?\", \".\");\n  }\n  return mask;\n}\n\n/** Create a regular expression from one or more wildcard masks\n * @param masks - One or more masks with '?' and/or '*' wildcards\n * @returns Regular expression string\n*/\nexport function regExpFromWildcards(masks: string | string[], options?: { wildcards?: WildcardTypes; caseInsensitive?: boolean }): RegExp {\n  if (Array.isArray(masks) && masks.length === 0)\n    throw new Error(\"Empty mask list\");\n\n  const code = Array.isArray(masks)\n    ? `^(${masks.map(mask => escapeRegExp(mask, { wildcards: options?.wildcards || \"?*\" })).join('|')})$`\n    : `^${escapeRegExp(masks, { wildcards: options?.wildcards || \"?*\" })}$`;\n  return new RegExp(code, options?.caseInsensitive ? \"i\" : undefined);\n}\n\nfunction isHTMLUnrepresentableChar(curch: number) {\n  return (curch < 32 && curch !== 9 && curch !== 10 && curch !== 13)\n    || (curch >= 128 && curch <= 159);\n}\n\nfunction encodeEntities(str: string, html: boolean) {\n  let s = \"\";\n  for (const char of str) {\n    const curch = char.codePointAt(0);\n    if (curch === undefined || isHTMLUnrepresentableChar(curch))\n      continue;\n    if (curch >= 32 && curch < 128 && curch !== 38 && curch !== 60 && curch !== 62 && (html || curch !== 34 && curch !== 39)) {\n      s += String.fromCodePoint(curch);\n      continue;\n    }\n\n    switch (curch) {\n      case 10:\n        {\n          if (html) {\n            s += \"<br>\";\n            continue;\n          }\n          break;\n        }\n      case 13:\n        {\n          if (html)\n            continue;\n          break;\n        }\n      case 34:\n        {\n          s += \"&quot;\";\n          continue;\n        }\n      case 38:\n        {\n          s += \"&amp;\";\n          continue;\n        }\n      case 39:\n        {\n          s += \"&apos;\";\n          continue;\n        }\n      case 60:\n        {\n          s += \"&lt;\";\n          continue;\n        }\n      case 62:\n        {\n          s += \"&gt;\";\n          continue;\n        }\n    }\n\n    s += \"&#\" + curch + \";\";\n  }\n  return s;\n}\n\nfunction decodeEntities(str: string, html: boolean) {\n  if (html)\n    str = str.replace(/<br *\\/?>/g, \"\\n\");\n\n  str = str.replace(/&#(\\d+);/g, (_, dec) => String.fromCharCode(dec))\n    .replace(/&lt;/g, \"<\")\n    .replace(/&gt;/g, \">\")\n    .replace(/&quot;/g, '\"')\n    .replace(/&apos;/g, \"'\")\n    .replace(/&amp;/g, \"&\");\n\n  return str;\n}\n\nexport type StringEncodings = \"base64url\" | \"attribute\" | \"html\";\n\nexport function encodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return btoa(str).replaceAll(\"=\", \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\");\n  if (encoding === \"attribute\")\n    return encodeEntities(str, false);\n  if (encoding === \"html\")\n    return encodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\nexport function decodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return atob(str.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\"));\n  if (encoding === \"attribute\")\n    return decodeEntities(str, false);\n  if (encoding === \"html\")\n    return decodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\ntype JSONReplacerArgument = ((this: unknown, key: string, value: unknown) => unknown) | undefined;\n\nexport interface StringifyOptions {\n  replacer?: JSONReplacerArgument;\n  space?: string | number;\n  stable?: boolean;\n  ///Encode with types (preserve Money, Date, BigInt). Needs std.parseTyped\n  typed?: boolean;\n  ///What to target: string (like JSON.stringify), script (escapes '/') or attribute (escapes '/' and applies attribute encoding)\n  target?: \"string\" | \"script\" | \"attribute\";\n}\n\n/** Improved JSON encoder\n * @param arg - Object to encode\n * @param options - Encoding options\n*/\nexport function stringify(arg: unknown, options?: StringifyOptions) {\n  const usereplacer: JSONReplacerArgument = options?.stable || options?.typed ? (function (this: unknown, key: string, value: unknown) {\n    if (options.typed) {\n      const origvalue = (this as Record<string, unknown>)[key]; //We can't use 'value' as .toJSON() will already have been invoked\n      const type = stdTypeOf(origvalue);\n      switch (type) {\n        case \"function\":\n          throw new Error(`Cannot stringify property '${key}' of type \"${type}'`);\n        case \"Date\":\n          value = { \"$stdType\": \"Date\", date: (origvalue as Date).toISOString() };\n          break;\n        case \"Money\":\n        case \"bigint\":\n        case \"Instant\":\n        case \"PlainDate\":\n        case \"PlainTime\":\n        case \"PlainDateTime\":\n        case \"ZonedDateTime\":\n          value = { \"$stdType\": type, [type.toLowerCase()]: (origvalue as { toString: () => string }).toString() };\n          break;\n        case \"object\":\n          if (\"$stdType\" in (origvalue as { \"$stdType\": string }))\n            throw new Error(`Cannot encode objects with already embedded '$stdType's`);\n        //fallthrough\n      }\n    }\n    if (options.stable && value && typeof value === \"object\" && !Array.isArray(value))\n      value = Object.fromEntries(Object.entries(value).sort((lhs, rhs) => lhs < rhs ? -1 : lhs === rhs ? 0 : 1));\n    if (options.replacer)\n      value = options.replacer.call(this, key, value);\n    return value;\n  }) : options?.replacer ?? undefined;\n\n  let result = JSON.stringify(arg, usereplacer, options?.space);\n  if (options?.target && [\"script\", \"attribute\"].includes(options.target)) {\n    result = result.replaceAll(\"/\", \"\\\\/\");\n    if (options.target === \"attribute\")\n      result = encodeEntities(result, false);\n  }\n  return result;\n}\n\n/** Decode JSON with types (Generated using stringify with typed:true ) */\nexport function parseTyped(input: string) {\n  return JSON.parse(input, (key, value) => {\n    switch (value?.[\"$stdType\"]) {\n      case \"Money\":\n        return new Money(value.money);\n      case \"Date\":\n        return new Date(value.date);\n      case \"bigint\":\n      case \"BigInt\": //pre wh5.7 spelling\n        return BigInt(value.bigint as string);\n      case \"Instant\":\n      case \"PlainDate\":\n      case \"PlainTime\":\n      case \"PlainDateTime\":\n      case \"ZonedDateTime\":\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        if (!(globalThis as any).Temporal)\n          throw new Error(`Temporal is not available in this environment, cannot deserialize value of type Temporal.${value[\"$stdType\"]}. Load eg. @webhare/deps/temporal-polyfill to use Temporal types in browsers`);\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        return (globalThis as any).Temporal[value[\"$stdType\"]].from(value[value[\"$stdType\"].toLowerCase()]);\n      case undefined:\n        return value;\n      default:\n        throw new Error(`Unrecognized type '${value[\"$stdType\"]}'`);\n    }\n  });\n}\n\n/** Generate a slug from a (suggested) (file)name\n * @param text - Text to convert\n * @param options - Options for slugification\n * @param options.separator - Separator to use between words (defaults to '-')\n * @param options.keep - Set of characters to keep in addition to a-z0-9\n * @returns Slugified text or null if we couldn't generate anything reeadable\n */\nexport function slugify(text: string, { separator = \"-\", keep = \"\" }: {\n  separator?: string;\n  keep?: string;\n} = {}): string | null {\n  //This function mixes HS getSafeName with a few more modern approaches\n  const keepclass = `[^a-z0-9${escapeRegExp(keep)}]`;\n  text = text\n    .normalize('NFD')                   // split an accented letter in the base letter and the acent\n    // eslint-disable-next-line no-control-regex\n    .replaceAll(/[\\u0000-\\u001F]/g, '')\n    .replaceAll(/[\\u0300-\\u036f]/g, '')   // remove all previously split accents\n    .replaceAll(/ß/g, 'ss')               // german ss\n    .toLowerCase()\n    .replace(new RegExp(`^${keepclass}+`), \"\") //replace bad characters at the start\n    .replace(new RegExp(`${keepclass}+$`), \"\") //.. and end\n    .replaceAll(new RegExp(`${keepclass}+`, \"g\"), separator); // replace all non alphanumeric/space with a single dash\n\n  return text || null; //we return 'null' on purpose so callers realize we won't necessarily give them a string!\n}\n\n/** Check if an email address is valid in modern times (an emailcheck much closer to what a browser would do, with additional sanity checks. No attempt to allow all legacy styles supported by the RFCs but 99.9%+ sure to be an error if seen submitted in a form\n    @returns True if the email address appears to be a well-formed email address to a non-greybeard\n*/\nexport function isValidEmail(email: string): boolean {\n  if (email.length > 254) //TODO count bytes instead of characters\n    return false;\n\n  return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*(?:\\.[a-zA-Z0-9-]{2,})$/.test(email);\n}\n\n/** Uppercases a string using the C-locale (so only the ASCII characters a-z are uppercased)\n * @param str - String to uppercase\n * @returns Uppercased string\n */\nexport function toCLocaleUppercase(str: string) {\n  return str.replaceAll(/[a-z]+/g, part => part.toUpperCase());\n}\n\n/** Lowercases a string using the C-locale (so only the ASCII characters A-Z are lowercased)\n * @param str - String to lowercase\n * @returns Lowercased string\n */\nexport function toCLocaleLowercase(str: string) {\n  return str.replaceAll(/[A-Z]+/g, part => part.toLowerCase());\n}\n\n/** Calculate the levenshtein distance between two strings */\nexport function levenshteinDistance(a: string, b: string): number {\n  /* calculateLevenshteinDistance is adopted from https://github.com/gustf/js-levenshtein/blob/master/index.js, licensed MIT © Gustaf Andersson\n    Picked over fastest-levenshtein because a permanent 256KB memory area for a bit more speed doesn't seem worth it\n  */\n  function _min(d0: number, d1: number, d2: number, bx: number, ay: number) {\n    return d0 < d1 || d2 < d1\n      ? d0 > d2\n        ? d2 + 1\n        : d0 + 1\n      : bx === ay\n        ? d1\n        : d1 + 1;\n  }\n\n  if (a === b) {\n    return 0;\n  }\n\n  if (a.length > b.length) {\n    const tmp = a;\n    a = b;\n    b = tmp;\n  }\n\n  let la = a.length;\n  let lb = b.length;\n\n  while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {\n    la--;\n    lb--;\n  }\n\n  let offset = 0;\n\n  while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {\n    offset++;\n  }\n\n  la -= offset;\n  lb -= offset;\n\n  if (la === 0 || lb < 3) {\n    return lb;\n  }\n\n  let x = 0;\n  let y, d0, d1, d2, d3, dd = 0, dy, ay, bx0, bx1, bx2, bx3;\n\n  const vector: number[] = [];\n\n  for (y = 0; y < la; y++) {\n    vector.push(y + 1);\n    vector.push(a.charCodeAt(offset + y));\n  }\n\n  const len = vector.length - 1;\n\n  for (; x < lb - 3;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    bx1 = b.charCodeAt(offset + (d1 = x + 1));\n    bx2 = b.charCodeAt(offset + (d2 = x + 2));\n    bx3 = b.charCodeAt(offset + (d3 = x + 3));\n    dd = (x += 4);\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      ay = vector[y + 1];\n      d0 = _min(dy, d0, d1, bx0, ay);\n      d1 = _min(d0, d1, d2, bx1, ay);\n      d2 = _min(d1, d2, d3, bx2, ay);\n      dd = _min(d2, d3, dd, bx3, ay);\n      vector[y] = dd;\n      d3 = d2;\n      d2 = d1;\n      d1 = d0;\n      d0 = dy;\n    }\n  }\n\n  for (; x < lb;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    dd = ++x;\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]);\n      d0 = dy;\n    }\n  }\n\n  return dd;\n}\n\n/** Return the length of the string in bytes when UTF-8 encoded */\nexport function getUTF8Length(str: string) {\n  return new TextEncoder().encode(str).length;\n}\n\n/** Truncate the string so it's at most len UTF-8 bytes long */\nexport function limitUTF8Length(str: string, len: number) {\n  // TextEncoder.encodeInto writes into the given array until there's no more room to add more valid UTF-8 sequences from the\n  // source. We can use this property to limit the number of bytes by creating an array that has room for at most the given\n  // number of bytes.\n  const utf8array = new Uint8Array(len);\n  // This function returns the actual number of bytes written to the array\n  const { written } = new TextEncoder().encodeInto(str, utf8array);\n  // Decode only the actually written bytes\n  return new TextDecoder().decode(utf8array.subarray(0, written));\n}\n\n/** Update the search parameters in a URL\n * @param inUrl - URL to update\n * @param updates - Updates to apply, use 'null' to delete a variable\n * @returns Updated URL\n */\nexport function updateURL(inUrl: string | URL, updates: Record<string, string | null>): URL {\n  const u = new URL(inUrl);\n  for (const [k, v] of Object.entries(updates)) {\n    if (v === null) {\n      u.searchParams.delete(k);\n    } else {\n      u.searchParams.set(k, v);\n    }\n  }\n  return u;\n}\n","/** Test whether a string looks like a valid random id */\nexport function isLikeRandomId(input: string): boolean { //TODO add encoding parameter/bytes support ?\n  return Boolean(input.match(/^[A-Za-z0-9_-]{22}$/));\n}\n\n/** Test whether a string is a valid hex UUID\n * @param input - uuid in hex format to verify. you may need to lowercase the uuid first\n * @param format - optional, if set to \"v4\" it will only accept UUIDv4 format\n*/\nexport function isValidUUID(input: string, format?: \"v4\"): boolean {\n  //we'll require you to lowercase the uuid first to increase the chance that you'll actually be storing/matching it in lowercase too\n\n  if (format === \"v4\")\n    return Boolean(input.match(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/));\n  else if (format !== undefined)\n    throw new Error(`Unsupported format '${format}'`);\n  else\n    return Boolean(input.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/));\n}\n\n/** Generate a configurable random id (the default settings, base64url and 16 bytes, match HareScript's GenerateUFS128BitId)\n * @param encoding - Encoding to use, base64url, hex or uuidv4. Default is base64url\n * @param bytes - Number of bytes to generate. Default is 16\n * @returns An encoded ID. With the default settings it will be a url (and filename) safe string of 22 characters in length\n */\nexport function generateRandomId(encoding: \"base64url\" | \"hex\" | \"uuidv4\" = \"base64url\", bytes: number = 16): string {\n  if (encoding === \"uuidv4\") {\n    if (bytes !== 16)\n      throw new Error(\"UUIDv4 encoding only supports 16 bytes\");\n\n    if (crypto.randomUUID) //NOTE: not available in non-secure contexts so the fallback can never go away\n      return crypto.randomUUID();\n  }\n\n  const u8array = new Uint8Array(bytes);\n  crypto.getRandomValues(u8array);\n\n  if (encoding === \"uuidv4\") {\n    u8array[6] = (u8array[6] & 0x0f) | 0x40;\n    u8array[8] = (u8array[8] & 0x3f) | 0x80;\n    return [...u8array.values()].map(x => x.toString(16).padStart(2, \"0\")).join(\"\").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, \"$1-$2-$3-$4-$5\");\n  }\n\n  if (encoding === \"base64url\")\n    return btoa(String.fromCharCode.apply(null, u8array as unknown as number[])).replaceAll(\"=\", \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\");\n\n  if (encoding === \"hex\")\n    return [...u8array.values()].map(x => x.toString(16).padStart(2, \"0\")).join(\"\");\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any -- Cannot specify this without using any */\n\nexport interface EmplaceHandler<ValueType> {\n  insert?: () => ValueType;\n  update?: (current: ValueType) => ValueType;\n}\n\nfunction binarySearchImpl<A, K>(compareFn: (element: A, key: K) => number, contents: A[], searchfor: K, upper_bound: boolean): { present: boolean; index: number } {\n  let first = 0;\n  let len = contents.length;\n  let present = false;\n\n  const cmpbound = upper_bound ? 1 : 0;\n  let unsorted_cmp = 0; // if this is non-0 and cmp is this value, we have an unsorted list\n  while (len > 0) {\n    const half = Math.floor(len / 2);\n    const middle = first + half;\n    const cmp = compareFn(contents[middle], searchfor);\n    if (cmp === 0) {\n      present = true;\n      unsorted_cmp = upper_bound ? -1 : 1;\n    } else if (cmp === unsorted_cmp)\n      throw new Error(`The provided array was not properly sorted!`);\n\n    if (cmp < cmpbound) {\n      first = middle + 1;\n      len -= half;\n      --len;\n    } else {\n      len = half;\n    }\n  }\n  return { present, index: first };\n}\n\n//emplace is based on https://github.com/tc39/proposal-upsert (a Map.prototype.emplace)\n/** Place a value into a Map\n * @param map - The map to place the value into\n * @param key - The key to add/replace\n * @param handler - Callbacks for inserting or updating the value\n * @returns The value that was placed into the map.\n * @throws If the key is not found and no insert handler is provided\n */\nexport function emplace<T extends Map<any, any> | WeakMap<any, any>>(\n  map: T,\n  key: T extends Map<infer K, any> ? K : T extends WeakMap<infer K, any> ? K : never,\n  handler?: T extends Map<any, infer V> ? EmplaceHandler<V> : T extends WeakMap<any, infer V> ? EmplaceHandler<V> : never):\n  T extends Map<any, infer V> ? V : T extends WeakMap<any, infer V> ? V : never {\n  let current = map.get(key);\n  if (current !== undefined) {\n    if (handler?.update) {\n      current = handler.update(current);\n      map.set(key, current);\n    }\n    return current;\n  }\n\n  if (!handler?.insert)\n    throw new Error(\"Key not found and no insert handler provided\");\n\n  const setvalue = handler.insert();\n  map.set(key, setvalue);\n  return setvalue;\n}\n\n// the `| keyof X` is needed to be able to use a `keyof X` type as key parameter in DistributedPick or DistributedOmit in generics\nexport type DistributedKeys<X extends object> = (X extends object ? keyof X : never) | keyof X;\n\n/** Applies Pick to all types in a union. Allows all keys that are present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = pick(a, [\"t\", \"a\", \"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @returns Type with only the specified keys (distributed over the union if present)\n*/\nexport type DistributedPick<X extends object, Y extends DistributedKeys<X>> = X extends object ? Pick<X, keyof X & Y> : never;\n\n/** Applies Omit to all types in a union. Allows all keys that are not present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = omit(a, [\"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @returns Type with only the specified keys left out (distributed over the union if present)\n*/\nexport type DistributedOmit<X extends object, Y extends DistributedKeys<X>> = X extends object ? Omit<X, keyof X & Y> : never;\n\n/** Returns an object with a selection of properties\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @param obj - Object to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting object\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedPick<T, K>;\n\n/** Returns an array with a selection of properties\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to return\n    @param arr - Array to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting array\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedPick<T, K>>;\n\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedPick<T, K> | Array<DistributedPick<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => pick(elt, keys));\n  const ret = {} as T;\n  keys.forEach((key: K) => {\n    if (key in value)\n      ret[key] = value[key];\n  });\n  return ret as object as DistributedPick<T, K>;\n}\n\n/** Returns an object with a selection of properties left out\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @param obj - Object to leave properties out of\n    @param keys - Names of the properties to remove\n    @returns Resulting object\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedOmit<T, K>;\n\n/** Returns an array with a selection of properties left out\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to leave out\n    @param arr - Array to leave properties out of\n    @param keys - Names of the properties to leave out\n    @returns Resulting array\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedOmit<T, K>>;\n\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedOmit<T, K> | Array<DistributedOmit<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => omit(elt, keys));\n  const ret = {} as T;\n  for (const [key, val] of Object.entries(value)) {\n    if (!keys.includes(key as K))\n      ret[key as K] = val;\n  }\n  return ret as object as DistributedOmit<T, K>;\n}\n\n/** Shuffle an array in-place\n * @param array - Array to shuffle\n * @returns The shuffled array\n*/\nexport function shuffle<T>(array: T[]): T[] {\n  for (let i = array.length - 1; i > 0; i--) {\n    const j = Math.floor(Math.random() * (i + 1));\n    [array[i], array[j]] = [array[j], array[i]];\n  }\n  return array;\n}\n\n/** Returns (and TypeScript-asserts) that the specified function is truthy. Handy for adjusting the type of an array when\n * filtering out falsy values\n * @example\n * const myarray: Array&lt;number | null&gt; = [0, null];\n * const filtered: number[] = myarray.filter(isTruthy);\n **/\nexport function isTruthy<T>(a: T): a is (T & {}) {\n  return Boolean(a);\n}\n\n/** Append to array, without overflowing the stack (eg V8 overflows at more than 32K entries)\n * @param array - Array to append to\n * @param values - Values to append\n*/\nexport function appendToArray<T>(array: T[], values: ReadonlyArray<NoInfer<T>>): void {\n  if (values.length < 1000)\n    array.push(...values); //push should be safe enough\n  else for (const value of values) //performance wise this appears just as fast as tricks with pushing blocks of slices\n    array.push(value);\n\n  //not returning the original array to make it clear we're not creating a new one\n}\n\ntype TypedEntriesInternal<T extends object, K extends keyof T> = K extends keyof T ? [K, T[K]] : never;\n\n/** Returns a union of [ key, value ] types for an object */\nexport type TypedEntries<T extends object> = T extends object ? TypedEntriesInternal<T, keyof T & string> : never;\n\n/** Returns an array of key/values of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.entries returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedEntries<T extends object>(obj: T): Array<TypedEntries<T>> {\n  return Object.entries(obj) as Array<TypedEntries<T>>;\n}\n\n/** Returns an array of keys of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.keys returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedKeys<T extends object>(obj: T): Array<keyof T & string> {\n  return Object.keys(obj) as Array<keyof T & string>;\n}\n\n/** Given a union of [key, value] types, returns the object constructed from those pairs. Exists because\n *  Object.fromEntries does not take the type of the keys and values into account.\n * @typeParam T - Union of [key, value] pairs\n */\nexport type TypedFromEntries<T extends [string, unknown]> = { [C in T as C[0]]: C[1] };\n\n/** Returns an object from an iterable of [key, value] pairs, with exact types. Exists because Object.fromEntries\n * doesn't take the type of the keys and values into account.\n * @param entries - Iterable of [key, value] pairs\n * @returns An object with the same keys and values as the input\n */\nexport function typedFromEntries<T extends [string, unknown]>(entries: Iterable<T>): TypedFromEntries<T> {\n  return Object.fromEntries(entries) as TypedFromEntries<T>;\n}\n\n\nexport class SortedMultiSet<V> {\n  private contents: V[] = [];\n  private compareFn;\n\n  constructor(compareFn: (lhs: V, rhs: V) => number, contents?: V[]) {\n    this.compareFn = compareFn;\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): V | undefined {\n    return this.contents.at(index);\n  }\n\n  add(value: V): number {\n    const pos = this.upperBound(value);\n    this.contents.splice(pos, 0, value);\n    return pos;\n  }\n\n  addMultiple(values: V[]): void {\n    for (const value of values) {\n      this.add(value);\n    }\n  }\n\n  delete(key: V): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<V>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<V>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<V>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): V[] {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<V, void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<V>): V[] {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<V>): Iterable<V> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n\nexport class SortedMultiMap<K, V> {\n  private compareFn;\n  private contents: Array<[K, V]> = [];\n\n  constructor(compareFn: (lhs: K, rhs: K) => number, contents?: Array<[K, V]>) {\n    this.compareFn = (element: [K, V], key: K) => compareFn(element[0], key);\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): [K, V] | undefined {\n    return this.contents.at(index);\n  }\n\n  add(key: K, value: V): number {\n    const pos = this.upperBound(key);\n    this.contents.splice(pos, 0, [key, value]);\n    return pos;\n  }\n\n  addMultiple(values: Array<[K, V]>) {\n    for (const [key, value] of values) {\n      this.add(key, value);\n    }\n  }\n\n  delete(key: K): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<K>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<K>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<K>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): Array<[K, V]> {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<[K, V], void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<K>): Array<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<K>): Iterable<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n","import { isPromise } from \"./quacks.ts\";\n\nfunction propagateAbort(signal: AbortSignal, cb: ((reason: typeof signal[\"reason\"]) => void) | AbortController) {\n  if (signal.aborted) {\n    if (\"abort\" in cb)\n      cb.abort(signal.reason);\n    else\n      cb(signal.reason);\n  } else signal.addEventListener(\"abort\", () => {\n    if (\"abort\" in cb)\n      cb.abort(signal.reason);\n    else\n      cb(signal.reason);\n  });\n}\n\nexport type AbortSignals = Iterable<AbortSignal | Promise<AbortSignal> | undefined | null> | AbortSignal | Promise<AbortSignal> | null | undefined;\n\n/** Calls the callback when any of the passed abort signals is (or already was) aborted. Use\n * this instead of addEventListener when it is possible that any of the abortsignals was already aborted.\n*/\nexport function whenAborted(signals: AbortSignals, cb: ((reason: AbortSignal[\"reason\"]) => void) | AbortController): void {\n  propagateAbort(combineAbortSignals(signals), cb);\n}\n\n/** Combines abort signals (or promises for abort signals) into one abort signal. More generic version of AbortSignal.any() */\nexport function combineAbortSignals(signals: AbortSignals): AbortSignal {\n  if (!signals || !(Symbol.iterator in signals))\n    signals = [signals];\n  const abortController = new AbortController;\n  for (const signal of signals) {\n    if (signal) {\n      if (\"then\" in signal) {\n        // Convert promise errors to abort\n        void signal.then(s => propagateAbort(s, abortController), e => abortController.abort(e));\n      } else\n        propagateAbort(signal, abortController);\n    }\n  }\n  return abortController.signal;\n}\n\n/** Returns a signal that can be used like `using signal = getScopeSignal()` and will be aborted when going out of scope */\nexport function getScopeSignal(): AbortSignal & { [Symbol.dispose](): void } {\n  const ctrl = new AbortController();\n  const signal = ctrl.signal as AbortSignal & { [Symbol.dispose](): void };\n  signal[Symbol.dispose] = () => ctrl.abort();\n  return signal;\n}\n\ntype PipeReturn<PFinal, PAll extends readonly unknown[]> = Extract<PAll[number], Promise<unknown>> extends never ? PFinal : Promise<Awaited<PFinal>>;\n\n/** @hidden */\nexport function pipe<P1>(f1: P1 | ((a: void) => P1)): PipeReturn<P1, [P1]>;\nexport function pipe<P1, P2>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2): PipeReturn<P2, [P1, P2]>;\nexport function pipe<P1, P2, P3>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3): PipeReturn<P3, [P1, P2, P3]>;\nexport function pipe<P1, P2, P3, P4>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4): PipeReturn<P4, [P1, P2, P3, P4]>;\nexport function pipe<P1, P2, P3, P4, P5>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5): PipeReturn<P5, [P1, P2, P3, P4, P5]>;\nexport function pipe<P1, P2, P3, P4, P5, P6>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6): PipeReturn<P6, [P1, P2, P3, P4, P5, P6]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7): PipeReturn<P7, [P1, P2, P3, P4, P5, P6, P7]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8): PipeReturn<P8, [P1, P2, P3, P4, P5, P6, P7, P8]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9): PipeReturn<P9, [P1, P2, P3, P4, P5, P6, P7, P8, P9]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10): PipeReturn<P10, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11): PipeReturn<P11, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12): PipeReturn<P12, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13): PipeReturn<P13, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13, f14: (n: Awaited<P13>) => P14): PipeReturn<P14, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13, f14: (n: Awaited<P13>) => P14, f15: (o: Awaited<P14>) => P15): PipeReturn<P15, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15]>;\nexport function pipe<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16>(f1: P1 | ((a: void) => P1), f2: (b: Awaited<P1>) => P2, f3: (c: Awaited<P2>) => P3, f4: (d: Awaited<P3>) => P4, f5: (e: Awaited<P4>) => P5, f6: (f: Awaited<P5>) => P6, f7: (g: Awaited<P6>) => P7, f8: (h: Awaited<P7>) => P8, f9: (i: Awaited<P8>) => P9, f10: (j: Awaited<P9>) => P10, f11: (k: Awaited<P10>) => P11, f12: (l: Awaited<P11>) => P12, f13: (m: Awaited<P12>) => P13, f14: (n: Awaited<P13>) => P14, f15: (o: Awaited<P14>) => P15, f16: (p: Awaited<P15>) => P16): PipeReturn<P16, [P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16]>;\n\n/** Chain together (possibly async) function calls, each receiving the resolved (awaited) output of the previous one. The first parameter may be a value, all further parameters must be functions.\n *  Type safe up to 16 parameters\n */\nexport function pipe(fn0: unknown, ...fns: Array<(x: unknown) => unknown>): unknown;\n\nexport function pipe(fn0: unknown, ...fns: Array<(x: unknown) => unknown>): unknown {\n  let result = typeof fn0 === \"function\" ? fn0() : fn0;\n\n  if (isPromise(result)) { //switch to full async handling immediately\n    return (async () => {\n      let asyncResult = await result;\n      for (const fn of fns)\n        asyncResult = await fn(asyncResult);\n      return asyncResult;\n    })();\n  }\n\n  for (let idx = 0; idx < fns.length; ++idx) {\n    const next = fns[idx](result);\n    if (isPromise(next)) { //switch to async as soon as we hit a promise\n      return (async () => {\n        let asyncResult = await next;\n        for (let asyncIdx = idx + 1; asyncIdx < fns.length; ++asyncIdx)\n          asyncResult = await fns[asyncIdx](asyncResult);\n        return asyncResult;\n      })();\n    }\n    result = next;\n  }\n\n  return result;\n}\n","const unlock = Symbol(\"unlock\");\n\n/** A mutex which is only visible in the current JavaScript VM\n\n    @example\n```ts\nconst mutex = new LocalMutex;\n\nusing lock = await mutex.lock();\nlock.release();\n\n// If you'll be relying on automatic release\nusing lock = await mutex.lock();\nvoid(lock);\n```\n\n*/\nexport class LocalMutex {\n  private locked = false;\n  private unlockList = new Array<() => void>;\n\n  /** Lock this mutex\n   * @returns Lock object. Use with `using` to ensure automatic unlock\n   */\n  async lock() {\n    if (this.locked) {\n      const defer = Promise.withResolvers<void>();\n      this.unlockList.push(() => defer.resolve());\n      await defer.promise;\n    } else {\n      this.locked = true;\n    }\n    return new LocalLock(this);\n  }\n\n  [unlock](): void {\n    if (this.unlockList.length > 0)\n      (this.unlockList.shift()!)(); //we're fair... unlock longest waiter\n    else\n      this.locked = false;\n  }\n}\n\n/** Instance of a LocalMutex lock */\nclass LocalLock implements Disposable {\n  private mutex: LocalMutex | null;\n\n  constructor(mutex: LocalMutex) {\n    this.mutex = mutex;\n  }\n  /** Explicitly release the lock\n   * @throws Error if the lock is already released\n  */\n  release() {\n    if (!this.mutex)\n      throw new Error(\"Lock already released\");\n\n    this.mutex[unlock]();\n    this.mutex = null;\n  }\n  [Symbol.dispose]() {\n    this.mutex?.[unlock]();\n  }\n}\n\nexport type { LocalLock };\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/std\" {\n}\n\n// Adding APIs may also require an update to https://www.webhare.dev/manuals/typescript/harescript-conversion-guide/\nexport { attempt, sleep, createDeferred, wrapInTimeout, serialize, wrapSerialized, type DeferredPromise, type SerializeOptions } from \"./promises.ts\";\n\nexport { compare, compareProperties, enumReverseMap, nameToCamelCase, nameToSnakeCase, toSnakeCase, toCamelCase, maybePromiseAll, mapMaybePromise } from \"./types.ts\";\nexport type { ToSnakeCase, ToCamelCase, ComparableType, MaybePromise } from \"./types.ts\";\n\nexport { encodeString, decodeString, escapeRegExp, regExpFromWildcards, stringify, parseTyped, slugify, isValidEmail, type StringEncodings, toCLocaleLowercase, toCLocaleUppercase, levenshteinDistance, getUTF8Length, limitUTF8Length, updateURL } from \"./strings.ts\";\nexport { generateRandomId, isLikeRandomId, isValidUUID } from \"./platformbased.ts\";\n\nexport { shuffle, emplace, pick, omit, isTruthy, appendToArray, typedEntries, typedFromEntries, typedKeys, SortedMultiSet, SortedMultiMap, type TypedEntries, type TypedFromEntries } from \"./collections.ts\";\nexport type { EmplaceHandler, DistributedKeys, DistributedOmit, DistributedPick } from \"./collections.ts\";\n\nexport { Money, type MoneyRoundingMode, type MoneyFormatOptions } from \"./money.ts\";\n\nexport { addDuration, parseDuration, subtractDuration, convertWaitPeriodToDate, isValidDate, isValidTime, convertFlexibleInstantToDate, formatDateTime } from \"./datetime.ts\";\nexport type { Duration, WaitPeriod, FlexibleInstant } from \"./datetime.ts\";\n\nexport { stdTypeOf, isDate, isBlob, isFile, isError, isPromise, isMoney, isTemporalInstant, isTemporalPlainDate, isTemporalPlainDateTime, isTemporalZonedDateTime, isTemporalPlainTime } from \"./quacks.ts\";\n\nexport { combineAbortSignals, getScopeSignal, whenAborted, pipe } from \"./utils.ts\";\n\nexport { LocalMutex, type LocalLock } from \"./localmutex.ts\";\n\n/** Throw an error with the specified message. This function allows you to throw inside expressions\n * @param err - The error message\n * @returns This function never returns\n * @throws An error with the specified message\n */\nexport function throwError(err: Error | string): never {\n  //TODO remove ourselves from the stack ?\n  throw err instanceof Error ? err : new Error(err);\n}\n","type FormValueList = Array<{ name: string; value: string }>;\n\n/** A navigation instruction encapsulates the next step that a client has to take in eg. a login, payment or wizard flow.\n * Use navigateTo to execute a navigation in a browser\n*/\n\nexport type NavigateInstruction =\n  {\n    type: \"redirect\";\n    url: string;\n  } | {\n    type: \"form\";\n    form: {\n      action: string;\n      vars: FormValueList;\n      method?: \"POST\";\n    };\n  } | {\n    type: \"reload\";\n  } | {\n    type: \"postmessage\";\n    message: unknown;\n    target?: \"parent\" | \"opener\";\n  } | {\n    type: \"close\";\n  };\n\nfunction submitForm(action: string, values: FormValueList, method = \"POST\") {\n  const form = document.createElement(\"form\");\n  form.method = method;\n  form.action = action;\n  form.append(...values.map(item => {\n    const input = document.createElement(\"input\");\n    input.type = \"hidden\";\n    input.name = item.name;\n    input.value = item.value;\n    return input;\n  }));\n  document.body.appendChild(form);\n  form.submit();\n}\n\n/** Navigate to a specific URL (may be hookable by other scripts)\n* @param navigation - Target URL or NavigateInstruction\n*/\nexport function navigateTo(navigation: string | NavigateInstruction) {\n  if (typeof window === \"undefined\")\n    throw new Error(`navigateTo() is not available in this environment`);\n\n  if (typeof navigation === \"string\")\n    navigation = { type: \"redirect\", url: navigation };\n\n  switch (navigation.type) {\n    case \"redirect\":\n      {\n        location.href = navigation.url;\n      } break;\n\n    case \"form\":\n      {\n        submitForm(navigation.form.action, navigation.form.vars, navigation.form.method);\n      } break;\n\n    case \"reload\":\n      {\n        window.location.reload();\n      } break;\n\n    case \"postmessage\":\n      {\n        if (!navigation.target || navigation.target === \"parent\")\n          window.parent.postMessage(navigation.message, \"*\");\n        else if (navigation.target === \"opener\") {\n          window.opener.postMessage(navigation.message, \"*\");\n          window.close();\n        } else\n          throw Error(\"Unknown postmessage target '\" + navigation.target + \"' received\");\n      } break;\n\n    case \"close\":\n      {\n        window.close();\n      } break;\n\n    default:\n      throw new Error(`Unknown navigation type '${(navigation as { type: string }).type}'`);\n  }\n}\n","import { debugFlags, registerDebugConfigChangedCallback } from \"./envbackend\";\nimport { generateRandomId } from \"@webhare/std\";\n\nlet hookedfetch = false;\n\nfunction sanitizeBody(body: unknown) {\n  if (body instanceof ArrayBuffer) {\n    const view = new Uint8Array(body.slice(0, 5000)); //show the bytes but filter unprintable as '.'\n    return Array.from(view).map(v => v >= 32 && v < 127 ? String.fromCharCode(v) : \".\").join(\"\");\n  }\n  if (body instanceof URLSearchParams)\n    return body.toString();\n  if (typeof body !== 'string') {\n    return `[${typeof body}]`;\n  }\n  body = body.substring(0, 5000).replaceAll(\"\\r\", \" \").replaceAll(\"\\n\", \" \");\n  return body;\n}\n\nfunction getResponseSummary(response: Pick<Response, \"headers\">) {\n  const toks = [];\n  if (response.headers.get(\"Content-Type\"))\n    toks.push(response.headers.get(\"Content-Type\"));\n  if (response.headers.get(\"Content-Length\"))\n    toks.push(response.headers.get(\"Content-Length\") + \" bytes\");\n  if (response.headers.get(\"Transfer-Encoding\"))\n    toks.push(response.headers.get(\"Transfer-Encoding\"));\n  if (response.headers.get(\"Content-Encoding\"))\n    toks.push(response.headers.get(\"Content-Encoding\"));\n\n  return toks.length ? `(${toks.join(\", \")})` : \"\";\n}\n\nfunction headersToString(headers: Headers) {\n  return JSON.stringify(Object.fromEntries(headers.entries()));\n}\n\nexport function extractRequestInfo(input: RequestInfo | URL, init?: RequestInit) {\n  const method = (init?.method || (input as Request)?.method || \"GET\");\n  const url = input instanceof URL ? input.toString() : typeof input === \"string\" ? input : input.url;\n  const headers = new Headers(typeof input === \"object\" && !(input instanceof URL) ? input.headers : init?.headers);\n  const body = typeof input === \"object\" && !(input instanceof URL) ? input.body : init?.body;\n  return { method, url, headers, body };\n}\n\nexport async function extractRequestBody(body: BodyInit): Promise<XMLHttpRequestBodyInit> {\n  if (!(body instanceof ReadableStream))\n    return body;\n\n  //convert the ReadableStream to ArrayBuffer so we can print AND send it (TODO ideally 'tee' the stream and just grab the first 5K bytes)\n  const reader = body.getReader();\n  const chunks = [];\n  for (; ;) {\n    const { done, value } = await reader.read();\n    if (done)\n      break;\n    chunks.push(value);\n  }\n  return await new Blob(chunks).arrayBuffer();\n}\n\nexport function logWrqRequest(method: string, url: string, headers: Headers, body: XMLHttpRequestBodyInit | undefined | null) {\n  const debugrequestid = generateRandomId();\n\n  console.log(`[wrq] ${debugrequestid} ${method.padEnd(7)} ${url}`);\n  console.log(`[wrq] ${debugrequestid} headers ${headersToString(headers)}`);\n  if (body) {\n    console.log(`[wrq] ${debugrequestid} body    ${sanitizeBody(body)}`);\n  }\n\n  return debugrequestid;\n}\n\nexport async function logWrqResponse(debugrequestid: string, fetchresult: Pick<Response, \"ok\" | \"status\" | \"statusText\" | \"headers\" | \"json\" | \"text\" | \"arrayBuffer\" | \"clone\">) {\n  console.log(`[wrq] ${debugrequestid} result  ${fetchresult.status} ${fetchresult.statusText} ${getResponseSummary(fetchresult)}`);\n  console.log(`[wrq] ${debugrequestid} headers ${headersToString(fetchresult.headers)}`);\n\n  const ct = fetchresult.headers.get(\"Content-Type\");\n  if (ct && [\"text/html\", \"text/plain\", \"application/json\"].includes(ct?.split(';')[0])) {\n    const responsebody = await fetchresult.clone().text();\n    console.log(`[wrq] ${debugrequestid} body    ${sanitizeBody(responsebody)}`);\n  }\n}\n\nasync function debuggableFetch(originalfetch: typeof fetch, input: RequestInfo | URL, init?: RequestInit) {\n  if (!debugFlags.wrq)\n    return originalfetch(input, init);\n\n  let { method, url, headers, body } = extractRequestInfo(input, init);\n  if (body) {\n    body = await extractRequestBody(body);\n    init = { ...init, body };\n  }\n\n  const debugrequestid = logWrqRequest(method, url, headers, body);\n\n  const fetchresult = await originalfetch(input, init); //TODO log responses as well (if safe/applicable, eg not binary or Very Long... and we probably should wait for the first json()/text()/body() call? but at least log the status and time!)\n  await logWrqResponse(debugrequestid, fetchresult);\n\n  return fetchresult;\n}\n\nexport function hookFetch() {\n  if (hookedfetch)\n    return;\n\n  globalThis.fetch = debuggableFetch.bind(null, globalThis.fetch);\n  hookedfetch = true;\n}\n\nexport function enableFetchDebugging() {\n  // Hook global fetch if requested\n  if (globalThis[\"fetch\"]) {\n    if (debugFlags.wrq)\n      hookFetch();\n\n    registerDebugConfigChangedCallback(() => {\n      if (debugFlags.wrq)\n        hookFetch();\n    });\n  }\n}\n","/* Manages the $wh global, an API for just-in-time debugging */\nimport type { DebugRegistry } from \"@webhare/env\";\nimport { debugFlags } from \"./envbackend\";\n\nlet debugRegFinalizer: FinalizationRegistry<{ type: keyof DebugRegistry; key: string }> | undefined;\n\nexport type WHGlobal = DebugRegistry & {\n  debugFlags: typeof debugFlags;\n  /** Global counter to avoid HMRs from duplicating IDs */\n  nextId: number;\n};\n\ndeclare global {\n  var $wh: WHGlobal;\n}\n\nglobalThis.$wh = {\n  debugFlags,\n  nextId: 1\n} satisfies WHGlobal;\n\nexport function addToDebugRegistry<T extends keyof DebugRegistry>(type: T, key: string, value: NonNullable<ReturnType<NonNullable<DebugRegistry[T]>[string][\"deref\"]>>) {\n  const debugRegistry = globalThis.$wh as unknown as DebugRegistry;\n  //@ts-ignore prevents '>   Type '{}' is not assignable to type 'never'. in jssdk builds, probably because noone yet extends DebugRegistry there\n  debugRegistry[type] ||= {};\n  debugRegFinalizer ||= new FinalizationRegistry(({ type: t, key: k }) => {\n    delete debugRegistry![t]?.[k];\n  });\n\n  if (debugRegistry[type][key])\n    console.error(`Debug registry key ${key} already exists, overwriting it`);\n\n  (debugRegistry[type] as Record<string, unknown>)[key] = new WeakRef(value);\n  debugRegFinalizer.register(value, { type, key });\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/env\" {\n  interface DebugRegistry {\n  }\n}\n\nimport { debugFlags, dtapStage, isLive, backendBase, getAssetBase, setAssetBase, getModulePublicAssetBase } from \"./envbackend\";\nimport type { DTAPStage } from \"./concepts\";\n\nexport { type NavigateInstruction, navigateTo } from \"./navigation\";\nexport { enableFetchDebugging } from \"./fetchdebug\";\nexport { addToDebugRegistry } from \"./whglobal\";\nexport { updateDebugConfig } from \"./envbackend\";\nexport { type DTAPStage, dtapStage, debugFlags, isLive, backendBase, getAssetBase, setAssetBase, getModulePublicAssetBase };\n\n//user locale *which Tollium and sites should start to use to define localization, and perhaps gettid too?)\nexport type UserLocale = {\n  /** The language code, eg 'en' including optional country, eg en-US */\n  lang: string;\n  //TODO regional settings\n};\n\n//export deprecated variants\nexport { dtapstage, islive } from \"./envbackend\";\n\n/** @deprecated For WH5.4 and up use 'debugFlags' */\nexport const flags = debugFlags;\n","import type { GetTidHooks } from \"./types.js\";\n\nlet hookFactory: (() => GetTidHooks) | undefined;\nlet gotHooks = false;\n\nexport function setGetTidHooksFactory(newHookFactory: () => GetTidHooks) {\n  if (gotHooks)\n    throw new Error(`The call to setGetTidHooksFactory was too late - hooks have already been retrieved once`);\n  hookFactory = newHookFactory;\n}\n\nexport function getGetTidHooks() {\n  gotHooks = true;\n  return hookFactory?.();\n}\n","import { decodeString, encodeString } from '@webhare/std';\nimport type { CompiledLanguageFile, GetTidHooks, LanguagePart, LanguageText, RecursiveLanguageTexts, TidAllowedHTMLTags, TidParam } from './types';\nimport { getGetTidHooks } from './hooks';\nimport { debugFlags, dtapStage } from '@webhare/env';\nimport { getLang } from '@webhare/dompack/src/tree';\n\n\n\nlet hooks: GetTidHooks | undefined;\nlet browserSetLanguage = getLang().language;\nconst defaultLanguage = \"en\";\n\nfunction ensureHooks(): GetTidHooks {\n  return hooks ??= getGetTidHooks?.() ?? {\n    loader: null,\n    currentLanguage: (lang) => {\n      if (lang)\n        browserSetLanguage = lang;\n      return browserSetLanguage;\n    }\n  };\n}\n\nexport function getTidLanguage(): string {\n  return ensureHooks().currentLanguage() || defaultLanguage;\n}\n\nexport function setTidLanguage(newLanguage: string): void {\n  ensureHooks().currentLanguage(newLanguage.toLowerCase());\n}\n\nconst langFileCache: Record<string, CompiledLanguageFile> = {};\n\nfunction getLanguageFile(moduleName: string, langCode: string): CompiledLanguageFile | undefined {\n  const langkey = `${moduleName}:${langCode}`;\n  let compiled = langFileCache[langkey];\n  if (!compiled || !compiled.resource) {\n    const { loader, addResourceChangeListener } = ensureHooks();\n    if (loader) {\n      try {\n        const loaded = compiled = loader(moduleName, langCode, compiled?.registered ?? new Map);\n        // Reload the language file on the next lookup when it has been modified\n        addResourceChangeListener?.(module, loaded.resource, () => {\n          loaded.resource = \"\";\n          loaded.texts.clear();\n        });\n      } catch (e) {\n        // loading failed, erase the loaded texts (keep the registered texts, though)\n        if (dtapStage !== \"production\" || debugFlags.gtd) {\n          console.error(e);\n        }\n        const texts = compiled?.registered ?? new Map;\n        compiled = { resource: \"\", fallbackLanguage: \"\", langCode, texts, registered: texts };\n      }\n      langFileCache[langkey] = compiled;\n    }\n  }\n  if (!compiled && (dtapStage !== \"production\" || debugFlags.gtd)) {\n    console.warn(`No language texts found for module '${moduleName}' and language '${langCode}'`);\n  }\n  return compiled;\n}\n\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- needed for generics\nexport type GetTidRenderFunc<Result extends object = object> = ((tag: TidAllowedHTMLTags, props: { children?: any[]; href?: string }, ...childNodes: any[]) => Result);\nexport type GetTidOptions = { langCode?: string; render?: GetTidRenderFunc | \"fragment\" };\n\ntype GetTidArgumentTypes = [GetTidOptions?] | [TidParam[], GetTidOptions?] | [TidParam?, TidParam?, TidParam?, TidParam?];\n\nfunction toHTMLNode(tag: string, props: { href?: string; children?: Array<string | Node> }): Node {\n  const node = document.createElement(tag);\n  if (props.href)\n    node.setAttribute(\"href\", props.href);\n  if (props.children)\n    node.append(...props.children);\n  return node;\n}\n\nfunction wrapInFragment(children: Array<string | Node>): DocumentFragment {\n  const fragment = document.createDocumentFragment();\n  fragment.append(...children);\n  return fragment;\n}\n\n\nfunction getTidInternal(tid: string, params: TidParam[], options?: GetTidOptions): string | Array<string | object> | DocumentFragment {\n  if (tid === \"\") {\n    return \"\";\n  }\n\n  if (tid.startsWith(\":\")) {\n    return tid.substring(1);\n  } else if (tid.startsWith(\"<>\")) {\n    return decodeString(tid.substring(2), \"html\");\n  }\n\n  const langCode = options?.langCode?.toLowerCase() || getTidLanguage();\n  if (options?.render) {\n    if (options.render === \"fragment\") {\n      const nodes = calcTIDForLanguage(langCode, tid, params, true, toHTMLNode) as Array<string | Node>;\n      return wrapInFragment(nodes);\n    }\n    return calcTIDForLanguage(langCode, tid, params, true, options.render);\n  } else\n    return calcTIDForLanguage(langCode, tid, params, false, null).join(\"\");\n}\n\nexport function getTid(tid: string, options?: GetTidOptions & { render?: undefined }): string;\nexport function getTid<VNode extends object>(tid: string, options?: GetTidOptions & { render?: GetTidRenderFunc<VNode> }): string | Array<string | VNode>;\nexport function getTid(tid: string, options?: GetTidOptions & { render?: \"fragment\" }): DocumentFragment;\nexport function getTid(tid: string, param: TidParam[], options?: GetTidOptions & { render?: undefined }): string;\nexport function getTid<VNode extends object>(tid: string, param: TidParam[], options?: GetTidOptions & { render?: GetTidRenderFunc<VNode> }): string | Array<string | VNode>;\nexport function getTid(tid: string, param: TidParam[], options?: GetTidOptions & { render?: \"fragment\" }): DocumentFragment;\nexport function getTid(tid: string, p1?: TidParam, p2?: TidParam, p3?: TidParam, p4?: TidParam): string;\n\nexport function getTid(tid: string, ...p: GetTidArgumentTypes): string | Array<string | object> | DocumentFragment {\n  if (Array.isArray(p[0])) // case: param: TidParam[], options?: GetTidOptions)\n    return getTidInternal(tid, p[0], p[1] as GetTidOptions);\n  if (p[0] && typeof p[0] === \"object\") // case: options: GetTidOptions\n    return getTidInternal(tid, [], p[0]);\n  return getTidInternal(tid, p as Array<TidParam | undefined>, {});\n}\n\nexport function getTidForLanguage(langCode: string, tid: string, p1: TidParam = null, p2: TidParam = null, p3: TidParam = null, p4: TidParam = null): string {\n  return getTid(tid, [p1, p2, p3, p4], { langCode });\n}\n\nexport function getHTMLTid(tid: string, ...params: TidParam[]): string {\n  return getHTMLTidForLanguage(getTidLanguage(), tid, ...params);\n}\n\nexport function getHTMLTidForLanguage(langCode: string, tid: string, ...params: TidParam[]): string {\n  if (tid === \"\") {\n    return \"\";\n  }\n\n  if (tid.startsWith(\":\")) {\n    return encodeString(tid.substring(1), \"html\");\n  } else if (tid.startsWith(\"<>\")) {\n    return tid.substring(2);\n  }\n\n  return calcTIDForLanguage(langCode, tid, params, true, null).join(\"\");\n}\n\nexport function getTIDListForLanguage(langcode: string, gid: string) {\n  gid = getCanonicalTid(gid.toLowerCase());\n  langcode = langcode.toLowerCase();\n\n  const modsep = gid.indexOf(':');\n  if (modsep === -1) {\n    if (dtapStage !== \"production\" || debugFlags.gtd)\n      console.warn(`Missing module name in call for gid '${gid}'`);\n    return `(cannot find textnode: ${gid})`;\n  }\n\n  const module = gid.substring(0, modsep);\n  const lookup = gid.substring(modsep + 1).replace(/ /g, \"_\") + \".\";\n\n  const compiled = getLanguageFile(module, langcode);\n  const result: string[] = [];\n  if (compiled) {\n    for (const key of compiled.texts.keys()) {\n      if (key.startsWith(lookup) && key.indexOf(\".\", lookup.length) === -1)\n        result.push(`${module}:${key}`);\n    }\n    if (compiled.fallbackLanguage) {\n      const fallback = getLanguageFile(module, compiled.fallbackLanguage);\n      if (fallback) {\n        for (const key of fallback.texts.keys()) {\n          if (key.startsWith(lookup) && key.indexOf(\".\", lookup.length) === -1 && !result.includes(`${module}:${key}`))\n            result.push(`${module}:${key}`);\n        }\n      }\n    }\n  }\n\n  return result;\n}\n\nfunction cannotFind(tid: string) {\n  if (debugFlags.sut)\n    return [tid.substring(tid.lastIndexOf(\".\"))];\n\n  return [`(cannot find text: ${tid})`];\n}\nfunction calcTIDForLanguage(langcode: string, tid: string, rawParams: TidParam[], rich: boolean, render: null): string[];\nfunction calcTIDForLanguage(langcode: string, tid: string, rawParams: TidParam[], rich: boolean, render: GetTidRenderFunc): Array<string | object>;\n\n\nfunction calcTIDForLanguage(langcode: string, tid: string, rawParams: TidParam[], rich: boolean, render: GetTidRenderFunc | null): Array<string | object> {\n  tid = getCanonicalTid(tid.toLowerCase());\n  if (langcode.match(/^[a-z]{2}-/)) //truncate country codes from language identifiers (eg en-GB) until we have actual support for those, so we don't break when en-GB is passed straight from eg. document.documentElement.lang\n    langcode = langcode.substring(0, 2);\n\n  if (tid === \"tollium:tilde.locale.datetimestrings\") {\n    return [getLanguageDatetimeStrings(langcode)];\n  }\n\n  // convert null to \"\", numbers to strings\n  const params = rawParams.map(p => (typeof p === \"number\" ? p.toString() : (p ?? \"\")));\n\n  const modsep = tid.indexOf(':');\n  if (modsep === -1) {\n    if (dtapStage !== \"production\" || debugFlags.gtd)\n      console.warn(`Missing module name in call for tid '${tid}'`);\n    return [`(missing module name in tid: ${tid})`];\n  }\n\n  const module = tid.substring(0, modsep);\n  const lookup = tid.substring(modsep + 1).replace(/ /g, \"_\");\n  tid = `${module}:${lookup}`;\n\n  if (langcode === \"debug\") {\n    const debugtid = `{${[tid, ...params].join(\"|\")}}`;\n    return [rich ? encodeString(debugtid, \"html\") : debugtid];\n  }\n\n  const compiled = getLanguageFile(module, langcode);\n  const match = compiled?.texts.get(lookup);\n  if (!match && compiled?.fallbackLanguage) {\n    const fallback = getLanguageFile(module, compiled.fallbackLanguage);\n    const fallbackMatch = fallback?.texts.get(lookup);\n    if (!fallbackMatch && (dtapStage !== \"production\" || debugFlags.gtd)) {\n      console.warn(`Cannot find text ${tid} for language ${langcode}, also tried fallback language '${compiled.fallbackLanguage}'`);\n    }\n    return fallbackMatch ? executeCompiledTidText(fallbackMatch, params, rich, render) : cannotFind(tid);\n  }\n\n  if (!match && (dtapStage !== \"production\" || debugFlags.gtd)) {\n    console.warn(`Cannot find text ${tid} for language ${langcode}, no fallback language`);\n  }\n  return match ? executeCompiledTidText(match, params, rich, render) : cannotFind(tid);\n}\n\nfunction getCanonicalTid(tid: string) {\n  if (tid.startsWith(\"tollium:common.buttons.\") || tid.startsWith(\"tollium:common.actions.\") || tid.startsWith(\"tollium:common.labels.\")) {\n    return `tollium:tilde.${tid.substring(tid.indexOf(\".\") + 1)}`;\n  } else if (tid.startsWith(\"~\")) {\n    return `tollium:tilde.${tid.substring(1)}`;\n  }\n\n  return tid;\n}\n\nfunction renderString(tok: string, rich: boolean, render: GetTidRenderFunc | null) {\n  return rich ?\n    render ?\n      tok.split(/(\\n)/).map(part => part !== \"\\n\" ? part : render(\"br\", {})).filter(_ => _) :\n      [encodeString(tok, \"html\")] :\n    [tok];\n}\n\nfunction executeCompiledTidText(text: string | LanguagePart[], params: string[], rich: boolean, render: GetTidRenderFunc | null): Array<object | string> {\n  if (typeof text === \"string\")\n    return renderString(text, rich, render);\n\n  const parts = new Array<object | string>;\n  for (const tok of text) {\n    if (typeof tok === \"string\") {\n      parts.push(...renderString(tok, rich, render));\n    } else if (typeof tok === \"number\") {\n      if (tok >= 1) {\n        const get_param = params[tok - 1];\n        if (get_param) {\n          parts.push(...renderString(get_param, rich, render));\n        }\n      }\n    } else if (tok.t === \"tag\") {\n      const sub = executeCompiledTidText(tok.subs, params, rich, render);\n      if (rich && render)\n        parts.push(render(tok.tag, { children: sub }));\n      else\n        parts.push(...(rich ? [`<${tok.tag}>`, ...sub, `</${tok.tag}>`] : sub));\n    } else if (tok.t === \"ifparam\") {\n      const get_param = params[tok.p - 1] || \"\";\n      parts.push(...executeCompiledTidText(get_param.toUpperCase() === tok.value.toUpperCase() ? tok.subs : tok.subselse, params, rich, render));\n    } else if (tok.t === \"a\") {\n      const sub = executeCompiledTidText(tok.subs, params, rich, render);\n      if (rich) {\n        let link = tok.link;\n        if (tok.linkparam > 0 && tok.linkparam <= params.length) {\n          link = params[tok.linkparam - 1] || link;\n        }\n        if (link) {\n          if (render)\n            parts.push(render(\"a\", { href: link, children: sub }));\n          else\n            parts.push(`<a href=\"${encodeString(link, \"attribute\")}\">`, ...sub, `</a>`);\n        } else {\n          parts.push(...sub);\n        }\n      } else {\n        parts.push(...sub);\n      }\n    }\n  }\n  return parts;\n}\n\nfunction flattenRecursiveLanguageTexts(text: RecursiveLanguageTexts, pathsofar: string, result: Map<string, LanguageText>): void {\n  if (typeof text === \"string\" || Array.isArray(text))\n    result.set(pathsofar, text);\n  else\n    for (const [name, value] of Object.entries(text))\n      flattenRecursiveLanguageTexts(value, `${pathsofar}${pathsofar && name ? \".\" : \"\"}${name}`, result);\n}\n\nexport function registerTexts(module: string, langCode: string, tids: RecursiveLanguageTexts) {\n  const langkey = `${module}:${langCode}`;\n  let compiledFile = langFileCache[langkey];\n  if (!compiledFile) {\n    const texts = new Map;\n    langFileCache[langkey] = compiledFile = { resource: \"\", fallbackLanguage: \"\", langCode, texts, registered: texts };\n  }\n  flattenRecursiveLanguageTexts(tids, \"\", compiledFile.registered);\n  if (compiledFile.texts !== compiledFile.registered) {\n    for (const [key, value] of compiledFile.registered)\n      compiledFile.texts.set(key, value);\n  }\n}\n\nfunction getLanguageDatetimeStrings(langCode: string) {\n  switch (langCode.substring(0, 2)) {\n    case \"nl\": return \"am;pm;januari;februari;maart;april;mei;juni;juli;augustus;september;oktober;november;december;maandag;dinsdag;woensdag;donderdag;vrijdag;zaterdag;zondag;jan;feb;mrt;apr;mei;jun;jul;aug;sep;okt;nov;dec;ma;di;wo;do;vr;za;zo\";\n    case \"de\": return \"am;pm;Januar;Februar;März;April;Mai;Juni;Juli;August;September;Oktober;November;Dezember;Montag;Dienstag;Mittwoch;Donnerstag;Freitag;Samstag;Sonntag;Jan.;Febr.;März;Apr.;Mai;Juni;Juli;Aug.;Sept.;Okt.;Nov.;Dez.;Mo;Di;Mi;Do;Fr;Sa;So\";\n    case \"fr\": return \"am;pm;Janvier;Février;Mars;Avril;Mai;Juin;Juillet;Août;Septembre;Octobre;Novembre;Décembre;Lundi;Mardi;Mercredi;Jeudi;Vendredi;Samedi;Dimanche;Janv;Févr;Mars;Avril;Mai;Juin;Juil;Août;Sept;Oct;Nov;Déc;Lun;Mar;Mer;Jeu;Ven;Sam;Dim\";\n    case \"jp\": {\n      return Buffer.from(\"5Y2I5YmNO+WNiOW+jDvvvJHmnIg777yS5pyIO++8k+aciDvvvJTmnIg777yV5pyIO++8luaciDvvvJfmnIg777yY5pyIO++8meaciDvvvJHvvJDmnIg777yR77yR5pyIO++8ke+8kuaciDvmnIjmm5zml6U754Gr5puc5pelO+awtOabnOaXpTvmnKjmm5zml6U76YeR5puc5pelO+Wcn+abnOaXpTvml6Xmm5zml6U777yR5pyIO++8kuaciDvvvJPmnIg777yU5pyIO++8leaciDvvvJbmnIg777yX5pyIO++8mOaciDvvvJnmnIg777yR77yQ5pyIO++8ke+8keaciDvvvJHvvJLmnIg75pyIO+eBqzvmsLQ75pyoO+mHkTvlnJ875pel\", \"base64\").toString();\n    }\n  }\n\n  // \"en\" is the default\n  return \"am;pm;January;February;March;April;May;June;July;August;September;October;November;December;Monday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday;Jan;Feb;Mar;Apr;May;Jun;Jul;Aug;Sep;Oct;Nov;Dec;Mon;Tue;Wed;Thu;Fri;Sat;Sun\";\n}\n","/* frontend-config parses the wh-config object in the browser and mocks any missing data. @webhare/env does not actually expose this config, @webhare/frontend does\n   The frontend configuration is built in PageBuildRequest's 'frontendConfig' member */\n\nimport type { DTAPStage } from \"@webhare/env/src/concepts\";\nimport { debugFlags, initEnv } from \"@webhare/env/src/envbackend\";\nimport { getBrowserDebugFlags } from \"@webhare/env/src/init-browser\";\nimport { getLang } from \"@webhare/dompack/src/tree\";\nimport type { FrontendDataTypes } from \"@webhare/frontend\";\nimport { omit, throwError } from \"@webhare/std\";\n\n\n/** The format of the <script id=\"wh-config\"> object  */\nexport type WHConfigScriptData = {\n  //NOTE: existing frontend code doesn't expect site/obj to ever be null. not sure if 'object' provides the best interface or whether we need some sort of 'unknown but an existing object'\n  /** Page (targetobject) specific settings\n   *  @deprecated Use setFrontendData for type-safe settings\n  */\n  obj: { [key: string]: unknown };\n  /** Site specific settings\n   *  @deprecated Use setFrontendData for type-safe settings\n   */\n  site: { [key: string]: unknown };\n\n  /** Root URL of this site */\n  siteRoot: string;\n};\n\nexport type WHConfigScriptData_FromServer = WHConfigScriptData & { dtapStage: DTAPStage };\n\n//names fields can still have when not yet republished\ninterface WHConfigScriptData_OldPublishFields {\n  islive: boolean;\n  dtapstage: DTAPStage;\n  siteroot: string;\n}\n\n//fallback names with deprecation warnings\ninterface WHConfigScriptData_LegacyFields {\n  /** @deprecated Use dtapStage in WH5.4+ */\n  islive: boolean;\n  /** @deprecated Use `dtapStage` from \"\\@webhare/env\"; in WH5.4+ */\n  dtapstage: DTAPStage;\n  /** @deprecated Use `getSiteRoot` from \"\\@webhare/frontend\"; in WH5.7+ */\n  siteroot: string;\n}\n\nlet config: WHConfigScriptData_FromServer | undefined;\nlet siteroot: string | undefined;\nlet dtapStage: DTAPStage = \"production\";\n\n//if document is undefined, we're serverside or in a worker\nconst whconfigel = typeof document !== \"undefined\" ? document.querySelector('script#wh-config') : null;\nif (whconfigel?.textContent) {\n  const parsedConfig: WHConfigScriptData_FromServer & WHConfigScriptData_OldPublishFields = JSON.parse(whconfigel.textContent);\n  config = omit(parsedConfig, [\"siteroot\", \"dtapstage\", \"islive\"]);\n\n  //Fallbacks for pages last published with WH5.3 *and* pages published from HareScript which still emit lowercase props\n  siteroot = parsedConfig.siteRoot ?? parsedConfig.siteroot!;\n  dtapStage = parsedConfig.dtapStage ?? parsedConfig.dtapstage;\n}\n\ninitEnv(dtapStage, '/');\n\nif (typeof location !== \"undefined\")\n  for (const flag of getBrowserDebugFlags('wh-debug'))\n    debugFlags[flag] = true;\n\n\n/** @deprecated frontendConfig has been deprecated. Switch to the getFrontendData system */\n// Make sure we have obj/site as some sort of object, to prevent crashes on naive 'if ($wh.config.obj.x)' tests'\nexport const frontendConfig: WHConfigScriptData & {\n  /** @deprecated Use `getLang().tag` in WH6.0+ & WH5.9.7 */\n  locale?: string;\n} = {\n  ...config,\n  obj: config?.obj || {},\n  site: config?.site || {},\n  siteRoot: siteroot || \"\",\n  dtapstage: dtapStage,\n  islive: dtapStage === \"production\" || dtapStage === \"acceptance\",\n  siteroot: siteroot || \"\",\n  ...typeof document !== \"undefined\" ? { locale: getLang().tag } : {},\n} as WHConfigScriptData & WHConfigScriptData_LegacyFields;\n\n// this is what we actually store in the config object but is type-unsafe to access. Plugins still store data in the config object\nexport type WHConfigSerializedData = WHConfigScriptData & WHConfigScriptData_LegacyFields & { [key in keyof FrontendDataTypes]?: FrontendDataTypes[key] };\n\nif (dtapStage === \"development\") { //WH6.0: it's time to hard phase-out the old fields\n  Object.defineProperties(frontendConfig, {\n    islive: { get() { throw new Error(\"frontendConfig.islive will be removed - replace with testing 'dtapStage' for production | acceptance (WH5.4+)\"); } },\n    dtapstage: { get() { throw new Error(\"frontendConfig.dtapstage will be removed - replace with 'dtapStage' (WH5.4+)\"); } },\n    siteroot: { get() { throw new Error(\"frontendConfig.siteroot will be removed - replace with 'getSiteRoot()' (WH5.7+)\"); } },\n    //TODO but only WH6 addded this property AND getLang so there's no phasing out yet.\n    //locale: { get() { throw new Error(\"frontendConfig.locale will be removed - replace with getLang().tag in WH6.0+ & WH5.9.7\"); } },\n  });\n}\n\n//NOTE: These APIs need to live in init.ts so eg gtm.ts can access us without triggering a CSS reset through frontend.ts. When frontend.ts stops auto-resetting we might move it back\n\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options: { allowMissing: true }): FrontendDataTypes[Type] | null;\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options?: { allowMissing: boolean }): FrontendDataTypes[Type];\n\n/** Get data exported by the response\n * @typeParam Type - The type of data to get\n * @param dataObject - The data object of data to get\n * @param allowMissing - If true, return null if the data object is missing. Otherwise throw an error\n * @example\n```\n  declare module \"@webhare/frontend\" {\n    interface FrontendDataTypes {\n      \"mymodule:type\": {\n        test: number;\n      };\n    }\n  }\n\n  const data = getFrontendData(\"mymodule:type\");\n```\n*/\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(dataObject: Type, { allowMissing = false } = {}): FrontendDataTypes[Type] | null {\n  const retval = (config as undefined | WHConfigSerializedData)?.[dataObject] as FrontendDataTypes[Type];\n  if (!retval)\n    if (allowMissing)\n      return null;\n    else\n      throw new Error(`Missing frontend data object: ${dataObject}`);\n\n  return retval;\n}\n\n/** Get the current site root\n *\n * @returns The site root URL (ending with a slash)\n*/\nexport function getSiteRoot(): string { //now an API to improve treeshaking\n  return siteroot ?? throwError(\"Site root is undefined. HTML code may be broken\");\n}\n","\n//Note that @webhare/env does not invoke this API itself. In WebHare @webhare/frontend/src/init uses this to initialize\nexport function getBrowserDebugFlags(varname: string): string[] {\n  const flags = [];\n  const urldebugvar = new URL(location.href).searchParams.get(varname);\n  if (urldebugvar)\n    flags.push(...urldebugvar.split(','));\n\n  //not importing getCookie to solve some import ordering issues\n  if (typeof document !== \"undefined\") { //'document' is undefined in a worker but assetpacks compiled for a ServiceWorker will also load us\n    const debugcookie = document.cookie.match(`(?:^|;)\\\\s*${varname}=([^;]*)`); //TODO escape varname\n    if (debugcookie) {\n      const debugcookievalue = decodeURIComponent(debugcookie[1]);\n      if (debugcookievalue)\n        flags.push(... (debugcookievalue.split('.').filter(flag => !flag.startsWith('sig='))));\n    }\n  }\n\n  if (typeof sessionStorage !== \"undefined\") {\n    const sessionDebug = sessionStorage.getItem(varname);\n    if (sessionDebug)\n      flags.push(...sessionDebug.split(','));\n  }\n\n  return flags;\n}\n","// Set up dispose symbols - https://github.com/evanw/esbuild/pull/3192 \"you'll need to polyfill Symbol.dispose if it's not present before you use it.\n\n//@ts-expect-error -- It's marked readonly\nSymbol.dispose ||= Symbol.for('Symbol.dispose');\n//@ts-expect-error -- It's marked readonly\nSymbol.asyncDispose ||= Symbol.for('Symbol.asyncDispose');\n\n// Set up promise resolvers (ES2024)\nPromise.withResolvers ||= function <T>(): PromiseWithResolvers<T> {\n  let resolve: (value: T | PromiseLike<T>) => void;\n  let reject: (reason: Error) => void;\n  const promise = new Promise<T>((_resolve, _reject) => { resolve = _resolve; reject = _reject; });\n  // @ts-expect-error `resolve` and `reject` are assigned synchronously, which isn't picked up by the TypeScript compiler (see\n  // https://github.com/Microsoft/TypeScript/issues/30053)\n  return { promise, resolve, reject };\n};\n\n// Polyfills for https://caniuse.com/?search=groupby - needed until we can assume safari 17.4 as global baseline\nif (!Map.groupBy)\n  Map.groupBy = function <Item, Key>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Map<Key, Item[]> {\n    const retval = new Map<Key, Item[]>;\n    let idx = 0;\n    for (const item of items) {\n      const key = callbackfn(item, idx++);\n      let list = retval.get(key);\n      if (!list)\n        retval.set(key, list = []);\n      list.push(item);\n    }\n    return retval;\n  };\n\nif (!Object.groupBy)\n  Object.groupBy = function <Item, Key extends string | number | symbol>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Partial<Record<Key, Item[]>> {\n    return Object.fromEntries(Map.groupBy(items, callbackfn).entries()) as Partial<Record<Key, Item[]>>;\n  };\n","/* eslint-disable @typescript-eslint/no-loop-func */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-this-alias */\n\n/* Iterator polyfills (https://caniuse.com/?search=iterator) - stage 4 ES but not in all browsers yet\n   Based on https://github.com/alkihis/iterator-polyfill/tree/master but we removed all the AsyncIterator\n   stuff as that's still stage 2 AND not implemented in TypeScript (as of 5.6)\n\n   We're ignoring a few linting/any issues as we really don't care to maintain this much\n   Fixed an issue with .some - reported as https://github.com/alkihis/iterator-polyfill/issues/6\n*/\n\n(function () {\n  // polyfill already applied / proposal implemented\n  if ('Iterator' in globalThis) {\n    return;\n  }\n\n  // Polyfill for Iterator\n  const IteratorPrototype = {};\n\n  const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());\n  const OriginalIteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);\n\n  Object.setPrototypeOf(OriginalIteratorPrototype, IteratorPrototype);\n\n  Object.defineProperties(IteratorPrototype, {\n    [Symbol.iterator]: {\n      value() {\n        return this;\n      }\n    },\n    map: {\n      *value<T, R>(callback: (value: T) => R): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = callback(value.value);\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    filter: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          if (callback(real_value)) {\n            next_value = yield real_value;\n            value = it.next(next_value);\n          } else {\n            value = it.next(next_value);\n          }\n        }\n\n        return value.value;\n      },\n    },\n    find: {\n      value<T>(callback: (value: boolean) => T) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return real_value;\n\n          value = it.next();\n        }\n      }\n    },\n    every: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!callback(real_value))\n            return false;\n\n          value = it.next();\n        }\n\n        return true;\n      }\n    },\n    some: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value)) {\n            it.return();\n            return true;\n          }\n\n          value = it.next();\n        }\n\n        return false;\n      }\n    },\n    toArray: {\n      value(max_count = Infinity) {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max_count <= 0)\n            return values;\n\n          values.push(real_value);\n\n          if (max_count !== Infinity)\n            max_count--;\n\n          value = it.next();\n        }\n\n        return values;\n      }\n    },\n    take: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining <= 0)\n            return;\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n          remaining--;\n        }\n\n        return value.value;\n      },\n    },\n    drop: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining > 0) {\n            value = it.next(next_value);\n            remaining--;\n            continue;\n          }\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    asIndexedPairs: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let index = 0;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const next_value = yield [index, real_value];\n          value = it.next(next_value);\n          index++;\n        }\n\n        return value.value;\n      }\n    },\n    flatMap: {\n      *value<T, R extends object>(mapper: (value: T) => IterableIterator<R> | R): Generator<any, any, any> {\n        if (typeof mapper !== 'function') {\n          throw new TypeError('Mapper must be a function.');\n        }\n\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const mapped = mapper(real_value);\n\n          if (Symbol.iterator in mapped) {\n            next_value = yield* mapped[Symbol.iterator]();\n          } else {\n            next_value = yield mapped;\n          }\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    reduce: {\n      value<T, V>(reducer: (acc: V, value: T) => V, initial_value?: V) {\n        let acc = initial_value;\n\n        const it = this;\n        if (acc === undefined) {\n          acc = it.next().value;\n        }\n\n        let value = it.next();\n        while (!value.done) {\n          const real_value = value.value;\n\n          acc = reducer(acc!, real_value);\n\n          value = it.next();\n        }\n\n        return acc;\n      }\n    },\n    forEach: {\n      value<T>(callback: (value: T) => any) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          callback(real_value);\n\n          value = it.next();\n        }\n      }\n    },\n    [Symbol.toStringTag]: {\n      value: 'IteratorPrototype'\n    },\n\n    /* OUTSIDE PROPOSAL */\n    count: {\n      value() {\n        let count = 0;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          count++;\n          value = it.next();\n        }\n\n        return count;\n      },\n    },\n    join: {\n      value(string: string) {\n        let final = '';\n        let first = true;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (first) {\n            first = false;\n            final += real_value;\n          } else {\n            final += string + real_value;\n          }\n\n          value = it.next();\n        }\n\n        return final;\n      }\n    },\n    chain: {\n      *value<I>(...iterables: IterableIterator<I>[]) {\n        yield* this;\n\n        for (const it of iterables) {\n          yield* it;\n        }\n      }\n    },\n    zip: {\n      *value<T, O>(...others: IterableIterator<O>[]): Iterator<(T | O)[]> {\n        const it_array = [this, ...others].map((e: any) => Symbol.iterator in e ? e[Symbol.iterator]() : e as Iterator<T | O>);\n        let values = it_array.map(e => e.next());\n        let next_value: any;\n\n        while (values.every(e => !e.done)) {\n          next_value = yield values.map(e => e.value);\n          values = it_array.map(e => e.next(next_value));\n        }\n      },\n    },\n    takeWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    dropWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n        let finished = false;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!finished && callback(real_value)) {\n            value = it.next(next_value);\n            continue;\n          }\n\n          finished = true;\n          next_value = yield real_value;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    fuse: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (real_value !== undefined && real_value !== null)\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    partition: {\n      value<T>(callback: (value: T) => boolean) {\n        const partition1 = [], partition2 = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            partition1.push(real_value);\n          else\n            partition2.push(real_value);\n\n          value = it.next();\n        }\n\n        return [partition1, partition2];\n      },\n    },\n    findIndex: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let i = 0;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return i;\n\n          value = it.next();\n          i++;\n        }\n\n        return -1;\n      }\n    },\n    max: {\n      value() {\n        let max = -Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max < real_value)\n            max = real_value;\n\n          value = it.next();\n        }\n\n        return max;\n      },\n    },\n    min: {\n      value() {\n        let min = Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (min > real_value)\n            min = real_value;\n\n          value = it.next();\n        }\n\n        return min;\n      },\n    },\n    cycle: {\n      *value(): Generator<any, any, any> {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n          values.push(real_value);\n\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        while (true) {\n          yield* values;\n        }\n      },\n    },\n  });\n\n  //iterator.from from https://github.com/rauschma/iterator-helpers-polyfill/\n\n  function isObject(value: unknown) {\n    if (value === null) return false;\n    const t = typeof value;\n    return t === 'object' || t === 'function';\n  }\n\n  function GetIteratorFlattenable<T>(obj: Record<symbol, any>): T {\n    if (!isObject(obj)) {\n      throw new TypeError();\n    }\n    const method = obj[Symbol.iterator];\n    let iterator = undefined;\n    if (typeof method !== 'function') {\n      iterator = obj;\n    } else {\n      iterator = method.call(obj);\n    }\n    if (!isObject(iterator)) {\n      throw new TypeError();\n    }\n    return iterator;\n  }\n\n  if (!('Iterator' in globalThis)) {\n    const Iterator = function Iterator() { };\n\n    Iterator.prototype = IteratorPrototype;\n\n    // @ts-expect-error We're still missing From in this poyfill\n    (globalThis).Iterator = Iterator;\n  }\n\n\n  //----- Static method -----\n  // Must be done after Iterator.prototype was set up,\n  // so that `extends Iterator` works below\n\n  class WrappedIterator<T, TReturn = any, TNext = undefined> extends Iterator<T, TReturn, TNext> {\n    #iterator;\n    constructor(iterator: Iterator<T, TReturn, TNext>) {\n      super();\n      this.#iterator = iterator;\n    }\n    override next(...args: [] | [TNext]): any {\n      return this.#iterator.next(...args);\n    }\n    // `async` helps with line (*)\n    override return(value?: TReturn | PromiseLike<TReturn>): any {\n      const returnMethod = this.#iterator.return;\n      if (returnMethod === undefined) {\n        return { done: true, value: value as any }; // (*)\n      }\n      return returnMethod.call(this.#iterator);\n    }\n  }\n\n  function Iterator_from<T>(value: any) {\n    const iterator = GetIteratorFlattenable<Iterator<T>>(value);\n    if (iterator instanceof Iterator) {\n      return iterator;\n    }\n    // `iterator´ does not support the new API – wrap it so that it does\n    return new WrappedIterator(iterator);\n  }\n\n  Object.defineProperty(\n    Iterator, 'from',\n    {\n      writable: true,\n      enumerable: false,\n      configurable: true,\n      value: Iterator_from,\n    }\n  );\n})();\n","import { debugFlags } from '@webhare/env';\nimport * as domevents from '../../../modules/system/js/dompack/src/events';\nimport \"@webhare/tsrun/src/polyfills\";\n\nlet locallocks: BusyLock[] = [];\nlet modallocked = false;\nlet uiwatcher: NodeJS.Timeout | null = null;\nlet installedanticancelhandler = false;\n\nlet currentbusymodaldialog: HTMLDialogElement | null = null;\nlet currentbusymodaluserdialog: HTMLDialogElement | null = null;\nlet busymodalcontent: string | HTMLElement | HTMLDialogElement | undefined;\nlet mylockmgr: LockManager | undefined;\n\nexport type BusyModalEvent = CustomEvent<{ show: boolean }>;\n\n// As 'Lock' already exists on the Web (https://developer.mozilla.org/docs/Web/API/Lock) and it's seldom used just use a longer name. Available since WH 5.4\nexport interface UIBusyLock extends Disposable {\n  release(): void;\n  [Symbol.dispose](): void;\n}\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:busymodal\": BusyModalEvent;\n  }\n  interface Window {\n    __dompack_busylockmanager?: LockManager;\n  }\n\n  // __dompack_busylockmanager: LockManager | undefined;  //\n}\n\nfunction getLockmgr(): LockManager {\n  if (!mylockmgr) {\n    mylockmgr = getParentLockManager() || new LockManager;\n    if (typeof window !== \"undefined\")\n      window.__dompack_busylockmanager = mylockmgr;\n  }\n  return mylockmgr;\n}\n\nfunction anyModalLocks() {\n  return locallocks.some(l => l.modal);\n}\n\n/* scheduleCheckUIFree is invoked by release() or when waitUIFree is explicitly called. the call from release() should\n   be a 'fast' path. We schedule a full check for the next tick if there's a chance it might actually find a free UI */\nfunction scheduleCheckUIFree() {\n  if (!uiwatcher && locallocks.length === 0)\n    uiwatcher = setTimeout(() => checkUIFree(), 0);\n}\n\n/* check if the UI is actually free. if so, remove busymodals and resolve waitUIFrees for the benefit of testfw  */\nfunction checkUIFree() {\n  uiwatcher = null;\n\n  if (modallocked && !anyModalLocks()) { //did the last frame-level *modal* lock just get released?\n    modallocked = false;\n    toggleBusyModal(false);\n  }\n\n  if (locallocks.length === 0) {\n    const lockmgr = getLockmgr();\n    lockmgr.busyframes.delete(window); //we won't release our block in the lockmanager until we've had a chance to remove our modal layer\n    lockmgr.checkUIFree(); //to resolve any waitUIFrees. runs in the top-level frame. note that lockmgr cares about ALL ui locks, not just modals\n  }\n}\n\nfunction isDialogElement(el: unknown): boolean {\n  return typeof el === \"object\" && (el as HTMLElement).matches?.(\"dialog\") || false;\n}\n\nfunction checkCancelEvent(evt: Event) {\n  if (modallocked)\n    evt.preventDefault();\n}\n\nfunction toggleBusyModal(show: boolean) {\n  //'islock' is legacy non-camel version. TypeScript typing should help us transition (since 5.3). 'as' shuts up the warning TODO remove 'islock' and the 'as'\n  if (!domevents.dispatchCustomEvent(window, 'dompack:busymodal', { bubbles: true, cancelable: true, detail: { show: show, islock: show } as BusyModalEvent['detail'] }))\n    return; //cancelled!\n\n  if (!installedanticancelhandler) {\n    //capture cancel, as it doesn't bubble up\n    addEventListener(\"cancel\", evt => checkCancelEvent(evt), { capture: true });\n    installedanticancelhandler = true;\n  }\n\n  if (show) {\n    if (isDialogElement(busymodalcontent)) { //the user provided us with an element\n      currentbusymodaluserdialog = busymodalcontent as HTMLDialogElement;\n      currentbusymodaluserdialog.showModal();\n    } else if (busymodalcontent) { //we'll create our own dialog\n      const dialog = document.createElement('dialog');\n      const toembed = typeof busymodalcontent === \"string\" ? document.createTextNode(busymodalcontent) : busymodalcontent.cloneNode(true);\n      dialog.className = \"dompack-busydialog\";\n      dialog.role = \"status\";\n      dialog.ariaLive = \"off\";\n      dialog.append(toembed);\n      document.body.appendChild(dialog);\n      currentbusymodaldialog = dialog;\n      dialog.showModal();\n      return;\n    }\n\n    document.documentElement.classList.add(\"dompack--busymodal\");\n    return;\n  }\n\n  //hiding\n  document.documentElement.classList.remove(\"dompack--busymodal\");\n  if (currentbusymodaluserdialog)\n    currentbusymodaluserdialog.close();\n  if (currentbusymodaldialog) { //we added a dialog to the dom\n    currentbusymodaldialog.close();\n    document.body.removeChild(currentbusymodaldialog);\n    currentbusymodaldialog = null;\n  }\n}\n\nclass LockManager {\n  locks: BusyLock[];\n  busyframes: Set<Window> = new Set;\n  busycounter: number;\n  deferreduipromise: PromiseWithResolvers<boolean> | null;\n\n  //this object is not for external consumption\n  constructor() {\n    this.locks = [];\n    this.busycounter = 0;\n    this.deferreduipromise = null;\n  }\n  add(lock: BusyLock) {\n    this.locks.push(lock);\n    const returnvalue = this.busycounter++;\n    return returnvalue;\n  }\n  release(lock: BusyLock) {\n    const pos = this.locks.indexOf(lock);\n    if (pos === -1) {\n      if (debugFlags.bus) {\n        console.error(\"Duplicate release of busy lock #\" + lock.locknum);\n        console.log(\"Lock allocated:\");\n        console.log(lock.acquirestack);\n        console.log(\"Lock first released:\");\n        console.log(lock.releasestack);\n      }\n      throw new Error(\"Duplicate release of busy lock\");\n    }\n\n    this.locks.splice(pos, 1);\n  }\n  getNumLocks() {\n    return this.locks.length;\n  }\n  //used by child windows to schedule a check in *our* frame (eg before they themselves are unloaded)\n  scheduleCheckUIFree() {\n    scheduleCheckUIFree();\n  }\n  checkUIFree() {\n    if (this.locks.length === 0 && this.busyframes.size === 0 && this.deferreduipromise) {\n      this.deferreduipromise.resolve(true);\n      this.deferreduipromise = null;\n    }\n  }\n  waitUIFree() {\n    if (!this.deferreduipromise)\n      this.deferreduipromise = Promise.withResolvers();\n\n    scheduleCheckUIFree(); //ensures uiwait is released at next tick if no locks are present at all\n    return this.deferreduipromise.promise;\n  }\n  logLocks() {\n    this.locks.forEach(lock => console.log('[bus] lock #' + lock.locknum, lock.acquirestack, lock));\n    console.log(\"[bus] total \" + this.locks.length + \" locks\");\n  }\n  getLockIds() {\n    return this.locks.map(l => \"#\" + l.locknum).join(\", \");\n  }\n}\n\n/** Configure an (accessible) modal dialog\n * @param bmc - What to show in the dialog: either a text or DOM fragment to clone.\n *              If a <dialog> element is passed, this dialog will be used instead of creating a new one.\n */\nexport function setupBusyModal(bmc: NonNullable<typeof busymodalcontent>) {\n  busymodalcontent = bmc;\n}\n\ninterface LockOptions {\n  ///Whether this lock should enable a modality laayer\n  modal?: boolean;\n}\n\nclass BusyLock implements UIBusyLock {\n  modal: boolean;\n  locknum: number;\n  acquirestack: string | undefined;\n  releasestack: string | undefined;\n\n  constructor(options?: LockOptions) {\n    //legacy non-camel name is 'ismodal'\n    this.modal = options?.modal ?? (options as { ismodal?: boolean })?.ismodal ?? false;\n\n    const lockmgr = getLockmgr();\n    this.locknum = lockmgr.add(this);\n    lockmgr.busyframes.add(window);\n    locallocks.push(this);\n\n    if (this.modal && !modallocked) {\n      modallocked = true;\n      toggleBusyModal(true);\n    }\n\n    if (debugFlags.bus) {\n      this.acquirestack = (new Error).stack;\n      console.trace('[bus] Busy lock #' + this.locknum + ' taken. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n  }\n\n  [Symbol.dispose]() {\n    if (debugFlags.bus)\n      this.releasestack = (new Error).stack;\n\n    const lockmgr = getLockmgr();\n    lockmgr.release(this);\n    const lockpos = locallocks.indexOf(this);\n    locallocks.splice(lockpos, 1);\n\n    if (debugFlags.bus) {\n      console.trace('[bus] Busy lock #' + this.locknum + ' released. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n\n    scheduleCheckUIFree();\n  }\n\n  release() {\n    this[Symbol.dispose]();\n  }\n}\n\n/** Return a promise resolving as soon as the UI (any accessible frame) is free for at least one tick */\nexport function waitUIFree() {\n  return getLockmgr().waitUIFree();\n}\n\n/**\n     flag userinterface as busy. tests then know not to interact with the UI until the busy flag is released\n *\n    @param options - Options.<br>\n                   - modal: true/false - Whether the lock is a modal lock\n */\nexport function flagUIBusy(options?: LockOptions): UIBusyLock {\n  return new BusyLock(options);\n}\n\nexport function getUIBusyCounter() {\n  return getLockmgr().busycounter;\n}\n\nfunction getParentLockManager(): LockManager | null {\n  try { //we're accessing a parent window, so we may hit security exceptions\n    if (!(window.parent?.__dompack_busylockmanager))\n      return null;\n\n    //if we connected to a parent...  deregister our locks, eg. if parent navigated our frame away\n    window.addEventListener(\"pagehide\", () => {\n      if (debugFlags.bus)\n        console.log(\"[bus] Frame unloading, \" + locallocks.length + \" locks pending.\", locallocks.map(l => \"#\" + l.locknum).join(\", \"), locallocks);\n\n      //switch to local instance in case anyone still tries to touch these locks during unload\n      const lockmgr = getLockmgr();\n      const locallockmgr = new LockManager;\n      locallocks.forEach(lock => { lockmgr.release(lock); locallockmgr.add(lock); });\n      locallocks = [];\n\n      lockmgr.busyframes.delete(window); //explicitly remove us so we won't be waited upon\n      lockmgr.scheduleCheckUIFree();\n      mylockmgr = locallockmgr;\n    });\n\n    return window.parent.__dompack_busylockmanager;\n  } catch (e) {\n    return null;\n  }\n}\n","import type { FormControlElement } from \"@webhare/dompack\";\n\nexport const CustomEvent = globalThis.CustomEvent;\n/** Wrap an event to ensure it's target is a HTMLElement\n * @typeParam EventType - The expected event type\n * @typeParam CurrentTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n * @typeParam RelatedTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n*/\nexport type DocEvent<EventType extends Event, CurrentTargetType extends HTMLElement = HTMLElement, RelatedTargetType extends HTMLElement = HTMLElement> = EventType & {\n  target: HTMLElement;\n  currentTarget: CurrentTargetType;\n  relatedTarget: RelatedTargetType | null;\n};\n\nexport type DomEventOptions =\n  {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    relatedTarget?: EventTarget;\n    detail?: object;\n  };\n\n/** @deprecated Browsers finally have cross-platform event dispatching. Use element.dispatchEvent(new MouseEvent/FocusEvent/CustomEvent) */\nexport function dispatchDomEvent(element: EventTarget, eventtype: string, options?: DomEventOptions) {\n  //see here https://developer.mozilla.org/en-US/docs/Web/Events whether an event is bubbles/cancelabel\n  options = {\n    bubbles: [\n      \"input\", \"change\", \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\"\n    ].includes(eventtype),\n    cancelable: [\n      \"animationstart\", \"animationcancel\", \"animationend\", \"animationiteration\",\n      \"beforeunload\",\n      \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\",\n      \"transitionstart\", \"transitioncancel\", \"transitionend\", \"transitionrun\"\n    ].includes(eventtype),\n    ...options\n  };\n\n  if (!element || !(element as Node).ownerDocument)\n    return true; //the element has left the dom... so there's no more bubbling. just drop it\n\n  //FIXME the load/scroll is buggy and we should be probably be using new Event (but an earlier attempt at that triggered quite a few test failures)\n  const createtype = /*[\"load\",\"scroll\"].includes(eventtype) === \"load\" ? \"UIEvents\" :*/[\"focus\", \"blur\", \"focusin\", \"focusout\"].includes(eventtype) ? \"FocusEvent\" : eventtype === \"click\" ? \"MouseEvents\" : \"HTMLEvents\";\n  //we verified its non-null ness above but TS doesn't really understand that\n  const evt = (element as Node).ownerDocument!.createEvent(createtype);\n  evt.initEvent(eventtype, options.bubbles, options.cancelable);\n  if (options.detail)\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we should just rewrite to new Event\n    (evt as any).detail = options.detail;\n  if (options.relatedTarget) //its a readonly prop, so redefine it\n    Object.defineProperty(evt, 'relatedTarget', { value: options.relatedTarget, writable: false });\n\n  //TODO: Should we keep this code?\n  // @ts-expect-error IScroll is a custom Window property set by IScroll\n  if (eventtype === 'click' && window.IScroll)\n    // @ts-expect-error _constructed is a custom Event property used by IScroll\n    evt._constructed = true; //ensure IScroll doesn't blindly cancel our synthetic clicks\n\n  return element.dispatchEvent(evt);\n}\n\n/** Fire the proper modified events (input and/or change) on the element after changing its value\n * @param element - Element to receive event\n * @deprecated Use changeValue so we can figure out the proper events to fire\n */\nexport function fireModifiedEvents(element: FormControlElement) {\n  element.dispatchEvent(new InputEvent(\"input\"));\n  element.dispatchEvent(new Event(\"change\"));\n}\n\n/** @deprecated Browsers finally have cross-platform event dispatching. Use element.dispatchEvent(new MouseEvent/FocusEvent/CustomEvent) */\nexport function fireHTMLEvent(element: EventTarget, type: string, options?: DomEventOptions) {\n  return dispatchDomEvent(element, type, options);\n}\n\ntype CustomEventParams =\n  {\n    /** Whether this event should bubble up in the DOM */\n    bubbles: boolean;\n    /** Whether this event can be cancelled */\n    cancelable: boolean;\n    /** Custom event information */\n    detail?: unknown;\n    /** Handler to execute if the default isn't prevented by a event listener */\n    defaulthandler?: (evt: CustomEvent) => void;\n  };\n\n/** Fire a custom event\n    @param node - node to fire the event on\n    @param event - event type. You should add this event to the GlobalEventHandlersEventMap for validation in dispatchCustomEvent calls and addEventListener callbacks.\n    @param params - Event options\n    @returns true if the default wasn't prevented\n */\n\nexport function dispatchCustomEvent<K extends string>(\n  node: EventTarget,\n  event: K,\n  params: CustomEventParams & (K extends keyof GlobalEventHandlersEventMap ?\n    GlobalEventHandlersEventMap[K] extends CustomEvent ?\n    { detail: GlobalEventHandlersEventMap[K][\"detail\"] } : unknown : unknown)) {\n\n  if (!params)\n    throw new Error(`Missing dispatchCustomEvent params`);\n  ['bubbles', 'cancelable'].forEach(prop => {\n    if (!(prop in params))\n      throw new Error(`Missing '${prop}' in dispatchCustomEvent params`);\n  });\n\n  const evt = new CustomEvent(event, {\n    bubbles: params.bubbles,\n    cancelable: params.cancelable,\n    detail: params.detail\n  });\n  let defaultaction = true;\n  try {\n    if (!node.dispatchEvent(evt))\n      defaultaction = false; //defaultPrevented is unreliable on IE11, so double check\n  } finally {\n    if (!evt.defaultPrevented && params.defaulthandler && defaultaction) {\n      params.defaulthandler(evt);\n    }\n  }\n  return defaultaction && !evt.defaultPrevented;\n}\n\n/**\n     Change the value of a form element, and fire the correct events as if it were a user change\n *\n    @param element - Element to change\n    @param newvalue - New value\n */\nexport function changeValue(element: FormControlElement, newvalue: string | number | boolean) {\n  if (element.matches(`input[type=radio], input[type=checkbox]`)) {\n    if (Boolean((element as HTMLInputElement).checked) === Boolean(newvalue))\n      return;\n    (element as HTMLInputElement).checked = Boolean(newvalue);\n  } else {\n    //FIXME it's not really clean to assume that this element is changeable - throw for non input/select..\n    const asString = String(newvalue);\n    if ((element as HTMLInputElement).value === asString)\n      return;\n\n    (element as HTMLInputElement).value = String(newvalue);\n  }\n  dispatchDomEvent(element as EventTarget, 'input');\n  dispatchDomEvent(element as EventTarget, 'change');\n}\n\nlet keydata: { mapping: { [key: string]: string } };\n\nfunction initKeyMapping() {\n  keydata =\n  {\n    // Mapping from keyIdentifier/key to key. If not found, translate U+XXXX to the unicode char and return that.\n\n    // List of all current key mappings (and current inconsistencies\n    // at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values\n    mapping:\n    {\n      \"Del\": \"Delete\", // IE/edge use 'Del' instead of 'Delete'\n      \"Esc\": \"Escape\", // IE/edge use 'Esc' instead of 'Escape'\n      \"OS\": \"Meta\", // Meta key is called OS on IE 9 and Firefox (tested v50)\n      \"Win\": \"Meta\", // Meta key is called Win on IE/Edge\n      \"Scroll\": \"ScrollLock\", // More IE/Edge, from tests\n      \"PrintScreen\": \"Print\", // More IE/Edge, from tests\n      \"MozHomeScreen\": \"GoHome\", // Prior to Firefox 37, the Home button generated a key code of \"Exit\". Starting in Firefox 37, the button generates the key code \"MozHomeScreen\".\n\n      // Internet Explorer 9 and Firefox 36 and earlier return \"Left\", \"Right\", \"Up\", and \"Down\" for the arrow keys, instead of \"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", and \"ArrowDown\".\n      \"Left\": \"ArrowLeft\",\n      \"Right\": \"ArrowRight\",\n      \"Up\": \"ArrowUp\",\n      \"Down\": \"ArrowDown\",\n      // More IE and old Firefox stuff\n      \"Crsel\": \"CrSel\",\n      \"Exsel\": \"ExSel\",\n      \"Nonconvert\": \"NonConvert\",\n      // Internet Explorer 9 and Firefox 36 and earlier report \"Apps\" instead of \"ContextMenu\" for the context menu key.\n      \"Apps\": \"ContextMenu\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"MediaNextTrack\" and \"MediaPreviousTrack\" instead of \"MediaTrackNext\" and \"MediaTrackPrevious\".\n      \"MediaNextTrack\": \"MediaTrackNext\",\n      \"MediaPreviousTrack\": \"MediaTrackPrevious\",\n      // In Internet Explorer 9, and prior to Firefox 49, \"AudioVolumeUp\", \"AudioVolumeDown\", and \"AudioVolumeMute\" were \"VolumeUp\", \"VolumeDown\", and \"VolumeMute\".\n      // In Firefox 49 they were updated to match the latest specification. The old names are still used on Boot to Gecko.\n      \"VolumeUp\": \"AudioVolumeUp\",\n      \"VolumeDown\": \"AudioVolumeDown\",\n      \"VolumeMute\": \"AudioVolumeMute\",\n      // Firefox added proper support for the \"TV\" key in Firefox 37; before that, this key generated the key code \"Live\".\n      \"Live\": \"TV\",\n      // Internet Explorer 9 and Firefox 36 and earlier identify the zoom toggle button as \"Zoom\". Firefox 37 corrects this to \"ZoomToggle\".\n      \"Zoom\": \"ZoomToggle\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"SelectMedia\" instead of \"LaunchMediaPlayer\". Firefox 37 through Firefox 48 use \"MediaSelect\". Firefox 49 has been updated to match the latest specification, and to return \"LaunchMediaPlayer\".\n      \"SelectMedia\": \"LaunchMediaPlayer\",\n      \"MediaSelect\": \"LaunchMediaPlayer\",\n      // Google Chrome returns \"LaunchCalculator\" instead of \"LaunchApplication1\". See Chromium bug 612743 for more information.\n      // Google Chrome returns \"LaunchMyComputer\" instead of \"LaunchApplication2\". See Chromium bug 612743 for more information.\n      // (LaunchCalculator and LaunchMyComputer are valid too, so no translation)\n\n      // While older browsers used words like \"Add\", \"Decimal\", \"Multiply\", and so forth modern browsers identify these using the actual character (\"+\", \".\", \"*\", and so forth).\n      \"Multiply\": \"*\",\n      \"Add\": \"+\",\n      \"Divide\": \"/\",\n      \"Subtract\": \"-\",\n      \"Decimal\": \".\", // (mozilla Key_Values doc says depends on region)\n      \"Separator\": \".\", // (mozilla Key_Values doc says depends on region)\n\n      // keyIdenfier spec mapping of non-printable keys: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      // Used in safari\n      \"U+0008\": \"Backspace\",\n      \"U+0009\": \"Tab\",\n      \"U+000D\": \"Enter\",\n      \"U+0018\": \"Cancel\",\n      \"U+001B\": \"Escape\",\n      \"U+007F\": \"Delete\",\n      \"U+0300\": \"DeadGrave\",\n      \"U+0301\": \"DeadEacute\",\n      \"U+0302\": \"DeadCircumflex\",\n      \"U+0303\": \"DeadTilde\",\n      \"U+0304\": \"DeadMacron\",\n      \"U+0306\": \"DeadBreve\",\n      \"U+0307\": \"DeadAboveDot\",\n      \"U+0308\": \"DeadUmlaut\",\n      \"U+030A\": \"DeadAboveRing\",\n      \"U+030B\": \"DeadDoubleacute\",\n      \"U+030C\": \"DeadCaron\",\n      \"U+0327\": \"DeadCedilla\",\n      \"U+0328\": \"DeadOgonek\",\n      \"U+0345\": \"DeadIota\",\n      \"U+3099\": \"DeadVoicedSound\",\n      \"U+309A\": \"DeadSemivoicedSound\",\n\n      // keyIdenfier spec mapping to characters: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      \"Exclamation\": \"!\",\n      \"DoubleQuote\": \"\\\"\",\n      \"Hash\": \"#\",\n      \"Dollar\": \"$\",\n      \"Ampersand\": \"&\",\n      \"LeftParen\": \"(\",\n      \"RightParen\": \")\",\n      \"Asterisk\": \"*\",\n      \"Plus\": \"+\",\n      \"Percent\": \"%\",\n      \"Comma\": \",\",\n      \"HyphenMinus\": \"-\",\n      \"Period\": \".\",\n      \"Solidus\": \"/\",\n      \"Colon\": \":\",\n      \"Semicolon\": \";\",\n      \"LessThan\": \"<\",\n      \"Equals\": \"=\",\n      \"GreaterThan\": \">\",\n      \"QuestionMark\": \"?\",\n      \"At\": \"@\",\n      \"LeftSquareBracket\": \"[\",\n      \"Backslash\": \"\\\\\",\n      \"RightSquareBracket\": \"]\",\n      \"Circumflex\": \"^\",\n      \"Underscore\": \"_\",\n      \"Grave\": \"`\",\n      \"LeftCurlyBracket\": \"{\",\n      \"Pipe\": \"|\",\n      \"RightCurlyBracket\": \"}\",\n      \"Euro\": \"€\",\n      \"InvertedExclamation\": \"¡\",\n\n      // Safari fixes: viewed in local tests\n      \"U+0010\": \"ContextMenu\"\n    }\n  };\n}\n\nexport type NormalizedKeyboardEvent =\n  {\n    type: string;\n    target: EventTarget | null;\n    key: string;\n    code: string;\n    ctrlKey: boolean;\n    altKey: boolean;\n    location: number;\n    shiftKey: boolean;\n    metaKey: boolean;\n    repeat: boolean;\n    isComposing: boolean;\n  };\n\n/**\n     Returns normalized keyboard event properties, following the current W3C UI Events spec\n *\n    @param evt - Keyboard event\n    @returns Normalized keyboard event data\n */\nexport function normalizeKeyboardEventData(evt: KeyboardEvent): NormalizedKeyboardEvent {\n  // event.key is supported from chrome:51, edge, ff: 29, ie: 9, not in safari\n  // event.keyIdentifier in chrome 26-54, opera 15-41, safara: 5.1\n  // safari doesn't provide either in keypress events, use U+evt.keyCode (uppercase 4-byte hex)\n\n  let key = evt.key;\n  if (!keydata)\n    initKeyMapping();\n  if (keydata.mapping[key])\n    key = keydata.mapping[key];\n  else if (key.startsWith(\"U+\")) // U+xxxx code\n    key = String.fromCodePoint(parseInt(key.substring(2), 16));\n\n  // Seen in chrome 56.0.2924.76 on linux, numpad '.' without numlock returns key \"\\u0000\"\n  if (evt.key === \"\\u0000\" && evt.code === \"NumpadDecimal\")\n    key = \".\";\n\n  return (\n    {\n      type: evt.type,\n      target: evt.target,\n      key: key,\n      code: evt.code || \"Unidentified\",\n      ctrlKey: evt.ctrlKey,\n      altKey: evt.altKey,\n      location: evt.location,\n      shiftKey: evt.shiftKey,\n      metaKey: evt.metaKey,\n      repeat: evt.repeat,\n      isComposing: evt.isComposing\n    });\n}\n\n/**\n * Stop, fully, an event\n *\n * @param event - Event to stop\n */\nexport function stop(event: Event) {\n  event.preventDefault();\n  event.stopImmediatePropagation();\n}\n\n/** Add an event listener to HTMLElements inside a document (which allows us to ensure that 'target' is a HTMLElement for easier typings) */\nexport function addDocEventListener<CurrentTargetType extends HTMLElement, Type extends keyof HTMLElementEventMap>(node: CurrentTargetType, type: Type, listener: (this: CurrentTargetType, ev: DocEvent<HTMLElementEventMap[Type], CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\n\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void {\n  node.addEventListener(type, listener as EventListener, options);\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/dompack\" {\n}\n\n/* This is our public api */\nexport { flagUIBusy, setupBusyModal } from './busy';\nexport type { UIBusyLock, BusyModalEvent } from './busy';\nexport { dispatchCustomEvent, dispatchDomEvent, fireModifiedEvents, changeValue, stop, addDocEventListener } from '../../../modules/system/js/dompack/src/events';\nexport type { DocEvent, DomEventOptions } from '../../../modules/system/js/dompack/src/events';\nexport { qS, qR, qSA, isFormControl, isEditControl, isElement, isHTMLElement, isSVGElement, getRelativeBounds, getLang } from './tree';\nexport type { FormControlElement, Rect } from './tree';\nexport { isDomReady, onDomReady } from '../../../modules/system/js/dompack/src/tree';\nexport { create, jsxcreate, jsxfragment } from '../../../modules/system/js/dompack/src/create';\nexport { focus, register, registerMissed } from '../../../modules/system/js/dompack/src/components';\nexport type { TakeFocusEvent } from '../../../modules/system/js/dompack/src/components';\nexport { getLocal, setLocal, getSession, setSession, listCookies, getCookie, setCookie, deleteCookie, listLocalKeys, listSessionKeys } from './storage';\nexport { loadImage, loadScript, loadCSS } from \"./preload\";\nexport { getBrowser, isMultiSelectKey, isCopyKey } from './browser';\nexport type { KeyAttributeValue, UserAgentInfo, Platform, Device } from './browser';\n\n/** @deprecated As 'Lock' conflicts, in WH5.4+ you can safely switch to UIBusyLock */\nimport type { UIBusyLock } from './busy';\nexport type Lock = UIBusyLock;\n","\n/* Regex to identify dimensionless style sttributes. copied from old version of preact/src/constants.js (MIT)\n   meant to capture:\n  { boxFlex:1, boxFlexGroup:1, columnCount:1, fillOpacity:1, flex:1, flexGrow:1,\n    flexPositive:1, flexShrink:1, flexNegative:1, fontWeight:1, lineClamp:1, lineHeight:1,\n    opacity:1, order:1, orphans:1, strokeOpacity:1, widows:1, zIndex:1, zoom:1\n*/\nconst IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;\n\nexport { qS, qSA } from '@webhare/dompack/src/tree.ts';\n\nfunction generateInsertList(nodes: Array<string | Node>) {\n  if (nodes.length === 1)\n    return typeof nodes[0] === 'string' ? document.createTextNode(nodes[0]) : nodes[0];\n\n  const frag = document.createDocumentFragment();\n  nodes.forEach(node => frag.appendChild(typeof node === 'string' ? document.createTextNode(node) : node));\n  return frag;\n}\n\n/** @deprecated Use node.matches() */\nexport function matches(node: Element, selector: string): boolean {\n  //only invoke 'matches' if it exists. it *should* but past versions of dompack.matches would check for it too (and thus not fail if you passed in a string instead of a Node)\n  return node.matches?.(selector);\n}\n/** @deprecated Use node.closest() */\nexport function closest(node: Element, selector: string) {\n  if (node.closest)\n    return node.closest(selector);\n  //TODO: Warn about out-of-date browser?\n  let testNode: Element | null = node;\n  for (; testNode && !matches(testNode, selector); testNode = testNode.parentElement)\n    /*iterate*/;\n  return testNode;\n}\n//implements contains. TODO we only really need this on IE11, which doesn't consider a text node a child, we can probably fall back to native elsewhere ?\n/** @deprecated Use node.contains() */\nexport function contains(ancestor: Node, child: Node) {\n  if (ancestor.contains)\n    return ancestor.contains(child);\n  //TODO: Warn about out-of-date browser?\n  for (let testNode: Node | null = child; testNode; testNode = testNode.parentNode)\n    if (testNode === ancestor)\n      return true;\n  return false;\n}\n//insert a range of nodes before a node: https://dom.spec.whatwg.org/#dom-childnode-before\n/** @deprecated Use node.before() */\nexport function before(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.before) {\n    node.before(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node);\n}\n//insert a range of nodes after a node: https://dom.spec.whatwg.org/#dom-childnode-after\n/** @deprecated Use node.after() */\nexport function after(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.after) {\n    node.after(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node.nextSibling);\n}\n//replace node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-replacewith\n/** @deprecated Use node.replaceWith() */\nexport function replaceWith(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.replaceWith) {\n    node.replaceWith(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.replaceChild(generateInsertList(nodes), node);\n}\n//remove node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-remove\n/** @deprecated Use node.remove() */\nexport function remove(node: ChildNode) {\n  if (node.remove) {\n    node.remove();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.removeChild(node);\n}\n//insert nodes at start: https://dom.spec.whatwg.org/#dom-parentnode-prepend\n/** @deprecated Use node.prepend() */\nexport function prepend(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.prepend) {\n    node.prepend(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.insertBefore(generateInsertList(nodes), node.firstChild);\n}\n//insert nodes at end: https://dom.spec.whatwg.org/#dom-parentnode-append\n/** @deprecated Use node.append() */\nexport function append(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.append) {\n    node.append(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.appendChild(generateInsertList(nodes));\n}\n\n/**\n * Toggle a single class\n *\n * @param node - Node to modify\n * @param classname - Class to toggle\n * @param settoggle - true to enable, false to disable, undefined to toggle\n * @deprecated Just use classList.toggle on the node itself\n */\n/** @deprecated Use classList.toggle() */\nexport function toggleClass(node: Element, classname: string, settoggle?: boolean) {\n  if (arguments.length === 2) //in old dompack, 2 argument version toggled and 3 argument version toggled off. match that behavior\n    node.classList.toggle(classname);\n  else\n    node.classList.toggle(classname, settoggle);\n}\n\n/**\n     Toggle classes in a node\n *\n    @param node - Node which classes to toggle\n    @param toggles - Object, all keys will be added/removed based on the truthyness of their values\n */\nexport function toggleClasses(node: Element, toggles: { [key: string]: boolean }) {\n  if (typeof (toggles) !== \"object\")\n    throw new Error(\"Expected an object with keys as classnames\");\n  Object.keys(toggles).forEach(key => node.classList[toggles[key] ? \"add\" : \"remove\"](key));\n}\n\n/* remove the contents of an existing node */\n/** @deprecated Use node.replaceChildren() */\nexport function empty(node: Element) {\n  if (node.replaceChildren) {\n    node.replaceChildren();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  while (node.lastChild)\n    node.removeChild(node.lastChild);\n}\n\nexport function isDomReady() {\n  //ensure no domready events can run if there will never be a dom\n  return typeof document !== \"undefined\" && (document.readyState === \"interactive\" || document.readyState === \"complete\");\n}\n\n/* run the specified function 'on ready'. adds to DOMContentLoaded if dom is not ready yet. Exceptions/rejections from the ready handler will not be fatal to the rest of code execution */\nexport function onDomReady(callback: () => unknown | Promise<unknown>) {\n  if (isDomReady()) {\n    try {\n      void callback(); //Ignore unhandled rejections\n    } catch (e) { // We don't want our caller to 'stop' due to a domready exception as its usually the toplevel initialization code, so log the exception ourselves\n      void Promise.reject(new Error(\"Synchronous onDomReady handler failed\", { cause: e })); //Let it propagate as a standard unhandled rejection\n    }\n  } else\n    document.addEventListener(\"DOMContentLoaded\", () => void callback());\n}\n\n//parse JSON data, throw with more info on parse failure\nexport function getJSONAttribute<T>(node: Element, attributename: string): T | null {\n  try {\n    if (node.hasAttribute(attributename))\n      return JSON.parse(node.getAttribute(attributename) as string);\n  } catch (e) {\n    console.error(\"JSON parse failure on attribute '\" + attributename + \"' of node\", node);\n    throw e;\n  }\n  return null;\n}\n\n/**\n     Get the base URI of the current document. IE11 doesn't implement document.baseURI\n *\n    @param doc - Document to query. Defaults to window.document\n    @deprecated Use document.baseURI\n */\nexport function getBaseURI(doc: Document | undefined) {\n  if (!doc)\n    doc = window.document;\n  if (doc.baseURI)\n    return doc.baseURI;\n\n  const base = doc.querySelector('base');\n  if (base && base.href)\n    return base.href;\n  return doc.URL;\n}\n\n/**\n     Sets multiple styles on a node, automatically adding 'px' to numbers when appropriate\n    (can be used as replacement for Mootools .setStyles)\n *\n * @param node - Node to update\n * @param value - Styles to set\n */\nexport function setStyles(node: HTMLElement, value?: string | { [key: string]: string | number }) {\n  if (!value)\n    node.style.cssText = '';\n  else if (typeof value === 'string')\n    node.style.cssText = value || '';\n  else {\n    for (const [key, propvalue] of Object.entries(value)) {\n      // for numbers, add 'px' if the constant isn't dimensionless (eg zIndex)\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we don't know which keys will be set\n      (node.style as any)[key] = typeof value[key] === 'number' && IS_NON_DIMENSIONAL.test(key) === false\n        ? propvalue + 'px'\n        : propvalue;\n    }\n  }\n}\n","import { append, setStyles } from './tree';\n\n// This will assign the `any` type to the list of accepted attributes for elements constructed via JSX syntax.\ndeclare global {\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  namespace JSX {\n    interface IntrinsicElements {\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      [eleName: string]: any;\n    }\n  }\n}\n\ntype CreateAttributes = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [key: string]: any;\n  on?: {\n    [key in keyof GlobalEventHandlersEventMap]?: (evt: GlobalEventHandlersEventMap[key]) => void;\n  };\n};\n\ntype CreateElementFunction = (attributes: CreateAttributes, _1?: null, _2?: null) => HTMLElement;\n\nfunction flattenArray<T>(list: T[]): T[] {\n  return list.reduce((acc: T[], elt) => acc.concat(Array.isArray(elt) ? flattenArray(elt) : elt), []);\n}\n\nfunction setClassName(node: Element, value?: string | string[] | { [key: string]: boolean }) {\n  if (!value)\n    node.className = '';\n  else if (typeof value === 'string')\n    node.className = value || '';\n  else if (Array.isArray(value))\n    node.className = value.filter(elt => elt && typeof elt === 'string').join(\" \");\n  else if (typeof value === \"object\") {\n    let str = \"\";\n    Object.keys(value).forEach((key, idx) => { if (value[key]) str += (idx ? \" \" : \"\") + key; });\n    node.className = str;\n  }\n}\n\n/**\n     Matches non-first uppercase characters\n    (when the second char is uppercases, the first char is passed too)\n */\nconst MATCH_UPCASE = /([A-Z])/g;\nconst MATCH_DASH_AND_CHAR = /-([a-zA-Z])/g;\n\n/**\n Convert a camelCased identifier to a dashed string\n *\n * @param value - identifier to convert\n */\nexport function toDashed(value: string) {\n  if (value)\n    return (value.substring(0, 1) + value.substring(1).replace(MATCH_UPCASE, \"-$1\")).toLowerCase();\n  return \"\";\n}\n\n/**\n Convert a dashed string to a camelCase identifier\n *\n * @param value - identifier to convert\n */\nexport function toCamel(value: string) {\n  return value.replace(MATCH_DASH_AND_CHAR, (_, match_1) => match_1.toUpperCase());\n}\n\nfunction attrHasBooleanValue(propname: string) {\n  return ['disabled', 'checked', 'selected', 'readonly', 'multiple', 'ismap'].includes(propname);\n}\n\nexport function createElement(elementname: string, attributes?: CreateAttributes, toattrs?: boolean) {\n  const node = document.createElement(elementname);\n  if (attributes) {\n    Object.keys(attributes).forEach(attrname => {\n      if (attrname === 'events')\n        throw new Error(\"Use 'on' instead of 'events' in dompack.create\");\n      if (attrname === 'styles')\n        throw new Error(\"Use 'style' instead of 'styles' in dompack.create\");\n      if (attrname === 'children') {\n        // allow null 'children' property for jsxcreate, property delete is detrimental to performance.\n        if (attributes[attrname])\n          throw new Error(\"Use 'childNodes' instead of 'children' in dompack.create\");\n        return;\n      }\n\n      const value = attributes[attrname];\n\n      if (attrname === 'on') //create event listeners\n        return void Object.keys(value).forEach(eventname => node.addEventListener(eventname, value[eventname], false));\n      else if (attrname.startsWith(\"on\"))\n        return void node.addEventListener(toDashed(attrname.substring(2)), value, false);\n\n      if (attrname === \"className\" || attrname === \"class\") {\n        if (node.className) // already modified the class?\n          throw new Error(\"Specify either 'className' or 'class' to dompack.create, but not both\");\n        setClassName(node, value);\n        return;\n      }\n\n      if (attrname === 'style')\n        return void setStyles(node, value);\n\n      if (attrname === 'dataset') //explicitly assign\n        return void Object.assign(node[attrname], value);\n\n      if (attrname === 'childNodes') //append as children\n        return void append(node, ...attributes.childNodes.filter((child: Node | string | number | boolean | null) => child !== null && child !== true && child !== false && child !== undefined));\n\n      if (toattrs && attrHasBooleanValue(attrname)) {\n        if (value)\n          node.setAttribute(attrname, \"\");\n        else\n          node.removeAttribute(attrname);\n        return;\n      }\n\n      if (toattrs && !attrname.startsWith(\"prop\")) {\n        if (value !== null && value !== undefined) {\n          if (value && typeof value === \"object\")\n            throw new Error(\"Cannot store non-null objects in attributes, use a property starting with 'prop'\");\n          node.setAttribute(attrname, attributes[attrname]);\n        }\n      } else {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we don't know which keys will be set\n        (node as any)[attrname] = attributes[attrname];\n      }\n    });\n  }\n  return node;\n}\n\n/* create elements. sets properties (not attributes!) immediately.\n   everything inside 'on' is added as an addEventListener without capture\n   everything inside 'childNodes' is appended to the node. nulls are ignored inside childNodes\n\n   Examples:\n   domtools.create(\"input\", { type:\"file\", className: \"myupload\", style: { display: \"none\" }));\n\n*/\nexport function create<K extends keyof HTMLElementTagNameMap>(elementname: K, attributes?: CreateAttributes, children?: Array<Node | string>): HTMLElementTagNameMap[K];\nexport function create(elementname: string, attributes?: CreateAttributes, children?: Array<Node | string>): HTMLElement;\n\nexport function create(elementname: string, attributes?: CreateAttributes, children?: Array<Node | string>) {\n  const el = createElement(elementname, attributes, false);\n  if (children?.length)\n    el.append(...children);\n  return el;\n}\n\n/** Function to create for jsx, create elements directly (instead of virtual dom nodes).\n\n    import * as dompack from 'dompack';\n\n    /* \\@jsx dompack.jsxcreate *\\/\n    /* \\@jsxFrag dompack.jsxfragment *\\/\n    your code\n\n    @param element - Name of the element to create\n    @param childNodes - Any child nodes to add immediately\n*/\nexport function jsxcreate<K extends keyof HTMLElementTagNameMap>(element: K, attributes: CreateAttributes, ...childNodes: Array<Node | string | number>): HTMLElementTagNameMap[K];\nexport function jsxcreate(element: string | CreateElementFunction, attributes: CreateAttributes, ...childNodes: Array<Node | string | number>): HTMLElement;\n\nexport function jsxcreate(element: string | CreateElementFunction, attributes: CreateAttributes, ...childNodes: Array<Node | string | number>): HTMLElement {\n  // Ensure attributes\n  attributes = attributes || {};\n  // Flatten childnodes arrays, convert numbers to strings. Also support children property (React uses that)\n  let parts: Array<Node | string | number> = (attributes.childNodes || []).concat(attributes.children || []).concat(childNodes);\n  if (attributes.children)\n    attributes.children = null;\n  parts = flattenArray(parts);\n  parts = parts.map((elt) => typeof elt === \"number\" ? String(elt) : elt);\n  // Create the element\n  attributes.childNodes = parts;\n  if (typeof element === \"function\")\n    return element(attributes, null, null);\n  return createElement(element, attributes, true);\n}\n\nexport function jsxfragment(inp: Node): DocumentFragment {\n  const frag = document.createDocumentFragment();\n  frag.append(...inp.childNodes);\n  return frag;\n}\n","import * as domtree from './tree';\nimport * as domevents from './events';\n\nexport type TakeFocusEvent = CustomEvent<{ options?: FocusOptions }>;\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:takefocus\": TakeFocusEvent;\n  }\n}\n\ntype RegistrationHandler<E extends Element = HTMLElement> = (node: E, index?: number) => void;\ntype ComponentRegistration<E extends Element = HTMLElement> =\n  {\n    selector: string;\n    handler: RegistrationHandler<E>;\n    index: number;\n    num: number;\n    afterdomready: boolean;\n  };\n\nconst components: Array<ComponentRegistration<Element>> = [];\nconst map = new WeakMap();\n\n//is a node completely in the dom? if we can find a sibling anywhere, it must be closed\nfunction isNodeCompletelyInDom(node: Element | null) {\n  for (; node; node = node.parentElement)\n    if (node.nextSibling)\n      return true;\n  return false;\n}\nfunction processRegistration<E extends Element>(item: E, reg: ComponentRegistration<E>, domready: boolean) {\n  if (!domready && !isNodeCompletelyInDom(item))\n    return; //not safe to register\n\n  if (!map.has(item))\n    map.set(item, [reg.num]);\n  else {\n    const list = map.get(item);\n    if (list.includes(reg.num))\n      return;\n    list.push(reg.num);\n  }\n  reg.handler(item, reg.index++); //note: if an exception is reported from Object.handler,\n}\nfunction applyRegistration<E extends Element>(reg: ComponentRegistration<E>, startnode?: Element) {\n  const domready = domtree.isDomReady();\n  if (reg.afterdomready && !domready)\n    return;\n\n  const items = Array.from((startnode || document).querySelectorAll(reg.selector)) as E[];\n  if (startnode?.matches(reg.selector))\n    items.unshift(startnode as E); //if startnode matches it has to be an E\n\n  items.forEach(item => {\n    try {\n      processRegistration<E>(item, reg, domready);\n    } catch (e) {\n      console.error(\"Exception handling registration of\", item, \"for rule\", reg.selector);\n      console.log(\"Registration\", reg);\n      if (e instanceof Error) {\n        console.log(e, e.stack);\n        if (window.onerror) {\n          // Send to onerror to trigger exception reporting\n          try {\n            // @ts-expect-error: fileName, lineNumber and columnNumber are non-standard\n            window.onerror(e.message, e.fileName || \"\", e.lineNumber || 1, e.columNumber || 1, e);\n          } catch (e2) { }\n        }\n      } else\n        console.log(e);\n    }\n  });\n}\n\n/* A focus implementation that allows the node to intercept focused, allowing eg\n   radio/checkbox replacements to redirect focus but also explicitly preventing\n   focus of a disabled element\n   Returns true when the focus operation was successfull or handled by an event handler.\n   @param node Node to focus\n   @param options.preventScroll Prevent scroll to focused element\n*/\nexport function focus(node: Element, options?: FocusOptions) {\n  if (!domevents.dispatchCustomEvent(node, 'dompack:takefocus', { bubbles: true, cancelable: true, detail: { options } }))\n    return true;\n\n  if (typeof (node as HTMLElement).focus !== \"function\" || (node as HTMLInputElement).disabled)\n    return false;\n\n  (node as HTMLInputElement).focus(options);\n  return true;\n}\n\n/**\n * @param node - Node to show\n * @param options - Scroll options\n * @deprecated invoke scrollIntoView directly  on the nodes\n */\nexport function scrollIntoView(node: Element, options?: ScrollIntoViewOptions) {\n  node.scrollIntoView(options);\n  return true;\n}\n\n/**\n    Register a component for auto-initialization.\n\n    @param selector - Selector the component must match\n    @param handler - Handler\n    @param options - Any unrecognized options are passed to the handler\n\n    The handler will be invoked with two parameters\n    - the node to register\n    - the index of the node (a unique counter for this selector - first is 0)\n */\n\nexport function register<E extends Element = HTMLElement>(selector: string, handler: RegistrationHandler<E>, options?: { afterdomready: boolean }) {\n  const newreg: ComponentRegistration<E> =\n  {\n    selector: selector,\n    handler: handler,\n    index: 0,\n    num: components.length,\n    afterdomready: !options || options.afterdomready\n  };\n  if (components.length === 0 && !domtree.isDomReady()) //first component... we'll need a ready handler\n    domtree.onDomReady(() => registerMissed());\n\n  components.push(newreg as ComponentRegistration<Element>);\n  applyRegistration(newreg);\n}\n\n// register any components we missed on previous scans\nexport function registerMissed(startnode?: Element) {\n  const todo = components.slice(0);\n  todo.forEach(item => applyRegistration(item, startnode));\n}\n","import { buildCookieHeader, type CookieOptions } from '@webhare/dompack/src/cookiebuilder';\nimport { escapeRegExp, parseTyped, stringify } from '@webhare/std';\n\nconst backup: {\n  sessionStorage?: Record<string, string>;\n  localStorage?: Record<string, string>;\n} = {};\ntype BrowserStorage = keyof typeof backup;\n\nexport function listCookies() {\n  return document.cookie.split(';').map(cookie => {\n    const parts = cookie.split('=');\n    return { name: decodeURIComponent(parts[0].trim()), value: decodeURIComponent(parts[1] || '') };\n  });\n}\n\nexport function setCookie(key: string, value: string, options?: CookieOptions) {\n  document.cookie = buildCookieHeader(key, value, options);\n}\n\nexport function getCookie(key: string): string | null {\n  const value = document.cookie.match('(?:^|;)\\\\s*' + escapeRegExp(key) + '=([^;]*)');\n  return (value) ? decodeURIComponent(value[1]) : null;\n}\n\nexport function deleteCookie(key: string, options?: CookieOptions) {\n  setCookie(key, '', { ...options, duration: -1, expires: undefined });\n}\n\nfunction get(storage: BrowserStorage, key: string): unknown | null {\n  let foundvalue: string | undefined | null = backup[storage]?.[key];\n  if (foundvalue) //if it's in the backups storage encoding can't fail either\n    return parseTyped(foundvalue);\n\n  try {\n    foundvalue = window[storage].getItem(key);\n    if (foundvalue)\n      return parseTyped(foundvalue);\n  } catch (e) {\n    //we ignore parse failures\n  }\n  return null;\n}\n\nfunction set(storage: BrowserStorage, key: string, value: unknown) {\n  const tostore = value !== null && value !== undefined ? stringify(value, { typed: true }) : null;\n  try {\n    if (tostore !== null)\n      window[storage].setItem(key, tostore);\n    else\n      window[storage].removeItem(key);\n    return;\n  } catch (e) {\n    //ignore\n  }\n\n  const store = (backup[storage] ||= {});\n  if (tostore !== null)\n    store[key] = tostore;\n  else\n    delete store[key];\n}\n\nexport function getSession<T>(key: string): T | null {\n  return get(\"sessionStorage\", key) as T | null;\n}\nexport function setSession<T>(key: string, value: T | null) {\n  set(\"sessionStorage\", key, value);\n}\nexport function getLocal<T>(key: string): T | null {\n  return get(\"localStorage\", key) as T | null;\n}\nexport function setLocal<T>(key: string, value: T | null) {\n  set(\"localStorage\", key, value);\n}\nexport function listSessionKeys() {\n  try {\n    return Object.keys(window.sessionStorage);\n  } catch (e) {\n    return Object.keys(backup.sessionStorage || {});\n  }\n}\nexport function listLocalKeys() {\n  try {\n    return Object.keys(window.localStorage);\n  } catch (e) {\n    return Object.keys(backup.localStorage || {});\n  }\n}\n","/** Load an image\n * @param imgsrc - The image source URL\n * @returns A promise resolving to the image node\n */\nexport function loadImage(imgsrc: string): Promise<HTMLImageElement> {\n  return new Promise((resolve, reject) => {\n    const img = new Image;\n    img.onload = () => {\n      resolve(img);\n    };\n    img.onerror = reject;\n    img.src = imgsrc;\n  });\n}\n\n/** Load a JavaScript file and add it to the DOM\n * @param scriptsrc - The script source URL\n * @param options.module - Load as module\n * @returns A promise resolving to the script node\n */\nexport function loadScript(scriptsrc: string, options?: { module?: boolean; doc?: Document }): Promise<HTMLScriptElement> {\n  return new Promise((resolve, reject) => {\n    const doc = options?.doc ?? document;\n    const scripttag = doc.createElement('script');\n    scripttag.onload = () => {\n      resolve(scripttag);\n    };\n    scripttag.onerror = reject;\n    scripttag.src = scriptsrc;\n    if (options?.module)\n      scripttag.type = \"module\";\n\n    doc.querySelector('head,body')?.appendChild(scripttag);\n  });\n}\n\n/** Load a CSS file and add it to the DOM\n * @param src - The CSS source URL\n * @returns A promise resolving to the link node\n*/\nexport function loadCSS(src: string, options?: { doc?: Document }): Promise<HTMLLinkElement> {\n  const doc = options?.doc ?? document;\n  const element = doc.createElement('link');\n  element.type = 'text/css';\n  element.rel = 'stylesheet';\n  element.href = src;\n\n  const retval = new Promise<HTMLLinkElement>((resolve, reject) => {\n    element.onload = () => resolve(element);\n    element.onerror = reject;\n  });\n\n  doc.querySelector('head,body')?.appendChild(element);\n  return retval;\n}\n","/* Identify devices for the purpose of analytics/tracing\n   NOT a library for feature detection!\n   Originally based on Mootools.Browser\n*/\n\nexport type Platform = \"windows\" | \"ios\" | \"webos\" | \"android\" | \"linux\" | \"mac\" | \"other\";\nexport type Device = \"desktop\" | \"mobile\" | \"tablet\" | \"\";\n\n/** Valid KeyboardEvent.key values (next to 'plain' keys)\n    This list was built from https://www.w3.org/TR/uievents-key/\n    using `console.log([...new Set([...document.querySelectorAll(\".key-table-key .key\")].map(_ => _.textContent))].toSorted().join(' | '))`\n*/\nexport type KeyAttributeValue = \"AVRInput\" | \"AVRPower\" | \"Accept\" | \"Again\" | \"AllCandidates\" | \"Alphanumeric\" | \"Alt\" | \"AltGraph\" | \"AppSwitch\" | \"ArrowDown\" | \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"Attn\" | \"AudioBalanceLeft\" | \"AudioBalanceRight\" | \"AudioBassBoostDown\" | \"AudioBassBoostToggle\" | \"AudioBassBoostUp\" | \"AudioFaderFront\" | \"AudioFaderRear\" | \"AudioSurroundModeNext\" | \"AudioTrebleDown\" | \"AudioTrebleUp\" | \"AudioVolumeDown\" | \"AudioVolumeMute\" | \"AudioVolumeUp\" | \"Backspace\" | \"BrightnessDown\" | \"BrightnessUp\" | \"BrowserBack\" | \"BrowserFavorites\" | \"BrowserForward\" | \"BrowserHome\" | \"BrowserRefresh\" | \"BrowserSearch\" | \"BrowserStop\" | \"Call\" | \"Camera\" | \"CameraFocus\" | \"Cancel\" | \"CapsLock\" | \"ChannelDown\" | \"ChannelUp\" | \"Clear\" | \"Close\" | \"ClosedCaptionToggle\" | \"CodeInput\" | \"ColorF0Red\" | \"ColorF1Green\" | \"ColorF2Yellow\" | \"ColorF3Blue\" | \"ColorF4Grey\" | \"ColorF5Brown\" | \"Compose\" | \"ContextMenu\" | \"Control\" | \"Convert\" | \"Copy\" | \"CrSel\" | \"Cut\" | \"DVR\" | \"Dead\" | \"Delete\" | \"Dimmer\" | \"DisplaySwap\" | \"Eisu\" | \"Eject\" | \"End\" | \"EndCall\" | \"Enter\" | \"EraseEof\" | \"Escape\" | \"ExSel\" | \"Execute\" | \"Exit\" | \"F1\" | \"F10\" | \"F11\" | \"F12\" | \"F2\" | \"F3\" | \"F4\" | \"F5\" | \"F6\" | \"F7\" | \"F8\" | \"F9\" | \"FavoriteClear0\" | \"FavoriteClear1\" | \"FavoriteClear2\" | \"FavoriteClear3\" | \"FavoriteRecall0\" | \"FavoriteRecall1\" | \"FavoriteRecall2\" | \"FavoriteRecall3\" | \"FavoriteStore0\" | \"FavoriteStore1\" | \"FavoriteStore2\" | \"FavoriteStore3\" | \"FinalMode\" | \"Find\" | \"Fn\" | \"FnLock\" | \"GoBack\" | \"GoHome\" | \"GroupFirst\" | \"GroupLast\" | \"GroupNext\" | \"GroupPrevious\" | \"Guide\" | \"GuideNextDay\" | \"GuidePreviousDay\" | \"HangulMode\" | \"HanjaMode\" | \"Hankaku\" | \"HeadsetHook\" | \"Help\" | \"Hibernate\" | \"Hiragana\" | \"HiraganaKatakana\" | \"Home\" | \"Hyper\" | \"Info\" | \"Insert\" | \"InstantReplay\" | \"JunjaMode\" | \"KanaMode\" | \"KanjiMode\" | \"Katakana\" | \"Key11\" | \"Key12\" | \"LastNumberRedial\" | \"LaunchApplication1\" | \"LaunchApplication2\" | \"LaunchCalendar\" | \"LaunchContacts\" | \"LaunchMail\" | \"LaunchMediaPlayer\" | \"LaunchMusicPlayer\" | \"LaunchPhone\" | \"LaunchScreenSaver\" | \"LaunchSpreadsheet\" | \"LaunchWebBrowser\" | \"LaunchWebCam\" | \"LaunchWordProcessor\" | \"Link\" | \"ListProgram\" | \"LiveContent\" | \"Lock\" | \"LogOff\" | \"MailForward\" | \"MailReply\" | \"MailSend\" | \"MannerMode\" | \"MediaApps\" | \"MediaAudioTrack\" | \"MediaClose\" | \"MediaFastForward\" | \"MediaLast\" | \"MediaNextTrack\" | \"MediaPause\" | \"MediaPlay\" | \"MediaPlayPause\" | \"MediaPreviousTrack\" | \"MediaRecord\" | \"MediaRewind\" | \"MediaSkipBackward\" | \"MediaSkipForward\" | \"MediaStepBackward\" | \"MediaStepForward\" | \"MediaStop\" | \"MediaTopMenu\" | \"MediaTrackNext\" | \"MediaTrackPrevious\" | \"Meta\" | \"MicrophoneToggle\" | \"MicrophoneVolumeDown\" | \"MicrophoneVolumeMute\" | \"MicrophoneVolumeUp\" | \"ModeChange\" | \"NavigateIn\" | \"NavigateNext\" | \"NavigateOut\" | \"NavigatePrevious\" | \"New\" | \"NextCandidate\" | \"NextFavoriteChannel\" | \"NextUserProfile\" | \"NonConvert\" | \"Notification\" | \"NumLock\" | \"OnDemand\" | \"Open\" | \"PageDown\" | \"PageUp\" | \"Pairing\" | \"Paste\" | \"Pause\" | \"PinPDown\" | \"PinPMove\" | \"PinPToggle\" | \"PinPUp\" | \"Play\" | \"PlaySpeedDown\" | \"PlaySpeedReset\" | \"PlaySpeedUp\" | \"Power\" | \"PowerOff\" | \"PreviousCandidate\" | \"Print\" | \"PrintScreen\" | \"Process\" | \"Props\" | \"RandomToggle\" | \"RcLowBattery\" | \"RecordSpeedNext\" | \"Redo\" | \"RfBypass\" | \"Romaji\" | \"STBInput\" | \"STBPower\" | \"Save\" | \"ScanChannelsToggle\" | \"ScreenModeNext\" | \"ScrollLock\" | \"Select\" | \"Settings\" | \"Shift\" | \"SingleCandidate\" | \"Soft1\" | \"Soft2\" | \"Soft3\" | \"Soft4\" | \"SpeechCorrectionList\" | \"SpeechInputToggle\" | \"SpellCheck\" | \"SplitScreenToggle\" | \"Standby\" | \"Subtitle\" | \"Super\" | \"Symbol\" | \"SymbolLock\" | \"TV\" | \"TV3DMode\" | \"TVAntennaCable\" | \"TVAudioDescription\" | \"TVAudioDescriptionMixDown\" | \"TVAudioDescriptionMixUp\" | \"TVContentsMenu\" | \"TVDataService\" | \"TVInput\" | \"TVInputComponent1\" | \"TVInputComponent2\" | \"TVInputComposite1\" | \"TVInputComposite2\" | \"TVInputHDMI1\" | \"TVInputHDMI2\" | \"TVInputHDMI3\" | \"TVInputHDMI4\" | \"TVInputVGA1\" | \"TVMediaContext\" | \"TVNetwork\" | \"TVNumberEntry\" | \"TVPower\" | \"TVRadioService\" | \"TVSatellite\" | \"TVSatelliteBS\" | \"TVSatelliteCS\" | \"TVSatelliteToggle\" | \"TVTerrestrialAnalog\" | \"TVTerrestrialDigital\" | \"TVTimer\" | \"Tab\" | \"Teletext\" | \"Undo\" | \"Unidentified\" | \"VideoModeNext\" | \"VoiceDial\" | \"WakeUp\" | \"Wink\" | \"Zenkaku\" | \"ZenkakuHankaku\" | \"ZoomIn\" | \"ZoomOut\" | \"ZoomToggle\";\n\nexport type UserAgentInfo =\n  {\n    /** Browser name, eg 'chrome' or 'firefox' */\n    name: string;\n    /** Browser numeric version (eg 97) */\n    version: number;\n    /** Platform the browser is running on (eg 'windows') */\n    platform: Platform;\n    /** Type of device (eg 'desktop' or 'tablet' for an iPad) */\n    device: Device;\n    /** platform-browsername-version eg ios-safari-11 */\n    triplet: string;\n  };\n\nexport function parseUserAgent(ua: string): UserAgentInfo {\n  ua = ua.toLowerCase();\n\n  // chrome is included in the edge UA, so need to check for edge first, before checking if it's chrome.\n  // safari is included in the miuibrowser UA, so need to check for miuibrowser first, before checking if it's safari.\n  let UA: RegExpMatchArray | null = ua.match(/(edge|miuibrowser)[\\s/:]([\\w\\d.]+)/);\n  if (!UA)\n    UA = ua.match(/(opera|ie|firefox|chrome|trident|crios|version)[\\s/:]([\\w\\d.]+)?.*?(safari|(?:rv[\\s/:]|version[\\s/:])([\\w\\d.]+)|$)/);\n  if (!UA) { //try ios 11.4.1\n    UA = ua.match(/; cpu os ([\\d]+)/);\n    if (UA)\n      UA = ['', 'safari', UA[1]];\n  }\n  if (!UA)\n    UA = ['', 'unknown', \"0\"];\n\n  if (UA[1] === 'trident') {\n    UA[1] = 'ie';\n    if (UA[4]) UA[2] = UA[4];\n  } else if (UA[1] === 'crios') {\n    UA[1] = 'chrome';\n  }\n\n  let platform = ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || ua.match(/mac|win|linux/) || ['other'])[0];\n  if (platform === 'win')\n    platform = 'windows';\n\n  const name = (UA[1] === 'version') ? UA[3] : UA[1];\n  const version = parseInt((UA[1] === 'opera' && UA[4]) ? UA[4] : UA[2]);\n  const device = ua.match(/ipad/) ? 'tablet' : ['ios', 'webos', 'android'].includes(platform) ? 'mobile' : ['mac', 'windows', 'linux'].includes(platform) ? 'desktop' : '';\n\n  return {\n    name,\n    version,\n    platform: platform as Platform,\n    device,\n    triplet: platform + '-' + name + '-' + version\n  };\n}\n\n/**\n * Is the native 'multiselect' modifier for this platform pressed? (Cmd for Mac, Ctrl for Windows/Linux)\n *\n * @param event - Event to check\n */\nexport function isMultiSelectKey(event: KeyboardEvent | MouseEvent): boolean {\n  return getBrowser().platform === 'mac' ? event.metaKey : event.ctrlKey;\n}\n\n/**\n * Is the native 'copy' modifier for this platform pressed?\n *\n * @param event - Event to check\n */\nexport function isCopyKey(event: KeyboardEvent | MouseEvent): boolean {\n  return getBrowser().platform === 'mac' ? event.altKey : event.ctrlKey;\n}\n\nlet browser: Readonly<UserAgentInfo> | undefined;\n\n/** Get browser information */\nexport function getBrowser(): Readonly<UserAgentInfo> {\n  browser ||= Object.freeze(parseUserAgent(globalThis.navigator?.userAgent || \"\"));\n  //Offer this as a function to improve treeshakability\n  return browser;\n}\n\n//CSS Query used to find valid submittors\nexport const submitselector = 'input[type=submit],input[type=image],button[type=submit],button:not([type])';\n//Must match possible types returned by the submitselector\nexport type SubmitSelectorType = HTMLInputElement | HTMLButtonElement;\n","import { isHTMLElement } from \"@webhare/dompack\";\nimport type { CMSConfig } from \"@mod-system/js/internal/generation/gen_misc_ts\";\n\nlet config: CMSConfig | undefined;\n\nfunction forwardPublisherNavigation(event: Event) {\n  /* we watch for clicks.. as we only want to update the Publisher's selection for user triggered actions (otherwise we'd\n     start navigation in response to JS or internal link autoredirects) */\n  if (!isHTMLElement(event.target) || !config?.interfaceServers)\n    return;\n\n  const navaction = event.target.closest<HTMLAnchorElement>('a[href]');\n  if (!navaction)\n    return;\n\n  const desturl = navaction.href;\n  if (desturl.split('#')[0] !== location.href.split('#')[0]) { //it's actual navigation...\n    for (const origin of config.interfaceServers)\n      if (origin.startsWith(document.referrer || ''))\n        try {\n          window.top?.postMessage({ type: \"webhare-navigation\", location: desturl }, origin);\n        } catch (ignore) {\n          //ignore crossdomain errors\n        }\n  }\n}\n\nasync function configureForCMS() {\n  try {\n    const res = await fetch(\"/.wh/ea/config/cms.json\");\n    config = await res.json();\n  } catch (e) {\n    console.log(\"Failed to get CMS configuration\", e);\n    return;\n  }\n  window.addEventListener(\"click\", forwardPublisherNavigation);\n}\n\nif (typeof window !== \"undefined\" && window !== window.top) { //if we're in an iframe, we may be running in WebHare and need to forward navigation events\n  //we have no way to detect whether we're in a WebHare iframe or a 3rd party iframe. assume it's webhare and grab the interface servers\n  void configureForCMS();\n}\n","import { getBrowser } from \"@webhare/dompack\";\nimport { generateRandomId } from \"@webhare/std\";\nimport { debugFlags, isLive } from \"@webhare/env\";\n\ninterface PxlEventDetails {\n  event: string;\n  data: PxlEventData;\n  options: PxlOptions;\n  isAlt: boolean;\n}\n\nexport type PxlEvent = CustomEvent<PxlEventDetails>;\n\nexport type PxlEventData = {\n  [K in `ds_${string}` | `db_${string}` | `dn_${string}`]: (K extends `ds_${string}` ? string :\n    (K extends `db_${string}` ? boolean :\n      (K extends `dn_${string}` ? number : never)))\n};\n\nexport interface PxlOptions {\n  /** Override pi (pxlId) to control or anonymize user ids*/\n  pi?: string | undefined;\n  /**  Base url to which to send PXL events. Defaults to \"/.wh/ea/pxl/\". */\n  url: string;\n  /**  Sample rate for the alternative record url as a fraction of the number of events, for example, setting it to 1/100 sends 1 in 100 events to the alternative record url. Defaults to 0 (no sampling). */\n  altSampleRate: number;\n  /**  Alternative record url. Defaults to \"/.wh/ea/pxl/alt/\". */\n  altUrl: string;\n  /** The number of days the user id is valid. Defaults to 30. */\n  sessionExpiration: number; //TODO if we ever camel this, also add 'Days' to the name\n  /** Set to true to omit some browser context fields (\"bu\", \"bs\" and \"bp\"). This option can\n      be used to reduce the length of the pxl url. Defaults to false. */\n  noBrowser: boolean;\n  /** Node responsible for generating this event (if not set, 'window' is assumed). Used for the event handlers */\n  node?: HTMLElement;\n  /** Send pixels as beacons */\n  beacon: boolean;\n  /** Callback to execute once pixel is sent */\n  onComplete?: () => void;\n}\n\n//event names must match isValidModuleScopedName, but we won't do the module name checks here. also isValidModuleScopedName lives in @webhare/services so..\nconst eventname_regex = /^([a-z0-9][-a-z0-9_]*[a-z0-9]):([a-z0-9][-.a-z0-9_]*[a-z0-9])$/;\nconst datakey_regex = /^(ds_[0-9a-z_]+)|(dn_[0-9a-z_]+)|(db_[0-9a-z_]+)$/;\n/*TODO: Not sure yet what the new maximum URL length will be\nconst max_data_length = 600; // The maximum number of bytes stored for the request*/\nconst max_sessionid_age = 30;\n\nlet globalOptions: Partial<PxlOptions> | undefined;\n\nlet pagesession: string | undefined; //current page session id (used to track multiple events from single page)\nlet useAltRecordURL = false; //send events for this page to the altrecordurl\nlet seqnr = 0;\n\nlet pxlUserId: string | undefined, pxlSessionId: string | undefined;\n\nfunction buildOptions(options: Partial<PxlOptions> | undefined): PxlOptions {\n  return {\n    url: \"/.wh/ea/pxl/\",\n    altSampleRate: 0,\n    altUrl: \"/.wh/ea/pxl/alt/\",\n    sessionExpiration: max_sessionid_age,\n    noBrowser: false,\n    beacon: false,\n    ...globalOptions,\n    ...options\n  };\n}\n\n/** Set global pxl options\n    @param options - Option updates\n*/\nexport function setPxlOptions(options: Partial<PxlOptions> | null) {\n  globalOptions = { ...globalOptions, ...options };\n\n  if (globalOptions.altUrl && globalOptions.altSampleRate) {\n    useAltRecordURL = Math.random() < globalOptions.altSampleRate;\n    if (debugFlags.pxl)\n      console.log(`[pxl] using altrecordurl for ${100 * globalOptions.altSampleRate}% of pageloads, this session is sent to the ${useAltRecordURL ? \"alternative\" : \"normal\"} url`);\n  } else\n    useAltRecordURL = false;\n}\n\nfunction pxlFailed(errormessage: string, ...params: unknown[]) {\n  console.error('[pxl] ' + errormessage, ...params);\n  if (!isLive)\n    throw new Error(errormessage); //big errors on test servers\n  return null;\n}\n\nexport function makePxlURL(baseurl: string, eventname: string, data?: PxlEventData | null, options?: Partial<PxlOptions>) {\n  options = { ...globalOptions, ...options };\n\n  if (typeof eventname !== \"string\")\n    return pxlFailed(`Invalid eventname name '${eventname}', expected string, got ${typeof eventname}`);\n  if (!eventname_regex.test(eventname))\n    return pxlFailed(`Invalid eventname name '${eventname}', must be a valid module:event name`);\n  if (data && typeof data !== \"object\")\n    return pxlFailed(`Invalid data, expected object, got ${typeof data}`);\n\n  if (!pagesession)\n    pagesession = generateRandomId();\n\n  //not using URL object, simplifies support of relative URLs\n  const url = typeof document !== \"undefined\" ? new URL(baseurl, document.baseURI) : new URL(baseurl);\n  url.searchParams.set(\"pe\", eventname);\n  url.searchParams.set(\"pp\", pagesession);\n  url.searchParams.set(\"pc\", String(++seqnr));\n  url.searchParams.set(\"ps\", getPxlSessionId());\n  url.searchParams.set(\"pi\", options?.pi ?? getPxlId());\n\n  if (options.altSampleRate)\n    url.searchParams.set(\"pr\", String(options.altSampleRate));\n\n  const browser = getBrowser();\n  url.searchParams.set(\"bt\", browser.triplet);\n  if (browser.device)\n    url.searchParams.set(\"bd\", browser.device);\n\n  if (typeof document !== \"undefined\") {\n    if (document.documentElement.dataset.whOb)\n      url.searchParams.set(\"ob\", document.documentElement.dataset.whOb.substring(0, 20));\n    if (document.location)\n      url.searchParams.set(\"bl\", document.location.href.substring(0, 1000));\n    if (document.referrer)\n      url.searchParams.set(\"br\", document.referrer.substring(0, 1000));\n\n    if (!options.noBrowser) {\n      url.searchParams.set(\"bu\", window.navigator.userAgent.substring(0, 300));\n      if (window.screen.width && window.screen.height)\n        url.searchParams.set(\"bs\", `${window.screen.width}x${window.screen.height}`);\n      if (window.devicePixelRatio)\n        url.searchParams.set(\"bp\", String(window.devicePixelRatio));\n    }\n  }\n\n  if (data) {\n    for (const [name, value] of Object.entries(data)) {\n      const test = datakey_regex.exec(name);\n      if (!test)\n        return pxlFailed(`Invalid data field name '${name}', should be ds_XXX, dn_XXX or db_XXX with X consisting of characters in the range 0 - 9, a - z or an underscore`);\n\n      const type = typeof value;\n\n      if (test[1]) { // String\n        if (value && type !== \"string\")\n          return pxlFailed(`Invalid value type '${type}', expected 'string' for field '${name}'`);\n\n        url.searchParams.set(name, value as string || '');\n      } else if (test[2]) { // Number\n        if (value && type !== \"number\")\n          return pxlFailed(`Invalid value type '${type}', expected 'number' for field '${name}'`);\n\n        url.searchParams.set(name, String(value) || '0');\n      } else if (test[3]) { // Boolean\n        if (value && type !== \"boolean\")\n          return pxlFailed(`Invalid value type '${type}', expected 'boolean' for field '${name}'`);\n\n        url.searchParams.set(name, value ? \"true\" : \"false\");\n      }\n    }\n  }\n  return url;\n}\n\nexport function getPxlId(): string {\n  if (!pxlUserId) {\n    try {\n      const timestampvar = localStorage.getItem(\"_wh.ti\");\n      if (timestampvar && new Date(timestampvar) > new Date) { //not expired yet\n        pxlUserId = localStorage.getItem(\"_wh.pi\") || undefined;\n        if (pxlUserId && debugFlags.pxl)\n          console.log(`[pxl] Using id ${pxlUserId} from localStorage`);\n      }\n      pxlUserId ||= generateRandomId();\n      const sessionExpireDays = (globalOptions?.sessionExpiration ?? max_sessionid_age);\n      const expiration = new Date(Date.now() + sessionExpireDays * 24 * 60 * 60 * 1000);\n      localStorage.setItem(\"_wh.pi\", pxlUserId);\n      localStorage.setItem(\"_wh.ti\", expiration.toISOString());\n    } catch {\n      pxlUserId ||= generateRandomId();\n    }\n  }\n  return pxlUserId;\n}\n\nexport function getPxlSessionId() {\n  if (!pxlSessionId) {\n    try {\n      pxlSessionId = sessionStorage[\"_wh.ps\"];\n      pxlSessionId ||= generateRandomId();\n      sessionStorage[\"_wh.ps\"] = pxlSessionId;\n    } catch { //privacy mode? just (re)try to generate an id\n      pxlSessionId ||= generateRandomId();\n    }\n  }\n  return pxlSessionId;\n}\n\n/** Send a pxl event\n    @param event - Event type, preferably in the format 'module:event'\n    @param data - Event data. A map whose keys must start with either ds_ (string), db_ (boolean) or dn_ (number)\n*/\nexport function sendPxlEvent(event: string, data?: PxlEventData | null, options?: Partial<PxlOptions>) {\n  const finaloptions = buildOptions(options);\n  const baseurl = useAltRecordURL ? finaloptions.altUrl : finaloptions.url;\n\n  if (debugFlags.pxl)\n    console.log(`[pxl] Event '${event}'`, data);\n\n  // Add the pxl event to the url. We wrap it in async() for simpler code but we won't force our callers to await us, they rarely want to\n  (async () => {\n    const url = makePxlURL(baseurl, event, data, finaloptions);\n    if (!url)\n      return;\n\n    if (finaloptions.beacon && typeof navigator !== \"undefined\" && navigator.sendBeacon) {\n      navigator.sendBeacon(url);\n      return; //as beacons don't return anything per definition, we can stop here\n    }\n\n    if (debugFlags.pxl)\n      console.log(`[pxl] Pinging pxl '${url}'`);\n\n    // Load the pxl file using fetch\n    const fetchRes = await fetch(url, { mode: \"no-cors\", method: \"HEAD\", credentials: \"same-origin\", cache: \"no-store\", keepalive: true });\n    if (fetchRes.type === \"opaque\") { //we can't verify cross-server requests\n      if (debugFlags.pxl)\n        console.log(`[pxl] Assuming succesful pxl event '${event}'`);\n      return;\n    }\n    if (!fetchRes.ok) {\n      console.error(`[pxl] Failed to send pxl event '${event}'`, fetchRes);\n      return;\n    }\n\n    if (finaloptions.onComplete) //if we care about completion, we'll explicitly wait for the body to come in\n      await fetchRes.text(); //this will throw if the request failed, so we can skip the next check\n\n    if (debugFlags.pxl)\n      console.log(`[pxl] Successfully sent pxl event '${event}'`);\n  })().catch((error: Error) => {\n    console.error(`[pxl] Error while sending pxl event '${event}'`, error);\n  }).finally(() => {\n    finaloptions.onComplete?.(); //any exception here we'll keep uncaught\n  });\n}\n","/* This is our public api. Any direct inclusions from src/.... not mentioned here are not a stable API\n*/\n\nexport { createDeferred } from '@webhare/std';\nexport { flagUIBusy, getRelativeBounds, type Rect } from '@webhare/dompack';\nexport {\n  dispatchCustomEvent, dispatchDomEvent, fireModifiedEvents, changeValue, normalizeKeyboardEventData,\n  stop\n} from './src/events';\nexport {\n  qS, qSA, contains, closest, matches,\n  empty, isDomReady, onDomReady, getJSONAttribute,\n  before, after, replaceWith, remove, prepend, append,\n  toggleClass, toggleClasses,\n  setStyles,\n  getBaseURI,\n} from './src/tree';\nexport { create, jsxcreate, jsxfragment } from './src/create';\nexport { focus, register, registerMissed, scrollIntoView } from './src/components';\nexport type { TakeFocusEvent } from './src/components';\n\nimport { debugFlags } from \"@webhare/env\";\n\n/** @deprecated You should use debugFlags from \\@webhare/env */\nexport const debugflags = debugFlags;\n","import * as dompack from '@webhare/dompack';\n\n//NOTE: Do *NOT* load @webhare/frontend or we enforce the new CSS reset!\nimport { navigateTo, type NavigateInstruction } from \"@webhare/env\";\nexport { frontendConfig as config } from '@webhare/frontend/src/init';\n\nexport function executeSubmitInstruction(instr: NavigateInstruction, options?: {\n  ismodal?: boolean;\n  iframe?: HTMLIFrameElement;\n}) {\n  if (!instr)\n    throw Error(\"Unknown instruction received\");\n\n  options = { ismodal: true, ...options };\n  //Are there any cirumstances where you would want to reelase this lock?\n  dompack.flagUIBusy({ modal: options.ismodal || false });\n  navigateTo(instr);\n}\n","let appname: string;\n\nexport function setAppName(newappname: string) {\n  appname = newappname;\n}\n\nexport function getAppName() {\n  return appname;\n}\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n    return (idbProxyableTypes ||\n        (idbProxyableTypes = [\n            IDBDatabase,\n            IDBObjectStore,\n            IDBIndex,\n            IDBCursor,\n            IDBTransaction,\n        ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n    return (cursorAdvanceMethods ||\n        (cursorAdvanceMethods = [\n            IDBCursor.prototype.advance,\n            IDBCursor.prototype.continue,\n            IDBCursor.prototype.continuePrimaryKey,\n        ]));\n}\nconst transactionDoneMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n    const promise = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            request.removeEventListener('success', success);\n            request.removeEventListener('error', error);\n        };\n        const success = () => {\n            resolve(wrap(request.result));\n            unlisten();\n        };\n        const error = () => {\n            reject(request.error);\n            unlisten();\n        };\n        request.addEventListener('success', success);\n        request.addEventListener('error', error);\n    });\n    // This mapping exists in reverseTransformCache but doesn't exist in transformCache. This\n    // is because we create many promises from a single IDBRequest.\n    reverseTransformCache.set(promise, request);\n    return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n    // Early bail if we've already created a done promise for this transaction.\n    if (transactionDoneMap.has(tx))\n        return;\n    const done = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            tx.removeEventListener('complete', complete);\n            tx.removeEventListener('error', error);\n            tx.removeEventListener('abort', error);\n        };\n        const complete = () => {\n            resolve();\n            unlisten();\n        };\n        const error = () => {\n            reject(tx.error || new DOMException('AbortError', 'AbortError'));\n            unlisten();\n        };\n        tx.addEventListener('complete', complete);\n        tx.addEventListener('error', error);\n        tx.addEventListener('abort', error);\n    });\n    // Cache it for later retrieval.\n    transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n    get(target, prop, receiver) {\n        if (target instanceof IDBTransaction) {\n            // Special handling for transaction.done.\n            if (prop === 'done')\n                return transactionDoneMap.get(target);\n            // Make tx.store return the only store in the transaction, or undefined if there are many.\n            if (prop === 'store') {\n                return receiver.objectStoreNames[1]\n                    ? undefined\n                    : receiver.objectStore(receiver.objectStoreNames[0]);\n            }\n        }\n        // Else transform whatever we get back.\n        return wrap(target[prop]);\n    },\n    set(target, prop, value) {\n        target[prop] = value;\n        return true;\n    },\n    has(target, prop) {\n        if (target instanceof IDBTransaction &&\n            (prop === 'done' || prop === 'store')) {\n            return true;\n        }\n        return prop in target;\n    },\n};\nfunction replaceTraps(callback) {\n    idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n    // Due to expected object equality (which is enforced by the caching in `wrap`), we\n    // only create one new func per func.\n    // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n    // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n    // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n    // with real promises, so each advance methods returns a new promise for the cursor object, or\n    // undefined if the end of the cursor has been reached.\n    if (getCursorAdvanceMethods().includes(func)) {\n        return function (...args) {\n            // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n            // the original object.\n            func.apply(unwrap(this), args);\n            return wrap(this.request);\n        };\n    }\n    return function (...args) {\n        // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n        // the original object.\n        return wrap(func.apply(unwrap(this), args));\n    };\n}\nfunction transformCachableValue(value) {\n    if (typeof value === 'function')\n        return wrapFunction(value);\n    // This doesn't return, it just creates a 'done' promise for the transaction,\n    // which is later returned for transaction.done (see idbObjectHandler).\n    if (value instanceof IDBTransaction)\n        cacheDonePromiseForTransaction(value);\n    if (instanceOfAny(value, getIdbProxyableTypes()))\n        return new Proxy(value, idbProxyTraps);\n    // Return the same value back if we're not going to transform it.\n    return value;\n}\nfunction wrap(value) {\n    // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n    // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n    if (value instanceof IDBRequest)\n        return promisifyRequest(value);\n    // If we've already transformed this value before, reuse the transformed value.\n    // This is faster, but it also provides object equality.\n    if (transformCache.has(value))\n        return transformCache.get(value);\n    const newValue = transformCachableValue(value);\n    // Not all types are transformed.\n    // These may be primitive types, so they can't be WeakMap keys.\n    if (newValue !== value) {\n        transformCache.set(value, newValue);\n        reverseTransformCache.set(newValue, value);\n    }\n    return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n    const request = indexedDB.open(name, version);\n    const openPromise = wrap(request);\n    if (upgrade) {\n        request.addEventListener('upgradeneeded', (event) => {\n            upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n        });\n    }\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event.newVersion, event));\n    }\n    openPromise\n        .then((db) => {\n        if (terminated)\n            db.addEventListener('close', () => terminated());\n        if (blocking) {\n            db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n        }\n    })\n        .catch(() => { });\n    return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n    const request = indexedDB.deleteDatabase(name);\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event));\n    }\n    return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n    if (!(target instanceof IDBDatabase &&\n        !(prop in target) &&\n        typeof prop === 'string')) {\n        return;\n    }\n    if (cachedMethods.get(prop))\n        return cachedMethods.get(prop);\n    const targetFuncName = prop.replace(/FromIndex$/, '');\n    const useIndex = prop !== targetFuncName;\n    const isWrite = writeMethods.includes(targetFuncName);\n    if (\n    // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n    !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n        !(isWrite || readMethods.includes(targetFuncName))) {\n        return;\n    }\n    const method = async function (storeName, ...args) {\n        // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n        const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n        let target = tx.store;\n        if (useIndex)\n            target = target.index(args.shift());\n        // Must reject if op rejects.\n        // If it's a write operation, must reject if tx.done rejects.\n        // Must reject with op rejection first.\n        // Must resolve with op value.\n        // Must handle both promises (no unhandled rejections)\n        return (await Promise.all([\n            target[targetFuncName](...args),\n            isWrite && tx.done,\n        ]))[0];\n    };\n    cachedMethods.set(prop, method);\n    return method;\n}\nreplaceTraps((oldTraps) => ({\n    ...oldTraps,\n    get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n    has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nconst advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];\nconst methodMap = {};\nconst advanceResults = new WeakMap();\nconst ittrProxiedCursorToOriginalProxy = new WeakMap();\nconst cursorIteratorTraps = {\n    get(target, prop) {\n        if (!advanceMethodProps.includes(prop))\n            return target[prop];\n        let cachedFunc = methodMap[prop];\n        if (!cachedFunc) {\n            cachedFunc = methodMap[prop] = function (...args) {\n                advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));\n            };\n        }\n        return cachedFunc;\n    },\n};\nasync function* iterate(...args) {\n    // tslint:disable-next-line:no-this-assignment\n    let cursor = this;\n    if (!(cursor instanceof IDBCursor)) {\n        cursor = await cursor.openCursor(...args);\n    }\n    if (!cursor)\n        return;\n    cursor = cursor;\n    const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);\n    ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);\n    // Map this double-proxy back to the original, so other cursor methods work.\n    reverseTransformCache.set(proxiedCursor, unwrap(cursor));\n    while (cursor) {\n        yield proxiedCursor;\n        // If one of the advancing methods was not called, call continue().\n        cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());\n        advanceResults.delete(proxiedCursor);\n    }\n}\nfunction isIteratorProp(target, prop) {\n    return ((prop === Symbol.asyncIterator &&\n        instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||\n        (prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore])));\n}\nreplaceTraps((oldTraps) => ({\n    ...oldTraps,\n    get(target, prop, receiver) {\n        if (isIteratorProp(target, prop))\n            return iterate;\n        return oldTraps.get(target, prop, receiver);\n    },\n    has(target, prop) {\n        return isIteratorProp(target, prop) || oldTraps.has(target, prop);\n    },\n}));\n\nexport { deleteDB, openDB, unwrap, wrap };\n","import * as idb from 'idb';\n\nexport async function deleteDatabase(appname: string) {\n  try {\n    await idb.deleteDB('pwadb-' + appname);\n  } catch (e) {\n    console.log(\"Deletedb failed\", e);\n  }\n}\n\nexport async function clearCache(appname: string) {\n  try {\n    const cache = await window.caches.open(\"pwacache-\" + appname);\n    for (const key of await cache.keys())\n      await cache.delete(key);\n  } catch (e) {\n    console.error(\"Cache cleanup failed\", e);\n    throw e;\n  }\n}\n\nexport async function unregisterServiceWorkers() {\n  const currentregistrations = await navigator.serviceWorker.getRegistrations();\n  for (const reg of currentregistrations)\n    await reg.unregister();\n}\n","import * as dompack from 'dompack';\nimport \"./debugmenu.scss\";\nimport * as settings from './settings';\nimport * as maintenance from './maintenance';\n\nlet debuglayer: HTMLDivElement | undefined;\n\nasync function clearCache() {\n  await maintenance.clearCache(settings.getAppName());\n}\nasync function restartApp() {\n  location.reload();\n}\nasync function unregisterServiceWorkers() {\n  await maintenance.unregisterServiceWorkers();\n}\n\nexport function runPWADebugMenu() {\n  if (debuglayer)\n    debuglayer.remove();\n\n  debuglayer =\n    <div id=\"pwadebugmenu\">\n      <h1>PWA Debugger</h1>\n      <div>\n        <button type=\"button\" onClick={clearCache}>Clear cache</button><br />\n        <button type=\"button\" onClick={unregisterServiceWorkers}>unregisterServiceWorkers</button><br />\n        <button type=\"button\" onClick={restartApp}>Restart application</button><br />\n      </div>\n    </div>;\n\n  document.body.appendChild(debuglayer!);\n}\n\n\nlet activatetouches: number[] = [];\nlet expectnumtouches = Infinity;\nlet expecttaptime = Infinity;\n\nfunction testMenuTap(event: Event) {\n  activatetouches.push(Date.now());\n  activatetouches = activatetouches.slice(-expectnumtouches);\n\n  const totaltime = (activatetouches.at(-1)! - activatetouches[0]);\n  if (totaltime) { // fast enough\n    if (activatetouches.length > 1)\n      dompack.stop(event);\n\n    if (activatetouches.length === expectnumtouches)\n      runPWADebugMenu();\n  }\n}\n\ndompack.register(\"[data-app-activatedebugmenu]\", node => {\n  const settings2 = node.dataset.appActivatedebugmenu?.split(':');\n  if (!settings2)\n    return;\n\n  expectnumtouches = parseInt(settings2[0]);\n  expecttaptime = parseInt(settings2[1]);\n  if (!expecttaptime || !expectnumtouches)\n    return;\n\n  node.addEventListener(\"touchstart\", testMenuTap);\n  node.addEventListener(\"click\", testMenuTap);\n});\n","/* @mod-platform/js/concepts/ is for constants, concepts, simple support APIs, but heavily shared stuff\n   that we can't find a place for (yet) in the jssdk\n\n  this file holds stuff needed to run or build the frontend */\n\n/** Get base url for assetpacks\n * @param assetpack - assetpack name, like \"platform:frontend\"\n * @returns The base URL for the assetpack, starting with and ending in a slash\n*/\nexport function getAssetPackBase(assetpack: string) {\n  return `/.wh/ea/ap/${assetpack.replace(':', '.')}/`;\n}\n\n/** The path to devkit's debug package */\nexport const devkitDebugPath = `/.wh/mod/devkit/public/debug.mjs`;\n","/* eslint-disable no-alert */ //TODO avoid the alert()s though. require dompack dialogs?\n\nimport * as pxl from \"@mod-consilio/js/pxl\";\nimport * as dompack from 'dompack';\nimport * as whintegration from '@mod-system/js/wh/integration';\nimport './internal/debugmenu';\nimport * as settings from './internal/settings';\nimport { getAssetPackBase } from \"@mod-platform/js/concepts/frontend\";\nimport { navigateTo } from \"@webhare/env\";\nimport type { PublishedPWASSettings, PWACheckVersionResponse } from \"@mod-platform/webfeatures/pwaserviceworker/pwaserviceworker\";\nimport { getFrontendData, getSiteRoot } from \"@webhare/frontend\";\n\nconst appbase = location.href.indexOf(\"?\") > -1 ? location.href.split('?')[0] : location.href.split('#')[0];\n//Pre 6.0 WebHares might still have published as whconfig.obj.pwasettings\nconst pwasettings = getFrontendData(\"platform:pwasettings\", { allowMissing: true }) ?? (whintegration.config.obj as { pwasettings: PublishedPWASSettings }).pwasettings;\nlet didinit = false;\n\n//set up a promise we'll use to signal succesful offline mode\nconst offlinedeferred = Promise.withResolvers<void>();\nlet swregistration: ServiceWorkerRegistration | undefined;\n\nfunction getAppName() {\n  if (pwasettings.appname)\n    return pwasettings.appname; //in WH6.0 (and attempting to backport to at least WH5.9.4) the appname should be published directly\n\n  //we'll assume the webdesignname is the appname\n  //TODO clean this up. designroot is undocumented, appname should be in PWASSettings\n  const settings2 = (whintegration.config as unknown as { designroot: string }).designroot.match(/^\\/.publisher\\/sd\\/([^/]*)\\/([^/]*)\\/$/)!;\n  const module = settings2[1];\n  const webdesign = settings2[2];\n  return module + ':' + webdesign;\n}\n\nfunction sendSWRequestTo(sw: ServiceWorker, type: string, data?: object) {\n  return new Promise((resolve, reject) => {\n    const msg_chan = new MessageChannel();\n    msg_chan.port1.onmessage = event => {\n      if (event.data && event.data.__throw)\n        reject(new Error(event.data.__throw));\n      else\n        resolve(event.data);\n    };\n    // console.log(navigator.serviceWorker);\n    // console.log(navigator.serviceWorker.controller);\n    // navigator.serviceWorker.controller.postMessage({ swrequest: type, data }, [msg_chan.port2]);\n    sw.postMessage({ swrequest: type, data }, [msg_chan.port2]);\n  });\n}\n\n//TODO type the SWRequest protocol properly\nasync function sendSWRequest(type: string, data?: object) {\n  //wait for SW to be available. (waiting for ready isn't safe, it may pick up an already installed SW but doesn't mean that onReady is done\n  await offlinedeferred.promise;\n  if (!swregistration?.active)\n    throw new Error(\"ServiceWorker registration failed\");\n  return sendSWRequestTo(swregistration.active, type, data);\n}\n\nexport async function checkForUpdate(): Promise<PWACheckVersionResponse> {\n  return await sendSWRequest(\"checkversion\", {\n    pwauid: document.documentElement.dataset.whPwaUid,\n    pwafileid: document.documentElement.dataset.whPwaFileid\n  }) as PWACheckVersionResponse;\n}\nexport async function downloadUpdate() {\n  return await sendSWRequest(\"downloadupdate\");\n}\n//install downloaded update now\nexport async function updateApplication() {\n  console.log(\"Reloading to update application\");\n  navigateTo({ type: \"reload\" });\n  return new Promise((resolve, reject) => setTimeout(() => reject(new Error(\"The update failed\")), 20000)); //timeout 20 sec...\n}\n\n\nexport function onReady(initfunction: () => void, options?: {\n  reportusage?: boolean;\n  onAvailableOffline?: () => void;\n  onOfflineFailed?: (e: Error) => void;\n}): void {\n  if (didinit)\n    throw new Error(\"pwalib.onReady should be invoked only once\");\n\n  didinit = true;\n\n  //figure out the base of the app we have to work with\n  if (!location.href.startsWith(getSiteRoot())) {\n    alert(\"You cannot access a PWA app using a URL outside its site.\\n\\nThe WebHare 'preview' is not supported by a PWA\");\n    return;\n  }\n  if (!appbase.endsWith('/')) {\n    //we might redirect deeper.. but this shouldn't happen anyway\n    alert(\"The application base URL must end with a /\");\n    return;\n  }\n\n  if (options?.reportusage) {\n    //determinate app name. we should probably get Versioninfo and webhare/other version numbers too\n    pxl.sendPxlEvent(\"publisher:pwastart\", { ds_appname: settings.getAppName() });\n  }\n\n  //wait for dompack to be ready...\n  dompack.onDomReady(async function () {\n    //we can now run initialization which can do some basic UI setup\n    initfunction();\n\n    //bind it to user given clalbacks\n    if (options?.onAvailableOffline)\n      offlinedeferred.promise = offlinedeferred.promise.then(() => options.onAvailableOffline!());\n    if (options?.onOfflineFailed) //we need to chain our catch to the new promise above or we risk a \"unhandled rejection\" - https://stackoverflow.com/questions/52409326/unhandled-promise-rejection-despite-catching-the-promise\n      offlinedeferred.promise = offlinedeferred.promise.catch(e => options.onOfflineFailed!(e));\n\n    //and we can start registration\n    if (!(\"serviceWorker\" in navigator)) {\n      offlinedeferred.reject(new Error(\"This browser does not support serviceWorker\"));\n      return;\n    }\n    if (window.isSecureContext === false) {\n      offlinedeferred.reject(new Error(\"This webpage is not running in a secure context (https or localhost)\"));\n      return;\n    }\n\n    const swurl = `${getAssetPackBase(\"platform:pwaserviceworker\")}ap.mjs?app=${encodeURIComponent(settings.getAppName())}`;\n\n    try {\n      swregistration = await navigator.serviceWorker.register(swurl, { scope: appbase });\n\n      if (swregistration.installing) { //detect an installing worker going straight to redundant\n        swregistration.installing.addEventListener(\"statechange\", () => {\n          if (swregistration?.installing?.state === \"redundant\")\n            offlinedeferred.reject(new Error(\"The serviceWorker failed to install\"));\n        });\n      }\n\n      offlinedeferred.resolve(navigator.serviceWorker.ready.then(() => void undefined));\n    } catch (e) {\n      console.log(\"PWA Registration failed\", (e as Error).message);\n      offlinedeferred.reject(e);\n    }\n  });\n}\n\n//inform any serviceworkers that a pwalib app has connected. gives them a chance to watch for forced version checks\nasync function precheckExistingWorkers() {\n  if (!navigator.serviceWorker)\n    return;\n\n  const registrations = await (navigator.serviceWorker.getRegistrations());\n  for (const sw of registrations)\n    if (sw.active && sw.scope === appbase)\n      await sendSWRequestTo(sw.active, 'loading', {\n        pwasettings: pwasettings,\n        pwauid: document.documentElement.dataset.whPwaUid,\n        pwafileid: document.documentElement.dataset.whPwaFileid\n      });\n}\n\nfunction onServiceWorkerMessage(event: MessageEvent) {\n  if (event.data.type === 'forceRefresh') {\n    console.log(\"Reloading because forced by the serice worker\");\n    navigateTo({ type: \"reload\" });\n    return;\n  }\n  if (event.data.type === \"log\") {\n    //@ts-expect-error TODO ugly, cleanup up\n    console[event.data.loglevel](\"[From ServiceWorker] \" + event.data.message);\n    return;\n  }\n  console.error(\"onServiceWorkerMessage\", event.data);\n}\n\nif (pwasettings) { //only activate if pwasettings are present - avoid sideeffects\n  settings.setAppName(getAppName());\n\n  navigator.serviceWorker.addEventListener(\"message\", onServiceWorkerMessage);\n  void precheckExistingWorkers();\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/jsonrpc-client\" {\n}\n\nimport { debugFlags, backendBase } from \"@webhare/env\";\nimport { type StackTrace, parseTrace, prependStackTrace, type PromisifyInterface } from \"@webhare/js-api-tools\";\n\n//just number RPCs globally instead of per server, makes debug ouput more useful\nlet globalseqnr = 0;\n\nexport interface RPCCallOptions {\n  /** Append function name to URLs. Purely for better logging/visibility as the WebHare JSONRPC server will ignore it */\n  addfunctionname?: boolean;\n  /** Custom URL marker */\n  urlappend?: string;\n  /** Call timeout */\n  timeout?: number;\n  /** Abort signal to cancel the RPC */\n  signal?: AbortSignal;\n  /** Retry on 429 */\n  retry429?: boolean;\n  /** Silent - do not log errors */\n  silent?: boolean;\n  /** Debug (Follows 'rpc' debugflag if not explicity specified) */\n  debug?: boolean;\n  /** Wrap result with response info */\n  wrapresult?: boolean;\n  keepalive?: boolean;\n  /** Headers to submit (Eg Authorization) */\n  headers?: Record<string, string>;\n  /** Base URL for service paths */\n  baseUrl?: string;\n  /** Overide fetch credentials option (defaults to same-origin) */\n  credentials?: RequestCredentials;\n}\n\nexport type RequestID = number | string | null;\n\nexport interface JSONRPCBaseResponse {\n  id: RequestID;\n  debug?: {\n    consoleLog: Array<{\n      //TODO this is Serialized<ConsoleLogItem[]> - should probably rename it to SerializedToJSON and move to std or env ?\n      /** Date when console function was called */\n      when: string;\n      /** `console` method that was called (eg 'log') */\n      method: string;\n      /** Logged data */\n      data: string;\n      /** Location of caller */\n      location?: {\n        filename: string;\n        line: number;\n        col: number;\n        func: string;\n      };\n      /** Codecontext */\n      codeContextId?: string;\n    }>;\n  };\n}\n\nexport interface JSONRPCSuccesfulResponse extends JSONRPCBaseResponse {\n  error: null;\n  result: unknown;\n}\n\nexport interface JSONRPCErrorResponse extends JSONRPCBaseResponse {\n  result: null;\n  error: {\n    code: number;\n    message: string;\n    data?: {\n      trace?: StackTrace;\n    };\n  };\n}\n\nexport type JSONRPCResponse = JSONRPCSuccesfulResponse | JSONRPCErrorResponse;\n\nfunction getDebugAppend() {\n  if (typeof window !== \"undefined\" && typeof window.location !== \"undefined\") {\n    const urldebugvar = new URL(window.location.href).searchParams.get(\"wh-debug\");\n    if (urldebugvar)\n      return '?wh-debug=' + encodeURIComponent(urldebugvar);\n  }\n  return '';\n}\n\nclass ControlledCall {\n  client: RPCClient;\n  options: RPCCallOptions;\n  abortcontroller: AbortController;\n  timeout?: number;\n  _callurl: string;\n  _fetchoptions: RequestInit;\n  promise: Promise<unknown>;\n  timedout?: boolean;\n  aborted?: boolean;\n\n  constructor(client: RPCClient, method: string, stack: StackTrace | null, id: number, options: RPCCallOptions, callurl: string, fetchoptions: RequestInit) {\n    this.client = client;\n    this.options = options;\n\n    // if(options.timeout || options.signal) //as long as rpcResolve exists, we'll ALWAYS need to setup a controller\n    {\n      this.abortcontroller = new AbortController;\n      fetchoptions.signal = this.abortcontroller.signal;\n\n      if (options.timeout && options.timeout > 0) {\n        this.timeout = options.timeout;\n        setTimeout(() => this._handleTimeout(), options.timeout);\n      }\n      if (options.signal) {\n        options.signal.addEventListener(\"abort\", () => this._abort());\n      }\n    }\n\n    this._callurl = callurl;\n    this._fetchoptions = fetchoptions;\n\n    const fetchpromise = fetch(this._callurl, this._fetchoptions);\n    this.promise = this._completeCall(method, stack, id, fetchpromise) as Promise<unknown>;\n  }\n  _handleTimeout() {\n    this.timedout = true;\n    this.abortcontroller.abort();\n  }\n  _abort() {\n    this.aborted = true;\n    this.abortcontroller.abort();\n  }\n\n  async _completeCall(method: string, requestStack: StackTrace | null, id: number, fetchpromise: Promise<Response>) {\n    let response;\n    try {\n      for (; ;) { //loop to handle \"429 Conflict\"s\n        response = await fetchpromise;\n        if (response.status === 429 && !(\"retry429\" in this.options && !this.options.retry429) && response.headers.get(\"Retry-After\")) {\n          const retryafter = parseInt(response.headers.get(\"Retry-After\") || \"\");\n          if (this.client.debug)\n            console.warn(`[rpc] We are being throttled (429 Too Many Requests) - retrying after ${retryafter} seconds`);\n\n          await new Promise(resolve => setTimeout(resolve, retryafter * 1000));\n          fetchpromise = fetch(this._callurl, this._fetchoptions);\n          continue;\n        }\n        break;\n      }\n    } catch (exception) {\n      if (this.client.debug)\n        console.log(`[rpc] #${id} Exception invoking '${method}'`, exception);\n\n      if (this.aborted)\n        throw new Error(`RPC Aborted`);\n      else if (this.timedout)\n        throw new Error(`RPC Timeout: timeout was set to ${this.timeout} milliseconds`);\n      else\n        throw new Error(`RPC Failed: exception: ` + exception);\n    }\n\n    let jsonresponse;\n    try {\n      jsonresponse = await response.json() as JSONRPCResponse;\n      if (jsonresponse?.debug) {\n        if (jsonresponse.debug.consoleLog) {\n          for (const logitem of jsonresponse.debug.consoleLog) {\n            //should we log 'when'? it's getting more and more noisy then though....\n            //TODO should we match the remote's method (after validating) or just keep eveyrthing at 'log' ?\n            console.log(`[remote:${logitem.method}] ${logitem.location ? `${logitem.location.filename.split(\"/\").at(-1)}:${logitem.location.line}: ` : ''}${logitem.data}`);\n          }\n        }\n\n        delete jsonresponse.debug; //reduce noise in later logs\n      }\n\n      if (this.client.debug)\n        console.log(`[rpc] #${id} Received response to '${method}'`, jsonresponse);\n    } catch (exception) {\n      if (this.client.debug)\n        console.warn(`[rpc] #${id} Response was not valid JSON`, exception);\n    }\n\n    if (!jsonresponse)\n      throw new Error(\"RPC Failed: Invalid JSON/RPC response received\");\n\n    if (jsonresponse?.error) {\n      const err = new Error(\"RPC Error: \" + (jsonresponse.error.message || \"Unknown error\"));\n      if (jsonresponse.error.data?.trace) {\n        try {\n          prependStackTrace(err, jsonresponse.error.data.trace);\n        } catch (err2) {\n          //ignore stacktrace manipulation error\n        }\n      }\n\n      if (!this.options.silent)\n        this.client._tryLogError(requestStack, err);\n      throw err;\n    }\n\n    if (response.status === 200 && jsonresponse && jsonresponse.id !== id)\n      throw new Error(\"RPC Failed: Invalid JSON/RPC response received\");\n\n    if (this.options.wrapresult) {\n      return {\n        status: response.status,\n        result: jsonresponse.result || null,\n        error: jsonresponse.error || null,\n        retryafter: response.headers.get(\"Retry-After\") ? parseInt(response.headers.get(\"Retry-After\") || \"\") : null\n      };\n    }\n\n    return jsonresponse.result;\n  }\n}\n\n/** Invokes (WebHare) JSON/RPC\n    @param url - URL to invoke (leave empty or pass no parameters at all to callback to the current page)\n    */\nclass RPCClient {\n  url: string;\n  addfunctionname: boolean;\n  urlappend: string;\n  options: RPCCallOptions;\n  whservicematch: RegExpMatchArray | null;\n\n  constructor(url: string, options?: RPCCallOptions) {\n    this.options = {\n      timeout: 0,\n      debug: false,\n      ...options\n    };\n\n    if (!url)\n      throw new Error(`You must specify either a WebHare service name or a full URL`);\n\n    this.url = url;\n    this.whservicematch = this.url.match(/^([a-z0-9_]+):([a-z0-9_]+)$/);\n    //if shorthand syntax is used, we know we're talking to our local webhare. add function names and the profiling flag if needed\n    this.addfunctionname = this.options.addfunctionname !== undefined ? this.options.addfunctionname : Boolean(this.whservicematch);\n    this.urlappend = this.options.urlappend !== undefined ? this.options.urlappend : this.whservicematch ? getDebugAppend() : \"\";\n  }\n\n  get debug() {\n    return this.options.debug || debugFlags.rpc;\n  }\n\n  _tryLogError(requestStack: StackTrace | null, error: Error) {\n    console.group();\n    console.warn(\"RPC failed:\", error);\n    if (requestStack) {\n      console.warn(\"Stack at calling point\");\n      console.log(requestStack);\n    }\n    console.groupEnd();\n  }\n\n  //calculate the final URL. delayed here so services can be created on import (getDefaultRPCBase may require waiting for service.ready)\n  private getURL() {\n    //wh_services are always in the root (and soon inside /.wh)\n    const url = this.whservicematch ? `/wh_services/${this.whservicematch[1]}/${this.whservicematch[2]}` : this.url;\n    if (url.match(/^https?:\\/\\//))\n      return url;\n\n    if (this.options.baseUrl)\n      return new URL(url, this.options.baseUrl).toString();\n    else if (backendBase)\n      return backendBase + (backendBase.endsWith('/') && url.startsWith('/') ? url.substring(1) : url);\n    else\n      throw new Error(`You must set the baseUrl option when using the JSONRPC Client without a full URL outside Webhare`);\n  }\n\n  invoke(method: string, params: unknown[]) {\n    //build the URL, add profiling and function parameters where needed\n    let callurl = this.getURL();\n    if (this.addfunctionname) //simplifies log analysis, ignored by the server\n      callurl += `/${method}`;\n    callurl += this.urlappend;\n\n    const id = ++globalseqnr;\n    let requestStack: StackTrace | null = null;\n\n    if (this.debug) {\n      requestStack = parseTrace(new Error);\n      console.log(`[rpc] #${id} Invoking '${method}'`, params, callurl);\n    }\n\n    const fetchoptions: RequestInit = {\n      method: \"POST\",\n      credentials: this.options.credentials || 'same-origin', //this is the default since 2017-08-25, but Edge pre-18 is still around and will fail here\n      headers: {\n        \"Accept\": \"application/json\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        ...this.options.headers\n      },\n      body: JSON.stringify(\n        {\n          id: id,\n          method: method,\n          params: params || []\n        }),\n      keepalive: Boolean(this.options.keepalive)\n    };\n\n    return new ControlledCall(this, method, requestStack, id, this.options, callurl, fetchoptions).promise;\n  }\n}\n\ntype ServiceBase<T> = {\n  withOptions(options: RPCCallOptions): T & ServiceBase<T>;\n};\n\nclass ServiceProxy<T> {\n  client: RPCClient;\n\n  constructor(client: RPCClient) {\n    this.client = client;\n  }\n\n  get(target: object, prop: string, receiver: unknown) {\n    if (prop === 'withOptions') { //create a withOptions function\n      return (options: RPCCallOptions) => {\n        const newoptions = {\n          ...this.client.options,\n          ...options,\n          headers: { ...this.client.options.headers, ...options.headers }\n        };\n        return createClient<T>(this.client.url, newoptions);\n      };\n    }\n\n    return (...args: unknown[]) => this.client.invoke(prop, args);\n  }\n}\n\n\n/** Creates an async version of the functions in a class\n * @typeParam ServiceType - Type definition of the service class that implements this service.\n*/\ntype ConvertToRPCInterface<ServiceType> = PromisifyInterface<ServiceType, `_${string}` | \"close\" | \"emit\">;\n\n/** Get the client interface type as would be returned by createClient */\nexport type GetClientInterface<Client> = ConvertToRPCInterface<Client> & ServiceBase<ConvertToRPCInterface<Client>>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- If you don't care to type the service, just assume it can do anything\nexport function createClient<Client = any>(servicename: string, options?: RPCCallOptions): GetClientInterface<Client> {\n  const rpcclient = new RPCClient(servicename, options);\n  return new Proxy({}, new ServiceProxy<Client>(rpcclient)) as GetClientInterface<Client>;\n}\n","var UNKNOWN_FUNCTION = '<unknown>';\n/**\n * This parses the different stack traces and puts them into one format\n * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)\n */\n\nfunction parse(stackString) {\n  var lines = stackString.split('\\n');\n  return lines.reduce(function (stack, line) {\n    var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);\n\n    if (parseResult) {\n      stack.push(parseResult);\n    }\n\n    return stack;\n  }, []);\n}\nvar chromeRe = /^\\s*at (.*?) ?\\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\\/|[a-z]:\\\\|\\\\\\\\).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nvar chromeEvalRe = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nfunction parseChrome(line) {\n  var parts = chromeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n\n  var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n  var submatch = chromeEvalRe.exec(parts[2]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line/column number\n    parts[2] = submatch[1]; // url\n\n    parts[3] = submatch[2]; // line\n\n    parts[4] = submatch[3]; // column\n  }\n\n  return {\n    file: !isNative ? parts[2] : null,\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: isNative ? [parts[2]] : [],\n    lineNumber: parts[3] ? +parts[3] : null,\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar winjsRe = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseWinjs(line) {\n  var parts = winjsRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar geckoRe = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nvar geckoEvalRe = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nfunction parseGecko(line) {\n  var parts = geckoRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n  var submatch = geckoEvalRe.exec(parts[3]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line number\n    parts[3] = submatch[1];\n    parts[4] = submatch[2];\n    parts[5] = null; // no column when eval\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: parts[2] ? parts[2].split(',') : [],\n    lineNumber: parts[4] ? +parts[4] : null,\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar javaScriptCoreRe = /^\\s*(?:([^@]*)(?:\\((.*?)\\))?@)?(\\S.*?):(\\d+)(?::(\\d+))?\\s*$/i;\n\nfunction parseJSC(line) {\n  var parts = javaScriptCoreRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[4],\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar nodeRe = /^\\s*at (?:((?:\\[object object\\])?[^\\\\/]+(?: \\[as \\S+\\])?) )?\\(?(.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseNode(line) {\n  var parts = nodeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nexport { parse };\n","import * as stacktrace_parser from \"stacktrace-parser\";\n\nexport type StackTraceItem = {\n  filename: string;\n  line: number;\n  col: number;\n  func: string;\n};\n\nexport type StackTrace = StackTraceItem[];\n\nexport function parseTrace(e: Error): StackTrace {\n  if (!e?.stack)\n    return [];\n\n  const trace = stacktrace_parser.parse(e.stack);\n  return trace.map(i => ({ filename: i.file || \"\", line: i.lineNumber || 1, col: i.column || 1, func: (i.methodName || \"\") }));\n}\n\nexport function getStackTrace(): StackTrace {\n  return parseTrace(new Error()).slice(1);\n}\n\nexport function formatTrace(trace: StackTraceItem[]): string {\n  return trace.map(e =>\n    `    at ${e.func} (${e.filename}:${e.line}:${e.col})`).join(\"\\n\");\n}\n\nexport function prependStackTrace(error: Error, trace: StackTrace) {\n  if (!error.stack)\n    return; //no stack to manipulate\n\n  const stacklines = error.stack?.split(\"\\n\") || [];\n  const tracelines = formatTrace(trace);\n  error.stack = (stacklines[0] ? stacklines[0] + \"\\n\" : \"\") + tracelines + '\\n' + (stacklines.slice(1).join(\"\\n\"));\n  return error;\n}\n","import { levenshteinDistance } from \"@webhare/std\";\n\n/** Find the best match for a string fiven a list of alternatives. Defaults to case insensitive match.\n    @param name - Name to search\n    @param alternatives - Alternatives to choose from\n    @param matchCase - Do a case sensitive compare (defaults to FALSE)\n    @returns Best match or null if none found\n*/\nexport function getBestMatch(name: string, alternatives: readonly string[], { matchCase = false } = {}): string | null {\n  if (!matchCase)\n    name = name.toLowerCase();\n\n  const threshold = name.length < 3 ? 1 : 2;\n  const matches = alternatives.\n    map((value) => ({ value, distance: levenshteinDistance(name, matchCase ? value : value.toLowerCase()) })).\n    filter((match) => match.distance <= threshold).\n    sort((a, b) => a.distance - b.distance);\n\n  return matches[0]?.value || null;\n}\n\n/** Return match info as text to append to the end of a message\n    @param name - Name to search\n    @param alternatives - Alternatives to choose from\n    @param matchCase - Do a case sensitive compare (defaults to FALSE)\n    @returns Returns \", did you mean 'XXX'?\" text if a better match was found, otherwise an empty string\n    @example throw new Error(`${libname} does not export '${name}'${addBestMatch(name, Object.keys(lib))}`);\n\n*/\nexport function addBestMatch(name: string, alternatives: string[], { matchCase = false } = {}): string {\n  const match = getBestMatch(name, alternatives, { matchCase });\n  return match ? `, did you mean '${match}'?` : \"\";\n}\n","import { createClient } from \"@webhare/jsonrpc-client\";\nimport { type NavigateInstruction, navigateTo } from \"@webhare/env\";\nimport * as dompack from '@webhare/dompack';\nimport type { LoginOptions } from \"@webhare/auth/src/identity\";\nimport { rpc } from \"@webhare/rpc\";\n\n//NOTE: Do *NOT* load @webhare/frontend or we enforce the new CSS reset!\nimport { getFrontendData } from '@webhare/frontend/src/init';\nimport { PublicCookieSuffix, type LoginErrorCode, type LoginResult, type LoginTweaks } from \"@webhare/auth/src/shared\";\nimport { parseTyped, toSnakeCase, type ToSnakeCase } from \"@webhare/std\";\nimport type WRDAuthenticationProvider from \"@mod-wrd/js/auth\";\nimport type { OAuth2PromptFlag } from \"@webhare/auth/src/oauth2-client\";\n\n/** WRDAuth configuration */\nexport interface WRDAuthOptions {\n  /** Callback that is invoked after a succesful login. If not set the page will be reloaded. */\n  onLogin?: () => Promise<void> | void;\n}\n\nexport interface PublicAuthData {\n  expiresMs: number;\n  userInfo?: object | null;\n  persistent?: boolean;\n}\n\ndeclare module \"@webhare/frontend\" {\n  interface FrontendDataTypes {\n    \"wrd:auth\": {\n      /** WRDAuth cookiename (used to store userinfo and expiry) */\n      cookiename: string;\n    };\n  }\n}\n\ndeclare global {\n  interface Window {\n    $wh$legacyAuthProvider: WRDAuthenticationProvider;\n    triggerWebHareSSO?: (tag: string, options?: SSOLoginOptions) => Promise<void>;\n  }\n}\n\n/** Current authoptions. undefined if setupWRDAuth hasn't been invoked yet */\nlet authOptions: WRDAuthOptions | undefined;\n\n/** Get current login cookie. If empty, wrdauth is not initialized here */\nfunction getCookieName(): string | null {\n  const settings = getFrontendData(\"wrd:auth\", { allowMissing: true });\n  return settings?.cookiename || null;\n}\n\nfunction getAuthLocalData(): PublicAuthData | null {\n  const c = getCookieName();\n  if (!c)\n    return null;\n\n  try {\n    return parseTyped(dompack.getCookie(c + PublicCookieSuffix)!) as PublicAuthData;\n  } catch {\n    return null;\n  }\n}\n\nasync function submitLoginForm(node: HTMLFormElement, event: SubmitEvent) {\n  if (node.propWhFormhandler)\n    return; //already handled by publisher forms so we'll defer to that\n  dompack.stop(event);\n\n  const username = (node.elements.namedItem(\"login\") as HTMLInputElement)?.value;\n  const password = (node.elements.namedItem(\"password\") as HTMLInputElement)?.value;\n  const site = (node.elements.namedItem(\"site\") as HTMLInputElement)?.value || undefined;\n  const returnto = (node.elements.namedItem(\"returnto\") as HTMLInputElement)?.value || undefined;\n  const persistentlogin = (node.elements.namedItem(\"persistent\") as HTMLInputElement)?.checked;\n  if (!login || !password)\n    throw new Error(`submitLoginForm: required elements login/password not set or missing`);\n\n  using lock = dompack.flagUIBusy({ modal: true });\n  void (lock);\n\n  const loginresult = await login(username, password, {\n    persistent: persistentlogin,\n    site,\n    returnTo: returnto ? new URL(returnto, location.href).toString() : location.href.split('#')[0]\n  });\n  if (loginresult.loggedIn) {\n    refreshLoginStatus();\n    if (loginresult.navigateTo.type === \"redirect\" && loginresult.navigateTo.url.split('#')[0] === location.href.split('#')[0]  //stay on same page\n      && authOptions?.onLogin) {\n\n      if (loginresult.navigateTo.url.includes('#')) //execute any #hash instruction\n        history.replaceState(null, \"\", loginresult.navigateTo.url.substring(loginresult.navigateTo.url.indexOf('#')));\n\n      await authOptions.onLogin();\n    } else {\n      //Reload the page to get the new login status - TODO put this behind a 'login state change' event and allow users to cancel it if they can deal with login/logout on-page\n      console.log(\"Post login redirect\", loginresult.navigateTo);\n      navigateTo(loginresult.navigateTo);\n    }\n  } else if (\"navigateTo\" in loginresult) {\n    console.log(\"Login incomplete, redirecting to\", loginresult.navigateTo);\n    navigateTo(loginresult.navigateTo);\n  } else\n    failLogin(loginresult.error ?? loginresult.code, { code: loginresult.code, data: \"\" }, node); //FIXME restore the code & data members from old wrdauth\n}\n\nfunction refreshLoginStatus() {\n  const loggedIn = isLoggedIn();\n  document.documentElement.classList.toggle(\"wh-wrdauth--isloggedin\", loggedIn);\n\n  window.$wh$legacyAuthProvider?.refresh();\n}\n\n/** Return whether a user's currently logged in */\nexport function isLoggedIn(): boolean {\n  return (getAuthLocalData()?.expiresMs || 0) > Date.now();\n}\n\n/** Setup WRDAuth frontend integration */\nexport function setupWRDAuth(options?: WRDAuthOptions) {\n  if (authOptions)\n    throw new Error(`Duplicate setupWRDAuth call`);\n\n  authOptions = { ...options };\n\n  dompack.register<HTMLFormElement>('form.wh-wrdauth__loginform,form.wh-wrdauth-login__form', node => {\n    node.setAttribute(\"data-wh-wrdauth-attached\", \"\");\n    dompack.addDocEventListener(node, \"submit\", evt => submitLoginForm(node, evt));\n  });\n  dompack.register('.wh-wrdauth__logout', node => {\n    function handleLogoutClick(event: Event) {\n      dompack.stop(event);\n\n      //letting rejections escape - our trigger is generally setup in HTML so there's nothing to catch but uncaught rejection handlers anyway\n      if (node instanceof HTMLAnchorElement && node.href && node.href.split('#')[0] !== location.href.split('#')[0]) { //logout link sending you elsewhere\n        void doLogout().then(() => {\n          console.log(\"Logout complete, redirecting to\", node.href);\n          navigateTo({ type: \"redirect\", url: node.href });\n        });\n      } else {\n        void logout(); //TODO what if the logout only changed the anchor? but what's the usecase for that?\n      }\n    }\n\n    dompack.addDocEventListener(node, \"click\", event => handleLogoutClick(event));\n  });\n\n  dompack.onDomReady(() => {\n    if (\"$wh$wrdauth\" in window) {\n      console.error(\"Both setupWRDAuth from @webhare/frontend and @mod-wrd/js/auth are present in this page. Mixing these is not supported!\");\n    }\n  });\n\n  refreshLoginStatus();\n}\n\nfunction failLogin(message: string, response: { code: LoginErrorCode; data: string }, form: HTMLFormElement) {\n  const evtdetail = {\n    message: message,\n    code: response.code,\n    data: response.data\n  };\n\n  const cancelled = !dompack.dispatchCustomEvent(form || document.documentElement, \"wh:wrdauth-loginfailed\", { bubbles: true, cancelable: true, detail: evtdetail });\n  if (!cancelled) {\n    //TODO depending on error we may need to change a different field?\n    const loginfield = dompack.qR<HTMLInputElement>(form, \"input[name=password]\");\n    loginfield.setCustomValidity(message);\n    // loginfield.reportValidity(); //this actually blocks wh-form error handling from showing the error in-page when so desired\n    loginfield.focus();\n  }\n}\n\n/** Retrieve userinfo if set by onFrontendUserInfo in your WRDAuth customizer */\nexport function getUserInfo<T extends object = object>(): T | null {\n  return isLoggedIn() ? getAuthLocalData()?.userInfo as T | null : null;\n}\n\nfunction getLoginTweaks(): LoginTweaks {\n  const tweaks: LoginTweaks = {\n    lang: dompack.getLang().tag\n  };\n\n  const urlvars = new URL(location.href);\n  if (urlvars.searchParams.has(\"wrdauth_limit_expiry\"))\n    tweaks.limitExpiry = parseInt(urlvars.searchParams.get(\"wrdauth_limit_expiry\") || '0') || undefined;\n\n  return tweaks;\n}\n\n/** Implements the common username/password flows */\nexport async function login(username: string, password: string, options: LoginOptions = {}): Promise<LoginResult> {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  const result = await rpc(\"platform:authservice\").login(username, password, cookieName, dompack.getBrowser().triplet, { ...options, ...getLoginTweaks() });\n  if (result.loggedIn && !getAuthLocalData())\n    throw new Error(\"Login succeeded but no auth data was set in the cookie\");\n\n  return result;\n}\n\n/** Execute and verify cookie clearance to prepare for logging out */\nasync function doLogout() {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  await rpc(\"platform:authservice\").logout(cookieName, dompack.getBrowser().triplet);\n\n  if (getAuthLocalData())\n    throw new Error(\"Logged out but we still have auth data in the cookie\");\n}\n\n/** Logout the current user */\nexport async function logout() {\n  await doLogout();\n  console.log(\"Reloading to process the new logged out status\");\n  navigateTo({ type: \"reload\" }); //TODO put this behind a 'login state change' event\n}\n\nexport interface MyService {\n  startLogin2(urlpath: string, tag: string, options: ToSnakeCase<SSOLoginOptions>): Promise<NavigateInstruction>;\n}\n\ninterface SSOLoginOptions {\n  /** @deprecated use prompt: \"none\" from WH6.0 up */\n  passive?: boolean;\n  /** Set the prompt flag for the authorize request */\n  prompt?: OAuth2PromptFlag;\n}\n\nexport function startSSOLogin(tag: string, options?: SSOLoginOptions): Promise<void> {\n  const client = createClient<MyService>(\"wrd:auth\");\n\n  if (options?.passive)\n    options = { prompt: \"none\", ...options, passive: undefined }; //force prompt to none in passive mode, and remove the passive flag since it doesn't mean anything to the server\n\n  const defer = Promise.withResolvers<void>();\n\n  //Launch SSO login for the current page.\n  //TODO also pass getLoginTweaks() at least to OIDC logins as soon as we've ported this to authservice\n  client.startLogin2(location.pathname + location.search + location.hash, tag, toSnakeCase(options) || {}).then(instr => {\n    //we leave the promise unresolved so any busy layers stay active during the actual redirect\n    //TODO can we have navigateTo detect failed navigations so we can throw ?\n    navigateTo(instr);\n  }).catch((e: Error) => {\n    defer.reject(e);\n  });\n\n  return defer.promise;\n}\n\n/** Configure WebHare external auth buttons (even hidden ones) to listen for bookmarklet login requests */\nexport function setupWebHareSSOTrigger(): void {\n  window.triggerWebHareSSO = startSSOLogin;\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/rpc\" {\n  export interface KnownRPCServices {\n    /* Filled by generated services.ts files */\n  }\n}\n\nimport { debugFlags, backendBase } from \"@webhare/env\";\nimport { type StackTrace, parseTrace, prependStackTrace, type PromisifyInterface } from \"@webhare/js-api-tools\";\nimport { omit, parseTyped, stringify } from \"@webhare/std\";\n\n//Preload interface definitions. To solve this cleaner we would have to do some sort of auto-inject but how to robustly do that accross IDEs/Tscs ?\n\n//@ts-ignore Ignore if it doesn't exist. this line *must* remain a @ts-ignore\nimport type { } from \"@mod-platform/generated/ts/services.ts\";\n//@ts-ignore Ignore if it doesn't exist. this line *must* remain a @ts-ignore\nimport type { } from \"wh:ts/services.ts\";\n\nfunction isAbsolute(url: string) {\n  return url.startsWith(\"http:\") || url.startsWith(\"https:\");\n}\n\nfunction getBaseURL() {\n  if (!backendBase)\n    throw new Error(`You must set the baseUrl option when using the RPC Client outside Webhare`);\n  return isAbsolute(backendBase) ? backendBase : new URL(backendBase, location.origin);\n}\n\nexport interface RPCClientOptions {\n  /** Custom request update. Use to eg. set keepalive or add debug variables to the URL */\n  onBeforeRequest?: (url: URL, requestInit: RequestInit & { headers: Headers }) => void;\n  /** Response callback. Use this if you need to capture details on the incoming respones. May be invoked multiple times per request, eg due to 429 errors! */\n  onResponse?: (response: Response) => void;\n  /** Call timeout */\n  timeout?: number;\n  /** Abort signal to cancel the RPC */\n  signal?: AbortSignal;\n  /** Retry on 429 */\n  retry429?: boolean;\n  /** Silent - do not log errors */\n  silent?: boolean;\n  /** Debug (Follows 'rpc' debugflag if not explicity specified) */\n  debug?: boolean;\n  /** Headers to submit (Eg Authorization) */\n  headers?: Record<string, string>;\n  /** Base URL for service paths */\n  baseUrl?: string;\n}\n\n/** RPC Response format */\nexport type RPCResponse = ({\n  /** Result. Not present if the function didn't return anything */\n  result?: unknown;\n} | {\n  /** Error message */\n  error: string;\n  /** Captured stack trace (if 'etr' debugFlag is set) */\n  trace?: StackTrace;\n}) & {\n  /** Captured console log entries (if 'etr' debugFlag is set) */\n  consoleLog?: Array<{\n    //TODO this is Serialized<ConsoleLogItem[]> - should probably rename it to SerializedToJSON and move to std or env ?\n    /** Date when console function was called */\n    when: string;\n    /** `console` method that was called (eg 'log') */\n    method: string;\n    /** Logged data */\n    data: string;\n    /** Location of caller */\n    location?: {\n      filename: string;\n      line: number;\n      col: number;\n      func: string;\n    };\n    /** Codecontext */\n    codeContextId?: string;\n  }>;\n};\n\nclass ControlledCall {\n  client: RPCClient;\n  options: RPCClientOptions;\n  abortcontroller?: AbortController;\n  timeout?: number;\n  _callurl: string;\n  _fetchoptions: RequestInit;\n  promise: Promise<unknown>;\n  timedout?: boolean;\n  aborted?: boolean;\n\n  constructor(client: RPCClient, method: string, stack: StackTrace | null, options: RPCClientOptions, callurl: URL, fetchoptions: RequestInit) {\n    this.client = client;\n    this.options = options;\n\n    if (options.timeout || options.signal) {\n      this.abortcontroller = new AbortController;\n      fetchoptions.signal = this.abortcontroller.signal;\n\n      if (options.timeout && options.timeout > 0) {\n        this.timeout = options.timeout;\n        setTimeout(() => this._handleTimeout(), options.timeout);\n      }\n      if (options.signal) {\n        options.signal.addEventListener(\"abort\", () => this._abort());\n      }\n    }\n\n    this._callurl = callurl.toString();\n    this._fetchoptions = fetchoptions;\n\n    const fetchpromise = fetch(this._callurl, this._fetchoptions);\n    this.promise = this._completeCall(method, stack, fetchpromise) as Promise<unknown>;\n  }\n  _handleTimeout() {\n    this.timedout = true;\n    this.abortcontroller?.abort();\n  }\n  _abort() {\n    this.aborted = true;\n    this.abortcontroller?.abort();\n  }\n\n  async _completeCall(method: string, requestStack: StackTrace | null, fetchpromise: Promise<Response>) {\n    let response;\n    for (; ;) { //loop to handle \"429 Conflict\"s\n      try { //we should only guard the fetch call and specifically *not* the onResponse callback\n        response = await fetchpromise;\n      } catch (exception) {\n        if (this.client.debug)\n          console.log(`[rpc] Exception invoking '${method}'`, exception);\n\n        if (this.aborted)\n          throw new Error(`RPC Aborted`);\n        else if (this.timedout)\n          throw new Error(`RPC Timeout: timeout was set to ${this.timeout} milliseconds`);\n        else\n          throw new Error(`RPC Failed: exception: ` + exception);\n      }\n\n      this.options.onResponse?.(response); //allow hooks to capture headers\n\n      if (response.status === 429 && !(\"retry429\" in this.options && !this.options.retry429) && response.headers.get(\"Retry-After\")) {\n        const retryafter = parseInt(response.headers.get(\"Retry-After\") || \"\");\n        if (this.client.debug)\n          console.warn(`[rpc] We are being throttled (429 Too Many Requests) - retrying after ${retryafter} seconds`);\n\n        await new Promise(resolve => setTimeout(resolve, retryafter * 1000));\n        fetchpromise = fetch(this._callurl, this._fetchoptions);\n        continue;\n      }\n      break;\n    }\n\n    let jsonresponse: RPCResponse;\n    try {\n      jsonresponse = parseTyped(await response.text());\n      if (jsonresponse.consoleLog) {\n        for (const logitem of jsonresponse.consoleLog) {\n          //should we log 'when'? it's getting more and more noisy then though....\n          //TODO should we match the remote's method (after validating) or just keep everything at 'log' ?\n          console.log(`[remote:${logitem.method}] ${logitem.location ? `${logitem.location.filename.split(\"/\").at(-1)}:${logitem.location.line}: ` : ''}${logitem.data}`);\n        }\n      }\n\n      if (this.client.debug)\n        console.log(`[rpc] Received response to '${method}'`, omit(jsonresponse, [\"consoleLog\", \"trace\"]));\n    } catch (exception) {\n      if (this.client.debug)\n        console.warn(`[rpc] Response was not valid JSON`, exception);\n      throw new Error(\"RPC Failed: Invalid response received\", { cause: exception });\n    }\n\n    if (\"error\" in jsonresponse) {\n      const err = new Error(`RPC Error: ${jsonresponse.error}`);\n      if (jsonresponse.trace) {\n        try {\n          prependStackTrace(err, jsonresponse.trace);\n        } catch (err2) {\n          //ignore stacktrace manipulation error\n        }\n      }\n\n      if (this.options.debug) {\n        console.group();\n        console.warn(\"RPC failed:\", err);\n        if (requestStack) {\n          console.warn(\"Stack at calling point\");\n          console.log(requestStack);\n        }\n        console.groupEnd();\n      }\n\n      throw err;\n    }\n\n    return jsonresponse.result;\n  }\n}\n\nclass RPCClient {\n  readonly url: string;\n  options: RPCClientOptions;\n\n  constructor(url: string, options?: RPCClientOptions) {\n    this.url = url;\n    this.options = {\n      timeout: 0,\n      debug: false,\n      ...options\n    };\n  }\n\n  get debug() {\n    return this.options.debug || debugFlags.rpc;\n  }\n\n  _tryLogError(requestStack: StackTrace | null, error: Error) {\n  }\n\n  invoke(method: string, params: unknown[]) {\n    //build the URL, add profiling and function parameters where needed\n    //We'll delay the baseurl calculation until the first call to allow for the backendBase to be set up\n    const callurl = isAbsolute(this.url) ? new URL(this.url + method) : new URL(this.url + method, this.options.baseUrl || getBaseURL());\n\n    let requestStack: StackTrace | null = null;\n\n    const fetchoptions: RequestInit & { headers: Headers } = {\n      method: \"POST\",\n      headers: new Headers({\n        \"Accept\": \"application/json\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        ...this.options.headers\n      }),\n      body: stringify(params, { typed: true }),\n    };\n\n    const pathName = typeof location !== \"undefined\" ? location.pathname : new URL(this.options.baseUrl || getBaseURL()).pathname;\n    if (pathName !== '/')\n      callurl.searchParams.set(\"pathname\", pathName);\n\n    if (this.debug) {\n      requestStack = parseTrace(new Error);\n      console.log(`[rpc] Invoking '${method}'`, params);\n    }\n\n    this.options.onBeforeRequest?.(callurl, fetchoptions);\n    return new ControlledCall(this, method, requestStack, this.options, callurl, fetchoptions).promise;\n  }\n}\n\ntype ServiceBase<T> = {\n  withOptions(options: RPCClientOptions): T & ServiceBase<T>;\n};\n\nclass ServiceProxy<Service extends keyof KnownRPCServices | object> {\n  client: RPCClient;\n\n  constructor(client: RPCClient) {\n    this.client = client;\n  }\n\n  get(target: object, prop: string, receiver: unknown) {\n    if ([\"then\", \"catch\", \"finally\"].includes(prop)) //do not appear like our object is a promise\n      return undefined;\n\n    if (prop === 'withOptions') { //create a withOptions function\n      return (options: RPCClientOptions) => {\n        const newoptions = {\n          ...this.client.options,\n          ...options,\n          headers: { ...this.client.options.headers, ...options.headers }\n        };\n        return rpc(this.client.url as (Service extends keyof KnownRPCServices ? Service : string), newoptions);\n      };\n    }\n\n    return (...args: unknown[]) => this.client.invoke(prop, args);\n  }\n}\n\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\ntype OmitFirstArg<F> = F extends (x: any, ...args: infer P) => infer R ? (...args: P) => R : never;\n\nexport type OmitRPCContextArgs<ServiceType> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\n  [K in keyof ServiceType as ServiceType[K] extends (...a: any) => any ? K : never]: ServiceType[K] extends (...a: any[]) => void ? OmitFirstArg<ServiceType[K]> : never;\n};\n\n\ntype ExtractInterface<Service extends object> = PromisifyInterface<Service> & ServiceBase<PromisifyInterface<Service>>;\n\n/** Get the client interface type as would be returned by createClient\n * @typeParam Service - either the `module:service` name or the interface to implement. If you want to pass the implementation's type you should wrap it into `OmitRPCContextArgs`.\n*/\nexport type GetRPCClientInterface<Service extends (keyof KnownRPCServices) | object> = Service extends keyof KnownRPCServices ? ExtractInterface<OmitRPCContextArgs<KnownRPCServices[Service]>> : Service extends object ? ExtractInterface<Service> : never;\n\n/** Create a WebHare RPC client\n  @param service - URL (https://<ORIGIN>/.wh/rpc/module/service/) or service name (module:service) to invoke\n*/\nexport function rpc<Service extends keyof KnownRPCServices>(service: Service, options?: RPCClientOptions): GetRPCClientInterface<Service>;\nexport function rpc<Service extends keyof KnownRPCServices>(service: string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\nexport function rpc<Service extends object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\n\nexport function rpc<Service extends keyof KnownRPCServices | object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service> {\n  //NOTE: needed the separate overloads to get Intellisense to list the known services for createRPClient's first argument\n\n  if (!service)\n    throw new Error(`You must specify either a WebHare rpcService name or a full URL`);\n\n  const servicematch = service.match(/^([a-z0-9_]+):([a-z0-9_]+)$/);\n  if (servicematch)\n    service = `/.wh/rpc/${servicematch[1]}/${servicematch[2]}/` as (Service extends keyof KnownRPCServices ? Service : string);\n  else if (!service.endsWith('/'))\n    throw new Error(`Service URL must end in a slash`);\n\n  const rpcclient = new RPCClient(service, options);\n  return new Proxy({}, new ServiceProxy<GetRPCClientInterface<Service>>(rpcclient)) as GetRPCClientInterface<Service>;\n}\n","/* TODO Move consilio pxl here eventually, but limit how much we actually want to export */\nimport { sendPxlEvent, type PxlEventData, type PxlOptions } from \"@mod-consilio/js/pxl\";\nimport { dtapStage } from \"@webhare/env\";\nimport type { FormAnalyticsEvent } from \"@webhare/forms\";\nimport type { PxlDataTypes } from \"@webhare/frontend\";\nexport { setPxlOptions, getPxlId as getPxlUserId, getPxlSessionId } from \"@mod-consilio/js/pxl\";\n\nexport type PxlData = Record<string, string | number | boolean>;\n\n// Track listener installation. Especially needed during the transition from @mod-publisher/js/forms to @webhare/frontend. After the transition we might not need stack traces anymore\nconst activeListenPrefixes = new Map<string, Error>;\n\n// Combine with `string & {}` to prevent TypeScript from eliminating `keyof PxlDataTypes`\ntype AllowedKeys = keyof PxlDataTypes | (string & {});\n\n// Filters out invalid types from the PXL data type\ntype FilterValidTypes<T extends object | void> = T extends object ? {\n  [K in keyof T]: T[K] extends undefined | string | number | boolean ?\n  T[K] :\n  { __error: \"Invalid property type used in PXL event declaration, allowed: boolean, number, string\"; __type: T[K] };\n} : T;\n\n/// Helper type to allow making the data parameter optional when the datatype is void\ntype ParamTuples<DataType, Key extends AllowedKeys> = Key extends keyof PxlDataTypes ?\n  [data: FilterValidTypes<PxlDataTypes[Key]>, options?: Partial<PxlOptions>] :\n  (DataType extends void ?\n    [data?: void, options?: Partial<PxlOptions>] :\n    [data: DataType, options?: Partial<PxlOptions>]);\n\n// Error type for when an event is not declared in PxlDataTypes and no data type override is provided\ntype NeedTypeParamError = { __error: \"Event not declared in PxlDataTypes and no data type override provided\" } & symbol;\n\nexport function sendPxl<DataType extends (Event extends keyof PxlDataTypes ? NeedTypeParamError : void | PxlData | NeedTypeParamError) = NeedTypeParamError, Event extends AllowedKeys = AllowedKeys>(eventKey: Event, ...params: ParamTuples<NoInfer<DataType>, Event>): void {\n  const [data, options] = params;\n  const pxldata: PxlEventData = {};\n  for (const [k, v] of Object.entries(data ?? {})) {\n    if (v === undefined)\n      continue;\n    if (typeof v === \"string\")\n      pxldata[`ds_${k}`] = v;\n    else if (typeof v === \"number\")\n      pxldata[`dn_${k}`] = v;\n    else if (typeof v === \"boolean\")\n      pxldata[`db_${k}`] = v;\n    else\n      throw new Error(`Invalid type '${typeof v}' for PXL data key '${k}'`);\n  }\n\n  sendPxlEvent(eventKey, pxldata, options);\n}\n\n/** Setup pxl events for form analytics events\n * @param options - Options for the form analytics setup\n     - `eventPrefix`. Prefix to use. Default is `platform:form_` but existing integrations may (also) require `publisher:form`\n*/\nexport function setupFormAnalytics(options?: { eventPrefix: string }): void {\n  const prefix = options?.eventPrefix || \"platform:form_\";\n  const registered = activeListenPrefixes.get(prefix);\n  if (registered)\n    if (dtapStage !== \"production\")\n      return console.error(`Duplicate setupFormAnalytics for prefix '${prefix}', earlier registration: `, registered);\n\n  activeListenPrefixes.set(prefix, new Error); //getStackTrace() would have been nicer, but doesn't get sourcemapped in the console\n\n  addEventListener(\"wh:form-analytics\", (e: FormAnalyticsEvent) => {\n    const formeventdata: { [K in `formmeta_${string}`]: string | number | boolean } = {};\n    for (const [key, val] of Object.entries(e.detail))\n      if (key !== \"event\" && [\"string\", \"number\", \"boolean\"].includes(typeof val))\n        formeventdata[`formmeta_${key}`] = val;\n\n    sendPxl<PxlData>(`${prefix}${e.detail.event}`, formeventdata, e.detail.event === \"abandoned\" ? { beacon: true } : undefined);\n  });\n}\n","import { qSA } from \"@webhare/dompack\";\nimport { debugFlags } from \"@webhare/env\";\nimport type { FormAnalyticsEvent } from \"@webhare/forms\";\nimport type { DataLayerEntry } from \"./gtm-types\";\nimport { omit } from \"@webhare/std\";\n\ndeclare global {\n  interface Window {\n    /** The google tag manager (GTM) datalayer */\n    dataLayer: DataLayerEntry[]; //technically window.dataLayer may not exist and should be optional, but we already used to declare it as existing from gtm.ts\n  }\n  //It's safer to access dataLayer through globalThis, which will always be available in all environments unlike 'window'\n  var dataLayer: DataLayerEntry[] | undefined;\n}\n\n//ADDME if we ever figure out a bundler trick to flush this command to the top of all imports/loads, that would be great (we could consider *ALWAYS* putting this in the generated startup code, or we'd need to do a tree pre-walk to see if gtm.es is loaded anywhere)\n(globalThis as unknown as Window).dataLayer ||= [];\nlet lastSeen: DataLayerEntry | undefined;\n\nfunction showDataLayerUpdates() {\n  if (!globalThis.dataLayer)\n    return; //not set up (yet?)\n\n  if (debugFlags.anl)\n    globalThis.dataLayer.slice(globalThis.dataLayer.indexOf(lastSeen!) + 1).forEach(entry => console.log(\"[anl] dataLayer.push:\", entry));\n\n  lastSeen = globalThis.dataLayer[globalThis.dataLayer.length - 1];\n}\n\n/** Push to the dataLayer\n * @param vars - The variables to push\n * @param options - Options for the push\n *   timeout Time before any eventCallback is forcibly called (default 200ms)\n*/\nexport function pushToDataLayer(vars: DataLayerEntry, options?: { timeout?: number }) {\n  if (vars.eventCallback) { //we'll wrap the callback into a promise to ensure it's only invoked once\n    const savecallback = vars.eventCallback;\n    let newcallback: () => void;\n    void (new Promise<void>(resolve => newcallback = resolve)).then(() => savecallback());\n    setTimeout(() => newcallback, options?.timeout || 200);\n  }\n\n  globalThis.dataLayer?.push(vars);\n  showDataLayerUpdates();\n}\n\nfunction collectFormValues(formnode: HTMLFormElement): Record<string, unknown> {\n  const donefields: Record<string, boolean> = {};\n  const outdata: Record<string, unknown> = {};\n\n  const multifields = qSA<HTMLInputElement>(formnode, 'input[type=radio], input[type=checkbox]');\n  for (const multifield of multifields) {\n    if (!multifield.name || donefields[multifield.name])\n      continue; //we did this one\n\n    donefields[multifield.name] = true;\n\n    let idx = 0;\n    const values = [];\n    const labels = [];\n    const checkboxes = multifields.filter(node => node.name === multifield.name);\n\n    for (const node of checkboxes.filter(cbox => cbox.checked)) {\n      const keyname = 'form_' + multifield.name + (idx ? '_' + idx : '');\n      let labelsfornode = node.dataset.gtmTag || qSA(`label[for=\"${CSS.escape(node.id)}\"]`).map(labelnode => labelnode.textContent).filter(labelnode => Boolean(labelnode)).join(' ');\n      labelsfornode = labelsfornode.trim(); //TODO normalize whitespace\n      outdata[keyname] = node.value;\n      outdata[keyname + '_label'] = labelsfornode;\n\n      ++idx;\n      values.push(node.value);\n      labels.push(labelsfornode);\n    }\n\n    if (values.length) {\n      const allkeyname = 'form_' + multifield.name + '_all';\n      outdata[allkeyname] = values.join(';');\n      outdata[allkeyname + '_label'] = labels.join(';');\n    }\n  }\n\n  for (const field of formnode.querySelectorAll<HTMLSelectElement | HTMLInputElement>('input:not([type=radio]):not([type=checkbox]),select,textarea')) {\n    if (!field.name || donefields[field.name])\n      continue;\n\n    donefields[field.name] = true;\n\n    const val = field.value;\n    outdata['form_' + field.name] = val;\n    if (field.matches('select')) {\n      const opt = (field as HTMLSelectElement).options[(field as HTMLSelectElement).selectedIndex];\n      if (opt)\n        outdata['form_' + field.name + '_label'] = opt.dataset.gtmTag || opt.textContent;\n    }\n  }\n  return outdata;\n}\n\n/** Setup the dataLayer */\nlet didinit: boolean | undefined;\nexport function setupGTM() {\n  if (!didinit) {\n    didinit = true;\n    if (debugFlags.anl)\n      setInterval(showDataLayerUpdates, 100);\n  }\n}\n\n/** Setup dataLayer events for form analytics events\n * @param options - Options for the form analytics setup\n     - `eventPrefix`. Prefix to use. Default is `wh-platform:form_` but existing integrations may (also) require `publisher:form`\n*/\nexport function setupFormAnalyticsForGTM(options?: { eventPrefix: string }): void {\n  setupGTM(); //ensurse the GTM basics are installed\n\n  addEventListener(\"wh:form-analytics\", (e: FormAnalyticsEvent) => {\n    //we use the same prefixing as pxl events would\n    const entry: DataLayerEntry = {\n      event: `${options?.eventPrefix || \"platform:form_\"}${e.detail.event}`\n    };\n\n    for (const [key, val] of Object.entries(e.detail))\n      if (key !== \"event\" && [\"string\", \"number\", \"boolean\"].includes(typeof val))\n        entry[`formmeta_${key}`] = val;\n\n    const form = e.target as HTMLFormElement | undefined;\n    if (form?.dataset.gtmSubmit) {\n      //When set, we push both the form: variable in gtmSubmit and the current form field avlues\n      Object.assign(entry, JSON.parse(form.dataset.gtmSubmit));\n      Object.assign(entry, collectFormValues(form));\n    }\n\n    pushToDataLayer(entry);\n  });\n}\n\nfunction processClickDataLayerTags(event: MouseEvent) {\n  const entry: Record<string, unknown> = {};\n\n  for (let node = event.target as HTMLElement | undefined | null; node; node = node?.parentElement)\n    for (const attr of node.attributes)\n      if (attr.nodeName.startsWith(\"data-wh-datalayer-onclick-\")) {\n        const key = attr.nodeName.substring(26);\n        if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n          entry[key] = attr.nodeValue || \"\";\n      } else if (attr.nodeName === \"data-wh-datalayer-onclick\") { //JSON setter\n        const data = JSON.parse(attr.nodeValue!);\n        for (const [key, value] of Object.entries(data))\n          if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n            entry[key] = value;\n      }\n\n  if (Object.keys(entry).length)\n    pushToDataLayer(entry as DataLayerEntry);\n}\n\n/** Setup support for data-wh-datalayer-onclick-xxx=\"yyy\" attributes. When clicking an element with these attributes the JSON from the attribute and all parents are merged together and pushed to the dataLayer  */\nexport function setupDataLayerTags() {\n  //we capture so we can also simply set variables for any existing GTM handlers\n  window.addEventListener(\"click\", processClickDataLayerTags, { capture: true });\n}\n\n/** Get the current variables in the GTM datalayer\n * @param win - The window to get the dataLayer from (default: current window)\n * @return The current variables in the GTM datalayer, merged together from all entries. Note that this is a snapshot and won't update as the dataLayer changes\n*/\nexport function getCurrentDataLayerVariables<DataLayerFormat extends object = Record<string, unknown>>(win: Window = window): DataLayerFormat {\n  const state: DataLayerFormat = {} as DataLayerFormat;\n  if (win.dataLayer)\n    win.dataLayer.forEach(entry =>\n      Object.assign(state, structuredClone(omit(entry, [\"event\", \"eventCallback\", \"gtm.uniqueEventId\"]))));\n  return state;\n}\n","/* To verify tree shaking viability, try:\n   whcd\n   cd whtree\n   echo 'import \"@webhare/frontend\"' | node_modules/.bin/esbuild --loader:.css=empty --tsconfig=tsconfig.json --bundle --minify\n*/\n\n// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/frontend\" {\n}\n\nimport { onDomReady } from \"@webhare/dompack\";\nexport { frontendConfig, getFrontendData, getSiteRoot } from \"./init\";\nexport { startSSOLogin, login, setupWRDAuth, isLoggedIn, logout, getUserInfo, setupWebHareSSOTrigger } from \"./auth\";\nexport { loadAssetPack, setupAuthorMode, type AuthorModeOptions } from \"./authormode\";\nexport { setPxlOptions, sendPxl, getPxlUserId, getPxlSessionId, setupFormAnalytics, type PxlData } from \"./pxl\";\nexport { getRemoteIPAddress, getGeoIPInfo, type GetIPInfoOptions, type GeoIPInfoResult } from \"./analytics\";\nexport { setupGTM, setupFormAnalyticsForGTM, pushToDataLayer, setupDataLayerTags, getCurrentDataLayerVariables } from \"./gtm\";\nexport { setupLinksInNewWindow, type LinkOpenOptions } from \"./linkhandler\";\n\nexport type * from \"./gtm-types\";\n\n// we shouldn't deprecate navigateTo exported from frontend. in fact it makes more sense to export it from frontend than env as it's browser-only\nexport { navigateTo } from \"@webhare/env\";\n\n/** Registry for data we receive from the backend */\nexport interface FrontendDataTypes {\n}\n\n/** Registry for expected PXL formats */\nexport interface PxlDataTypes {\n}\n\n/** Test whether the current page is being iframed in the WebHare test framework */\nexport function isInTestFramework(): boolean {\n  if (window.top !== window) { //in a frame\n    try {\n      if ((window.top as { __testframework?: unknown })?.__testframework)\n        return true;//we're inside a testframe, pretend to be the parent\n    } catch (ignore) {\n    }\n  }\n  return false;\n}\n\nfunction postRenderChecks() {\n  const log = document.getElementById(\"wh-console-log\");\n  if (log) {\n    const logtext = atob(log.textContent || \"\");\n    console.group(\"[etr] Server-side console output\");\n    console.log(logtext);\n    console.groupEnd();\n  }\n}\n\nonDomReady(postRenderChecks);\n","// Auto-generated language file from /opt/whdata/installedmodules/kiskeya.20261027T130541.723Z/webdesigns/registrationapp/registrationapp.lang.json\nvar registerTexts = require(\"@webhare/gettid/src/internal\").registerTexts;\nregisterTexts(\"kiskeya\",\"fr\",{\"frontend\":{\"registrationapp\":{\"addregistration\":\"Ajouter une inscription\",\"apptitle\":\"App. d'Inscription Plan Kiskeya\",\"editregistration\":{\"\":\"Modifier l'inscription\",\"addprofile\":\"Ajouter un profil\",\"adopteeprofile\":\"Profil de l'adopté\",\"adopteeprofiles\":\"Profils des adoptés\",\"areyousuredeleteprofile\":[\"Êtes-vous sûr de vouloir supprimer le profil\",{\"t\":\"ifparam\",\"p\":1,\"value\":\"\",\"subs\":[],\"subselse\":[\" de \",1]},\"?\"],\"deleteprofile\":\"Supprimer le profil?\",\"editprofile\":\"Modifier profil\",\"imlookingfor\":\"Je cherche ...\",\"legenda\":\"Légende\",\"legenda-noaccess\":\"Privé\",\"legenda-publicaccess\":\"Toujours visible\",\"legenda-restrictedaccess\":\"Derrière la login\",\"personalprofile\":\"Personne qui cherche\",\"searchadopteedescription\":\"Je vis en Haïti et je recherche un parent disparu\",\"startsync\":\"Envoyer les inscriptions stockées au serveur?\",\"storeandecrypt\":\"Finaliser et crypter l'inscription\",\"storeandecrypt-sure\":[\"Êtes-vous sûr de vouloir finaliser les informations de profil saisies ?\",\"\\n\",\"Après finalisation, les informations de profil ne peuvent être modifiées dans « Mes inscriptions » qu'après avoir synchronisé les informations avec le serveur.\"]},\"exportcount\":[{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 inscription est prête à être exportée\"],\"subselse\":[1,\" inscriptions sont prêtes à être exportées\"]}],\"installnotification\":[\"Installez cette application sur votre appareil pour un accès hors ligne!\",\"\\n\",\"Pour une installation locale, consultez la page \",{\"t\":\"a\",\"link\":\"#instructions\",\"linkparam\":0,\"target\":\"\",\"subs\":\"instructions\"},\".\"],\"instructions\":\"Instructions\",\"login\":\"Login\",\"logout\":\"Déconnexion\",\"menu\":\"Menu\",\"myregistrations\":{\"\":\"Mes inscriptions\",\"exported\":\"Inscriptions exportées\",\"noexporteditems\":\"Aucune inscription exportée trouvée\",\"storedlocal\":\"Stocké localement (crypté):\"},\"mysettings\":{\"\":\"Mes réglages\",\"languages\":\"Langue\",\"personal\":\"Mes Details\"},\"newregistrations\":\"Nouvelle inscription\",\"passwordreset\":\"Réinitialiser le mot de passe\",\"sendmyregistrationstoserver\":\"Envoyer mes inscriptions au serveur\",\"setpassword\":\"Définir le mot de passe\",\"startpage\":\"Page de démarrage\",\"startpage-header\":\"d'Inscriptions Plan Kiskeya\",\"status-offline\":\"Offline\",\"status-online\":\"Online\",\"surelogout\":[\"Êtes-vous sûr de vouloir vous déconnecter?\",\"\\n\",\"Attention : vous avez besoin d'une connexion Internet active pour vous reconnecter.\"],\"sync\":\"Synchroniser/envoyer les inscriptions au serveur\",\"syncnotification-offline\":\"N'oubliez pas de synchroniser les inscriptions stockées localement avec le serveur lorsque vous êtes en ligne!\",\"syncnotification-online\":\"Envoyer les inscriptions stockées localement au serveur\",\"viewmyregistrations\":\"Consulter mes inscriptions\",\"common\":{\"abort\":\"Avorter\",\"close\":\"Fermer\",\"error\":\"Error\",\"failed\":\"Échoué\",\"no\":\"Non\",\"saved\":\"Enregistré\",\"start\":\"Commencer\",\"starthere\":\"Commencez ici\",\"warning\":\"Attention\",\"yes\":\"Qui\"},\"forms\":{\"adoption_location\":[\"L’adresse de l'enfant au moment de l'adoption\",\"\\n\",\"(chaque indice est utile)\"],\"allowmailcontact\":[\"Autoriser les autres inscrits à vous envoyer un message\",\"\\n\",\"(votre adresse e-mail ne sera pas affichée)\"],\"birth_city\":\"Lieu de naissance originale (comme mentionné dans votre passeport)\",\"birthcertificate\":\"Acte de naissance\",\"birthdate\":\"Date de naissance\",\"causedisappearance\":\"Cause de la disparition\",\"contactpersons\":\"Personne de contact\",\"department\":\"Département (région) Haïti\",\"description\":\"Description  (facultatif)\",\"documentsdescription\":\"Est-ce qu'il y a d'autres documents officiels?\",\"email\":\"Adresse e-mail\",\"error-password-notequal\":\"Les mots de passe que vous avez entrés ne correspondent pas\",\"error-password-tosmall\":[\"Le mot de passe doit contenir au minimum \",1,\" caractères\"],\"family_otherinfo\":\"Autres informations\",\"female\":\"Femme\",\"firstname\":\"Prénom\",\"forgotpassword\":\"Réinitialiser le mot de passe\",\"forgotpassword-instructions\":\"Entrez l'adresse email associée à votre compte pour recevoir un lien de réinitialisation de mot de passe.\",\"forgotpassword-send\":\"Votre demande a été traitée. Vous recevrez un email avec un lien de réinitialisation si nous pouvons localiser votre compte.\",\"forgotpassword-success\":\"Votre mot de passe est maintenant enregistré\",\"gender\":\"Sexe\",\"hasbirthcertificate\":\"Disposez-vous d'un acte de naissance?\",\"image\":\"Uploadez une photo de profil (photo d'identité)\",\"invalidlogin\":\"Email ou mot de passe invalide\",\"lastlocation\":\"Le dernier lieu de résidence de la personne disparue\",\"lastname\":\"Nom de famille\",\"male\":\"Homme\",\"name\":\"Nom\",\"other\":\"Autre\",\"password\":\"Mot de passe\",\"password2\":\"Répéter le mot de passe\",\"passwordforgotten\":\"Vous avez oublié votre mot de passe?\",\"phone\":\"Téléphone\",\"photos\":\"Disposez-vous de photos du moment de l'adoption ou avant?\",\"place\":\"Lieu\",\"referenceperson\":\"Si nous perdons le contact avec vous, qui pouvons-nous contacter et comment\",\"relationtype\":\"Relation familiale\",\"relationtype_other\":\"Relation sinon\",\"relatives\":\"Autres membres de famille\",\"save\":\"Enregistrer\",\"send\":\"Envoyer\",\"yes\":\"Qui\"}}}});\nregisterTexts(\"kiskeya\",\"en\",{\"frontend\":{\"registrationapp\":{\"addregistration\":\"Add registration\",\"apptitle\":\"Plan Kiskeya Registration App.\",\"editregistration\":{\"\":\"Edit registration\",\"addprofile\":\"Add profile\",\"adopteeprofile\":\"Adoptee profile\",\"adopteeprofiles\":\"Adoptee profiles\",\"areyousuredeleteprofile\":[\"Are you sure you want to delete \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"\",\"subs\":[\"this profile\"],\"subselse\":[\"profile for \",1]},\"?\"],\"deleteprofile\":\"Delete profile?\",\"editprofile\":\"Edit profile\",\"imlookingfor\":\"I am looking for ...\",\"legenda\":\"Legend\",\"legenda-noaccess\":\"Private\",\"legenda-publicaccess\":\"Always visible\",\"legenda-restrictedaccess\":\"Behind login\",\"personalprofile\":\"Profile searching person\",\"searchadopteedescription\":\"I live in Haiti and am searching for a missing relative\",\"startsync\":\"Send stored registrations to server?\",\"storeandecrypt\":\"Finalize & encypt registration\",\"storeandecrypt-sure\":[\"Are you sure you want to finalize the entered profile information?\",\"\\n\",\"After finalizing, the profile information can only be edited in 'My registrations' after syncing the information with the server.\"]},\"exportcount\":[1,\" registration\",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\" is\"],\"subselse\":[\"s are\"]},\" ready for export\"],\"installnotification\":[\"Install this application on your device for offline access!\",\"\\n\",\"For local installation, see the \",{\"t\":\"a\",\"link\":\"#instructions\",\"linkparam\":0,\"target\":\"\",\"subs\":\"instructions\"},\" page.\"],\"instructions\":\"Instructions\",\"login\":\"Login\",\"logout\":\"Logout\",\"menu\":\"Menu\",\"myregistrations\":{\"\":\"My registrations\",\"exported\":\"Exported registrations\",\"noexporteditems\":\"No exported registrations found\",\"storedlocal\":\"Stored local (encrypted):\"},\"mysettings\":{\"\":\"My settings\",\"languages\":\"Language\",\"personal\":\"My details\"},\"newregistrations\":\"New registration\",\"passwordreset\":\"Password reset\",\"sendmyregistrationstoserver\":\"Send my registrations to server\",\"setpassword\":\"Setup password\",\"startpage\":\"Start page\",\"startpage-header\":\"Plan Kiskeya Registrations\",\"status-offline\":\"Offline\",\"status-online\":\"Online\",\"surelogout\":[\"Are you sure you want to logout?\",\"\\n\",\"Warning: You need an active internet connection to login again.\"],\"sync\":\"Sync/send registrations to server\",\"syncnotification-offline\":\"Remember to sync localy stored registrations with server when online!\",\"syncnotification-online\":\"Send localy stored registrations to the server\",\"viewmyregistrations\":\"View my registrations\",\"common\":{\"abort\":\"Abort\",\"close\":\"Close\",\"error\":\"Error\",\"failed\":\"Failed\",\"no\":\"No\",\"saved\":\"Saved\",\"start\":\"Start\",\"starthere\":\"Start here\",\"warning\":\"Warning\",\"yes\":\"Yes\"},\"forms\":{\"adoption_location\":[\"The child's address at the time of adoption\",\"\\n\",\"(any clue is helpful)\"],\"allowmailcontact\":[\"Allow other registrants to send you a message\",\"\\n\",\"(your email address will not be shown)\"],\"birth_city\":\"Place of birth (as in passport)\",\"birthcertificate\":\"Birth certificate\",\"birthdate\":\"Date of birth\",\"causedisappearance\":\"Cause of disappearance\",\"contactpersons\":\"Contact persons\",\"department\":\"Region Haïti\",\"description\":\"Description (optional)\",\"documentsdescription\":\"Are there other information papers\",\"email\":\"E-mail address\",\"error-password-notequal\":\"The passwords you entered did not match\",\"error-password-tosmall\":[\"The password should contain minimal \",1,\" characters\"],\"family_otherinfo\":\"Other information\",\"female\":\"Female\",\"firstname\":\"First name\",\"forgotpassword\":\"Password reset\",\"forgotpassword-instructions\":\"Enter the email address associated with your account to receive a password reset link.\",\"forgotpassword-send\":\"Your request has been processed. You'll receive an email with a reset link if we can locate your account.\",\"forgotpassword-success\":\"Password is successfully set\",\"gender\":\"Gender\",\"hasbirthcertificate\":\"In possession of birth certificate\",\"image\":\"A recent portrait photo of you\",\"invalidlogin\":\"Invalid email or password\",\"lastlocation\":\"Last known place\",\"lastname\":\"Last name\",\"male\":\"Male\",\"name\":\"Name\",\"other\":\"Other\",\"password\":\"Password\",\"password2\":\"Repeat password\",\"passwordforgotten\":\"Password forgotten?\",\"phone\":\"Phone\",\"photos\":\"Do you have photos from or before the moment of adoption?\",\"place\":\"Place\",\"referenceperson\":\"If we lose contact with you, who can we contact and how\",\"relationtype\":\"Relation\",\"relationtype_other\":\"Other relation\",\"relatives\":\"Known family\",\"save\":\"Save\",\"send\":\"Send\",\"yes\":\"Yes\"}}}});\n// Adding dependency: /opt/whdata/installedmodules/kiskeya.20261027T130541.723Z/language/fr.xml\n// Adding dependency: /opt/whdata/installedmodules/kiskeya.20261027T130541.723Z/language/default.xml\n// Adding dependency: /opt/whdata/installedmodules/kiskeya.20261027T130541.723Z/language/default.xml\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/gettid\" {\n}\n\nexport {\n  getTidLanguage,\n  setTidLanguage,\n  getTid,\n  getTidForLanguage,\n  getHTMLTid,\n  getHTMLTidForLanguage,\n  getTIDListForLanguage\n} from \"./internal\";\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/upload\" {\n}\n\nimport * as dompack from \"@webhare/dompack\";\n\n/* Note: you can't really build a FileList yourself, but FileList doesn't satisfy File[] and neither the reverse works. (noone is really happy with that though)\n   So we'll just accept both types */\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"wh:requestfiles\": CustomEvent<{\n      /** Callback to invoke with the list of files to upload */\n      resolve: (files: File[]) => void;\n    } & Required<UploadRequestOptions>>;\n  }\n}\n\nexport interface UploadRequestOptions {\n  ///List of mimetypes to accept, supports wildcards (eg `image/*`)\n  accept?: string[];\n  ///Allow multiple files to be selected. By default determined by whether you use requestFiles or requestFile, but can be set to false to force requestFiles to only accept one file\n  multiple?: boolean;\n}\n\nexport interface UploadProgressStatus {\n  uploadedBytes: number;\n  totalBytes: number;\n  uploadedFiles: number;\n  totalFiles: number;\n  //Upload speed in bytes/sec.\n  uploadSpeed: number;\n}\n\nexport interface UploadOptions {\n  onProgress?: (progress: UploadProgressStatus) => void;\n  signal?: AbortSignal;\n}\n\nexport interface UploadResult {\n  name: string;\n  size: number;\n  type: string;\n  token: string;\n}\n\nexport interface UploadManifest {\n  files: Array<{\n    name: string;\n    size: number;\n    type: string;\n  }>;\n}\n\nexport interface UploadInstructions {\n  baseUrl: string;\n  sessionId: string;\n  chunkSize: number;\n  signal?: AbortSignal;\n}\n\nexport type ResourceDescriptorCompatible = {\n  resource: Blob;\n  mediaType: string;\n  fileName: string | null;\n};\n\nexport interface UploaderBase {\n  readonly manifest: UploadManifest;\n  upload(instructions: UploadInstructions, options?: UploadOptions): Promise<UploadResult | UploadResult[]>;\n}\n\nfunction isRealBlob(data: Blob) { return data instanceof Blob; }\nasync function convertToRealBlob(data: Blob): Promise<Blob> { return new Blob([await data.arrayBuffer()]); }\n\nexport class MultiFileUploader implements UploaderBase {\n  readonly #files: Array<{ name: string; size: number; type: string; data: Blob }>;\n  readonly manifest: UploadManifest;\n\n  constructor(files: Array<File | Blob | ResourceDescriptorCompatible>, signal?: AbortSignal) {\n    if (!files.length)\n      throw new Error(\"No files to upload\");\n\n    this.#files = files.map(item => (\n      \"resource\" in item ? {\n        name: item.fileName ?? \"upload\",\n        size: item.resource.size,\n        type: item.mediaType || \"application/octet-stream\",\n        data: item.resource,\n      } : {\n        name: \"name\" in item ? item.name : \"upload\",\n        size: item.size,\n        type: item.type || \"application/octet-stream\",\n        data: item\n      }));\n    this.manifest = {\n      files: this.#files.map(file => ({ name: file.name, size: file.size, type: file.type }))\n    };\n  }\n\n  async upload(instructions: UploadInstructions, options?: UploadOptions): Promise<UploadResult[]> {\n    const outfiles: UploadResult[] = [];\n    let uploadedBytes = 0, uploadedFiles = 0;\n    const totalBytes = this.#files.reduce((acc, file) => acc + file.size, 0);\n    const totalFiles = this.#files.length;\n    const start = Date.now();\n\n    function fireProgressEvent(partialbytes: number) {\n      const curUploaded = uploadedBytes + partialbytes;\n      const timeElapsed = Date.now() - start;\n      options?.onProgress?.({ uploadedBytes: curUploaded, totalBytes, uploadedFiles, totalFiles, uploadSpeed: timeElapsed ? curUploaded / (timeElapsed / 1000) : 0 });\n    }\n\n    fireProgressEvent(0);\n\n    for (const [idx, file] of this.#files.entries()) {\n      for (let offset = 0; offset < file.size; offset += instructions.chunkSize) {\n        let data = file.data.slice(offset, offset + instructions.chunkSize);\n        // Data needs to be a real Blob for XMLHttpRequest to work\n        if (!isRealBlob(data))\n          data = await convertToRealBlob(data);\n        const uploadurl = `${instructions.baseUrl}&offset=${offset}&file=${idx}`;\n\n\n        /* we can't use fetch as we can't do progress tracking there!\n           there's https://stackoverflow.com/questions/35711724/upload-progress-indicators-for-fetch but it requires duplex: half which requires QUIC/H2\n\n           https://fetch.spec.whatwg.org/#fetch-api says\n           The fetch() method is relatively low-level API for fetching resources. It covers slightly more ground than XMLHttpRequest, although it is currently lacking when it comes to request progression (not response progression).\n\n        let bytesUploaded = 0;\n        const progressTrackingStream = new TransformStream<Uint8Array, Uint8Array>({\n          transform(chunk: Uint8Array, controller: TransformStreamDefaultController<Uint8Array>) {\n            controller.enqueue(chunk);\n            bytesUploaded += chunk.byteLength;\n            console.log(\"upload progress:\", bytesUploaded / data.size);\n            // uploadProgress.value = bytesUploaded / totalBytes;\n          },\n          flush(controller: TransformStreamDefaultController<Uint8Array>) {\n            console.log(\"completed stream\");\n          },\n        });\n           */\n        if (options?.signal?.aborted)\n          throw new Error(\"Upload has been aborted\");\n\n        if (globalThis.XMLHttpRequest) { //let's hope by the time browsers drop XMLHttpRequest, fetch finally has proper progress\n          const defer = Promise.withResolvers<void>();\n          const xmlhttp = new globalThis.XMLHttpRequest;\n          xmlhttp.overrideMimeType(\"application/octet-stream\");\n          xmlhttp.upload.addEventListener('progress', ev => fireProgressEvent(ev.loaded));\n          xmlhttp.addEventListener('abort', (ev: ProgressEvent<XMLHttpRequestEventTarget>) => defer.reject(new Error(\"Upload has been aborted\")));\n          xmlhttp.addEventListener('error', (ev: ProgressEvent<XMLHttpRequestEventTarget>) => defer.reject(new Error(\"Error\")));\n          xmlhttp.addEventListener('load', () => defer.resolve()); //invoked on success\n          xmlhttp.addEventListener('loadend', (ev: ProgressEvent<XMLHttpRequestEventTarget>) => { //invoked after either abort/error/load\n          });\n          xmlhttp.open(\"POST\", uploadurl, true);\n          xmlhttp.send(data);\n\n          const doAbort = () => xmlhttp.abort();\n          options?.signal?.addEventListener(\"abort\", doAbort);\n          await defer.promise;\n          options?.signal?.removeEventListener(\"abort\", doAbort);\n        } else { //fallback to fetch(). needed on Node, but it'll break progress reporting\n          const uploadresult = await fetch(uploadurl, {\n            method: \"POST\",\n            headers: { \"Content-Type\": \"application/octet-stream\" },\n            body: data // At some point... .stream().pipeThrough(progressTrackingStream) - but see above why it won't work yet\n          });\n\n          if (!uploadresult.ok)\n            throw new Error(`Upload failed`);\n        }\n\n        uploadedBytes += data.size;\n      }\n\n      outfiles.push({ ...this.manifest.files[idx], token: instructions.sessionId + '#' + idx });\n      ++uploadedFiles;\n      fireProgressEvent(0);\n    }\n\n    return outfiles;\n  }\n}\n\nexport class SingleFileUploader implements UploaderBase {\n  uploader;\n\n  get manifest() {\n    return this.uploader.manifest;\n  }\n\n  constructor(file: File | Blob | ResourceDescriptorCompatible) {\n    this.uploader = new MultiFileUploader([file]);\n  }\n\n  async upload(instructions: UploadInstructions, options?: UploadOptions): Promise<UploadResult> {\n    return (await this.uploader.upload(instructions, options))[0];\n  }\n}\n\nasync function getFilelistFromUser(multiple: boolean, accept: string[]): Promise<File[]> {\n  const defer = Promise.withResolvers<File[]>();\n  if (dompack.dispatchCustomEvent(window, \"wh:requestfiles\", { bubbles: true, cancelable: true, detail: { resolve: defer.resolve, multiple, accept } })) {\n    const input = document.createElement('input');\n    input.type = \"file\";\n    input.multiple = multiple;\n\n    if (accept.length)\n      input.accept = accept.join(\",\");\n    input.addEventListener(\"change\", () => defer.resolve([...input.files || []]));\n    input.addEventListener(\"cancel\", () => defer.resolve([]));\n    input.showPicker();\n  }\n\n  const list = await defer.promise;\n  if (!multiple && list.length > 1)\n    throw new Error(`wh:requestfiles intercepter selected multiple files, but only one was requested`);\n  return list;\n}\n\nexport async function requestFiles(options?: UploadRequestOptions): Promise<File[] | null> {\n  const files = await getFilelistFromUser(!(options?.multiple === false), options?.accept || []);\n  if (!files.length)\n    return null;\n\n  return files;\n}\n\n// We're adding a separate interface for single-file uploads as it's quite annoying to have to deal with interfaces generalized for multiple files if you really, really know you only ever wanted one file anyway\nexport async function requestFile(options?: UploadRequestOptions): Promise<File | null> {\n  const files = await getFilelistFromUser(false, options?.accept || []);\n  if (files.length !== 1)\n    return null;\n\n  return files[0];\n}\n\n/** Convert a file to a data: URL\n * @param file - The file to convert\n * @returns A promise that resolves to the data: URL\n*/\nexport function getFileAsDataURL(file: File): Promise<string> {\n  return new Promise((resolve, reject) => {\n    const reader = new FileReader;\n    // MDN: When the read operation is finished… the loadend event is triggered.\n    reader.addEventListener(\"loadend\", () => {\n      //At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.\n      resolve(reader.result as string);\n    });\n    reader.addEventListener(\"error\", () => reject(new Error(\"Failed to load file\")));\n    reader.readAsDataURL(file);\n  });\n}\n","import * as dompack from '@webhare/dompack';\nimport type { FieldErrorOptions, FormFrontendMessage } from '../formbase';\nimport { debugFlags } from '@webhare/env';\nimport { getFieldDisplayName, getFieldNativeError } from '@webhare/forms/src/domsupport';\n\n///Fired at nodes to apply error\nexport type SetFieldErrorData = {\n  error: FormFrontendMessage;\n  reportimmediately: boolean;\n  serverside: boolean;\n  metadata: unknown;\n};\n\nexport type FieldValidator<E extends HTMLElement = HTMLElement> = (node: E) => Promise<FormFrontendMessage | undefined> | FormFrontendMessage | undefined;\n\nfunction setupServerErrorClear(field: HTMLElement) {\n  const group = field.closest<HTMLElement>('.wh-form__fieldgroup') || field;\n  field.propWhCleanupFunction = () => {\n    group.removeEventListener(\"change\", field.propWhCleanupFunction!, true);\n    group.removeEventListener(\"input\", field.propWhCleanupFunction!, true);\n    group.removeEventListener(\"blur\", field.propWhCleanupFunction!, true);\n    setFieldError(field, '', { serverside: true });\n    field.propWhCleanupFunction = undefined;\n  };\n\n  // to be rightly paranoid (plugins and JS directly editing other fields) we'll blur when anything anywhere seems to change\n  // eg wrd.testwrdauth-emailchange would fail on Chrome without this if the browser window was not currently focused\n  group.addEventListener(\"change\", field.propWhCleanupFunction, true);\n  group.addEventListener(\"input\", field.propWhCleanupFunction, true);\n  if (!field.closest('form[novalidate]')) //if we're doing html5 validation, errors will block submit, so let's already clear on blur\n    group.addEventListener(\"blur\", field.propWhCleanupFunction, true);\n}\n\nclass ComponentValidationState {\n  el: HTMLElement;\n\n  /** Explicitly set error */\n  explicit: {\n    error: FormFrontendMessage;\n    serverside: boolean;\n    reportimmediately: boolean;\n    metadata?: unknown;\n\n  } | null = null;\n\n  /** Dynamic errors (generated by the validation steps, refreshable instead of waiting for explciit errors) */\n  dynamicError: FormFrontendMessage | null = null;\n\n  validators: FieldValidator[] = [];\n\n  constructor(el: HTMLElement) {\n    this.el = el;\n  }\n\n  getState(): { error: FormFrontendMessage; suggested?: never } | { error?: never; suggested: FormFrontendMessage } | null {\n    const err = this.getError();\n    if (err)\n      return { error: err };\n\n    if (this.el.propWhValidationSuggestion)\n      return { suggested: this.el.propWhValidationSuggestion };\n\n    return null;\n  }\n\n  getError(): FormFrontendMessage | null {\n    return this.explicit?.error || this.dynamicError || getFieldNativeError(this.el) || null;\n  }\n\n  hasError(): boolean {\n    return Boolean(this.getError());\n  }\n}\n\nconst validations = new WeakMap<HTMLElement, ComponentValidationState>();\n\nexport function getValidationState(field: HTMLElement) {\n\n  const state = validations.get(field);\n  if (state)\n    return state;\n\n  const newstate = new ComponentValidationState(field);\n  validations.set(field, newstate);\n  return newstate;\n}\n\n/* TODO Are we sure we should expose this API? A form-level setupValidator might be better as we can then re-validate at the proper point in time\n   instead of relying on an external user to enable and shutdown the error. We're mixing two completely different systems with setupValidator (which\n   works nicely with our focusout hadling) and setFieldError (which is extremely stateful and relies on the error-setter managing all the edge cases)\n\n   Oh and serverside errors float somewhere halfway that spectrum.. as we setup explicit clearing callbacks to remove the state we created ourselves.\n*/\nexport function setFieldError(field: Element, error: FormFrontendMessage, options?: Partial<FieldErrorOptions>) {\n  if (!dompack.isHTMLElement(field))\n    throw new Error(`Field is not a valid target for handling errors`);\n\n  const state = getValidationState(field);\n  if (!error) {  //clearing\n    if (!state.explicit)\n      return; //no change\n\n    state.explicit = null;\n    if (debugFlags.fhv)\n      console.log(`[fhv] Clearing error state for ${getFieldDisplayName(field)}`, field, error, options);\n  } else { //changing ?\n    if (debugFlags.fhv)\n      console.log(`[fhv] ${state.explicit ? 'Updating' : 'Setting'} error state for ${getFieldDisplayName(field)}`, field, error, options);\n\n    state.explicit = {\n      error,\n      serverside: options?.serverside || false,\n      reportimmediately: options?.reportimmediately || false,\n      metadata: options?.metadata\n    };\n\n    if (options?.serverside)\n      setupServerErrorClear(field);\n  }\n\n  updateFieldError(field);\n}\n\nexport function updateFieldError(field: HTMLElement) {\n  const state = getValidationState(field);\n\n  dompack.dispatchCustomEvent(field, 'wh:form-setfielderror', //this is where parsley hooks in and cancels to handle the rendering of faults itself\n    {\n      bubbles: true,\n      cancelable: true,\n      detail: {\n        error: state.explicit?.error || getFieldNativeError(field) || '',\n        reportimmediately: state.explicit?.reportimmediately || false,\n        serverside: state.explicit?.serverside || false,\n        metadata: state.explicit?.metadata\n      }\n    });\n}\n\n/** Set up a custom validator\n * @param node - Form element to validate\n * @param checker - Sync or async function that returns a string with an error message or undefined if the field is valid.\n*/\nexport function setupValidator<NodeType extends HTMLElement>(node: NodeType, checker: FieldValidator<NodeType>): void {\n  getValidationState(node).validators.push(checker as FieldValidator);\n\n  //if the checker as a name, we'll add it. otherwise we'll ensure that data-wh-form-custom-validator is set so we can scan for it (and it's probably nice to see it in the dom)\n  node.dataset.whFormCustomValidator = ((node.dataset.whFormCustomValidator || \"\") + \" \" + (checker.name || \"?\")).trim();\n}\n","/**\n * Get ISO-formatted local date from a date (getISOString returns an UTC datetime)\n *\n * @param date - Date to return\n * @returns Date as a YYYY-MM-DD string\n */\nexport function getISOLocalDate(date: Date) {\n  return date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);\n}\n","export function getActiveElement(doc: Document | null): HTMLElement | null {\n  return doc?.activeElement as HTMLElement || null;\n}\n\nexport function getToplevelWindow() {\n  let toplevelwindow: Window = window;\n  while (toplevelwindow.frameElement)\n    toplevelwindow = toplevelwindow.parent;\n  return toplevelwindow;\n}\n\nexport function asIframe(node: Element | null): HTMLIFrameElement | null {\n  return node && (node as HTMLElement)?.matches?.('iframe') ? node as HTMLIFrameElement : null;\n}\n\n/**\n     Find the currently focused element\n *\n    @param limitdoc - If set, only return compontents in the specified document (prevents editable iframes from returning subframes)\n    @returns The element or null\n */\nexport function getCurrentlyFocusedElement(limitdoc?: Document): HTMLElement | null {\n  try {\n    let focused = getActiveElement(getToplevelWindow().document);\n    for (; ;) {\n      const frame = asIframe(focused);\n      if (frame && (!limitdoc || frame.ownerDocument !== limitdoc))\n        focused = getActiveElement(frame.contentDocument);\n      else\n        break;\n    }\n    if (focused && limitdoc && focused.ownerDocument !== limitdoc)\n      return null;\n    return focused;\n  } catch (e) {\n    return null;\n  }\n}\n\n/** Return whether the node is reachable for focus by keyboard navigation\n   (because tabIndex === -1 will be seen a non(keyboard)focusable by this function)\n\n    @param node - Node to test\n    @param ignoreInert - Ignore the inert attribute\n*/\nexport function canFocusTo(node: Element, { ignoreInertAttribute = false } = {}): node is HTMLElement { //returns if a -visible- node is focusable (this function does not check for visibility itself)\n  if (!node.closest) //callers are not necessarily calling us with HTMLElement, eg getClosestValidFocusTarget might supply a document\n    return false;\n  if (!ignoreInertAttribute && node.closest('[inert]'))\n    return false;\n\n  if ((node as HTMLElement).contentEditable === \"true\")\n    return true;\n  if (node.shadowRoot?.delegatesFocus)\n    return true;\n\n  return (node as HTMLElement).tabIndex >= 0 && !(node as HTMLInputElement).disabled && !(node.tagName === 'A' && !(node as HTMLAnchorElement).href);\n}\n\nexport function getFocusableComponents(startnode: Element | null, options?: boolean | { recurseFrames?: boolean; ignoreInertAttribute?: boolean }): HTMLElement[] {\n  if (typeof options !== \"object\") {\n    options = { recurseFrames: options };\n  }\n  let focusable: HTMLElement[] = [];\n  if (!startnode)\n    return focusable;\n  for (const currentnode of startnode.children) {\n    // Get current style (avoid mootools due to cross-frame issues)\n    const currentstyle = getComputedStyle(currentnode);\n    if (!currentstyle || currentstyle.display === \"none\" || currentstyle.visibility === \"hidden\") {\n      //if(currentnode.getStyle) console.log(\"getFocusableComponents skipping\",currentnode, $(currentnode).getStyle(\"display\"), currentnode.getStyle(\"visibility\"))\n      continue;\n    }\n\n    let iframe;\n    if (options?.recurseFrames && (iframe = asIframe(currentnode))) { //might contain more things to focus\n      try {\n        const subnodes = getFocusableComponents(iframe.contentDocument!.documentElement, options);\n        if (subnodes.length)\n          focusable = focusable.concat(subnodes);\n      } catch {\n        //assume permission error\n      }\n    } else if (canFocusTo(currentnode, options)) {\n      focusable.push(currentnode);\n    }\n\n    if ((currentnode as HTMLElement).isContentEditable)\n      continue; //don't look for further focusable nodes inside, the whole RTE counts as an editable component\n\n    const subnodes = getFocusableComponents(currentnode, options);\n    if (subnodes.length)\n      focusable = focusable.concat(subnodes);\n  }\n  return focusable;\n}\n\nexport function getAllFocusableComponents() {\n  return getFocusableComponents(getToplevelWindow().document.documentElement, true);\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\ntype FormatFunction = (value: any) => string | number;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\ntype UpdateFunction = (node: HTMLElement, value: any) => void;\nconst formatters: { [key: string]: FormatFunction } = {};\nconst updaters: { [key: string]: UpdateFunction } = {};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\nfunction mergeNode(node: HTMLElement, set: string, data: any) {\n  const parts = set.split(\":\");\n  const isNodeFunc = parts.length === 1;\n  if (parts.length > 2) {\n    console.error(`Illegal merge expression: '${set}'`, node);\n    return;\n  }\n\n  let func = \"\";\n  let exprpath = (isNodeFunc ? parts[0] : parts[1]).trim();\n\n  const callparts = exprpath.split(\"(\");\n  if (callparts.length > 1) {\n    if (callparts.length !== 2) {\n      console.error(`Illegal merge value: '${set}'`, node);\n      return;\n    }\n\n    func = callparts[0].trim();\n    const funcrest = callparts[1].split(\")\");\n    if (funcrest.length !== 2 || funcrest[1] !== \"\") {\n      console.error(`Illegal merge value: '${set}'`, node);\n      return;\n    }\n    exprpath = funcrest[0].trim();\n  }\n\n  let value = data;\n  if (exprpath !== \"*\") {\n    const exprpathparts = exprpath.split(\".\");\n    for (let i = 0; i < exprpathparts.length; ++i) {\n      value = value[exprpathparts[i].trim()];\n      if (typeof value === \"undefined\")\n        return;\n    }\n  }\n\n  if (isNodeFunc) {\n    if (func && updaters[func])\n      updaters[func](node, value);\n    else if (func)\n      console.error(`Unknown updating function '${func}' in '${set}'`, node);\n    else\n      console.error(`A function is required for merges without a property (in '${set}')`, node);\n    return;\n  }\n\n  const prop = parts[0].trim();\n  if (func) {\n    if (formatters[func])\n      value = formatters[func](value);\n    else {\n      console.error(`Unknown formatting function '${func}' in '${set}'`, node);\n      return;\n    }\n  }\n\n  if (typeof value !== \"string\" && typeof value !== \"number\") {\n    console.error(`Got a value of type ${typeof value} in '${set}'`, node);\n    return;\n  }\n\n  switch (prop) {\n    case 'events':\n    case 'styles':\n    case 'children':\n    case 'on':\n    case \"className\":\n    case \"class\":\n    case 'style':\n    case 'dataset':\n    case 'childNodes':\n      {\n        console.error(`Cannot modify '${prop}' with merge`, node);\n        return;\n      }\n    default:\n      {\n        // 1-to-1 name to property mapping\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we don't know which keys will be set\n        (node as any)[prop] = value;\n        return;\n      }\n  }\n}\n\n/**\n     Apply all merge fields within a node, recursively\n *\n    @param mergenode - Root node to start merging\n    @param data - Merge data\n    @param options - filter: If set, a function that will be called for every node with merge functions. If it returns a falsy value, the node will be skipped.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- we can't know the types passed to merge call\nexport async function run(mergenode: ParentNode, data: any, { filter }: { filter?: (node: Element) => boolean } = {}) {\n  const nodes = mergenode.querySelectorAll('*[data-merge],*[data-wh-merge]') as NodeListOf<HTMLElement>;\n  for (const node of Array.from(nodes)) { //FIXME drop support for data-wh-merge as soon as we've completed the phase out\n    if (node.nodeType !== 1 || (filter && !filter(node)))\n      continue;\n\n    // Parse 'a=b;c=d(e)'\n    const sets = ((node as HTMLElement).dataset.merge || (node as HTMLElement).dataset.whMerge)?.split(\";\");\n    if (sets)\n      for (const set of sets)\n        mergeNode(node, set, data);\n  }\n}\n\n/**\n     Register a formatter function.\n *\n    @param name - Name of the formatter function\n    @param callback - Formatter function. Called with parameter (value), must return a formatted value to write to the property.\n */\nexport function registerFormatter(name: string, callback: FormatFunction) {\n  formatters[name] = callback;\n}\n\n/**\n     Register an updater function (used to update multiple properties of a node at once)\n *\n    @param name - Name of the updater function\n    @param callback - Updater function. Called with parameters (node: HTMLElement, value: Any).\n */\nexport function registerUpdater(name: string, callback: UpdateFunction) {\n  updaters[name] = callback;\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from '@webhare/dompack';\nimport { type DocEvent, type FormControlElement, type TakeFocusEvent, addDocEventListener, isFormControl } from '@webhare/dompack';\nimport * as domfocus from 'dompack/browserfix/focus';\nimport * as webharefields from './internal/webharefields';\nimport * as merge from './internal/merge';\nimport './internal/requiredstyles.css';\nimport { type SetFieldErrorData, getValidationState, setFieldError, setupValidator, updateFieldError } from './internal/customvalidation';\nimport { generateRandomId, isPromise, wrapSerialized } from '@webhare/std';\nimport { debugFlags, dtapStage, navigateTo, type NavigateInstruction } from '@webhare/env';\nimport { getFieldDisplayName, isFieldNativeErrored, isRadioOrCheckbox, isRadioNodeList, type ConstrainedRadioNodeList, parseCondition, getFormElementCandidates, isFormFieldLike, queryFormFieldLike, getFieldName } from '@webhare/forms/src/domsupport';\nimport { rfSymbol } from '@webhare/forms/src/registeredfield';\nimport type { FormAnalyticsEventData, FormAnalyticsSubEvents, FormCondition, FormFileValue, RPCFormMessage } from '@webhare/forms/src/types';\nimport { FieldMapDataProxy, FormFieldMap } from '@webhare/forms/src/fieldmap';\nimport { submitselector, type SubmitSelectorType } from '@webhare/dompack/src/browser';\nimport type { FormSubmitDetails } from './rpc';\nimport type { FormConfiguration } from '@webhare/forms';\n\n//Suggestion or error messages\nexport type FormFrontendMessage = HTMLElement | string;\n\ndeclare global {\n  interface HTMLElement {\n    //TODO Clean this up, these are internal. Move to a dataset, safer against DOM manipulation eg as done by slimselect\n    //Used by formgroups:\n    propWhFormInitialRequired?: boolean;\n    propWhFormCurrentEnabled?: boolean;\n    propWhFormCurrentRequired?: boolean;\n    propWhFormCurrentVisible?: boolean;\n    //Used by formlines:\n    propWhFormlineCurrentVisible?: boolean;\n    propWhValidationSuggestion?: FormFrontendMessage | null;\n    propWhCleanupFunction?: () => void;\n    /** @deprecated Use `getFormHandler` or `getFormData` from `@webhare/forms` to access the form's API */\n    propWhFormhandler?: FormBase<object>;\n    whFormsApiChecker?: () => Promise<void> | void;\n    whUseFormGetValue?: boolean;\n    whValidationPolyfilled?: boolean;\n    __didPlaceholderWarning?: boolean;\n  }\n\n  interface GlobalEventHandlersEventMap {\n    \"wh:form-enable\": CustomEvent<{ enabled: boolean }>;\n    \"wh:form-require\": CustomEvent<{ required: boolean }>;\n    \"wh:form-getvalue\": CustomEvent<{ deferred: PromiseWithResolvers<unknown> }>;\n    \"wh:form-setfielderror\": CustomEvent<SetFieldErrorData>; //TODO can we phase this out? it's a too deep integration\n    \"wh:form-configure\": CustomEvent<FormConfiguration>;\n    \"wh:form-pagechange\": CustomEvent<{\n      formHandler: FormBase<object>;\n      /** TODO Add numPages and currentPage, but we'd need to figure out how to properly account for Captcha pages (you don't want either numPages or currentPage to count that one)\n      numPages: number;\n      currentPage: number;\n      */\n    }>;\n    \"wh:form-preparesubmit\": CustomEvent<{ extrasubmit: Record<string, unknown> }>;\n    \"wh:form-response\": CustomEvent<FormSubmitResult>;\n    \"wh:form-submitted\": CustomEvent<FormSubmitDetails>;\n  }\n}\n\ntype ExtraData = unknown;\n\ntype FormControlDescription = {\n  name: string;\n  multi: false;\n  node: HTMLElement;\n} | {\n  name: string;\n  multi: true;\n  nodes: HTMLInputElement[];\n};\n\nexport type FormResultValue = Record<string, unknown>;\n\n/** The result returned to onSubmitSuccess */\nexport type FormSubmitEmbeddedResult<UserResult = { [key: string]: unknown }> = UserResult & {\n  //webtool submit additions. TODO a future API shouldn't mix these at the same level but allow them in the FormSubmitResult\n  submittype?: string;\n  richvalues?: RichValues;\n  resultsguid?: string;\n  submitinstruction?: NavigateInstruction;\n};\n\nexport interface FormSubmitMessage {\n  name: string;\n  message: string;\n  metadata: unknown;\n}\n\nexport interface FormSubmitResult {\n  success: boolean;\n  //TODO a next form iteration should not mix all these additional props into the form user's 'result'\n  result: FormSubmitEmbeddedResult;\n  errors: FormSubmitMessage[];\n  warnings: FormSubmitMessage[];\n  messages: RPCFormMessage[];\n}\n\ntype RichValues = Array<{ field: string; value: string }>;\n\nexport interface FieldErrorOptions {\n  serverside: boolean;\n  reportimmediately: boolean;\n  metadata?: unknown;\n}\n\ntype LimitSet = undefined | HTMLElement | HTMLElement[];\n\ninterface ValidationOptions {\n  // focusfailed Focus the first invalid element (defaults to true)\n  focusfailed?: boolean;\n  iffailedbefore?: boolean;\n}\n\ninterface FormValidationResult {\n  /// True if the fields successfuly validated\n  valid: boolean;\n  failed: HTMLElement[];\n  firstfailed: HTMLElement | null;\n}\n\ninterface ValidationQueueElement {\n  limitset?: LimitSet;\n  options?: ValidationOptions;\n  defer: PromiseWithResolvers<FormValidationResult>;\n}\n\ninterface PageState {\n  pages: HTMLElement[];\n  curpage: number;\n}\n\nlet delayvalidation = false, validationpendingfor: EventTarget | null = null;\nlet didGlobalHandlers: true | undefined;\n\n/** Convert linefeeds to BR tags */\nfunction lineFeedsToBreaks(text: string): DocumentFragment {\n  const frag = new DocumentFragment;\n  for (const part of text.split(/\\r?\\n/)) {\n    if (frag.childNodes.length)\n      frag.appendChild(document.createElement(\"br\"));\n    frag.append(part);\n  }\n  return frag;\n}\n\nfunction getPageIdx(state: PageState, page: number | HTMLElement) {\n  if (typeof page === 'number') {\n    if (page < 0 || page >= state.pages.length)\n      throw new Error(`Cannot navigate to nonexisting page #${page}`);\n    return page;\n  }\n\n  const idx = state.pages.indexOf(page);\n  if (idx === -1) {\n    console.error(`Cannot find page by element`, page);\n    throw new Error(`Cannot find page`);\n  }\n\n  return idx;\n}\n\nfunction getErrorFields(validationresult: FormValidationResult) {\n  return validationresult.failed.map(field => getFieldName(field) || field.dataset.whFormGroupFor || \"?\")\n    .sort()\n    .filter((value, index, self) => self.indexOf(value) === index) //unique filter\n    .join(\" \");\n}\nfunction hasEverFailed(field: HTMLElement) {\n  if (field.matches(\"input[type=radio],input[type=checkbox]\")) //these are handled by their group, so do the failed check there\n    return field.closest(\".wh-form__fieldgroup\")?.classList.contains('wh-form__field--everfailed');\n\n  return field.classList.contains('wh-form__field--everfailed');\n}\nfunction doValidation(field: EventTarget | null, iffailedbefore: boolean) {\n  if (iffailedbefore || validationpendingfor)\n    releasePendingValidations(); //release any earlier validation. this also cancels 'delayvalidation' but better safe than sorry if we double-run here\n\n  if (delayvalidation) { //Can't be \"iffailedbefore\" as that would have been cleared above\n    if (debugFlags.fhv)\n      console.log(\"[fhv] doValidation: validations are delayed. now pending: \", field);\n    validationpendingfor = field;\n    return;\n  }\n\n  const form = (field as HTMLElement).closest?.('form');\n  if (!form || !form.propWhFormhandler)\n    return;\n\n  const formhandler = form.propWhFormhandler;\n  formhandler.validate([field as HTMLElement], { focusfailed: false, iffailedbefore: iffailedbefore });\n}\n\n\nfunction doDelayValidation() {\n  if (delayvalidation)\n    releasePendingValidations();\n\n  delayvalidation = true;\n}\n\nfunction releasePendingValidations() {\n  if (!delayvalidation)\n    return;\n\n  delayvalidation = false;\n\n  if (validationpendingfor) {\n    const tovalidate = validationpendingfor;\n    if (debugFlags.fhv)\n      console.log(\"[fhv] releasePendingValidations: \", tovalidate);\n    validationpendingfor = null;\n    doValidation(tovalidate, false);\n  }\n}\n\n/* Browser extensions such as 1Password interfere with the event model and may\n   cause focusout to not fire for email and password fields. They don't seem\n   to break focusin so we'll watch focusin to detect missed focusout events */\nlet lastfocusout: EventTarget | null = null;\nfunction handleFocusOutEvent(event: FocusEvent) {\n  lastfocusout = event.target;\n  doValidation(event.target, false);\n}\nfunction handleFocusInEvent(event: FocusEvent) {\n  if (event.relatedTarget && lastfocusout !== event.relatedTarget)\n    doValidation(event.relatedTarget, false);\n}\n\nfunction handleValidateAfterEvent(event: Event) {\n  doValidation(event.target, true);\n}\n\nexport default class FormBase<DataShape extends object = Record<string, unknown>> extends FormFieldMap<DataShape> {\n  /** @deprecated Use node.elements if you want a true HTMLFormControlsCollection, use getElementByName since WH5.4+ for properly typed elements */\n  readonly elements: HTMLFormControlsCollection;\n  private _formsessionid = generateRandomId();\n  private _firstinteraction: number | undefined;\n  protected _submitstart: number | undefined;\n  private validationqueue = new Array<ValidationQueueElement>;\n  private _submitter: SubmitSelectorType | null = null;\n  private _submittimeout: NodeJS.Timeout | undefined;\n  /** Is the form currently interactive? Used to ignore changes done by code/setFieldValue */\n  private isInteractive = true;\n  /** Did we warn about old style form controls? */\n  private didLegacyWarning = false;\n  /** Are we currently in the _submit handler? (prevent duplicate submit attemps while eg. inside onBeforeSubmit) */\n  private inSubmit = false;\n  /** Where should the exitButton navigate to? */\n  private exitButtonNavigateTo?: NavigateInstruction;\n  /** Name of last focused element */\n  #lastFocused = \"\";\n\n  readonly data = new Proxy<DataShape>({} as DataShape, new FieldMapDataProxy(this));\n\n  readonly node: HTMLFormElement;\n\n  constructor(node: HTMLFormElement) {\n    if (node.nodeName !== 'FORM')\n      throw new Error(\"Specified node is not a <form>\"); //we want our clients to be able to assume 'this.node.elements' works\n\n    super(\"\", getFormElementCandidates(node, ''));\n\n    this.node = node;\n\n    this.elements = node.elements;\n    if (this.node.propWhFormhandler)\n      throw new Error(\"Specified node already has an attached form handler\");\n    this.node.propWhFormhandler = this;\n\n    //TODO Can we scope these handlers to the form ? Or register only once needed?\n    if (!didGlobalHandlers) {\n      didGlobalHandlers = true;\n      window.addEventListener(\"mouseup\", releasePendingValidations, true);\n      window.addEventListener(\"focusin\", handleFocusInEvent, true);\n    }\n\n    //Implement webhare fields extensions, eg 'now' for date fields or 'enablecomponents'\n    webharefields.setup(this.node);\n    //Implement page navigation\n    addDocEventListener(this.node, \"click\", evt => this._checkClick(evt));\n    addDocEventListener(this.node, \"dompack:takefocus\", evt => this._onTakeFocus(evt));\n    addDocEventListener(this.node, \"input\", evt => this._onInputChange(), { capture: true });\n    addDocEventListener(this.node, \"change\", evt => this._onInputChange(), { capture: true });\n    addDocEventListener(this.node, 'submit', evt => this._submit(evt, null));\n    addDocEventListener(this.node, 'wh:form-dosubmit', evt => { throw new Error(`wh:form-dosubmit is no longer supported`); });\n    addDocEventListener(this.node, \"wh:form-setfielderror\", evt => this._doSetFieldError(evt));\n    addDocEventListener(this.node, \"mousedown\", doDelayValidation);\n    addDocEventListener(this.node, \"focusout\", handleFocusOutEvent, { capture: true });\n    addDocEventListener(this.node, \"input\", handleValidateAfterEvent, { capture: true });\n    addDocEventListener(this.node, \"change\", handleValidateAfterEvent, { capture: true });\n    addDocEventListener(this.node, \"focusin\", this.#recordLastFocus, { capture: true });\n    this.node.noValidate = true;\n\n    this._rewriteEnableOn();\n    this._updateConditions(true); //Update required etc handlers\n    this._applyPrefills();\n\n    //Update page navigation\n    const pagestate = this._getPageState();\n    this._updatePageVisibility(pagestate.pages, 0);\n    this._updatePageNavigation();\n  }\n\n  static getForNode<DataShape extends object = Record<string, unknown>>(node: HTMLElement): FormBase<DataShape> | null {\n    return (node.propWhFormhandler as FormBase<DataShape>) || null;\n  }\n\n  ///like namedItem but improves on the types returned. does *not* lookup by data-wh-form-name!\n  getElementByName(name: string): FormControlElement | ConstrainedRadioNodeList | null {\n    return this.node.elements.namedItem(name) as FormControlElement | ConstrainedRadioNodeList | null;\n  }\n\n  /** Get language for this form */\n  getLangCode() {\n    return this.node.closest<HTMLElement>('[lang]')?.lang ?? 'en';\n  }\n\n  #recordLastFocus = (evt: dompack.DocEvent<FocusEvent>) => {\n    if (this.node.contains(evt.target)) {\n      const name = getFieldName(evt.target) || evt.target.dataset.whFormGroupFor;\n      if (name)\n        this.#lastFocused = name;\n    }\n  };\n\n  #onUnload = () => {\n    this.sendFormEvent({\n      event: 'abandoned',\n      lastfocused: this.#lastFocused,\n      pagenum: this.getCurrentPageNumber()\n    });\n  };\n\n  protected __formStarted() {\n  }\n\n  protected sendFormEvent(event?: FormAnalyticsSubEvents) {\n    const now = Date.now();\n    if (event?.event === 'submitted')\n      removeEventListener(\"pagehide\", this.#onUnload);\n\n    if (!this._firstinteraction) {   //The user hasn't interacted with the form yet\n      if (!this.isInteractive) { //ignore events triggered by code, eg a form prefill\n        if (event?.event && debugFlags.anl)\n          console.log(`[anl] Form is supressing broadcast of '${event?.event}' because it hasn't been interacted with yet`);\n        return;\n      }\n\n      //The user has interacted, start the clock!\n      this._firstinteraction = now; //set for calculation base *and* to prevent endless loops\n      this.sendFormEvent({ event: \"started\" });\n      addEventListener(\"pagehide\", this.#onUnload);\n    }\n\n    if (!event)\n      return; //we were only triggered to signal First Interaction\n    this._firstinteraction ||= now;\n\n    const pagestate = this._getPageState();\n    const eventdata: FormAnalyticsEventData = {\n      ...event,\n      id: this.node.dataset.whFormId || '',\n      session: this._formsessionid,\n      pagetitle: this._getPageTitle(pagestate.curpage),\n      pagenum: pagestate.curpage + 1,\n      time: now - this._firstinteraction,\n      objref: this.node.dataset.whFormObjref || ''\n    };\n\n    if (this._submitstart) //is set during a pending submission\n      eventdata.waittime = Date.now() - this._submitstart;\n\n    dompack.dispatchCustomEvent(this.node, \"wh:form-analytics\", { bubbles: true, cancelable: false, detail: eventdata });\n  }\n\n  _rewriteEnableOn() { //ADDME move this to webhare server\n    // EnablingComponents may set data-wh-form-enable. input(radio/checkbox) and option qualify\n    type EnablingComponent = HTMLInputElement | HTMLOptionElement;\n\n    // This is the initialization, check the enable components for all elements within the form\n    for (const control of dompack.qSA<EnablingComponent>(this.node, \"*[data-wh-form-enable]\"))\n      for (const element of control.dataset.whFormEnable!.split(\" \")) {\n        const target = this.getElementByName(element);\n        if (target && target instanceof HTMLElement) {\n          const name = (control instanceof HTMLOptionElement ? control.closest<HTMLSelectElement>(\"select\") : control)?.name;\n          if (!name) //duplicated node?\n            continue;\n\n          let ourcondition: FormCondition = { field: name, matchtype: \"IN\", value: control.value };\n          if (target.dataset.whFormEnabledIf) //append to existing criterium\n            ourcondition = { conditions: [parseCondition(target.dataset.whFormEnabledIf), ourcondition], matchtype: \"AND\" };\n          target.dataset.whFormEnabledIf = JSON.stringify({ c: ourcondition });\n        }\n      }\n  }\n\n  _applyPrefills() {\n    //Apply prefills. Set in field order, so controls-enabling-controls things will generally work\n    const searchparams = new URL(location.href).searchParams;\n    for (const field of this._queryAllFields()) {\n      const allvalues = searchparams.getAll(field.name);\n      if (!allvalues.length)\n        continue;\n\n      if (field.multi && field.nodes[0].type === 'checkbox') {\n        for (const node of field.nodes) {\n          const shouldbechecked = allvalues.includes(node.value);\n          if (shouldbechecked !== node.checked) //NOTE: used to read 'field.checked' which doesn't exist so this if() would always evaluate to true\n            this.setFieldValue(node, shouldbechecked);\n        }\n      } else if (field.multi) { //implies radio\n        const tocheck = field.nodes.filter(_ => _.value === allvalues[allvalues.length - 1])[0];\n        if (tocheck && !tocheck.checked)\n          this.setFieldValue(tocheck, true);\n        if (!tocheck)\n          field.nodes.filter(_ => _.checked).forEach(_ => this.setFieldValue(_, false));\n      } else if (field.node.matches(\"input:not([type=file]),select,textarea\")) { //Limit URL prefills to simple elements - TODO allow custom components to decide on this themselves OR *explicitly* require fields to opt-in to being prefillable\n        if (!this._isNowSettable(field.node))\n          continue;\n        this.setFieldValue(field.node, allvalues[allvalues.length - 1]); //last value wins\n      }\n    }\n  }\n\n  /**\n   * Set or update the message for the specified field\n   * @param field - node on which the validation triggered\n   * @param type - type of the message (\"error\" or \"suggestion\") - a field or group can have both an \"error\" and \"suggestion\" visible\n   * @param getError - function which returns a reference to the error node (or DocumentFragment) or a text\n   *\n   * .wh-form__field--error      - Used to indicate this element has an error\n   * .wh-form__field--suggestion - Used to indicate this element has an suggestion\n   * .wh-form__error             - The error message container\n   * .wh-form_suggestion         - The suggestion message container\n   */\n  _updateFieldGroupMessageState(field: HTMLElement, type: \"error\" | \"suggestion\", getError: (field: HTMLElement) => FormFrontendMessage | null) {\n    //Please note that _updateFieldGroupMessageState doesn't *validate* anything - it takes the current error/suggestion status and updates the DOM accordingly\n\n    /*\n    ADDME: ability to show multiple messages in case both the toplevel and a subfield have an error/suggestion.\n           Example: a checkboxgroup in which too many options are selected AND the required textfield of a selected option is empty.\n\n    ADDME: how should an error message reference a required nested textfield?\n\n    ADDME: Support progressive enhancements such as splitdatetime which use a native form element\n           to store the value. (it's probably confusing that aria-described by ends up on an\n           element which needs receives focus and cannot be used to influence/fix the value).\n           (such as the splitdatetime)\n\n           Suggestion for possible solution:\n           - have the progressive enchancement code add an attribute to the native form element\n             with the ID of the (group)element.\n    */\n    const fieldgroup = field.closest<HTMLElement>(\".wh-form__fieldgroup\");\n    //console.log(\"_updateFieldGroupMessageState\", field, fieldgroup);\n    if (!fieldgroup)\n      return;\n\n    /* Within the group this field belongs to we lookup the first node we can find which is marked as having the\n       type of message we want (\"error\" or \"suggestion\").\n       First we'll see if the fieldgroup wants to report something (radio & checkboxes handle their errors at the group level)\n       otherwise whe'll look for the first node which has a message.\n    */\n    const field_with_message = fieldgroup.classList.contains(\"wh-form__field--\" + type) ? fieldgroup : fieldgroup.querySelector<HTMLElement>(\".wh-form__field--\" + type);\n    //Do not pick up errors from deeper groups (array rows)\n    const error = (field_with_message && field_with_message.closest(\".wh-form__fieldgroup\") === fieldgroup ? getError(field_with_message) : null) || null;\n\n    // Now mark the whole .wh-form__fieldgroup as having an error/suggestion\n    fieldgroup.classList.toggle(\"wh-form__fieldgroup--\" + type, Boolean(error));\n\n    // Lookup the error message from the field metadata\n    if (error) { //mark the field has having failed at one point. we will now switch to faster updating error state\n      if (!field.classList.contains('wh-form__field--everfailed')) {\n        if (debugFlags.fhv)\n          console.log('[fhv] marking as everfailed', field, 'because of error', error);\n        field.classList.add('wh-form__field--everfailed');\n      }\n    }\n\n    // Determine the contextnode to set ARIA attributes on\n\n    // ADDME: before looking up a group, check if there an attribute specifying\n    //        another element with role=\"group\" handled the input.\n\n    // Find the first role=\"group\" we can find\n    // (ineither the .wh-form__subfield or .wh-form__field)\n    const potentialgroupnode = field.closest<HTMLElement>(\"[role=group],.wh-form__subfield,wh-form__fieldgroup\");\n    const group = potentialgroupnode?.role === \"group\" ? potentialgroupnode : null;\n    const contextnode = group ?? field;\n\n    let messageid = \"\";\n    let messagenode = fieldgroup.querySelector(\".wh-form__\" + type); //either wh-form__error or wh-form__suggestion\n\n    // Create a container for the suggestion or error\n    if (messagenode) {\n      messageid = messagenode.id; // reuse the existing messagenode\n    } else {\n      if (!error)\n        return; //nothing to do\n\n      // Generate a temporary id for the message which we can use in\n      // the aria-describedby to point to the message.\n      const random = Math.floor((1 + Math.random()) * 0x10000000).toString(16);\n      messageid = \"whform-msg-\" + random; // `${fieldname}-${random}`;\n\n      const suggestionholder = field.closest('.wh-form__fields') || fieldgroup.querySelector('.wh-form__fields') || fieldgroup;\n      messagenode = dompack.create(\"div\", { className: \"wh-form__\" + type }); // add a wh-form__error or wh-form__suggestion message container\n      messagenode.id = messageid; // id to reference to in the aria-describedby\n      suggestionholder.appendChild(messagenode);\n    }\n\n    if (error) { // Do we show a message?\n      messagenode.replaceChildren(typeof error === \"string\" ? lineFeedsToBreaks(error) : error);\n      this._addDescribedBy(contextnode, messageid);\n\n      if (type === \"error\")\n        contextnode.setAttribute(\"aria-invalid\", \"true\");\n    } else {\n      messagenode.replaceChildren(); // remove previous errors/suggestions texts from the errornode\n      this._removeDescribedBy(contextnode, messageid);\n      contextnode.removeAttribute(\"aria-invalid\");\n    }\n\n  }\n\n  // add the specified id of the message element to the list of elements in aria-describedby\n  _addDescribedBy(contextnode: HTMLElement, messageid: string) {\n    const describedby = contextnode.getAttribute(\"aria-describedby\") ?? \"\";\n    const describedby_fields = describedby !== \"\" ? describedby.split(\" \") : [];\n\n    if (describedby_fields.indexOf(messageid) === -1) {\n\n      describedby_fields.push(messageid);\n      contextnode.setAttribute(\"aria-describedby\", describedby_fields.join(\" \"));\n    }\n  }\n\n  // remove the specified id of the message element from the list of elements in aria-describedby\n  _removeDescribedBy(contextnode: HTMLElement, messageid: string) {\n    const describedby = contextnode.getAttribute(\"aria-describedby\") ?? \"\";\n    const describedby_fields = describedby !== \"\" ? describedby.split(\" \") : [];\n\n    for (let idx = 0; idx < describedby_fields.length; idx++) {\n      if (describedby_fields[idx] === messageid) {\n        describedby_fields.splice(idx, 1); // remove that item\n        break;\n      }\n    }\n\n    if (describedby_fields.length > 0)\n      contextnode.setAttribute(\"aria-describedby\", describedby_fields.join(\" \"));\n    else\n      contextnode.removeAttribute(\"aria-describedby\");\n  }\n\n  _updateFieldGroupErrorState(field: HTMLElement) {\n    this._updateFieldGroupMessageState(field, 'error', failedfield => getValidationState(failedfield).getError());\n  }\n\n  _updateFieldGroupSuggestionState(field: HTMLElement) {\n    this._updateFieldGroupMessageState(field, 'suggestion', failedfield => failedfield.propWhValidationSuggestion || '');\n  }\n\n  _doSetFieldError(evt: DocEvent<CustomEvent<SetFieldErrorData>>) {\n    //FIXME properly handle multiple fields in this group reporting errors\n    dompack.stop(evt);\n\n\n    this._reportFieldValidity(evt.target);\n  }\n\n  /** @returns false on error */\n  _reportFieldValidity(node: HTMLElement): boolean {\n    const state = getValidationState(node).getState();\n    node.classList.toggle(\"wh-form__field--error\", Boolean(state?.error));\n    node.classList.toggle(\"wh-form__field--suggestion\", Boolean(state?.suggested));\n\n    this._updateFieldGroupErrorState(node);\n    this._updateFieldGroupSuggestionState(node);\n    return !(state && \"error\" in state);\n  }\n\n  //validate and submit. normal submissions should use this function, directly calling submit() skips validation and busy locking\n  async validateAndSubmit(extradata: ExtraData) {\n    await this._submit(null, extradata);\n  }\n\n  /** Override beforeSubmit to have a last chance to block/confirm actual form submission\n   * @returns true to continue submitting\n  */\n  beforeSubmit(extradata: ExtraData): boolean | Promise<boolean> {\n    return true;\n  }\n\n  async _submit(evt: SubmitEvent | null, extradata: ExtraData) {\n    if (this.node.classList.contains('wh-form--submitting') || this.inSubmit) { //already submitting\n      evt?.preventDefault(); //avoid 'No RPC handler installed' noise during 429 errors\n      return;\n    }\n\n    //A form element's default button is the first submit button in tree order whose form owner is that form element.\n    const submitter = this._submitter || this.node.querySelector(submitselector);\n    this._submitter = null;\n\n    if (debugFlags.fhv)\n      console.log('[fhv] received submit event, submitter:', submitter);\n\n    let tempbutton = null;\n    if (submitter) { //temporarily add a hidden field representing the selected button\n      tempbutton = document.createElement('input');\n      tempbutton.name = submitter.name;\n      tempbutton.value = submitter.value;\n      tempbutton.type = \"hidden\";\n      this.node.appendChild(tempbutton);\n    }\n\n    try {\n      this.inSubmit = true;\n      const beforeResult = this.beforeSubmit(extradata);\n      if (!beforeResult || (isPromise(beforeResult) && !await beforeResult))\n        return;\n\n      /* DEPRECATED - Switch to onBeforeSubmit in 5.7+ */\n      if (!dompack.dispatchCustomEvent(this.node, 'wh:form-beforesubmit', { bubbles: true, cancelable: true })) { //allow parsley to hook into us\n        console.error(\"The use of wh:form-beforesubmit is deprecated and will be removed in a future version. Use onBeforeSubmit instead\");\n        return;\n      }\n\n      await this._doSubmit(evt, extradata);\n    } finally {\n      tempbutton?.remove();\n      this.inSubmit = false;\n    }\n  }\n\n  private _shouldValidateField(el: HTMLElement) {\n    //TODO maybe we can get rid of the data attributes by checking for explicit symbols like whFormsApiChecker\n    return (el.whFormsApiChecker || el.matches(`${queryFormFieldLike},*[data-wh-form-name],*[data-wh-form-custom-validator`)) &&\n      this._isPartOfForm(el);\n  }\n\n  _getFieldsToValidate(startingpoint?: HTMLElement) {\n    return dompack.qSA<HTMLElement>(startingpoint ?? this.node, \"*\").filter(el => this._shouldValidateField(el));\n  }\n\n  //reset any serverside generated errors (generally done when preparing a new submission)\n  resetServerSideErrors() {\n    for (const field of this._getFieldsToValidate()) {\n      const state = getValidationState(field);\n      if (state?.explicit?.serverside && field.propWhCleanupFunction)\n        field.propWhCleanupFunction();\n    }\n  }\n\n  async _doSubmit(evt: SubmitEvent | null, extradata: ExtraData) {\n    if (evt)\n      evt.preventDefault();\n\n    const lock = dompack.flagUIBusy({ modal: true });\n    this._submitstart = Date.now();\n    this._submittimeout = setTimeout(() => this._submitHasTimedOut(), 5000);\n    this.node.classList.add('wh-form--submitting');\n\n    try {\n      this.resetServerSideErrors();\n\n      const validationresult = await this.validate();\n      if (validationresult.valid) {\n        const result = await this.submit(extradata);\n        if (result.result && result.result.submittype && result.result.submittype !== this._getVariableValueForConditions(\"formsubmittype\")) {\n          this.node.setAttribute(\"data-wh-form-var-formsubmittype\", result.result.submittype);\n          this._updateConditions(false);\n        }\n      } else {\n        this.sendFormEvent({ event: \"failed\", errorfields: getErrorFields(validationresult), errorsource: 'client' });\n      }\n    } finally {\n      lock.release();\n      this.node.classList.remove('wh-form--submitting');\n      if (this._submittimeout) {\n        clearTimeout(this._submittimeout);\n        this._submittimeout = undefined;\n      }\n      this._submitstart = undefined;\n    }\n  }\n\n  _submitHasTimedOut() { //TODO extend this to (background) RPCs too, and make waitfor more specific. also check whether we're stuck on client or server side\n    this.sendFormEvent({ event: \"slow\", waitfor: \"submit\" });\n  }\n\n  //default submission function. eg. RPC will override this\n  async submit(extradata?: ExtraData): Promise<{ result?: FormSubmitEmbeddedResult }> {\n    this.node.submit();\n    return {};\n  }\n\n  _onTakeFocus(evt: DocEvent<TakeFocusEvent>) {\n    const containingpage = evt.target.closest('.wh-form__page');\n    if (containingpage && containingpage.classList.contains('wh-form__page--hidden')) {\n      //make sure the page containing the errored component is visible\n      const pagenum = dompack.qSA(this.node, '.wh-form__page').findIndex(page => page === containingpage);\n      if (pagenum >= 0)\n        this.gotoPage(pagenum);\n    }\n  }\n\n  _checkClick(evt: DocEvent<MouseEvent>) {\n    const actionnode = evt.target?.closest<HTMLElement>(\"*[data-wh-form-action]\");\n    if (!actionnode) {\n      const submitter = evt.target.closest<SubmitSelectorType>(submitselector);\n      if (submitter?.form === this.node) { //if we found the submit buton AND it's for *this* form. don't intercept otherwise\n        if (!this.node.classList.contains('wh-form--allowsubmit')) { //we're not allowed to submit yet (not on a final page)\n          dompack.stop(evt);\n          if (this.node.classList.contains('wh-form--allownext'))  //but we can convert your action to a NextPage! which is likely what you intended\n            this.executeFormAction('next');\n          return;\n        }\n\n        this._submitter = submitter; //store as submitter in case a submit event actually occurs\n        setTimeout(() => this._submitter = null); //but clear it as soon as event processing ends\n      }\n      return;\n    }\n\n    dompack.stop(evt);\n    this.executeFormAction(actionnode.dataset.whFormAction!);\n  }\n\n  private _getPageState(): PageState {\n    const pages = dompack.qSA<HTMLElement>(this.node, '.wh-form__page');\n    const curpage = pages.findIndex(page => !page.classList.contains('wh-form__page--hidden'));\n    return { pages, curpage };\n  }\n\n  _updatePageVisibility(pagelist: HTMLElement[], currentpage: number) {\n    pagelist.forEach((page, idx) => {\n      page.classList.toggle('wh-form__page--hidden', idx !== currentpage);\n      page.classList.toggle('wh-form__page--visible', idx === currentpage);\n    });\n  }\n\n  ///Get the currently opened page (page node)\n  getCurrentPage() {\n    const state = this._getPageState();\n    return state.curpage >= 0 ? state.pages[state.curpage] : null;\n  }\n\n  /** Position the specified element's group or the form itself into view, using `.wh-anchor` nodes to correct for fixed headers\n      @param scrollto -  Element to position into view. If not set, the form it scrolled into view */\n  scrollIntoView(scrollto?: HTMLElement) {\n    const origscrollto = scrollto;\n    scrollto = (scrollto ? scrollto.closest<HTMLElement>('.wh-form__fieldgroup') : undefined) || this.node;\n    scrollto = scrollto.querySelector<HTMLElement>('.wh-anchor') || scrollto;\n    if (origscrollto && scrollto !== origscrollto && debugFlags.fhv)\n      console.log('[fhv] Modified scroll target from ', origscrollto, ' to anchor ', scrollto);\n    else if (debugFlags.fhv)\n      console.log('[fhv] Scroll to ', scrollto);\n\n    scrollto.scrollIntoView();\n  }\n\n  /** Get the current page number\n      @returns 0-based index of page to jump to */\n  getCurrentPageNumber() {\n    return this._getPageState().curpage;\n  }\n\n  /** Goto a specific page\n      @param page - 0-based index of page or the HTML element of the page to jump to */\n  async gotoPage(page: number | HTMLElement, { __isSubmit = false } = {}): Promise<void> {\n    const state = this._getPageState();\n    const pageidx = getPageIdx(state, page);\n    if (state.curpage === pageidx)\n      return;\n\n    const goingforward = pageidx > state.curpage;\n    if (!__isSubmit)\n      this.sendFormEvent({\n        event: goingforward ? __isSubmit ? 'submitted' : 'nextpage' : 'previouspage',\n        targetpagenum: pageidx + 1,\n        targetpagetitle: this._getPageTitle(pageidx)\n      });\n\n    this._updatePageVisibility(state.pages, pageidx);\n    if (goingforward) //only makes sense to update if we're making progress\n      merge.run(state.pages[pageidx], { form: await this.getFormValue() });\n\n    this._updatePageNavigation();\n\n    //scroll back up\n    this.scrollIntoView();\n\n    /* tell the page it's now visible - note that we specifically don't fire this on init, as it's very likely\n       users would 'miss' the event anyway - registerHandler usually executes faster than your wh:form-pagechange\n       registrations, if you wrapped those in a dompack.register */\n    dompack.dispatchCustomEvent(state.pages[pageidx], \"wh:form-pagechange\", { bubbles: true, cancelable: false, detail: { formHandler: this } });\n  }\n\n  private _getDestinationPage(pagestate: PageState, direction: number) {\n    let pagenum = pagestate.curpage + direction;\n    //TODO \"captcha\" should no longer exist since WH5.9 - unless there are still some static published forms around, so keep skipping them for a while\n    while (pagenum >= 0 && pagenum < pagestate.pages.length && (pagestate.pages[pagenum].propWhFormCurrentVisible === false || pagestate.pages[pagenum].dataset.whFormPagerole === \"captcha\"))\n      pagenum = pagenum + direction;\n    if (pagenum < 0 || pagenum >= pagestate.pages.length)\n      return -1;\n    return pagenum;\n  }\n\n  _getPageTitle(pagenum: number) {\n    const pagenode = this._getPageState().pages[pagenum];\n    if (!pagenode)\n      return \"\";\n    return pagenode.dataset.whFormPagetitle || (\"#\" + (pagenum + 1));\n  }\n\n  async executeFormAction(action: string) {\n    switch (action) {\n      case 'previous':\n        {\n          if (this.node.classList.contains('wh-form--allowprevious')) {\n            const pagestate = this._getPageState();\n            if (pagestate.curpage > 0)\n              this.gotoPage(this._getDestinationPage(pagestate, -1));\n            else if (this.node.dataset.whFormBacklink)\n              navigateTo({ type: \"redirect\", url: this.node.dataset.whFormBacklink });\n          }\n          return;\n        }\n      case 'next':\n        {\n          const pagestate = this._getPageState();\n          if (this.node.classList.contains('wh-form--allownext')) {\n            this.resetServerSideErrors();\n\n            const validationstatus = await this.validate(pagestate.pages[pagestate.curpage]);\n            if (validationstatus.valid) {\n              this.gotoPage(this._getDestinationPage(pagestate, +1));\n            } else {\n              this.sendFormEvent({ event: \"failed\", errorfields: getErrorFields(validationstatus), errorsource: 'nextpage' });\n            }\n          }\n          return;\n        }\n      case 'exit': {\n        if (!this.exitButtonNavigateTo)\n          throw new Error(\"No exit navigation target set for this form\");\n\n        navigateTo(this.exitButtonNavigateTo);\n        return;\n      }\n      default: {\n        console.error(`Unknown form action '${action}'`);\n      }\n    }\n  }\n\n  async refreshConditions() {\n    await this._updateConditions(false);\n  }\n\n  _onInputChange() {\n    this.sendFormEvent(); //only trigger implicit _firstinteraction event\n    this._updateConditions(false);\n  }\n\n  async _updateConditions(isinit: boolean) {\n    // Check pages visibility\n    const hiddenPages = [];\n    const mergeNodes = [];\n    let anychanges = false;\n\n    for (const formpage of dompack.qSA(this.node, \".wh-form__page\")) {\n      let visible = true;\n      if (formpage.dataset.whFormVisibleIf) {\n        visible = this._matchesCondition(formpage.dataset.whFormVisibleIf);\n        if (!visible)\n          hiddenPages.push(formpage); // We don't have to check fields on this page any further\n\n        if (visible !== formpage.propWhFormCurrentVisible) {\n          anychanges = true;\n          formpage.propWhFormCurrentVisible = visible;\n          mergeNodes.push(formpage);\n        }\n      }\n    }\n    if (anychanges)\n      this._updatePageNavigation();\n\n    const tovalidate = new Array<HTMLElement>;\n    const hiddengroups = [], enabledgroups = [], requiredgroups = [];\n    for (const formgroup of dompack.qSA(this.node, \".wh-form__fieldgroup\")) {\n      const groupPage = formgroup.closest<HTMLElement>(\".wh-form__page\");\n      const visible = (!groupPage || !hiddenPages.includes(groupPage)) && this._matchesCondition(formgroup.dataset.whFormVisibleIf);\n      if (!visible)\n        hiddengroups.push(formgroup);\n\n      const enabled = visible\n        && this._matchesCondition(formgroup.dataset.whFormEnabledIf);\n\n      if (enabled)\n        enabledgroups.push(formgroup);\n\n      //load initial status?\n      if (formgroup.propWhFormInitialRequired === undefined)\n        formgroup.propWhFormInitialRequired = formgroup.classList.contains(\"wh-form__fieldgroup--required\");\n\n      const required = enabled\n        && (formgroup.dataset.whFormRequiredIf ? this._matchesCondition(formgroup.dataset.whFormRequiredIf) : formgroup.propWhFormInitialRequired);\n\n      if (required)\n        requiredgroups.push(formgroup);\n\n      if (visible !== formgroup.propWhFormCurrentVisible // These are initially undefined, so this code will always run first time\n        || enabled !== formgroup.propWhFormCurrentEnabled\n        || required !== formgroup.propWhFormCurrentRequired) {\n        formgroup.propWhFormCurrentVisible = visible;\n        formgroup.propWhFormCurrentEnabled = enabled;\n        formgroup.propWhFormCurrentRequired = required;\n\n        formgroup.classList.toggle(\"wh-form__fieldgroup--disabled\", !enabled);\n        formgroup.classList.toggle(\"wh-form__fieldgroup--hidden\", !visible);\n        formgroup.classList.toggle(\"wh-form__fieldgroup--required\", required);\n\n        mergeNodes.push(formgroup);\n      }\n    }\n\n    for (const formline of dompack.qSA(this.node, \".wh-form__fieldline\")) {\n      const formgroup = formline.closest<HTMLElement>(\".wh-form__fieldgroup\");\n      if (!formgroup)\n        continue;\n      const visible = !hiddengroups.includes(formgroup) && this._matchesCondition(formline.dataset.whFormVisibleIf);\n      const enabled = visible && enabledgroups.includes(formgroup) && this._matchesCondition(formline.dataset.whFormEnabledIf);\n      const required = enabled && requiredgroups.includes(formgroup);\n\n      if (visible !== formline.propWhFormlineCurrentVisible) {  // These are initially undefined, so this code will always run first time\n        formline.propWhFormlineCurrentVisible = visible;\n        formline.classList.toggle(\"wh-form__fieldline--hidden\", !visible);\n      }\n\n      // Look for nodes that are explicit enable state (enablee/require) listeners, or that need to do so because they're real input controls\n      const inputtargets = dompack.qSA(formline, `${queryFormFieldLike},[data-wh-form-state-listener='true']`);\n\n      for (const node of inputtargets) {\n        //Record initial states\n        if (!node.dataset.whFormSavedEnabled)\n          node.dataset.whFormSavedEnabled = (\"disabled\" in node ? !node.disabled : !(\"whFormDisabled\" in node.dataset)).toString();\n\n        if (!node.dataset.whFormSavedRequired)\n          node.dataset.whFormSavedRequired = Boolean(\"required\" in node && node.required).toString();\n\n        // The field is enabled if all of these are matched:\n        // - we're setting it to enabled now\n        // - it hasn't been disabled explicitly (set initially on the node)\n        // - it hasn't been disabled through enablecomponents\n        const node_enabled = enabled && node.dataset.whFormSavedEnabled === \"true\" && this._matchesCondition(node.dataset.whFormEnabledIf);\n\n        /* TODO ideally we'd eliminate 'current enabled/required' states, but we need them as long as some components intercept wh:form-enable and wh:form-require events\n                to know the state we told them to put the component in. we may be able to eliminate those events */\n        //if node.dataset.whFormCurrentEnabled is unset, we may still need to apply disabled state to a fresh field\n        if (!node.dataset.whFormCurrentEnabled || node_enabled !== (node.dataset.whFormCurrentEnabled === \"true\")) {\n          node.dataset.whFormCurrentEnabled = node_enabled ? \"true\" : \"false\";\n\n          // Give the formgroup a chance to handle it\n          if (dompack.dispatchCustomEvent(node, \"wh:form-enable\", { bubbles: true, cancelable: true, detail: { enabled: node_enabled } })) {\n            // Not cancelled, so run our default handler\n            if (isFormFieldLike(node)) //For true html5 inputs we'll use the native attributes. formstatelisteners: we use data attributes\n              node.disabled = !node_enabled;\n            else if (node_enabled)\n              node.removeAttribute(\"data-wh-form-disabled\");\n            else\n              node.setAttribute(\"data-wh-form-disabled\", \"\");\n          }\n\n          if (!isinit && !node_enabled && !tovalidate.includes(node))\n            tovalidate.push(node); // to clear errors for this disabled field\n        }\n\n        const node_required = (node.dataset.whFormSavedRequired === \"true\" || required) && node_enabled && visible;\n        //if node.dataset.whFormCurrentEnabled is unset, we may still need to apply disabled state to a fresh field\n        //if node.dataset.whFormCurrentRequired is unset, we may still need to apply required state to a fresh field\n        if (!node.dataset.whFormCurrentRequired || node.dataset.whFormCurrentRequired !== (node_required ? \"true\" : \"false\")) {\n          node.dataset.whFormCurrentRequired = node_required ? \"true\" : \"false\";\n\n          // Give the formgroup a chance to handle it\n          if (dompack.dispatchCustomEvent(node, \"wh:form-require\", { bubbles: true, cancelable: true, detail: { required: node_required } })) {\n            // Not cancelled, so run our default handler\n            if (isFormFieldLike(node)) { //For true html5 inputs we'll use the native attributes. formstatelisteners: we use data attributes\n              if (!isFormControl(node) || node.type !== 'checkbox') //don't set required on checkboxes, that doesn't do what you want\n                node.required = node_required;\n            } else if (node_required)\n              node.setAttribute(\"data-wh-form-required\", \"\");\n            else\n              node.removeAttribute(\"data-wh-form-required\");\n          }\n\n          if (!isinit && !node_required && formgroup.classList.contains(\"wh-form__fieldgroup--error\") && !tovalidate.includes(node))\n            tovalidate.push(node); // to clear errors for this now optional field\n        }\n      }\n    }\n\n    for (const option of dompack.qSA<HTMLOptionElement>(this.node, \".wh-form__fieldgroup select option\")) {\n      const visible = this._matchesCondition(option.dataset.whFormVisibleIf);\n\n      //Record initial states\n      if (!option.dataset.whFormSavedEnabled)\n        option.dataset.whFormSavedEnabled = (!option.disabled).toString();\n      if (!option.dataset.whFormSavedHidden)\n        option.dataset.whFormSavedHidden = option.hidden.toString();\n\n      const option_enabled = visible && option.dataset.whFormSavedEnabled === \"true\";\n      const option_hidden = !visible || option.dataset.whFormSavedHidden === \"true\";\n\n      if (option_enabled !== (option.dataset.whFormCurrentEnabled === \"true\") || option_hidden !== (option.dataset.whFormCurrentHidden === \"true\")) {\n        option.dataset.whFormCurrentEnabled = option_enabled ? \"true\" : \"false\";\n        option.dataset.whFormCurrentHidden = option_hidden ? \"true\" : \"false\";\n        option.disabled = !option_enabled;\n        option.hidden = option_hidden;\n\n        // If this option was the selected option, but is now disabled (but not the placeholder), reset the select's value\n        const selectnode = option.closest<HTMLSelectElement>(\"select\");\n        if (selectnode && option.selected && (!option_enabled || option_hidden) && option.dataset.placeholder === undefined) {\n          if (selectnode.options[0].dataset.placeholder !== undefined) { //we have a placeholder...\n            selectnode.selectedIndex = 0;\n          } else {\n            selectnode.selectedIndex = -1;\n            if (!selectnode.__didPlaceholderWarning) {\n              selectnode.__didPlaceholderWarning = true;\n              console.warn(\"This <select> lacks an explicit placeholder so we had to set selectedIndex to -1\", selectnode);\n            }\n          }\n        }\n\n        if (selectnode && !isinit && !tovalidate.includes(selectnode))\n          tovalidate.push(selectnode); // to clear errors for this option's select field\n      }\n    }\n\n    if (tovalidate.length)\n      await this.validate(tovalidate, { focusfailed: false, iffailedbefore: true });\n\n    this.fixupMergeFields(mergeNodes);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-misused-promises -- FIXME: needs API rework\n  __scheduleUpdateConditions = wrapSerialized(() => this._updateConditions(false), { coalesce: true });\n\n  async fixupMergeFields(nodes: HTMLElement[]) {\n    // Rename the data-wh-merge attribute to data-wh-dont-merge on hidden pages and within hidden formgroups to prevent\n    // merging invisible nodes\n    // FIXME 'merge' has a filter option now - convert to that!\n    const formvalue = await this.getFormValue();\n    for (const node of nodes) {\n      if (node.propWhFormCurrentVisible) {\n        for (const mergeNode of dompack.qSA(node, '*[data-wh-dont-merge]')) {\n          mergeNode.dataset.merge = mergeNode.dataset.whDontMerge;\n          mergeNode.removeAttribute(\"data-wh-dont-merge\");\n        }\n        merge.run(node, { form: formvalue });\n      } else {\n        for (const mergeNode of dompack.qSA(node, '*[data-merge]')) {\n          mergeNode.dataset.whDontMerge = mergeNode.dataset.merge;\n          mergeNode.removeAttribute(\"data-merge\");\n        }\n      }\n    }\n  }\n\n  _matchesCondition(conditiontext: string | undefined) {\n    if (!conditiontext)\n      return true;\n\n    return this._matchesConditionRecursive(parseCondition(conditiontext));\n  }\n\n  _getConditionRawValue(fieldname: string, options?: { checkdisabled?: boolean }) {\n    if (this.node.hasAttribute(\"data-wh-form-var-\" + fieldname))\n      return this.node.getAttribute(\"data-wh-form-var-\" + fieldname);\n\n    const matchfield = this.getElementByName(fieldname);\n    if (!matchfield) {\n      console.error(`No match for conditional required field '${fieldname}'`);\n      return null;\n    }\n\n    if (isRadioNodeList(matchfield)) {\n      let currentvalue = null;\n\n      for (const field of matchfield)\n        if (((options && options.checkdisabled) || this._isNowSettable(field)) && field.checked) {\n          if (field.type !== \"checkbox\")\n            return field.value;\n\n          if (!currentvalue)\n            currentvalue = [];\n          currentvalue.push(field.value);\n        }\n      return currentvalue;\n    } else {\n      //Can we set this field?\n      if ((!options || !options.checkdisabled) && !this._isNowSettable(matchfield))\n        return null;\n    }\n\n    if (matchfield.type === \"checkbox\")\n      return (matchfield as HTMLInputElement).checked ? [matchfield.value] : null;\n\n    if (matchfield.type === \"radio\")\n      return (matchfield as HTMLInputElement).checked ? matchfield.value : null;\n\n    return matchfield.value;\n  }\n\n  _getVariableValueForConditions(conditionfield: string, options?: { matchcase?: boolean; checkdisabled?: boolean }) {\n    if (this.node.hasAttribute(\"data-wh-form-var-\" + conditionfield))\n      return this.node.getAttribute(\"data-wh-form-var-\" + conditionfield);\n\n    const fields = conditionfield.split(\"$\");\n\n    if (fields.length > 1) {\n      // If the condition field has a subfield, check if it's available through a form var\n      // The '$' in the attribute name is replaced with '.' to make the attribute name valid\n      const attrname = fields.join(\".\");\n      if (this.node.hasAttribute(\"data-wh-form-var-\" + attrname))\n        return this.node.getAttribute(\"data-wh-form-var-\" + attrname);\n    }\n\n    let currentvalue = this._getConditionRawValue(fields[0], options);\n    if (fields.length === 1 || currentvalue === null) //no subs to process\n      return currentvalue;\n\n    // Look for an extrafield match\n    const matchfield = this.getElementByName(fields[0]);\n    if (!matchfield) {\n      console.error(`No match for conditional required field '${conditionfield}'`);\n      return null;\n    }\n\n    if (matchfield instanceof HTMLSelectElement) {\n      if (Array.isArray(currentvalue)) {\n        const selectedvalue = currentvalue;\n        currentvalue = [];\n        for (const val of selectedvalue) {\n          const selected = dompack.qS<HTMLOptionElement>(matchfield, `option[value=\"${CSS.escape(val)}\"]`);\n          if (!selected?.dataset.__extrafields)\n            return null;\n          const extrafields = JSON.parse(selected.dataset.__extrafields);\n          currentvalue.push(extrafields[fields[1]]);\n        }\n      } else {\n        const selected = dompack.qS<HTMLOptionElement>(matchfield, `option[value=\"${CSS.escape(currentvalue)}\"]`);\n        if (!selected?.dataset.__extrafields)\n          return null;\n        const extrafields = JSON.parse(selected.dataset.__extrafields);\n        currentvalue = extrafields[fields[1]];\n      }\n      return currentvalue;\n    } else {\n      console.error(\"Subfield matching not supported for non-select fields\");\n      return null;\n    }\n  }\n\n\n  _matchesConditionRecursive(condition: FormCondition): boolean {\n    switch (condition.matchtype) {\n      case \"AND\":\n        for (const subcondition of condition.conditions)\n          if (!this._matchesConditionRecursive(subcondition))\n            return false;\n        return true;\n\n      case \"OR\":\n        for (const subcondition of condition.conditions)\n          if (this._matchesConditionRecursive(subcondition))\n            return true;\n        return false;\n\n      case \"NOT\":\n        return !this._matchesConditionRecursive(condition.condition);\n\n      case \"AGE<\":\n      case \"AGE>=\": {\n        const currentvalue = this._getVariableValueForConditions(condition.field);\n        if (!currentvalue)\n          return false;\n\n        const now = new Date, birthdate = new Date(Array.isArray(currentvalue) ? currentvalue[0] : currentvalue); //should never be an array, but _getVariableValueForConditions is generic\n        let age = now.getFullYear() - birthdate.getFullYear();\n        //birthdate not hit yet this year? then you lose a year\n        if (now.getMonth() < birthdate.getMonth()\n          || (now.getMonth() === birthdate.getMonth() && now.getDate() < birthdate.getDate())) {\n          --age;\n        }\n\n        return (condition.matchtype === 'AGE<' ? age < condition.value : age >= condition.value);\n      }\n    }\n\n    const currentvalue = this._getVariableValueForConditions(condition.field, condition.options);\n\n    if (condition.matchtype === \"HASVALUE\")\n      return Boolean(currentvalue) === Boolean(condition.value);\n\n    if ([\"IN\", \"HAS\", \"IS\"].includes(condition.matchtype)) {\n      const matchcase = condition.options?.matchcase !== false; // Defaults to true\n      const compareagainst = Array.isArray(condition.value) ? condition.value : condition.value ? [condition.value] : [];\n      const currentValArray: string[] = Array.isArray(currentvalue) ? currentvalue : currentvalue ? [currentvalue] : [];\n\n      // If the match is not case-sensitive, the condition value is already uppercased, so we only have to uppercase the\n      // current value(s) when checking\n      if (!matchcase)\n        currentValArray.forEach((_, idx) => currentValArray[idx] = currentValArray[idx].toUpperCase());\n\n      // The current value and the condition value should (at least) overlap\n      if (!currentValArray.some(value => compareagainst.includes(value)))\n        return false;\n\n      // For \"HAS\" and \"IS\" conditions, all of the required values should be selected (there shouldn't be required values\n      // that are not selected)\n      if ((condition.matchtype === \"HAS\" || condition.matchtype === \"IS\") && compareagainst.some(value => !currentValArray.includes(value)))\n        return false;\n\n      // For an \"IS\" condition, all of the selected values should be required (there shouldn't be selected values that are\n      // not required)\n      if (condition.matchtype === \"IS\" && currentValArray.some(value => !compareagainst.includes(value)))\n        return false;\n\n      return true;\n    }\n\n    return console.error(`No support for conditional type '${condition.matchtype}'`), false;\n  }\n\n  _updatePageNavigation() {\n    const pagestate = this._getPageState();\n    const nextpage = this._getDestinationPage(pagestate, +1);\n    const morepages = nextpage !== -1;\n    const curpagerole = pagestate.pages[pagestate.curpage] ? pagestate.pages[pagestate.curpage].dataset.whFormPagerole : '';\n    const nextpagerole = morepages ? pagestate.pages[nextpage].dataset.whFormPagerole : \"\";\n\n    this.node.classList.toggle(\"wh-form--allowprevious\", Boolean((pagestate.curpage > 0 && curpagerole !== 'thankyou') || (pagestate.curpage <= 0 && this.node.dataset.whFormBacklink)));\n    this.node.classList.toggle(\"wh-form--allownext\", morepages && nextpagerole !== 'thankyou');\n    this.node.classList.toggle(\"wh-form--allowsubmit\", curpagerole === 'thankyou'\n      ? pagestate.pages[pagestate.curpage].dataset.whFormExitButton !== undefined\n      : (!morepages || nextpagerole === 'thankyou'));\n\n    // Also handle the thank you page preparation (changing submit labels, redirecting if necessary)\n    this._prepareThankYouPage(pagestate.curpage);\n  }\n\n  _prepareThankYouPage(nextpage: number) {\n    const state = this._getPageState();\n    if (nextpage !== -1 && state.pages[nextpage] && state.pages[nextpage].dataset.whFormPagerole === 'thankyou') {\n      const rawNavigateTo = state.pages[nextpage].dataset.whFormNavigateTo;\n      const exitButton = state.pages[nextpage].dataset.whFormExitButton;\n      const parsedNavTo = rawNavigateTo ? JSON.parse(rawNavigateTo) : null;\n      if (parsedNavTo)\n        this.exitButtonNavigateTo = parsedNavTo;\n\n      const redirectdelay = parseInt(state.pages[nextpage].dataset.whFormPageredirectDelay ?? \"\");\n\n      if (exitButton) {\n        const submitButton = this.node.querySelector<HTMLElement>(\".wh-form__button--submit\");\n        const submitButtonLabel = submitButton?.querySelector<HTMLElement>(\".wh-form__buttonlabel\");\n        if (submitButton && submitButtonLabel) {\n          submitButton.dataset.whFormAction = \"exit\";\n          submitButtonLabel.textContent = exitButton;\n        } else {\n          console.error(`Unable to find the submit button '.wh-form__button--submit .wh-form__buttonlabel' - I need to replace its label with '${exitButton}'!`);\n        }\n      }\n\n      if (parsedNavTo && !(redirectdelay >= 0) && !exitButton) {\n        navigateTo(parsedNavTo);\n        return;\n      }\n\n      if (parsedNavTo && redirectdelay >= 0) {\n        // If redirectdelay==0 (redirect immediately, while showing the thank you page), redirect after a small delay to\n        // give the browser time to hide the busy layer\n        // Might be caused by this: https://stackoverflow.com/a/60439478\n        setTimeout(() => navigateTo(parsedNavTo), redirectdelay * 1000 || 100);\n      }\n    }\n  }\n\n  _navigateToThankYou(richvalues?: RichValues) {\n    const state = this._getPageState();\n\n    if (state.curpage >= 0) {\n      const nextpage = this._getDestinationPage(state, +1);\n      if (nextpage !== -1 && state.pages[nextpage] && state.pages[nextpage].dataset.whFormPagerole === 'thankyou') {\n        this.updateRichValues(state.pages[nextpage], richvalues);\n        this.gotoPage(nextpage, { __isSubmit: true });\n      }\n    }\n  }\n  updateRichValues(page: HTMLElement, richvalues?: RichValues) {\n    if (richvalues) {\n      for (const { field, value } of richvalues) {\n        const node = page.querySelector(`.wh-form__fieldgroup--richtext[data-wh-form-group-for=\"${CSS.escape(field)}\"] .wh-form__richtext`);\n        if (node) {\n          node.innerHTML = value;\n          dompack.registerMissed(node);\n        }\n      }\n    }\n  }\n\n  private ensureLegacyWarning(field: HTMLElement) {\n    if (!this.didLegacyWarning && dtapStage !== \"production\")\n      console.warn(`[form] ${getFieldDisplayName(field)} is using wh:form-getvalue/wh:form-setvalue events. It should switch to JSFormElement`);\n\n    this.didLegacyWarning = true;\n  }\n\n  /* Override this to overwrite the processing of individual fields. Note that\n     radio and checkboxes are not passed through getFieldValue, and that\n     getFieldValue may return undefined or a promise. */\n  async getFieldValue(field: HTMLElement) {\n    if (field[rfSymbol])\n      return field[rfSymbol].getValue();\n\n    if (field.hasAttribute('data-wh-form-name') || field.whUseFormGetValue) {\n      //create a deferred promise for the field to fulfill\n      const deferred = Promise.withResolvers<unknown>();\n      //if cancelled, we'll assume the promise is taken over\n      if (!dompack.dispatchCustomEvent(field, 'wh:form-getvalue', { bubbles: true, cancelable: true, detail: { deferred } })) {\n        this.ensureLegacyWarning(field);\n        return deferred.promise;\n      }\n    }\n    if (!isFormFieldLike(field)) {\n      /* Can't fail on these, weird embeddings do weird things. Eg google's recaptcha v2 triggers this because it assigns a random name=\n         to the iframe it injects and then we pick that up.. (may need to move this error behind a debugflag if that's the only likely cause) */\n      if (debugFlags.fhv)\n        console.log(`[fhv] Cannot get value on non-FormControl`, field);\n      return undefined; //TODO throw? but wasn't currently fatal\n    }\n\n    if (field.matches('input[type=file]')) //We don't care for multiple yet, as our form RPC APIs don't support that either\n      return [...(field as HTMLInputElement).files || []].map(file => ({ fileName: file.name, file: file, link: null })) satisfies FormFileValue[];\n\n    return field.value;\n  }\n\n  /* Override this to overwrite the setting of individual fields. In contrast\n     to getFieldValue, this function will also be invoked for radio and checkboxes */\n  setFieldValue(fieldnode: HTMLElement, value: unknown) {\n    if (fieldnode[rfSymbol])\n      return fieldnode[rfSymbol].setValue(value);\n\n    if (fieldnode.hasAttribute('data-wh-form-name')) {\n      if (!dompack.dispatchCustomEvent(fieldnode, 'wh:form-setvalue', { bubbles: true, cancelable: true, detail: { value } })) {\n        this.ensureLegacyWarning(fieldnode);\n        return;\n      }\n      // Event is not cancelled, set node value directly\n    }\n\n    if (!isFormFieldLike(fieldnode)) {\n      console.error(`Cannot set value on non-FormControl`, fieldnode, value);\n      return; //TODO throw? but wasn't currently fatal\n    }\n\n    //NOTE this blocks a lot of 'new sets' being done through setFieldValue, eg resetting an array by setting it to []. which is fine for me, just use the data proxy..\n    if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n      console.error(`Setting value of type ${typeof value} on a FormControl`, fieldnode, value);\n      return; //TODO throw? but wasn't currently fatal\n    }\n\n    const saveInteractive = this.isInteractive;\n    try {\n      this.isInteractive = false;\n      if (isFormControl(fieldnode))\n        dompack.changeValue(fieldnode, value);\n      else\n        fieldnode.value = value;\n    } finally {\n      this.isInteractive = saveInteractive;\n    }\n  }\n\n  _isPartOfForm(el: HTMLElement) {\n    //In HTML terms, an input must either have *no* form attribute or explicitly point to us. eg <input form> is *outside* a form\n    //However nodes may live in fragments (eg arrayedits) that are not in the DOM and not attached anywhere, so we also consider anything outside the DOM to be in our form...\n    return !(\"form\" in el) || el.form === this.node || !document.contains(el)\n      || (!this.node && !el.hasAttribute(\"form\")); //FIXME remove this workaround needed now to work around form init race where arrayfields try to use _queryAllFields\n  }\n\n  _queryAllFields(options?: {\n    skiparraymembers?: boolean;\n    skipfield?: HTMLElement;\n    onlysettable?: boolean;\n    startnode?: HTMLElement;\n  }): FormControlDescription[] {\n    const foundfields = new Array<FormControlDescription>;\n    const skiparraymembers = options && options.skiparraymembers;\n\n    for (const field of this._getFieldsToValidate(options?.startnode)) {\n      if (options && field === options.skipfield) //arrayfield.es needs it\n        continue;\n      if (!this._isPartOfForm(field))\n        continue;\n      if (options && options.onlysettable && !this._isNowSettable(field))\n        continue;\n      if (skiparraymembers && field.closest(\".wh-form__arrayrow\"))\n        continue;\n\n      const name = getFieldName(field);\n      if (!name)\n        continue;\n\n      let addto = foundfields.find(_ => _.name === name);\n      if (isRadioOrCheckbox(field)) { //expect multiple inputs with this name?\n        if (!addto) {\n          addto = { name: name, multi: true, nodes: [] };\n          foundfields.push(addto);\n        } else if (!addto.multi) {\n          console.error(`[fhv] Encountered duplicate field '${name}'`, field);\n          continue;\n        }\n        addto.nodes.push(field);\n      } else {\n        if (addto) {\n          console.error(`[fhv] Encountered duplicate field '${name}'`, field);\n          continue;\n        }\n\n        foundfields.push({ name: name, multi: false, node: field });\n      }\n    }\n\n    return foundfields;\n  }\n\n  /** Return the names of all form elements */\n  getFormElementNames() {\n    return this._queryAllFields().map(_ => _.name);\n  }\n\n  /** getValue from a field as returned by _queryAllFields (supporting both multilevel and plain fields)\n      @returns promise */\n  _getQueryiedFieldValue(field: FormControlDescription) {\n    if (!field.multi)\n      return this.getFieldValue(field.node);\n\n    return field.nodes.filter(node => node.checked).map(node => node.value);\n  }\n\n  /** Return a promise resolving to the submittable form value */\n  async getFormValue(): Promise<FormResultValue> {\n    const outdata: FormResultValue = {};\n    const fieldpromises = new Array<Promise<void>>;\n\n    for (const field of this._queryAllFields({ onlysettable: true, skiparraymembers: true }))\n      this._processFieldValue(outdata, fieldpromises, field.name, this._getQueryiedFieldValue(field));\n\n    await Promise.all(fieldpromises);\n    return outdata;\n  }\n\n  _isNowSettable(node: HTMLElement) {\n    // If the node is disabled, it's not settable\n    if (\"disabled\" in node && node.disabled)\n      return false;\n\n    // If the node's field group is disabled or hidden, it's not settable\n    const formgroup = node.closest(\".wh-form__fieldgroup\");\n    if (formgroup) {\n      if (formgroup.classList.contains(\"wh-form__fieldgroup--disabled\"))\n        return false;\n      if (formgroup.classList.contains(\"wh-form__fieldgroup--hidden\"))\n        return false;\n    }\n\n    // If the node's form page is hidden dynamically, it's not settable\n    const formpage = node.closest<HTMLElement>(\".wh-form__page\");\n    if (formpage) {\n      if (formpage.propWhFormCurrentVisible === false)\n        return false;\n    }\n    // The node is settable\n    return true;\n  }\n\n  _processFieldValue(outdata: FormResultValue, fieldpromises: Array<Promise<void>>, fieldname: string, receivedvalue: unknown) {\n    if (receivedvalue === undefined)\n      return;\n    if (isPromise(receivedvalue)) {\n      fieldpromises.push(new Promise<void>((resolve, reject) => {\n        receivedvalue.then(result => {\n          if (result !== undefined)\n            outdata[fieldname] = result;\n\n          resolve();\n        }).catch(e => reject(e as Error));\n      }));\n    } else {\n      outdata[fieldname] = receivedvalue;\n    }\n  }\n\n  //get the option lines associated with a specific radio/checkbox group\n  getOptions(name: string) {\n    const nodes = this.getElementByName(name);\n    if (!(nodes instanceof RadioNodeList))\n      return [];\n\n    return [...nodes].map(node => ({\n      inputnode: node,\n      fieldline: node.closest<HTMLElement>('.wh-form__fieldline'),\n      value: node.value\n    }));\n  }\n\n  /** gets the selected option associated with a radio/checkbox group as an array\n      */\n  getSelectedOptions(name: string) {\n    let opts = this.getOptions(name);\n    opts = opts.filter(node => node.inputnode.checked);\n    return opts;\n  }\n\n  /** get the selected option associated with a radio/checkbox group. returns an object that's either null or the first selected option\n      */\n  getSelectedOption(name: string) {\n    const opts = this.getSelectedOptions(name);\n    return opts.length ? opts[0] : null;\n  }\n\n  /** get the fieldgroup for an element */\n  getFieldGroup(name: string): HTMLElement | null {\n    let node = this.getElementByName(name);\n    if (node instanceof RadioNodeList)\n      node = node[0];\n\n    return node ? node.closest<HTMLElement>('.wh-form__fieldgroup') : null;\n  }\n\n  /** get the values of the currently selected radio/checkbox group */\n  private getValues(name: string) {\n    return this.getSelectedOptions(name).map(node => node.value);\n  }\n  /** get the value of the first currently selected radio/checkbox group */\n  private getValue(name: string) {\n    const vals = this.getValues(name);\n    return vals.length ? vals[0] : null;\n  }\n\n  /** @deprecated Just import setupValidator from \\@mod-publisher/js/forms */\n  static setupValidator(node: HTMLElement, checker: (node: HTMLElement) => Promise<string> | string) {\n    setupValidator(node, checker);\n  }\n\n  /** @deprecated Just import setFieldError from \\@mod-publisher/js/forms */\n  static setFieldError(field: HTMLElement, error: string, options?: Partial<FieldErrorOptions>) {\n    setFieldError(field, error, options);\n  }\n\n  setFieldError(field: HTMLElement, error: string, options?: Partial<FieldErrorOptions>) {\n    setFieldError(field, error, options);\n  }\n\n  async validateSingleFormField(field: HTMLElement): Promise<boolean> {\n    return true;\n  }\n\n  async _validateSingleFieldOurselves(field: HTMLElement): Promise<boolean> {\n    const state = getValidationState(field);\n\n    if (!state.explicit && isFieldNativeErrored(field)) {\n      //browser checks go first, any additional checks are always additive (just disable browserchecks you don't want to apply)\n      updateFieldError(field);\n      return this._reportFieldValidity(field);\n    }\n\n    //TODO we probably *shouldn't* be bothering running our validations if state.explicit is set, but then setFieldError needs to rerun the checks once the explicit error is dropped\n    state.dynamicError = null;\n    await this.validateSingleFormField(field);\n\n    if (!state.dynamicError)\n      for (const validator of state.validators) {\n        state.dynamicError = await validator(field) || null;\n        if (state.dynamicError)\n          break; //one is enough\n      }\n\n    if (!state.dynamicError && field.whFormsApiChecker)\n      await field.whFormsApiChecker();\n\n    return this._reportFieldValidity(field);\n  }\n\n  /** validate the form\n      @param limitset - A single element, nodelist or array of elements to validate (or their children)\n      @returns a promise that will fulfill when the form is validated\n       */\n  async validate(limitset?: LimitSet, options?: ValidationOptions): Promise<FormValidationResult> {\n    if (debugFlags.fdv) {\n      console.warn(`[fdv] Validation of form was skipped`);\n      return { valid: true, failed: [], firstfailed: null };\n    }\n\n    //Overlapping validations are dangerous, because we can't evaluate 'hasEverFailed' too early... if an earlier validation is still running it may still decide to mark fields as failed.\n    const defer = Promise.withResolvers<FormValidationResult>();\n    this.validationqueue.push({ defer, limitset, options });\n    if (this.validationqueue.length === 1)\n      this._executeNextValidation(); //we're first on the queue so process it\n\n    return defer.promise;\n  }\n\n  async _executeNextValidation() {\n    while (this.validationqueue.length) {\n      const item = this.validationqueue[0];\n      try {\n        const result = await this._executeQueuedValidation(item.limitset, item.options);\n        item.defer.resolve(result);\n      } catch (error) {\n        item.defer.reject(error as Error);\n      }\n      this.validationqueue.shift(); //remove the top item\n    }\n  }\n\n  async _executeQueuedValidation(limitset?: LimitSet, options?: ValidationOptions): Promise<FormValidationResult> {\n    const original = limitset;\n    if (!limitset)  //validate entire form if unspecified what to validate\n      limitset = this._getFieldsToValidate();\n\n    const tovalidate = new Set<HTMLElement>;\n    for (const node of Array.isArray(limitset) ? limitset : [limitset]) {\n      /* If you're explicitly validating a radio/checkbox, we need to validate its group (but not recurse down) as that's where radiogroup.es and checkboxgroup.es attach their validations\n         If you're targeting a group, we'll end up validating both the radio/checkbox (directly attached here) and any eg. embedded textedits  */\n      if (node.matches(`input[type=radio],input[type=checkbox]`)) {\n        const group = node.closest<HTMLElement>(\".wh-form__fieldgroup\");\n        if (group)\n          tovalidate.add(group);\n        continue;\n      }\n\n      if (this._shouldValidateField(node))\n        tovalidate.add(node);\n      for (const subnode of this._getFieldsToValidate(node)) //TODO this is overly recursive esp. if limitset is empty...\n        tovalidate.add(subnode);\n    }\n\n    /* This was:\n    tovalidate = Array.from(tovalidate); //we need an array now for further processing\n       but that breaks on some old mootools integrations, see https://gitlab.webhare.com/webharebv/codekloppers/-/issues/677#note_146801\n       wokaround: */\n    let tovalidatelist = [...tovalidate]; //we need an array now for further processing\n\n    if (options && options.iffailedbefore)\n      tovalidatelist = tovalidatelist.filter(node => hasEverFailed(node));\n\n    if (debugFlags.fhv)\n      console.log(\"[fhv] Validation of %o expanded to %d elements: %o\", original, tovalidatelist.length, [...tovalidatelist]);\n\n    const lock = dompack.flagUIBusy();\n    try {\n      if (!tovalidatelist.length)\n        return { valid: true, failed: [], firstfailed: null };\n\n      const validationresults = await Promise.all(tovalidatelist.map(fld => this._validateSingleFieldOurselves(fld)));\n      //remove the elements from validate for which the promise failed\n      const failed = tovalidatelist.filter((fld, idx) => !validationresults[idx]);\n      const result: FormValidationResult = {\n        valid: failed.length === 0,\n        failed: failed,\n        firstfailed: null\n      };\n\n      result.firstfailed = result.failed.length ? result.failed[0] : null;\n      if (result.firstfailed && (!options || options.focusfailed)) {\n        //FIXME shouldn't getFocusableComponents also return startnode if focusable?\n        const tofocus = domfocus.canFocusTo(result.firstfailed) ? result.firstfailed : domfocus.getFocusableComponents(result.firstfailed)[0];\n        if (tofocus)\n          dompack.focus(tofocus, { preventScroll: true });\n\n        this.scrollIntoView(result.firstfailed);\n      }\n\n      if (debugFlags.fhv)\n        console.log(`[fhv] Validation of ${tovalidatelist.length} fields done, ${result.failed.length} failed`, result);\n\n      return result;\n    } finally {\n      lock.release();\n    }\n  }\n\n  async reset() {\n    this.node.reset();\n    if (this.getCurrentPageNumber() > 0)\n      await this.gotoPage(0);\n  }\n}\n","export const rfSymbol = Symbol('RegisteredField');\n\ndeclare global {\n  interface HTMLElement {\n    [rfSymbol]?: FormFieldAPI;\n  }\n}\n\nexport interface FormFieldAPI {\n  getValue(): unknown;\n  setValue(newvalue: unknown): void;\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport { getTid } from \"@webhare/gettid\";\nimport \"./arrayfield.css\";\nimport { throwError } from \"@webhare/std\";\nimport { addDocEventListener, qS, qSA, type DocEvent, registerMissed, stop } from \"@webhare/dompack\";\nimport { getFieldName, getFormElementCandidates, getFormHandler, parseCondition, setFieldName } from \"@webhare/forms/src/domsupport\";\nimport type { FormCondition } from \"@webhare/forms/src/types\";\nimport { RecordFieldHandler, type FormParent } from \"@webhare/forms/src/fieldmap\";\nimport type FormBase from \"../formbase\";\nimport { setup } from \"../internal/webharefields\";\n\n\nfunction fixupConditionRecursive(node: HTMLElement, condition: FormCondition, mapping: Map<string, string>): boolean {\n  switch (condition.matchtype) {\n    case \"AND\":\n    case \"OR\":\n      {\n        let anychanges = false;\n        for (const subcondition of condition.conditions)\n          anychanges = fixupConditionRecursive(node, subcondition, mapping) || anychanges;\n        return anychanges;\n      }\n    case \"NOT\":\n      {\n        return fixupConditionRecursive(node, condition.condition, mapping);\n      }\n    default:\n      {\n        const newName = mapping.get(condition.field);\n        if (newName && node.querySelector(`[name=\"${newName}\"]`)) {\n          condition.field = newName;\n          return true;\n        }\n      }\n  }\n  return false;\n}\n\ntype NewType = FormParent;\n\nexport default class ArrayField {\n  valueNode: HTMLInputElement;\n  nextrowid = 0;\n  template;\n  insertPoint: HTMLElement;\n  arrayBaseName;\n  handler: NewType;\n  node: HTMLElement;\n  name: string;\n\n  constructor(handler: NewType, node: HTMLElement, items: HTMLElement[], name: string) {\n    this.handler = handler;\n    this.node = node;\n    this.name = name;\n    this.arrayBaseName = node.dataset.whFormGroupFor || throwError(\"Missing array base name\");\n\n    // The template for new rows. If we have arrays-in-array, it will still be the first <template>\n    this.template = qS<HTMLTemplateElement>(node, \"template\") || throwError(\"Missing array template\");\n    // The node before which to add new rows\n    this.insertPoint = this.template.parentNode!.lastElementChild! as HTMLElement;\n    if (!this.insertPoint.matches(\".wh-form__arrayadd\"))\n      throw new Error(\"Missing array insert point\");\n\n    // Event handler for add/delete button clicks\n    this.insertPoint.addEventListener(\"click\", event => this.onAddRow(event));\n    addDocEventListener(node, \"click\", event => this._onClick(event));\n\n    // Proxy node for getting/setting properties and receiving events\n    this.valueNode = qS<HTMLInputElement>(node, \"input.wh-form__arrayinput\") ?? throwError(\"Missing array input\");\n    this.valueNode.whUseFormGetValue = true;\n    this.valueNode.addEventListener(\"wh:form-getvalue\", event => this._onGetValue(event));\n    //@ts-expect-error wh:form-setvalue isn't defined - but it'll go away anyway\n    this.valueNode.addEventListener(\"wh:form-setvalue\", event => this._onSetValue(event));\n\n    // Initialize initial value rows\n    for (const rownode of qSA(this.node, \".wh-form__arrayrow\"))\n      this._fixupRowNode(rownode);\n\n    this._checkValidity();\n  }\n\n  get form(): FormBase {\n    const form = getFormHandler(this.node.closest(\"form\") ?? throwError(\"Could not find <form>\")) ?? throwError(\"Could not find form for arrayfield\");\n    if (!form._getFieldsToValidate) //avoid calling into formbase from our constructor, it may not be there yet...\n      throw new Error(\"The <form> is not ready yet\");\n    return form;\n  }\n\n  addRow(): HTMLElement {\n    // Instatiate a new row\n    const newrow = this.template.content.cloneNode(true) as HTMLElement;\n    (newrow.firstElementChild! as HTMLElement).dataset.whFormRowid = String(this.nextrowid++);\n\n    // Insert the new row\n    this.insertPoint.parentNode!.insertBefore(newrow, this.insertPoint);\n    const addedrow = this.insertPoint.previousElementSibling! as HTMLElement;\n\n    /* If the form is relying on legacy dompack.register to go through ImgEditField and do the actual\n       customElements.define call.... then the 'name' attributes won't actually work on the 'new' elements.\n       therefore dompack.registerMissed must run before _fixupRowNode */\n    registerMissed(addedrow);\n    setup(addedrow);\n\n    this._fixupRowNode(addedrow as HTMLElement);\n    this._checkValidity();\n    this.form.__scheduleUpdateConditions();\n    return this.insertPoint.previousSibling as HTMLElement;\n  }\n\n  /* seems a unused API ?.  .. if we need to provide this, just let people pass us a row node instead of understanding IDs\n    removeRow(id)\n    {\n      // Remove a row by id\n      let node = this.node.querySelector(`.wh-form__arrayrow[data-row-id=${id}]`);\n      if (node)\n        this._removeRowNode(node);\n    }\n  */\n\n  private onAddRow(event: Event) {\n    stop(event);\n    this.addRow();\n  }\n  _onClick(event: DocEvent<MouseEvent>) {\n    // Check if a delete button was clicked\n    const delNode = event.target.closest(\".wh-form__arraydelete\");\n    if (delNode) {\n      event.preventDefault();\n      this._removeRowNode(delNode.closest(\".wh-form__arrayrow\")!);\n    }\n  }\n\n  getRowHandler(row: HTMLElement): RecordFieldHandler {\n    const rowBaseName = this.valueNode.name + \".\" + row.dataset.whFormRowid;\n    const rowFields = getFormElementCandidates(row, rowBaseName).filter(_ => _.dataset.whFormCellname !== \"row_uid\"); //row_uid points back to us, so requesting that triggers a loop\n    return new RecordFieldHandler(this.handler, rowBaseName, rowFields);\n  }\n\n  getValue() {\n    const rows = [];\n    for (const row of qSA(this.node, \".wh-form__arrayrow\").filter(n => n.parentNode === this.template.parentNode)) {\n      const handler = this.getRowHandler(row);\n      const rowval = handler.getValue();\n      rows.push(rowval);\n    }\n    return rows;\n  }\n\n  _onGetValue(event: CustomEvent<{ deferred: PromiseWithResolvers<unknown> }>) {\n    // We're using the deferred promise to return our value\n    event.preventDefault();\n    event.stopPropagation();\n\n    // Create a promise for each row that resolves with the combined value of all fields in the row\n    const valuePromises = [];\n    for (const row of qSA(this.node, \".wh-form__arrayrow\").filter(n => n.parentNode === this.template.parentNode)) {\n      const rowFields = this._queryAllFields(row);\n      // Create a promise for each of the row's subfields to get its value\n      const rowPromises = rowFields.map(field => (this.form as FormBase)._getQueryiedFieldValue(field)); //FIXME get rid of 'as FormBase' to support array-in-array\n      // Add an all promise for the value promises and add it to the list of row promises\n      valuePromises.push(Promise.all(rowPromises).then(values => {\n        // Combine the values into a value object for this row\n        const rowValue: Record<string, unknown> = { formrowid: row.dataset.whFormRowid };\n        values.forEach((value, idx) => {\n          // The values are returned in the order that the promises were added to the list of value promises, so we can use\n          // the index of the value to get the original field\n          const rowField = rowFields[idx];\n          const firstnode = rowField.multi ? rowField.nodes[0] : rowField.node;\n          rowValue[firstnode.dataset.whFormCellname!] = value;\n        });\n        return rowValue;\n      }));\n    }\n    // Wait for all the row promises (which resolves with a list of promise resolution values, which will be the final value\n    // of the array field)\n    Promise.all(valuePromises).then(valueRows => event.detail.deferred.resolve(valueRows));\n  }\n\n  setValue(newvalue: unknown[]) {\n    if (!Array.isArray(newvalue))\n      throw new Error(`Invalid value for array field '${this.name}': ${JSON.stringify(newvalue)}`);\n\n    // Remove all current rows (TODO optimize)\n    while (this.insertPoint.previousElementSibling?.classList.contains(\"wh-form__arrayrow\"))\n      this._removeRowNode(this.insertPoint.previousElementSibling);\n\n    // Check if we have an array value\n    for (const value of newvalue) {\n      // Add a row\n      const row = this.addRow();\n      const handler = this.getRowHandler(row);\n      handler.setValue(value);\n    }\n    this._checkValidity();\n  }\n\n  _onSetValue(event: CustomEvent<{ value: unknown }>) {\n    event.preventDefault();\n    event.stopPropagation();\n\n    // Remove all current rows\n    while (this.insertPoint.previousElementSibling?.classList.contains(\"wh-form__arrayrow\"))\n      this._removeRowNode(this.insertPoint.previousElementSibling);\n\n    // Check if we have an array value\n    if (Array.isArray(event.detail.value)) {\n      for (const value of event.detail.value) {\n        // Add a row\n        const row = this.addRow();\n        // Initialize the row's fields\n        for (const field of this._queryAllFields(row)) {\n          for (const fieldnode of (field.multi ? field.nodes : [field.node])) {\n            if (fieldnode.dataset.whFormCellname && fieldnode.dataset.whFormCellname in value) {\n              (this.form as FormBase).setFieldValue(fieldnode, value[fieldnode.dataset.whFormCellname]); //FIXME get rid of 'as FormBase' to support array-in-array\n            }\n          }\n        }\n      }\n    }\n    this._checkValidity();\n  }\n\n  _fixupRowNode(node: HTMLElement) {\n    const rowid = node.dataset.whFormRowid;\n\n    // Rename all fields to avoid duplicate field names\n    const mapping = new Map<string, string>;\n    for (const fieldnode of getFormElementCandidates(node, this.arrayBaseName)) {\n\n      // Leave embedded arrayfields alone! Except if this is specifically the wh-form__arrayinput one level down\n      const nodeArray = fieldnode.closest(\".wh-form__fieldgroup--array\");\n      if (nodeArray && nodeArray !== this.node && !(fieldnode.matches(\".wh-form__arrayinput\") && (nodeArray.parentNode! as HTMLElement).closest(\".wh-form__fieldgroup--array\") === this.node)) {\n        // console.log(\"Skipping\", fieldnode, \"as it's not in our array\");\n        continue;\n      }\n\n      // Rename fields\n      const fieldname = getFieldName(fieldnode);\n      // When rendering, the fields simply have their arrayname prefixed in their name=, see InstantiateField in array.whlib (TODO seems dangerous, eg preset radio buttons interfering with each other?\n      // So we'll just take the part after the first dot as the cellname\n      fieldnode.dataset.whFormCellname ||= fieldname.substring(this.arrayBaseName.length + 1);\n\n      const cellname: string = fieldnode.dataset.whFormCellname;\n      const subname = this.valueNode.name + \".\" + rowid + \".\" + cellname;\n      // console.log(\"for\", this.name, \"rename\", fieldname, \"to\", subname, fieldnode);\n      setFieldName(fieldnode, subname);\n      mapping.set(fieldname, subname);\n\n      // Rename id's to make them unique; update the labels within the field's fieldgroup to point to the new id\n      if (fieldnode.id) {\n        const labelnodes = qSA<HTMLLabelElement>(node, `label[for=\"${fieldnode.id}\"]`);\n        fieldnode.id += \"-\" + rowid;\n        for (const labelnode of labelnodes)\n          labelnode.htmlFor = fieldnode.id;\n      }\n\n      // Rewrite conditions after all fields have been renamed\n      for (const type of [\"visible\", \"enabled\", \"required\"]) {\n        for (const conditionnode of qSA(node, `[data-wh-form-${type}-if]`)) {\n          const condition = parseCondition(conditionnode.dataset[`whForm${type[0].toUpperCase() + type.slice(1)}If`]!);\n          if (fixupConditionRecursive(node, condition, mapping))\n            conditionnode.dataset[`whForm${type[0].toUpperCase() + type.slice(1)}If`] = JSON.stringify({ c: condition });\n        }\n      }\n    }\n\n    this.getRowHandler(node); //initializes deeper arrays. fieldmap should probably be handling this and build a full mapping top to botom...\n  }\n\n  _removeRowNode(node: Element) {\n    // Remove the row node\n    node.remove();\n    this._checkValidity();\n  }\n\n  _checkValidity() {\n    const minRows = parseInt(this.valueNode.dataset.whMin || \"0\");\n    const maxRows = parseInt(this.valueNode.dataset.whMax || \"0\");\n\n    const numRows = this.node.querySelectorAll(\".wh-form__arrayrow\").length;\n    if (numRows < minRows)\n      this.valueNode.setCustomValidity(getTid(\"publisher:site.forms.commonerrors.minarray\", minRows));\n    else if (maxRows > 0 && numRows > maxRows)\n      this.valueNode.setCustomValidity(getTid(\"publisher:site.forms.commonerrors.maxarray\", maxRows));\n    else\n      this.valueNode.setCustomValidity(\"\");\n\n    // Disable the add button if the maximum number of rows is reached\n    if (maxRows > 0 && numRows >= maxRows)\n      this.node.classList.add(\"wh-form__array--maxrows\");\n    else\n      this.node.classList.remove(\"wh-form__array--maxrows\");\n  }\n\n  _queryAllFields(node: HTMLElement) {\n    return (this.form as FormBase)._queryAllFields({ startnode: node, skipfield: this.valueNode });  //FIXME get rid of 'as FormBase' to support array-in-array\n  }\n}\n","import { getFieldName } from \"./domsupport\";\nimport { rfSymbol, type FormFieldAPI } from \"./registeredfield\";\nimport ArrayField from \"@mod-publisher/js/forms/fields/arrayfield\";\nimport type { AddressValue } from \"@webhare/address\";\nimport { omit, nameToSnakeCase, nameToCamelCase, throwError, isDate } from \"@webhare/std\";\nimport type { RecursivePartial } from \"@webhare/js-api-tools\";\nimport type { FormFieldLike } from \"./jsformelement\";\n\nexport interface FormParent {\n  __scheduleUpdateConditions(): void;\n}\n\n\ninterface FormField {\n  getValue(): unknown;\n\n  /** Set a value\n   * @param newvalue - The new value to set\n   * @param ignoreInvalid - Do not throw if the value is invalid. Used for eg. prefills which can't usefully handle it anyway\n   * @returns True if succesfully set */\n\n  setValue(newvalue: unknown): void;\n}\n\ntype ValueType = \"number\" | \"boolean\" | \"date\";\n\nfunction unmapFieldName(camelCaseName: string) {\n  return camelCaseName.startsWith(\"__formfield\") ? camelCaseName : nameToSnakeCase(camelCaseName);\n\n}\nfunction mapFieldName(htmlName: string) {\n  return htmlName.startsWith(\"__formfield\") ? htmlName : nameToCamelCase(htmlName);\n}\n\nfunction mapValue(type: ValueType, invalue: string) {\n  switch (type) {\n    case \"number\":\n      return parseFloat(invalue);\n    case \"boolean\":\n      return invalue === \"true\";\n    case \"date\":\n      return new Date(invalue);\n  }\n}\n\nfunction unmapValue(type: ValueType | undefined, invalue: unknown, fieldDescr: string) {\n  switch (type) {\n    case null:\n      if (typeof invalue !== \"string\")\n        throw new Error(`Invalid type ${typeof invalue} for string field ${fieldDescr}: ${invalue}`);\n      return invalue;\n\n    case \"number\":\n      if (typeof invalue !== \"number\")\n        throw new Error(`Invalid type ${typeof invalue} for number field ${fieldDescr}: ${invalue}`);\n      return String(invalue);\n\n    case \"boolean\":\n      if (typeof invalue !== \"boolean\")\n        throw new Error(`Invalid type ${typeof invalue} for boolean field ${fieldDescr}: ${invalue}`);\n      return String(invalue);\n\n    case \"date\":\n      if (!isDate(invalue))\n        throw new Error(`Invalid type ${typeof invalue} for date field ${fieldDescr}: ${invalue}`);\n      return invalue.toISOString();\n  }\n}\n\nclass HTMLFormFieldHandler implements FormField {\n  valuetype?: ValueType;\n  private form: FormParent;\n  private readonly field: FormFieldLike;\n\n  constructor(form: FormParent, field: FormFieldLike) {\n    this.form = form;\n    this.field = field;\n    this.valuetype = field.dataset.whFormValueType as undefined | ValueType;\n    if (!this.valuetype && field.matches('input[type=number]'))\n      this.valuetype = \"number\";\n  }\n\n  getValue(): unknown {\n    if (this.field.matches('input[type=checkbox]'))\n      return (this.field as HTMLInputElement).checked;\n    if (this.field.matches('input[type=date]'))\n      return (this.field as HTMLInputElement).valueAsDate;\n\n    if (this.field.tagName === \"SELECT\") {\n      const selectedrow = (this.field as HTMLSelectElement).selectedOptions[0];\n      if (!selectedrow || selectedrow.dataset.placeholder !== undefined)\n        return null; //didn't select a 'real' option\n\n      return this.valuetype ? mapValue(this.valuetype, selectedrow.value) : selectedrow.value;\n    }\n\n    return this.valuetype ? mapValue(this.valuetype, this.field.value as string) : this.field.value;\n  }\n\n  setValue(newvalue: unknown): void {\n    if (this.field.matches('input[type=checkbox]')) {\n      //For convenience we're interpreting setting a checkbox as 'truthy' instead of explicit true/false\n      const setvalue = Boolean(newvalue);\n      if (setvalue === (this.field as HTMLInputElement).checked)\n        return;\n\n      (this.field as HTMLInputElement).checked = setvalue;\n    } else if (this.field.matches('input[type=date]')) {\n      if ((this.field as HTMLInputElement)?.valueAsDate?.getTime() === (newvalue as Date | null)?.getTime())\n        return;\n      (this.field as HTMLInputElement).valueAsDate = newvalue as Date;\n    } else if (this.field.tagName === \"SELECT\" && newvalue === null) { //'null' resets the select to 'no value', so figure out if there's a placeholder row\n      const setvalue = (this.field as HTMLSelectElement).options[0]?.dataset.placeholder !== undefined ? 0 : -1;\n      if ((this.field as HTMLSelectElement).selectedIndex === setvalue)\n        return;\n      (this.field as HTMLSelectElement).selectedIndex = setvalue;\n    } else {\n      const setvalue = this.valuetype ? unmapValue(this.valuetype, newvalue, this.field.name) : newvalue;\n      if (this.field.value === setvalue)\n        return;\n      this.field.value = setvalue;\n    }\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\nclass RadioFormFieldHandler implements FormField {\n  valuetype?: ValueType;\n  private form: FormParent;\n  private readonly name: string;\n  private readonly rnodes: HTMLInputElement[];\n\n  constructor(form: FormParent, name: string, rnodes: HTMLInputElement[]) {\n    this.form = form;\n    this.name = name;\n    this.rnodes = rnodes;\n    const group = rnodes[0].closest<HTMLElement>(\".wh-form__fieldgroup\");\n    if (!group) { //value metadata is stored at the fieldgroup level, so reject these\n      console.error(\"Missing group for radiofield \", group);\n      console.error('if a radio field does not want to participate in the form, it should set attribute form=\"\"');\n    } else {\n      this.valuetype = group.dataset.whFormValueType as undefined | ValueType;\n    }\n  }\n  getValue(): unknown {\n    const node = this.rnodes.find(_ => _.checked);\n    return (node ? this.valuetype ? mapValue(this.valuetype, node.value) : node.value : null);\n  }\n  setValue(newvalue: unknown): void {\n    if (newvalue === null) {\n      for (const node of this.rnodes)\n        node.checked = false;\n\n      this.form.__scheduleUpdateConditions();\n      return;\n    }\n\n    const myname = `radio group ${this.name}`;\n    const setvalue = unmapValue(this.valuetype, newvalue, myname);\n\n    const node = this.rnodes.find(_ => _.value === setvalue);\n    if (!node)\n      throw new Error(`No such value '${setvalue}' in radio group '${this.name}`);\n\n    node.checked = true;\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\nclass CheckboxGroupHandler implements FormField {\n  valuetype?: ValueType;\n  private form: FormParent;\n  private readonly name: string;\n  private readonly cboxes: HTMLInputElement[];\n\n  constructor(form: FormParent, name: string, cboxes: HTMLInputElement[]) {\n    this.form = form;\n    this.name = name;\n    this.cboxes = cboxes;\n    this.valuetype = (cboxes[0].closest<HTMLElement>(\".wh-form__fieldgroup\") ?? throwError(\"RadioFormFieldHandler: Missing group\")).dataset.whFormValueType as undefined | ValueType;\n  }\n  getValue(): unknown {\n    return this.cboxes.filter(_ => _.checked).map(_ => this.valuetype ? mapValue(this.valuetype, _.value) : _.value);\n  }\n  setValue(newvalue: unknown): void {\n    const myname = `checkbox group '${this.name}'`;\n    if (!Array.isArray(newvalue))\n      throw new Error(`Value for ${myname} should be an array, got '${JSON.stringify(newvalue)}'`);\n\n    const toset = newvalue.map(_ => unmapValue(this.valuetype, _, myname));\n\n    this.cboxes.forEach(_ => _.checked = toset.includes(_.value));\n    this.form.__scheduleUpdateConditions();\n\n    //in case the error is caught and ignored (eg prefill), we'll update what we can\n    const missing = toset.filter(_ => !this.cboxes.some(cbox => cbox.value === _));\n    if (missing.length)\n      throw new Error(`Invalid value(s) for ${myname}: ${missing.join(', ')}`);\n  }\n}\n\nclass RegisteredFieldHandler implements FormField {\n  protected form: FormParent;\n  private readonly field: FormFieldAPI;\n\n  constructor(form: FormParent, field: FormFieldAPI) {\n    this.form = form;\n    this.field = field;\n  }\n\n  getValue(): unknown {\n    return this.field.getValue();\n  }\n  setValue(newvalue: unknown): void {\n    this.field.setValue(newvalue);\n  }\n}\n\nexport class ArrayFieldHandler extends RegisteredFieldHandler implements FormField {\n  private node: HTMLElement;\n\n  constructor(form: FormParent, node: HTMLElement, items: HTMLElement[]) {\n    node[rfSymbol] ||= new ArrayField(form, node, items, getFieldName(items[0]));\n    super(form, node[rfSymbol]);\n    this.node = node;\n  }\n\n  __scheduleUpdateConditions() {\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\n/** The FormFieldMap exposes a multi-level (ie unflattened) view of the form values. Internally it works with the\n   original names because generated fields names, eg __formfieldbbbwVsWih_0DrJOc0beS7Q_, cannot be assumed to be snake_case and convertable */\nexport abstract class FormFieldMap<DataShape> {\n  /** Field mapping. Uses original names */\n  protected fieldmap = new Map<string, FormField>();\n  protected fieldName: string;\n\n  constructor(fieldName: string, nodes: HTMLElement[]) {\n    this.fieldName = fieldName;\n    const subpos = fieldName ? fieldName.length + 1 : 0;\n    const groups = Map.groupBy(nodes, _ => getFieldName(_).substring(subpos).split('.')[0]);\n\n    for (const [name, items] of groups) {\n      const fullName = (fieldName ? fieldName + '.' : '') + name;\n      if (!name) {\n        console.error(`There are fields without a name:`, items);\n        continue;\n      }\n\n      if (items[0].matches('input[type=radio]')) {\n        this.fieldmap.set(name, new RadioFormFieldHandler(this, fullName, items as HTMLInputElement[]));\n        continue;\n      }\n\n      if (items[0].matches('.wh-form__arrayinput')) {\n        const arraygroup = items[0].closest<HTMLElement>('.wh-form__fieldgroup--array');\n        if (arraygroup) {\n          this.fieldmap.set(name, new ArrayFieldHandler(this, arraygroup, items));\n          continue;\n        }\n      }\n\n      const hasGroupLeader = getFieldName(items[0]) === fullName; //ie name has no followup '.xx'\n      if (hasGroupLeader) { //if no subname, it's the group leader ?\n        if (items[0].matches('input[type=checkbox]')) {//is it a checkbox group?\n          const cboxgroup = items[0].closest(\".wh-form__fieldgroup--checkboxgroup\");\n          if (cboxgroup) {\n            this.fieldmap.set(name, new CheckboxGroupHandler(this, fullName, items as HTMLInputElement[]));\n            continue;\n          }\n        }\n\n        this.fieldmap.set(name, new HTMLFormFieldHandler(this, items[0] as FormFieldLike));\n        continue;\n      }\n\n      //We're an implicit record (even if with just one member)\n      if (items[0].matches('select[name$=\".country\"][data-orderingdata]')) //looks like address.whlib\n        this.fieldmap.set(name, new AddressFieldHandler(this, fullName, items));\n      else\n        this.fieldmap.set(name, new RecordFieldHandler(this, fullName, items));\n    }\n  }\n\n  abstract __scheduleUpdateConditions(): void;\n\n  /** Get a field handler by name */\n  getField(name: string, options: { allowMissing: true }): FormField | null;\n  getField(name: string, options?: { allowMissing?: boolean }): FormField;\n\n  getField(name: string, options?: { allowMissing?: boolean }): FormField | null {\n    const mapName = unmapFieldName(name);\n    const match = this.fieldmap.get(mapName);\n    if (match)\n      return match;\n    if (options?.allowMissing)\n      return null;\n\n    throw new Error(`Field '${name}' not found in this form`); //TODO report the fukll anme\n  }\n\n  getFieldNames(): string[] {\n    return [...this.fieldmap.keys()].map(mapFieldName);\n  }\n\n  /** Set a value for multiple fields\n   * @param data - The data to set\n   * @param ignoreUnknownFields - Do not throw if a field is not found in the form. This is the default\n   */\n  assign(data: RecursivePartial<DataShape>, { ignoreUnknownFields = true } = {}) {\n    for (const [key, value] of Object.entries(data as object)) {\n      const field = this.getField(key, { allowMissing: ignoreUnknownFields });\n      if (field)\n        field.setValue(value);\n    }\n  }\n}\n\nexport class RecordFieldHandler extends FormFieldMap<object> implements FormField {\n  private form: FormParent;\n\n  constructor(form: FormParent, baseName: string, nodes: HTMLElement[]) {\n    super(baseName, nodes);\n    this.form = form;\n  }\n\n  getValue(): unknown {\n    const retval: Record<string, unknown> = {};\n    for (const [name, field] of this.fieldmap) {\n      const val = field.getValue();\n      if (val !== undefined) //Suppress undefined values (where we cannot safely re-set them, eg images in Object.keys\n        retval[mapFieldName(name)] = val;\n    }\n\n    return retval;\n  }\n\n  setValue(newvalue: unknown): void {\n    if (typeof newvalue !== 'object' || newvalue === null)\n      throw new Error(`Invalid value for record field '${this.fieldName}': ${newvalue}`);\n\n    for (const [name, field] of this.fieldmap) {\n      const prettyName = mapFieldName(name);\n      if (prettyName in newvalue)\n        field.setValue((newvalue as Record<string, unknown>)[prettyName]);\n    }\n  }\n\n  __scheduleUpdateConditions() {\n    this.form.__scheduleUpdateConditions();\n  }\n}\n\n/* TODO cleanup... this is a workaround to translate nr_detail to houseNumber. ideally the server would just send house_number as field\n        name but that transition will take time. also we need a nice way to 'take over' addressifelds rather than fieldmapper special casing\n        its detection\n*/\ntype OldAddressValue = Omit<AddressValue, \"houseNumber\"> & { nrDetail?: string };\n\nclass AddressFieldHandler extends RecordFieldHandler {\n  constructor(form: FormParent, baseName: string, nodes: HTMLElement[]) {\n    super(form, baseName, nodes);\n  }\n\n  getValue(): unknown {\n    const val = super.getValue() as OldAddressValue;\n    if (!val?.country)\n      return null;\n\n    return val?.nrDetail !== undefined ? { ...omit(val, [\"nrDetail\"]), houseNumber: val.nrDetail } : val;\n  }\n\n  setValue(val: unknown) {\n    if (val === null) {\n      super.setValue({ country: null, city: \"\", street: \"\", zip: \"\", nrDetail: \"\", state: \"\" });\n      return;\n    }\n\n    ///@ts-expect-error ugly hack, not really worth overwriting with as\n    super.setValue(val?.houseNumber !== undefined ? { ...omit(val, [\"houseNumber\"]), nrDetail: val.houseNumber } : val);\n  }\n}\n\nexport class FieldMapDataProxy implements ProxyHandler<object> {\n  private readonly form: FormFieldMap<object>;\n\n  constructor(form: FormFieldMap<object>) {\n    this.form = form;\n  }\n  get(target: object, p: string | symbol) {\n    //Don't attempt to validate getters... it will break various introspection calls (eg requesting constructor, checking for 'then'...)\n    const field = typeof p === \"string\" ? this.form.getField(p, { allowMissing: true }) : null;\n    return field ? field.getValue() : (target as Record<string | symbol, unknown>)[p];\n  }\n  set(target: unknown, p: string, value: unknown): boolean {\n    this.form.getField(p).setValue(value);\n    return true;\n  }\n  ownKeys(target: object): ArrayLike<string | symbol> {\n    return this.form.getFieldNames();\n  }\n  getOwnPropertyDescriptor(target: unknown, prop: string) { // allows ownKeys to actually return to Object.keys\n    return { enumerable: true, configurable: true };\n  }\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from \"@webhare/dompack\";\nimport FormBase from \"../formbase\";\nimport { debugFlags } from \"@webhare/env\";\nimport { verifyHareScriptAddress, type HareScriptAddressValidationResult, type AddressChecks, type HareScriptAddressValue } from \"@webhare/forms/src/address\";\nimport { setFieldError } from \"../internal/customvalidation\";\nimport { throwError } from \"@webhare/std\";\n\nclass SubField {\n  node;\n  fieldgroup: HTMLElement;\n  pos: number;\n\n  constructor(node: dompack.FormControlElement, pos: number) {\n    this.node = node;\n    this.pos = pos;\n    this.fieldgroup = node.closest(\".wh-form__fieldgroup\") ?? throwError(\"Could not find fieldgroup for field\");\n  }\n}\n\ninterface OrderingData {\n  countries: string[];\n  fieldorder: string[];\n}\n\nexport default class AddressField {\n  numvaliditycalls = 0;\n  node: HTMLElement;\n  formnode: HTMLFormElement;\n  countryNode: HTMLSelectElement;\n  currentcountry: string;\n  fieldName: string;\n  orderingData: OrderingData[];\n  allFields = new Map<string, SubField>;\n  _updatingFields = false;\n\n  constructor(node: HTMLElement) {\n    this.node = node;\n    //We won't FormBase.getForNode yet here so we're not too dependent on registration ordering\n    this.formnode = node.closest(\"form\") ?? throwError(\"Could not find form for addressfield\");\n\n    // AddressField is initialized for the address's country field, so first find the other fields\n    this.countryNode = dompack.qR(this.node, \"select.wh-form__pulldown\"); //TODO why aren't we targetting by ID ? this will work but seems ambiguous\n    if (!this.countryNode)\n      throw new Error(\"Could not find country select node\");\n    if (!this.countryNode.dataset.orderingdata)\n      throw new Error(\"Addressfield not properly configured\");\n\n    this.currentcountry = this.countryNode.value;\n    this.fieldName = this.countryNode.name.substr(0, this.countryNode.name.lastIndexOf(\".\"));\n    this.orderingData = JSON.parse(this.countryNode.dataset.orderingdata) as OrderingData[];\n    const prefixLength = this.fieldName.length + 1; // fieldName + \".\"\n    this.allFields = new Map();\n    let fieldpos = 0;\n    this.allFields.set(this.countryNode.name.substr(prefixLength), new SubField(this.countryNode, ++fieldpos));\n\n    for (const field of dompack.qSA<HTMLInputElement | HTMLTextAreaElement>(this.formnode, `[name^='${this.fieldName}.']`)) {\n      this.allFields.set(field.name.substring(prefixLength), new SubField(field, ++fieldpos));\n\n      field.addEventListener(\"change\", event => this._gotFieldChange(event));\n    }\n\n    if (this.orderingData) {\n      this.countryNode.addEventListener(\"change\", () => this._reconfigureFieldOrdering());\n      this._reconfigureFieldOrdering();\n    }\n  }\n\n  _gotFieldChange(event: Event) {\n    if (this._updatingFields)\n      return; // We're updating our own fields\n\n    if (event.target === this.countryNode && this.currentcountry !== this.countryNode.value) {\n      //country changed. clear errors on all fields before revalidating.. otherwise the errors will just seem to 'linger' for a while after switching\n      this._clearErrors();\n      this.currentcountry = this.countryNode.value;\n    }\n\n    if (this._getFieldValue(\"country\") === \"NL\") {\n      if (!this._getFieldValue(\"zip\") || !this._getFieldValue(\"nr_detail\"))\n        return;\n    }\n    this._checkValidity(event);\n  }\n\n  _getFieldValue(fieldname: string) {\n    const data = this.allFields.get(fieldname);\n    if (data)\n      return data.node.value;\n    return \"\";\n  }\n\n  _getFirstCountrySpecificField() {\n    let firstfield = null;\n    for (const [key, field] of this.allFields.entries())\n      if (key !== \"country\" && !field.fieldgroup.classList.contains(\"wh-form__fieldgroup--hidden\") && (!firstfield || firstfield.pos > field.pos))\n        firstfield = field;\n\n    return firstfield ?? throwError(\"Cannot find field for error\");\n  }\n\n  _reconfigureFieldOrdering() {\n    const country = this.countryNode.value;\n    if (country) {\n      const ordering = this.orderingData.find(e => e.countries.length === 0 || e.countries.includes(country));\n      if (ordering) {\n        let prevgroup;\n        for (let idx = 0; idx < ordering.fieldorder.length; ++idx) {\n          const item = this.allFields.get(ordering.fieldorder[idx]);\n          if (!item)\n            continue; //ordering may appear to fields that have not been rendered, eg 'state'\n\n          item.pos = idx + 1;\n          const fieldgroup = item.fieldgroup;\n          if (prevgroup) {\n            const compareres = prevgroup!.compareDocumentPosition(fieldgroup);\n            if (compareres & Node.DOCUMENT_POSITION_PRECEDING)\n              prevgroup!.parentNode!.insertBefore(fieldgroup, prevgroup!.nextSibling);\n          }\n          prevgroup = fieldgroup;\n        }\n      }\n    }\n\n    //street + city should skip client side validation for NL, we will be looking it up server side (FIXME we should consider overwriting our validation to delay validation until address lookups are complete)\n    for (const fieldname of ['street', 'city']) {\n      const field = this.allFields.get(fieldname);\n      if (field)\n        if (country.toUpperCase() === 'NL')\n          field.node.setAttribute(\"data-wh-form-skipnativevalidation\", \"\");\n        else\n          field.node.removeAttribute(\"data-wh-form-skipnativevalidation\");\n    }\n  }\n\n  _clearErrors() {\n    this.allFields.forEach(field => setFieldError(field.node, \"\", { reportimmediately: true }));\n  }\n\n  _getCurState() {\n    const value: HareScriptAddressValue = { country: \"\" };\n    const visiblefields: HTMLElement[] = [];\n    let anyset = false, allrequiredset = true;\n    this.allFields.forEach((field, key) => {\n      if (!field.fieldgroup.classList.contains(\"wh-form__fieldgroup--hidden\")) {\n        visiblefields.push(field.node.closest(\".wh-form__fieldgroup\")!);\n        value[key as keyof HareScriptAddressValue] = field.node.value;\n\n        if (!anyset && key !== 'country' && field.node.value)\n          anyset = true;\n        if (field.node.required && !field.node.value && !field.node.hasAttribute(\"data-wh-form-skipnativevalidation\"))\n          allrequiredset = false;\n      }\n    });\n\n    return { value, visiblefields, anyset, allrequiredset, lookupkey: JSON.stringify(value) };\n  }\n\n  async _checkValidity(event: Event) {\n    const form = FormBase.getForNode(this.formnode) ?? throwError(\"Parent form for address field not yet initialized\");\n    /* we used to clear fields that are no longer visible after a country change, add visible fields to the value we're checking\n       but not sure why. ignoring those fields should be okay? and this is a very eager trigger, so if we really do this, do\n       this on base of the country actually changing, not an external checkbox controlling visibility of the whole country field\n       and a stray update event\n       */\n    const curstate = this._getCurState();\n    if (!curstate.anyset) { //fields are empty..\n      this._clearErrors();\n      return; //then don't validate\n    }\n    if (!curstate.allrequiredset)\n      return; //no need to validate if we don't even have the required fields in place\n\n    let result: HareScriptAddressValidationResult;\n    const lock = dompack.flagUIBusy();\n    try {\n      curstate.visiblefields.forEach(el => el.classList.add(\"wh-form__fieldgroup--addresslookup\"));\n      ++this.numvaliditycalls;\n      result = await verifyHareScriptAddress(curstate.value as HareScriptAddressValue, {\n        lang: form.getLangCode(),\n        checks: (this.node.dataset.checks?.split(' ') ?? []) as AddressChecks[]\n      });\n    } catch (e) {\n      console.error(`Error while validating value: ${e}`);\n      return;\n    } finally {\n      if (--this.numvaliditycalls === 0) //we're the last call\n        curstate.visiblefields.forEach(el => el.classList.remove(\"wh-form__fieldgroup--addresslookup\"));\n\n      lock.release();\n    }\n    if (this._getCurState().lookupkey !== curstate.lookupkey)\n      return; //abandon this _checkValidity call, the field has already changed.\n\n    if (debugFlags.fhv)\n      console.log(`[fhv] Validation result for address '${this.fieldName}': ${result.status}`);\n\n    if (debugFlags.fdv) {\n      if ([\"different_citystreet\", \"incomplete\"].includes(result.status))\n        console.warn(`[fdv] Address validation was performed, processing incomplete address (status: '${result.status}')`);\n      else {\n        console.warn(`[fdv] Ignoring return status '${result.status}' of address validation`);\n        result.status = \"ok\";\n      }\n    }\n\n    this._clearErrors();\n\n    for (const err of result.errors) {\n      const field = this.allFields.get(err.fields[0]) ?? this._getFirstCountrySpecificField();\n      if (field)\n        form.setFieldError(field.node, err.message, { reportimmediately: true });\n    }\n\n    if (result.corrections) {\n      let anychanges = false;\n      this._updatingFields = true;\n\n      for (const [key, newvalue] of Object.entries(result.corrections)) {\n        const field = this.allFields.get(key);\n        if (field && field.node.value !== newvalue) {\n          dompack.changeValue(field.node, newvalue);\n          anychanges = true;\n        }\n      }\n\n      this._updatingFields = false;\n      if (anychanges)\n        form.refreshConditions();\n    }\n  }\n}\n","import type { AddressValue } from \"@webhare/address\";\nimport { stringify, emplace, omit } from \"@webhare/std\";\nimport { getFormService, type HareScriptAddressValidationResult, type HareScriptAddressValue } from \"./formservice\";\n\nexport type { HareScriptAddressValue, HareScriptAddressValidationResult } from \"./formservice\";\n\nexport type AddressChecks = \"nl-zip-suggest\" | \"nl-zip-force\";\n\nexport type AddressValidationStatus = \"ok\" | \"unknown\" | \"error\";\n// not_supported\" | \"ok\" | \"not_enough_data\" | \"invalid_city\" | \"invalid_zip\" | \"invalid_nr_detail\" | \"zip_not_found\" | \"address_not_found\" | \"different_citystreet\" | \"incomplete\" | \"lookup_failed\";\n\nexport interface AddressValidationOptions {\n  checks?: AddressChecks[];\n  lang?: string;\n}\n\nexport interface AddressValidationResult {\n  status: AddressValidationStatus;\n  errors: Array<{\n    ///Fields affected by the error\n    fields: string[];\n    ///Error message in the requested language\n    message: string;\n  }>;\n  corrections: Partial<Record<keyof AddressValue, string>> | null;\n}\n\nlet lookupcache: Map<string, Promise<AddressValidationResult>> | undefined;\n\nexport async function verifyHareScriptAddress(address: HareScriptAddressValue, options: AddressValidationOptions = {}): Promise<HareScriptAddressValidationResult> {\n  if (!lookupcache)\n    lookupcache = new Map<string, Promise<AddressValidationResult>>;\n\n  const lookupkey = stringify({ address, options }, { stable: true });\n  const lookup = emplace(lookupcache, lookupkey, {\n    insert: () => getFormService().verifyAddress(location.pathname, address, options)\n  });\n  return await lookup;\n}\n\nexport async function verifyAddress(address: AddressValue, options: AddressValidationOptions = {}): Promise<AddressValidationResult> {\n  if (!lookupcache)\n    lookupcache = new Map<string, Promise<AddressValidationResult>>;\n\n  // convert houseNumber to nr_detail\n  const hsAddress = { ...omit(address, [\"houseNumber\"]), nr_detail: address.houseNumber };\n\n  const hsresult = await verifyHareScriptAddress(hsAddress, options);\n\n  // back-convert nr_detail to houseNumber\n  let corrections: AddressValidationResult[\"corrections\"] = null;\n  if (hsresult.corrections) {\n    corrections = {};\n    for (const [key, value] of Object.entries(hsresult.corrections) as Array<[keyof HareScriptAddressValue, string]>) {\n      corrections[key === \"nr_detail\" ? \"houseNumber\" as const : key] = value;\n    }\n  }\n  return {\n    status: hsresult.status,\n    errors: hsresult.errors.map(error => ({ fields: error.fields.map(f => f === \"houseNumber\" ? \"nr_detail\" : f), message: error.message })),\n    corrections,\n  };\n}\n","import { createClient, type GetClientInterface } from \"@webhare/jsonrpc-client\";\nimport type { AddressValidationOptions, AddressValidationStatus } from \"./address\";\nimport type { FormSubmitResult } from \"@mod-publisher/js/forms/formbase\";\nimport type { EmailValidationResult, RPCFormTarget, RPCFormInvokeRPC, RPCFormSubmission, RPCFormMessage } from \"./types\";\nimport type { FormService } from \"@mod-publisher/lib/internal/forms/service\";\nimport type { AddressValue } from \"@webhare/address\";\nimport type { CaptchaProvider } from \"@mod-publisher/js/captcha/api\";\n\n\n/// HareScript uses 'nr_detail' instead of 'houseNumber'\nexport type HareScriptAddressValue = Omit<AddressValue, \"houseNumber\"> & { nr_detail?: string };\n\nexport interface HareScriptAddressValidationResult {\n  status: AddressValidationStatus;\n  errors: Array<{\n    ///Fields affected by the error\n    fields: string[];\n    ///Error message in the requested language\n    message: string;\n  }>;\n  corrections: Partial<Record<keyof HareScriptAddressValue, string>> | null;\n}\n\nexport interface PublisherFormService {\n  /** Validate an email address for validity (including against server configured correction/blacklists)\n   *\n   * @param langcode - Language code for messages\n   * @param emailaddress - Address to validate\n   * @returns Validation result\n   */\n  validateEmail(langcode: string, emailaddress: string): Promise<EmailValidationResult>;\n\n  formValidateEmail(target: RPCFormTarget & { field: string }, emailaddress: string): Promise<EmailValidationResult>;\n\n  /** Get an image from a remote URL */\n  getImgFromRemoteURL(imageurl: string): Promise<string>;\n\n  /** Get the final image URL to use */\n  getUploadedFileFinalURL(uploadurl: string): Promise<string>;\n\n  validateEmbeddedObjects(objrefs: string[]): Promise<{ tokill: string[] }>;\n\n  /** Verify address */\n  verifyAddress(url: string, address: HareScriptAddressValue, options: AddressValidationOptions): Promise<HareScriptAddressValidationResult>;\n\n  formSubmit(submitinfo: RPCFormSubmission): Promise<FormSubmitResult>;\n\n  formInvoke(submitinfo: RPCFormInvokeRPC): Promise<{\n    messages: RPCFormMessage[];\n    result: unknown;\n  }>;\n\n  requestBuiltinForm(submitinfo: RPCFormTarget, filename: string, formname: string): Promise<{ html: string }>;\n\n  /** Get captcha configuration. This is needed when the form will preactivate captchas (if form submission requests a captcha it will transmit provider setting in the error metadata) */\n  getCaptchaConfiguration(submitinfo: RPCFormTarget): Promise<CaptchaProvider | null>;\n}\n\nlet hsformservice: GetClientInterface<PublisherFormService> | undefined;\nlet tsformservice: GetClientInterface<FormService> | undefined;\n\nexport function getFormService(): GetClientInterface<PublisherFormService> {\n  hsformservice ||= createClient<PublisherFormService>(\"publisher:forms\");\n  return hsformservice;\n}\n\nexport function getTSFormService(): GetClientInterface<FormService> {\n  tsformservice ||= createClient<FormService>(\"publisher:formsts\");\n  return tsformservice;\n}\n","import { isValidDate, isValidTime } from '@webhare/std';\n\nexport function formatDate(dateformat: string, year: number, month: number, day: number): string {\n  if (!isValidDate(year, month, day, { minYear: 1 }))\n    return '';\n\n  let output = '';\n\n  for (const c of dateformat.split(\"\")) {\n    switch (c.toUpperCase()) {\n      case \"Y\":\n        output += ('000' + year).slice(-4);\n        break;\n      case \"M\":\n        output += ('0' + month).slice(-2);\n        break;\n      case \"D\":\n        output += ('0' + day).slice(-2);\n        break;\n      default:\n        output += c;\n        break;\n    }\n  }\n  return output;\n}\n\nexport function formatISODate(year: number, month: number, date: number) {\n  return formatDate(\"Y-M-D\", year, month, date);\n}\n\nexport function formatISOTime(hour: number, minute: number, second: number | null, msec: number | null) {\n  if (!isValidTime(hour, minute, second !== null ? second : 0, msec !== null ? msec : 0))\n    return '';\n\n  let time = ('0' + hour).slice(-2) + ':' + ('0' + minute).slice(-2);\n  if (second !== null)\n    time += ':' + ('0' + second).slice(-2);\n  if (msec !== null)\n    time += '.' + ('00' + msec).slice(-3);\n  return time;\n}\n\nexport interface DateParts {\n  day: number;\n  month: number;\n  year: number;\n}\n\nexport function parseDate(format: string, newdate: string, options?: { nofail: boolean }): DateParts | null {\n  if (!newdate) //empty\n    return null;\n\n  //replace . and / with -\n  const setdate = newdate.replace(/[./]/g, '-');\n  const parts = setdate.split('-');\n\n  if (parts.length === 3) { //parseable\n    format = format.toLowerCase();\n    const dayoffset = format.indexOf('d');\n    const monthoffset = format.indexOf('m');\n    const yearoffset = format.indexOf('y');\n\n    const daypos = 0 + (dayoffset > monthoffset ? 1 : 0) + (dayoffset > yearoffset ? 1 : 0);\n    const monthpos = 0 + (monthoffset > dayoffset ? 1 : 0) + (monthoffset > yearoffset ? 1 : 0);\n    const yearpos = 0 + (yearoffset > dayoffset ? 1 : 0) + (yearoffset > monthoffset ? 1 : 0);\n\n    const day = parseInt(parts[daypos], 0);\n    const month = parseInt(parts[monthpos], 0);\n    const year = parseInt(parts[yearpos], 0);\n\n    // The browser will always add 1900 for years 0-99, so handle years < 100\n    // if (year >= 0 && year < 100 && this.options.cutoffyear > 0)\n    // {\n    //   if (year < this.options.cutoffyear)\n    //     year += 2000;\n    //   else\n    //     year += 1900;\n    // }\n    if (isValidDate(year, month, day))\n      return { year, month, day };\n  }\n  if (options && options.nofail)\n    return null;\n\n  throw new Error(`Invalid date value: '${newdate}'`);\n}\n\n//compare two dates. return -1 if lhs<rhs, 0 if lhs==rhs, 1 if lhs>rhs\nexport function compareDate(lhs: DateParts | null, rhs: DateParts | null) {\n  if (!lhs)\n    return rhs ? -1 : 0; //if rhs is set, <null> is before anything. oterhwise equal\n  else if (!rhs)\n    return 1; //lhs must be set, so lhs>rhs\n\n  return lhs.year < rhs.year ? -1\n    : lhs.year > rhs.year ? 1\n      : lhs.month < rhs.month ? -1\n        : lhs.month > rhs.month ? 1\n          : lhs.day < rhs.day ? -1\n            : lhs.day > rhs.day ? 1\n              : 0;\n}\n\nexport function parseISODate(newdate: string, options?: { nofail: boolean }) {\n  return parseDate('y-m-d', newdate, options);\n}\n\nexport function getLocalToday(): DateParts {\n  const today = new Date;\n  return { year: today.getFullYear(), month: 1 + today.getMonth(), day: today.getDate() };\n}\n\nexport function parseISOTime(intime: string, { nofail = false } = {}) {\n  const split = intime.match(/^([0-9]+):([0-9]+)(:([0-9]+))?(\\.([0-9]+))?$/);\n  if (split) {\n    const hour = parseInt(split[1], 10);\n    const minute = parseInt(split[2], 10);\n    const second = parseInt(split[4] || \"0\", 10);\n    const msec = parseInt(split[6] || \"0\", 10);\n    return { hour, minute, second, msec };\n  }\n  if (nofail)\n    return undefined;\n\n  throw new Error(`Invalid time value: '${intime}'`);\n}\n\nexport function getWeekNumber(jsdate: Date) {\n  jsdate = new Date(jsdate); //don't modify the caller's date!\n  jsdate.setHours(0, 0, 0, 0);\n  // Thursday in current week decides the year.\n  jsdate.setDate(jsdate.getDate() + 3 - (jsdate.getDay() + 6) % 7);\n  // January 4 is always in week 1.\n  const week1 = new Date(jsdate.getFullYear(), 0, 4);\n  // Adjust to Thursday in week 1 and count number of weeks from jsdate to week1.\n  return 1 + Math.round(((jsdate.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);\n}\n\nexport function makeJSUTCDate(dateparts: DateParts) {\n  return new Date(Date.UTC(dateparts.year, dateparts.month - 1, dateparts.day));\n}\n\nexport function formatJSUTCISODate(dateobj: Date) {\n  return dateobj.getUTCFullYear() + '-' + ('0' + (dateobj.getUTCMonth() + 1)).slice(-2) + '-' + ('0' + dateobj.getUTCDate()).slice(-2);\n}\n","import * as dompack from 'dompack';\nimport { qSA } from 'dompack';\nimport * as datetime from 'dompack/types/datetime';\nimport AddressField from '@mod-publisher/js/forms/fields/addressfield';\nimport { setupValidator } from './customvalidation';\n\nimport { getTid } from \"@webhare/gettid\";\nimport { formatDate, parseISODate } from './datehelpers';\nimport { isValidDate } from '@webhare/std';\n\nfunction validateCheckboxGroup(groupnode: HTMLElement) {\n  const nodes = dompack.qSA<HTMLInputElement>(groupnode, \"input[type='checkbox']\");\n  const min = Number(groupnode.dataset.whMin) || 0;\n  const max = Number(groupnode.dataset.whMax) || 0;\n\n  const anyenabled = nodes.some(node => !node.disabled);\n  const numChecked = nodes.filter(node => node.checked).length;\n\n  if (anyenabled) {\n    if (numChecked < min)\n      return getTid(\"publisher:site.forms.commonerrors.mincheck\", min);\n    else if (max > 0 && numChecked > max)\n      return getTid(\"publisher:site.forms.commonerrors.maxcheck\", max);\n  }\n}\n\nfunction validateRadioGroup(groupnode: HTMLElement) {\n  const nodes = dompack.qSA<HTMLInputElement>(groupnode, \"input[type='radio']\");\n  const isrequired = nodes.some(node => node.required);\n\n  if (isrequired) {\n    const isanychecked = nodes.some(node => node.checked && !node.disabled);\n    if (!isanychecked)\n      return getTid(\"publisher:site.forms.commonerrors.required\");\n  }\n}\n\nexport function reformatDate(datestr: string): string {\n  const parsed = parseISODate(datestr);\n  return parsed ? formatDate(\"D-M-Y\", parsed.year, parsed.month, parsed.day) : \"\";\n}\n\nfunction validateDate(date: HTMLInputElement) {\n  if (date.getAttribute('type') !== 'date') //it's no longer a date field\n    return '';\n  if (!date.value) //any required checks should be handled by the HTML5 compat layer, nothing for us to check\n    return '';\n\n  const dateparts = date.value.match(/^([0-9]+)-([0-9]+)-([0-9]+)$/) || [];\n  const year = parseInt(dateparts[1]), month = parseInt(dateparts[2]), day = parseInt(dateparts[3]);\n  if (!isValidDate(year, month, day))\n    return getTid(\"publisher:site.forms.commonerrors.default\");\n\n  const normalizeddate = ('0000' + year).substr(-4) + '-' + ('00' + month).substr(-2) + '-' + ('00' + day).substr(-2);\n  const min = date.getAttribute(\"min\"), max = date.getAttribute(\"max\");\n  if (min && normalizeddate < min)\n    return getTid(\"publisher:site.forms.commonerrors.min\", reformatDate(min));\n  if (max && normalizeddate > max)\n    return getTid(\"publisher:site.forms.commonerrors.max\", reformatDate(max));\n\n  return '';\n}\n\nfunction validateTime(time: HTMLInputElement) {\n  if (time.getAttribute('type') !== 'time') //it's no longer a time field\n    return '';\n  if (!time.value) //any required checks should be handled by the HTML5 compat layer, nothing for us to check\n    return '';\n\n  const timeparts = time.value.match(/^([0-9]+):([0-9]+)(:([0-9]+))?$/) || [];\n  const hours = parseInt(timeparts[1]), minutes = parseInt(timeparts[2]), seconds = parseInt(timeparts[3]);\n  if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || (!isNaN(seconds) && (seconds < 0 || seconds > 59)))\n    return getTid(\"publisher:site.forms.commonerrors.default\");\n\n  return '';\n}\n\nexport function setup(form: HTMLElement) {\n  for (const datecontrol of qSA<HTMLInputElement>(form, 'input[type=date]')) {\n    for (const field of ['whMin', 'whMax', 'whValue'])\n      if (datecontrol.dataset[field]) {\n        //parse 'now' or 'now+5d'. be able to extract '+5d'\n        const datematch = datecontrol.dataset[field]!.match(/^now((\\+|-)\\d+d)?$/);\n\n        if (datematch) {\n          const propname = field.substr(2).toLowerCase();\n          let thedate;\n          if (datematch[1])\n            thedate = new Date(Date.now() + parseInt(datematch[1]) * 86400 * 1000);\n          else\n            thedate = new Date;\n\n          (datecontrol as unknown as Record<string, string>)[propname] = datetime.getISOLocalDate(thedate);\n        }\n      }\n\n    if (datecontrol.type !== 'date' && !datecontrol.whValidationPolyfilled) { //this browser doesn't natively support date fields\n      datecontrol.whValidationPolyfilled = true;\n      //ADDME some sort of global validator would be better so we don't get confused by fields that change their type\n      setupValidator(datecontrol, validateDate);\n    }\n  }\n\n  for (const timecontrol of qSA<HTMLInputElement>(form, 'input[type=time][data-wh-value]')) {\n    //parse 'now'\n    //ADDME: Support for stuff like 'now + 15 minutes' 'next whole hour + 2.5 hours'?\n    const timematch = timecontrol.dataset.whValue!.match(/^now$/);\n\n    if (timematch) {\n      const thedate = new Date;\n\n      let propvalue = ('0' + thedate.getHours()).substr(-2) + '-' + ('0' + thedate.getMinutes()).substr(-2);\n      if (parseInt(timecontrol.getAttribute(\"step\") || '0') % 60) //step not multiple of 60? seconds\n        propvalue += '-' + ('0' + thedate.getSeconds()).substr(-2);\n      timecontrol.value = propvalue;\n    }\n\n    if (timecontrol.type !== 'time' && !timecontrol.whValidationPolyfilled) { //this browser doesn't natively support time fields\n      timecontrol.whValidationPolyfilled = true;\n      //ADDME some sort of global validator would be better so we don't get confused by fields that change their type\n      setupValidator(timecontrol, validateTime);\n    }\n  }\n\n  // Setup checkbox group (min/max checked) validation\n  for (const checkboxgroup of qSA(form, \".wh-form__fieldgroup--checkboxgroup\"))\n    setupValidator(checkboxgroup, validateCheckboxGroup);\n\n  // Setup radio group (hidden/disabled) validation\n  for (const radiogroup of qSA(form, \".wh-form__fieldgroup--radiogroup\")) {\n    setupValidator(radiogroup, validateRadioGroup);\n\n    //we should probably disable by name (or form.elements[name] but validate() and form isn't really tracking name either...\n    dompack.qSA<HTMLInputElement>(radiogroup, `input[type='radio']`).forEach(\n      node => node.dataset.whFormSkipnativevalidation = \"true\"); //don't handle by both RadioGroupField *and* native validation\n\n  }\n\n  // Setup address field validation\n  for (const addresscontrol of qSA(form, \".wh-form__fieldgroup--addressfield\"))\n    new AddressField(addresscontrol);\n}\n","export interface FormFieldLike extends HTMLElement {\n  disabled: boolean;\n  name: string;\n  required: boolean;\n  value: unknown;\n}\n\n/** Base class for customElements that need to act as WebHare (Publisher) form elements */\nexport abstract class JSFormElement<ValueType> extends HTMLElement implements FormFieldLike {\n  static formAssociated = true;\n  static observedAttributes = [\"required\", \"disabled\"];\n\n  // #internals = this.attachInternals();\n\n  constructor() {\n    super();\n  }\n\n  get name() {\n    return this.getAttribute('name') || '';\n  }\n  set name(newname: string) {\n    this.setAttribute('name', newname);\n  }\n  get required(): boolean {\n    return this.hasAttribute('required');\n  }\n  set required(required: boolean) {\n    if (required)\n      this.setAttribute(\"required\", \"\");\n    else\n      this.removeAttribute(\"required\");\n\n    this.refreshState();\n  }\n\n  get disabled(): boolean {\n    return this.hasAttribute('disabled');\n  }\n  set disabled(disable: boolean) {\n    if (disable)\n      this.setAttribute(\"disabled\", \"\");\n    else\n      this.removeAttribute(\"disabled\");\n\n    this.refreshState();\n  }\n\n  abstract value: ValueType;\n\n  /** Invoked whenever disabled/required states change */\n  protected refreshState() {\n  }\n\n  attributeChangedCallback(name: string, oldValue: unknown, newValue: unknown) {\n    if ([\"disabled\", \"required\"].includes(name))\n      this.refreshState();\n  }\n}\n","/* Support APIs to deal with DOM native form elements (eg input, select, textarea) */\n\nimport type FormBase from '@mod-publisher/js/forms/formbase';\nimport { reformatDate } from \"@mod-publisher/js/forms/internal/webharefields\";\nimport { getTid } from \"@webhare/gettid\";\nimport { isFormControl, isHTMLElement, qSA, type FormControlElement } from \"@webhare/dompack\";\nimport type { FormCondition } from \"./types\";\nimport { JSFormElement, type FormFieldLike } from \"./jsformelement\";\nimport { throwError } from '@webhare/std';\n\nexport type ConstrainedRadioNodeList = RadioNodeList & NodeListOf<HTMLInputElement>;\n\n//Query elements that are likely to be formfieldlike. Anything with a [name] but not eg button (and not data-wh-form-name which usually relies on getformvalue events)\nexport const queryFormFieldLike = `[name]:not(button):not(a):not(output)`;\n\nexport function isInputElement(field: Element): field is HTMLInputElement {\n  return isHTMLElement(field) && field.tagName === 'INPUT';\n}\n\n/// Implements required, disabled, ..\nexport function isFormFieldLike(control: HTMLElement): control is FormFieldLike {\n  return isFormControl(control as HTMLElement) || control instanceof JSFormElement;\n}\n\nexport function isRadioOrCheckbox(field: Element): field is HTMLInputElement {\n  return isInputElement(field) && [\"radio\", \"checkbox\"].includes(field.type);\n}\n\n// Constrains the RadioNodeList type to only return HTMLInputElements. reduces number of casts we need\nexport function isRadioNodeList(el: RadioNodeList | Element): el is ConstrainedRadioNodeList {\n  return el instanceof RadioNodeList;\n}\n\nexport function getFieldName(field: HTMLElement): string {\n  return field.dataset.whFormName || (field as HTMLInputElement).name || '';\n}\n\nexport function setFieldName(field: HTMLElement, newname: string) {\n  if (field.dataset.whFormName !== undefined)\n    field.dataset.whFormName = newname;\n  else if ((field as HTMLInputElement).name !== undefined)\n    (field as HTMLInputElement).name = newname;\n  else\n    throw new Error('Cannot set name on field without existing name');\n}\n\nexport function getFieldDisplayName(field: HTMLElement | ConstrainedRadioNodeList): string {\n  if (isRadioNodeList(field))\n    return `radiogroup '${(field.item(0) as HTMLInputElement)?.name || (field.item(0) as HTMLElement)?.id || '<unnamed>'}'`;\n  if (isFormControl(field))\n    return `native field '${field.name || field.id || '<unnamed>'}'`;\n  if (field.dataset.whFormName)\n    return `custom field '${field.dataset.whFormName || field.id || '<unnamed>'}'`;\n  if (field.classList.contains('wh-form__fieldgroup'))\n    return `field group '${field.dataset.whFormGroupFor || field.id || '<unnamed>'}'`;\n  return `${field.tagName} element '${field.id || '<unnamed>'}'`;\n}\n\n/** The WH Form rendering generates wh-fileedit elements. If no handler is detected for them, we downgrade them to input type=file before\n *  the form actually sets up its handler (it's still safe to rewrite top level form elements then)\n*/\nexport function downgradeUploadFields(form: HTMLElement) {\n  for (const uploadfield of qSA(form, \"wh-fileedit\")) {\n    const input = document.createElement(\"input\");\n    input.type = \"file\";\n    for (const attr of uploadfield.attributes)\n      input.setAttribute(attr.name, attr.value);\n\n    uploadfield.replaceWith(input);\n  }\n}\n\nexport function getErrorForValidity(field: FormControlElement): string {\n  const validity = field.validity;\n  if (validity.customError && field.validationMessage)\n    return field.validationMessage;\n\n  if (validity.valueMissing)\n    return getTid(\"publisher:site.forms.commonerrors.required\");\n  if (field instanceof HTMLInputElement) {\n    if (validity.rangeOverflow) {\n      const max = field.type === 'date' ? reformatDate(field.max) : field.max;\n      return getTid(\"publisher:site.forms.commonerrors.max\", max);\n    }\n    if (validity.rangeUnderflow) {\n      const min = field.type === 'date' ? reformatDate(field.min) : field.min;\n      return getTid(\"publisher:site.forms.commonerrors.min\", min);\n    }\n    if (validity.tooShort)\n      return getTid(\"publisher:site.forms.commonerrors.minlength\", field.minLength);\n    if (validity.tooLong)\n      return getTid(\"publisher:site.forms.commonerrors.maxlength\", field.maxLength);\n    if (validity.stepMismatch)\n      if (!field.step || parseInt(field.step) === 1)\n        return getTid(\"publisher:site.forms.commonerrors.step1mismatch\");\n      else\n        return getTid(\"publisher:site.forms.commonerrors.stepmismatch\", field.step);\n  }\n\n  if (validity.badInput)\n    return getTid(\"publisher:site.forms.commonerrors.default\");\n  if (validity.typeMismatch)\n    if ([\"email\", \"url\", \"number\"].includes(field.type))\n      return getTid(\"publisher:site.forms.commonerrors.\" + field.type);\n\n  for (const key of [\"badInput\", \"customError\", \"patternMismatch\", \"rangeOverflow\", \"rangeUnderflow\", \"stepMismatch\", \"typeMismatch\", \"valueMissing\"] as const)\n    if (validity[key])\n      return key;\n\n  return '?';\n}\n\nexport function isFieldNativeErrored(field: HTMLElement): field is FormControlElement {\n  return isFormControl(field) && !field.hasAttribute(\"data-wh-form-skipnativevalidation\") && !field.checkValidity();\n}\n\nexport function getFieldNativeError(field: HTMLElement) {\n  if (isFieldNativeErrored(field))\n    return getErrorForValidity(field);\n\n  return null;\n}\n\n\nexport function parseCondition(conditiontext: string): FormCondition {\n  interface FormConditionWrapper {\n    c: FormCondition;\n  }\n\n  return (JSON.parse(conditiontext) as FormConditionWrapper).c;\n}\n\nexport function getFormElementCandidates(basenode: HTMLElement, namePrefix: string) {\n  const parentForm = basenode.closest('form');\n  if (!parentForm)\n    throw new Error('No form found for element');\n\n  const candidates = qSA<HTMLElement>(basenode, queryFormFieldLike).filter(el => !(\"form\" in el) || el.form === parentForm);\n  if (namePrefix)\n    return candidates.filter(el => getFieldName(el).startsWith(namePrefix + '.'));\n  else\n    return candidates;\n}\n\n/** Get the handler for a form element */\nexport function getFormHandler<FormType extends FormBase<object> = FormBase>(node: HTMLFormElement, options: { allowMissing: true }): FormType | null;\nexport function getFormHandler<FormType extends FormBase<object> = FormBase>(node: HTMLFormElement, options?: { allowMissing?: boolean }): FormType;\n\nexport function getFormHandler<FormType extends FormBase<object> = FormBase>(node: HTMLFormElement, { allowMissing = false } = {}): FormType | null {\n  //FIXME convert to Symbol? but make sure we work cross-realm (ie tests)\n  return (node.propWhFormhandler as FormType) || (allowMissing ? null : throwError('No form handler found for form'));\n}\n\n/** Get the data for a form element. Shorthand for getFormHandler\\<FormBase\\<Shape\\>\\>(xx).data */\nexport function getFormData<DataShape extends object = Record<string, unknown>>(node: HTMLFormElement, options: { allowMissing: true }): DataShape | null;\nexport function getFormData<DataShape extends object = Record<string, unknown>>(node: HTMLFormElement, options?: { allowMissing?: boolean }): DataShape;\n\nexport function getFormData<DataShape extends object = Record<string, unknown>>(node: HTMLFormElement, { allowMissing = false } = {}): DataShape | null {\n  return getFormHandler<FormBase<DataShape>>(node, { allowMissing })?.data;\n}\n","// Auto-generated language file from /opt/wh/whtree/modules/publisher/js/forms/internal/form.lang.json\nvar registerTexts = require(\"@webhare/gettid/src/internal\").registerTexts;\nregisterTexts(\"publisher\",\"fr\",{\"site\":{\"forms\":{\"nextpage\":\"Prochain\",\"previouspage\":\"Précédent\",\"selectfile\":\"Choisir le dossier\",\"starsrequired\":\"* indique un champ obligatoire\",\"submit\":\"Soumettre\",\"addressfield\":{\"address_not_found\":\"Cette adresse est introuvable.\",\"invalid_nr_detail\":\"Numéro de maison avec ajout invalide.\",\"invalid_zip\":\"Code postal invalide.\",\"zip_not_found\":\"Combinaison inconnue de code postal et numéro de rue.\"},\"commonerrors\":{\"alphanum\":\"Cette valeur doit être alphanumérique.\",\"check\":[\"Vous devez sélectionner entre \",1,\" et \",2,\" choix.\"],\"default\":\"Cette valeur semble non valide.\",\"digits\":\"Cette valeur doit être numérique.\",\"email\":\"Cette valeur n'est pas une adresse email valide.\",\"email_baddomain\":[\"En raison de difficultés d'envoyer emails à \",1,\" adresses, nous vous demandons d'utiliser un autre fournisseur d'email.\"],\"email_suggestion\":[\"Cela devrait-il être \",1,\"?\"],\"equalto\":\"Cette valeur devrait être identique.\",\"integer\":\"Cette valeur doit être un entier.\",\"length\":[\"Cette valeur doit contenir entre \",1,\" et \",2,\" caractères.\"],\"max\":[\"Cette valeur ne doit pas excéder \",1,\".\"],\"maxarray\":[\"Vous pouvez ajouter un maximum de \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 élément \"],\"subselse\":[1,\" éléments\"]},\".\"],\"maxcheck\":[\"Vous devez sélectionner \",1,\" choix maximum.\"],\"maxlength\":[\"Cette chaîne est trop longue. Elle doit avoir au maximum \",1,\" caractères.\"],\"min\":[\"Cette valeur ne doit pas être inférieure à \",1,\".\"],\"minarray\":[\"Il faut ajouter au moins \",1,\" éléments.\"],\"mincheck\":[\"Vous devez sélectionner au moins \",1,\" choix.\"],\"minlength\":[\"Cette chaîne est trop courte. Elle doit avoir au minimum \",1,\" caractères.\"],\"notblank\":\"Cette valeur ne peut pas être vide.\",\"number\":\"Cette valeur doit être un nombre.\",\"pattern\":\"Cette valeur semble non valide.\",\"range\":[\"Cette valeur doit être comprise entre \",1,\" et \",2,\".\"],\"required\":\"Ce champ est requis.\",\"url\":\"Cette valeur n'est pas une URL valide.\",\"badfiletype\":\"This file type is not allowed\",\"cannotprocessfile\":\"This file looks suspicious and can unfortunately not be uploaded\",\"date\":\"This is not a valid date\",\"formunavailable\":\"This form is currently unavailable\",\"maxheight\":[\"The image is too big. It should be at most \",2,\" pixels high.\"],\"maxsignupsreached\":\"The maximum number of signups has been reached\",\"maxwidth\":[\"The image is too big. It should be at most \",2,\" pixels wide.\"],\"minheight\":[\"The image is too small. It should be at least \",2,\" pixels high.\"],\"minwidth\":[\"The image is too small. It should be at least \",2,\" pixels wide.\"],\"step1mismatch\":\"The value must be a whole number\",\"stepmismatch\":[\"The value should be a multiple of \",1,\".\"],\"time\":\"This is not a valid time\",\"unacceptableemail\":\"This email address is not acceptable here\",\"upload_cannotcheck\":\"This file cannot be uploaded as we are currently unable to verify it\",\"upload_suspicious\":\"This file looks suspicious and can unfortunately not be uploaded\"},\"imgedit-explain-upload\":\"Drag and drop files here or click to upload\",\"imgedit-groupelement-replace\":[1,\", Replace image\"],\"imgedit-groupelement-upload\":[1,\", Upload image\"],\"imgedit-remove\":\"Remove image\",\"splitdatetime-day-arialabel\":\"day\",\"splitdatetime-hours-arialabel\":\"hour\",\"splitdatetime-minutes-arialabel\":\"minute\",\"splitdatetime-month-arialabel\":\"month\",\"splitdatetime-seconds-arialabel\":\"second\",\"splitdatetime-year-arialabel\":\"year\",\"upload-emptytext\":\"No file chosen\",\"upload-filename\":[\"Uploaded file is \",1],\"upload-remove\":\"Remove file\"}}});\nregisterTexts(\"publisher\",\"en\",{\"site\":{\"forms\":{\"imgedit-explain-upload\":\"Drag and drop files here or click to upload\",\"imgedit-groupelement-replace\":[1,\", Replace image\"],\"imgedit-groupelement-upload\":[1,\", Upload image\"],\"imgedit-remove\":\"Remove image\",\"nextpage\":\"Next\",\"previouspage\":\"Previous\",\"selectfile\":\"Select file\",\"splitdatetime-day-arialabel\":\"day\",\"splitdatetime-hours-arialabel\":\"hour\",\"splitdatetime-minutes-arialabel\":\"minute\",\"splitdatetime-month-arialabel\":\"month\",\"splitdatetime-seconds-arialabel\":\"second\",\"splitdatetime-year-arialabel\":\"year\",\"starsrequired\":\"* indicates a required field\",\"submit\":\"Submit\",\"upload-emptytext\":\"No file chosen\",\"upload-filename\":[\"Uploaded file is \",1],\"upload-remove\":\"Remove file\",\"addressfield\":{\"address_not_found\":\"The address could not be found.\",\"invalid_nr_detail\":\"Invalid house number.\",\"invalid_zip\":\"Invalid ZIP or postal code.\",\"zip_not_found\":\"Unknown combination of postal code and house number.\"},\"commonerrors\":{\"alphanum\":\"This value should be alphanumeric.\",\"badfiletype\":\"This file type is not allowed\",\"cannotprocessfile\":\"This file looks suspicious and can unfortunately not be uploaded\",\"check\":[\"You must select between \",1,\" and \",2,\" choices.\"],\"date\":\"This is not a valid date\",\"default\":\"This value seems to be invalid.\",\"digits\":\"This value should be digits.\",\"email\":\"This value should be a valid email.\",\"email_baddomain\":[\"Due to difficulties with mailing to \",1,\" email addresses we kindly request you to use an alternative email provider.\"],\"email_suggestion\":[\"Did you mean \",1,\"?\"],\"equalto\":\"This value should be the same.\",\"formunavailable\":\"This form is currently unavailable\",\"integer\":\"This value should be a valid integer.\",\"length\":[\"This value length is invalid. It should be between \",1,\" and \",2,\" characters long.\"],\"max\":[\"This value should be lower than or equal to \",1,\".\"],\"maxarray\":[\"You can add at most \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 item\"],\"subselse\":[1,\" items\"]},\".\"],\"maxcheck\":[\"You must select \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 choice\"],\"subselse\":[1,\" choices\"]},\" or fewer.\"],\"maxheight\":[\"The image is too big. It should be at most \",2,\" pixels high.\"],\"maxlength\":[\"This value is too long. It should have \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 character\"],\"subselse\":[1,\" characters\"]},\" or fewer.\"],\"maxsignupsreached\":\"The maximum number of signups has been reached\",\"maxwidth\":[\"The image is too big. It should be at most \",2,\" pixels wide.\"],\"min\":[\"This value should be greater than or equal to \",1,\".\"],\"minarray\":[\"You must add at least \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 item\"],\"subselse\":[1,\" items\"]},\".\"],\"mincheck\":[\"You must select at least \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 choice\"],\"subselse\":[1,\" choices\"]},\".\"],\"minheight\":[\"The image is too small. It should be at least \",2,\" pixels high.\"],\"minlength\":[\"This value is too short. It should have \",{\"t\":\"ifparam\",\"p\":1,\"value\":\"1\",\"subs\":[\"1 character\"],\"subselse\":[1,\" characters\"]},\" or more.\"],\"minwidth\":[\"The image is too small. It should be at least \",2,\" pixels wide.\"],\"notblank\":\"This value should not be blank.\",\"number\":\"This value should be a valid number.\",\"pattern\":\"This value seems to be invalid.\",\"range\":[\"This value should be between \",1,\" and \",2,\".\"],\"required\":\"This value is required.\",\"step1mismatch\":\"The value must be a whole number\",\"stepmismatch\":[\"The value should be a multiple of \",1,\".\"],\"time\":\"This is not a valid time\",\"unacceptableemail\":\"This email address is not acceptable here\",\"upload_cannotcheck\":\"This file cannot be uploaded as we are currently unable to verify it\",\"upload_suspicious\":\"This file looks suspicious and can unfortunately not be uploaded\",\"url\":\"This value should be a valid url.\"}}}});\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/fr.xml\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/default.xml\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/default.xml\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from 'dompack';\nimport { requestFile } from \"@webhare/upload\";\n\nimport { getTid } from \"@webhare/gettid\";\nimport { setFieldError } from '@mod-publisher/js/forms/internal/customvalidation';\nimport { getFieldDisplayName } from '@webhare/forms/src/domsupport';\nimport { JSFormElement } from '@webhare/forms/src/jsformelement';\nimport type { FormFileValue } from '@webhare/forms/src/types';\nimport \"@mod-publisher/js/forms/internal/form.lang.json\"; //we need eg publisher:site.forms.selectfile\n\nfunction isAcceptableType(fileType: string, masks: string[]) {\n  if (masks.includes(fileType))\n    return true;\n\n  const basetype = fileType.split('/')[0];\n  if (['image', 'video', 'audio'].includes(basetype) && masks.includes(basetype + '/*'))\n    return true;\n\n  return false;\n}\n\n\nexport abstract class FileEditElement extends JSFormElement<FormFileValue[]> {\n  root;\n  maindiv;\n  readonly group: HTMLElement | null;\n\n  /** The current uploaded files */\n  protected currentFiles = new Array<FormFileValue>;\n  /** Maximum number of files */\n  protected maxFiles;\n\n  constructor() {\n    super();\n    this.root = this.attachShadow({ mode: 'open', delegatesFocus: true });\n    this.maindiv = document.createElement(\"div\");\n    this.maindiv.inert = this.disabled;\n\n    const csslink = document.createElement(\"link\");\n    csslink.rel = \"stylesheet\";\n    csslink.href = \"/.wh/ea/p/forms/controls.css\";\n    this.root.append(csslink, this.maindiv);\n\n    this.group = this.closest<HTMLElement>(\".wh-form__fieldgroup\");\n    this.whFormsApiChecker = async () => { await this._check(); };\n    this.maxFiles = parseInt(this.getAttribute(\"max-files\")!) || 1;\n    if (this.getAttribute(\"value\"))\n      this.#setValue(JSON.parse(this.getAttribute(\"value\")!));\n\n    if (this.group) {\n      this.group.addEventListener(\"dragover\", evt => evt.preventDefault());\n      this.group.addEventListener(\"dragenter\", evt => evt.preventDefault());\n      this.group.addEventListener(\"drop\", evt => this.doDrop(evt));\n    }\n  }\n  abstract refresh(): void;\n  isSet(): boolean {\n    return this.currentFiles.length > 0;\n  }\n  async _check() {\n    const error = this.required && !this.isSet();\n    if (error)\n      setFieldError(this, getTid(\"publisher:site.forms.commonerrors.required\"), { reportimmediately: false });\n    else\n      setFieldError(this, \"\", { reportimmediately: false });\n    return error;\n  }\n\n  protected refreshState() {\n    this.maindiv.inert = this.disabled;\n  }\n\n  get value(): FormFileValue[] {\n    return this.currentFiles;\n  }\n\n  set value(value: FormFileValue[]) {\n    this.#setValue(value);\n    this.refresh();\n  }\n\n  #setValue(value: Array<Partial<FormFileValue>>) { //taking a partial so we can do a better job at fixing missing fields from incorrect callers\n    //updates the value but does not fire events/refresh()\n    const toset: FormFileValue[] = [];\n\n    for (const row of value) {\n      if (row?.file) {\n        if (!this._isAcceptableType(row.file.type))\n          throw new Error(`File type ${row.file.type} is not acceptable for ${getFieldDisplayName(this)}`);\n        toset.push({ fileName: row.fileName || row.file.name, file: row.file, link: null });\n      } else if (row?.link) {\n        toset.push({ fileName: row.fileName || \"\", file: null, link: row.link });\n      } else {\n        throw new Error(`Incorrect value type received for ${getFieldDisplayName(this)} - expect 'file' or 'link' to be set`);\n      }\n\n      if (toset.length >= this.maxFiles)\n        break;\n    }\n    this.currentFiles = toset;\n  }\n\n  _isAcceptableType(mimetype: string) {\n    const accept = this.getAttribute(\"accept\")?.split(',').map(mask => mask.trim()) ?? [];\n    return !accept.length || isAcceptableType(mimetype, accept);\n  }\n\n  private doDrop(evt: DragEvent) {\n    //FIXME check 'accept' - or can the drag handlers do that?\n    evt.preventDefault();\n\n    const files = evt.dataTransfer?.files;\n    if (files)\n      this.processUpload(files[0]);\n  }\n\n  async uploadFile(evt: Event) {\n    evt.preventDefault();\n\n    if (this.disabled || this.currentFiles.length >= this.maxFiles)\n      return; //should not even have been offered?\n\n    const accept = this.getAttribute(\"accept\")?.split(',') ?? [];\n    using lock = dompack.flagUIBusy();\n    void (lock);\n\n    const file = await requestFile({ accept });\n    if (!file)\n      return;\n\n    await this.processUpload(file);\n  }\n\n  private async processUpload(file: File) {\n    if (this.disabled || this.currentFiles.length >= this.maxFiles)\n      return; //should not even have been offered?\n\n    if (!this._isAcceptableType(file.type)) {\n      //TODO tell server it can destroy the file immediately (should have told uploadsession at the start?\n      const msg = this.dataset.whAccepterror || getTid(\"publisher:site.forms.commonerrors.badfiletype\");\n      setFieldError(this, msg, { reportimmediately: true });\n      return;\n    }\n\n    this.currentFiles.push({ fileName: file.name, file: file, link: null });\n    this.refresh();\n    dompack.dispatchCustomEvent(this, 'change', { bubbles: true, cancelable: false });\n  }\n\n  protected deleteFile(evt: Event, idx: number) {\n    if (evt)\n      dompack.stop(evt);\n\n    this.currentFiles.splice(idx, 1);\n    this.refresh();\n    dompack.dispatchCustomEvent(this, 'change', { bubbles: true, cancelable: false });\n  }\n\n  protected setupUploadButton(button: HTMLElement) {\n    button.addEventListener(\"click\", evt => void this.uploadFile(evt));\n  }\n\n  protected setupDeleteButton(button: HTMLElement, idx: number) {\n    button.addEventListener(\"click\", evt => this.deleteFile(evt, idx));\n    button.ariaLabel = getTid(\"publisher:site.forms.imgedit-remove\");\n  }\n}\n","import * as dompack from 'dompack';\nimport { getTid } from \"@webhare/gettid\";\nimport { FileEditElement as FileEditElementBase } from './fileeditbase';\nimport './upload.css';\nimport { isFile } from '@webhare/std';\n\n\n\n//FIXME nicer class name? eg add form or field to these (and imgedit) class names?\nexport class FileUploadFormElement extends FileEditElementBase {\n  constructor() {\n    super();\n    this.refresh();\n  }\n\n  #constructFileHolder() {\n    const fileholder = document.createElement(\"div\");\n    fileholder.classList.add('file');\n    return fileholder;\n  }\n\n  refresh() {\n    const nodes = [];\n\n    for (const [idx, file] of this.currentFiles.entries()) {\n      const fileholder = this.#constructFileHolder();\n\n      // const label = getLabelText(this.node);\n      // aria-label={label}\n      const filename = isFile(file) ? file.name : file.fileName;\n      /* for ease of 'form like' presentation, we're currently using an <input>. but quite hacky, eg. we need readonly to have it not interfere with clicks. */\n      const filenamefield =\n        <input part=\"filename\" class=\"file__name\" type=\"text\" value={filename} readonly />;\n\n      const deletebutton = <button part=\"button deletebutton\" class=\"deletebutton file__deletebutton\" />;\n      this.setupDeleteButton(deletebutton, idx);\n\n      fileholder.append(filenamefield, deletebutton);\n      nodes.push(fileholder);\n    }\n\n    if (this.currentFiles.length < this.maxFiles) {\n      const fileholder = this.#constructFileHolder();\n      fileholder.classList.add('file--placeholder');\n\n      const filenamefield =\n        <input part=\"filename\" class=\"file__name\" type=\"text\" value=\"\" placeholder={getTid(\"publisher:site.forms.upload-emptytext\")} disabled readonly />;\n\n      const uploadbutton = <button part=\"button selectbutton\" type=\"button\" class=\"wh-form__uploadfieldselect wh-form__button\"><span class=\"wh-form__buttonlabel\">{getTid(\"publisher:site.forms.selectfile\")}</span></button>;\n      this.setupUploadButton(fileholder);\n      fileholder.append(filenamefield, uploadbutton);\n      nodes.push(fileholder);\n    }\n\n    this.maindiv.replaceChildren(...nodes);\n  }\n}\n\n//////// Legacy version. We expect existing users to migrate to the version above\n\nexport default class UploadField {\n  constructor(node: HTMLElement) {\n    if (!customElements.get(\"wh-fileedit\"))\n      customElements.define(\"wh-fileedit\", FileUploadFormElement);\n  }\n}\n","/* import ImgEditField from '@mod-publisher/js/forms/fields/imgedit';\n*/\nimport * as dompack from '@webhare/dompack';\nimport { FileEditElement } from './fileeditbase';\nimport { emplace } from '@webhare/std';\nimport { getTid } from '@webhare/gettid';\nimport { getFileAsDataURL } from '@webhare/upload';\nimport { setFieldError } from '@mod-publisher/js/forms/internal/customvalidation';\n\nlet revoker: FinalizationRegistry<string> | undefined;\nconst cachedURLs = new WeakMap<File, string>();\n\nfunction createFileURL(file: File): string {\n  return emplace(cachedURLs, file, {\n    insert: () => {\n      const newurl = URL.createObjectURL(file);\n      //setup a finalizer to revoke object urls\n      revoker ||= new FinalizationRegistry<string>((oldurl) => URL.revokeObjectURL(oldurl));\n      //as soon as file is lost to us\n      revoker.register(file, newurl);\n      return newurl;\n    }\n  });\n}\n\nasync function getImageDimensions(file: File): Promise<{ width: number; height: number }> {\n  const img = await dompack.loadImage(await getFileAsDataURL(file));\n  return { width: img.naturalWidth, height: img.naturalHeight };\n}\n\ninterface ImgEditTexts {\n  explainUpload?: string;\n}\n\nexport class ImgEditElement extends FileEditElement {\n  static observedAttributes = [\"min-width\", \"max-width\", \"min-height\", \"max-height\"];\n\n  private static texts: ImgEditTexts | null = null;\n\n  minWidth: number;\n  maxWidth: number;\n  minHeight: number;\n  maxHeight: number;\n\n  constructor() {\n    super();\n    // this.addEventListener(\"keypress\", evt => this.checkForUploadOrClear(evt)); // handle space+enter to active\n\n    this.maindiv.classList.add(\"images\");\n\n    this.minWidth = parseInt(this.getAttribute(\"min-width\") || \"0\") || 0;\n    this.maxWidth = parseInt(this.getAttribute(\"max-width\") || \"0\") || 0;\n    this.minHeight = parseInt(this.getAttribute(\"min-height\") || \"0\") || 0;\n    this.maxHeight = parseInt(this.getAttribute(\"max-height\") || \"0\") || 0;\n\n    this.refresh();\n  }\n\n  attributeChangedCallback(name: string, _oldValue: string, newValue: string) {\n    const value = parseInt(newValue);\n    if (isNaN(value))\n      return;\n    switch (name) {\n      case \"min-width\": {\n        this.minWidth = value;\n        break;\n      }\n      case \"max-width\": {\n        this.maxWidth = value;\n        break;\n      }\n      case \"min-height\": {\n        this.minHeight = value;\n        break;\n      }\n      case \"max-height\": {\n        this.maxHeight = value;\n        break;\n      }\n    }\n  }\n\n  static setTexts(textupdate: ImgEditTexts) {\n    if (!ImgEditElement.texts)\n      ImgEditElement.texts = {};\n\n    Object.assign(ImgEditElement.texts, textupdate);\n    dompack.qSA<ImgEditElement>(\"wh-imgedit\").forEach(node => node.refresh()); //update any existing nodes\n  }\n\n  async _check() {\n    const error = await super._check();\n    if (!error && this.isSet() && (this.minWidth || this.maxWidth || this.minHeight || this.maxHeight)) {\n      for (const file of this.currentFiles) {\n        if (file.file) {\n          const size = await getImageDimensions(file.file);\n          if (this.minWidth && size.width < this.minWidth)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.minwidth\", size.width, this.minWidth), { reportimmediately: false });\n          else if (this.maxWidth && size.width > this.maxWidth)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.maxwidth\", size.width, this.maxWidth), { reportimmediately: false });\n          else if (this.minHeight && size.height < this.minHeight)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.minheight\", size.height, this.minHeight), { reportimmediately: false });\n          else if (this.maxHeight && size.height > this.maxHeight)\n            setFieldError(this, getTid(\"publisher:site.forms.commonerrors.maxheight\", size.height, this.maxHeight), { reportimmediately: false });\n        }\n      }\n    }\n    return error;\n  }\n\n  refresh() {\n    const nodes = [];\n    for (const [idx, file] of this.currentFiles.entries()) {\n      const imgholder = dompack.create(\"div\", { class: \"image\", part: \"image\" });\n      const img = dompack.create(\"img\", { class: 'image__img', src: file.link ?? createFileURL(file.file) });\n\n      const deletebutton = dompack.create(\"button\", { part: \"button deletebutton\", class: \"deletebutton image__deletebutton\" });\n      this.setupDeleteButton(deletebutton, idx);\n\n      imgholder.append(img, deletebutton);\n      nodes.push(imgholder);\n    }\n\n    if (this.currentFiles.length < this.maxFiles) {\n      //add an extra 'image' which is the placeholder for additional uploads\n      const imgholder = dompack.create(\"div\", { class: \"image image--placeholder\", part: \"image placeholder\" });\n      const contentwrapper = dompack.create(\"div\", { class: \"image__content\" });\n      const uploadicon = dompack.create(\"div\", { class: \"image__uploadicon\", part: \"uploadicon\" });\n      const explain = dompack.create(\"div\", {\n        class: \"image__explain\",\n        textContent: ImgEditElement.texts?.explainUpload || getTid(\"publisher:site.forms.imgedit-explain-upload\")\n      });\n      imgholder.append(contentwrapper);\n      contentwrapper.append(uploadicon, explain);\n      imgholder.tabIndex = 0;\n      this.setupUploadButton(imgholder);\n      nodes.push(imgholder);\n    }\n\n    /* FIXME aria label, currently set at group level, should be per image?\n\n          // Set the aria-label to a combined label of the field together with the action which activating it through click/enter/space will perform\n          this.node.setAttribute(\"aria-label\", getTid(\"publisher:site.forms.imgedit-groupelement-upload\", this.node.dataset.arialabel));\n\n                    // Set the aria-label to a combined label of the field together with the action which activating it through click/enter/space will perform\n          this.node.setAttribute(\"aria-label\", getTid(\"publisher:site.forms.imgedit-groupelement-replace\", this.node.dataset.arialabel));\n*/\n\n    this.maindiv.replaceChildren(...nodes);\n  }\n}\n\n//////// Legacy version. We expect existing users to migrate to the version above\n\nexport default class ImgEditField {\n  constructor(node: HTMLElement) {\n    if (!customElements.get(\"wh-imgedit\"))\n      customElements.define(\"wh-imgedit\", ImgEditElement);\n  }\n}\n","import * as dompack from 'dompack';\nimport { getTid, getTidLanguage } from \"@webhare/gettid\";\nimport { getFormService } from \"@webhare/forms/src/formservice\";\nimport { isValidEmail, wrapInTimeout } from '@webhare/std';\nimport { setFieldError } from './customvalidation';\nimport type { EmailValidationResult } from '@webhare/forms/src/types';\nimport type FormBase from '../formbase';\nimport type RPCFormBase from '../rpc';\nimport { debugFlags } from '@webhare/env';\n\nconst cache:\n  {\n    [key: string]: Promise<EmailValidationResult>;\n  } = {};\n\nfunction mayValidateField(field: HTMLInputElement) {\n  if (field.disabled || field.readOnly) //FIXME shouldn't we just decide not to validate at a much higher level if something cannot be changed ?\n    return false;\n\n  if (field.autocomplete && field.autocomplete.split(' ').includes(\"username\")) //Well, we shouldn't *force* usernames as a blacklisted domain might still have been explicitly added as login. but suggestions are still useful?\n    return false;\n  return true;\n}\n\nfunction acceptEmailSuggestion<DataShape extends object = Record<string, unknown>>(evt: Event, form: FormBase<DataShape>, field: HTMLInputElement, suggestion: string) {\n  dompack.stop(evt);\n  field.value = suggestion;\n  field.propWhValidationSuggestion = null;\n  form._reportFieldValidity(field);\n}\n\nexport async function validateField<DataShape extends object = Record<string, unknown>>(form: FormBase<DataShape> | RPCFormBase<DataShape>, field: HTMLInputElement) {\n  if (field.dataset.whFormEmailBlocked) {\n    delete field.dataset.whFormEmailBlocked;\n    setFieldError(field, \"\"); //explicitly clear our earlier setFieldError, but only if we set it. FIXME To really cleanly solve this we need better integration with rpc.ts - we want to be in the setupValidation chain and simply return errors instead of being explictly invoked\n  }\n\n  const checkvalue: string = field.value;\n  if (!checkvalue || !mayValidateField(field)) {\n    return true; //not a problem\n  }\n\n  if (!isValidEmail(checkvalue)) {\n    //TODO why aren't we just returning the error like a validator callback? may also help avoid the whFormEamailBlocked hack..\n    field.dataset.whFormEmailBlocked = \"true\";\n    setFieldError(field, getTid(\"publisher:site.forms.commonerrors.email\"));\n    return false;\n  }\n\n  //user is 'done' with email field apparently. remotely validate it\n  const key = \"e_\" + field.name + \".\" + checkvalue; //e_ prefix protects against funny people using 'constructor' etc. TODO just switch to a Map<> or similar. TODO only include field.name if needed, and also bind to the form then\n  if (cache[key] === undefined) {\n    const rpcCall = \"getRPCFormIdentifier\" in form ?\n      //TODO rendering.whlib should add a data attribute if there are form+field-specific checks, perhaps we can even generalize that for all fields instead of just email whenever they need to do direct validation\n      getFormService().formValidateEmail({ ...form.getRPCFormIdentifier(), field: field.name }, checkvalue)\n      : getFormService().validateEmail(getTidLanguage(), checkvalue);\n\n    //wrap in timeout\n    cache[key] = wrapInTimeout(rpcCall, 3000, \"Timeout\");\n  }\n\n  //TODO should we ever clear the cache? only relevant probably if someone is on the frontend testing emails and doesn't want to refresh\n  let result: EmailValidationResult | undefined;\n\n  try {\n    result = await cache[key];\n  } catch (e) { //timeout or other error, or offline form (PWA?)\n    if (debugFlags.fhv)\n      console.log('[fhv] Email validation error or timeout for value', checkvalue, e);\n  }\n\n  if (checkvalue !== field.value || !mayValidateField(field))\n    return true; //the field already changed, don't report about old errors\n\n  if (result?.blocked) {\n    field.dataset.whFormEmailBlocked = \"true\";\n    setFieldError(field, result.blocked);\n    return false;\n  }\n\n  if (result?.force) {\n    field.value = result.force;\n\n    //we should be able to assume we won't have to revalidate a server-provided suggestion\n    cache[\"e_\" + field.name + \".\" + result.force] = Promise.resolve<EmailValidationResult>({});\n\n    return true;\n  } else if (result?.suggestion) {\n    const suggestion = getTid(\"publisher:site.forms.commonerrors.email_suggestion\", \"___SUGGESTION___\").split(\"___SUGGESTION___\");\n\n    //we should be able to assume we won't have to revalidate a server-provided suggestion\n    cache[\"e_\" + field.name + \".\" + result.suggestion] = Promise.resolve<EmailValidationResult>({});\n\n    field.propWhValidationSuggestion =\n      <span class=\"wh-form__emailcorrection\">\n        {suggestion[0]}\n        <a href=\"#\" class=\"wh-form__emailcorrected\" on={{ click: (evt: Event) => acceptEmailSuggestion(evt, form, field, result.suggestion as string) }}>{result.suggestion}</a>\n        {suggestion[1]}\n      </span>;\n    return true;\n  }\n  return true;\n}\n","import { debugFlags } from \"@webhare/env\";\n\n/** @deprecated  Use debugFlags from \\@webhare/env */\nconst debugflags = debugFlags;\nexport { debugflags };\n\n//Add all flags as a dompack-debug-- class\nif (typeof document !== 'undefined')\n  document.documentElement.classList.add(...Object.keys(debugFlags).map(flagname => \"dompack--debug-\" + flagname));\nif (debugFlags.dompack)\n  console.log('[dompack] debugging flags: ' + Object.keys(debugFlags).join(', '));\n","/* @recommendedimport: import * as browser from 'dompack/extra/browser';\n\n   Identify devices for the purpose of analytics/tracing\n   NOT a library for feature detection!\n\n   Based on Mootools.Browser\n*/\n/* eslint no-useless-escape: off */\n\ntype Platform = \"windows\" | \"ios\" | \"webos\" | \"android\" | \"linux\" | \"mac\" | \"other\";\n\nexport type UserAgentInfo =\n  {\n    name: string;\n    version: number;\n    platform: Platform;\n    device: \"desktop\" | \"mobile\" | \"tablet\" | \"\";\n  };\n\nexport function parseUserAgent(ua: string): UserAgentInfo {\n  ua = ua.toLowerCase();\n\n  // chrome is included in the edge UA, so need to check for edge first, before checking if it's chrome.\n  // safari is included in the miuibrowser UA, so need to check for miuibrowser first, before checking if it's safari.\n  let UA: RegExpMatchArray | null = ua.match(/(edge|miuibrowser)[\\s\\/:]([\\w\\d\\.]+)/);\n  if (!UA)\n    UA = ua.match(/(opera|ie|firefox|chrome|trident|crios|version)[\\s\\/:]([\\w\\d\\.]+)?.*?(safari|(?:rv[\\s\\/:]|version[\\s\\/:])([\\w\\d\\.]+)|$)/);\n  if (!UA) { //try ios 11.4.1\n    UA = ua.match(/; cpu os ([\\d]+)/);\n    if (UA)\n      UA = ['', 'safari', UA[1]];\n  }\n  if (!UA)\n    UA = ['', 'unknown', \"0\"];\n\n  if (UA[1] === 'trident') {\n    UA[1] = 'ie';\n    if (UA[4]) UA[2] = UA[4];\n  } else if (UA[1] === 'crios') {\n    UA[1] = 'chrome';\n  }\n\n  let platform = ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || ua.match(/mac|win|linux/) || ['other'])[0];\n  if (platform === 'win') platform = 'windows';\n\n  const ret: UserAgentInfo =\n  {\n    name: (UA[1] === 'version') ? UA[3] : UA[1],\n    version: parseInt((UA[1] === 'opera' && UA[4]) ? UA[4] : UA[2]),\n    platform: platform as Platform,\n    device: ua.match(/ipad/) ? 'tablet' : ['ios', 'webos', 'android'].includes(platform) ? 'mobile' : ['mac', 'windows', 'linux'].includes(platform) ? 'desktop' : ''\n  };\n\n  return ret;\n}\n\n//module.exports =\nconst browser = parseUserAgent(globalThis.navigator?.userAgent || \"\");\n\nexport function getName() {\n  return browser.name;\n}\nexport function getVersion() {\n  return browser.version;\n}\nexport function getPlatform() {\n  return browser.platform;\n}\nexport function getDevice() {\n  return browser.device;\n}\nexport function getTriplet() {\n  return browser.platform + '-' + browser.name + '-' + browser.version;\n}\n","/* All keynames should be mixed-cased, as done here: http://www.w3.org/TR/DOM-Level-3-Events-key/\n\n   Modifiers should be in the ordering Alt+Control+Meta+Shift+key (ie alphabetical)\n\n   To simply prevent keys from propagating up (ie to keep Enter inside its textarea)\n   new KeyboardHandler(this.textarea, {}, { dontpropagate: ['Enter']});\n*/\n\nimport { type NormalizedKeyboardEvent, normalizeKeyboardEventData } from '../src/events';\nimport { debugflags } from '../src/debug';\nimport { getPlatform } from './browser';\nconst IS_MAC_PLATFORM = getPlatform() === \"mac\";\n\nconst propnames = {\n  shiftKey: \"Shift\",\n  ctrlKey: IS_MAC_PLATFORM ? \"Control\" : [\"Accel\", \"Control\"],\n  metaKey: IS_MAC_PLATFORM ? [\"Accel\", \"Meta\"] : \"Meta\",\n  altKey: \"Alt\"\n};\n\nfunction getFinalKey(event: NormalizedKeyboardEvent) { //get the name for the 'final' key, eg the 'D' in 'alt+control+d'\n  if (event.code?.startsWith('Key') && event.code.length === 4)\n    return event.code.substring(3, 4).toUpperCase();\n  if (event.code?.startsWith('Digit') && event.code.length === 6)\n    return event.code.substring(5, 6).toUpperCase();\n  return event.key.length === 1 ? event.key.toUpperCase() : event.key;\n}\n\nfunction getKeyNames(event: NormalizedKeyboardEvent) {\n  let names: string[][] = [[]];\n\n  /*\n    // Firefix under selenium on linux always says 'Unidentified' as key. Backup for some keys.\n    if (basekey === \"Unidentified\")\n      basekey = selenium_backup[event.keyCode];\n  */\n  // Create the modifiers in the names array (omit the basekey, so we can sort on modifier first)\n  (Object.keys(propnames) as Array<keyof typeof propnames>).forEach(propname => {\n    if (event[propname]) {\n      // The key is pressed. Add the modifier name to all current names.\n      const modifier: string | string[] = propnames[propname];\n      if (!Array.isArray(modifier))\n        names.forEach(function (arr) { arr.push(modifier); });\n      else {\n        // Multiple modifiers map to this key, duplicate all result sequences for every modifier\n        const newkeys: string[][] = [];\n        modifier.forEach(function (singlemodifier) {\n          names.forEach(function (arr) {\n            newkeys.push(arr.concat([singlemodifier]));\n          });\n        });\n        names = newkeys;\n      }\n    }\n  });\n\n  return names.map(function (arr) {\n    // Sort the modifier names\n    arr = arr.sort();\n    arr.push(getFinalKey(event));\n    return arr.join(\"+\");\n  });\n}\n\nfunction validateKeyName(key: string) {\n  const modifiers = key.split(\"+\");\n  modifiers.pop();\n\n  // Check for allowed modifiers\n  modifiers.forEach(function (mod) {\n    if (![\"Accel\", \"Alt\", \"Control\", \"Meta\", \"Shift\"].includes(mod))\n      throw new Error(\"Illegal modifier name '\" + mod + \"' in key '\" + key + \"'\");\n  });\n\n  const original_order = modifiers.join('+');\n  modifiers.sort();\n  if (modifiers.join('+') !== original_order)\n    throw new Error(\"Illegal key name \" + key + \", modifiers must be sorted alphabetically\");\n}\n\ntype KeyboardMappingHandler = (event: KeyboardEvent) => boolean | void;\ntype KeyboardMapping = { [key: string]: KeyboardMappingHandler };\ntype KeyPressHandler = (event: KeyboardEvent, key: string) => boolean | void;\ntype KeyboardEventHandler = (event: Event) => void;\ntype KeyboardHandlerOptions =\n  {\n    stopmapped?: boolean;\n    dontpropagate?: string[];\n    onkeypress?: KeyPressHandler;\n    captureunsafekeys?: boolean;\n    listenoptions?: AddEventListenerOptions;\n  };\n\n/**\n     node: The node to attach to\n    keymap: Keymap\n    options.stopmapped - preventDefault and stopPropagation on any key we have in our map\n    options.dontpropagate - string array of keys not to propagate out of this object\n    options.onkeypress - when set, call for all keypresses. signature: function (event, key). Should always return true and preventDefault (and/or stop) the event to cancel its handling\n    options.listenoptions - addEventListener options (eg \\{capture:true\\})\n */\nexport default class KeyboardHandler {\n  node: EventTarget;\n  keymap: KeyboardMapping;\n  stopmapped: boolean;\n  dontpropagate: string[];\n  onkeypress?: KeyPressHandler;\n  captureunsafekeys: boolean;\n  private _listenoptions?: AddEventListenerOptions;\n  private _onkeydown: KeyboardEventHandler;\n  private _onkeypress: KeyboardEventHandler;\n\n  constructor(node: EventTarget, keymap: KeyboardMapping, options?: KeyboardHandlerOptions) {\n    this.node = node;\n    this.keymap = {};\n    this.stopmapped = options?.stopmapped ?? false;\n    this.dontpropagate = options?.dontpropagate ? [...options.dontpropagate].map(name => name.toUpperCase()) : [];\n    this.onkeypress = options?.onkeypress;\n    this.captureunsafekeys = options?.captureunsafekeys ?? false;\n    this._listenoptions = options?.listenoptions;\n\n    Object.keys(keymap).forEach(keyname => {\n      if (debugflags.key)\n        validateKeyName(keyname);\n      this.keymap[keyname.toUpperCase()] = keymap[keyname];\n    });\n\n    this._onkeydown = (event) => this._onKeyDown(event);\n    this._onkeypress = (event) => this._onKeyPress(event);\n    node.addEventListener('keydown', this._onkeydown, this._listenoptions);\n    node.addEventListener('keypress', this._onkeypress, this._listenoptions);\n  }\n\n  destroy() {\n    this.node.removeEventListener('keydown', this._onkeydown, this._listenoptions);\n    this.node.removeEventListener('keypress', this._onkeypress, this._listenoptions);\n  }\n\n  /**\n       Returns thether the current pressed special key should be ignored for the current target node\n      Used to detect input/textarea/rte's\n   *\n      @param target - Current target node for keyboard event\n      @param key - Parsed key\n      @param keynames - Potential names for the keys (as returned by GetKeyNames)\n      @returns Whether the key must be ignored by KeyboardHandler, default browser behaviour should be triggered.\n   */\n  private _mustIgnoreKey(target: EventTarget | null, key: string, keynames: string[]) {\n    if (!(target instanceof Node))\n      return false;\n    const tag = target.nodeName.toLowerCase();\n    if (tag === \"select\") {\n      if ([\"ArrowUp\", \"ArrowDown\", \"Home\", \"End\", \"PageUp\", \"PageDown\"].indexOf(key) !== -1)\n        return true;\n    } else if (tag === \"input\" || tag === \"textarea\" || (target instanceof HTMLElement && target.isContentEditable)) {\n      // These keys we ignore, regardless of the modifier\n      if ([\n        \"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\",\n        \"PageUp\", \"PageDown\",\n        \"Home\", \"End\",\n        \"Insert\", \"Delete\", \"Backspace\"\n      ].indexOf(key) !== -1)\n        return true;\n\n      let is_special_combo = false;\n\n      // only input doesn't want exact combo 'Enter', the rest does\n      if (tag !== \"input\" && keynames.indexOf(\"Enter\") !== -1)\n        is_special_combo = true;\n\n      // Only contenteditable wants \"Shift+Enter\"\n      if (target instanceof HTMLElement && target.isContentEditable && keynames.indexOf(\"Shift+Enter\") !== -1)\n        is_special_combo = true;\n\n      // These exact combo's are wanted by all inputs\n      [\"Accel+A\", \"Accel+V\", \"Accel+C\", \"Accel+X\"].forEach(function (name) {\n        is_special_combo = is_special_combo || keynames.indexOf(name) !== -1;\n      });\n      return is_special_combo;\n    }\n    return false;\n  }\n\n  addKey(keybinding: string, handler: KeyboardMappingHandler) {\n    if (debugflags.key) {\n      validateKeyName(keybinding);\n      console.log(\"[key] KeyDown handler registered for \" + keybinding);\n    }\n    this.keymap[keybinding.toUpperCase()] = handler;\n  }\n  removeKey(keybinding: string) {\n    delete this.keymap[keybinding.toUpperCase()];\n  }\n  _onKeyDown(event: Event) { // We're a key event handler, so we know the event is a KeyboardEvent\n    const keydata = normalizeKeyboardEventData(event as KeyboardEvent);\n\n    // Get all possible names for this key\n    const keynames = getKeyNames(keydata);\n    if (!keydata.key || !keynames.length) {\n      if (debugflags.key)\n        console.log(\"[key] KeyDown handler for \", this.node, \" did not recognize key from event\", event);\n      return true;\n    }\n\n    if (debugflags.key)\n      console.log(\"[key] KeyDown handler for \", this.node, \" got key \", keydata.key, \" with target \", event.target, \" keynames:\", keynames);\n\n    /* Some keys we ignore, unless we're explicitly bound to a node, so we don't inadvertly break eg a <input> node inside\n       a listview we're handling or otherwise break a user's expectation. Set the option 'captureunsafekeys' if you explicitly\n       want to be able to capture any key */\n\n    if (!this.captureunsafekeys && this._mustIgnoreKey(event.target, keydata.key, keynames)) {\n      if (debugflags.key)\n        console.log(\"[key] KeyDown event will not be intercepted, it's an unsafe key to intercept\");\n      return true;\n    }\n\n    if (this.dontpropagate) {\n      keynames.forEach(keyname => {\n        if (this.dontpropagate.includes(keyname)) {\n          if (debugflags.key)\n            console.log(\"[key] KeyDown event will not bubbleup because of our dontpropagate option (but may still trigger a default action)\");\n          event.stopPropagation();\n        }\n      });\n    }\n\n    for (let i = 0; i < keynames.length; ++i) {\n      const mapping = this.keymap[keynames[i].toUpperCase()];\n      if (!mapping)\n        continue;\n\n      if (this.stopmapped) {\n        if (debugflags.key)\n          console.log(\"[key] KeyDown event will not bubbleup or trigger default, because we're configured to block any mapped key\");\n        event.stopPropagation();\n        event.preventDefault();\n      }\n\n      const ishandled = mapping.apply(this.node, [event as KeyboardEvent]);\n      if (ishandled && !event.defaultPrevented) {\n        console.warn(`The key handler for '${keynames[i]}' should preventDefault (or dompack.stop) the event to block fruther propagation`);\n        event.stopPropagation();\n        event.preventDefault();\n        if (debugflags.key)\n          console.log(\"[key] KeyDown event will not bubbleup or trigger default, because the keyhandler indicated the key was handled\");\n      }\n\n      if (!event.defaultPrevented && debugflags.key)\n        console.log(\"[key] KeyDown event was not blocked by its explicitly configured handler\");\n    }\n    return true;\n  }\n  _onKeyPress(event: Event) { // We're a key event handler, so we know the event is a KeyboardEvent\n    const keydata = normalizeKeyboardEventData(event as KeyboardEvent);\n\n    if (this.onkeypress) {\n      if (!this.onkeypress.apply(this.node, [event as KeyboardEvent, keydata.key])) {\n        if (!event.defaultPrevented)\n          console.warn(\"The onkeypress handler should preventDefault (or dompack.stop) the event to block fruther propagation\");\n        event.stopPropagation();\n        event.preventDefault();\n      }\n    }\n  }\n}\n\nexport function getEventKeyNames(event: KeyboardEvent) {\n  const keydata = normalizeKeyboardEventData(event);\n  return getKeyNames(keydata);\n}\n","/* Dialogapi offers an API to which dialog providers cannot connect. It does\n   not implement the dialogs themselves\n*/\n\nimport * as dompack from 'dompack';\nimport * as domfocus from 'dompack/browserfix/focus';\nimport KeyboardHandler from \"dompack/extra/keyboard\";\n\nexport type DialogOptions =\n  {\n    /**  Allow the dialog to be cancelled by clicking outside the dialog. Defaults to true if no choices are specified */\n    allowcancel?: boolean;\n    /**  Element to focus on closing the dialog */\n    focusonclose?: HTMLElement;\n    /**  An AbortSignal which if set will close the dialog and resolve it with a null response */\n    signal?: EventTarget;\n    /**  Additional class to set on the dialog */\n    messageboxclassbase?: string;\n\n    borrow?: Element | string;\n  };\ntype DialogConstructor = (options?: DialogOptions) => DialogBase;\n\nconst dialogstack: DialogBase[] = [];\nlet keyhandler: KeyboardHandler | null = null;\nlet dialogconstructor: DialogConstructor | null = null;\nlet dialogoptions: DialogOptions | null = null;\n\nfunction onEscape(event: KeyboardEvent) {\n  if (!dialogstack.length)\n    return;\n\n  dompack.stop(event);\n  if (dialogstack[dialogstack.length - 1].options.allowcancel)\n    dialogstack[dialogstack.length - 1].resolve(null);\n}\n\nfunction onTab(event: KeyboardEvent, direction: number) {\n  if (!dialogstack.length)\n    return;\n\n  dompack.stop(event);\n\n  const focusable = domfocus.getFocusableComponents(dialogstack[dialogstack.length - 1].contentnode, true);\n  const el = domfocus.getCurrentlyFocusedElement();\n  const tofocusidx = el ? focusable.indexOf(el) + direction : -1;\n  const tofocus = tofocusidx < 0 ? focusable[focusable.length - 1] : tofocusidx >= focusable.length ? focusable[0] : focusable[tofocusidx];\n  if (tofocus)\n    dompack.focus(tofocus);\n}\n\nexport class DialogBase {\n  options: DialogOptions;\n  private _borrowedfrom: Element | null = null;\n  private _borrowednext: Element | null = null;\n  contentnode: Element | null; //FIXME a successor to DialogBase should not allow these to be | null. have our child inform us through super() about the contentnode and buttonsnode so we can ensure it's set\n  buttonsnode: Element | null = null;\n  private _deferred: PromiseWithResolvers<string | null>;\n  open: boolean;\n  private _previousfocus: Element | null = null;\n\n  constructor(options?: DialogOptions) {\n    this.options = {\n      allowcancel: true,\n      ...options\n    };\n\n    if (this.options.borrow && typeof this.options.borrow === 'string') {\n      const borrow = document.querySelector(this.options.borrow);\n      if (!borrow)\n        throw new Error(\"Invalid 'borrow' selectior: \" + this.options.borrow);\n      this.options.borrow = borrow;\n    }\n    // At this point, if this.options.borrow was a string, it's been resolved to an Element\n\n    if (this.options.borrow) {\n      this._borrowedfrom = (this.options.borrow as Element).parentElement;\n      this._borrowednext = (this.options.borrow as Element).nextElementSibling;\n    }\n\n    if (this.options.signal)\n      this.options.signal.addEventListener(\"abort\", () => { this.resolve(null); });\n\n    this.contentnode = null;\n    this._deferred = Promise.withResolvers();\n    this.open = false;\n  }\n\n  async runModal() {\n    if (this.open)\n      throw new Error(\"Attempting to re-open already opened dialog\");\n\n    if (!keyhandler)\n      keyhandler = new KeyboardHandler(window, {\n        \"Escape\": (evt: KeyboardEvent) => onEscape(evt),\n        \"Tab\": (evt: KeyboardEvent) => onTab(evt, +1),\n        \"Shift+Tab\": (evt: KeyboardEvent) => onTab(evt, -1)\n      }, { captureunsafekeys: true, listenoptions: { capture: true } });\n\n    this._previousfocus = domfocus.getCurrentlyFocusedElement();\n    this._openDialog();\n\n    this.open = true;\n    dialogstack.push(this);\n\n    try {\n      this.afterShow();\n      this._checkFocus();\n      return await this._deferred.promise;\n    } finally {\n      if (this.open)\n        this.closeDialog();\n    }\n  }\n\n  _openDialog() {\n    throw new Error(\"_openDialog not overridden by dialog class\");\n  }\n\n  _checkFocus() {\n    const focusable = domfocus.getFocusableComponents(this.contentnode, true);\n    if (focusable.length !== 0)\n      dompack.focus(focusable[0]);\n    else\n      dompack.focus(document.body);\n  }\n\n  //close the dialog. this may be invoked even when inside runModal to ensure synchronous dialog cleanup\n  closeDialog() {\n    if (!this.open)\n      return;\n\n    const myoffset = dialogstack.indexOf(this);\n    if (myoffset >= 0)\n      dialogstack.splice(myoffset, 1);\n\n    this.open = false;\n    if (this.options.borrow)\n      if (this._borrowedfrom)\n        this._borrowedfrom.insertBefore(this.options.borrow as Element, this._borrowednext);\n      else\n        this._borrowednext?.remove();\n\n    if (this.options.focusonclose)\n      dompack.focus(this.options.focusonclose);\n    else if (this._previousfocus)\n      dompack.focus(this._previousfocus as HTMLElement);\n\n    if (dialogstack.length === 0 && keyhandler) {\n      keyhandler.destroy();\n      keyhandler = null;\n    }\n  }\n\n  /**\n   * resolve the dialog with the specified answer\n   *\n   * @param response - Response (or choice) to return. null if the dialog was simply cancelled\n   */\n  resolve(response: string | null) {\n    if (this.open)\n      this.closeDialog();\n    this._deferred.resolve(response);\n  }\n\n  afterShow() {\n    // supposed to be empty but extenders can override\n  }\n}\n\nexport function setupDialogs(newdialogconstructor: DialogConstructor, options?: DialogOptions) {\n  if (dialogconstructor) {\n    console.error(\"Duplicate setupDialogs call!\");\n    return;\n  }\n\n  dialogconstructor = newdialogconstructor;\n  dialogoptions = { messageboxclassbase: 'dompack-messagebox__', ...options };\n}\n\n/** Verify whether the dialog api is initialized */\nexport function isCreateDialogAvailable(): boolean {\n  return Boolean(dialogconstructor);\n}\n\n/**\n * Create a dialog\n *\n * @param options - dialog settings\n */\nexport function createDialog(options?: DialogOptions) {\n  if (!dialogconstructor)\n    throw new Error(\"Cannot create dialog, no dialog class defined\");\n\n  const dialog = dialogconstructor(options);\n  if (dialog.options.borrow)\n    dialog.contentnode?.appendChild(dialog.options.borrow as Element);\n  return dialog;\n}\n\ntype DialogChoice =\n  {\n    /** Title for the choice */\n    title: string;\n    /** Override result to return if clicked (otherwise you'll just receive the title) */\n    result?: string;\n    className?: string;\n  };\n\n\n/**\n                     @param question - if a string, will be wrapped as textContent into a <p> and presented as the question\n                    - if a html node, will appear as the question (allowing you to insert html)\n                    - if an array of nodes, all these nodes will be inserted\n    @param choices - Buttons (choices) the message box will offer, eg Ok and Cancel\n    @param options - Dialog options\n */\nexport async function runMessageBox(question: string | HTMLElement | HTMLElement[], choices: DialogChoice[], options?: DialogOptions) {\n  choices = choices || [];\n  options = { allowcancel: choices.length === 0, ...options };\n\n  const dialog = createDialog(options);\n  const choicebuttons = choices.map(choice =>\n    dompack.create(\"button\", {\n      type: \"button\",\n      className: dialogoptions ? dialogoptions.messageboxclassbase + \"button \" + (choice.className || \"\") : \"\",\n      textContent: choice.title,\n      on: { click: () => dialog.resolve(choice.result || choice.title) },\n      dataset: { messageboxResult: choice.result || choice.title }\n    }));\n\n  if (typeof question === 'string')\n    question = dompack.create(\"p\", { textContent: question });\n\n  if (Array.isArray(question))\n    dialog.contentnode?.append(...question);\n  else\n    dialog.contentnode?.append(question);\n\n  if (dialog.buttonsnode) //this dialog has a separte node for the button area\n    dialog.buttonsnode.append(...choicebuttons);\n  else\n    dialog.contentnode?.append(dompack.create(\"div\", {\n      className: dialogoptions ? dialogoptions.messageboxclassbase + \"buttongroup\" : \"\",\n      childNodes: choicebuttons\n    }));\n\n  return dialog.runModal();\n}\n","/* eslint-disable @typescript-eslint/no-floating-promises -- FIXME: needs API rework */\n\nimport * as dompack from '@webhare/dompack';\nimport * as focus from 'dompack/browserfix/focus';\nimport * as merge from './internal/merge';\nimport FormBase, { type FormResultValue, type FormSubmitEmbeddedResult, type FormSubmitMessage, type FormSubmitResult } from './formbase';\nimport { getFormService, getTSFormService, type PublisherFormService } from \"@webhare/forms/src/formservice\";\nimport * as emailvalidation from './internal/emailvalidation';\nimport { runMessageBox } from 'dompack/api/dialog';\nimport { debugFlags, isLive, navigateTo, type NavigateInstruction } from \"@webhare/env\";\nimport { isBlob, pick } from '@webhare/std';\nimport { setFieldError } from './internal/customvalidation';\nimport type { RPCFormTarget, RPCFormInvokeBase, RPCFormSubmission } from '@webhare/forms/src/types';\nimport { SingleFileUploader, type UploadResult } from '@webhare/upload';\nimport { createClient } from '@webhare/jsonrpc-client';\nimport { setupCaptchaFieldGroup } from './fields/captchafield';\nimport { getFormConfiguration } from '@webhare/forms/src/registration';\nimport type { CaptchaProvider } from '../captcha/api';\n\nfunction unpackObject(formvalue: FormResultValue): RPCFormInvokeBase[\"vals\"] {\n  return Object.entries(formvalue).map(_ => ({ name: _[0], value: _[1] }));\n}\n\nexport interface FormSubmitDetails<DataShape extends object = Record<string, unknown>> {\n  form: HTMLElement;\n  rpchandler: RPCFormBase<DataShape>;\n  extrasubmitdata?: unknown;\n  submitted: FormResultValue;\n  result: unknown;\n  errors: FormSubmitMessage[];\n}\n\ntype UploadCache = WeakMap<Blob, UploadResult>;\n\nfunction buildTarget(target: string): RPCFormTarget {\n  return { target, url: location.href.split('/').slice(3).join('/') };\n}\n\nclass FormSubmitter {\n  private readonly target;\n  private readonly cache: UploadCache;\n  private readonly offline: boolean;\n\n  constructor(target: string, cache: UploadCache | null, offline: boolean) {\n    this.target = buildTarget(target);\n    this.cache = cache || new WeakMap();\n    this.offline = offline;\n  }\n\n  private async uploadFile(file: Blob) {\n    if (this.offline)\n      throw new Error(\"Cannot upload files in offline mode\"); //TODO convert to dataurl and test it\n\n    //TODO what if the server discarded the token? we should negotiate with the server which files it (still) wants\n    const completed = this.cache.get(file);\n    if (completed)\n      return completed;\n\n    const uploader = new SingleFileUploader(file);\n    //Ask the server if it's okay to upload these files\n    const uploadinstructions = await getTSFormService().requestUpload(this.target, uploader.manifest);\n    //Run the actual upload. Options: onProgress, signal\n    const uploadedfile: UploadResult = await uploader.upload(uploadinstructions);\n    this.cache.set(file, uploadedfile);\n    return uploadedfile;\n  }\n\n  private async convertSubmittable(formvalue: unknown): Promise<unknown> {\n    //TODO combine multiple uploads into one\n    if (Array.isArray(formvalue))\n      return await Promise.all(formvalue.map(file => this.getSubmittable(file)));\n\n    if (formvalue && typeof formvalue === 'object') {\n      if (isBlob(formvalue))\n        return await this.uploadFile(formvalue as Blob);\n\n      const result: Record<string, unknown> = {};\n      for (const [key, value] of Object.entries(formvalue)) {\n        result[key] = await this.getSubmittable(value);\n        //console.log(key, value, result[key]);\n      }\n      return result;\n    }\n    return formvalue;\n  }\n\n  async getSubmittable(formvalue: object): Promise<FormResultValue> {\n    return await this.convertSubmittable(formvalue) as FormResultValue;\n  }\n}\n\n/** Directly submit a RPC form to WebHare\n *  @param target - Formtarget as obtained from\n * @deprecated Switch to \\@webhare/forms submitForm and buildFormSubmission\n */\nexport async function submitForm(target: string, formvalue: FormResultValue, options?: { extrasubmit: unknown }): Promise<FormSubmitResult> {\n  const submitparameters = await buildRPCFormSubmission(target, formvalue, { extraSubmit: options?.extrasubmit || null, });\n  return await submitRPCForm(submitparameters);\n}\n\n/** Return a value safe for RPC submission or typed serialization */\nexport async function buildRPCFormSubmission<DataShape extends object = Record<string, unknown>>(target: string, formValue: DataShape, options?:\n  {\n    extraSubmit?: unknown;\n    offline?: boolean;\n    uploadCache?: WeakMap<Blob, UploadResult>;\n    __setupEvent?: FormSubmitDetails<DataShape>;\n  }): Promise<RPCFormSubmission> {\n  const submitter = new FormSubmitter(target, options?.uploadCache || null, options?.offline || false);\n\n  const vals = await submitter.getSubmittable(formValue);\n\n  if (options?.__setupEvent) {\n    const eventdetail = options.__setupEvent;\n    eventdetail.extrasubmitdata = options.extraSubmit || null;\n    eventdetail.submitted = vals;\n  }\n\n  const submitparameters: RPCFormSubmission = {\n    ...buildTarget(target),\n    vals: unpackObject(vals),\n    extrasubmit: options?.extraSubmit || null\n  };\n  return submitparameters;\n}\n\nexport async function submitRPCForm(submission: RPCFormSubmission): Promise<FormSubmitResult> {\n  // TODO switch over to typed rpc, allow rpc options that make sense to be specified as options to submitRPCForm\n  const client = createClient<PublisherFormService>(\"publisher:forms\");\n  return await client.formSubmit(submission);\n}\n\nexport default class RPCFormBase<DataShape extends object = Record<string, unknown>> extends FormBase<DataShape> {\n  __formhandler = {\n    errors: [],\n    warnings: [],\n    formid: \"\",\n    url: \"\",\n    target: \"\",\n    submitting: false\n  };\n\n  #hadFocus = false;\n  #completedUploads = new WeakMap<Blob, UploadResult>;\n  #settingUpCaptcha = false;\n\n  pendingrpcs = new Array<Promise<unknown>>;\n\n  constructor(formnode: HTMLFormElement) {\n    super(formnode);\n    this.__formhandler.formid = formnode.dataset.whFormId || ''; //needed for 'old' __formwidget: stuff\n    this.__formhandler.url = location.href.split('/').slice(3).join('/');\n    this.__formhandler.target = formnode.dataset.whFormTarget || '';\n    window.addEventListener(\"wh:form-configure\", () => this.checkCaptcha());\n    this.node.addEventListener(\"focusin\", this.#onFirstFocus, true);\n\n    if (!this.__formhandler.target) {\n      if (this.__formhandler.formid) {\n        console.error(\"This page needs to be republished!\");\n      } else {\n        if (!isLive)\n          console.error(\"Missing data-wh-form-target on form, did your witty apply '[form.formattributes]' to the <form> tag ?\", formnode);\n        throw new Error(\"Form does not appear to be a WebHare form\");\n      }\n    }\n\n    this.checkCaptcha();\n  }\n\n  getRPCFormIdentifier(): RPCFormTarget { //submitinfo as required by some RPCs\n    return buildTarget(this.__formhandler.target);\n  }\n\n  async #getSubmitVals(): Promise<FormResultValue> {\n    const formvalue = await this.getFormValue();\n    const submitter = new FormSubmitter(this.__formhandler.target, this.#completedUploads, false);\n    return await submitter.getSubmittable(formvalue);\n  }\n\n  //Invoke a function on the form on the server\n  async _invokeRPC(background: boolean, methodname: string, args: unknown[]) {\n    const waiter = Promise.withResolvers<void>();\n\n    if (!background)\n      this.onRPC(waiter.promise);\n\n    const lock = dompack.flagUIBusy({ modal: !background });\n    try {\n      const rpc = getFormService().formInvoke({\n        ...this.getRPCFormIdentifier(),\n        vals: unpackObject(await this.#getSubmitVals()),\n        methodname,\n        args\n      });\n      this.pendingrpcs.push(rpc);\n      const result = await rpc;\n      this._processMessages(result.messages);\n      return result.result;\n    } finally {\n      lock.release();\n      waiter.resolve();\n    }\n  }\n\n  /* Override this to implement support for incoming field messages */\n  processFieldMessage(field: string, prop: string, value: unknown) {\n    if (field === \"#form\") {\n      if (prop === \"dataset\") {\n        for (const [key, keyValue] of Object.entries(value || {})) {\n          this.node.setAttribute(`data-${key}`, String(keyValue));\n        }\n        return;\n      }\n      console.warn(\"Message for non-existing form field: %s, prop: %s, value: %s\", field, prop, String(value));\n      return;\n    }\n    if (field.startsWith(\"#page.\")) {\n      const matchpage = field === \"#page.thankyou\" ? this.node.querySelector<HTMLElement>(`.wh-form__page[data-wh-form-pagerole=thankyou]`) : null;\n      if (!matchpage) { //we currently don't have anything to edit on other pages than thankyou\n        console.warn(\"Message for non-page field: %s, prop: %s, value: %s\", field, prop, String(value));\n        return;\n      }\n\n      if (prop === 'data') {\n        const dataval = value as { redirect: NavigateInstruction | null; exitbutton: string };\n        matchpage.dataset.whFormNavigateTo = dataval.redirect ? JSON.stringify(dataval.redirect) : undefined;\n        matchpage.dataset.whFormExitButton = dataval.exitbutton;\n      }\n    } else {\n      const fieldnode = this.node.querySelector<HTMLElement>(`*[name=\"${CSS.escape(field)}\"], *[data-wh-form-name=\"${CSS.escape(field)}\"]`);\n      if (!fieldnode) {\n        console.warn(\"Message for non-existent field: %s, prop: %s, value: %s\", field, prop, String(value));\n        return;\n      }\n      if (prop === 'value') {\n        this.setFieldValue(fieldnode, value);\n        return;\n      } else if (prop === 'richvalue') {\n        if (!fieldnode.classList.contains(\"wh-form__richtext\"))\n          console.warn(\"Message for non-richtext field: %s, prop: %s, value: %s\", field, prop, String(value));\n        else {\n          fieldnode.innerHTML = value as string;\n          dompack.registerMissed(fieldnode);\n        }\n        return;\n      }\n    }\n    console.warn(\"Unknown field message: field: %s, prop: %s, value: %s\", field, prop, String(value));\n  }\n\n  //Override this function to easily submit extra fields\n  getFormExtraSubmitData(): object | Promise<object> {\n    return {};\n  }\n\n  //Invoked when RPC is occuring. Is passed a promise that will resolve on completion\n  //onRPC is DEPRECATED, switching to event based api\n  onRPC(promise: Promise<void>) {\n  }\n\n  /** Invoke a function on the form on the server\n      @param methodname - Name of the function on the form\n      @param args - Arguments for the function\n      @returns Promise that resolves to the result of the rpc call\n  */\n  invokeRPC(methodname: string, ...args: unknown[]) {\n    return this._invokeRPC(false, methodname, args);\n  }\n\n  /** Invoke a function on the form on the server, doesn't call .onRPC or request modality layers\n      @param methodname - Name of the function on the form\n      @param args - Arguments for the function\n      @returns Promise that resolves to the result of the rpc call\n  */\n  invokeBackgroundRPC(methodname: string, ...args: unknown[]) {\n    return this._invokeRPC(true, methodname, args);\n  }\n\n  _processMessages(messages: Array<{ field: string; prop: string; data: unknown }>) {\n    for (const msg of messages) {\n      this.processFieldMessage(msg.field, msg.prop, msg.data);\n    }\n    this.refreshConditions();\n  }\n\n  async _flushPendingRPCs() {\n    while (this.pendingrpcs.length) {\n      try {\n        await this.pendingrpcs.pop();\n      } catch (ignore) {\n        //*we* can't handle those...\n      }\n    }\n  }\n\n  async buildFormSubmission(extradata?: object, options?: { __setupEvent?: FormSubmitDetails<DataShape> }): Promise<RPCFormSubmission> {\n    //Request extrasubmit first, so that if it returns a promise, it can execute in parallel with getFormValue\n    const extraSubmitAwaitable = this.getFormExtraSubmitData();\n    //FIXME we want getFormValue to be sync (and just use 'this.data' here) - who is still sending promises our way? too much to sort out for a backport\n    const formvalue = await this.getFormValue() as DataShape;\n    const extraSubmit = { ...extradata, ...(await extraSubmitAwaitable as Record<string, unknown>) };\n\n    await this._flushPendingRPCs();\n    dompack.dispatchCustomEvent(this.node, \"wh:form-preparesubmit\", {\n      bubbles: true, cancelable: false, detail: {\n        extrasubmit: extraSubmit\n      }\n    });\n\n    const submitparameters = await buildRPCFormSubmission<DataShape>(this.__formhandler.target, formvalue, {\n      extraSubmit,\n      offline: false,\n      uploadCache: this.#completedUploads,\n      //hack because we need to record the 'vars' value before unpackObject flattens it for safe HareScript RPC\n      __setupEvent: options?.__setupEvent\n    });\n\n    return submitparameters;\n  }\n\n  #onFirstFocus = () => {\n    this.#hadFocus = true;\n    this.checkCaptcha();\n  };\n\n  private checkCaptcha() {\n    //Checks whether to show captcha based on configuration. Note that even if *we* think it's not needed, form submission may still require a captcha\n    const config = getFormConfiguration();\n    const shouldShow = config?.captcha === \"onLoad\" || (config?.captcha === \"onActivate\" && this.#hadFocus);\n    if (shouldShow && this.node.dataset.whFormCaptcha !== undefined && !this.#settingUpCaptcha && !this.getElementByName(\"__form_captcha\")) {\n      this.#settingUpCaptcha = true;\n      void getFormService().getCaptchaConfiguration(this.getRPCFormIdentifier()).then(captchaConfig => {\n        if (captchaConfig) {\n          setupCaptchaFieldGroup(this, captchaConfig);\n        }\n      });\n    }\n  }\n\n  async submitForm(parameters: RPCFormSubmission): Promise<FormSubmitResult> {\n    return await submitRPCForm(parameters);\n  }\n\n  async submit(extradata?: object): Promise<{ result?: FormSubmitEmbeddedResult }> {\n    //ADDME timeout and free the form after some time\n    if (this.__formhandler.submitting) //throwing is the safest solution... having the caller register a second resolve is too dangerous\n      throw new Error(\"The form is already being submitted\");\n\n    const waiter = Promise.withResolvers<void>();\n    let insubmitrpc = false;\n    this.onRPC(waiter.promise);\n\n    const eventdetail: FormSubmitDetails<DataShape> = {\n      form: this.node,\n      rpchandler: this,\n      submitted: {},\n      errors: [],\n      result: null\n    };\n\n    try {\n      this.__formhandler.submitting = true;\n\n      const submitparameters = await this.buildFormSubmission(extradata, { __setupEvent: eventdetail });\n\n      if (debugFlags.fhv)\n        console.log('[fhv] start submission', submitparameters);\n\n      insubmitrpc = true; //so we can easily determine exception source\n      const result = await this.submitForm(submitparameters);\n      insubmitrpc = false;\n\n      if (debugFlags.fhv)\n        console.log('[fhv] received response', result);\n\n      this._processMessages(result.messages);\n\n      if (!dompack.dispatchCustomEvent(this.node, \"wh:form-response\", { bubbles: true, cancelable: true, detail: result }))\n        return result;\n\n      eventdetail.result = result.result;\n      eventdetail.errors = result.errors;\n\n      let didfirstfocus = false;\n      const globalerrors = [];\n      for (const error of result.errors) {\n        if (!error.name) {\n          globalerrors.push(error);\n          continue;\n        }\n\n        let failednode = this.node.querySelector('[name=\"' + error.name + '\"], [data-wh-form-name=\"' + error.name + '\"]');\n        if (!failednode) {\n          if (error.name === \"__form_captcha\") { //created on demand\n            const serverMetadata = error.metadata as { provider: CaptchaProvider };\n            failednode = setupCaptchaFieldGroup(this, serverMetadata.provider);\n          } else {\n            console.error(\"[fhv] Unable to find node '\" + error.name + \"' which caused error:\" + error.message);\n            continue;\n          }\n        }\n        if (!didfirstfocus) {\n          dompack.focus(failednode);\n          didfirstfocus = true;\n        }\n        setFieldError(failednode, error.message, { reportimmediately: true, serverside: true, metadata: error.metadata });\n      }\n\n      if (result.success) {\n        this.sendFormEvent({ event: 'submitted' });\n        if (dompack.dispatchCustomEvent(this.node, \"wh:form-submitted\", { bubbles: true, cancelable: true, detail: eventdetail as FormSubmitDetails<Record<string, unknown>> })) {\n          merge.run(this.node, { form: await this.getFormValue() });\n\n          //FIXME why is going to 'thank you' not in the formbase?\n          this._navigateToThankYou(result.result && result.result.richvalues);\n          this.onSubmitSuccess(result.result);\n        }\n      } else {\n        const failedfields = result.errors.map(error => error.name || \"*\").sort().join(\" \");\n        this.sendFormEvent({ event: 'failed', errorfields: failedfields, errorsource: 'server' });\n\n        if (globalerrors.length) {\n          if (dompack.dispatchCustomEvent(this.node, \"wh:form-globalerrors\", { bubbles: true, cancelable: true, detail: { globalerrors } }))\n            this.displayGlobalErrors(globalerrors);\n        }\n\n        if (dompack.dispatchCustomEvent(this.node, \"wh:form-failed\", { bubbles: true, cancelable: true, detail: eventdetail }))\n          this.onSubmitFailed(result.errors, result.result);\n      }\n      return pick(result, [\"result\"]);\n    } catch (e) {\n      this.sendFormEvent({ event: 'exception', exception: String(e), errorsource: insubmitrpc ? 'server' : 'client' });\n\n      if (dompack.dispatchCustomEvent(this.node, \"wh:form-exception\", { bubbles: true, cancelable: true, detail: eventdetail }))\n        this.onSubmitException(e as Error);\n\n      throw e;\n    } finally {\n      waiter.resolve();\n      this.__formhandler.submitting = false;\n    }\n  }\n\n  displayGlobalErrors(globalerrors: FormSubmitMessage[]) {\n    try {\n      const errors = globalerrors.map(error => dompack.create(\"p\", { textContent: error.message }));\n      runMessageBox(errors, [{ title: \"OK\" }]); //TODO: language?\n    } catch (e) {\n      console.error(\"runMessageBox failed\", e);\n      // eslint-disable-next-line no-alert -- alert is our fallback without message boxes\n      alert(globalerrors.map(error => error.message).join(\"\\n\"));\n    }\n  }\n\n  //Get the first group that failed error handling\n  getFirstFailedGroup() {\n    return this.node.querySelector(\".wh-form__fieldgroup-error\");\n  }\n\n  //override this to deal with succesful submissions\n  onSubmitSuccess(result: FormSubmitEmbeddedResult<unknown>) {\n    const formpos = this.node.getBoundingClientRect();\n    if (formpos.top < 0)\n      this.node.scrollIntoView({ block: 'start', behavior: 'smooth' });\n\n    if (result && result.resultsguid)\n      this.node.dataset.whFormResultguid = result.resultsguid;\n\n    if (result && result.submitinstruction)\n      navigateTo(result.submitinstruction);\n  }\n\n  //override this to deal with failed submissions\n  onSubmitFailed(errors: FormSubmitMessage[], result: unknown) {\n  }\n\n  //override this to deal with form exceptions\n  onSubmitException(e: Error) {\n  }\n\n  async validateSingleFormField(field: HTMLElement): Promise<boolean> {\n    if (field instanceof HTMLInputElement && field.type === \"email\") { //TODO perhaps move this to webharefields.es ?\n      if (focus.getCurrentlyFocusedElement() === field) { //TODO clearing suggestion on change should probably be generalized\n        if (field.propWhValidationSuggestion) {\n          field.propWhValidationSuggestion = null;\n        }\n      }\n\n      //Just because it's focused doesn't mean we shouldn't validate it\n      const validation = emailvalidation.validateField(this, field);\n      this.pendingrpcs.push(validation);\n      if (!(await validation))\n        return false;\n    }\n    return true;\n  }\n}\n","// Auto-generated language file from /opt/wh/whtree/modules/publisher/js/captcha/__captcha.lang.json\nvar registerTexts = require(\"@webhare/gettid/src/internal\").registerTexts;\nregisterTexts(\"publisher\",\"fr\",{\"site\":{\"captcha\":{\"explain\":\"Merci de cocher la case ci-dessous\",\"title\":\"Vérification\"}}});\nregisterTexts(\"publisher\",\"en\",{\"site\":{\"captcha\":{\"explain\":\"Please check the box below\",\"title\":\"Verification\"}}});\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/fr.xml\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/default.xml\n// Adding dependency: /opt/wh/whtree/modules/publisher/language/default.xml\n","import { getTid } from \"@webhare/gettid\";\nimport \"./__captcha.lang.json\";\n\nexport interface CaptchaProvider {\n  name: string;\n  apikey: string;\n}\n\nexport interface CaptchaSettings {\n  title: string;\n  onResponse: (response: string) => void;\n}\n\nexport interface CaptchaProviderRegistration {\n  initialize: (provider: CaptchaProvider, injectInto: HTMLElement, settings: CaptchaSettings) => Promise<void>;\n}\n\nexport const captcharegistry: Record<string, CaptchaProviderRegistration> = {};\n\n\nexport async function initializeCaptcha(provider: CaptchaProvider, injectInto: HTMLElement, settings?: Partial<CaptchaSettings>): Promise<void> {\n  if (!captcharegistry[provider.name])\n    throw new Error(`Captcha provider '${provider.name}' not registered`);\n  if (!settings?.onResponse)\n    throw new Error(\"onResponse callback is required\");\n\n  const finalsettings: CaptchaSettings = {\n    title: settings?.title ?? getTid(\"publisher:site.captcha.title\"),\n    onResponse: settings?.onResponse ?? (() => { }),\n  };\n\n  await captcharegistry[provider.name].initialize(provider, injectInto, finalsettings);\n}\n","import FormBase from '@mod-publisher/js/forms/rpc';\nimport type { FormConfiguration, FormHandlerFactory } from \"@webhare/forms\";\nimport { dispatchCustomEvent, flagUIBusy, qSA, register } from \"@webhare/dompack\";\nimport { emplace, sleep } from \"@webhare/std\";\nimport { downgradeUploadFields } from \"./domsupport\";\n\nlet formConfiguration: FormConfiguration | undefined;\nlet handlers: Map<string, FormHandlerFactory | PromiseWithResolvers<FormHandlerFactory>> | undefined;\nlet configuredRegistrations: true | undefined;\nconst firstWarningMs = 150, warningIntervalMs = 5000;\n\nasync function scheduleFormSetup(form: HTMLFormElement, factory: FormHandlerFactory) {\n  using lock = flagUIBusy();\n  void (lock);\n\n  //Ensure any custom elements in the form are actually registered or our communication with these elements may fail\n  const customEls = [...new Set(qSA(form, \"[name]\").map(_ => _.tagName.toLowerCase()))].filter(_ => _.includes(\"-\"));\n  if (customEls.length) {\n    const initPromise = Promise.all(customEls.map(_ => customElements.whenDefined(_))).then(() => ({ timeout: false }));\n\n    let nextWarning = Date.now() + firstWarningMs;\n    for (; ;) {\n      const timeoutPromise = sleep(new Date(nextWarning)).then(() => ({ timeout: true }));\n      const result = await Promise.race([initPromise, timeoutPromise]);\n      if (!result.timeout)\n        break;\n\n      const missing = customEls.filter(tag => !customElements.get(tag)).join(\", \");\n      if (missing === 'wh-fileedit') {\n        console.warn(`Developers: we recommend explicitly registering a component for \".wh-form__upload\"`);\n        downgradeUploadFields(form);\n        break;\n      }\n      console.warn(`Still waiting for the following custom elements to be defined in form ${form.id ?? form.dataset.whFormId}:`, missing);\n      nextWarning = Date.now() + warningIntervalMs;\n    }\n  }\n  factory(form);\n}\n\nexport function configureForms(setup: FormConfiguration) {\n  if (!Object.keys(setup).length)\n    return;\n\n  formConfiguration = { ...formConfiguration, ...setup };\n  dispatchCustomEvent(window, \"wh:form-configure\", { bubbles: true, cancelable: false, detail: formConfiguration });\n}\n\nexport function registerHandlers(addHandlers: Record<string, FormHandlerFactory>) {\n  if (!handlers) { //register initial handlers (now that form support is activated)\n    //we want to stop distinguishing between these, not worth the effort/complexity seperating  them\n    const defaultHandler = (form: HTMLFormElement) => new FormBase(form);\n    addHandlers = {\n      \"publisher:form\": defaultHandler,\n      \"publisher:rpc\": defaultHandler,\n      ...addHandlers\n    };\n    handlers = new Map;\n  }\n\n  //Configure the handlers. If there's a resolvable promise waiting for us, resolve it, otherwise directly insert the handler\n  for (const [handlername, handler] of Object.entries(addHandlers))\n    emplace(handlers, handlername, {\n      insert: () => handler,\n      update: current => {\n        if (\"promise\" in current) {\n          current.resolve(handler);\n          return current;\n        } else\n          throw new Error(`Handler '${handlername}' is already registered`);\n      }\n    });\n\n  //Set up a registration for form elements, but ensure they only go through one scheduleFormSetup ever\n  if (!configuredRegistrations) { //register for forms that have yet to appear\n    register<HTMLFormElement>(\"form[data-wh-form-handler]\", form => {\n      //Get the current handler or set up a promise that will receive the handler\n      const handler = emplace(handlers!, form.dataset.whFormHandler!, { insert: () => Promise.withResolvers<FormHandlerFactory>() });\n      if (\"promise\" in handler)\n        void handler.promise.then(factory => scheduleFormSetup(form, factory));\n      else\n        void scheduleFormSetup(form, handler);\n\n    });\n    configuredRegistrations = true;\n  }\n}\n\nexport function registerHandler(handlername: string, handler: FormHandlerFactory) {\n  registerHandlers({ [handlername]: handler });\n}\n\nexport function getFormConfiguration(): FormConfiguration | undefined {\n  return formConfiguration;\n}\n","/* To verify tree shaking viability, try:\n   whcd\n   cd whtree\n   echo 'import \"@webhare/forms\"' | node_modules/.bin/esbuild --loader:.css=empty --tsconfig=tsconfig.json --bundle --minify\n*/\n\n// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/forms\" {\n}\n\nimport FormBase from '@mod-publisher/js/forms/rpc';\nimport { default as LocalFormBase } from \"@mod-publisher/js/forms/formbase\"; //'FormBase', the RPC-ing one, is the one you want 99% of the time. LocalFormBase is for pure local handling (eg a PWA Config screen)\nimport { verifyAddress, type AddressValidationResult, type AddressChecks } from './address';\nimport { FileUploadFormElement as FileEditElement } from \"@mod-publisher/js/forms/fields/upload\";\nimport { ImgEditElement } from \"@mod-publisher/js/forms/fields/imgedit\";\nimport { JSFormElement } from './jsformelement';\nimport type { FormFileValue, FormAnalyticsEvent } from './types';\nimport { getFormHandler, getFormData } from './domsupport';\nimport { configureForms, registerHandlers } from './registration';\n\n/* TODO / NOTES\n  - we cannot move this file into jssdk namespace, the lang.json compiler doesn't accept paths that cannot be translated to a WH resource\n  - lang.json isn't really TS compatible, a nicer followup TS interface would allow something like\n    import myModuleTexts from \"wh:tid/mymodle\";\n    and offer intellisense (after solving the problems like \"what if a module wants to export multiple sets, how to implement HTMLTid and variables, etc\")\n  - so for now we'll hardcode importing form.lang.json so external users don't have to do this, take the treeshaking hit, and plan to move builtin texts\n    to some sort of /.wh/generated/builtin-language-texts system where we load the common builtin texts per language on demand\n*/\nimport \"@mod-publisher/js/forms/internal/form.lang.json\";\nimport { omit } from '@webhare/std';\n\nexport { FormBase, verifyAddress, ImgEditElement, FileEditElement, JSFormElement, getFormHandler, getFormData };\nexport type { FormSubmitResult } from \"@mod-publisher/js/forms/formbase\";\nexport { buildRPCFormSubmission as buildFormSubmission, submitRPCForm as submitForm } from \"@mod-publisher/js/forms/rpc\";\nexport type { RPCFormSubmission as FormSubmission } from \"./types\";\nexport type { AddressValidationResult, AddressChecks, FormFileValue, FormAnalyticsEvent };\nexport { DateField, TimeField } from \"@mod-publisher/js/forms/fields/datetime\";\nexport { registerHandler } from \"./registration\";\nexport { setupGoogleRecaptcha } from \"@mod-publisher/js/captcha/google-recaptcha\";\nexport { setupFriendlyCaptcha } from \"./friendly-captcha\";\nexport { setupValidator } from \"@mod-publisher/js/forms/internal/customvalidation\";\nexport { LocalFormBase };\n\nexport type FormHandlerFactory = (form: HTMLFormElement) => LocalFormBase;\n\nexport type FormConfiguration = {\n  captcha?: \"onLoad\" | \"onActivate\";\n};\n\nexport type FormSetupOptions = FormConfiguration & {\n  handlers: Record<string, FormHandlerFactory>;\n};\n\n/// Initialize all forms we already have the handler for\nexport function setupForms(options?: Partial<FormSetupOptions>) {\n  registerHandlers(options?.handlers ?? {});\n  if (options)\n    configureForms(omit(options, [\"handlers\"]));\n}\n","/* eslint-disable */\n/// @ts-nocheck -- Bulk rename to enable TypeScript validation\n\nimport * as dompack from 'dompack';\nimport KeyboardHandler from \"dompack/extra/keyboard\";\nimport * as datehelpers from \"./datehelpers\";\nimport { getLang } from '@webhare/dompack/src/tree';\n// import \"./datestrings.lang.json\";\n//import { getTid } from \"@webhare/gettid\";\n\n// FIXME work with backend\nconst langcodes =\n{\n  \"nl\": \"am;pm;januari;februari;maart;april;mei;juni;juli;augustus;september;oktober;november;december;maandag;dinsdag;woensdag;donderdag;vrijdag;zaterdag;zondag;jan;feb;mrt;apr;mei;jun;jul;aug;sep;okt;nov;dec;ma;di;wo;do;vr;za;zo\",\n  \"de\": \"am;pm;Januar;Februar;März;April;Mai;Juni;Juli;August;September;Oktober;November;Dezember;Montag;Dienstag;Mittwoch;Donnerstag;Freitag;Samstag;Sonntag;Jan.;Febr.;März;Apr.;Mai;Juni;Juli;Aug.;Sept.;Okt.;Nov.;Dez.;Mo;Di;Mi;Do;Fr;Sa;So\",\n  \"en\": \"am;pm;January;February;March;April;May;June;July;August;September;October;November;December;Monday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday;Jan;Feb;Mar;Apr;May;Jun;Jul;Aug;Sep;Oct;Nov;Dec;Mon;Tue;Wed;Thu;Fri;Sat;Sun\"\n};\n\n//Load any needed localizations yourself: frameworks.mootools.more.locale.nl-nl.date, frameworks.mootools.more.locale.es-es.date, frameworks.mootools.more.locale.de-de.date, frameworks.mootools.more.locale.fr-fr.date\n\n/*\n\nConverting calendar.js code to calendar2.js\n\n    Changed classes\n      - .-wh-calendar-popup   ->   .wh-datepicker > .value\n      - .-wh-calendar-icon    ->   .wh-datepicker > .arrow\n\n    Changed <input> attributes:\n      - data-formatting -> data-format\n      - data-empty -> placeholder\n\n    Load:\n      LOAD: wh.ui.calendar2\n      LOAD: wh.locale.common.de-de.date\n      LOAD: wh.locale.common.en-us.date\n      LOAD: wh.locale.common.nl-nl.date\n\n    Taal instellen:\n      Locale.use(\"de-DE\");\n      Locale.use(\"en-US\");\n      Locale.use(\"nl-NL\");\n*/\n\n\n/////////////////////\n//\n//\n\n//NOTE preparing to sync this with dompack selectlist.es\n\nclass ComponentOverlay {\n  constructor() {\n    this._boundGlobalEvents = null;\n  }\n  _startOverlayDismissCapture() {\n    //set up capturing handlers to kill our pulldowns asap when something else is clicked\n    if (!this._boundGlobalEvents)\n      this._boundGlobalEvents = evt => this._globalEvents(evt);\n\n    if (!dompack.debugflags.meo) {\n      window.addEventListener(\"keyup\", this._boundGlobalEvents, true);\n      window.addEventListener(\"mousedown\", this._boundGlobalEvents, true);\n      window.addEventListener(\"touchstart\", this._boundGlobalEvents, true);\n    }\n  }\n  _endOverlayDismissCapture() {\n    window.removeEventListener(\"keyup\", this._boundGlobalEvents, true);\n    window.removeEventListener(\"mousedown\", this._boundGlobalEvents, true);\n    window.removeEventListener(\"touchstart\", this._boundGlobalEvents, true);\n  }\n  _globalEvents(evt) {\n    if (evt && evt.type === \"keyup\") {\n      if (evt.keyCode === 27)\n        this._dismissOverlay();\n      return;\n    }\n\n    if (!dompack.contains(this._anchornode, evt.target) && !dompack.contains(this._items, evt.target))\n      this._dismissOverlay();\n  }\n}\n\n\n\n//\n//\n////////////////////\n\n\n\n/*\n * $wh.CalendarTable\n * Builds a plain calendar table based on mootools locale settings\n *\n */\n\nclass CalendarTable extends ComponentOverlay {\n  constructor() {\n    super();\n    this.options = {\n      weeknumbers: false,\n      header_weeknr: '', //weeknr.\n      min: null, //minimal date\n      max: null //maximal date (out of range gets disabled class\n    };\n    this.cdate = null;\n    this.showdate = null;\n  }\n\n  _onDayClick(evt) {\n    const clickedday = evt.target.closest(`.${this.options.baseclass}__day--selectable`);\n    // console.error(clickedday, clickedday.dataset.whDatepickerDate);\n    if (!clickedday)\n      return;\n\n    dompack.stop(evt);\n    this._dismissOverlay();\n\n    dompack.changeValue(this._datenode, clickedday.dataset.whDatepickerDate);\n  }\n\n  getTable(showdate, options) {\n    this.options = { ...this.options, options };\n\n    const caltable = dompack.create('table', {\n      className: this.options.baseclass + '__days',\n      on: { click: evt => this._onDayClick(evt) }\n    });\n    const calbody = dompack.create('tbody');\n    caltable.appendChild(calbody);\n\n    //Build week rows\n    const rownode = <tr class={this.options.baseclass + '__weekdays'}></tr>;\n    if (this.options.weeknumbers)\n      rownode.appendChild(<td></td>); //placeholder for upperleft corner\n\n    for (let w = 0; w < 7; ++w) {\n      rownode.appendChild(<th scope=\"column\" class={this.options.baseclass + '__weekday'}><span>{this._languagetexts[w + 33]}</span></th>);\n    }\n    calbody.appendChild(rownode);\n\n    const mindate = this.options.min ? {\n      day: this.options.min.getUTCDay(),\n      month: this.options.min.getUTCMonth(),\n      year: this.options.min.getUTCFullYear()\n    } : null;\n\n    const maxdate = this.options.max ? {\n      day: this.options.max.getUTCDay(),\n      month: this.options.max.getUTCMonth(),\n      year: this.options.max.getUTCFullYear()\n    } : null;\n\n    //What is the weekday for the first day of the selected month ?\n    const startofmonth = datehelpers.makeJSUTCDate({ ...showdate, day: 1 });\n    const showmonth = startofmonth.getUTCMonth();\n    const showyear = startofmonth.getUTCFullYear();\n\n    //    console.log(startofmonth);\n    const startofmonth_weekday = startofmonth.getUTCDay(); //0-6 where 0=Sunday\n\n    //Work backwards to a monday (start of the week)\n    const backwardsdays = startofmonth_weekday === 0 ? 6 : startofmonth_weekday - 1;\n    let currentgriddate = startofmonth.getTime() - (backwardsdays * 86400 * 1000);\n\n    //Build the grid!\n    for (let week = 0; week < 6; ++week) {\n      const rownode = dompack.create('tr', { className: this.options.baseclass + '__week' });\n\n      for (let day = 0; day < 7; ++day) {\n        const date = new Date(currentgriddate);\n        if (this.options.weeknumbers && day === 0)\n          rownode.appendChild(<th class={this.options.baseclass + '__weeknr'} scope=\"row\"><span>{datehelpers.getWeekNumber(date)}</span></th>);\n\n        const dateY = date.getUTCFullYear();\n        const dateM = date.getUTCMonth();\n        const dateD = date.getUTCDate();\n\n        const celldate = { year: dateY, month: dateM + 1, day: dateD };\n\n        const dayclass = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'][day];\n        const daynode = dompack.create('td', {\n          className: `${this.options.baseclass}__day ${this.options.baseclass}__day--${dayclass}`,\n          childNodes: [dompack.create(\"span\", { textContent: date.getUTCDate() })],\n          dataset: { whDatepickerDate: datehelpers.formatJSUTCISODate(date) }\n        });\n\n        if (dateM !== showmonth || dateY !== showyear)\n          daynode.classList.add(this.options.baseclass + '__day--othermonth');\n\n        if ((mindate && dateY < mindate.year && dateM < mindate.month && dateD < mindate.day)\n          || (maxdate && dateY > maxdate.year && dateM > maxdate.month && dateD > maxdate.day)) {\n          daynode.classList.add(this.options.baseclass + '__day--disabled');\n        } else {\n          daynode.setAttribute(\"tabindex\", \"0\");\n          daynode.classList.add(this.options.baseclass + '__day--selectable');\n        }\n\n        if (datehelpers.compareDate(this.today, celldate) === 0)\n          daynode.classList.add(this.options.baseclass + '__day--today');\n\n        if (this.date && datehelpers.compareDate(this.date, celldate) === 0)\n          daynode.classList.add(this.options.baseclass + '__day--selected');\n\n        rownode.appendChild(daynode);\n        currentgriddate += 86400 * 1000;\n      }\n      calbody.appendChild(rownode);\n    }\n\n    return caltable;\n  }\n}\n\nclass Calendar2 extends CalendarTable {\n  constructor(options) {\n    super();\n    this.options = {\n      weeknumbers: false,\n      date: null,   // initial value\n      min: null,\n      max: null,\n      ...options\n    };\n    this.node = null;\n    this.tablenode = null;\n    this.yearspinner = null;\n    this.monthselectnode = null;\n    this.date = null; //selected date\n    this.keys = null;\n    this.focusednode = null;\n  }\n\n  _onYearMonthChange(evt) {\n    this.options.date = {\n      year: this.yearspinner.value,\n      month: this.monthselectnode.value,\n      day: this._currentdate ? this._currentdate.day : 1\n    };\n\n    this._currentdate.month = parseInt(this.monthselectnode.value);\n    this._currentdate.year = parseInt(this.yearspinner.value);\n\n    this.setMonthTable(this.options.date);\n  }\n\n  readDateNode() {\n    this.mindate = datehelpers.parseISODate(this._datenode.min, { nofail: true });\n    this.maxdate = datehelpers.parseISODate(this._datenode.max, { nofail: true });\n    this.date = datehelpers.parseISODate(this._datenode.value, { nofail: true });\n    const suggestion = datehelpers.parseISODate(this._datenode.dataset.suggestion, { nofail: true });\n    const max = datehelpers.parseISODate(this._datenode.max);\n    this.today = datehelpers.getLocalToday();\n\n    this.yearspinner.min = this.mindate ? this.mindate.year : 1901;\n    this.yearspinner.max = this.maxdate ? this.maxdate.year : 2099;\n\n    let showdate = this.date ?? suggestion ?? this.today;\n    if (this.mindate && datehelpers.makeJSUTCDate(showdate) < datehelpers.makeJSUTCDate(this.mindate))\n      showdate = this.mindate;\n    if (this.maxdate && datehelpers.makeJSUTCDate(showdate) > datehelpers.makeJSUTCDate(this.maxdate))\n      showdate = this.maxdate;\n\n    if (!this._currentdate)\n      this._currentdate = showdate;\n\n    this.setMonthTable(showdate);\n  }\n\n  _addMeToNode(container) {\n    this.node = container;\n\n    this.yearspinner = <input type=\"number\" class={`${this.options.baseclass}__yearselect`} step=\"1\" on={{ change: evt => this._onYearMonthChange(evt) }} />;\n    this.monthselectnode = <select class={`${this.options.baseclass}__monthselect`} on={{ change: evt => this._onYearMonthChange(evt) }} />;\n\n    this.readDateNode();\n\n    //build calendar interface:\n    const headernode = <div class={this.options.baseclass + \"__header\"}>\n      <div class={this.options.baseclass + \"__previous\"} onClick={evt => this.changeMonth(evt, -1)} />\n      {this.monthselectnode}\n      {this.yearspinner}\n      <div class={this.options.baseclass + \"__next\"} onClick={evt => this.changeMonth(evt, +1)} />\n    </div>;\n\n    //month pulldown\n    const selectedmonth = this._currentdate.month;\n    for (let m = 0; m < 12; ++m)\n      this.monthselectnode.appendChild(<option value={m + 1} selected={m === selectedmonth - 1}>{this._languagetexts[m + 2]}</option>);\n\n    this.node.append(headernode, this.tablenode);//, btnbarnode);\n\n    //looks like we're visible ! install a capturing\n    new KeyboardHandler(this.node, {\n      \"Enter\": ev => this.onKeyEnter(ev)\n    }\n      , { captureunsafekeys: true }\n    );\n\n    // Locale.addEvent(\"change\", this.onLanguageChange.bind(this));\n    this._startOverlayDismissCapture();\n    this._onYearMonthChange();\n  }\n\n  setMonthTable(showdate) {\n    this.yearspinner.value = showdate.year;\n    this.monthselectnode.value = showdate.month;\n\n    const newtable = this.getTable(showdate);\n\n    if (this.tablenode)\n      this.tablenode.replaceWith(newtable);\n    this.tablenode = newtable;\n\n    this.setFocus();\n  }\n\n  setFocus() {\n    if (!this.tablenode.clientWidth)\n      return;//Not (yet) visible\n\n    //Set focus on showdate or else first selectable date\n    let fnode;\n    if (this.date)\n      fnode = this.tablenode.querySelector(\"td[data-wh-datepicker-date='\" + datehelpers.formatISODate(this.date.year, this.date.month, this.date.day) + \"']\");\n    if (!fnode) //else pick first selectable day\n      fnode = this.tablenode.querySelector(\".\" + this.options.baseclass + '__day--selectable');\n    if (fnode)\n      fnode.focus();\n  }\n\n  onKeyEnter(ev) {\n    const daynode = ev.target.closest(\".\" + this.options.baseclass + '__day--selectable');\n    if (!daynode)\n      return;\n\n    this._onDayClick(ev);\n  }\n\n  _dismissOverlay() {\n    this.node.remove();\n    this._endOverlayDismissCapture();\n    this._owner.__closedDatepicker();\n  }\n\n  changeMonth(evt, direction) {\n    dompack.stop(evt);\n\n    let newyear = parseInt(this.yearspinner.value);\n    let newmonth = parseInt(this.monthselectnode.value) + direction;\n\n    if (newmonth > 12 || newmonth < 1) //wrap it\n    {\n      newyear += direction;\n      newmonth = direction > 0 ? 1 : 12;\n    }\n    this.setMonthTable({ year: newyear, month: newmonth });\n  }\n}\n\nclass DatePicker extends Calendar2 {\n  /** options.baseclass Base class to use for the elements in the date picker. Defaults to 'datepicker' */\n  constructor(owner) {\n    super({ ...owner.options, baseclass: owner._baseclass + '__picker' });\n    this._owner = owner;\n    this._datenode = owner._replacednode;\n    this.options = {\n      ...this.options,\n      language: null\n    };\n    //TODO limit by supportedlanguages and use gettid(\"~locale.datetimestrings\")\n    if (!this.options.language)\n      this.options.language = getLang().language;\n\n    this._languagetexts = (langcodes[this.options.language] || langcodes.en).split(';');\n\n    //we use the node to store our result, so verify it\n    //FIXME maybe this should be optional and you be allowed to create a datepicker without a corresponding node if you just manage getvalue/setvalue yourself, or maybe this glue code belongs outside us\n    //     if(node.nodeName !== 'INPUT' || node.getAttribute('type') !== 'date')\n    //       throw new Error(\"The DatePicker expects to be associated with a input[type=date]\");\n\n    //     this._node = node;\n    //     this._class = (options ? options.baseclass : '') || 'datepicker';\n    //     this._node.classList.add(this._class + \"--attached\");\n    // //\n    // this._node.addEventListener(\"wh:datepicker-request\");\n\n    this._anchornode = this._datenode.nextSibling;\n\n    this._calendarnode = dompack.create('div', { className: this.options.baseclass }); //tabindex:0 ?\n    this._addMeToNode(this._calendarnode);\n\n    this._items = this._calendarnode; //TODO bit ugly but keeps us compatible with selectlist.es\n\n    this._calendarnode.addEventListener(\"change\", ev => {\n      console.log(ev);\n    });\n\n    //Allow users to hook into the datepicker\n    dompack.dispatchCustomEvent(this._datenode, \"wh:datepicker-built\", { bubbles: true, cancelable: false, detail: { input: this._datenode, datepicker: this._calendarnode } });\n\n    //ADDME can we borrow positioning code from the dompack pulldown?\n    //for now, attach to bottom\n    document.body.appendChild(this._calendarnode);\n    const calendarnodesize = this._calendarnode.getBoundingClientRect();\n    const anchornode = this._anchornode.getBoundingClientRect();\n\n    //fits left aligned?\n    if (anchornode.left + calendarnodesize.width > window.innerWidth) { //doesn't fit left aligned, we must right align\n      this._calendarnode.style.right = '0px';\n    } else //left align\n    {\n      this._calendarnode.style.left = Math.ceil(anchornode.left) + 'px';\n    }\n\n    //fits top aligned?\n    if (anchornode.top + calendarnodesize.height > window.innerHeight) { //doesn't fit below, send above\n      let y = (window.innerHeight - anchornode.top);\n      if ((window.innerHeight - y) - calendarnodesize.height < 0) //Prevent calendar hiding behind top of window\n        y = window.innerHeight - calendarnodesize.height;\n      this._calendarnode.style.bottom = y + 'px';\n    } else //left align\n    {\n      this._calendarnode.style.top = Math.ceil(anchornode.bottom) + 'px';\n    }\n\n    this.setFocus();\n  }\n}\n\nexport default DatePicker;\n","import * as dompack from '@webhare/dompack';\nimport { type CaptchaProvider, type CaptchaSettings, captcharegistry } from \"@mod-publisher/js/captcha/api\";\n\n//recaptcha API: https://developers.google.com/recaptcha/docs/display\nlet recaptchaload: PromiseWithResolvers<void> | undefined;\n\ntype RecaptchaOptions = { language?: string };\nlet recaptchaOptions: RecaptchaOptions | undefined;\n\ndeclare global {\n  interface Window {\n    $wh__ongooglerecaptchaloaded: () => void;\n    grecaptcha: {\n      render: (node: HTMLElement, options: { sitekey: string; callback: () => void }) => string;\n      getResponse: (id: string) => string;\n    };\n  }\n}\n\nwindow.$wh__ongooglerecaptchaloaded = function () {\n  recaptchaload!.resolve();\n};\n\nfunction makeRecaptchaLoadPromise() {\n  recaptchaload = Promise.withResolvers<void>();\n  document.querySelector<HTMLElement>(\"head,body\")!.append(<script src=\"https://www.google.com/recaptcha/api.js?onload=$wh__ongooglerecaptchaloaded&amp;render=explicit\" />);\n  return recaptchaload.promise;\n}\n\nexport async function runRecaptcha(provider: CaptchaProvider, injectInto: HTMLElement, settings: CaptchaSettings) {\n  const lock = dompack.flagUIBusy({ modal: true });\n  try {\n    await (recaptchaload ? recaptchaload.promise : makeRecaptchaLoadPromise());\n\n    const captchanode = <div class=\"wh-captcha__googlerecaptchaholder\"></div>;\n    injectInto.append(captchanode);\n\n    if (provider.apikey === 'mock') {\n      captchanode.appendChild(<label class=\"wh-captcha__mock\"><input type=\"checkbox\" on={{ click: () => settings.onResponse('mock') }} />I am a human, beep-bop</label>);\n    } else {\n      const recaptchaid = window.grecaptcha.render(captchanode, {\n        sitekey: provider.apikey,\n        ...recaptchaOptions?.language ? { hl: recaptchaOptions.language } : {},\n        callback: () => {\n          const response = window.grecaptcha ? window.grecaptcha.getResponse(recaptchaid) : '';\n          settings.onResponse(response);\n        }\n      });\n    }\n  } finally {\n    lock.release();\n  }\n}\n\n\n/** Setup Google reCAPTCHA rendering\n * @param options Optional settings, currently supports:\n *  - language: The language code to use for the reCAPTCHA widget. See https://developers.google.com/recaptcha/docs/language for supported language codes\n */\nexport function setupGoogleRecaptcha(options?: RecaptchaOptions) {\n  if (captcharegistry[\"google-recaptcha\"])\n    throw new Error(\"Duplicate google recaptcha initialization\");\n\n  recaptchaOptions = { ...recaptchaOptions, ...options };\n  captcharegistry[\"google-recaptcha\"] = { initialize: runRecaptcha };\n}\n","import * as dompack from '@webhare/dompack';\nimport { initializeCaptcha, type CaptchaProvider } from \"@mod-publisher/js/captcha/api\";\nimport { setFieldError, type SetFieldErrorData } from '../internal/customvalidation';\n\nimport \"../../captcha/__captcha.lang.json\"; //TODO or have forms send this tid (so it can also be overridden there)\nimport { JSFormElement } from '@webhare/forms';\nimport { getTid } from '@webhare/gettid';\nimport type RPCFormBase from '../rpc';\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"wh-captcha\": CaptchaField;\n  }\n}\n\nexport default class CaptchaField extends JSFormElement<string> {\n  value = '';\n  provider: CaptchaProvider | null = null;\n\n  constructor() {\n    super();\n    this.addEventListener('wh:form-setfielderror', evt => void this._setFieldError(evt));\n    this.whFormsApiChecker = () => this.check();\n\n    const form = this.closest('form');\n    if (form)\n      form.addEventListener('reset', () => this.onReset());\n  }\n\n  check(): void {\n    if (!this.value)\n      setFieldError(this, getTid(\"publisher:site.forms.commonerrors.required\"), { reportimmediately: false });\n    else\n      setFieldError(this, \"\", { reportimmediately: false });\n  }\n\n  setup(provider: CaptchaProvider) {\n    if (this.provider)\n      throw new Error(\"CaptchaField is already setup\");\n\n    this.provider = provider;\n    this.initialize();\n  }\n\n  private initialize() {\n    this.value = '';\n    this.replaceChildren();\n    void initializeCaptcha(this.provider!, this, {\n      onResponse: (result: string) => { this.value = result; }\n    });\n  }\n\n  private onReset() {\n    void this.initialize();\n  }\n\n  async _setFieldError(evt: CustomEvent<SetFieldErrorData>) {\n    dompack.stop(evt);\n    if (!evt.detail.error) //error cleared\n      return;\n\n    if (this.value) { //we were already sending a response!\n      console.log(\"Captcha response was rejected, resetting\");\n      this.onReset(); //better restart the control, timeout or duplicate submission\n    }\n  }\n}\n\nexport function setupCaptchaFieldGroup(form: RPCFormBase<object>, provider: CaptchaProvider): CaptchaField {\n  /* Setup a page-less holder for the captcha field\n\n    <div class=\"wh-form__page wh-form__page--visible\">\n      <div class=\"wh-form__fieldgroup\" data-wh-form-group-for=\"__form_captcha\">\n        ...\n    */\n\n  const captchaControl = dompack.create(\"wh-captcha\", { class: \"wh-form__captcha\", dataset: { whFormName: \"__form_captcha\", whFormRequired: \"true\" } });\n\n  const virtualCaptchaPage = dompack.create(\"div\", { class: \"wh-form__captchapage\" }, [\n    dompack.create(\"div\", { class: \"wh-form__fieldgroup\", dataset: { whFormGroupFor: \"__form_captcha\" } }, [\n      dompack.create(\"label\", { class: \"wh-form__label\" }, [getTid(\"publisher:site.captcha.title\")]),\n      dompack.create(\"div\", { class: \"wh-form__fields\" },\n        [dompack.create(\"div\", { class: \"wh-form__fieldline\" }, [captchaControl])]\n      )\n    ])\n  ]);\n\n  //Position it before the navbuttons, but if they are missing for whatever reason, just add to the end of the form\n  const buttonarea = dompack.qS(form.node, \".wh-form__navbuttons\");\n  if (buttonarea)\n    buttonarea.before(virtualCaptchaPage);\n  else\n    form.node.appendChild(virtualCaptchaPage);\n\n  void captchaControl.setup(provider);\n\n  return captchaControl;\n}\n\n\ncustomElements.define(\"wh-captcha\", CaptchaField);\n","/* PLEASE NOTE - including @mod-publisher/js/forms is considered including the 'legacy form api'. It comes\n   without tree shaking support and autoregisters forms\n\n   @webhare/forms provides a tree-shakable implementation (but requires more setup). To switch please see dev module forms.ts\n  setupForms();\n*/\n\nimport './internal/requiredstyles.css';\nimport * as merge from './internal/merge';\nimport { setFieldError, setupValidator } from './internal/customvalidation';\nimport FormBase, { type FormSubmitEmbeddedResult } from './formbase';\nimport RPCFormBase from './rpc';\nimport { setupForms, registerHandler } from '@webhare/forms';\nimport { isLive } from '@webhare/env';\nimport { setupFormAnalytics } from '@webhare/frontend/src/pxl';\n\nexport { FormBase, RPCFormBase, setFieldError, setupValidator, type FormSubmitEmbeddedResult };\n\nexport const registerMergeFormatter = merge.registerFormatter;\n\ntype LegacyFormHandlerFactory = (form: HTMLFormElement) => FormBase;\n\nfunction legacyRegisterFormHandler(handlername: string, handler: LegacyFormHandlerFactory) {\n  registerHandler(handlername, (form: HTMLFormElement) => {\n    const createdForm = handler(form);\n    if (!isLive && createdForm instanceof FormBase && !(createdForm instanceof RPCFormBase)) {\n      console.warn(`Form handler for '${handlername}' is deriving from @mod-publisher/js/forms#FormBase - it should derive from RPCFormBase (In WH5.7+, the FormBase exported by @webhare/forms will *be* the RPCFormBase)`);\n    }\n    return createdForm as RPCFormBase;\n  });\n}\n\n/** @deprecated setup() is no longer needed */\nexport function setup(options: unknown) {\n}\n\n// We explicitly bind the 'publisher:form' forms to FormBase. The modern version doesn't distinguish between these anymore (and we want to move away from that difference anyawy, RPCBase isn't that much different)\nsetupForms({\n  handlers: { \"publisher:form\": form => new FormBase(form) as RPCFormBase }\n});\n\n// We assume if you're importing @mod-publisher/js/forms you don't know about having to do setupFormAnalytics to keep analytics in WH 5.7+\nsetupFormAnalytics();\n\nexport { legacyRegisterFormHandler as registerHandler };\n","import * as dompack from \"@webhare/dompack\";\nimport { setFieldError } from '@mod-publisher/js/forms';\nimport { JSFormElement } from \"@webhare/forms\";\n\nexport type datepartsType = { year: number; month: number; day: number };\n\nexport default class KSKDateParts extends JSFormElement<datepartsType | null> {\n\n  daterec: datepartsType | null = null;\n  yearnode: HTMLInputElement;\n  monthnode: HTMLSelectElement;\n  daynode: HTMLSelectElement;\n\n  constructor() {\n    super();\n    this.whFormsApiChecker = () => this._check();\n    this.whUseFormGetValue = true;\n\n    this.yearnode = dompack.qR(this, \".wh-form__kskdateparts__year\") as HTMLInputElement;\n    this.monthnode = dompack.qR(this, \".wh-form__kskdateparts__month\") as HTMLSelectElement;\n    this.daynode = dompack.qR(this, \".wh-form__kskdateparts__day\") as HTMLSelectElement;\n  }\n\n  get value() {\n    this.daterec = {\n      year: parseInt(this.yearnode.value),\n      month: parseInt(this.monthnode.value),\n      day: parseInt(this.daynode.value)\n    } as datepartsType;\n\n    return this.daterec;\n  }\n\n  set value(value: datepartsType | null) {\n    this.daterec = value;\n    this.yearnode.value = this.daterec && this.daterec.year > 0 ? String(this.daterec.year) : \"\"; // Input: Make sure placeholder is shown when empty (not '0')\n    this.monthnode.value = this.daterec && this.daterec.month > 0 ? String(this.daterec.month) : \"0\"; // Select: show first 'placeholder' option\n    this.daynode.value = this.daterec && this.daterec.day > 0 ? String(this.daterec.day) : \"0\"; // Select: show first 'placeholder' option\n  }\n\n  _check() {\n    if (!this.daterec)\n      return;\n\n    if (this.daterec.month < 0 || this.daterec.month > 12) {\n      setFieldError(this, \"Invalid month\", { reportimmediately: false });\n      return;\n    }\n\n    if (this.daterec.day === 0 || this.daterec.month === 0)\n      return;\n\n    let daysinmonth = [1, 3, 5, 7, 8, 10, 12].includes(this.daterec.month) ? 31 : 30;\n    if (this.daterec.month === 2)\n      daysinmonth = this.daterec.year > 0 ? new Date(this.daterec.year, this.daterec.month, 0).getDate() : 29;\n\n    if (this.daterec.day < 0 || this.daterec.day > daysinmonth)\n      setFieldError(this, \"Invalid day selected\", { reportimmediately: false });\n  }\n}\n","\nimport {\n  getTid as getTidFromJSSDK,\n  getTidLanguage,\n  setTidLanguage,\n  getHTMLTid,\n} from \"@webhare/gettid\";\nimport { registerTexts } from \"@webhare/gettid/src/internal\";\n\n// Fill nodes with a data-texttid attribute with the translated text\nfunction convertElementTids(scope = document.body) {\n  // Only available in a DOM context and if the DOM is ready\n  if (typeof document === \"undefined\" || !scope)\n    return;\n  Array.from(scope.querySelectorAll(\"*[data-texttid]\")).forEach(function (node) {\n    node.textContent = getTid(node.getAttribute(\"data-texttid\") || \"\");\n  });\n}\n\n// If this script is run within a DOM context, convert data-texttid attributes automatically\nif (typeof document !== \"undefined\")\n  document.addEventListener(\"DOMContentLoaded\", () => convertElementTids());\n\nconst getTid = ((...args: Parameters<typeof getTidFromJSSDK>): string => getTidFromJSSDK(...args)) as typeof getTidFromJSSDK & {\n  tidLanguage: string;\n  html: typeof getHTMLTid;\n};\n\n// Define 'tidLanguage' as a property on the main export (so you can use getTid.tidLanguage)\nObject.defineProperty(getTid, \"tidLanguage\", { get: getTidLanguage, set: setTidLanguage });\n// Define 'html' as a method on the main export (so you can use getTid.html)\ngetTid.html = getHTMLTid;\n\n// Export getTid as the default function, explicitly export getTid, getHTMLTid and registerTexts as well\nexport {\n  getTid as default,\n  getTid,\n  getTidLanguage,\n  setTidLanguage,\n  getHTMLTid,\n  convertElementTids,\n  registerTexts\n};\n","import * as dompack from '../../index';\nimport * as dialogapi from '../../api/dialog';\n\ninterface DialogOptions extends dialogapi.DialogOptions {\n  theme?: string;\n}\n\nexport class BasicDialog extends dialogapi.DialogBase {\n  private _dialogclass: string;\n  holdernode: Element;\n  modalitynode: Element;\n\n  constructor(classname: string, options?: DialogOptions) {\n    super(options);\n    this._dialogclass = classname;\n\n    this.contentnode = dompack.create('div', { className: this._dialogclass });\n    this.holdernode = dompack.create('div',\n      {\n        className: this._dialogclass + \"__holder\",\n        childNodes: [this.contentnode]\n      });\n    this.modalitynode = dompack.create('div',\n      {\n        className: this._dialogclass + \"__modalbg\",\n        childNodes: [this.holdernode],\n        on: {\n          click: (evt: MouseEvent) => this._onModalityClick(evt),\n          wheel: (evt: WheelEvent) => dompack.stop(evt) //prevent scrolling modal-covered site using mousewheel\n        }\n      });\n\n    if (options?.theme)\n      this.modalitynode.classList.add(options.theme);\n  }\n\n  _openDialog() {\n    document.body.appendChild(this.modalitynode);\n  }\n\n  closeDialog() {\n    this.modalitynode.remove();\n    super.closeDialog();\n  }\n\n  _onModalityClick(evt: MouseEvent) {\n    if (this.holdernode.contains(evt.target as Node))\n      return; //event was targetted at our holder\n\n    dompack.stop(evt);\n    if (this.options.allowcancel)\n      this.resolve(null);\n  }\n\n  afterShow() {\n    dompack.registerMissed(this.holdernode);\n  }\n}\n\nexport function createDialog(classname: string, options?: DialogOptions) {\n  return new BasicDialog(classname, options);\n}\n","import './dialog.scss';\nimport * as dompack from \"@webhare/dompack\";\nimport { getTid } from \"@mod-tollium/js/gettid\";\nimport * as dialog from 'dompack/components/dialog';\nimport * as dialogapi from 'dompack/api/dialog';\n\nexport class kiskeyaDialog extends dialog.BasicDialog {\n  scrolly: number;\n\n  constructor(options: dialogapi.DialogOptions | undefined) {\n    super('kiskeya-dialog', options);\n\n    if (options && options.allowcancel)\n      this.holdernode.appendChild(<button type=\"button\" aria-label={getTid('kiskeya:frontend.registrationapp.common.close')} class=\"dialog__close\"><i class=\"fal fa-times\" aria-hidden=\"true\" /></button>);\n\n    this.scrolly = document.documentElement.scrollTop;\n    document.documentElement.classList.add(\"hidescroll\");\n\n    dompack.registerMissed(this.holdernode);\n\n    setTimeout(() => {\n      void (this.holdernode.clientWidth);\n      dompack.dispatchCustomEvent(this.holdernode, \"kiskeya:refreshcontent\", { bubbles: true, cancelable: false });\n    }, 310);\n\n    this.holdernode.addEventListener('click', ev => this.onClick(ev));\n  }\n\n  onClick(ev: Event) {\n    if (!ev.target)\n      return;\n\n    if ((ev.target as HTMLElement).closest(\".dialog__close,[data-action='close']\")) { //a close button\n      dompack.stop(ev);\n      this.resolve(\"close\");\n    }\n  }\n\n  closeDialog() {\n    super.closeDialog();\n\n    document.documentElement.classList.remove(\"hidescroll\");\n    document.documentElement.scrollTop = this.scrolly;\n  }\n\n  afterShow() {\n    //  if (this.contentnode && !dompack.qS(this.contentnode, \".styledscrollbar-y\"))\n    //    this.contentnode.classList.add(\"styledscrollbar-y\");\n\n    void (this.holdernode.clientWidth);//force css reflow\n    this.holdernode.classList.add(\"kiskeya-dialog__holder--aftershow\");\n\n    dompack.registerMissed(this.holdernode);\n  }\n}\n\ndialogapi.setupDialogs(options => new kiskeyaDialog(options));\n\nexport async function confirmDialog(title: string, text: string | HTMLElement, isWarning: boolean = false) {\n  const dlgobj = dialogapi.createDialog({ allowcancel: true });\n\n  const contentnode = <div class=\"confirmdialog\">\n    <div class=\"confirmdialog__header\">\n      <h3>{title}</h3>\n      {typeof text === \"string\" ? <p>{text}</p> : text}\n    </div>\n    <div class=\"confirmdialog__buttons confirmdialog__buttons--center\">\n      <button data-action=\"close\" type=\"button\" class=\"button button--outline button--blue\">\n        <span class=\"button__label\">{isWarning ? getTid('kiskeya:frontend.registrationapp.common.close') : getTid('kiskeya:frontend.registrationapp.common.no')}</span>\n      </button>\n      {!isWarning ?\n        <button data-action=\"yes\" type=\"button\" class=\"button\">\n          <span class=\"button__label\">{getTid('kiskeya:frontend.registrationapp.common.yes')}</span>\n        </button> : null}\n    </div>\n  </div>;\n\n  dlgobj.contentnode?.appendChild(contentnode);\n\n  contentnode.addEventListener(\"click\", (ev: MouseEvent) => {\n    const dialogbtn = (ev.target as HTMLElement).closest(\"button\");\n    if (dialogbtn) {\n      dompack.stop(ev);\n      dlgobj.resolve(dialogbtn.dataset.action ?? null);\n    }\n  });\n\n  return await dlgobj.runModal();\n}\n\nexport function showSavedMessage(failed: boolean = false) {\n  const node = <div class={\"savedmessage\" + (failed ? \" savedmessage--failed\" : \"\")}>{failed ? getTid('kiskeya:frontend.registrationapp.common.failed') : getTid('kiskeya:frontend.registrationapp.common.saved')}</div>;\n  document.body.appendChild(node);\n  void (node.clientWidth);\n  node.classList.add(\"savedmessage--show\");\n\n  setTimeout(() => {\n    node.classList.remove(\"savedmessage--show\");\n    setTimeout(() => node.parentNode.removeChild(node), 300);\n  }, failed ? 800 : 500);\n}\n","import * as dompack from \"@webhare/dompack\";\nimport UploadField from '@mod-publisher/js/forms/fields/upload';\nimport ImgEditField, { ImgEditElement } from '@mod-publisher/js/forms/fields/imgedit';\nimport KSKDateParts from '@mod-kiskeya/formcomponents/dateparts/';\nimport '@mod-publisher/js/forms/themes/neutral';\nimport './forms.scss';\nimport './datetime.scss';\nimport './buttons.scss';\nimport './dialog';\nimport './pagination.scss';\n\ndompack.register(\".wh-form__upload\", node => new UploadField(node));\ndompack.register(\".wh-form__imgedit\", node => new ImgEditField(node));\nImgEditElement.setTexts({\n  explainUpload:\n    document.documentElement.lang.startsWith('fr') ? \"Glissez et deposez l'image ici ou cliquez pour telecharger\"\n      : document.documentElement.lang.startsWith('nl') ? \"Sleep en zet afbeelding hier neer of klik om te uploaden\"\n        : \"Drag and drop image here or click to upload\"\n});\n\ncustomElements.define(\"ksk-dateparts\", KSKDateParts);\n\n// arrayedit accessibility fixes. Set aria-hidden on hidden input and convert span into buttons + add title/label attributes\ndompack.register(\"input.wh-form__arrayinput\", node => node.setAttribute(\"aria-hidden\", \"true\"));\n\ndompack.register(\"span.wh-form__arraydelete, span.wh-form__arrayadd\", node => {\n  const title = node.classList.contains(\"wh-form__arraydelete\") ? \"Delete\" : \"Add\";\n  const btn = <button type=\"button\" class={node.className} title={title} aria-label={title} />;\n  node.after(btn);\n  node.parentNode?.removeChild(node);\n});\n\n//Open links in option labels in new window\ndompack.register(\".wh-form .wh-form__optionlabel a\", node => node.setAttribute(\"target\", \"_blank\"));\n\ndompack.register(\".wh-form\", form => {\n  //Some additional button styling\n  dompack.qSA(form, \".wh-form__button--submit:not(.button),.wh-form__button--next:not(.button)\").forEach(btn => {\n    const txt = btn.textContent;\n    const labelnode = btn.querySelector(\".wh-form__buttonlabel\"); // Needed to keep css class(es) used in form api\n    btn.replaceChildren();\n    btn.append(<span class={(labelnode ? labelnode.className : \"\") + \" button__label\"}>{txt}</span>, <i class=\"button__icon far fa-angle-right\"></i>);\n  });\n\n  dompack.qSA(form, \".wh-form__button--previous:not(.button)\").forEach(btn => {\n    const txt = btn.textContent;\n    const labelnode = btn.querySelector(\".wh-form__buttonlabel\"); // Needed to keep css class(es) used in form api\n    btn.replaceChildren();\n    btn.classList.add(\"button--outline\");\n    btn.append(<i class=\"button__icon far fa-angle-left\"></i>, <span class={(labelnode ? labelnode.className : \"\") + \" button__label\"}>{txt}</span>);\n  });\n});\n\n//Styled (native) pulldown: add wrapper around select element + arrow for css-styling\ndompack.register(\".wh-styledinput select\", selectnode => {\n  let wrappernode = (selectnode.closest(\".wh-form__pulldown-styled\") as HTMLElement);\n  if (!wrappernode) { //if not already has styling wrapper, add..\n    wrappernode = <div class=\"wh-form__pulldown-styled\" />;\n    if (selectnode?.parentNode)\n      selectnode.parentNode.insertBefore(wrappernode, selectnode);\n    wrappernode.appendChild(selectnode);\n    wrappernode.appendChild(<span class=\"arrow far fa-angle-down\" />);\n  }\n\n  if (MutationObserver) {\n    if ((selectnode as HTMLSelectElement).disabled)\n      wrappernode.classList.add(\"wh-form__pulldown-styled--disabled\");\n    new MutationObserver(function () {\n      wrappernode.classList.toggle(\"wh-form__pulldown-styled--disabled\", (selectnode as HTMLSelectElement).disabled);\n    }).observe(selectnode, { subtree: false, attributes: true, characterData: false });\n  }\n});\n","import \"./login.scss\";\nimport { RPCFormBase, registerHandler } from '@mod-publisher/js/forms';\nimport * as dialogapi from 'dompack/api/dialog';\nimport * as dompack from \"@webhare/dompack\";\nimport type { FormSubmitEmbeddedResult } from \"@mod-publisher/js/forms/formbase\";\n\nexport type loginType = { email: string; fullname: string; publickey: string; guid: string } | null;\n\nexport async function showForgotPasswordDialog() {\n  const template = document.getElementById(\"forgotpasswordtemplate\") as HTMLTemplateElement;\n  if (!template)\n    return;\n\n  const resetform = dompack.qR(template.content, \"#forgotpasswordform\")?.cloneNode(true);\n\n  const resetdialog = dialogapi.createDialog({ allowcancel: true });\n  resetdialog.contentnode?.appendChild(resetform);\n  await resetdialog.runModal();\n}\n\nclass loginForm extends RPCFormBase {\n  constructor(node: HTMLFormElement) {\n    super(node);\n  }\n\n  onSubmitSuccess(result: FormSubmitEmbeddedResult) {\n    if (result as loginType) {\n      this.reset();\n      localStorage.setItem(\"kiskeya:registrationapp\", JSON.stringify(result));\n      dompack.dispatchCustomEvent(this.node, \"kiskeya:login\", { bubbles: true, cancelable: false });\n    }\n  }\n}\n\nregisterHandler(\"kiskeya:loginform\", node => new loginForm(node));\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n    return (idbProxyableTypes ||\n        (idbProxyableTypes = [\n            IDBDatabase,\n            IDBObjectStore,\n            IDBIndex,\n            IDBCursor,\n            IDBTransaction,\n        ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n    return (cursorAdvanceMethods ||\n        (cursorAdvanceMethods = [\n            IDBCursor.prototype.advance,\n            IDBCursor.prototype.continue,\n            IDBCursor.prototype.continuePrimaryKey,\n        ]));\n}\nconst transactionDoneMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n    const promise = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            request.removeEventListener('success', success);\n            request.removeEventListener('error', error);\n        };\n        const success = () => {\n            resolve(wrap(request.result));\n            unlisten();\n        };\n        const error = () => {\n            reject(request.error);\n            unlisten();\n        };\n        request.addEventListener('success', success);\n        request.addEventListener('error', error);\n    });\n    // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n    // is because we create many promises from a single IDBRequest.\n    reverseTransformCache.set(promise, request);\n    return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n    // Early bail if we've already created a done promise for this transaction.\n    if (transactionDoneMap.has(tx))\n        return;\n    const done = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            tx.removeEventListener('complete', complete);\n            tx.removeEventListener('error', error);\n            tx.removeEventListener('abort', error);\n        };\n        const complete = () => {\n            resolve();\n            unlisten();\n        };\n        const error = () => {\n            reject(tx.error || new DOMException('AbortError', 'AbortError'));\n            unlisten();\n        };\n        tx.addEventListener('complete', complete);\n        tx.addEventListener('error', error);\n        tx.addEventListener('abort', error);\n    });\n    // Cache it for later retrieval.\n    transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n    get(target, prop, receiver) {\n        if (target instanceof IDBTransaction) {\n            // Special handling for transaction.done.\n            if (prop === 'done')\n                return transactionDoneMap.get(target);\n            // Make tx.store return the only store in the transaction, or undefined if there are many.\n            if (prop === 'store') {\n                return receiver.objectStoreNames[1]\n                    ? undefined\n                    : receiver.objectStore(receiver.objectStoreNames[0]);\n            }\n        }\n        // Else transform whatever we get back.\n        return wrap(target[prop]);\n    },\n    set(target, prop, value) {\n        target[prop] = value;\n        return true;\n    },\n    has(target, prop) {\n        if (target instanceof IDBTransaction &&\n            (prop === 'done' || prop === 'store')) {\n            return true;\n        }\n        return prop in target;\n    },\n};\nfunction replaceTraps(callback) {\n    idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n    // Due to expected object equality (which is enforced by the caching in `wrap`), we\n    // only create one new func per func.\n    // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n    // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n    // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n    // with real promises, so each advance methods returns a new promise for the cursor object, or\n    // undefined if the end of the cursor has been reached.\n    if (getCursorAdvanceMethods().includes(func)) {\n        return function (...args) {\n            // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n            // the original object.\n            func.apply(unwrap(this), args);\n            return wrap(this.request);\n        };\n    }\n    return function (...args) {\n        // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n        // the original object.\n        return wrap(func.apply(unwrap(this), args));\n    };\n}\nfunction transformCachableValue(value) {\n    if (typeof value === 'function')\n        return wrapFunction(value);\n    // This doesn't return, it just creates a 'done' promise for the transaction,\n    // which is later returned for transaction.done (see idbObjectHandler).\n    if (value instanceof IDBTransaction)\n        cacheDonePromiseForTransaction(value);\n    if (instanceOfAny(value, getIdbProxyableTypes()))\n        return new Proxy(value, idbProxyTraps);\n    // Return the same value back if we're not going to transform it.\n    return value;\n}\nfunction wrap(value) {\n    // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n    // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n    if (value instanceof IDBRequest)\n        return promisifyRequest(value);\n    // If we've already transformed this value before, reuse the transformed value.\n    // This is faster, but it also provides object equality.\n    if (transformCache.has(value))\n        return transformCache.get(value);\n    const newValue = transformCachableValue(value);\n    // Not all types are transformed.\n    // These may be primitive types, so they can't be WeakMap keys.\n    if (newValue !== value) {\n        transformCache.set(value, newValue);\n        reverseTransformCache.set(newValue, value);\n    }\n    return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n    const request = indexedDB.open(name, version);\n    const openPromise = wrap(request);\n    if (upgrade) {\n        request.addEventListener('upgradeneeded', (event) => {\n            upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n        });\n    }\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event.newVersion, event));\n    }\n    openPromise\n        .then((db) => {\n        if (terminated)\n            db.addEventListener('close', () => terminated());\n        if (blocking) {\n            db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n        }\n    })\n        .catch(() => { });\n    return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n    const request = indexedDB.deleteDatabase(name);\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event));\n    }\n    return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n    if (!(target instanceof IDBDatabase &&\n        !(prop in target) &&\n        typeof prop === 'string')) {\n        return;\n    }\n    if (cachedMethods.get(prop))\n        return cachedMethods.get(prop);\n    const targetFuncName = prop.replace(/FromIndex$/, '');\n    const useIndex = prop !== targetFuncName;\n    const isWrite = writeMethods.includes(targetFuncName);\n    if (\n    // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n    !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n        !(isWrite || readMethods.includes(targetFuncName))) {\n        return;\n    }\n    const method = async function (storeName, ...args) {\n        // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n        const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n        let target = tx.store;\n        if (useIndex)\n            target = target.index(args.shift());\n        // Must reject if op rejects.\n        // If it's a write operation, must reject if tx.done rejects.\n        // Must reject with op rejection first.\n        // Must resolve with op value.\n        // Must handle both promises (no unhandled rejections)\n        return (await Promise.all([\n            target[targetFuncName](...args),\n            isWrite && tx.done,\n        ]))[0];\n    };\n    cachedMethods.set(prop, method);\n    return method;\n}\nreplaceTraps((oldTraps) => ({\n    ...oldTraps,\n    get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n    has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nconst advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];\nconst methodMap = {};\nconst advanceResults = new WeakMap();\nconst ittrProxiedCursorToOriginalProxy = new WeakMap();\nconst cursorIteratorTraps = {\n    get(target, prop) {\n        if (!advanceMethodProps.includes(prop))\n            return target[prop];\n        let cachedFunc = methodMap[prop];\n        if (!cachedFunc) {\n            cachedFunc = methodMap[prop] = function (...args) {\n                advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));\n            };\n        }\n        return cachedFunc;\n    },\n};\nasync function* iterate(...args) {\n    // tslint:disable-next-line:no-this-assignment\n    let cursor = this;\n    if (!(cursor instanceof IDBCursor)) {\n        cursor = await cursor.openCursor(...args);\n    }\n    if (!cursor)\n        return;\n    cursor = cursor;\n    const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);\n    ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);\n    // Map this double-proxy back to the original, so other cursor methods work.\n    reverseTransformCache.set(proxiedCursor, unwrap(cursor));\n    while (cursor) {\n        yield proxiedCursor;\n        // If one of the advancing methods was not called, call continue().\n        cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());\n        advanceResults.delete(proxiedCursor);\n    }\n}\nfunction isIteratorProp(target, prop) {\n    return ((prop === Symbol.asyncIterator &&\n        instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||\n        (prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore])));\n}\nreplaceTraps((oldTraps) => ({\n    ...oldTraps,\n    get(target, prop, receiver) {\n        if (isIteratorProp(target, prop))\n            return iterate;\n        return oldTraps.get(target, prop, receiver);\n    },\n    has(target, prop) {\n        return isIteratorProp(target, prop) || oldTraps.has(target, prop);\n    },\n}));\n\nexport { deleteDB, openDB, unwrap, wrap };\n","import \"./editregistration.scss\";\nimport { FormBase, registerHandler } from '@mod-publisher/js/forms';\nimport * as dompack from \"@webhare/dompack\";\nimport { getFileAsDataURL } from \"@webhare/upload\";\nimport { openDB, DBSchema, IDBPDatabase } from 'idb';\nimport { createClient } from \"@webhare/jsonrpc-client\";\nimport { getTid } from \"@mod-tollium/js/gettid\";\nimport { confirmDialog, showSavedMessage } from \"../../shared/forms/dialog\";\nimport * as dialogapi from 'dompack/api/dialog';\nimport { throwError, generateRandomId, toCamelCase, ToSnakeCase, toSnakeCase } from \"@webhare/std\";\nimport { encryptFormResult } from \"@mod-kiskeya/js/crypto\";\n\nasync function fetchAsFile(url: string, options?: { name?: string; overrideContentType?: string }): Promise<uploadFileType> {\n  const fetchresult = await fetch(url);\n  if (!fetchresult.ok)\n    throw new Error(`Failed to fetch ${url}: ${fetchresult.statusText}`);\n\n  const filename = options?.name ? options.name : \"file.dat\";\n\n  return {\n    file: new File([await fetchresult.blob()], filename, { type: options?.overrideContentType || fetchresult.headers.get(\"Content-Type\") || \"application/octet-stream\" }),\n    fileName: filename,\n    link: \"\"\n  };\n}\n\nlet __myprofileform: MyProfileRegistrationForm;\nlet __adopteeprofileform: AdopteeRegistrationForm;\nlet __wrdProfileform: MyProfileRegistrationForm;\nlet __wrdAdopteeprofileform: AdopteeRegistrationForm;\n/*\n  idb: see\n  https://www.npmjs.com/package/idb#typescript\n*/\n\ninterface ExportStatus {\n  status: string;\n  success: boolean;\n}\ninterface ExportRequestRes {\n  newuids: string[];\n  importeduids: string[];\n  success: boolean;\n  status: string;\n}\n\ninterface RPCService {\n  ExportRegistration(guid: string, //PWA User guid\n    language: string,\n    uid: string, // local uid\n    data: string\n  ): Promise<ExportStatus>;\n  ExportRequest(guid: string,\n    uids: string[],\n    language: string\n  ): Promise<ExportRequestRes>;\n  GetMyRegistration(guid: string,\n    profileguid: string,\n    language: string): Promise<ToSnakeCase<MyProfileTypeStorage>>;\n  GetAdoptee(guid: string,\n    profileguid: string,\n    language: string): Promise<ToSnakeCase<AdopteeTypeStorage>>;\n  UpdateRegistration(guid: string,\n    profileguid: string,\n    data: ToSnakeCase<MyProfileTypeStorage> | ToSnakeCase<AdopteeTypeStorage>,\n    language: string): Promise<ExportStatus>;\n}\n\ntype datepartsType = { year: number; month: number; day: number };\n\ntype RelativeType = {\n  formrowid: number;\n  relationtype: number;\n  relationOther: string;\n  wrdId: number;\n  wrdFirstname: string;\n  wrdLastname: string;\n  relDateofbirth: datepartsType;\n};\n\ntype AddressType = {\n  city: string;\n  country: string;\n  state: string;\n  street: string;\n  zip: string;\n  nrDetail?: string;\n  houseNumber?: string;\n};\n\ntype MyProfileType = {\n  uid: string; // local uid or wrd_id if wrd form\n  allowmailcontact: boolean;\n  birthCity: string;\n  dateofbirth: datepartsType;\n  department: number;\n  familyDescription: string;\n  familyOtherinfo: string;\n  image: uploadFileType[];\n  relationtype: number;\n  relationOther: string;\n  relatives: RelativeType[];\n  wrdContactAddress: AddressType;\n  wrdContactEmail: string;\n  wrdContactPhone: string;\n  referenceperson: string;\n  wrdFirstname: string;\n  wrdLastname: string;\n};\n\ntype MyProfileTypeStorage = Omit<MyProfileType, \"image\"> & {\n  image: string;\n  imageFilename: string;\n};\n\n\ntype AdopteeType = {\n  uid: string;\n  wrdGender: number;\n  hasbirthcertificate: boolean;\n  birthcertificate: uploadFileType[];\n  wrdFirstname: string;\n  wrdLastname: string;\n  dateofbirth: datepartsType;\n  birthCity: string;\n  department: number;\n  documentsdescription: string;\n  adoptionLocation: string;\n  adoptionInstitutehtName: string;\n  adoptionInstitutehtPlace: string;\n  adoptionInstitutehtContact: string;\n  cause: string;\n  photos: PhotoType[];\n};\n\ntype uploadFileType = {\n  file: File;\n  fileName: string;\n  link: string;\n};\n\ntype PhotoType = {\n  formrowid: number;\n  image: uploadFileType[];\n  description: string;\n};\n\ntype PhotoTypeStorage = {\n  formrowid: number;\n  image: string;\n  image_filename: string;\n  description: string;\n};\n\ntype AdopteeTypeStorage = Omit<AdopteeType, \"photos\" | \"birthcertificate\"> & {\n  photos: PhotoTypeStorage[];\n  birthcertificate: string;\n  birthcertificateFilename: string;\n};\n\ntype ExportType = {\n  uid: string;\n  name: string;\n  data: string;\n};\n\ninterface KiskeyaRegDB extends DBSchema {\n  myprofile: {\n    key: string;\n    value: MyProfileTypeStorage;\n  };\n  adoptee: {\n    key: string;\n    value: AdopteeTypeStorage;\n  };\n  export: {\n    key: string;\n    value: ExportType;\n  };\n}\n\nexport async function saveAndComplete() {\n  const hasdata = await __myprofileform.checkForStoredData();\n  if (!hasdata)\n    return;\n\n  const res = await confirmDialog(getTid('kiskeya:frontend.registrationapp.editregistration.storeandecrypt') + \"?\", getTid('kiskeya:frontend.registrationapp.editregistration.storeandecrypt-sure'));\n  if (res === \"yes\") {\n    await __myprofileform.finalizeAndEncypt();\n    location.hash = \"#startpage\"; // redirect to startpage\n  }\n\n  return;\n}\n\nexport async function syncRegistrations() {\n  const keys = await __myprofileform.getExportKeys();\n  if (!keys || keys.length === 0)\n    return;\n\n  const dlgobj = dialogapi.createDialog({ allowcancel: true });\n\n  const btn = <button type=\"button\" class=\"button button--blue\" tabindex=\"0\">\n    <span class=\"button__label\">{getTid('kiskeya:frontend.registrationapp.common.start')}</span>\n    <i class=\"button__icon far fa-cloud-upload\" aria-hidden=\"true\"></i>\n  </button>;\n\n  const contentnode = <div class=\"confirmdialog\">\n    <div class=\"confirmdialog__header\">\n      <h3>{getTid('kiskeya:frontend.registrationapp.editregistration.startsync')}</h3>\n      <p>\n        {getTid('kiskeya:frontend.registrationapp.exportcount', String(keys.length))}<br />\n      </p>\n      {btn}\n    </div>\n  </div>;\n\n  dlgobj.contentnode?.appendChild(contentnode);\n\n  btn.addEventListener(\"click\", (ev: MouseEvent) => {\n    dlgobj.resolve(null);\n\n    const mysettings = getUserSettings();\n    if (mysettings && mysettings.guid)\n      void __myprofileform.exportRegistrations(mysettings.guid);\n  });\n\n  return await dlgobj.runModal();\n}\n\nfunction getUserSettings() {\n  let mysettings;\n  try {\n    mysettings = JSON.parse(localStorage.getItem(\"kiskeya:registrationapp\") as string);\n  } catch (err) {\n    console.error(\"Error parsing settings\", err);\n  }\n\n  return mysettings;\n}\n\nexport function addSearchPerson() {\n  const template = document.getElementById(\"editregistration__person-template\") as HTMLTemplateElement;\n  if (!template)\n    return;\n\n  const personrow = dompack.qS(template.content, \".editregistration__person\")?.cloneNode(true) as HTMLElement;\n  if (!personrow)\n    return;\n\n  dompack.qSA(\"#editregistration .editregistration__searchpersons\").forEach(container => {\n    const lines = dompack.qSA(container, \".editregistration__person\");\n    lines.sort((a, b) => { return Number(a.dataset.id) - Number(b.dataset.id); });\n\n    const id = lines.length > 0 ? Number(lines[lines.length - 1].dataset.id) + 1 : 1;\n    personrow.dataset.id = String(id);\n\n    const editbtn = dompack.qS(personrow, \".editregistration__person__edit\") as HTMLAnchorElement;\n    if (editbtn)\n      editbtn.href = \"#editregistration.adopteeprofile:\" + personrow.dataset.id;\n\n    container.appendChild(personrow);\n  });\n}\n\nexport async function deleteSearchPerson(btn: HTMLButtonElement) {\n  const row = btn.closest(\".editregistration__person[data-id]\") as HTMLElement;\n  if (row) {\n    const name = dompack.qR(row, \".editregistration__person__name\")?.textContent;\n    const res = await confirmDialog(getTid('kiskeya:frontend.registrationapp.editregistration.deleteprofile'), getTid('kiskeya:frontend.registrationapp.editregistration.areyousuredeleteprofile', name));\n    if (res === \"yes\") {\n      row.parentNode?.removeChild(row);\n\n      const id = row.dataset.id;\n      if (id) {// remove entry from registration data\n        if (id.startsWith(\"wrd:\"))\n          void __wrdAdopteeprofileform.deleteAdoptee(id);\n        else\n          void __adopteeprofileform.deleteAdoptee(id);\n      }\n    }\n  }\n}\n\nexport function saveMyProfileForm() {\n  if (__myprofileform.dirty)\n    void __myprofileform.saveData();\n}\n\nexport function saveAdopteeForm() {\n  if (__adopteeprofileform.dirty)\n    void __adopteeprofileform.saveData();\n}\n\nexport function preparePersonalForm(regid: string) { // Only used for wrd form\n  __wrdProfileform.preparePersonalForm(regid);\n}\n\nexport function prepareAdopteeForm(regid: string) {\n  if (regid.startsWith(\"wrd:\"))\n    __wrdAdopteeprofileform.prepareAdopteeForm(regid);\n  else\n    __adopteeprofileform.prepareAdopteeForm(regid);\n}\n\nclass RegistrationForm extends FormBase {\n  db: IDBPDatabase<KiskeyaRegDB> | null = null;\n  pages: HTMLElement[];\n  activepage: number = 0;\n  pagination: HTMLElement[] = [];\n  dirty: boolean = false;\n  language: string = \"fr\";\n  isWrdForm: boolean = false;\n  constructor(node: HTMLFormElement, formname: string) {\n    super(node);\n\n    this.isWrdForm = this.node.dataset.storage === \"wrd\";\n    this.language = document.documentElement.lang ? document.documentElement.lang.split(\"-\")[0] : \"en\";\n    this.pages = dompack.qSA(this.node, \".wh-form__page\");\n\n    if (!this.isWrdForm)\n      void this.initDb(formname);\n    this.setupPagination();\n\n    this.node.addEventListener(\"change\", () => this.setDirty());\n  }\n\n  async finalizeAndEncypt() { // Only for local registration\n    const myprofile = await this.db?.get('myprofile', \"myprofile\");\n    if (!myprofile)\n      return;\n\n    const searchpersons = await this.db?.getAll('adoptee');\n\n    const encrypteddata = await encryptFormResult(getUserSettings().publickey, toSnakeCase({ ...myprofile, searchpersons }));\n    if (!encrypteddata)\n      return;\n\n    const now = new Date().toISOString();\n    await this.db?.put('export', {\n      uid: myprofile.uid,\n      data: encrypteddata,\n      name: myprofile.wrdFirstname + \" \" + myprofile.wrdLastname\n    }, now);\n\n    void __myprofileform.resetAll(); // if ready, empty current forms, use current datetime as key\n  }\n\n  setDirty() {\n    this.dirty = true;\n  }\n\n  clearDirty() {\n    this.dirty = false;\n  }\n\n  async checkForStoredData() { // Only for local registration\n    let hasdata = false;\n\n    const profiledata = await this.db?.get('myprofile', \"myprofile\");\n\n    hasdata = Boolean(profiledata && (profiledata.wrdFirstname + profiledata.wrdLastname));\n    document.documentElement.classList.toggle(\"hasmyprofile\", hasdata);\n\n    // First/last name is required!\n    if (!hasdata && !profiledata?.wrdFirstname && !profiledata?.wrdLastname)\n      hasdata = false;\n\n    if (hasdata) {\n      const keys = await this.db?.getAllKeys('adoptee');\n      hasdata = Boolean(keys && keys.length > 0);\n\n      document.documentElement.classList.toggle(\"hasadopteeprofile\", hasdata);\n    }\n\n    return hasdata;\n  }\n\n  async initDb(formname: string) {\n    this.db = await openDB<KiskeyaRegDB>('kiskeya-registration', 1, {\n      upgrade(db) {\n        db.createObjectStore('myprofile');\n        db.createObjectStore('adoptee');\n        db.createObjectStore('export');\n      },\n    });\n\n    if (!this.isWrdForm) { //if local registration get/prefill localy stored data\n      void this.prefillForm();\n      void this.checkForStoredData();\n      void this.updateExportCounter();\n    }\n  }\n\n  setupPagination() {\n    if (this.pages.length < 3) //If just 2 pages (form and finish page) then ignore\n      return;\n\n    let i = 0;\n    this.activepage = 0;\n    const paginationcontainer = <ul class=\"wh-form__pagination\" />;\n    for (const node of this.pages) {\n      if (node.classList.contains(\"wh-form__page--visible\"))\n        this.activepage = i;\n      const item = <li title={node.dataset.title}>{i === this.pages.length - 1 ? <span class=\"fal fa-flag-checkered\"></span> : <span>{i + 1}</span>}</li>;\n      paginationcontainer.appendChild(item);\n      this.pagination.push(item);\n      ++i;\n    }\n\n    this.node.classList.add(\"withpagination\");\n    paginationcontainer.addEventListener(\"click\", (ev: Event) => this.onPaginationClick(ev.target as HTMLElement));\n    this.pagination[this.activepage].classList.add(\"active\");\n\n    this.node.prepend(paginationcontainer);\n    this.node.addEventListener(\"wh:form-pagechange\", (ev: Event) => this.onPageChange(ev.target as HTMLElement));\n  }\n\n  async onPaginationClick(target: HTMLElement) {\n    const curpage = this.pages[this.activepage];\n    if (!curpage || curpage.dataset.whFormPagerole === \"thankyou\")\n      return;\n\n    const item = target.closest(\"li\");\n    if (!item || item.classList.contains(\"active\"))\n      return;\n\n    for (let i = 0; i < this.pagination.length; ++i) {\n      if (this.pagination[i] === item) {\n        // First validate current page\n        const validationstatus = await this.validate(this.pages[this.activepage]);\n        if (!validationstatus.valid)\n          return;\n\n        if (item.classList.contains(\"previous\"))\n          void this.gotoPage(i); //previous page(s)\n        else if (i < this.pagination.length - 1)\n          void this.gotoPage(i);//next page(s)\n        else //Last page\n          void this.gotoPage(i);\n\n        return;\n      }\n    }\n  }\n\n  onPageChange(page: HTMLElement) {\n    if (!this.pagination.length)\n      return;\n\n    let idx = this.activepage;\n    let i = 0;\n    let isprevious = true;\n    for (const node of this.pages) {\n      if (node === page) {\n        idx = i;\n        this.pagination[i].classList.add(\"active\");\n        this.pagination[i].classList.remove(\"previous\");\n        isprevious = false;\n      } else {\n        this.pagination[i].classList.remove(\"active\");\n        if (isprevious)\n          this.pagination[i].classList.add(\"previous\");\n        else\n          this.pagination[i].classList.remove(\"previous\");\n      }\n\n      ++i;\n    }\n\n    this.activepage = idx;\n\n    if (this.isWrdForm && this.activepage < this.pages.length - 1)\n      void this.validate(); // No submit if is wrd form, just validate, wrd form will when clicking on save button or on final page\n    else if (this.dirty) // Watch out! Only after form is prefilled, otherwise it will submit empty form\n      void this.validateAndSubmit(null); // Always try to submit the form with each page change\n  }\n\n  async getExportKeys() {\n    return await this.db?.getAllKeys('export');\n  }\n\n  async updateExportCounter() {\n\n    const myregblock = dompack.qR(\".myregistrations-stored\");\n    const myreglistnode = dompack.qR(myregblock, \".myregistrations-stored__list\");\n    myreglistnode.replaceChildren();\n\n    const keys = await this.getExportKeys();\n    const keycount = keys ? keys.length : 0;\n\n    myregblock.hidden = keycount === 0;\n\n    dompack.qSA(\".header__export\").forEach(node => {\n      node.hidden = keycount === 0;\n      document.documentElement.classList.toggle(\"hasexportdata\", keycount > 0);\n      node.setAttribute(\"title\", getTid('kiskeya:frontend.registrationapp.exportcount', String(keycount)));\n      node.dataset.count = keycount ? String(keycount) : \"\";\n    });\n\n    if (keys) {\n      for (const key of keys) {\n        const rec = await this.db?.get('export', key);\n        const name = rec?.name || \"\";\n\n        if (dompack.qS(myreglistnode, \"li[data-key='\" + key + \"']\"))\n          continue;\n\n        const d = new Date(key);\n        myreglistnode.appendChild(<li data-key={key}>{String(d.toLocaleString()) + ' - ' + name}</li>);\n      }\n    }\n\n    dompack.qSA(\".startpage__sync\").forEach(_ => _.hidden = keycount === 0);\n  }\n\n  async exportRegistrations(guid: string) {\n    // Just read/send export one at a time\n    let keys = await this.getExportKeys();\n    if (!keys)\n      return;\n\n    // Show dialog with counter\n    const dlgobj = dialogapi.createDialog({ allowcancel: false });\n\n    const btn = <button type=\"button\" class=\"button button--blue\" tabindex=\"0\">\n      <span class=\"button__label\">{getTid('kiskeya:frontend.registrationapp.common.abort')}</span>\n    </button>;\n\n    btn.addEventListener(\"click\", (ev: MouseEvent) => {\n      dlgobj.resolve(null);\n      active = false;\n    });\n\n    const indicator = <div class=\"syncdialog__progress\">{\"0/\" + String(keys.length)}</div>;\n\n    const contentnode = <div class=\"syncdialog\">\n      <i class=\"syncdialog__spinner far fa-sync fa-spin\" title=\"sync...\"></i>\n      {indicator}\n      {btn}\n    </div>;\n\n    dlgobj.contentnode?.appendChild(contentnode);\n\n    let active = true;\n    const services = createClient<RPCService>(\"kiskeya:kiskeya_service\");\n\n    const exportkeys = [];\n    for (const key of keys) {\n      const e = await this.db?.get('export', key);\n      if (e)\n        exportkeys.push({\n          uid: e.uid,\n          key\n        });\n    }\n\n    // First send set if uid's to check if they are aleady exported\n    const uids = exportkeys.map(_ => _.uid);\n    let syncreq = null;\n    try {\n      syncreq = await services.ExportRequest(guid, uids, this.language);\n    } catch (err) {\n      console.error(err);\n      return;\n    }\n    // console.log(syncreq);\n    if (syncreq && syncreq.success && syncreq.importeduids.length > 0) { // Cleanup old entries incase already exported\n      for (let i = 0; i < exportkeys.length; ++i) {\n        if (syncreq.importeduids.includes(exportkeys[i].uid))\n          await this.db?.delete('export', exportkeys[i].key);\n      }\n      keys = keys.filter(_ => !syncreq.importeduids.includes(_));\n      await this.updateExportCounter();\n    } else if (syncreq.status !== \"\") {\n      void confirmDialog(getTid('kiskeya:frontend.registrationapp.common.error'), syncreq.status, true);\n      return;\n    }\n\n    dlgobj.afterShow = async () => {\n      let i = 0;\n      for (const key of keys) {\n        if (!active)\n          break;\n        ++i;\n        const data = await this.db?.get('export', key);\n        if (data) {\n          let res = null;\n          try {\n            res = await services.ExportRegistration(guid, this.language, data.uid, data.data);\n          } catch (err) {\n            console.error(err);\n          }\n\n          if (res && res.success) {// Remove localy stored data on success\n            await this.db?.delete('export', key);\n            await this.updateExportCounter();\n          } else {\n            console.error(\"Export failed\", res);\n          }\n\n          indicator.textContent = i + \"/\" + String(keys.length);\n        }\n\n        if (i === keys.length)\n          setTimeout(() => dlgobj.resolve(null), 500);\n      }\n    };\n\n    await dlgobj.runModal();\n  }\n\n  async prefillForm(regid?: string) {\n    //Overwrite this method to prefill the form\n  }\n}\n\nclass MyProfileRegistrationForm extends RegistrationForm {\n  uid: string = \"\";\n  formhandler: FormBase<MyProfileType>;\n  constructor(node: HTMLFormElement) {\n    super(node, \"myprofile\");\n\n    this.formhandler = FormBase.getForNode<MyProfileType>(this.node) ?? throwError(\"No formhandler\");\n\n    document.addEventListener(\"kiskeya:logout\", () => void this.resetAll());\n  }\n\n  async resetAll() {\n    const keys = await this.db?.getAllKeys('adoptee');\n    if (!keys)\n      return;\n\n    await this.db?.clear('myprofile');\n    await this.db?.clear('adoptee');\n    this.uid = \"\";\n\n    void this.checkForStoredData();\n\n    this.updateGlobalLabels();\n    dompack.qSA(\"#editregistration .editregistration__searchpersons\").forEach(container => container.replaceChildren());\n\n    this.reset();\n    this.clearDirty();\n    this.data.relatives = []; // Workaround: arrayedit relatives\n    this.data.wrdContactEmail = \"info@plankiskeya.com\";\n    this.data.allowmailcontact = true; // Initial allow\n\n    void this.gotoPage(0);\n\n    // Workaround: reset image\n    this.data.image = [];\n  }\n\n  preparePersonalForm(profileguid: string) {\n    this.reset(); // First reset the form\n    this.clearDirty();\n    void this.prefillForm(profileguid);\n  }\n\n  async prefillForm(profileguid?: string) {\n    const lock = dompack.flagUIBusy({ modal: true });\n\n    let data: MyProfileType | null = null;\n    if (this.isWrdForm) {\n      if (profileguid) { // load wrd data by rpc\n        const mysettings = getUserSettings();\n        const services = createClient<RPCService>(\"kiskeya:kiskeya_service\");\n        let rpcData = null;\n        try {\n          rpcData = toCamelCase(await services.GetMyRegistration(mysettings.guid, profileguid, this.language));\n        } catch (err) {\n          console.error(err);\n        }\n\n        if (rpcData) {\n          data = {\n            ...rpcData,\n            image: rpcData.image ? [await fetchAsFile(rpcData.image, { name: rpcData.imageFilename })] : []\n          };\n        }\n\n      }\n    } else if (this.db) {\n      const localData = await this.db.get('myprofile', \"myprofile\");\n      if (localData)\n        data = {\n          ...localData,\n          image: localData.image ? [await fetchAsFile(localData.image, { name: localData.imageFilename })] : []\n        };\n      else\n        this.data.allowmailcontact = true; // Initial allow\n    }\n\n    lock.release();\n\n    if (data) {\n      this.uid = data.uid; // Only set uid if data is loaded\n      if (this.formhandler)\n        this.formhandler.assign(data, { ignoreUnknownFields: true });\n\n      if (!this.isWrdForm)\n        this.updateGlobalLabels(data); // Only used for local registration\n\n      this.clearDirty();\n      void this.gotoPage(0);\n    }\n  }\n\n  updateGlobalLabels(data?: { wrdFirstname: string; wrdLastname: string }) {\n    // Prefill fullname\n    const fullname = data ? (data.wrdFirstname + \" \" + data.wrdLastname).trim() : \"\";\n    dompack.qSA(\"#editregistration [data-prefill='fullname']\").forEach(node => node.textContent = fullname);\n\n    //Also check for export data\n    void this.updateExportCounter();\n  }\n\n  async getParsedFormValue() {\n    //const formval = await this.getFormValue();\n    const formval = this.formhandler?.data as MyProfileType;\n    if (!formval)\n      return null;\n\n    const parseddata: MyProfileTypeStorage = { ...formval, image: \"\", imageFilename: \"\" };\n\n    // convert image to dataurl\n    if (formval.image && formval.image.length && formval.image[0].file instanceof File && formval.image[0].file.type.startsWith(\"image\")) {\n      parseddata.image = await getFileAsDataURL(formval.image[0].file);\n      parseddata.imageFilename = formval.image[0].fileName;\n    }\n\n    return parseddata;\n  }\n\n  async saveData() {\n    const formval = await this.getParsedFormValue();\n    if (!formval)\n      return;\n\n    if (this.isWrdForm) {\n      if (this.uid.startsWith(\"wrd:\")) { // update wrd data by rpc\n        const lock = dompack.flagUIBusy({ modal: true });\n\n        const hsFormVal = toSnakeCase(formval);\n        if (hsFormVal.wrd_contact_address) {\n          hsFormVal.wrd_contact_address.nr_detail = hsFormVal.wrd_contact_address.house_number;\n          delete hsFormVal.wrd_contact_address?.house_number;\n        }\n        const mysettings = getUserSettings();\n        const services = createClient<RPCService>(\"kiskeya:kiskeya_service\");\n\n        let res = null;\n        try {\n          res = await services.UpdateRegistration(mysettings.guid, this.uid, hsFormVal, this.language);\n        } catch (err) {\n          console.error(err);\n        }\n\n        lock.release();\n\n        if (res && res.success) {\n          showSavedMessage();\n        } else {\n          showSavedMessage(true);\n          if (res)\n            console.error(\"saveData\", res);\n        }\n      }\n    } else {\n      if (this.db) {\n        if (!this.uid)\n          this.uid = generateRandomId();\n        await this.db.put('myprofile', { ...formval, uid: this.uid }, 'myprofile'); // Note last parameter is the key, for myprofile this is always 'myprofile'\n        showSavedMessage();\n      } else {\n        showSavedMessage(true);\n        console.error(\"saveData\", \"No db\");\n      }\n      this.updateGlobalLabels({ wrdFirstname: formval.wrdFirstname, wrdLastname: formval.wrdLastname });\n      void this.checkForStoredData();\n    }\n\n    this.clearDirty();\n  }\n\n  async submit() {\n    await this.saveData();\n    return {};\n  }\n}\n\nclass AdopteeRegistrationForm extends RegistrationForm {\n  regid: string = \"\";\n  uid: string = \"\";\n  formhandler: FormBase<AdopteeType> | null;\n  constructor(node: HTMLFormElement) {\n    super(node, \"adopteeprofile\");\n\n    this.formhandler = FormBase.getForNode<AdopteeType>(this.node);\n\n    document.addEventListener(\"kiskeya:logout\", () => {\n      this.reset();\n      this.clearDirty();\n    });\n  }\n\n  prepareAdopteeForm(regid: string) {\n    if (!regid)\n      return;\n\n    this.reset(); // First reset the form\n    this.clearDirty();\n    this.data.birthcertificate = []; // Workaround: birthcertificate (image uploads)\n    this.data.photos = []; // Workaround: arrayedit photos\n    void this.gotoPage(0);\n\n    void this.prefillForm(regid);\n  }\n\n  async prefillForm(regid: string) {\n    this.regid = regid;\n    if (regid)\n      await this.getDataForAdoptee(regid, true);\n\n    if (!this.isWrdForm)\n      void this.updateGlobalLabels(); // Only for local registration\n  }\n\n  async deleteAdoptee(id: string) {\n    if (this.isWrdForm) {\n      //Note: No delete adoptee if wrd form\n    } else {\n      await this.db?.delete('adoptee', 'adoptee' + id);\n      void this.checkForStoredData();\n    }\n  }\n\n  async getDataForAdoptee(regid: string, prefill = false) {\n    const lock = prefill ? dompack.flagUIBusy({ modal: true }) : null;\n\n    let data: AdopteeTypeStorage | null = null;\n\n    if (this.isWrdForm) {// load wrd data by rpc\n      const mysettings = getUserSettings();\n      const services = createClient<RPCService>(\"kiskeya:kiskeya_service\");\n      try {\n        data = toCamelCase(await services.GetAdoptee(mysettings.guid, regid, this.language));\n      } catch (err) {\n        console.error(err);\n      }\n    } else if (this.db) {\n      const localData = await this.db?.get('adoptee', \"adoptee\" + regid);\n      if (localData)\n        data = localData;\n    }\n\n    if (prefill && this.formhandler && data) {\n      const photos: PhotoType[] = [];\n      for (let i = 0; i < data.photos.length; ++i) {\n        const image = data.photos[i].image ? await fetchAsFile(data.photos[i].image, { name: data.photos[i].image_filename }) : null;\n        if (image)\n          photos.push({\n            formrowid: i,\n            image: [image],\n            description: data.photos[i].description\n          } as PhotoType);\n      }\n\n      this.formhandler.assign({\n        ...data,\n        birthcertificate: data.birthcertificate && data.hasbirthcertificate ? [await fetchAsFile(data.birthcertificate, { name: data.birthcertificateFilename })] : [],\n        photos\n      }, { ignoreUnknownFields: true });\n    }\n\n    if (data) {\n      if (prefill)\n        this.uid = data.uid;\n\n      if (!this.isWrdForm) { // Prefill adoptee rows (wrd form handles this in the myregistrations page)\n        const fullname = data.wrdFirstname + \" \" + data.wrdLastname;\n\n        const container = dompack.qS(\"#editregistration .editregistration__searchpersons\") as HTMLElement;\n\n        //add rows if needed\n        let personrow = dompack.qS(container, \".editregistration__person[data-id='\" + regid + \"']\") as HTMLElement;\n        if (!personrow) {\n          const template = document.getElementById(\"editregistration__person-template\") as HTMLTemplateElement;\n          if (!template)\n            return;\n\n          personrow = dompack.qS(template.content, \".editregistration__person\")?.cloneNode(true) as HTMLElement;\n          if (!personrow)\n            return;\n\n          personrow.dataset.id = regid;\n          const editbtn = dompack.qS(personrow, \".editregistration__person__edit\") as HTMLAnchorElement;\n          if (editbtn)\n            editbtn.href = \"#editregistration.adopteeprofile:\" + regid;\n\n          container.appendChild(personrow);\n        }\n\n        // Prefill name\n        dompack.qSA(personrow, \"[data-prefill='adopteename']\").forEach(node => node.textContent = fullname);\n      }\n\n      this.clearDirty();\n    }\n\n    if (lock)\n      lock.release();\n  }\n\n  async updateGlobalLabels() {\n    const keys = await this.db?.getAllKeys('adoptee');\n    if (!keys)\n      return;\n\n    keys.forEach(key => {\n      void this.getDataForAdoptee(key.replace(\"adoptee\", \"\"), false);\n    });\n  }\n\n  async parsePhotos(photos: PhotoType[]) {\n    if (!Array.isArray(photos))\n      return [];\n\n    const list: PhotoTypeStorage[] = [];\n    for (let i = 0; i < photos.length; ++i) {\n      list.push({\n        formrowid: i,\n        image: (photos[i].image && photos[i].image.length && photos[i].image[0].file instanceof File && photos[i].image[0].file.type.startsWith(\"image\")) ? await getFileAsDataURL(photos[i].image[0].file) : \"\",\n        image_filename: photos[i].image[0].fileName,\n        description: photos[i].description\n      });\n    }\n\n    return list;\n  }\n\n  async getParsedFormValue() {\n    const formval = this.formhandler?.data as AdopteeType;\n    if (!formval)\n      return null;\n\n    const parseddata: AdopteeTypeStorage = {\n      ...formval,\n      birthcertificate: \"\",\n      birthcertificateFilename: \"\",\n      photos: await this.parsePhotos(formval.photos as PhotoType[])\n    };\n\n    // convert image to dataurl\n    if (formval.hasbirthcertificate && formval.birthcertificate && formval.birthcertificate.length && formval.birthcertificate[0].file instanceof File && formval.birthcertificate[0].file.type.startsWith(\"image\")) {\n      parseddata.birthcertificate = await getFileAsDataURL(formval.birthcertificate[0].file);\n      parseddata.birthcertificateFilename = formval.birthcertificate[0].fileName;\n    }\n\n    return parseddata;\n  }\n\n  async saveData() {\n    const formval = await this.getParsedFormValue();\n    if (!formval)\n      return;\n\n    if (this.isWrdForm) {\n      if (this.uid.startsWith(\"wrd:\")) { // update wrd data by rpc\n        const lock = dompack.flagUIBusy({ modal: true });\n\n        const hsFormVal = toSnakeCase(formval);\n\n        const mysettings = getUserSettings();\n        const services = createClient<RPCService>(\"kiskeya:kiskeya_service\");\n        let res = null;\n        try {\n          res = await services.UpdateRegistration(mysettings.guid, this.uid, hsFormVal, this.language);\n        } catch (err) {\n          console.error(err);\n        }\n\n        lock.release();\n\n        if (res && res.success) {\n          showSavedMessage();\n        } else {\n          showSavedMessage(true);\n          console.error(\"saveData\", res);\n        }\n      }\n    } else {\n      if (this.db && this.regid) {\n        if (!this.uid)\n          this.uid = generateRandomId();\n        await this.db.put('adoptee', { ...formval, uid: this.uid }, 'adoptee' + this.regid);\n        showSavedMessage();\n      } else {\n        showSavedMessage(true);\n        console.error(\"saveData\", this.db ? \"Missing personal uid\" : \"No db\");\n      }\n      void this.updateGlobalLabels();\n      void this.checkForStoredData();\n    }\n\n    this.clearDirty();\n  }\n\n  async submit() {\n    await this.saveData();\n    return {};\n  }\n}\n\nregisterHandler(\"kiskeya:myprofileregistration\", node => {\n  const form = new MyProfileRegistrationForm(node);\n  if (form.isWrdForm)\n    __wrdProfileform = form;\n  else\n    __myprofileform = form;\n\n  return form;\n});\n\nregisterHandler(\"kiskeya:adopteeregistration\", node => {\n  const form = new AdopteeRegistrationForm(node);\n  if (form.isWrdForm)\n    __wrdAdopteeprofileform = form;\n  else\n    __adopteeprofileform = form;\n\n  return form;\n});\n","import { toSnakeCase } from \"@webhare/std\";\n\nconst { subtle } = globalThis.crypto;\nconst KiskeyaAlgo = { name: \"RSA-OAEP\", hash: \"SHA-256\" } as const;\n\nexport async function runOnceGenerateKeyMaterial(): Promise<{ publicKey: string; privateKey: string }> {\n  const keypair = await subtle.generateKey({ ...KiskeyaAlgo, modulusLength: 4096, publicExponent: new Uint8Array([1, 0, 1]) }, true, [\"encrypt\", \"decrypt\"]);\n\n  const publicKey = JSON.stringify(await subtle.exportKey(\"jwk\", keypair.publicKey));\n  const privateKey = JSON.stringify(await subtle.exportKey(\"jwk\", keypair.privateKey));\n\n  return { publicKey, privateKey };\n}\n\nasync function base64Encode(buf: ArrayBuffer) {\n  if (globalThis.FileReader) {\n    // use a FileReader to generate a base64 data URI:\n    const base64url = await new Promise<string>(resolve => {\n      const reader = new FileReader;\n      reader.onload = () => resolve(reader.result as string);\n      reader.readAsDataURL(new Blob([buf]));\n    });\n    // remove the `data:...;base64,` part from the start\n    return base64url.slice(base64url.indexOf(',') + 1);\n  }\n  return btoa(String.fromCharCode(...new Uint8Array(buf))); //TODO does not scale to megabyte range\n}\n\nfunction base64Decode(str: string) {\n  return new Uint8Array(atob(str).split('').map(c => c.charCodeAt(0)));\n}\n\nexport async function encryptFormResult(publicKey: string, formData: unknown): Promise<string> {\n  const key = await subtle.importKey(\"jwk\", JSON.parse(publicKey), KiskeyaAlgo, true, [\"encrypt\"]);\n\n  // create a random 96-bit initialization vector (IV)\n  const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));\n  // create an encryption key for AES\n  const aesKey = await subtle.generateKey({ name: \"AES-GCM\", length: 256 }, true, [\"encrypt\", \"decrypt\"]);\n  // get the data to encrypt\n  const toEncrypt = new TextEncoder().encode(JSON.stringify(formData));\n  // AES encrypt this data\n  const encryptedData: ArrayBuffer = await subtle.encrypt({ name: \"AES-GCM\", iv }, aesKey, toEncrypt);\n  // encrypt the AES key with the RSA public key\n  const encryptedKey: ArrayBuffer = await subtle.encrypt(KiskeyaAlgo, key, await subtle.exportKey(\"raw\", aesKey));\n\n  // concatenate the IV, the encrypted key and the encrypted data\n  // KED: Kiskeya Encrypted Data\n  return [\"KED\", await base64Encode(iv.buffer), await base64Encode(encryptedKey), await base64Encode(encryptedData)].join(\".\");\n}\n\nexport async function decryptFormResult(privateKey: string, kedData: string): Promise<unknown> {\n  const key = await subtle.importKey(\"jwk\", JSON.parse(privateKey), KiskeyaAlgo, true, [\"decrypt\"]);\n\n  const [id, encodedIv, encodedEncryptedKey, encodedEncryptedData] = kedData.split(\".\");\n  if (id !== \"KED\" || !encodedIv || !encodedEncryptedKey || !encodedEncryptedData)\n    throw new Error(\"Invalid encrypted data\");\n\n  const iv = base64Decode(encodedIv);\n  const encryptedKey = base64Decode(encodedEncryptedKey);\n  const encryptedData = base64Decode(encodedEncryptedData);\n\n  const aesKeyData = await subtle.decrypt(KiskeyaAlgo, key, encryptedKey);\n  const aesKey = await subtle.importKey(\"raw\", aesKeyData, { name: \"AES-GCM\" }, true, [\"decrypt\"]);\n  const decrypted = await subtle.decrypt({ name: \"AES-GCM\", iv }, aesKey, encryptedData);\n\n  return toSnakeCase(JSON.parse(new TextDecoder().decode(decrypted)));\n}\n","import \"./mysettings.scss\";\nimport * as dompack from \"@webhare/dompack\";\nimport { loginType } from \"../../pages/login/login\";\n\ndocument.addEventListener(\"kiskeya:logout\", () => {\n  setMyDetails(null);\n});\n\nexport function setMyDetails(settings: loginType | null) {\n  // Set the user's details\n  const node = dompack.qR(\".mysettings-personal\");\n  node.replaceChildren(); // Clear the node\n\n  if (settings) {\n    node.appendChild(<div class=\"fullname\">{settings.fullname}</div>);\n    node.appendChild(<a href={\"mailto:\" + settings.email} class=\"email\">{settings.email}</a>);\n  }\n}\n","import \"./myregistrations.scss\";\nimport { createClient } from \"@webhare/jsonrpc-client\";\nimport * as dompack from \"@webhare/dompack\";\nimport { getTid } from \"@mod-tollium/js/gettid\";\nimport { preparePersonalForm, prepareAdopteeForm } from \"../editregistration/editregistration\";\n\nlet __myregistrations: myRegistations | null = null;\n\ndocument.addEventListener(\"kiskeya:logout\", () => {\n  const listholder = dompack.qS(\".myregistrations-transfered__list\");\n  if (listholder)\n    listholder.replaceChildren();\n});\n\ntype myRegistation = {\n  title: string;\n  guid: string;\n  searchpersons: Array<{ guid: string; title: string }>;\n};\n\ntype myRegistations = {\n  registrations: myRegistation[];\n  totalcount: number;\n};\n\ninterface RPCService {\n  GetMyRegistrations(guid: string,\n    language: string\n  ): Promise<myRegistations>;\n}\n\nexport async function EditMyRegistration(pwauser: string, profileguid: string, language: string) {\n  await loadMyRegistrations(pwauser, language);\n\n  const reginfo = __myregistrations?.registrations.find(reg => reg.guid === profileguid);\n  if (reginfo) { // Prefill registration info\n    // First some cleanup\n    const container = dompack.qS(\".registrationsapp-page--myregistrations .editregistration__searchpersons\") as HTMLElement;\n    container.replaceChildren();\n\n    dompack.qR(\".registrationsapp-page--myregistrations .editregistration__person .editregistration__person__name\").textContent = reginfo.title;\n\n    let editbtn = dompack.qR(\".registrationsapp-page--myregistrations > .editregistration__person .editregistration__person__edit\") as HTMLAnchorElement;\n    editbtn.href = \"#myregistrations.editregistration.myprofile:\" + reginfo.guid;\n\n    // render edit adoptee profiles options\n    reginfo.searchpersons.forEach(person => {\n      const template = document.getElementById(\"editregistration__person-template\") as HTMLTemplateElement;\n      if (!template)\n        return;\n\n      const personrow = dompack.qR(template.content, \".editregistration__person\")?.cloneNode(true) as HTMLElement;\n      personrow.dataset.id = String(person.guid);\n      dompack.qR(personrow, \"[data-prefill='adopteename']\").textContent = person.title;\n\n      // No delete option for synct adoptee profiles. If needed manager can delete these in backend application\n      const deletebtn = dompack.qR(personrow, \".editregistration__person__delete\") as HTMLButtonElement;\n      deletebtn.parentNode?.removeChild(deletebtn);\n\n      editbtn = dompack.qR(personrow, \".editregistration__person__edit\") as HTMLAnchorElement;\n      editbtn.href = \"#myregistrations.editregistration.adopteeprofile:\" + person.guid;\n\n      container.appendChild(personrow);\n    });\n\n  } else\n    location.hash = \"#myregistrations\";\n}\n\nexport async function EditMyRegistrationProfile(pwauser: string, profileguid: string, language: string) {\n  if (__myregistrations === null)\n    await loadMyRegistrations(pwauser, language);\n\n  const reginfo = __myregistrations?.registrations.find(reg => reg.guid === profileguid);\n  if (reginfo) {\n    const backlink = dompack.qR(\".contentheader__back\") as HTMLAnchorElement;\n    backlink.href = \"#myregistrations.editregistration:\" + reginfo.guid;\n\n    dompack.qSA(\".registrationform--myprofile[data-storage='wrd'] .wh-form__button--submit[href^='#myregistrations.editregistration']\").forEach(anode => {\n      (anode as HTMLAnchorElement).href = \"#myregistrations.editregistration:\" + reginfo.guid;\n    });\n\n    // prefill personal profile form\n    preparePersonalForm(profileguid);\n\n  } else\n    location.hash = \"#myregistrations\";\n}\n\nexport async function EditMyRegistrationAdoptee(pwauser: string, profileguid: string, language: string) {\n  await loadMyRegistrations(pwauser, language);\n\n  const reginfo = __myregistrations?.registrations.find(reg => reg.searchpersons.findIndex(_ => _.guid === profileguid) > -1);\n  const adopteeinfo = reginfo?.searchpersons.find(person => person.guid === profileguid);\n  if (reginfo && adopteeinfo) {\n    const backlink = dompack.qR(\".contentheader__back\") as HTMLAnchorElement;\n    backlink.href = \"#myregistrations.editregistration:\" + reginfo.guid;\n\n    dompack.qSA(\".registrationform--adoptee[data-storage='wrd'] .wh-form__button--submit[href^='#myregistrations.editregistration']\").forEach(anode => {\n      (anode as HTMLAnchorElement).href = \"#myregistrations.editregistration:\" + reginfo.guid;\n    });\n\n    // prefill personal profile form\n    prepareAdopteeForm(profileguid);\n\n  } else\n    location.hash = \"#myregistrations\" + (reginfo ? \".editregistration:\" + reginfo.guid : \"\");\n}\n\nexport async function loadMyRegistrations(guid: string, language: string) {\n  const lock = dompack.flagUIBusy({ modal: true });\n\n  const services = createClient<RPCService>(\"kiskeya:kiskeya_service\");\n  let res = null;\n  try {\n    res = await services.GetMyRegistrations(guid, language);\n  } catch (err) {\n    console.error(err);\n  }\n\n  const listholder = dompack.qS(\".myregistrations-transfered__list\");\n  if (res && listholder) {\n    listholder.replaceChildren();\n\n    const regguids = res.registrations.map(reg => reg.guid);\n    const items = dompack.qSA(listholder, \"li[data-guid]\");\n    items.forEach((item: HTMLElement) => { // cleanup current list on myregistrations page\n      if (!regguids.includes(item.dataset.guid as string))\n        item.remove();\n    });\n\n    res.registrations.forEach(reg => {\n      const link = \"#myregistrations.editregistration:\" + reg.guid;\n      const item = <li data-guid={reg.guid} class=\"myregistrations-transfered__profile\">\n        <span class=\"myregistrations-transfered__profile__name\">{reg.title}</span>\n        <a href={link} class=\"myregistrations-transfered__profile__button button button--outline button--green\" aria-label={\"Edit \" + reg.title + \" profile\"}>\n          <span class=\"button__label\">{getTid('kiskeya:frontend.registrationapp.editregistration.editprofile')}</span>\n          <i class=\"button__icon far fa-pencil\" aria-hidden=\"true\"></i>\n        </a>\n      </li >;\n      listholder.appendChild(item);\n    });\n\n    (listholder.parentNode as HTMLElement).classList.toggle(\"noregistrations\", res.registrations.length === 0);\n  } else if (listholder)\n    listholder.replaceChildren();\n\n  __myregistrations = res;\n\n  lock.release();\n}\n","import \"@webhare/dompack/reset.css\";\nimport * as dompack from \"@webhare/dompack\";\nimport * as pwalib from '@mod-publisher/js/pwa';\nimport './registrationapp.lang.json';\nimport \"./registrationapp.scss\";\nimport \"./shared/rtd/rtd\";\nimport { createClient } from \"@webhare/jsonrpc-client\";\nimport \"./shared/forms/forms\";\nimport { confirmDialog } from \"./shared/forms/dialog\";\nimport { type loginType, showForgotPasswordDialog } from \"./pages/login/login\";\nimport { addSearchPerson, deleteSearchPerson, prepareAdopteeForm, saveMyProfileForm, saveAdopteeForm, saveAndComplete, syncRegistrations } from \"./pages/editregistration/editregistration\";\nimport \"./pages/startpage/startpage\";\nimport { setMyDetails } from \"./pages/mysettings/mysettings\";\nimport { loadMyRegistrations, EditMyRegistration, EditMyRegistrationProfile, EditMyRegistrationAdoptee } from \"./pages/myregistrations/myregistrations\";\nimport { getTid } from \"@webhare/gettid/src/internal\";\nimport { dtapStage } from \"@webhare/env\";\n\ntype pwaUpdateOptions = {\n  needsupdate: boolean;\n  forcerefresh: boolean;\n};\n\ninterface RPCService {\n  PollStatus(guid: string, language: string): Promise<{ status: string }>;\n}\n\nclass registrationApp {\n  online: boolean = navigator.onLine;\n  pages: { [key: string]: HTMLElement } = {};\n  localsettings: loginType | null = null;\n  loggedin: boolean = false;\n  activepage: HTMLElement | null = null;\n  heading1: HTMLElement | null = null;\n  installnotification: HTMLElement | null = null;\n  footernode: HTMLElement;\n  contentheader_top: HTMLElement | null = null;\n  language: string = \"en\";\n  lastupdatecheck: number = 0;\n\n  constructor() {\n    dompack.qSA(\".registrationsapp-page\").forEach(page => this.pages[page.id] = page as HTMLElement);\n\n    this.language = document.documentElement.lang ? document.documentElement.lang.split(\"-\")[0] : \"en\";\n\n    this.contentheader_top = dompack.qS(\".contentheader__top\");\n    this.heading1 = dompack.qS(\".contentheader h1\");\n\n    window.addEventListener(\"hashchange\", () => this.onHashChange());\n    document.addEventListener(\"click\", (ev) => void this.clickHandler(ev));\n    document.addEventListener(\"keyup\", (ev) => void this.clickHandler(ev));\n    document.addEventListener('visibilitychange', () => this.onVisibleChange());\n    window.addEventListener(\"resize\", () => this.updateFooterHeight());\n    addEventListener(\"load\", () => this.updateFooterHeight());\n    window.addEventListener('online', () => void this.checkOnlineStatus());\n    window.addEventListener('offline', () => void this.checkOnlineStatus());\n    void this.startup();\n\n    this.footernode = dompack.qR(\"footer\");\n    this.installnotification = dompack.qS(\".installnotification\");\n\n    this.checkInstalledLocal();\n\n    document.addEventListener(\"kiskeya:login\", () => this.login());\n    this.login();\n  }\n\n  async startup() {\n    await this.checkOnlineStatus();\n    if (this.online)\n      void this.checkForPWAUpdate();\n  }\n\n  updateFooterHeight() {\n    const h = this.footernode.clientHeight;\n    dompack.qSA(\".fixedbottombar\").forEach(node => node.style.transform = \"translateY(-\" + h + \"px)\");\n    document.body.style.paddingBottom = h + \"px\";\n  }\n\n  checkInstalledLocal() {\n    // Check if PWA is running in standalone mode:\n    // https://web.dev/learn/pwa/detection\n    // https://web.dev/articles/add-manifest#start-url\n    const isstandalone = window.matchMedia('(display-mode: standalone)').matches;\n\n    if (this.installnotification) {\n      if (isstandalone || dtapStage === \"development\") { // Don't show install notification when running in standalone mode or in development\n        this.installnotification.replaceChildren();\n        this.installnotification = null;\n      } else {\n        this.installnotification.addEventListener(\"click\", (ev: MouseEvent) => {\n          if (this.installnotification && (ev.target as HTMLElement).closest(\".installnotification__close\"))\n            this.hideInstallNotification();\n        });\n      }\n    }\n  }\n\n  hideInstallNotification() {\n    if (this.installnotification)\n      this.installnotification.hidden = true;\n  }\n\n  showInstallNotification() {\n    if (this.installnotification) {\n      this.installnotification.hidden = false;\n    }\n  }\n\n  onHashChange() {\n    let hash = window.location.hash.replace(\"#\", \"\");\n    if (!hash && this.loggedin)\n      hash = \"startpage\";\n    if (hash)\n      this.showPage(hash);\n  }\n\n  login() {\n    this.localsettings = this.getStoredSettings();\n\n    this.loggedin = Boolean(this.localsettings);\n\n    document.documentElement.classList.toggle(\"loggedin\", this.loggedin);\n\n    if (this.loggedin) {\n      if (!this.activepage || this.activepage.id === \"login\")\n        this.onHashChange();\n    } else {\n      this.showPage(\"login\");\n    }\n  }\n\n  async logout() {\n    const res = await confirmDialog(getTid(\"kiskeya:frontend.registrationapp.logout\"), getTid(\"kiskeya:frontend.registrationapp.surelogout\"));\n    if (res !== \"yes\")\n      return;\n\n    localStorage.removeItem(\"kiskeya:registrationapp\");\n    this.localsettings = null;\n    this.hideMenu();\n    this.hideUpdateNotification();\n\n    // Send event to clear all non encrypted data\n    dompack.dispatchCustomEvent(document, \"kiskeya:logout\", { bubbles: true, cancelable: false });\n\n    this.login(); // Goto login page\n  }\n\n  getStoredSettings() {\n    let mysettings;\n    try {\n      mysettings = JSON.parse(localStorage.getItem(\"kiskeya:registrationapp\") as string);\n    } catch (err) {\n      console.error(\"Error parsing settings\", err);\n    }\n\n    // Just some basic checks\n    if (mysettings && (!mysettings.guid.startsWith(\"wrd:\") || mysettings.guid.length < 32 || mysettings.publickey.length < 32))\n      mysettings = null;\n\n    return mysettings;\n  }\n\n  async checkOnlineStatus() {\n    if (navigator.onLine) { // Poll server for status\n      const services = createClient<RPCService>(\"kiskeya:kiskeya_service\");\n      let res = null;\n      try {\n        res = await services.PollStatus(this.localsettings ? this.localsettings.guid : \"\", this.language);\n      } catch (err) {\n        this.online = false;\n        document.documentElement.classList.toggle(\"online\", this.online);\n        return false;\n      }\n      this.online = res.status === \"online\";\n      document.documentElement.classList.toggle(\"online\", this.online);\n    } else {\n      this.online = false;\n      document.documentElement.classList.remove(\"online\");\n    }\n  }\n\n  async clickHandler(ev: Event) {\n    if (ev.type === \"keyup\" && (ev as KeyboardEvent).key !== \"Enter\") {\n      if ((ev as KeyboardEvent).key === \"Escape\" && document.documentElement.classList.contains(\"mainmenuopen\"))\n        this.hideMenu();\n      return;\n    }\n\n    if ((ev.target as HTMLElement).closest(\"a\"))\n      this.hideMenu(); // Just close menu when clicking on a link\n\n    const btn = (ev.target as HTMLElement).closest(\"button[data-action]\") as HTMLButtonElement;\n    if (btn && btn.dataset.action) {\n      switch (btn.dataset.action) {\n        case \"mainmenu\":\n          if (this.loggedin)\n            this.toggleMenu();\n          break;\n        case \"passwordforgotten\":\n          void showForgotPasswordDialog();\n          break;\n        case \"logout\":\n          void this.logout();\n          break;\n        case \"updateapp\":\n          void pwalib.updateApplication();\n          break;\n        case \"addsearchperson\":\n          if (this.localsettings)\n            addSearchPerson();\n          break;\n        case \"deletesearchperson\":\n          if (this.localsettings)\n            void deleteSearchPerson(btn);\n          break;\n        case \"sync\":\n          if (this.online && this.localsettings)\n            void syncRegistrations();\n          break;\n        case \"saveandcomplete\":\n          if (this.localsettings)\n            await saveAndComplete();\n          break;\n        default:\n          this.showPage(btn.dataset.action);\n          break;\n      }\n    }\n  }\n\n  toggleMenu() {\n    document.documentElement.classList.toggle(\"mainmenuopen\");\n  }\n\n  showMenu() {\n    document.documentElement.classList.add(\"mainmenuopen\");\n  }\n\n  hideMenu() {\n    document.documentElement.classList.remove(\"mainmenuopen\");\n  }\n\n  showPage(pageid: string) {\n    let regid = \"\";\n    if (pageid.indexOf(\":\") > -1) {\n      const parts = pageid.split(\":\");\n      regid = pageid.substring(parts[0].length + 1);\n      pageid = parts[0];\n    }\n\n    if (!this.loggedin && pageid !== \"login\") {\n      location.hash = \"#login\"; // redirect to login page\n      return;\n    }\n\n    const pagepath = pageid.split(\".\");\n\n    if (!pageid || !this.pages[pageid]) {\n      location.hash = \"#\" + (this.loggedin ? (this.activepage ? this.activepage.id : \"startpage\") : \"login\");\n      return;\n    }\n\n    if (this.loggedin && pageid === \"login\") {\n      location.hash = \"#startpage\"; // redirect to startpage\n      return;\n    }\n\n    this.hideMenu();\n    this.updateFooterHeight();//Update footer height\n\n    if (pagepath.length > 1 && pageid === \"editregistration.adopteeprofile\") {\n      // First check if adoptee registration with regid exists\n      if (dompack.qS(\".editregistration__person[data-id='\" + regid + \"']\"))\n        prepareAdopteeForm(regid);\n      else { // redirect to edit registration page\n        location.hash = \"#editregistration\";\n        return;\n      }\n    }\n\n    if (!this.pages[pageid] || (this.activepage && this.activepage.id === pageid))\n      return;\n\n    if (this.activepage) { // If previous page contains a profile form, save the form!\n      this.activepage.hidden = true;\n\n      if (this.activepage === this.pages[\"editregistration.adopteeprofile\"])\n        saveAdopteeForm();\n      else if (this.activepage === this.pages[\"editregistration.myprofile\"])\n        saveMyProfileForm();\n    }\n\n    if (pageid === \"mysettings\" && this.localsettings)\n      setMyDetails(this.localsettings);\n\n    if (this.heading1)\n      this.heading1.textContent = this.pages[pageid].dataset.title || \"\";\n\n    this.contentheader_top?.replaceChildren();\n\n    if (this.contentheader_top) {\n      if (pagepath.length > 0)\n        document.documentElement.dataset.pageid = pageid;\n\n      switch (pageid) {\n        case \"startpage\":\n          if (this.localsettings)\n            this.contentheader_top.append(<div class=\"contentheader__user\"><i class=\"far fa-user\" aria-hidden=\"true\" /><span>{this.localsettings.fullname}</span></div>);\n          break;\n        default:\n          if (this.loggedin) {\n            if (pagepath.length > 1) {\n              const prevpath = [...pagepath];\n              prevpath.pop();\n              const previd = prevpath.join(\".\");\n              const prevpage = this.pages[previd];\n              if (prevpage) {\n                this.contentheader_top.append(<a href={\"#\" + previd} class=\"contentheader__back\"><i class=\"far fa-angle-left\" aria-hidden=\"true\" /><span>{prevpage.dataset.title || \"Back\"}</span></a>);\n                break;\n              }\n            }\n\n            this.contentheader_top.append(<a href=\"#startpage\" class=\"contentheader__back\"><i class=\"far fa-angle-left\" aria-hidden=\"true\" /><span>{this.pages[\"startpage\"].dataset.title || \"Back\"}</span></a>);\n          }\n          break;\n      }\n    }\n\n    if (this.online && this.localsettings) {\n      if (pageid === \"myregistrations\")\n        void loadMyRegistrations(this.localsettings.guid, this.language);\n      else if (pageid === \"myregistrations.editregistration\")\n        void EditMyRegistration(this.localsettings.guid, regid, this.language);\n      else if (pageid === \"myregistrations.editregistration.myprofile\")\n        void EditMyRegistrationProfile(this.localsettings.guid, regid, this.language);\n      else if (pageid === \"myregistrations.editregistration.adopteeprofile\")\n        void EditMyRegistrationAdoptee(this.localsettings.guid, regid, this.language);\n    }\n\n    this.activepage = this.pages[pageid];\n    this.activepage.hidden = false;\n    this.showInstallNotification();\n\n    if (this.online)\n      void this.checkForPWAUpdate();\n  }\n\n  async checkForPWAUpdate() {\n    const now = new Date().getTime();\n    if (now - this.lastupdatecheck < 60000) // 1 minute\n      return; // Don't check for updates too often\n\n    this.lastupdatecheck = now;\n\n    const updateres = await pwalib.checkForUpdate() as pwaUpdateOptions;\n    if (!updateres.needsupdate)\n      return;\n\n    await pwalib.downloadUpdate();\n    this.showUpdateNotification();\n  }\n\n  showUpdateNotification() {\n    document.documentElement.classList.add(\"updatenotification\");\n  }\n\n  hideUpdateNotification() {\n    document.documentElement.classList.remove(\"updatenotification\");\n  }\n\n  onVisibleChange() { // Triggered when user opens or closes the application\n    if (document.visibilityState === 'visible') {\n      this.checkInstalledLocal();\n      void this.checkForPWAUpdate();\n    }\n  }\n}\n\npwalib.onReady(() => {\n  new registrationApp();\n}, { reportusage: true });\n","import \"@webhare/frontend/src/init\";import \"/opt/wh/whtree/modules/publisher/js/internal/polyfills/all\";\nimport \"/opt/whdata/installedmodules/kiskeya.20261027T130541.723Z/webdesigns/registrationapp/registrationapp_pwa.tsx\";const aps = globalThis.whAssetPacks ||= {}; aps[\"kiskeya:registrationapp_pwa\"]=\"2026-10-27T13:05:57.349Z\";"],"mappings":"kyCA0GA,SAASA,IAAuB,CAC9B,MAAO,eAAe,CAAC,GAAG,OAAO,KAAKC,CAAU,CAAC,EAAE,OAAOC,GAAOD,EAAWC,CAAG,CAAC,EAAE,KAAK,IAAI,CAAC,GAC9F,CAEA,SAASC,IAAuB,CAC9B,QAAWC,IAAM,CAAC,GAAGC,EAAwB,EAC3C,GAAI,CACFD,EAAG,CACL,OAAS,EAAG,CACV,QAAQ,MAAM,0CAA2CA,GAAI,KAAM,CAAC,CAEtE,CAEJ,CA+DO,SAASE,GAAQC,EAAyBC,EAAwB,CACvEC,EAAYF,EACZG,EAASD,IAAc,cAAgBA,IAAc,aACrDE,GAAcH,EAEdI,GAAYH,EACZI,GAASH,CACX,CA7LA,IAoCML,GAMAS,GAAmCC,GAGrCC,GAYEC,GA6COhB,EA2DTQ,EAGAC,EAGAC,GAOAC,GAEAC,GAhLJK,GAAAC,EAAA,kBAoCMd,GAA2B,IAAI,MAM/BS,GAA+B,CAAC,EAAGC,GAA8B,CAAC,EAelEE,GAAN,KAAiE,CACvD,eAA8B,CACpC,MAAO,CAAC,GAAGD,KAAwB,GAAK,CAAC,EAAGD,GAAi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backs","cb","settingschangedcallbacks","initEnv","setDtapStage","setBackendBase","dtapStage","isLive","backendBase","dtapstage","islive","globalDebugFlags","localDebugFlags","debugFlagsOverridesCB","DebugFlagsProxyHandler","init_envbackend","__esmMin","target","p","record","keys","newValue","toModify","value","qS","node_or_selector","selector","qR","matches","qSA","isFormControl","field","isHTMLElement","isElement","node","parseLanguageTag","languageTag","match","getLang","tag","init_tree","__esmMin","getWHType","obj","isCrossRealm","value","isMoney","isTemporalInstant","isTemporalPlainDateTime","isTemporalPlainDate","isTemporalPlainTime","isTemporalZonedDateTime","isDate","isBlob","isFile","isPromise","e","stdTypeOf","t","init_quacks","__esmMin","parseMS","ms","parseDuration","duration","matches","addDuration","startingdate","isTemporalInstant","direction","date","modifydays","timeoffset","convertFlexibleInstantToDate","input","convertWaitPeriodToDate","wait","options","isDate","isValidDate","year","month","day","minYear","isleapyear","init_datetime","__esmMin","init_quacks","sleep","duration","options","until","convertWaitPeriodToDate","resolve","timeoutid","wrapInTimeout","promise","timeout","rejectWith","timeoutpromise","reject","timer","error","wrapSerialized","fn","Coalescer","queue","args","res","init_promises","__esmMin","init_datetime","init_quacks","startpos","currentpos","result","i","e","init_finmath","__esmMin","init_money","__esmMin","init_finmath","init_quacks","nameToCamelCase","name","c","nameToSnakeCase","recodeObject","inp","isDate","isMoney","isBlob","isTemporalInstant","isTemporalPlainDate","isTemporalPlainDateTime","isTemporalZonedDateTime","recursiveToSnakeCase","toSnakeCase","key","value","recursiveToCamelCase","toCamelCase","init_types","__esmMin","init_money","init_quacks","isHTMLUnrepresentableChar","curch","encodeEntities","str","html","s","char","decodeEntities","_","dec","encodeString","encoding","decodeString","stringify","arg","options","usereplacer","key","value","origvalue","type","stdTypeOf","lhs","rhs","result","isValidEmail","email","init_strings","__esmMin","init_quacks","init_money","generateRandomId","encoding","bytes","u8array","x","init_platformbased","__esmMin","emplace","map","key","handler","current","setvalue","pick","value","keys","elt","ret","omit","val","init_collections","__esmMin","init_utils","__esmMin","init_quacks","unlock","LocalMutex","LocalLock","init_localmutex","__esmMin","defer","mutex","throwError","err","init_std","__esmMin","init_promises","init_types","init_strings","init_platformbased","init_collections","init_money","init_datetime","init_quacks","init_utils","init_localmutex","submitForm","action","values","method","form","item","input","navigateTo","navigation","init_navigation","__esmMin","init_fetchdebug","__esmMin","init_envbackend","init_std","init_whglobal","__esmMin","init_envbackend","debugFlags","init_env","__esmMin","init_envbackend","init_navigation","init_fetchdebug","init_whglobal","getGetTidHooks","gotHooks","hookFactory","init_hooks","__esmMin","internal_exports","__export","getHTMLTid","getHTMLTidForLanguage","getTIDListForLanguage","getTid","getTidForLanguage","getTidLanguage","registerTexts","setTidLanguage","ensureHooks","hooks","getGetTidHooks","lang","browserSetLanguage","defaultLanguage","newLanguage","getLanguageFile","moduleName","langCode","langkey","compiled","langFileCache","loader","addResourceChangeListener","loaded","e","dtapStage","debugFlags","texts","toHTMLNode","tag","props","node","wrapInFragment","children","fragment","getTidInternal","tid","params","options","decodeString","nodes","calcTIDForLanguage","p","p1","p2","p3","p4","encodeString","langcode","gid","getCanonicalTid","modsep","module","lookup","result","key","fallback","cannotFind","rawParams","rich","render","getLanguageDatetimeStrings","debugtid","match","fallbackMatch","executeCompiledTidText","renderString","tok","part","_","text","parts","get_param","sub","link","flattenRecursiveLanguageTexts","pathsofar","name","value","tids","compiledFile","init_internal","__esmMin","init_std","init_hooks","init_env","init_tree","getLang","init_envbackend","getBrowserDebugFlags","varname","flags","urldebugvar","debugcookie","debugcookievalue","flag","sessionDebug","init_tree","init_std","config","siteroot","dtapStage","whconfigel","parsedConfig","omit","initEnv","flag","getBrowserDebugFlags","debugFlags","frontendConfig","getLang","getFrontendData","dataObject","allowMissing","retval","getSiteRoot","throwError","resolve","reject","_resolve","_reject","items","callbackfn","retval","idx","item","key","list","IteratorPrototype","ArrayIteratorPrototype","OriginalIteratorPrototype","callback","it","value","next_value","real_value","max_count","values","limit","remaining","index","mapper","mapped","reducer","initial_value","acc","count","string","final","first","iterables","others","it_array","e","finished","partition1","partition2","i","max","min","isObject","t","GetIteratorFlattenable","obj","method","iterator","Iterator","WrappedIterator","#iterator","args","returnMethod","Iterator_from","init_env","CustomEvent","dispatchDomEvent","element","eventtype","options","createtype","evt","dispatchCustomEvent","node","event","params","prop","evt","CustomEvent","defaultaction","changeValue","element","newvalue","asString","dispatchDomEvent","keydata","initKeyMapping","normalizeKeyboardEventData","key","stop","addDocEventListener","type","listener","options","locallocks","modallocked","uiwatcher","installedanticancelhandler","currentbusymodaldialog","currentbusymodaluserdialog","busymodalcontent","mylockmgr","getLockmgr","getParentLockManager","LockManager","anyModalLocks","l","scheduleCheckUIFree","checkUIFree","toggleBusyModal","lockmgr","isDialogElement","el","checkCancelEvent","evt","show","dispatchCustomEvent","dialog","toembed","lock","pos","debugFlags","BusyLock","options","lockmgr","getLockmgr","locallocks","modallocked","toggleBusyModal","debugFlags","lockpos","scheduleCheckUIFree","flagUIBusy","options","BusyLock","getParentLockManager","debugFlags","locallocks","l","lockmgr","getLockmgr","locallockmgr","LockManager","lock","mylockmgr","init_tree","init_tree","IS_NON_DIMENSIONAL","generateInsertList","nodes","frag","node","append","node","nodes","generateInsertList","isDomReady","onDomReady","callback","setStyles","node","value","key","propvalue","IS_NON_DIMENSIONAL","flattenArray","list","acc","elt","setClassName","node","value","str","key","idx","MATCH_UPCASE","toDashed","value","MATCH_UPCASE","attrHasBooleanValue","propname","createElement","elementname","attributes","toattrs","node","attrname","value","eventname","toDashed","setClassName","setStyles","append","child","create","children","el","jsxcreate","element","childNodes","parts","flattenArray","elt","components","map","isNodeCompletelyInDom","node","processRegistration","item","reg","domready","list","applyRegistration","startnode","isDomReady","items","e","focus","options","dispatchCustomEvent","register","selector","handler","options","newreg","components","isDomReady","onDomReady","registerMissed","applyRegistration","startnode","item","init_std","loadImage","imgsrc","resolve","reject","img","parseUserAgent","ua","UA","platform","name","version","device","browser","getBrowser","parseUserAgent","submitselector","config","forwardPublisherNavigation","event","isHTMLElement","navaction","desturl","origin","configureForCMS","e","init_std","init_env","eventname_regex","datakey_regex","max_sessionid_age","globalOptions","pagesession","useAltRecordURL","seqnr","pxlUserId","pxlSessionId","buildOptions","options","pxlFailed","errormessage","params","isLive","makePxlURL","baseurl","eventname","data","options","globalOptions","eventname_regex","pagesession","generateRandomId","url","seqnr","getPxlSessionId","getPxlId","browser","getBrowser","name","value","test","datakey_regex","type","pxlUserId","timestampvar","debugFlags","sessionExpireDays","max_sessionid_age","expiration","pxlSessionId","sendPxlEvent","event","finaloptions","buildOptions","useAltRecordURL","fetchRes","error","init_std","init_env","init_env","appname","setAppName","newappname","getAppName","instanceOfAny","object","constructors","c","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","getCursorAdvanceMethods","transactionDoneMap","transformCache","reverseTransformCache","promisifyRequest","request","promise","resolve","reject","unlisten","success","error","wrap","cacheDonePromiseForTransaction","tx","done","complete","idbProxyTraps","target","prop","receiver","value","replaceTraps","callback","wrapFunction","func","args","unwrap","transformCachableValue","newValue","readMethods","writeMethods","cachedMethods","getMethod","target","prop","targetFuncName","useIndex","isWrite","method","storeName","args","tx","replaceTraps","oldTraps","receiver","advanceMethodProps","methodMap","advanceResults","ittrProxiedCursorToOriginalProxy","cursorIteratorTraps","cachedFunc","iterate","cursor","proxiedCursor","reverseTransformCache","unwrap","isIteratorProp","instanceOfAny","clearCache","appname","cache","key","unregisterServiceWorkers","currentregistrations","reg","debuglayer","clearCache","getAppName","restartApp","unregisterServiceWorkers","runPWADebugMenu","jsxcreate","activatetouches","expectnumtouches","expecttaptime","testMenuTap","event","stop","register","node","settings2","getAssetPackBase","assetpack","init_env","init_env","UNKNOWN_FUNCTION","parse","stackString","lines","stack","line","parseResult","parseChrome","parseWinjs","parseGecko","parseNode","parseJSC","chromeRe","chromeEvalRe","parts","isNative","isEval","submatch","winjsRe","geckoRe","geckoEvalRe","javaScriptCoreRe","nodeRe","parseTrace","e","parse","i","formatTrace","trace","prependStackTrace","error","stacklines","tracelines","init_std","globalseqnr","getDebugAppend","urldebugvar","ControlledCall","client","method","stack","id","options","callurl","fetchoptions","fetchpromise","requestStack","response","retryafter","resolve","exception","jsonresponse","logitem","err","prependStackTrace","RPCClient","url","debugFlags","error","backendBase","params","parseTrace","ServiceProxy","target","prop","receiver","newoptions","createClient","args","servicename","rpcclient","init_env","init_env","init_std","init_std","init_env","activeListenPrefixes","sendPxl","eventKey","params","data","options","pxldata","k","v","sendPxlEvent","setupFormAnalytics","prefix","registered","dtapStage","e","formeventdata","key","val","init_env","init_std","init_env","postRenderChecks","log","logtext","onDomReady","appbase","pwasettings","getFrontendData","frontendConfig","didinit","offlinedeferred","swregistration","getAppName","settings2","module","webdesign","sendSWRequestTo","sw","type","data","resolve","reject","msg_chan","event","sendSWRequest","checkForUpdate","downloadUpdate","updateApplication","navigateTo","onReady","initfunction","options","getSiteRoot","sendPxlEvent","onDomReady","e","swurl","getAssetPackBase","precheckExistingWorkers","registrations","onServiceWorkerMessage","setAppName","registerTexts","init_internal","isRealBlob","data","convertToRealBlob","MultiFileUploader","#files","files","signal","item","file","instructions","options","outfiles","uploadedBytes","uploadedFiles","totalBytes","acc","totalFiles","start","fireProgressEvent","partialbytes","curUploaded","timeElapsed","idx","offset","uploadurl","defer","xmlhttp","ev","doAbort","SingleFileUploader","getFilelistFromUser","multiple","accept","dispatchCustomEvent","input","list","requestFile","options","files","getFilelistFromUser","getFileAsDataURL","file","resolve","reject","reader","init_env","getISOLocalDate","date","getActiveElement","doc","getToplevelWindow","toplevelwindow","asIframe","node","getCurrentlyFocusedElement","limitdoc","focused","frame","canFocusTo","ignoreInertAttribute","getFocusableComponents","startnode","options","focusable","currentnode","currentstyle","iframe","subnodes","formatters","updaters","mergeNode","node","set","data","parts","isNodeFunc","func","exprpath","callparts","funcrest","value","exprpathparts","i","prop","run","mergenode","filter","nodes","sets","init_std","init_env","rfSymbol","init_std","fixupConditionRecursive","node","condition","mapping","anychanges","subcondition","newName","ArrayField","handler","items","name","throwError","qS","event","addDocEventListener","rownode","qSA","form","getFormHandler","newrow","addedrow","registerMissed","setup","stop","delNode","row","rowBaseName","rowFields","getFormElementCandidates","_","RecordFieldHandler","rows","n","rowval","valuePromises","rowPromises","field","values","rowValue","value","idx","rowField","firstnode","valueRows","newvalue","fieldnode","rowid","nodeArray","fieldname","getFieldName","cellname","subname","setFieldName","labelnodes","labelnode","type","conditionnode","parseCondition","minRows","maxRows","numRows","getTid","init_std","unmapFieldName","camelCaseName","nameToSnakeCase","mapFieldName","htmlName","nameToCamelCase","mapValue","type","invalue","unmapValue","fieldDescr","isDate","HTMLFormFieldHandler","form","field","selectedrow","newvalue","setvalue","RadioFormFieldHandler","name","rnodes","group","node","_","myname","CheckboxGroupHandler","cboxes","throwError","toset","missing","cbox","RegisteredFieldHandler","ArrayFieldHandler","items","rfSymbol","ArrayField","getFieldName","FormFieldMap","fieldName","nodes","subpos","groups","fullName","arraygroup","AddressFieldHandler","RecordFieldHandler","options","mapName","match","data","ignoreUnknownFields","key","value","baseName","retval","val","prettyName","omit","FieldMapDataProxy","target","p","prop","delayvalidation","validationpendingfor","didGlobalHandlers","lineFeedsToBreaks","text","frag","part","getPageIdx","state","page","idx","getErrorFields","validationresult","field","getFieldName","value","index","self","hasEverFailed","doValidation","iffailedbefore","releasePendingValidations","debugFlags","form","doDelayValidation","tovalidate","lastfocusout","handleFocusOutEvent","event","handleFocusInEvent","handleValidateAfterEvent","FormBase","FormFieldMap","generateRandomId","#lastFocused","FieldMapDataProxy","node","getFormElementCandidates","setup","addDocEventListener","evt","#recordLastFocus","pagestate","name","#onUnload","now","eventdata","dispatchCustomEvent","control","qSA","element","target","ourcondition","parseCondition","searchparams","allvalues","shouldbechecked","tocheck","_","type","getError","fieldgroup","field_with_message","error","potentialgroupnode","contextnode","messageid","messagenode","suggestionholder","create","describedby","describedby_fields","failedfield","getValidationState","stop","extradata","submitter","submitselector","tempbutton","beforeResult","isPromise","el","queryFormFieldLike","startingpoint","lock","flagUIBusy","result","containingpage","pagenum","actionnode","pages","curpage","pagelist","currentpage","scrollto","origscrollto","__isSubmit","pageidx","goingforward","run","direction","pagenode","action","navigateTo","validationstatus","isinit","hiddenPages","mergeNodes","anychanges","formpage","visible","hiddengroups","enabledgroups","requiredgroups","formgroup","groupPage","enabled","required","formline","inputtargets","node_enabled","isFormFieldLike","node_required","isFormControl","option","option_enabled","option_hidden","selectnode","wrapSerialized","nodes","formvalue","mergeNode","conditiontext","fieldname","options","matchfield","isRadioNodeList","currentvalue","conditionfield","fields","attrname","selectedvalue","val","selected","qS","extrafields","condition","subcondition","birthdate","age","matchcase","compareagainst","currentValArray","nextpage","morepages","curpagerole","nextpagerole","rawNavigateTo","exitButton","parsedNavTo","redirectdelay","submitButton","submitButtonLabel","richvalues","registerMissed","dtapStage","getFieldDisplayName","rfSymbol","deferred","file","fieldnode","saveInteractive","changeValue","foundfields","skiparraymembers","addto","isRadioOrCheckbox","outdata","fieldpromises","receivedvalue","resolve","reject","e","opts","vals","checker","setupValidator","setFieldError","isFieldNativeErrored","updateFieldError","validator","limitset","defer","item","original","group","subnode","tovalidatelist","validationresults","fld","failed","tofocus","canFocusTo","getFocusableComponents","focus","init_env","init_std","hsformservice","tsformservice","getFormService","createClient","getTSFormService","lookupcache","verifyHareScriptAddress","address","options","lookupkey","stringify","emplace","getFormService","init_std","SubField","node","pos","throwError","AddressField","qR","prefixLength","fieldpos","field","qSA","event","fieldname","data","firstfield","key","country","ordering","e","prevgroup","idx","item","fieldgroup","setFieldError","value","visiblefields","anyset","allrequiredset","form","FormBase","curstate","result","lock","flagUIBusy","el","verifyHareScriptAddress","debugFlags","err","anychanges","newvalue","changeValue","init_std","formatDate","dateformat","year","month","day","isValidDate","output","c","parseDate","format","newdate","options","parts","dayoffset","monthoffset","yearoffset","daypos","monthpos","yearpos","day","month","year","isValidDate","parseISODate","newdate","options","parseDate","init_std","validateCheckboxGroup","groupnode","nodes","qSA","min","max","anyenabled","node","numChecked","getTid","validateRadioGroup","reformatDate","datestr","parsed","parseISODate","formatDate","validateDate","date","dateparts","year","month","day","isValidDate","normalizeddate","validateTime","time","timeparts","hours","minutes","seconds","setup","form","datecontrol","field","datematch","propname","thedate","getISOLocalDate","setupValidator","timecontrol","propvalue","checkboxgroup","radiogroup","addresscontrol","AddressField","JSFormElement","newname","required","disable","name","oldValue","newValue","init_std","queryFormFieldLike","isInputElement","field","isHTMLElement","isFormFieldLike","control","isFormControl","JSFormElement","isRadioOrCheckbox","isRadioNodeList","el","getFieldName","setFieldName","newname","getFieldDisplayName","downgradeUploadFields","form","uploadfield","qSA","input","attr","getErrorForValidity","validity","getTid","max","reformatDate","min","key","isFieldNativeErrored","getFieldNativeError","parseCondition","conditiontext","getFormElementCandidates","basenode","namePrefix","parentForm","candidates","getFormHandler","node","allowMissing","throwError","setupServerErrorClear","field","group","setFieldError","ComponentValidationState","el","err","getFieldNativeError","validations","getValidationState","state","newstate","error","options","isHTMLElement","debugFlags","getFieldDisplayName","updateFieldError","dispatchCustomEvent","setupValidator","node","checker","registerTexts","isAcceptableType","fileType","masks","basetype","FileEditElement","JSFormElement","csslink","#setValue","evt","error","setFieldError","getTid","value","toset","row","getFieldDisplayName","mimetype","accept","mask","files","_stack","lock","__using","flagUIBusy","file","requestFile","_","_error","_hasError","__callDispose","msg","dispatchCustomEvent","idx","stop","button","init_std","FileUploadFormElement","FileEditElement","#constructFileHolder","fileholder","nodes","idx","file","filename","isFile","filenamefield","jsxcreate","deletebutton","getTid","uploadbutton","UploadField","node","init_std","revoker","cachedURLs","createFileURL","file","emplace","newurl","oldurl","getImageDimensions","img","loadImage","getFileAsDataURL","ImgEditElement","_ImgEditElement","FileEditElement","name","_oldValue","newValue","value","textupdate","qSA","node","error","size","setFieldError","getTid","nodes","idx","imgholder","create","deletebutton","contentwrapper","uploadicon","explain","ImgEditField","init_std","init_env","cache","mayValidateField","field","acceptEmailSuggestion","evt","form","suggestion","stop","validateField","setFieldError","checkvalue","isValidEmail","getTid","key","rpcCall","getFormService","getTidLanguage","wrapInTimeout","result","e","debugFlags","jsxcreate","init_env","debugflags","debugFlags","debugFlags","flagname","parseUserAgent","ua","UA","platform","browser","getPlatform","browser","IS_MAC_PLATFORM","getPlatform","propnames","getFinalKey","event","getKeyNames","names","propname","modifier","arr","newkeys","singlemodifier","validateKeyName","key","modifiers","mod","original_order","KeyboardHandler","node","keymap","options","name","keyname","debugflags","target","keynames","tag","is_special_combo","keybinding","handler","keydata","normalizeKeyboardEventData","i","mapping","dialogstack","keyhandler","dialogconstructor","dialogoptions","onEscape","event","stop","onTab","direction","focusable","getFocusableComponents","el","getCurrentlyFocusedElement","tofocusidx","tofocus","focus","DialogBase","options","borrow","KeyboardHandler","evt","myoffset","response","setupDialogs","newdialogconstructor","createDialog","options","dialogconstructor","dialog","runMessageBox","question","choices","choicebuttons","choice","create","dialogoptions","init_env","init_std","registerTexts","captcharegistry","initializeCaptcha","provider","injectInto","settings","finalsettings","getTid","init_std","formConfiguration","handlers","configuredRegistrations","firstWarningMs","warningIntervalMs","scheduleFormSetup","form","factory","_stack","lock","__using","flagUIBusy","customEls","qSA","_","initPromise","nextWarning","timeoutPromise","sleep","missing","tag","downgradeUploadFields","_error","_hasError","__callDispose","configureForms","setup","dispatchCustomEvent","registerHandlers","addHandlers","defaultHandler","RPCFormBase","handlername","handler","emplace","current","register","registerHandler","getFormConfiguration","init_std","init_tree","recaptchaload","recaptchaload","setupForms","options","registerHandlers","configureForms","omit","CaptchaField","JSFormElement","evt","form","setFieldError","getTid","provider","initializeCaptcha","result","stop","setupCaptchaFieldGroup","captchaControl","create","virtualCaptchaPage","buttonarea","qS","unpackObject","formvalue","_","buildTarget","target","FormSubmitter","cache","offline","file","completed","uploader","SingleFileUploader","uploadinstructions","getTSFormService","uploadedfile","isBlob","result","key","value","buildRPCFormSubmission","target","formValue","options","vals","FormSubmitter","eventdetail","buildTarget","unpackObject","submitRPCForm","submission","createClient","RPCFormBase","FormBase","#hadFocus","#completedUploads","#settingUpCaptcha","formnode","#onFirstFocus","isLive","#getSubmitVals","formvalue","background","methodname","args","waiter","lock","flagUIBusy","rpc","getFormService","result","field","prop","value","key","keyValue","matchpage","dataval","fieldnode","registerMissed","promise","messages","msg","extradata","extraSubmitAwaitable","extraSubmit","dispatchCustomEvent","config","getFormConfiguration","captchaConfig","setupCaptchaFieldGroup","parameters","insubmitrpc","submitparameters","debugFlags","didfirstfocus","globalerrors","error","failednode","serverMetadata","focus","setFieldError","run","failedfields","pick","e","errors","create","runMessageBox","navigateTo","getCurrentlyFocusedElement","validation","validateField","init_env","legacyRegisterFormHandler","handlername","handler","registerHandler","form","createdForm","isLive","FormBase","RPCFormBase","setupForms","form","FormBase","setupFormAnalytics","KSKDateParts","JSFormElement","qR","value","setFieldError","daysinmonth","init_internal","convertElementTids","scope","node","getTid","args","getTidLanguage","setTidLanguage","getHTMLTid","BasicDialog","DialogBase","classname","options","create","evt","stop","registerMissed","kiskeyaDialog","BasicDialog","options","jsxcreate","getTid","registerMissed","dispatchCustomEvent","ev","stop","setupDialogs","confirmDialog","title","text","isWarning","dlgobj","createDialog","contentnode","dialogbtn","showSavedMessage","failed","node","register","node","UploadField","ImgEditField","ImgEditElement","KSKDateParts","title","btn","jsxcreate","form","qSA","txt","labelnode","selectnode","wrappernode","showForgotPasswordDialog","template","resetform","qR","resetdialog","createDialog","loginForm","RPCFormBase","node","result","dispatchCustomEvent","legacyRegisterFormHandler","instanceOfAny","object","constructors","c","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","getCursorAdvanceMethods","transactionDoneMap","transformCache","reverseTransformCache","promisifyRequest","request","promise","resolve","reject","unlisten","success","error","wrap","cacheDonePromiseForTransaction","tx","done","complete","idbProxyTraps","target","prop","receiver","value","replaceTraps","callback","wrapFunction","func","args","unwrap","transformCachableValue","newValue","openDB","name","version","blocked","upgrade","blocking","terminated","openPromise","event","db","readMethods","writeMethods","cachedMethods","getMethod","target","prop","targetFuncName","useIndex","isWrite","method","storeName","args","tx","replaceTraps","oldTraps","receiver","advanceMethodProps","methodMap","advanceResults","ittrProxiedCursorToOriginalProxy","cursorIteratorTraps","cachedFunc","iterate","cursor","proxiedCursor","reverseTransformCache","unwrap","isIteratorProp","instanceOfAny","init_std","init_std","subtle","KiskeyaAlgo","base64Encode","buf","base64url","resolve","reader","encryptFormResult","publicKey","formData","key","subtle","KiskeyaAlgo","iv","aesKey","toEncrypt","encryptedData","encryptedKey","base64Encode","fetchAsFile","url","options","fetchresult","filename","__myprofileform","__adopteeprofileform","__wrdProfileform","__wrdAdopteeprofileform","saveAndComplete","confirmDialog","getTid","syncRegistrations","keys","dlgobj","createDialog","btn","jsxcreate","contentnode","ev","mysettings","getUserSettings","err","addSearchPerson","template","personrow","qS","qSA","container","lines","b","id","editbtn","deleteSearchPerson","row","name","qR","saveMyProfileForm","saveAdopteeForm","preparePersonalForm","regid","prepareAdopteeForm","RegistrationForm","FormBase","node","formname","myprofile","searchpersons","encrypteddata","encryptFormResult","toSnakeCase","now","hasdata","profiledata","openDB","db","i","paginationcontainer","item","target","curpage","page","idx","isprevious","myregblock","myreglistnode","keycount","key","_","guid","active","indicator","services","createClient","exportkeys","e","uids","syncreq","data","res","MyProfileRegistrationForm","throwError","profileguid","lock","flagUIBusy","rpcData","toCamelCase","localData","fullname","formval","parseddata","getFileAsDataURL","hsFormVal","showSavedMessage","generateRandomId","AdopteeRegistrationForm","prefill","photos","image","list","legacyRegisterFormHandler","form","setMyDetails","settings","node","qR","jsxcreate","__myregistrations","listholder","qS","EditMyRegistration","pwauser","profileguid","language","loadMyRegistrations","reginfo","reg","container","qR","editbtn","person","template","personrow","deletebtn","EditMyRegistrationProfile","backlink","qSA","anode","preparePersonalForm","EditMyRegistrationAdoptee","_","adopteeinfo","prepareAdopteeForm","guid","lock","flagUIBusy","services","createClient","res","err","regguids","item","link","jsxcreate","getTid","init_internal","init_env","registrationApp","qSA","page","qS","ev","qR","h","node","isstandalone","dtapStage","hash","confirmDialog","getTid","dispatchCustomEvent","mysettings","err","services","createClient","res","btn","showForgotPasswordDialog","updateApplication","addSearchPerson","deleteSearchPerson","syncRegistrations","saveAndComplete","pageid","regid","parts","pagepath","prepareAdopteeForm","saveAdopteeForm","saveMyProfileForm","setMyDetails","jsxcreate","prevpath","previd","prevpage","loadMyRegistrations","EditMyRegistration","EditMyRegistrationProfile","EditMyRegistrationAdoptee","now","checkForUpdate","downloadUpdate","onReady","aps"]}