const unSet = (obj, path, options = {}, tracking = {}) => {
	let internalPath = path;

	options = {
		"transformRead": returnWhatWasGiven,
		"transformKey": returnWhatWasGiven,
		"transformWrite": returnWhatWasGiven,
		...options
	};

	// No object data
	if (obj === undefined || obj === null) {
		return;
	}

	// No path string
	if (!internalPath) {
		return;
	}

	internalPath = clean(internalPath);

	// Path is not a string, throw error
	if (typeof internalPath !== "string") {
		throw new Error("Path argument must be a string");
	}

	if (typeof obj !== "object") {
		return;
	}

	const newObj = decouple(obj, options);

	// Path has no dot-notation, set key/value
	if (isNonCompositePath(internalPath)) {
		if (newObj.hasOwnProperty(unEscape(internalPath))) {
			delete newObj[options.transformKey(unEscape(internalPath))];
			return newObj;
		}

		tracking.returnOriginal = true;
		return obj;
	}

	const pathParts = split(internalPath);
	const pathPart = pathParts.shift();
	const transformedPathPart = options.transformKey(unEscape(pathPart));
	let childPart = newObj[transformedPathPart];

	if (!childPart) {
		// No child part available, nothing to unset!
		tracking.returnOriginal = true;
		return obj;
	}

	newObj[transformedPathPart] = unSet(childPart, pathParts.join('.'), options, tracking);

	if (tracking.returnOriginal) {
		return obj;
	}

	return newObj;
};


        error: err => {
          reject(err)
          this.fetching = this.fetching.remove(this.hash(session))
        },


module.exports = function(key) {
    key = normalizeKey(key.split('@').pop());
    return normalized[key] || false;
};


  getUrl() {
    return `http://localhost:${this.port}`
  }


          __(key) {
            self.apos.util.warnDevOnce('old-i18n-req-helper', stripIndent`
              The req.__() and res.__() functions are deprecated and do not localize in A3.
              Use req.t instead.
            `);
            return key;
          }


  commentSchema.statics.updateCommentsByPageId = function(comment, isMarkdown, commentId) {
    const Comment = this;

    return Comment.findOneAndUpdate(
      { _id: commentId },
      { $set: { comment, isMarkdown } },
    );

  };


tooltipText: (c: FormatterContext, d: LineChartDatum) => string;


              groupNames: groups.join(", "),
            }),
            "warning"
          );
        }
      });


function localMessage(msg, source) {
  var output = source.output;
  output.add(formatMessage(msg, output));
}


    resolve({root: require('os').homedir()});
  } else reject('Bad username or password');
});


    Object.keys(data).forEach((key) => {
      obj.add(ctx.next(data[key]));
    });


  constructor(url, options, db, saveTemplate) {
    super(db, saveTemplate);

    if (!saveTemplate) {
      // enable backwards-compatibilty tweaks.
      this.fromHackSession = true;
    }

    const parsedUrl = Url.parse(url);
    this.host = parsedUrl.hostname;
    if (this.fromHackSession) {
      // HackSessionContext.getExternalUiView() apparently ignored any path on the URL. Whoops.
    } else {
      if (parsedUrl.path === "/") {
        // The URL parser says path = "/" for both "http://foo" and "http://foo/". We want to be
        // strict, though.
        this.path = url.endsWith("/") ? "/" : "";
      } else {
        this.path = parsedUrl.path;
      }
    }

    this.port = parsedUrl.port;
    this.protocol = parsedUrl.protocol;
    this.options = options || {};
  }


Languages.get = async function (language, namespace) {
	const data = await fs.promises.readFile(path.join(languagesPath, language, `${namespace}.json`), 'utf8');
	const parsed = JSON.parse(data) || {};
	const result = await plugins.hooks.fire('filter:languages.get', {
		language,
		namespace,
		data: parsed,
	});
	return result.data;
};


tooltipText: (c: FormatterContext, d: BarChartDatum, e: string) => string;


    return next.handle(req).pipe(catchError(err => {
      if (err.status === 401) {
        this.authenticationService.logout();

        if (!req.url.includes('/v3/auth')) {
          // only reload the page if we aren't on the auth pages, this is so that we can display the auth errors.
          const stateUrl = this.router.routerState.snapshot.url;
          const _ = this.router.navigate(['/login'], {queryParams: {next: stateUrl}});
        }
      } else if (err.status >= 500) {


export function applyCommandArgs(configuration: any, argv: string[]) {
	if (!argv || !argv.length) {
		return;
	}

	argv = argv.slice(2);

	const parsedArgv = yargs(argv);
	const argvKeys = Object.keys(parsedArgv);
	if (!argvKeys.length) {
		return;
	}

	debug("Appling command arguments:", parsedArgv);

	if (parsedArgv.config) {
		const configFile = path.resolve(process.cwd(), parsedArgv.config);
		applyConfigFile(configuration, configFile);
	}

	for (const key in parsedArgv) {
		if (!parsedArgv.hasOwnProperty(key)) {
			continue;
		}

		const configKey = key
			.replace(/_/g, ".");

		debug(`Found config value from cmd args '${key}' to '${configKey}'`);

		setDeepProperty(configuration, configKey, parsedArgv[key]);
	}
}


scroll_to_bottom_key: common.has_mac_keyboard()
                ? "Fn + →"
                : "End",
        }),
    );
    $(`.enter_sends_${user_settings.enter_sends}`).show();
    common.adjust_mac_shortcuts(".enter_sends kbd");
}


const renderContent = (content: string | any) => {
  if (typeof content === 'string') {
    return renderHTML(content);
  }
  return content;
};


        return code.includes(hash);
      });
      if (containsMentions) {
        // disable code highlighting if there is a mention in there
        // highlighting will be wrong anyway because this is not valid code
        return code;
      }
      return hljs.highlightAuto(code).value;
    },
  });


function reduce(obj, str) {
    "use strict";
    try {
        if ( typeof str !== "string") {
            return;
        }
        if ( typeof obj !== "object") {
            return;
        }
        return str.split('.').reduce(indexFalse, obj);

    } catch(ex) {
        console.error(ex);
        return;
    }

}


  PageantSock.prototype.end = PageantSock.prototype.destroy = function() {
    this.buffer = null;
    if (this.proc) {
      this.proc.kill();
      this.proc = undefined;
    }
  };


export function stringEncode(string: string) {
    let encodedString = '';
    for (let i = 0; i < string.length; i++) {
        let charCodePointHex = string.charCodeAt(i).toString(16);
        encodedString += `\\u${charCodePointHex}`;
    }
    return encodedString;
}


userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,


  text(notificationName, data) {
    const username = formatUsername(data.display_username);

    let description;
    if (data.topic_title) {
      description = `<span data-topic-id="${this.attrs.topic_id}">${data.topic_title}</span>`;
    } else {
      description = this.description(data);
    }

    return I18n.t(data.message, { description, username });
  },


function showTooltip(target: HTMLElement): () => void {
  const tooltip = document.createElement("div");
  const isHidden = target.classList.contains("hidden");
  if (isHidden) {
    target.classList.remove("hidden");
  }
  tooltip.className = "keyboard-tooltip";
  tooltip.innerHTML = target.getAttribute("data-key") || "";
  document.body.appendChild(tooltip);
  const parentCoords = target.getBoundingClientRect();
  // Padded 10px to the left if there is space or centered otherwise
  const left =
    parentCoords.left +
    Math.min((target.offsetWidth - tooltip.offsetWidth) / 2, 10);
  const top =
    parentCoords.top + (target.offsetHeight - tooltip.offsetHeight) / 2;
  tooltip.style.left = `${left}px`;
  tooltip.style.top = `${top + window.pageYOffset}px`;
  return (): void => {
    tooltip.remove();
    if (isHidden) {
      target.classList.add("hidden");
    }
  };
}


function exportBranch(req, res) {
    const {branchId, type, format, version, taskId} = req.params;
    const branch = becca.getBranch(branchId);

    if (!branch) {
        const message = `Cannot export branch ${branchId} since it does not exist.`;
        log.error(message);

        res.status(500).send(message);
        return;
    }

    const taskContext = new TaskContext(taskId, 'export');

    try {
        if (type === 'subtree' && (format === 'html' || format === 'markdown')) {
            zipExportService.exportToZip(taskContext, branch, format, res);
        }
        else if (type === 'single') {
            singleExportService.exportSingleNote(taskContext, branch, format, res);
        }
        else if (format === 'opml') {
            opmlExportService.exportToOpml(taskContext, branch, version, res);
        }
        else {
            return [404, "Unrecognized export format " + format];
        }
    }
    catch (e) {
        const message = "Export failed with following error: '" + e.message + "'. More details might be in the logs.";
        taskContext.reportError(message);

        log.error(message + e.stack);

        res.status(500).send(message);
    }
}


export function esc<T=unknown>(value: T): T|string;
export function transform(input: string, options?: Options & { format?: 'esm' | 'cjs' }): string;


  ): void => {
    const name = createElement('h2', CLASS_CATEGORY_NAME);
    name.innerHTML =
      this.i18n.categories[category] || defaultI18n.categories[category];
    this.emojis.appendChild(name);
    this.headers.push(name);

    this.emojis.appendChild(
      new EmojiContainer(
        emojis,
        true,
        this.events,
        this.options,
        category !== 'recents'
      ).render()
    );
  };


): { destroy: () => void; update: (t: () => string) => void } {


export function addEmailAddresses(userId: UserId, emailAddress: string, success: UserAcctRespHandler) {
  postJsonSuccess('/-/add-email-address', success, { userId, emailAddress });
}


        next: schemaData => {
          if (
            schemaData &&
            ((schemaData.errors && schemaData.errors.length > 0) ||
              !schemaData.data)
          ) {
            throw new Error(JSON.stringify(schemaData, null, 2))
          }

          if (!schemaData) {
            throw new NoSchemaError(endpoint)
          }

          const schema = this.getSchema(schemaData.data as any)
          const tracingSupported =
            (schemaData.extensions && Boolean(schemaData.extensions.tracing)) ||
            false
          const result: TracingSchemaTuple = {
            schema,
            tracingSupported,
          }
          this.sessionCache.set(this.hash(session), result)
          resolve(result)
          this.fetching = this.fetching.remove(hash)
          const subscription = this.subscriptions.get(hash)
          if (subscription) {
            subscription(result.schema)
          }
        },


const escapedHost = `${host.replace(/\./g, ".")}`

  // Some simple styling options
  const backgroundColor = "#f9f9f9"
  const textColor = "#444444"
  const mainBackgroundColor = "#ffffff"
  const buttonBackgroundColor = "#346df1"
  const buttonBorderColor = "#346df1"
  const buttonTextColor = "#ffffff"

  return `

        ${escapedHost}

        Sign in as ${escapedEmail}

            Sign in

        If you did not request this email you can safely ignore it.

`
}


    async handler(ctx) {
      ctx.logStream.write(`Writing catalog-info.yaml`);
      const { entity } = ctx.input;

      await fs.writeFile(
        resolvePath(ctx.workspacePath, 'catalog-info.yaml'),
        yaml.stringify(entity),
      );
    },


export function logoutClientSideOnly(ps: { goTo?: St, skipSend?: Bo } = {}) {
  Server.deleteTempSessId();

  ReactDispatcher.handleViewAction({
    actionType: actionTypes.Logout
  });

  if (eds.isInEmbeddedCommentsIframe && !ps.skipSend) {
    // Tell the editor iframe that we've logged out.
    // And maybe we'll redirect the embedd*ing* window.  [sso_redir_par_win]
    sendToOtherIframes(['logoutClientSideOnly', ps]);

    // Probaby not needed, since reload() below, but anyway:
    patchTheStore({ setEditorOpen: false });
    const sessWin: MainWin = getMainWin();
    delete sessWin.typs.weakSessionId;
    sessWin.theStore.me = 'TyMLOGDOUT' as any;
  }

  // Disconnect WebSocket so we won't receive data, for this user, after we've
  // logged out: (we reload() below — but the service-worker might stay connected)
  pubsub.disconnectWebSocket();

  if (ps.goTo) {
    if (eds.isInIframe) {
      // Then we'll redirect the parent window instead. [sso_redir_par_win]
    }
    else {
      location.assign(ps.goTo);
    }
    // If that for some reason won't do anything, then make sure we really forget
    // all logged in state anyway:
    setTimeout(function() {
      logW(`location.assign(${ps.goTo}) had no effect? Reloading anyway...`);
      location.reload();
    }, 2000);
  }
  else {
    // Quick fix that reloads the admin page (if one views it) so login dialog appears.
    // But don't do in the goTo if branch — apparently location.reload()
    // cancels location.assign(..) — even if done on the lines after (!).
    location.reload();
  }
}


export function loadEmailAddressesAndLoginMethods(userId: UserId, success: UserAcctRespHandler) {
  get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => {
    success(response);
  });
}


        text: text({ url, host }),
        html: html({ url, host, email }),
      })
    },
    options,
  }
}


function isExternal(url) {
  let match = url.match(
    /^([^:/?#]+:)?(?:\/\/([^/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/
  );
  if (
    typeof match[1] === 'string' &&
    match[1].length > 0 &&
    match[1].toLowerCase() !== location.protocol
  ) {
    return true;
  }
  if (
    typeof match[2] === 'string' &&
    match[2].length > 0 &&
    match[2].replace(
      new RegExp(
        ':(' + { 'http:': 80, 'https:': 443 }[location.protocol] + ')?$'
      ),
      ''
    ) !== location.host
  ) {
    return true;
  }
  return false;
}


          ...(options.role === 'anon' ? {} : {
            user: {
              title: 'System Task',
              role: options.role
            }
          }),
          res: {},
          t(key, options = {}) {
            return self.apos.i18n.i18next.t(key, {
              ...options,
              lng: req.locale
            });
          },
          data: {},
          protocol: 'http',
          get: function (propName) {
            return { Host: 'you-need-to-set-baseUrl-in-app-js.com' }[propName];
          },
          query: {},
          url: '/',
          locale: self.apos.argv.locale || self.apos.modules['@apostrophecms/i18n'].defaultLocale,
          mode: 'published',
          aposNeverLoad: {},
          aposStack: [],
          __(key) {
            self.apos.util.warnDevOnce('old-i18n-req-helper', stripIndent`
              The req.__() and res.__() functions are deprecated and do not localize in A3.
              Use req.t instead.
            `);
            return key;
          }
        };
        addCloneMethod(req);
        req.res.__ = req.__;
        const { role, ..._properties } = options || {};
        Object.assign(req, _properties);
        self.apos.i18n.setPrefixUrls(req);
        return req;

        function addCloneMethod(req) {
          req.clone = (properties = {}) => {
            const _req = {
              ...req,
              ...properties
            };
            self.apos.i18n.setPrefixUrls(_req);
            addCloneMethod(_req);
            return _req;
          };
        }
      },


export function getCurSid12Maybe3(): St | N {  // [ts_authn_modl]
  const store: Store = debiki2.ReactStore.allData();
  const cookieName =
          debiki2.store_isFeatFlagOn(store, 'ffUseNewSid') ? 'TyCoSid123' : 'dwCoSid';
  let sid = getSetCookie(cookieName);
  if (!sid) {
    // Cannot use store.me.mySidPart1 — we might not yet have loaded
    // the current user from the server; store.me might be stale.
    const typs: PageSession = getMainWin().typs;
    // This might not include part 3 (won't, if we're in an embedded comments
    // iframe, and didn't login or resume via a popup win directly against the
    // server so we could access cookie TyCoSid123, which includes part 3).
    sid = typs.weakSessionId;
  }
  return sid || null;
}


        other_senders_count: Math.max(0, all_senders.length - MAX_AVATAR),
        other_sender_names,
        muted,
        topic_muted,
        participated: topic_data.participated,
        full_last_msg_date_time: full_datetime,
    };
}


export function escape(value: unknown, is_attr = false) {
	const str = String(value);

	const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
	pattern.lastIndex = 0;

	let escaped = '';
	let last = 0;

  while (pattern.test(str)) {
    const i = pattern.lastIndex - 1;
    const ch = str[i];
    escaped += str.substring(last, i) + (ch === '&' ? '&' : (ch === '"' ? '"' : '<'));
    last = i + 1;
  }

	return escaped + str.substring(last);
}


  const assigner = ( ...args: any[] ) => {
    console.log( { args } )
    return args.reduce( ( a, b ) => {
      if ( untracker.includes( a ) ) throw new TypeError( `can't convert ${a} to object` )
      if ( useuntrack && untracker.includes( b ) ) return a
      Object.keys( b ).forEach( key => {
        if ( untracker.includes( a[key] ) ) a[key] = b[key]
        else a[key] = delegate.call( this, a[key], b[key] )
      } )
      return a
    } )
  }
  return assigner
}

Assigner.count = ( qty: number, delegate: ( arg: any, ...args: any[] ) => any ) => {
  const assigner = ( ...receives: any[] ) => {
    let group = receives.shift()
    if ( untracker.includes( group ) ) throw new TypeError( `can't convert ${group} to object` )

    let args = receives.splice( 0, qty - 1 )

    while ( args.length ) {
      const keys = []
      for ( const arg of args )
        for ( const key of Object.keys( arg ) )
          if ( !keys.includes( key ) ) keys.push( key )

      for ( const key of keys )
        group[key] = delegate.call( this, group[key], ...args.map( arg => arg[key] ) )

      args = receives.splice( 0, qty - 1 )
    }

    return group
  }
  return assigner
}

declare namespace Assigner {
  export type BasicTypes = string | number | symbol | bigint | object | boolean | Function
  export type Types = BasicTypes | Types[]
  export type TypesWithExclude = BasicTypes | undefined | null | TypesWithExclude[]
}

export { Assigner }


export function store_isFeatFlagOn(store: Store, featureFlag: St): Bo {
  return _.includes(store.siteFeatureFlags, featureFlag) ||
         _.includes(store.serverFeatureFlags, featureFlag);
}


const getValue = (target, prop) => {
  if (prop === 'Math') return Math;
  const { expressions, data } = target;
  if (!expressions.has(prop)) return data.get(prop);
  const expression = expressions.get(prop);
  return expression();
};


export async function recursiveReadDir(dir: string): Promise<string[]> {
  const subdirs = await readdir(dir);
  const files = await Promise.all(
    subdirs.map(async subdir => {
      const res = resolve(dir, subdir);
      return (await stat(res)).isDirectory() ? recursiveReadDir(res) : [res];
    }),
  );
  return files.reduce((a, f) => a.concat(f), []);
}


                    handler: function (grid, rowIndex) {
                        let data = grid.getStore().getAt(rowIndex);
                        pimcore.helpers.deleteConfirm(t('translation'), data.data.key, function () {
                            grid.getStore().removeAt(rowIndex);
                        }.bind(this));
                    }.bind(this)


async function apiCommand<T>(command: string, parameters: {} = {}): Promise<T> {
  const url = "/api"
  const method = "POST"
  const headers = { "Content-Type": "application/json" }
  const data: ApiRequest = { command, parameters }

  const res = await axios.request<CommandResult<T>>({ url, method, headers, data })

  if (res.data.errors) {
    throw res.data.errors
  }

  if (res.data.result === undefined) {
    throw new Error("Empty response from server")
  }

  return res.data.result
}


  PageantSock.prototype.connect = function() {
    this.emit('connect');
  };


export default async function email(
  identifier: string,
  options: InternalOptions<"email">
) {
  const { url, adapter, provider, logger, callbackUrl } = options

  // Generate token
  const token =
    (await provider.generateVerificationToken?.()) ??


    getDownloadUrl(fileId, accessToken) {
        return `${Shopware.Context.api.apiPath}/_action/${this.getApiBasePath()}/` +
            `file/download?fileId=${fileId}&accessToken=${accessToken}`;
    }


  onBannerChange (input: HTMLInputElement) {
    this.bannerfileInput = new ElementRef(input)

    const bannerfile = this.bannerfileInput.nativeElement.files[0]
    if (bannerfile.size > this.maxBannerSize) {
      this.notifier.error('Error', $localize`This image is too large.`)
      return
    }

    const formData = new FormData()
    formData.append('bannerfile', bannerfile)
    this.bannerPopover?.close()
    this.bannerChange.emit(formData)

    if (this.previewImage) {
      this.preview = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(bannerfile))
    }
  }


        { host: serverB.getUrl(), clientAuthToken: serverB.authKey, enterprise: false },
      ],
    })

    garden.events.emit("_test", "foo")

    // Make sure events are flushed
    await streamer.close()

    expect(serverEventBusA.eventLog).to.eql([{ name: "_test", payload: "foo" }])
    expect(serverEventBusB.eventLog).to.eql([{ name: "_test", payload: "foo" }])
  })


            provisionCallback: (user, renew, cb) => {
                cb(null, 'zzz');
            }
        });

        xoauth2.getToken(false, function(err, accessToken) {
            expect(err).to.not.exist;
            expect(accessToken).to.equal('zzz');
            done();
        });
    });


    text(notificationName, data) {
      const username = `<span>${formatUsername(data.display_username)}</span>`;
      let description;
      if (data.topic_title) {
        description = `<span data-topic-id="${this.attrs.topic_id}">${data.topic_title}</span>`;
      } else {
        description = this.description(data);
      }

      return I18n.t(data.message, { description, username });
    },


export default function addStickyControl() {
  extend(DiscussionListState.prototype, 'requestParams', function(params) {
    if (app.current.matches(IndexPage) || app.current.matches(DiscussionPage)) {
      params.include.push('firstPost');
    }
  });

  extend(DiscussionListItem.prototype, 'infoItems', function(items) {
    const discussion = this.attrs.discussion;

    if (discussion.isSticky() && !this.attrs.params.q && !discussion.lastReadPostNumber()) {
      const firstPost = discussion.firstPost();

      if (firstPost) {
        const excerpt = truncate(firstPost.contentPlain(), 175);

        items.add('excerpt', m.trust(excerpt), -100);
      }
    }
  });
}


func cssGogsMinCssMap() (*asset, error) {
	bytes, err := cssGogsMinCssMapBytes()
	if err != nil {
		return nil, err
	}

	info := bindataFileInfo{name: "css/gogs.min.css.map", size: 22926, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)}
	a := &asset{bytes: bytes, info: info, digest: [32]uint8{0x46, 0x89, 0xb2, 0x95, 0x91, 0xfb, 0x5c, 0xda, 0xff, 0x63, 0x54, 0xc5, 0x91, 0xbf, 0x7a, 0x5a, 0xb5, 0x3d, 0xf, 0xf, 0x84, 0x41, 0x2d, 0xc3, 0x18, 0xf5, 0x74, 0xd7, 0xa9, 0x84, 0x70, 0xce}}
	return a, nil
}


  function onconnect() {
    var buf;
    if (isSigning) {
      /*
        byte        SSH2_AGENTC_SIGN_REQUEST
        string      key_blob
        string      data
        uint32      flags
      */
      var p = 9;
      buf = Buffer.allocUnsafe(4 + 1 + 4 + keylen + 4 + datalen + 4);
      writeUInt32BE(buf, buf.length - 4, 0);
      buf[4] = SIGN_REQUEST;
      writeUInt32BE(buf, keylen, 5);
      key.copy(buf, p);
      writeUInt32BE(buf, datalen, p += keylen);
      data.copy(buf, p += 4);
      writeUInt32BE(buf, 0, p += datalen);
      sock.write(buf);
    } else {
      /*
        byte        SSH2_AGENTC_REQUEST_IDENTITIES
      */
      sock.write(Buffer.from([0, 0, 0, 1, REQUEST_IDENTITIES]));
    }
  }


    Object.keys(obj).forEach((propertyName: string) => {
      const propertyMetadata = ConverterService.getPropertyMetadata(properties, propertyName);

      return this.convertProperty(obj, instance, propertyName, propertyMetadata, options);
    });


  handler: function ({log} = {}) {
    if (!this.server.options.pasv_url) {
      return this.reply(502);
    }

    this.connector = new PassiveConnector(this);
    return this.connector.setupServer()
    .then((server) => {
      let address = this.server.options.pasv_url;
      // Allow connecting from local
      if (isLocalIP(this.ip)) {
        address = this.ip;
      }
      const {port} = server.address();
      const host = address.replace(/\./g, ',');
      const portByte1 = port / 256 | 0;
      const portByte2 = port % 256;

      return this.reply(227, `PASV OK (${host},${portByte1},${portByte2})`);
    })
    .catch((err) => {
      log.error(err);
      return this.reply(425);
    });
  },


  constructor (
    private sanitizer: DomSanitizer,
    private serverService: ServerService,
    private notifier: Notifier
  ) { }


function process_request_callback(requestData: RequestData, err?: Error | null, response?: Response) {
    assert(typeof requestData.callback === "function");

    const request = requestData.request;

    if (!response && !err && requestData.msgType !== "CLO") {
        // this case happens when CLO is called and when some pending transactions
        // remains in the queue...
        err = new Error(" Connection has been closed by client , but this transaction cannot be honored");
    }

    if (response && response instanceof ServiceFault) {
        response.responseHeader.stringTable = [...(response.responseHeader.stringTable || [])];
        err = new Error(" serviceResult = " + response.responseHeader.serviceResult.toString());
        //  "  returned by server \n response:" + response.toString() + "\n  request: " + request.toString());
        (err as any).response = response;
        ((err as any).request = request), (response = undefined);
    }

    const theCallbackFunction = requestData.callback;
    /* istanbul ignore next */
    if (!theCallbackFunction) {
        throw new Error("Internal error");
    }
    assert(requestData.msgType === "CLO" || (err && !response) || (!err && response));

    // let set callback to undefined to prevent callback to be called again
    requestData.callback = undefined;

    theCallbackFunction(err || null, !err && response !== null ? response : undefined);
}


module.exports = function(url, options) {
    return fetch(url, options);
};


function reject(req, res, message) {
    log.info(`${req.method} ${req.path} rejected with 401 ${message}`);

    res.status(401).send(message);
}


  closeSocket() {
    if (this.dataSocket) {
      const socket = this.dataSocket;
      this.dataSocket.end(() => socket.destroy());
      this.dataSocket = null;
    }
  }


func cssGogsMinCss() (*asset, error) {
	bytes, err := cssGogsMinCssBytes()
	if err != nil {
		return nil, err
	}

	info := bindataFileInfo{name: "css/gogs.min.css", size: 64378, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)}
	a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xd9, 0x49, 0xa9, 0x99, 0x79, 0x58, 0x26, 0xec, 0xaa, 0x9, 0x5a, 0x24, 0x6, 0x69, 0x2e, 0xe0, 0x3a, 0xb1, 0x53, 0xc4, 0x42, 0x72, 0x4d, 0xe0, 0x67, 0x6d, 0xae, 0x6c, 0x8f, 0xc4, 0x27, 0x27}}
	return a, nil
}


function userBroadcast(msg, source) {
  var sourceMsg = '> ' + msg;
  var name = '{cyan-fg}{bold}' + source.name + '{/}';
  msg = ': ' + msg;
  for (var i = 0; i < users.length; ++i) {
    var user = users[i];
    var output = user.output;
    if (source === user)
      output.add(sourceMsg);
    else
      output.add(formatMessage(name, output) + msg);
  }
}


function parseComplexParam(queryParams: Object, keys: Object, value: any): void {
  let currentParams = queryParams;
  let keysLastIndex = keys.length - 1;
  for (let j = 0; j <= keysLastIndex; j++) {
    let key = keys[j] === '' ? currentParams.length : keys[j];
    if (j < keysLastIndex) {
      // The value has to be an array or a false value
      // It can happen that the value is no array if the key was repeated with traditional style like `list=1&list[]=2`
      let prevValue = !currentParams[key] || typeof currentParams[key] === 'object' ? currentParams[key] : [currentParams[key]];
      currentParams = currentParams[key] = prevValue || (isNaN(keys[j + 1]) ? {} : []);
    } else {
      currentParams = currentParams[key] = value;
    }
  }
}


function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {
    const response = new ResponseClass({
        responseHeader: { serviceResult: statusCode }
    });
    return channel.send_response("MSG", response, message);
}


) => [number, number, string] | undefined;


  constructor (
    private sanitizer: DomSanitizer,
    private serverService: ServerService
  ) {
    this.bytesPipe = new BytesPipe()
    this.maxSizeText = $localize`max size`
  }


            onUpdate: function(username, accessToken) {
                users[username] = accessToken;
            }


          function _ondata(data) {
            bc += data.length;
            if (state === 'secret') {
              // the secret we sent is echoed back to us by cygwin, not sure of
              // the reason for that, but we ignore it nonetheless ...
              if (bc === 16) {
                bc = 0;
                state = 'creds';
                sock.write(credsbuf);
              }
            } else if (state === 'creds') {
              // if this is the first attempt, make sure to gather the valid
              // uid and gid for our next attempt
              if (!isRetrying)
                inbuf.push(data);

              if (bc === 12) {
                sock.removeListener('connect', _onconnect);
                sock.removeListener('data', _ondata);
                sock.removeListener('close', _onclose);
                if (isRetrying) {
                  addSockListeners();
                  sock.emit('connect');
                } else {
                  isRetrying = true;
                  credsbuf = Buffer.concat(inbuf);
                  writeUInt32LE(credsbuf, process.pid, 0);
                  sock.destroy();
                  tryConnect();
                }
              }
            }
          }


const pushVal = (obj, path, val, options = {}) => {
	if (obj === undefined || obj === null || path === undefined) {
		return obj;
	}

	// Clean the path
	path = clean(path);

	const pathParts = split(path);
	const part = pathParts.shift();

	if (pathParts.length) {
		// Generate the path part in the object if it does not already exist
		obj[part] = decouple(obj[part], options) || {};

		// Recurse
		pushVal(obj[part], pathParts.join("."), val, options);
	} else if (part) {
		// We have found the target array, push the value
		obj[part] = decouple(obj[part], options) || [];

		if (!(obj[part] instanceof Array)) {
			throw("Cannot push to a path whose leaf node is not an array!");
		}

		obj[part].push(val);
	} else {
		// We have found the target array, push the value
		obj = decouple(obj, options) || [];

		if (!(obj instanceof Array)) {
			throw("Cannot push to a path whose leaf node is not an array!");
		}

		obj.push(val);
	}

	return decouple(obj, options);
};


  const {type, store = JsonEntityStore.from(type), ...next} = options;
  const propertiesMap = getPropertiesStores(store);

  let keys = Object.keys(src);
  const additionalProperties = propertiesMap.size ? !!store.schema.get("additionalProperties") || options.additionalProperties : true;
  const out: any = new type(src);

  propertiesMap.forEach((propStore) => {
    const key = propStore.parent.schema.getAliasOf(propStore.propertyName) || propStore.propertyName;
    keys = keys.filter((k) => k !== key);

    let value = alterValue(propStore.schema, src[key], {...options, self: src});

    next.type = propStore.computedType;

    if (propStore.schema.hasGenerics) {
      next.nestedGenerics = propStore.schema.nestedGenerics;
    } else if (propStore.schema.isGeneric && options.nestedGenerics) {
      const [genericTypes = [], ...nestedGenerics] = options.nestedGenerics;
      const genericLabels = propStore.parent.schema.genericLabels || [];

      next.type = genericTypes[genericLabels.indexOf(propStore.schema.genericType)] || Object;
      next.nestedGenerics = nestedGenerics;
    }

    value = deserialize(value, {
      ...next,
      collectionType: propStore.collectionType
    });

    if (value !== undefined) {
      out[propStore.propertyName] = value;
    }
  });

  if (additionalProperties) {
    keys.forEach((key) => {
      out[key] = src[key];
    });
  }

  return out;
}


module.exports = async function(tag) {
	if (!tag || ![ 'string', 'number' ].includes(typeof tag)) {
		throw new TypeError(`string was expected, instead got ${tag}`);
	}

	const { message, author, email } = this;

	await Promise.all([
		exec(`git config user.name "${await author}"`),
		exec(`git config user.email "${await email}"`),
	]);
	await exec(`git tag -a ${JSON.stringify(tag)} -m "${await message}"`);
	await exec(`git push origin ${JSON.stringify(`refs/tags/${tag}`)}`);
};


    userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
    totalHours,
  }


function spliceOne(list, index) {
  for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
    list[i] = list[k];
  list.pop();
}


    ctx.prompt(prompt, function retryPrompt(answers) {
      if (answers.length === 0)
        return ctx.reject(['keyboard-interactive']);
      nick = answers[0];
      if (nick.length > MAX_NAME_LEN) {
        return ctx.prompt('That nickname is too long.\n' + PROMPT_NAME,
                          retryPrompt);
      } else if (nick.length === 0) {
        return ctx.prompt('A nickname is required.\n' + PROMPT_NAME,
                          retryPrompt);
      }
      lowered = nick.toLowerCase();
      for (var i = 0; i < users.length; ++i) {
        if (users[i].name.toLowerCase() === lowered) {
          return ctx.prompt('That nickname is already in use.\n' + PROMPT_NAME,
                            retryPrompt);
        }
      }
      name = nick;
      ctx.accept();
    });


    setEntries(entries) {
        if (entries.length === 0) {
            this.emptyList();
            return;
        }

        let htmlToInsert = '';

        for (let timesheet of entries) {
            let label = this.attributes['template']
                .replace('%customer%', timesheet.project.customer.name)
                .replace('%project%', timesheet.project.name)
                .replace('%activity%', timesheet.activity.name);

            htmlToInsert +=
                `<li>` +
                    `<a href="${ this.attributes['href'].replace('000', timesheet.id) }" data-event="kimai.timesheetStart kimai.timesheetUpdate" class="api-link" data-method="PATCH" data-msg-error="timesheet.start.error" data-msg-success="timesheet.start.success">` +
                        `<i class="${ this.attributes['icon'] }"></i> ${ label }` +
                    `</a>` +
                `</li>`;
        }

        this.itemList.innerHTML = htmlToInsert;
    }


          text += `${c.amount(value, a.currency)}<br>`;
        });


template() {
    const { pfx, model, config } = this;
    const label = model.get('label') || '';

    return `

      ${label}

        ${config.iconTagRemove}

    `;
  }


  node.addEventListener("mouseenter", () => {
    const t = tooltip();
    t.innerHTML = getter();
  });


        GraphQLPlayground.init(root, ${JSON.stringify(
          extendedOptions,
          null,
          2,
        )})
      })


export function loadFromGitSync(input: Input): string | never {
  try {
    return execSync(createCommand(input), { encoding: 'utf-8' });
  } catch (error) {
    throw createLoadError(error);
  }
}


  Server.loadMyself((anyMe: Me | NU, stuffForMe?: StuffForMe) => {
    // @ifdef DEBUG
    // Might happen if there was no weakSessionId, and also, no cookie.
    dieIf(!anyMe, 'TyE4032SMH57');
    // @endif
    const newMe = anyMe as Me;
    if (isInSomeEmbCommentsIframe()) {
      // Tell the embedded comments or embedded editor iframe that we just logged in,
      // also include the session id, so Talkyard's script on the embedding page
      // can remember it — because cookies and localstorage in an iframe typically
      // get disabled by tracker blockers (they block 3rd party cookies).
      const mainWin = getMainWin();
      const typs: PageSession = mainWin.typs;
      const weakSessionId = typs.weakSessionId;
      const store: Store = ReactStore.allData();
      const settings: SettingsVisibleClientSide = store.settings;
      const rememberEmbSess =
              settings.rememberEmbSess !== false &&
              // If we got logged in automatically, then logout will be automatic too
              // — could be surprising if we had to click buttons to log out,
              // when we didn't need to do that, to log in.
              typs.sessType !== SessionType.AutoTokenSiteCustomSso;
      if (mainWin !== window) {
        mainWin.theStore.me = _.cloneDeep(newMe);
      }
      sendToOtherIframes([
        'justLoggedIn', { user: newMe, stuffForMe,
              weakSessionId, pubSiteId: eds.pubSiteId,  // [JLGDIN]
              sessionType: null, rememberEmbSess }]);
    }
    setNewMe(newMe, stuffForMe);
    if (afterwardsCallback) {
      afterwardsCallback();
    }
  });


  putComment(comment, isMarkdown, commentId, author) {
    const { pageId, revisionId } = this.getPageContainer().state;

    return this.appContainer.apiPost('/comments.update', {
      commentForm: {
        comment,
        page_id: pageId,
        revision_id: revisionId,
        is_markdown: isMarkdown,
        comment_id: commentId,
        author,
      },
    })
      .then((res) => {
        if (res.ok) {
          return this.retrieveComments();
        }
      });
  }


        html: html({ url, host, email }),
      })
    },


function detailedDataTableMapper(entry) {
  const project = Projects.findOne({ _id: entry.projectId })
  const mapping = [project ? project.name : '',
    dayjs.utc(entry.date).format(getGlobalSetting('dateformat')),
    entry.task,
    projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === entry.userId)?.profile?.name : '']
  if (getGlobalSetting('showCustomFieldsInDetails')) {
    if (CustomFields.find({ classname: 'time_entry' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) {
        mapping.push(entry[customfield[customFieldType]])
      }
    }
    if (CustomFields.find({ classname: 'project' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) {
        mapping.push(project[customfield[customFieldType]])
      }
    }
  }
  if (getGlobalSetting('showCustomerInDetails')) {
    mapping.push(project ? project.customer : '')
  }
  if (getGlobalSetting('useState')) {
    mapping.push(entry.state)
  }
  mapping.push(Number(timeInUserUnit(entry.hours)))
  mapping.push(entry._id)
  return mapping
}


            function check_response(err: Error | null, response: any) {
                should.not.exist(err);
                //xx debugLog(response.toString());
                response.responseHeader.serviceResult.should.eql(StatusCodes.BadInvalidArgument);
            }


function main() {
  try {
    let tag = process.env.GITHUB_REF;
    if (core.getInput('tag')) {
      tag = `refs/tags/${core.getInput('tag')}`;
    }

    exec(`git for-each-ref --format='%(contents)' ${tag}`, (err, stdout) => {
      if (err) {
        core.setFailed(err);
      } else {
        core.setOutput('git-tag-annotation', stdout);
      }
    });
  } catch (error) {
    core.setFailed(error.message);
  }
}


  get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => {
    success(response);
  });


    async showExportDialogEvent({notePath, defaultType}) {
        // each opening of the dialog resets the taskId, so we don't associate it with previous exports anymore
        this.taskId = '';
        this.$exportButton.removeAttr("disabled");

        if (defaultType === 'subtree') {
            this.$subtreeType.prop("checked", true).trigger('change');

            // to show/hide OPML versions
            this.$widget.find("input[name=export-subtree-format]:checked").trigger('change');
        }
        else if (defaultType === 'single') {
            this.$singleType.prop("checked", true).trigger('change');
        }
        else {
            throw new Error("Unrecognized type " + defaultType);
        }

        this.$widget.find(".opml-v2").prop("checked", true); // setting default

        utils.openDialog(this.$widget);

        const {noteId, parentNoteId} = treeService.getNoteIdAndParentIdFromNotePath(notePath);

        this.branchId = await froca.getBranchId(parentNoteId, noteId);

        const noteTitle = await treeService.getNoteTitle(noteId);

        this.$noteTitle.html(noteTitle);
    }


template({ labelInfo, labelHead, iconSync, iconAdd, pfx, ppfx }: any) {
    return `

${labelHead}

              <select id="${pfx}states" data-states></select>

      <input id="${pfx}new" data-input/>

        ${iconAdd}

        ${iconSync}

${labelInfo}:

`;
  }


function applyCommandArgs(configuration, argv) {
    if (!argv || !argv.length) {
        return;
    }
    argv = argv.slice(2);
    const parsedArgv = yargs(argv);
    const argvKeys = Object.keys(parsedArgv);
    if (!argvKeys.length) {
        return;
    }
    debug("Appling command arguments:", parsedArgv);
    if (parsedArgv.config) {
        const configFile = path.resolve(process.cwd(), parsedArgv.config);
        applyConfigFile(configuration, configFile);
    }
    for (const key in parsedArgv) {
        if (!parsedArgv.hasOwnProperty(key)) {
            continue;
        }
        const configKey = key
            .replace(/_/g, ".");
        debug(`Found config value from cmd args '${key}' to '${configKey}'`);
        setDeepProperty(configuration, configKey, parsedArgv[key]);
    }
}


export function buildQueryString(params: Object, traditional?: Boolean): string {
  let pairs = [];
  let keys = Object.keys(params || {}).sort();
  for (let i = 0, len = keys.length; i < len; i++) {
    let key = keys[i];
    pairs = pairs.concat(buildParam(key, params[key], traditional));
  }

  if (pairs.length === 0) {
    return '';
  }

  return pairs.join('&');
}


export default function isSafeRedirect(url: string): boolean {
  if (typeof url !== 'string') {
    throw new TypeError(`Invalid url: ${url}`);
  }

  // Prevent open redirects using the //foo.com format (double forward slash).
  if (/\/\//.test(url)) {
    return false;
  }

  return !/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url);
}


  void addPathParam(String name, String value, boolean encoded) {
    if (relativeUrl == null) {
      // The relative URL is cleared when the first query parameter is set.
      throw new AssertionError();
    }
    relativeUrl = relativeUrl.replace("{" + name + "}", canonicalizeForPath(value, encoded));
  }


  constructor(connection, {root, cwd} = {}) {
    this.connection = connection;
    this.cwd = nodePath.normalize(cwd ? nodePath.join(nodePath.sep, cwd) : nodePath.sep);
    this._root = nodePath.resolve(root || process.cwd());
  }


var cleanUrl = function(url) {
	url = decodeURIComponent(url);
	while(url.indexOf('..').length > 0) { url = url.replace('..', ''); }
	return url;
};


    Object.keys(data).forEach((key) => {
      obj.set(key, ctx.next(data[key]) as T);
    });


export function ffprobe(file: string): Promise<IFfprobe> {
  return new Promise<IFfprobe>((resolve, reject) => {
    if (!file) throw new Error('no file provided')

    stat(file, (err, stats) => {
      if (err) throw err

      exec('ffprobe -v quiet -print_format json -show_format -show_streams ' + file, (error, stdout, stderr) => {
        if (error) return reject(error)
        if (!stdout) return reject(new Error("can't probe file " + file))

        let ffprobed: IFfprobe

        try {
          ffprobed = JSON.parse(stdout)
        } catch (err) {
          return reject(err)
        }

        for (let i = 0; i < ffprobed.streams.length; i++) {
          if (ffprobed.streams[i].codec_type === 'video') ffprobed.video = ffprobed.streams[i] as IVideoStream
          if (ffprobed.streams[i].codec_type === 'audio' && ffprobed.streams[i].channels)
            ffprobed.audio = ffprobed.streams[i] as IAudioStream
        }
        resolve(ffprobed)
      })
    })
  })
}


module.exports = async function(path) {
	if (!path || typeof path !== 'string') {
		throw new TypeError(`string was expected, instead got ${path}`);
	}

	const absolute = resolve(path);

	if (!(await exist(absolute))) {
		throw new Error(`Could not find file at path "${absolute}"`);
	}

	const ts = await exec(`git log -1 --format="%at" -- ${path}`);

	return new Date(Number(ts) * 1000);
};


): { destroy: () => void; update: (t: () => string) => void } {


  PageantSock.prototype.write = function(buf) {
    if (this.buffer === null)
      this.buffer = buf;
    else {
      this.buffer = Buffer.concat([this.buffer, buf],
                                  this.buffer.length + buf.length);
    }
    // Wait for at least all length bytes
    if (this.buffer.length < 4)
      return;

    var len = readUInt32BE(this.buffer, 0);
    // Make sure we have a full message before querying pageant
    if ((this.buffer.length - 4) < len)
      return;

    buf = this.buffer.slice(0, 4 + len);
    if (this.buffer.length > (4 + len))
      this.buffer = this.buffer.slice(4 + len);
    else
      this.buffer = null;

    var self = this;
    var proc;
    var hadError = false;
    proc = this.proc = cp.spawn(EXEPATH, [ buf.length ]);
    proc.stdout.on('data', function(data) {
      self.emit('data', data);
    });
    proc.once('error', function(err) {
      if (!hadError) {
        hadError = true;
        self.emit('error', err);
      }
    });
    proc.once('close', function(code) {
      self.proc = undefined;
      if (ERROR[code] && !hadError) {
        hadError = true;
        self.emit('error', ERROR[code]);
      }
      self.emit('close', hadError);
    });
    proc.stdin.end(buf);
  };


    this.serversUpdatedListener = ({ servers }) => {
      // Update status log line with new `garden dashboard` server, if any
      for (const { host, command } of servers) {
        if (command === "dashboard") {
          this.showUrl(host)
          return
        }
      }

      // No active explicit dashboard processes, show own URL instead
      this.showUrl(this.getUrl())
    }


export function setDeepProperty(obj: any, propertyPath: string, value: any): void {
	const a = splitPath(propertyPath);
	const n = a.length;

	for (let i = 0; i < n - 1; i++) {
		const k = a[i];

		if (!(k in obj)) {
			obj[k] = {};
		}
		obj = obj[k];
	}

	obj[a[n - 1]] = value;
	return;
}


    constructor(
        private readonly ptarmiganService: PtarmiganService,
        private readonly bitcoinService: BitcoinService,
        private readonly cacheService: CacheService,
        private readonly invoicesGateway: InvoicesGateway
    ) {
    }


  }) => Awaitable<void>
  /**
   * By default, we are generating a random verification token.
   * You can make it predictable or modify it as you like with this method.
   * @example
   * ```js
   *  Providers.Email({
   *    async generateVerificationToken() {
   *      return "ABC123"
   *    }
   *  })
   * ```
   * [Documentation](https://next-auth.js.org/providers/email#customising-the-verification-token)
   */
  generateVerificationToken?: () => Awaitable<string>


          [req.locale]: self.getBrowserBundles(req.locale)
        };
        if (req.locale !== self.defaultLocale) {
          i18n[self.defaultLocale] = self.getBrowserBundles(self.defaultLocale);
        }
        const result = {
          i18n,
          locale: req.locale,
          defaultLocale: self.defaultLocale,
          locales: self.locales,
          debug: self.debug,
          show: self.show,
          action: self.action,
          crossDomainClipboard: req.session.aposCrossDomainClipboard
        };
        if (req.session.aposCrossDomainClipboard) {
          req.session.aposCrossDomainClipboard = null;
        }
        return result;
      },


  text: () => string
): { destroy: () => void; update: (t: () => string) => void } {


        servers: servers.map((p) => ({ command: p.command!, host: p.serverHost! })),
      })


function formatMessage(msg, output) {
  var output = output;
  output.parseTags = true;
  msg = output._parseTags(msg);
  output.parseTags = false;
  return msg;
}


export declare function applyCommandArgs(configuration: any, argv: string[]): void;
export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void;


function detailedDataTableMapper(entry) {
  const project = Projects.findOne({ _id: entry.projectId })
  const mapping = [project ? project.name : '',
    dayjs.utc(entry.date).format(getGlobalSetting('dateformat')),
    entry.task,
    projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === entry.userId)?.profile?.name : '']
  if (getGlobalSetting('showCustomFieldsInDetails')) {
    if (CustomFields.find({ classname: 'time_entry' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) {
        mapping.push(entry[customfield[customFieldType]])
      }
    }
    if (CustomFields.find({ classname: 'project' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) {
        mapping.push(project[customfield[customFieldType]])
      }
    }
  }
  if (getGlobalSetting('showCustomerInDetails')) {
    mapping.push(project ? project.customer : '')
  }
  if (getGlobalSetting('useState')) {
    mapping.push(entry.state)
  }
  mapping.push(Number(timeInUserUnit(entry.hours)))
  mapping.push(entry._id)
  return mapping
}


export function render_markdown_timestamp(time: number | Date): {
    text: string;
    tooltip_content: string;
} {
    const hourformat = user_settings.twenty_four_hour_time ? "HH:mm" : "h:mm a";
    const timestring = format(time, "E, MMM d yyyy, " + hourformat);

    const tz_offset_str = get_tz_with_UTC_offset(time);
    const tooltip_html_content = render_markdown_time_tooltip({tz_offset_str});

    return {
        text: timestring,
        tooltip_content: tooltip_html_content,
    };
}


declare function getSetCookie(cookieName: string, value?: string, options?: any): string;

// backw compat, later, do once per file instead (don't want a global 'r').
//
// ReactDOMFactories looks like:
//
// var ReactDOMFactories = {
//   a: createDOMFactory('a'),
//   abbr: ...
//
// function createDOMFactory(type) {
//   var factory = React.createElement.bind(null, type);
//   factory.type = type; // makes:  `<Foo />.type === Foo`  work
//   return factory;
//  };
//
// and React.createElement(type: keyof ReactHTML, props, ...children) returns:
//   DetailedReactHTMLElement<P, T>
//
const r: { [elmName: string]: (props?: any, ...children) => RElm } = ReactDOMFactories;


export function escape<T>(input: T): T extends SafeValue ? T['value'] : T {
  return typeof input === 'string'
    ? string.escapeHTML(input)
    : input instanceof SafeValue
    ? input.value
    : input
}


export const initAuth0: InitAuth0 = (params) => {
  const { baseConfig, nextConfig } = getConfig(params);

  // Init base layer (with base config)
  const getClient = clientFactory(baseConfig, { name: 'nextjs-auth0', version });
  const transientStore = new TransientStore(baseConfig);
  const cookieStore = new CookieStore(baseConfig);
  const sessionCache = new SessionCache(baseConfig, cookieStore);
  const baseHandleLogin = baseLoginHandler(baseConfig, getClient, transientStore);
  const baseHandleLogout = baseLogoutHandler(baseConfig, getClient, sessionCache);
  const baseHandleCallback = baseCallbackHandler(baseConfig, getClient, sessionCache, transientStore);

  // Init Next layer (with next config)
  const getSession = sessionFactory(sessionCache);
  const getAccessToken = accessTokenFactory(nextConfig, getClient, sessionCache);
  const withApiAuthRequired = withApiAuthRequiredFactory(sessionCache);
  const withPageAuthRequired = withPageAuthRequiredFactory(nextConfig.routes.login, getSession);
  const handleLogin = loginHandler(baseHandleLogin, nextConfig);
  const handleLogout = logoutHandler(baseHandleLogout);
  const handleCallback = callbackHandler(baseHandleCallback, nextConfig);
  const handleProfile = profileHandler(getClient, getAccessToken, sessionCache);
  const handleAuth = handlerFactory({ handleLogin, handleLogout, handleCallback, handleProfile });

  return {
    getSession,
    getAccessToken,
    withApiAuthRequired,
    withPageAuthRequired,
    handleLogin,
    handleLogout,
    handleCallback,
    handleProfile,
    handleAuth
  };
};


  api.update = async function(req, res) {
    const { commentForm } = req.body;

    const pageId = commentForm.page_id;
    const comment = commentForm.comment;
    const isMarkdown = commentForm.is_markdown;
    const commentId = commentForm.comment_id;
    const author = commentForm.author;

    if (comment === '') {
      return res.json(ApiResponse.error('Comment text is required'));
    }

    if (commentId == null) {
      return res.json(ApiResponse.error('\'comment_id\' is undefined'));
    }

    if (author !== req.user.username) {
      return res.json(ApiResponse.error('Only the author can edit'));
    }

    // check whether accessible
    const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
    if (!isAccessible) {
      return res.json(ApiResponse.error('Current user is not accessible to this page.'));
    }

    let updatedComment;
    try {
      updatedComment = await Comment.updateCommentsByPageId(comment, isMarkdown, commentId);
    }
    catch (err) {
      logger.error(err);
      return res.json(ApiResponse.error(err));
    }

    res.json(ApiResponse.success({ comment: updatedComment }));

    // process notification if needed
  };


const createCommand = ({ ref, path }: Input) => {
  return `git show ${ref}:${path}`;
};


  async convert(input, options) {
    this[_validate]();

    options = this[_parseOptions](options);

    const output = await this[_convert](input, options);

    return output;
  }


export function orderLinks<T extends NameAndType>(links: T[]) {
  const [provided, unknown] = partition<T>(links, isProvided);
  return [
    ...sortBy(provided, link => PROVIDED_TYPES.indexOf(link.type)),
    ...sortBy(unknown, link => link.name!.toLowerCase())
  ];
}


    parse(cookieStr) {
        let cookie = {};

        (cookieStr || '')
            .toString()
            .split(';')
            .forEach(cookiePart => {
                let valueParts = cookiePart.split('=');
                let key = valueParts
                    .shift()
                    .trim()
                    .toLowerCase();
                let value = valueParts.join('=').trim();
                let domain;

                if (!key) {
                    // skip empty parts
                    return;
                }

                switch (key) {
                    case 'expires':
                        value = new Date(value);
                        // ignore date if can not parse it
                        if (value.toString() !== 'Invalid Date') {
                            cookie.expires = value;
                        }
                        break;

                    case 'path':
                        cookie.path = value;
                        break;

                    case 'domain':
                        domain = value.toLowerCase();
                        if (domain.length && domain.charAt(0) !== '.') {
                            domain = '.' + domain; // ensure preceeding dot for user set domains
                        }
                        cookie.domain = domain;
                        break;

                    case 'max-age':
                        cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000);
                        break;

                    case 'secure':
                        cookie.secure = true;
                        break;

                    case 'httponly':
                        cookie.httponly = true;
                        break;

                    default:
                        if (!cookie.name) {
                            cookie.name = key;
                            cookie.value = value;
                        }
                }
            });

        return cookie;
    }


      return `1 ${base} = ${c.amount(d.value, quote)}<em>${day(d.date)}</em>`;
    },
  });
}


export function setupCleanupOnExit(cssPath: string) {
  if (!hasSetupCleanupOnExit){
    process.on('SIGINT', () => {
      console.log('Exiting, running CSS cleanup');

      exec(`rm -r ${cssPath}`, function(error) {
        if (error) {
          console.error(error);
          process.exit(1);
        }

        console.log('Deleted CSS files');
      });
    });

    hasSetupCleanupOnExit = true;
  }
}


        getDownloadUrl(file) {
            return this.importExport.getDownloadUrl(file.id, file.accessToken);
        },


const getCdnMarkup = ({ version, cdnUrl = '//cdn.jsdelivr.net/npm', faviconUrl }) => `
    <link rel="stylesheet" href="${cdnUrl}/graphql-playground-react${


export function escapeCommentText(value: string): string {
  return value.replace(END_COMMENT, END_COMMENT_ESCAPED);
}


function checkCredentials(req, res, next) {
    if (!sqlInit.isDbInitialized()) {
        res.status(400).send('Database is not initialized yet.');
        return;
    }

    if (!passwordService.isPasswordSet()) {
        res.status(400).send('Password has not been set yet. Please set a password and repeat the action');
        return;
    }

    const header = req.headers['trilium-cred'] || '';
    const auth = new Buffer.from(header, 'base64').toString();
    const [username, password] = auth.split(/:/);

    // username is ignored

    if (!passwordEncryptionService.verifyPassword(password)) {
        res.status(401).send('Incorrect password');
    }
    else {
        next();
    }
}


                message: new MockBuilder(
                    {
                        from: 'test@valid.sender',
                        to: 'test@valid.recipient'
                    },
                    'message\r\nline 2'
                )
            },
            function(err, data) {
                expect(err).to.not.exist;
                expect(data.messageId).to.equal('<test>');
                expect(output).to.equal('message\nline 2');
                client._spawn.restore();
                done();
            }
        );
    });


function get(target, path) {
    "use strict";
    try {
        return reduce(target, path);
    } catch(ex) {
        console.error(ex);
        return;
    }
}


export default function handleLoginFactory(handler: BaseHandleLogin, nextConfig: NextConfig): HandleLogin {
  return async (req, res, options = {}): Promise<void> => {
    try {
      assertReqRes(req, res);
      if (req.query.returnTo) {
        const returnTo = Array.isArray(req.query.returnTo) ? req.query.returnTo[0] : req.query.returnTo;

        if (!isSafeRedirect(returnTo)) {
          throw new Error('Invalid value provided for returnTo, must be a relative url');
        }

        options = { ...options, returnTo };
      }
      if (nextConfig.organization) {
        options = {
          ...options,
          authorizationParams: { organization: nextConfig.organization, ...options.authorizationParams }
        };
      }

      return await handler(req, res, options);
    } catch (e) {
      throw new HandlerError(e);
    }
  };
}


  formatMessage() {
    if (this.isATweet) {
      const withUserName = this.message.replace(
        TWITTER_USERNAME_REGEX,
        TWITTER_USERNAME_REPLACEMENT
      );
      const withHash = withUserName.replace(
        TWITTER_HASH_REGEX,
        TWITTER_HASH_REPLACEMENT
      );
      const markedDownOutput = marked(withHash);
      return markedDownOutput;
    }
    return marked(this.message, { breaks: true, gfm: true });
  }


export function cleanObject(obj: any): any {
  return Object.entries(obj).reduce(
    (obj, [key, value]) =>
      value === undefined
        ? obj
        : {
            ...obj,
            [key]: value
          },
    {}
  );
}


export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void;
export declare function getDeepProperty(obj: any, propertyPath: string): any;


    userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
    totalHours,
  }


function escapeShellArg(arg) {
  return arg.replace(/'/g, `'\\''`);
}


function lazyLoadCustomEmoji(element: HTMLElement): void {
  const img = createElement('img', CLASS_CUSTOM_EMOJI) as HTMLImageElement;

  if (element.dataset.emoji) {
    img.src = element.dataset.emoji;
    element.innerText = '';
    element.appendChild(img);
  }
}


      clip: Object.assign({ x: 0, y: 0 }, dimensions)
    }, provider.getScreenshotOptions(options)));

    return output;
  }


function detailedDataTableMapper(entry) {
  const project = Projects.findOne({ _id: entry.projectId })
  const mapping = [project ? project.name : '',
    dayjs.utc(entry.date).format(getGlobalSetting('dateformat')),
    entry.task,
    projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === entry.userId)?.profile?.name : '']
  if (getGlobalSetting('showCustomFieldsInDetails')) {
    if (CustomFields.find({ classname: 'time_entry' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) {
        mapping.push(entry[customfield[customFieldType]])
      }
    }
    if (CustomFields.find({ classname: 'project' }).count() > 0) {
      for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) {
        mapping.push(project[customfield[customFieldType]])
      }
    }
  }
  if (getGlobalSetting('showCustomerInDetails')) {
    mapping.push(project ? project.customer : '')
  }
  if (getGlobalSetting('useState')) {
    mapping.push(entry.state)
  }
  mapping.push(Number(timeInUserUnit(entry.hours)))
  mapping.push(entry._id)
  return mapping
}