(() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
var __esm = (fn, res) => function() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from == "object" || typeof from == "function")
for (let key of __getOwnPropNames(from))
!__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
mod
));
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
var init_process = __esm({
"node_modules/esbuild-plugins-node-modules-polyfill/globals/process.js"() {
}
});
var require_dayjs_min = __commonJS({
"node_modules/dayjs/dayjs.min.js"(exports3, module2) {
init_process();
(function(t, e) {
typeof exports3 == "object" && typeof module2 != "undefined" ? module2.exports = e() : typeof define == "function" && define.amd ? define(e) : (t = typeof globalThis != "undefined" ? globalThis : t || self).dayjs = e();
})(exports3, function() {
"use strict";
var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t2) {
var e2 = ["th", "st", "nd", "rd"], n2 = t2 % 100;
return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
} }, m = function(t2, e2, n2) {
var r2 = String(t2);
return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
}, v = { s: m, z: function(t2) {
var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
}, m: function t2(e2, n2) {
if (e2.date() < n2.date()) return -t2(n2, e2);
var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
}, a: function(t2) {
return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
}, p: function(t2) {
return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i, ms: r, Q: f }[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
}, u: function(t2) {
return t2 === void 0;
} }, g = "en", D = {};
D[g] = M;
var p = "$isDayjsObject", S = function(t2) {
return t2 instanceof _ || !(!t2 || !t2[p]);
}, w = function t2(e2, n2, r2) {
var i2;
if (!e2) return g;
if (typeof e2 == "string") {
var s2 = e2.toLowerCase();
D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
var u2 = e2.split("-");
if (!i2 && u2.length > 1) return t2(u2[0]);
} else {
var a2 = e2.name;
D[a2] = e2, i2 = a2;
}
return !r2 && i2 && (g = i2), i2 || !r2 && g;
}, O = function(t2, e2) {
if (S(t2)) return t2.clone();
var n2 = typeof e2 == "object" ? e2 : {};
return n2.date = t2, n2.args = arguments, new _(n2);
}, b = v;
b.l = w, b.i = S, b.w = function(t2, e2) {
return O(t2, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset });
};
var _ = function() {
function M2(t2) {
this.$L = w(t2.locale, null, !0), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = !0;
}
var m2 = M2.prototype;
return m2.parse = function(t2) {
this.$d = function(t3) {
var e2 = t3.date, n2 = t3.utc;
if (e2 === null) return new Date(NaN);
if (b.u(e2)) return new Date();
if (e2 instanceof Date) return new Date(e2);
if (typeof e2 == "string" && !/Z$/i.test(e2)) {
var r2 = e2.match($);
if (r2) {
var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
}
}
return new Date(e2);
}(t2), this.init();
}, m2.init = function() {
var t2 = this.$d;
this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
}, m2.$utils = function() {
return b;
}, m2.isValid = function() {
return this.$d.toString() !== l;
}, m2.isSame = function(t2, e2) {
var n2 = O(t2);
return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
}, m2.isAfter = function(t2, e2) {
return O(t2) < this.startOf(e2);
}, m2.isBefore = function(t2, e2) {
return this.endOf(e2) < O(t2);
}, m2.$g = function(t2, e2, n2) {
return b.u(t2) ? this[e2] : this.set(n2, t2);
}, m2.unix = function() {
return Math.floor(this.valueOf() / 1e3);
}, m2.valueOf = function() {
return this.$d.getTime();
}, m2.startOf = function(t2, e2) {
var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
return r2 ? i2 : i2.endOf(a);
}, $2 = function(t3, e3) {
return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2);
}, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
switch (f2) {
case h:
return r2 ? l2(1, 0) : l2(31, 11);
case c:
return r2 ? l2(1, M3) : l2(0, M3 + 1);
case o:
var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
case a:
case d:
return $2(v2 + "Hours", 0);
case u:
return $2(v2 + "Minutes", 1);
case s:
return $2(v2 + "Seconds", 2);
case i:
return $2(v2 + "Milliseconds", 3);
default:
return this.clone();
}
}, m2.endOf = function(t2) {
return this.startOf(t2, !1);
}, m2.$set = function(t2, e2) {
var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
if (o2 === c || o2 === h) {
var y2 = this.clone().set(d, 1);
y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
} else l2 && this.$d[l2]($2);
return this.init(), this;
}, m2.set = function(t2, e2) {
return this.clone().$set(t2, e2);
}, m2.get = function(t2) {
return this[b.p(t2)]();
}, m2.add = function(r2, f2) {
var d2, l2 = this;
r2 = Number(r2);
var $2 = b.p(f2), y2 = function(t2) {
var e2 = O(l2);
return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
};
if ($2 === c) return this.set(c, this.$M + r2);
if ($2 === h) return this.set(h, this.$y + r2);
if ($2 === a) return y2(1);
if ($2 === o) return y2(7);
var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
return b.w(m3, this);
}, m2.subtract = function(t2, e2) {
return this.add(-1 * t2, e2);
}, m2.format = function(t2) {
var e2 = this, n2 = this.$locale();
if (!this.isValid()) return n2.invalidDate || l;
var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i3, s3) {
return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
}, d2 = function(t3) {
return b.s(s2 % 12 || 12, t3, "0");
}, $2 = f2 || function(t3, e3, n3) {
var r3 = t3 < 12 ? "AM" : "PM";
return n3 ? r3.toLowerCase() : r3;
};
return r2.replace(y, function(t3, r3) {
return r3 || function(t4) {
switch (t4) {
case "YY":
return String(e2.$y).slice(-2);
case "YYYY":
return b.s(e2.$y, 4, "0");
case "M":
return a2 + 1;
case "MM":
return b.s(a2 + 1, 2, "0");
case "MMM":
return h2(n2.monthsShort, a2, c2, 3);
case "MMMM":
return h2(c2, a2);
case "D":
return e2.$D;
case "DD":
return b.s(e2.$D, 2, "0");
case "d":
return String(e2.$W);
case "dd":
return h2(n2.weekdaysMin, e2.$W, o2, 2);
case "ddd":
return h2(n2.weekdaysShort, e2.$W, o2, 3);
case "dddd":
return o2[e2.$W];
case "H":
return String(s2);
case "HH":
return b.s(s2, 2, "0");
case "h":
return d2(1);
case "hh":
return d2(2);
case "a":
return $2(s2, u2, !0);
case "A":
return $2(s2, u2, !1);
case "m":
return String(u2);
case "mm":
return b.s(u2, 2, "0");
case "s":
return String(e2.$s);
case "ss":
return b.s(e2.$s, 2, "0");
case "SSS":
return b.s(e2.$ms, 3, "0");
case "Z":
return i2;
}
return null;
}(t3) || i2.replace(":", "");
});
}, m2.utcOffset = function() {
return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
}, m2.diff = function(r2, d2, l2) {
var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
return b.m(y2, m3);
};
switch (M3) {
case h:
$2 = D2() / 12;
break;
case c:
$2 = D2();
break;
case f:
$2 = D2() / 3;
break;
case o:
$2 = (g2 - v2) / 6048e5;
break;
case a:
$2 = (g2 - v2) / 864e5;
break;
case u:
$2 = g2 / n;
break;
case s:
$2 = g2 / e;
break;
case i:
$2 = g2 / t;
break;
default:
$2 = g2;
}
return l2 ? $2 : b.a($2);
}, m2.daysInMonth = function() {
return this.endOf(c).$D;
}, m2.$locale = function() {
return D[this.$L];
}, m2.locale = function(t2, e2) {
if (!t2) return this.$L;
var n2 = this.clone(), r2 = w(t2, e2, !0);
return r2 && (n2.$L = r2), n2;
}, m2.clone = function() {
return b.w(this.$d, this);
}, m2.toDate = function() {
return new Date(this.valueOf());
}, m2.toJSON = function() {
return this.isValid() ? this.toISOString() : null;
}, m2.toISOString = function() {
return this.$d.toISOString();
}, m2.toString = function() {
return this.$d.toUTCString();
}, M2;
}(), k = _.prototype;
return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach(function(t2) {
k[t2[1]] = function(e2) {
return this.$g(e2, t2[0], t2[1]);
};
}), O.extend = function(t2, e2) {
return t2.$i || (t2(e2, _, O), t2.$i = !0), O;
}, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
return O(1e3 * t2);
}, O.en = D[g], O.Ls = D, O.p = {}, O;
});
}
});
init_process();
var chat_default = `<html lang="en">
<head>
<title>Copilot Chat</title>
<link rel="icon" href="data:,">
</head>
<body>
<div class="app-container"></div>
<script>(() => {
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
var __esm = (fn, res) => function() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
// node_modules/esbuild-plugins-node-modules-polyfill/globals/process.js
var init_process = __esm({
"node_modules/esbuild-plugins-node-modules-polyfill/globals/process.js"() {
}
});
// src-copilot/embed/chat.jsx
init_process();
// common-utils/dynamic-import-esm.js
init_process();
// package.json
var package_default = {
name: "amplenote-plugin-dev-env",
author: "debajandhar12",
version: "1.0.0",
type: "module",
repository: "https://github.com/debanjandhar12/my-amplenote-plugins-v2",
dependencies: {
"@ai-sdk/anthropic": "1.2.10",
"@ai-sdk/fireworks": "0.2.13",
"@ai-sdk/google": "1.2.14",
"@ai-sdk/groq": "1.2.8",
"@ai-sdk/openai": "1.3.21",
"@assistant-ui/react": "0.7.65",
"@assistant-ui/react-markdown": "0.7.16",
"@debanjandhar12/markmap-lib": "0.17.0-mod.3",
"@debanjandhar12/markmap-toolbar": "0.17.0-mod.3",
"@debanjandhar12/markmap-view": "0.17.0-mod.3",
"@duckdb/duckdb-wasm": "1.31.0",
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@huggingface/transformers": "3.7.3",
"@omnivore-app/api": "^1.0.4",
"@pinecone-database/pinecone": "4.1.0",
"@radix-ui/react-icons": "1.3.2",
"@radix-ui/themes": "3.2.0",
"@yiuayiu/telegram-markdown-escape": "^0.0.2-1",
ai: "4.3.13",
"apache-arrow": "^20.0.0",
"async-mutex": "0.5.0",
"chart.js": "^4.4.3",
"d3-svg-to-png": "^0.3.1",
"date-fns": "^3.6.0",
dayjs: "1.11.13",
"easy-web-worker": "7.0.2",
"emoji-mart": "^5.6.0",
"fast-dotproduct": "1.3.0",
fflate: "0.8.2",
fparser: "^3.1.0",
"fuse.js": "7.0.0",
idb: "8.0.2",
"iconv-lite": "^0.6.3",
"lodash-es": "^4.17.21",
luxon: "^3.4.4",
"markdown-it": "^14.1.0",
"mdast-util-to-string": "4.0.0",
"my-ample-plugin-external": "1.0.29",
nanoid: "^5.0.7",
"ollama-ai-provider": "1.2.0",
"parquetjs-lite": "^0.8.7",
react: "18.2.0",
"react-dom": "18.2.0",
"react-error-boundary": "5.0.0",
"react-string-diff": "0.2.0",
"react-virtuoso": "4.12.5",
"react-window": "1.8.11",
"remark-frontmatter": "5.0.0",
"remark-gfm": "4.0.0",
"remark-parse": "11.0.0",
"scheduler-polyfill": "1.3.0",
stopword: "3.1.5",
tributejs: "5.1.3",
unified: "11.0.0",
"unist-util-visit": "5.0.0",
"unist-util-visit-parents": "6.0.1",
"vosk-browser": "0.0.8",
zod: "3.23.8"
},
devDependencies: {
"@huggingface/transformers": "3.2.4",
"@playwright/test": "^1.49.1",
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^29.5.0",
"core-js": "^3.38.1",
cors: "^2.8.5",
"cross-fetch": "^4.0.0",
dotenv: "^16.0.3",
esbuild: "0.25.3",
"esbuild-jest2": "0.6.7",
"esbuild-plugin-external-global": "^1.0.1",
"esbuild-plugins-node-modules-polyfill": "1.7.0",
express: "^5.0.1",
"isomorphic-fetch": "^3.0.0",
jest: "^29.5.0",
jsdom: "^24.1.0",
"make-synchronous": "^1.0.0",
"node-fetch": "4.0.0-beta.4",
"p-retry": "6.2.1",
playwright: "^1.49.1",
sinon: "21.0.0",
"jest-allure2-reporter": "2.2.6",
"allure-commandline": "^2.32.0",
open: "^10.2.0"
},
scripts: {
test: "jest --testPathPattern=src-copilot",
"test:watch": "jest --testPathPattern=src-copilot --watch",
"allure:serve": \`npx allure generate --single-file ./allure/results --clean -o ./allure/report && node --input-type=module -e "import('open').then(o => o.default('./allure/report/index.html'))"\`,
"build:prod": "NODE_ENV=production node esbuild.js $(pwd)/src-copilot",
"build:dev": "node esbuild.js $(pwd)/src-copilot --watch --server"
}
};
// common-utils/dynamic-import-esm.js
var dynamicImportExternalPluginBundle = async (fileName) => {
let packageVersion = package_default.dependencies["my-ample-plugin-external"], pkg = \`my-ample-plugin-external/dist/\${fileName}\`, cdnList = getCDNList(pkg), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, packageVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 1e3)), abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return import(url).then((module2) => {
if (abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return { module: module2, url };
}).catch((e) => {
throw console.warn(\`Failed to import \${pkg} from \${cdn}: \${e.message}\`), e;
});
});
try {
let result = await Promise.any(importPromises);
abortController.abort();
let module2 = result.module;
if (!module2.versions)
throw new Error(\`Failed to import module: \${fileName}. Returned bundle does not have version property.\`);
for (let [key, value] of Object.entries(module2.versions))
if (value !== package_default.dependencies[key])
throw new Error(\`Failed to import module: \${fileName}. Version mismatch for \${key} (expected: \${package_default.dependencies[key]}, actual: \${value})\`);
return console.log(\`Imported \${pkg}@\${packageVersion} from \${result.url}\`), module2.default;
} catch {
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
}
};
var dynamicImportESM = async (pkg, pkgVersion = null) => {
let cdnList = getCDNList(pkg), resolvedVersion = resolvePackageVersion(pkg, pkgVersion), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, resolvedVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 2500)), abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return import(url).then((module2) => {
if (abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return { module: module2, url };
}).catch((e) => {
throw console.warn(\`Failed to import \${pkg} from \${cdn}: \${e.message}\`), e;
});
});
try {
let result = await Promise.any(importPromises);
return abortController.abort(), console.log(\`Imported \${pkg}@\${resolvedVersion} from \${result.url}\`), result.module;
} catch {
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
}
};
function getBasePackage(pkg) {
if (pkg.startsWith("@")) {
let [scope, name] = pkg.split("/");
return \`\${scope}/\${name}\`;
}
return pkg.split("/")[0];
}
function resolvePackageVersion(pkg, pkgVersion) {
let basePkg = getBasePackage(pkg), version = pkgVersion || package_default.dependencies[basePkg] || package_default.devDependencies[basePkg] || "latest";
return version.startsWith("^") || version.startsWith("~") ? version.substring(1) : version;
}
function getPackageFolderString(pkg) {
let folders = [];
return pkg.startsWith("@") ? [, , ...folders] = pkg.split("/") : [, ...folders] = pkg.split("/"), folders && folders.length > 0 ? \`/\${folders.join("/")}\` : "";
}
function getCDNList(pkg) {
let basePkg = getBasePackage(pkg);
return basePkg.includes("react") || basePkg.includes("radix") || basePkg.includes("build") || basePkg.includes("dotenv") ? ["https://esm.sh/", "https://legacy.esm.sh/"] : ["https://cdn.jsdelivr.net/npm/", "https://esm.sh/", "https://unpkg.com/"];
}
function buildCDNUrl(cdn, pkg, version) {
let basePkg = getBasePackage(pkg), versionString = version !== "latest" ? \`@\${version}\` : "", folderString = getPackageFolderString(pkg), url = new URL(\`\${cdn}\${basePkg}\${versionString}\${folderString}\`);
if (cdn !== "https://esm.sh/" && (basePkg.includes("react") || basePkg.includes("radix")) && !pkg.endsWith(".css"))
throw new Error(\`React based js packages is not supported in \${cdn}\`);
if (cdn !== "https://legacy.esm.sh/" && basePkg.includes("build"))
throw new Error(\`Build API package is not supported in \${cdn}\`);
cdn === "https://esm.sh/" && (basePkg !== "react-dom" && basePkg !== "react" && url.searchParams.set("bundle-deps", !1), !pkg.endsWith(".css") && pkg !== "build" && url.searchParams.set("deps", \`react@\${package_default.dependencies.react},react-dom@\${package_default.dependencies["react-dom"]}\`));
let urlString = url.toString();
return cdn === "https://cdn.jsdelivr.net/npm/" && !pkg.endsWith(".css") && (urlString += "/+esm"), urlString;
}
var dynamicImportCSS = async (pkg, pkgVersion = null) => {
let resolvedVersion = resolvePackageVersion(pkg, pkgVersion), url = buildCDNUrl("https://cdn.jsdelivr.net/npm/", pkg, resolvedVersion), link = document.createElement("link");
return link.rel = "stylesheet", link.href = url, document.head.appendChild(link), new Promise((resolve) => link.onload = resolve);
}, dynamic_import_esm_default = dynamicImportESM;
// src-copilot/aisdk-wrappers/getLLMModel.js
init_process();
// src-copilot/constants.js
init_process();
var LLM_API_URL_SETTING = "LLM API URL", LLM_API_KEY_SETTING = "LLM API Key", LLM_MODEL_SETTING = "LLM Model", LLM_MAX_TOKENS_SETTING = "LLM Max Tokens (Optional)", CUSTOM_LLM_INSTRUCTION_SETTING = "Custom LLM Instruction (Optional)", CUSTOM_LLM_AVATAR_SETTING = "Custom LLM Avatar (Optional)", USER_PROMPT_LIST_SETTING = "User Prompt List (DO NOT CHANGE MANUALLY)";
var MCP_SERVER_URL_LIST_SETTING = "MCP Server List (Optional)";
// src-copilot/aisdk-wrappers/getLLMModel.js
async function getLLMModel(appSettings2) {
let apiUrl = appSettings2[LLM_API_URL_SETTING], model = appSettings2[LLM_MODEL_SETTING], apiKey = appSettings2[LLM_API_KEY_SETTING];
if (!apiUrl || !apiUrl.trim()) throw new Error("API URL is not provided. Please check plugin settings.");
if (!model || !model.trim()) throw new Error("Model is not provided. Please check plugin settings.");
if (apiUrl.endsWith("/chat/completion") && (apiUrl = apiUrl.slice(0, -16)), apiUrl = apiUrl.toLowerCase(), model = model.toLowerCase(), apiUrl.includes("groq")) {
let { createGroq } = await dynamic_import_esm_default("@ai-sdk/groq");
return createGroq({
apiKey,
baseURL: apiUrl
// Default: https://api.groq.com/openai/v1
}).languageModel(model);
} else if (apiUrl.includes("localhost")) {
let { createOllama } = await dynamic_import_esm_default("ollama-ai-provider");
return createOllama({
apiKey,
baseURL: apiUrl
// Default: http://localhost:11434/api
}).languageModel(model);
} else if (apiUrl.includes("googleapis")) {
let { createGoogleGenerativeAI } = await dynamic_import_esm_default("@ai-sdk/google");
return createGoogleGenerativeAI({
apiKey,
baseURL: apiUrl
// Default: https://generativelanguage.googleapis.com/v1beta
}).languageModel(model);
} else if (apiUrl.includes("anthropic")) {
let { createAnthropic } = await dynamic_import_esm_default("@ai-sdk/anthropic");
return createAnthropic({
apiKey,
baseURL: apiUrl,
headers: { "anthropic-dangerous-direct-browser-access": "true" }
}).languageModel(model);
} else if (apiUrl.includes("openai") || apiUrl.includes("openrouter")) {
let { createOpenAI } = await dynamic_import_esm_default("@ai-sdk/openai");
return createOpenAI({
apiKey,
baseURL: apiUrl
// Default: https://api.openai.com/v1
}).languageModel(model);
} else if (apiUrl.includes("fireworks")) {
let { createFireworks } = await dynamic_import_esm_default("@ai-sdk/fireworks");
return createFireworks({
apiKey,
baseURL: apiUrl
}).languageModel(model.startsWith("accounts/fireworks/models/") ? model : \`accounts/fireworks/models/\${model}\`);
} else throw new Error("It is likely that incorrect LLM API URL is provided. Please check plugin settings.");
}
// common-utils/embed-comunication.js
init_process();
// src-copilot/test/frontend-chat/chat.testdata.js
init_process();
// common-utils/embed-ui.js
init_process();
function showEmbedLoader() {
window.LoadingStartTime = performance.now();
let overlay = document.createElement("div");
overlay.id = "embed-loader-overlay", overlay.style.cssText = \`
position: fixed;
top: 0;
left: 0;
width: 100%;
/*height: 100%;*/
background-color: rgba(0, 0, 0, 0.5);
z-index: 9998;
animation: fadeIn 0.3s ease-in-out;
\`;
let loader = document.createElement("div");
loader.id = "embed-loader", loader.style.cssText = \`
position: fixed;
left: 50%;
transform: translate(-50%, 0%);
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
z-index: 9999;
\`;
let keyframes = document.createElement("style");
keyframes.textContent = \`
@keyframes spin {
0% { transform: translate(-50%, -50%) rotate(0deg); }
100% { transform: translate(-50%, -50%) rotate(360deg); }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
\`, document.head.appendChild(keyframes), document.body.appendChild(overlay), document.body.appendChild(loader), overlay.style.display = "none", loader.style.display = "none", setTimeout(() => {
document.getElementById("embed-loader") && (loader.style.display = "block"), document.getElementById("embed-loader-overlay") && (overlay.style.display = "block");
}, 240);
}
function hideEmbedLoader() {
window.LoadingEndTime = performance.now(), console.log("Loading time:", window.LoadingEndTime - window.LoadingStartTime);
let loader = document.getElementById("embed-loader"), overlay = document.getElementById("embed-loader-overlay");
loader && loader.remove(), overlay && overlay.remove();
}
// src-copilot/frontend-chat/overwriteWithAmplenoteStyle.js
init_process();
var overwriteWithAmplenoteStyle = () => {
let body2 = document.body, styleEl = document.createElement("style");
styleEl.innerText = \`
.dark, .dark-theme, :is(.dark, .dark-theme) :where(.radix-themes:not(.light, .light-theme)) {
--color-background: #272f35;
}
.dark, .dark-theme {
--gray-1: #292f33;
--gray-2: #2f3539;
--gray-3: #343c43;
--gray-4: #36414b;
--gray-5: #3a4651;
--gray-6: #3e4d5a;
--gray-7: #455968;
--gray-8: #577084;
--gray-9: #617b8f;
--gray-10: #6d8599;
--gray-11: #a7bac9;
--gray-12: #eaeff3;
--gray-a1: #d12f0003;
--gray-a2: #f4c99b0a;
--gray-a3: #e0e8fc12;
--gray-a4: #b0d3fe1c;
--gray-a5: #aed2fb24;
--gray-a6: #a4d2fe2f;
--gray-a7: #9dd4fe41;
--gray-a8: #a1d4ff64;
--gray-a9: #a8d9ff72;
--gray-a10: #b3dbfd7f;
--gray-a11: #d6ecffbb;
--gray-a12: #f7fbfff0;
--gray-contrast: #FFFFFF;
--gray-surface: rgba(0, 0, 0, 0.05);
--gray-indicator: #617b8f;
--gray-track: #617b8f;
}
@supports (color: color(display-p3 1 1 1)) {
@media (color-gamut: p3) {
.dark, .dark-theme {
--gray-1: oklch(30% 0.0115 242.8);
--gray-2: oklch(32.3% 0.0119 242.8);
--gray-3: oklch(35.3% 0.0166 242.8);
--gray-4: oklch(37.1% 0.0213 242.8);
--gray-5: oklch(38.8% 0.024 242.8);
--gray-6: oklch(41.2% 0.0288 242.8);
--gray-7: oklch(45.3% 0.035 242.8);
--gray-8: oklch(53.4% 0.0433 242.8);
--gray-9: oklch(57% 0.0433 242.8);
--gray-10: oklch(60.5% 0.0412 242.8);
--gray-11: oklch(77.9% 0.0302 242.8);
--gray-12: oklch(94.9% 0.0081 242.8);
--gray-a1: color(display-p3 0.9451 0.1843 0 / 0.005);
--gray-a2: color(display-p3 0.9961 0.898 0.8 / 0.033);
--gray-a3: color(display-p3 0.902 0.9255 1 / 0.069);
--gray-a4: color(display-p3 0.698 0.8353 0.9961 / 0.109);
--gray-a5: color(display-p3 0.702 0.8353 1 / 0.138);
--gray-a6: color(display-p3 0.6784 0.8275 1 / 0.183);
--gray-a7: color(display-p3 0.6588 0.8235 1 / 0.252);
--gray-a8: color(display-p3 0.6824 0.8392 1 / 0.385);
--gray-a9: color(display-p3 0.7059 0.8549 1 / 0.439);
--gray-a10: color(display-p3 0.749 0.8706 1 / 0.488);
--gray-a11: color(display-p3 0.8667 0.9294 1 / 0.725);
--gray-a12: color(display-p3 0.9725 0.9843 1 / 0.941);
--gray-contrast: #FFFFFF;
--gray-surface: color(display-p3 0 0 0 / 5%);
--gray-indicator: oklch(57% 0.0433 242.8);
--gray-track: oklch(57% 0.0433 242.8);
}
}
}
.dark, .dark-theme {
--accent-1: #252f3c;
--accent-2: #253141;
--accent-3: #223e64;
--accent-4: #1a467f;
--accent-5: #1e508f;
--accent-6: #275b9e;
--accent-7: #2e68b2;
--accent-8: #3277cf;
--accent-9: #0080ff;
--accent-10: #3378d0;
--accent-11: #7cbaff;
--accent-12: #cbe3ff;
--accent-a1: #002ffc09;
--accent-a2: #084ff510;
--accent-a3: #126ffc3c;
--accent-a4: #046dfe5e;
--accent-a5: #1379ff72;
--accent-a6: #2784ff85;
--accent-a7: #328bff9e;
--accent-a8: #368dffc3;
--accent-a9: #0080ff;
--accent-a10: #378effc4;
--accent-a11: #7cbaff;
--accent-a12: #cbe3ff;
--accent-contrast: #fff;
--accent-surface: #24334d80;
--accent-indicator: #0080ff;
--accent-track: #0080ff;
}
@supports (color: color(display-p3 1 1 1)) {
@media (color-gamut: p3) {
.dark, .dark-theme {
--accent-1: oklch(30% 0.0278 256.1);
--accent-2: oklch(31% 0.0325 256.1);
--accent-3: oklch(36.2% 0.074 256.1);
--accent-4: oklch(39.6% 0.1073 256.1);
--accent-5: oklch(43.2% 0.1173 256.1);
--accent-6: oklch(47.1% 0.1224 256.1);
--accent-7: oklch(51.7% 0.1323 256.1);
--accent-8: oklch(57% 0.1522 256.1);
--accent-9: oklch(61.5% 0.2108 256.1);
--accent-10: oklch(57.3% 0.1522 256.1);
--accent-11: oklch(78% 0.1427 256.1);
--accent-12: oklch(90.8% 0.0525 256.1);
--accent-a1: color(display-p3 0 0.1882 0.9882 / 0.035);
--accent-a2: color(display-p3 0.0314 0.3176 0.9922 / 0.06);
--accent-a3: color(display-p3 0.1608 0.4314 1 / 0.222);
--accent-a4: color(display-p3 0.1294 0.4275 1 / 0.35);
--accent-a5: color(display-p3 0.1882 0.4824 1 / 0.424);
--accent-a6: color(display-p3 0.2549 0.5216 1 / 0.498);
--accent-a7: color(display-p3 0.2902 0.5529 1 / 0.597);
--accent-a8: color(display-p3 0.3098 0.5569 1 / 0.734);
--accent-a9: color(display-p3 0.2157 0.5059 1 / 0.961);
--accent-a10: color(display-p3 0.3137 0.5647 1 / 0.739);
--accent-a11: color(display-p3 0.5529 0.7373 0.9961 / 0.971);
--accent-a12: color(display-p3 0.8235 0.8941 1 / 0.986);
--accent-contrast: #fff;
--accent-surface: color(display-p3 0.1529 0.1961 0.2902 / 0.5);
--accent-indicator: oklch(61.5% 0.2108 256.1);
--accent-track: oklch(61.5% 0.2108 256.1);
}
}
}\`.replace(/\\s+/g, " ").trim(), styleEl.innerText += \`
.app-container .radix-themes {
--default-font-size: 14px;
}
\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl);
let styleEl2 = document.createElement("style");
styleEl2.innerText = \`
.dark {
--aui-background: 210, 10%, 18%;
--aui-foreground: 210, 10%, 94%;
--aui-card: 210, 10%, 20%;
--aui-card-foreground: 210, 10%, 94%;
--aui-popover: 210, 10%, 22%;
--aui-popover-foreground: 210, 10%, 94%;
--aui-border: 210, 10%, 50%;
--aui-input: 210, 10%, 50%;
--aui-ring: 210, 10%, 18%;
--aui-primary: 205 80% 50%;
--aui-primary-foreground: 0, 0%, 100%;
--aui-secondary: 205, 10%, 94%;
--aui-secondary-foreground: 205, 10%, 18%;
--aui-muted-foreground: 205, 10%, 50%;
--aui-accent: 205, 100%, 50%;
--aui-accent-foreground: 0, 0%, 100%;
--aui-destructive: 0, 84%, 60%;
--aui-destructive-foreground: 0, 0%, 98%;
--aui-radius: 0.3rem;
}\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl2);
let styleEl3 = document.createElement("style");
styleEl3.innerText = \`
.tool_group_mention {
background-color: var(--accent-a3);
border-radius: var(--aui-radius);
}
div.aui-user-message-content {
border-radius: 1.25rem;
}
.aui-composer-root, .aui-thread-welcome-suggestion {
background-color: rgb(39, 47, 53);
}
.aui-composer-cancel {
background-color: hsl(var(--aui-destructive));
color: hsl(var(--aui-destructive-foreground));
}
.aui-composer-cancel:hover,
.aui-composer-cancel:focus,
.aui-composer-cancel:active {
background-color: hsla(var(--aui-destructive), 0.9);
}
.aui-composer-cancel:disabled {
background-color: hsla(var(--aui-destructive), 0.5);
color: hsla(var(--aui-destructive-foreground), 0.5);
cursor: not-allowed;
}
.aui-composer-root {
padding-left: 0.325rem;
padding-right: 0.325rem;
}
\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl3);
};
// src-copilot/frontend-chat/ChatApp.jsx
init_process();
// src-copilot/frontend-chat/ChatAppWindow.jsx
init_process();
// src-copilot/frontend-chat/hooks/useChatSuggestions.jsx
init_process();
var useChatSuggestions = (count = 2) => {
let [suggestions, setSuggestions] = React.useState([]), threadId = AssistantUI.useThreadListItemRuntime().getState().id;
return React.useEffect(() => {
try {
setSuggestions(getRandomSuggestions(count));
} catch (e) {
console.error(e);
}
}, [threadId]), suggestions;
}, allSuggestions = [
{
prompt: "Create @tasks for today's shopping",
displayCondition: () => !0
},
{
prompt: "Summarize @tasks for today",
displayCondition: () => !0
},
{
prompt: "Search @web for best song of current year",
displayCondition: () => !0
},
{
prompt: "Provide summary of current @notes",
displayCondition: () => window.userData.currentNoteUUID !== null
},
{
prompt: "@help What are task domains?",
displayCondition: () => !0
}
], getRandomSuggestions = (count) => {
let validSuggestions = allSuggestions.filter((suggestion) => suggestion.displayCondition()), selectedIndices = [], result = [];
for (; selectedIndices.length < count && selectedIndices.length < validSuggestions.length; ) {
let randomIndex = Math.floor(Math.random() * validSuggestions.length);
selectedIndices.includes(randomIndex) || (selectedIndices.push(randomIndex), result.push(validSuggestions[randomIndex]));
}
return result.sort(
(a, b) => (
// Sort based on original index to maintain order
validSuggestions.indexOf(a) - validSuggestions.indexOf(b)
)
);
};
// src-copilot/frontend-chat/components/CustomComposer.jsx
init_process();
// src-copilot/frontend-chat/hooks/useTributeSetup.jsx
init_process();
// src-copilot/frontend-chat/context/ChatAppContext.jsx
init_process();
// src-copilot/frontend-chat/hooks/useToolRegistries.js
init_process();
// src-copilot/frontend-chat/tools-core/registry/ToolRegistry.js
init_process();
// src-copilot/frontend-chat/tools/DeleteUserNotes.jsx
init_process();
// src-copilot/frontend-chat/components/tools-ui/ToolCardContainer.jsx
init_process();
var ToolCardContainer = ({ children }) => {
let { Card } = window.RadixUI;
return /* @__PURE__ */ React.createElement("div", { style: { height: "fit-content", marginBottom: "2px" } }, /* @__PURE__ */ React.createElement(Card, null, children));
};
// src-copilot/frontend-chat/components/tools-ui/ItemSelectionTable.jsx
init_process();
// node_modules/lodash-es/lodash.js
init_process();
// node_modules/lodash-es/isSymbol.js
init_process();
// node_modules/lodash-es/_baseGetTag.js
init_process();
// node_modules/lodash-es/_Symbol.js
init_process();
// node_modules/lodash-es/_root.js
init_process();
// node_modules/lodash-es/_freeGlobal.js
init_process();
var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis, freeGlobal_default = freeGlobal;
// node_modules/lodash-es/_root.js
var freeSelf = typeof self == "object" && self && self.Object === Object && self, root = freeGlobal_default || freeSelf || Function("return this")(), root_default = root;
// node_modules/lodash-es/_Symbol.js
var Symbol2 = root_default.Symbol, Symbol_default = Symbol2;
// node_modules/lodash-es/_getRawTag.js
init_process();
var objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, nativeObjectToString = objectProto.toString, symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = !0;
} catch {
}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
}
var getRawTag_default = getRawTag;
// node_modules/lodash-es/_objectToString.js
init_process();
var objectProto2 = Object.prototype, nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;
// node_modules/lodash-es/_baseGetTag.js
var nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
return value == null ? value === void 0 ? undefinedTag : nullTag : symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;
// node_modules/lodash-es/isObjectLike.js
init_process();
function isObjectLike(value) {
return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;
// node_modules/lodash-es/isSymbol.js
var symbolTag = "[object Symbol]";
function isSymbol(value) {
return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
}
var isSymbol_default = isSymbol;
// node_modules/lodash-es/_baseToString.js
init_process();
// node_modules/lodash-es/_arrayMap.js
init_process();
function arrayMap(array, iteratee) {
for (var index = -1, length = array == null ? 0 : array.length, result = Array(length); ++index < length; )
result[index] = iteratee(array[index], index, array);
return result;
}
var arrayMap_default = arrayMap;
// node_modules/lodash-es/isArray.js
init_process();
var isArray = Array.isArray, isArray_default = isArray;
// node_modules/lodash-es/_baseToString.js
var INFINITY = 1 / 0, symbolProto = Symbol_default ? Symbol_default.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
function baseToString(value) {
if (typeof value == "string")
return value;
if (isArray_default(value))
return arrayMap_default(value, baseToString) + "";
if (isSymbol_default(value))
return symbolToString ? symbolToString.call(value) : "";
var result = value + "";
return result == "0" && 1 / value == -INFINITY ? "-0" : result;
}
var baseToString_default = baseToString;
// node_modules/lodash-es/toInteger.js
init_process();
// node_modules/lodash-es/toFinite.js
init_process();
// node_modules/lodash-es/toNumber.js
init_process();
// node_modules/lodash-es/_baseTrim.js
init_process();
// node_modules/lodash-es/_trimmedEndIndex.js
init_process();
var reWhitespace = /\\s/;
function trimmedEndIndex(string) {
for (var index = string.length; index-- && reWhitespace.test(string.charAt(index)); )
;
return index;
}
var trimmedEndIndex_default = trimmedEndIndex;
// node_modules/lodash-es/_baseTrim.js
var reTrimStart = /^\\s+/;
function baseTrim(string) {
return string && string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "");
}
var baseTrim_default = baseTrim;
// node_modules/lodash-es/isObject.js
init_process();
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;
// node_modules/lodash-es/toNumber.js
var NAN = NaN, reIsBadHex = /^[-+]0x[0-9a-f]+$/i, reIsBinary = /^0b[01]+$/i, reIsOctal = /^0o[0-7]+$/i, freeParseInt = parseInt;
function toNumber(value) {
if (typeof value == "number")
return value;
if (isSymbol_default(value))
return NAN;
if (isObject_default(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject_default(other) ? other + "" : other;
}
if (typeof value != "string")
return value === 0 ? value : +value;
value = baseTrim_default(value);
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_default = toNumber;
// node_modules/lodash-es/toFinite.js
var INFINITY2 = 1 / 0, MAX_INTEGER = 17976931348623157e292;
function toFinite(value) {
if (!value)
return value === 0 ? value : 0;
if (value = toNumber_default(value), value === INFINITY2 || value === -INFINITY2) {
var sign = value < 0 ? -1 : 1;
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
var toFinite_default = toFinite;
// node_modules/lodash-es/toInteger.js
function toInteger(value) {
var result = toFinite_default(value), remainder = result % 1;
return result === result ? remainder ? result - remainder : result : 0;
}
var toInteger_default = toInteger;
// node_modules/lodash-es/identity.js
init_process();
function identity(value) {
return value;
}
var identity_default = identity;
// node_modules/lodash-es/_WeakMap.js
init_process();
// node_modules/lodash-es/_getNative.js
init_process();
// node_modules/lodash-es/_baseIsNative.js
init_process();
// node_modules/lodash-es/isFunction.js
init_process();
var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
function isFunction(value) {
if (!isObject_default(value))
return !1;
var tag = baseGetTag_default(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_default = isFunction;
// node_modules/lodash-es/_isMasked.js
init_process();
// node_modules/lodash-es/_coreJsData.js
init_process();
var coreJsData = root_default["__core-js_shared__"], coreJsData_default = coreJsData;
// node_modules/lodash-es/_isMasked.js
var maskSrcKey = function() {
var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
}();
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
var isMasked_default = isMasked;
// node_modules/lodash-es/_toSource.js
init_process();
var funcProto = Function.prototype, funcToString = funcProto.toString;
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch {
}
try {
return func + "";
} catch {
}
}
return "";
}
var toSource_default = toSource;
// node_modules/lodash-es/_baseIsNative.js
var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g, reIsHostCtor = /^\\[object .+?Constructor\\]$/, funcProto2 = Function.prototype, objectProto3 = Object.prototype, funcToString2 = funcProto2.toString, hasOwnProperty2 = objectProto3.hasOwnProperty, reIsNative = RegExp(
"^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\\\$&").replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, "$1.*?") + "$"
);
function baseIsNative(value) {
if (!isObject_default(value) || isMasked_default(value))
return !1;
var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource_default(value));
}
var baseIsNative_default = baseIsNative;
// node_modules/lodash-es/_getValue.js
init_process();
function getValue(object, key) {
return object == null ? void 0 : object[key];
}
var getValue_default = getValue;
// node_modules/lodash-es/_getNative.js
function getNative(object, key) {
var value = getValue_default(object, key);
return baseIsNative_default(value) ? value : void 0;
}
var getNative_default = getNative;
// node_modules/lodash-es/_WeakMap.js
var WeakMap = getNative_default(root_default, "WeakMap"), WeakMap_default = WeakMap;
// node_modules/lodash-es/_baseCreate.js
init_process();
var objectCreate = Object.create, baseCreate = /* @__PURE__ */ function() {
function object() {
}
return function(proto) {
if (!isObject_default(proto))
return {};
if (objectCreate)
return objectCreate(proto);
object.prototype = proto;
var result = new object();
return object.prototype = void 0, result;
};
}(), baseCreate_default = baseCreate;
// node_modules/lodash-es/noop.js
init_process();
function noop() {
}
var noop_default = noop;
// node_modules/lodash-es/_copyArray.js
init_process();
function copyArray(source, array) {
var index = -1, length = source.length;
for (array || (array = Array(length)); ++index < length; )
array[index] = source[index];
return array;
}
var copyArray_default = copyArray;
// node_modules/lodash-es/_defineProperty.js
init_process();
var defineProperty = function() {
try {
var func = getNative_default(Object, "defineProperty");
return func({}, "", {}), func;
} catch {
}
}(), defineProperty_default = defineProperty;
// node_modules/lodash-es/_arrayEach.js
init_process();
function arrayEach(array, iteratee) {
for (var index = -1, length = array == null ? 0 : array.length; ++index < length && iteratee(array[index], index, array) !== !1; )
;
return array;
}
var arrayEach_default = arrayEach;
// node_modules/lodash-es/_arrayIncludes.js
init_process();
// node_modules/lodash-es/_baseIndexOf.js
init_process();
// node_modules/lodash-es/_baseFindIndex.js
init_process();
function baseFindIndex(array, predicate, fromIndex, fromRight) {
for (var length = array.length, index = fromIndex + (fromRight ? 1 : -1); fromRight ? index-- : ++index < length; )
if (predicate(array[index], index, array))
return index;
return -1;
}
var baseFindIndex_default = baseFindIndex;
// node_modules/lodash-es/_baseIsNaN.js
init_process();
function baseIsNaN(value) {
return value !== value;
}
var baseIsNaN_default = baseIsNaN;
// node_modules/lodash-es/_strictIndexOf.js
init_process();
function strictIndexOf(array, value, fromIndex) {
for (var index = fromIndex - 1, length = array.length; ++index < length; )
if (array[index] === value)
return index;
return -1;
}
var strictIndexOf_default = strictIndexOf;
// node_modules/lodash-es/_baseIndexOf.js
function baseIndexOf(array, value, fromIndex) {
return value === value ? strictIndexOf_default(array, value, fromIndex) : baseFindIndex_default(array, baseIsNaN_default, fromIndex);
}
var baseIndexOf_default = baseIndexOf;
// node_modules/lodash-es/_arrayIncludes.js
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf_default(array, value, 0) > -1;
}
var arrayIncludes_default = arrayIncludes;
// node_modules/lodash-es/_isIndex.js
init_process();
var MAX_SAFE_INTEGER = 9007199254740991, reIsUint = /^(?:0|[1-9]\\d*)$/;
function isIndex(value, length) {
var type = typeof value;
return length = length == null ? MAX_SAFE_INTEGER : length, !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
var isIndex_default = isIndex;
// node_modules/lodash-es/_assignValue.js
init_process();
// node_modules/lodash-es/_baseAssignValue.js
init_process();
function baseAssignValue(object, key, value) {
key == "__proto__" && defineProperty_default ? defineProperty_default(object, key, {
configurable: !0,
enumerable: !0,
value,
writable: !0
}) : object[key] = value;
}
var baseAssignValue_default = baseAssignValue;
// node_modules/lodash-es/eq.js
init_process();
function eq(value, other) {
return value === other || value !== value && other !== other;
}
var eq_default = eq;
// node_modules/lodash-es/_assignValue.js
var objectProto4 = Object.prototype, hasOwnProperty3 = objectProto4.hasOwnProperty;
function assignValue(object, key, value) {
var objValue = object[key];
(!(hasOwnProperty3.call(object, key) && eq_default(objValue, value)) || value === void 0 && !(key in object)) && baseAssignValue_default(object, key, value);
}
var assignValue_default = assignValue;
// node_modules/lodash-es/_copyObject.js
init_process();
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
for (var index = -1, length = props.length; ++index < length; ) {
var key = props[index], newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
newValue === void 0 && (newValue = source[key]), isNew ? baseAssignValue_default(object, key, newValue) : assignValue_default(object, key, newValue);
}
return object;
}
var copyObject_default = copyObject;
// node_modules/lodash-es/isArrayLike.js
init_process();
// node_modules/lodash-es/isLength.js
init_process();
var MAX_SAFE_INTEGER2 = 9007199254740991;
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
}
var isLength_default = isLength;
// node_modules/lodash-es/isArrayLike.js
function isArrayLike(value) {
return value != null && isLength_default(value.length) && !isFunction_default(value);
}
var isArrayLike_default = isArrayLike;
// node_modules/lodash-es/_isPrototype.js
init_process();
var objectProto5 = Object.prototype;
function isPrototype(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto5;
return value === proto;
}
var isPrototype_default = isPrototype;
// node_modules/lodash-es/keys.js
init_process();
// node_modules/lodash-es/_arrayLikeKeys.js
init_process();
// node_modules/lodash-es/_baseTimes.js
init_process();
function baseTimes(n, iteratee) {
for (var index = -1, result = Array(n); ++index < n; )
result[index] = iteratee(index);
return result;
}
var baseTimes_default = baseTimes;
// node_modules/lodash-es/isArguments.js
init_process();
// node_modules/lodash-es/_baseIsArguments.js
init_process();
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == argsTag;
}
var baseIsArguments_default = baseIsArguments;
// node_modules/lodash-es/isArguments.js
var objectProto6 = Object.prototype, hasOwnProperty4 = objectProto6.hasOwnProperty, propertyIsEnumerable = objectProto6.propertyIsEnumerable, isArguments = baseIsArguments_default(/* @__PURE__ */ function() {
return arguments;
}()) ? baseIsArguments_default : function(value) {
return isObjectLike_default(value) && hasOwnProperty4.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
}, isArguments_default = isArguments;
// node_modules/lodash-es/isBuffer.js
init_process();
// node_modules/lodash-es/stubFalse.js
init_process();
function stubFalse() {
return !1;
}
var stubFalse_default = stubFalse;
// node_modules/lodash-es/isBuffer.js
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports, Buffer2 = moduleExports ? root_default.Buffer : void 0, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0, isBuffer = nativeIsBuffer || stubFalse_default, isBuffer_default = isBuffer;
// node_modules/lodash-es/isTypedArray.js
init_process();
// node_modules/lodash-es/_baseIsTypedArray.js
init_process();
var argsTag2 = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag2 = "[object Function]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", weakMapTag = "[object WeakMap]", arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]", typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = !0;
typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag2] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = !1;
function baseIsTypedArray(value) {
return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[baseGetTag_default(value)];
}
var baseIsTypedArray_default = baseIsTypedArray;
// node_modules/lodash-es/_baseUnary.js
init_process();
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var baseUnary_default = baseUnary;
// node_modules/lodash-es/_nodeUtil.js
init_process();
var freeExports2 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule2 = freeExports2 && typeof module == "object" && module && !module.nodeType && module, moduleExports2 = freeModule2 && freeModule2.exports === freeExports2, freeProcess = moduleExports2 && freeGlobal_default.process, nodeUtil = function() {
try {
var types = freeModule2 && freeModule2.require && freeModule2.require("util").types;
return types || freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch {
}
}(), nodeUtil_default = nodeUtil;
// node_modules/lodash-es/isTypedArray.js
var nodeIsTypedArray = nodeUtil_default && nodeUtil_default.isTypedArray, isTypedArray = nodeIsTypedArray ? baseUnary_default(nodeIsTypedArray) : baseIsTypedArray_default, isTypedArray_default = isTypedArray;
// node_modules/lodash-es/_arrayLikeKeys.js
var objectProto7 = Object.prototype, hasOwnProperty5 = objectProto7.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length;
for (var key in value)
(inherited || hasOwnProperty5.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable \`arguments.length\` in strict mode.
(key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
isIndex_default(key, length))) && result.push(key);
return result;
}
var arrayLikeKeys_default = arrayLikeKeys;
// node_modules/lodash-es/_baseKeys.js
init_process();
// node_modules/lodash-es/_nativeKeys.js
init_process();
// node_modules/lodash-es/_overArg.js
init_process();
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var overArg_default = overArg;
// node_modules/lodash-es/_nativeKeys.js
var nativeKeys = overArg_default(Object.keys, Object), nativeKeys_default = nativeKeys;
// node_modules/lodash-es/_baseKeys.js
var objectProto8 = Object.prototype, hasOwnProperty6 = objectProto8.hasOwnProperty;
function baseKeys(object) {
if (!isPrototype_default(object))
return nativeKeys_default(object);
var result = [];
for (var key in Object(object))
hasOwnProperty6.call(object, key) && key != "constructor" && result.push(key);
return result;
}
var baseKeys_default = baseKeys;
// node_modules/lodash-es/keys.js
function keys(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object) : baseKeys_default(object);
}
var keys_default = keys;
// node_modules/lodash-es/keysIn.js
init_process();
// node_modules/lodash-es/_baseKeysIn.js
init_process();
// node_modules/lodash-es/_nativeKeysIn.js
init_process();
function nativeKeysIn(object) {
var result = [];
if (object != null)
for (var key in Object(object))
result.push(key);
return result;
}
var nativeKeysIn_default = nativeKeysIn;
// node_modules/lodash-es/_baseKeysIn.js
var objectProto9 = Object.prototype, hasOwnProperty7 = objectProto9.hasOwnProperty;
function baseKeysIn(object) {
if (!isObject_default(object))
return nativeKeysIn_default(object);
var isProto = isPrototype_default(object), result = [];
for (var key in object)
key == "constructor" && (isProto || !hasOwnProperty7.call(object, key)) || result.push(key);
return result;
}
var baseKeysIn_default = baseKeysIn;
// node_modules/lodash-es/keysIn.js
function keysIn(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object, !0) : baseKeysIn_default(object);
}
var keysIn_default = keysIn;
// node_modules/lodash-es/get.js
init_process();
// node_modules/lodash-es/_baseGet.js
init_process();
// node_modules/lodash-es/_castPath.js
init_process();
// node_modules/lodash-es/_isKey.js
init_process();
var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|(["'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/, reIsPlainProp = /^\\w*$/;
function isKey(value, object) {
if (isArray_default(value))
return !1;
var type = typeof value;
return type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_default(value) ? !0 : reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
var isKey_default = isKey;
// node_modules/lodash-es/_stringToPath.js
init_process();
// node_modules/lodash-es/_memoizeCapped.js
init_process();
// node_modules/lodash-es/memoize.js
init_process();
// node_modules/lodash-es/_MapCache.js
init_process();
// node_modules/lodash-es/_mapCacheClear.js
init_process();
// node_modules/lodash-es/_Hash.js
init_process();
// node_modules/lodash-es/_hashClear.js
init_process();
// node_modules/lodash-es/_nativeCreate.js
init_process();
var nativeCreate = getNative_default(Object, "create"), nativeCreate_default = nativeCreate;
// node_modules/lodash-es/_hashClear.js
function hashClear() {
this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {}, this.size = 0;
}
var hashClear_default = hashClear;
// node_modules/lodash-es/_hashDelete.js
init_process();
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
return this.size -= result ? 1 : 0, result;
}
var hashDelete_default = hashDelete;
// node_modules/lodash-es/_hashGet.js
init_process();
var HASH_UNDEFINED = "__lodash_hash_undefined__", objectProto10 = Object.prototype, hasOwnProperty8 = objectProto10.hasOwnProperty;
function hashGet(key) {
var data = this.__data__;
if (nativeCreate_default) {
var result = data[key];
return result === HASH_UNDEFINED ? void 0 : result;
}
return hasOwnProperty8.call(data, key) ? data[key] : void 0;
}
var hashGet_default = hashGet;
// node_modules/lodash-es/_hashHas.js
init_process();
var objectProto11 = Object.prototype, hasOwnProperty9 = objectProto11.hasOwnProperty;
function hashHas(key) {
var data = this.__data__;
return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty9.call(data, key);
}
var hashHas_default = hashHas;
// node_modules/lodash-es/_hashSet.js
init_process();
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
function hashSet(key, value) {
var data = this.__data__;
return this.size += this.has(key) ? 0 : 1, data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value, this;
}
var hashSet_default = hashSet;
// node_modules/lodash-es/_Hash.js
function Hash(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
Hash.prototype.clear = hashClear_default;
Hash.prototype.delete = hashDelete_default;
Hash.prototype.get = hashGet_default;
Hash.prototype.has = hashHas_default;
Hash.prototype.set = hashSet_default;
var Hash_default = Hash;
// node_modules/lodash-es/_ListCache.js
init_process();
// node_modules/lodash-es/_listCacheClear.js
init_process();
function listCacheClear() {
this.__data__ = [], this.size = 0;
}
var listCacheClear_default = listCacheClear;
// node_modules/lodash-es/_listCacheDelete.js
init_process();
// node_modules/lodash-es/_assocIndexOf.js
init_process();
function assocIndexOf(array, key) {
for (var length = array.length; length--; )
if (eq_default(array[length][0], key))
return length;
return -1;
}
var assocIndexOf_default = assocIndexOf;
// node_modules/lodash-es/_listCacheDelete.js
var arrayProto = Array.prototype, splice = arrayProto.splice;
function listCacheDelete(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
if (index < 0)
return !1;
var lastIndex = data.length - 1;
return index == lastIndex ? data.pop() : splice.call(data, index, 1), --this.size, !0;
}
var listCacheDelete_default = listCacheDelete;
// node_modules/lodash-es/_listCacheGet.js
init_process();
function listCacheGet(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
return index < 0 ? void 0 : data[index][1];
}
var listCacheGet_default = listCacheGet;
// node_modules/lodash-es/_listCacheHas.js
init_process();
function listCacheHas(key) {
return assocIndexOf_default(this.__data__, key) > -1;
}
var listCacheHas_default = listCacheHas;
// node_modules/lodash-es/_listCacheSet.js
init_process();
function listCacheSet(key, value) {
var data = this.__data__, index = assocIndexOf_default(data, key);
return index < 0 ? (++this.size, data.push([key, value])) : data[index][1] = value, this;
}
var listCacheSet_default = listCacheSet;
// node_modules/lodash-es/_ListCache.js
function ListCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
ListCache.prototype.clear = listCacheClear_default;
ListCache.prototype.delete = listCacheDelete_default;
ListCache.prototype.get = listCacheGet_default;
ListCache.prototype.has = listCacheHas_default;
ListCache.prototype.set = listCacheSet_default;
var ListCache_default = ListCache;
// node_modules/lodash-es/_Map.js
init_process();
var Map2 = getNative_default(root_default, "Map"), Map_default = Map2;
// node_modules/lodash-es/_mapCacheClear.js
function mapCacheClear() {
this.size = 0, this.__data__ = {
hash: new Hash_default(),
map: new (Map_default || ListCache_default)(),
string: new Hash_default()
};
}
var mapCacheClear_default = mapCacheClear;
// node_modules/lodash-es/_mapCacheDelete.js
init_process();
// node_modules/lodash-es/_getMapData.js
init_process();
// node_modules/lodash-es/_isKeyable.js
init_process();
function isKeyable(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
var isKeyable_default = isKeyable;
// node_modules/lodash-es/_getMapData.js
function getMapData(map, key) {
var data = map.__data__;
return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
var getMapData_default = getMapData;
// node_modules/lodash-es/_mapCacheDelete.js
function mapCacheDelete(key) {
var result = getMapData_default(this, key).delete(key);
return this.size -= result ? 1 : 0, result;
}
var mapCacheDelete_default = mapCacheDelete;
// node_modules/lodash-es/_mapCacheGet.js
init_process();
function mapCacheGet(key) {
return getMapData_default(this, key).get(key);
}
var mapCacheGet_default = mapCacheGet;
// node_modules/lodash-es/_mapCacheHas.js
init_process();
function mapCacheHas(key) {
return getMapData_default(this, key).has(key);
}
var mapCacheHas_default = mapCacheHas;
// node_modules/lodash-es/_mapCacheSet.js
init_process();
function mapCacheSet(key, value) {
var data = getMapData_default(this, key), size = data.size;
return data.set(key, value), this.size += data.size == size ? 0 : 1, this;
}
var mapCacheSet_default = mapCacheSet;
// node_modules/lodash-es/_MapCache.js
function MapCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
MapCache.prototype.clear = mapCacheClear_default;
MapCache.prototype.delete = mapCacheDelete_default;
MapCache.prototype.get = mapCacheGet_default;
MapCache.prototype.has = mapCacheHas_default;
MapCache.prototype.set = mapCacheSet_default;
var MapCache_default = MapCache;
// node_modules/lodash-es/memoize.js
var FUNC_ERROR_TEXT = "Expected a function";
function memoize(func, resolver) {
if (typeof func != "function" || resolver != null && typeof resolver != "function")
throw new TypeError(FUNC_ERROR_TEXT);
var memoized = function() {
var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
if (cache.has(key))
return cache.get(key);
var result = func.apply(this, args);
return memoized.cache = cache.set(key, result) || cache, result;
};
return memoized.cache = new (memoize.Cache || MapCache_default)(), memoized;
}
memoize.Cache = MapCache_default;
var memoize_default = memoize;
// node_modules/lodash-es/_memoizeCapped.js
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped(func) {
var result = memoize_default(func, function(key) {
return cache.size === MAX_MEMOIZE_SIZE && cache.clear(), key;
}), cache = result.cache;
return result;
}
var memoizeCapped_default = memoizeCapped;
// node_modules/lodash-es/_stringToPath.js
var rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|(["'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g, reEscapeChar = /\\\\(\\\\)?/g, stringToPath = memoizeCapped_default(function(string) {
var result = [];
return string.charCodeAt(0) === 46 && result.push(""), string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
}), result;
}), stringToPath_default = stringToPath;
// node_modules/lodash-es/toString.js
init_process();
function toString(value) {
return value == null ? "" : baseToString_default(value);
}
var toString_default = toString;
// node_modules/lodash-es/_castPath.js
function castPath(value, object) {
return isArray_default(value) ? value : isKey_default(value, object) ? [value] : stringToPath_default(toString_default(value));
}
var castPath_default = castPath;
// node_modules/lodash-es/_toKey.js
init_process();
var INFINITY3 = 1 / 0;
function toKey(value) {
if (typeof value == "string" || isSymbol_default(value))
return value;
var result = value + "";
return result == "0" && 1 / value == -INFINITY3 ? "-0" : result;
}
var toKey_default = toKey;
// node_modules/lodash-es/_baseGet.js
function baseGet(object, path) {
path = castPath_default(path, object);
for (var index = 0, length = path.length; object != null && index < length; )
object = object[toKey_default(path[index++])];
return index && index == length ? object : void 0;
}
var baseGet_default = baseGet;
// node_modules/lodash-es/get.js
function get(object, path, defaultValue) {
var result = object == null ? void 0 : baseGet_default(object, path);
return result === void 0 ? defaultValue : result;
}
var get_default = get;
// node_modules/lodash-es/_arrayPush.js
init_process();
function arrayPush(array, values) {
for (var index = -1, length = values.length, offset = array.length; ++index < length; )
array[offset + index] = values[index];
return array;
}
var arrayPush_default = arrayPush;
// node_modules/lodash-es/_getPrototype.js
init_process();
var getPrototype = overArg_default(Object.getPrototypeOf, Object), getPrototype_default = getPrototype;
// node_modules/lodash-es/capitalize.js
init_process();
// node_modules/lodash-es/upperFirst.js
init_process();
// node_modules/lodash-es/_createCaseFirst.js
init_process();
// node_modules/lodash-es/_castSlice.js
init_process();
// node_modules/lodash-es/_baseSlice.js
init_process();
function baseSlice(array, start, end) {
var index = -1, length = array.length;
start < 0 && (start = -start > length ? 0 : length + start), end = end > length ? length : end, end < 0 && (end += length), length = start > end ? 0 : end - start >>> 0, start >>>= 0;
for (var result = Array(length); ++index < length; )
result[index] = array[index + start];
return result;
}
var baseSlice_default = baseSlice;
// node_modules/lodash-es/_castSlice.js
function castSlice(array, start, end) {
var length = array.length;
return end = end === void 0 ? length : end, !start && end >= length ? array : baseSlice_default(array, start, end);
}
var castSlice_default = castSlice;
// node_modules/lodash-es/_hasUnicode.js
init_process();
var rsAstralRange = "\\\\ud800-\\\\udfff", rsComboMarksRange = "\\\\u0300-\\\\u036f", reComboHalfMarksRange = "\\\\ufe20-\\\\ufe2f", rsComboSymbolsRange = "\\\\u20d0-\\\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = "\\\\ufe0e\\\\ufe0f", rsZWJ = "\\\\u200d", reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]");
function hasUnicode(string) {
return reHasUnicode.test(string);
}
var hasUnicode_default = hasUnicode;
// node_modules/lodash-es/_stringToArray.js
init_process();
// node_modules/lodash-es/_asciiToArray.js
init_process();
function asciiToArray(string) {
return string.split("");
}
var asciiToArray_default = asciiToArray;
// node_modules/lodash-es/_unicodeToArray.js
init_process();
var rsAstralRange2 = "\\\\ud800-\\\\udfff", rsComboMarksRange2 = "\\\\u0300-\\\\u036f", reComboHalfMarksRange2 = "\\\\ufe20-\\\\ufe2f", rsComboSymbolsRange2 = "\\\\u20d0-\\\\u20ff", rsComboRange2 = rsComboMarksRange2 + reComboHalfMarksRange2 + rsComboSymbolsRange2, rsVarRange2 = "\\\\ufe0e\\\\ufe0f", rsAstral = "[" + rsAstralRange2 + "]", rsCombo = "[" + rsComboRange2 + "]", rsFitz = "\\\\ud83c[\\\\udffb-\\\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange2 + "]", rsRegional = "(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}", rsSurrPair = "[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]", rsZWJ2 = "\\\\u200d", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange2 + "]?", rsOptJoin = "(?:" + rsZWJ2 + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")", reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
var unicodeToArray_default = unicodeToArray;
// node_modules/lodash-es/_stringToArray.js
function stringToArray(string) {
return hasUnicode_default(string) ? unicodeToArray_default(string) : asciiToArray_default(string);
}
var stringToArray_default = stringToArray;
// node_modules/lodash-es/_createCaseFirst.js
function createCaseFirst(methodName) {
return function(string) {
string = toString_default(string);
var strSymbols = hasUnicode_default(string) ? stringToArray_default(string) : void 0, chr = strSymbols ? strSymbols[0] : string.charAt(0), trailing = strSymbols ? castSlice_default(strSymbols, 1).join("") : string.slice(1);
return chr[methodName]() + trailing;
};
}
var createCaseFirst_default = createCaseFirst;
// node_modules/lodash-es/upperFirst.js
var upperFirst = createCaseFirst_default("toUpperCase"), upperFirst_default = upperFirst;
// node_modules/lodash-es/capitalize.js
function capitalize(string) {
return upperFirst_default(toString_default(string).toLowerCase());
}
var capitalize_default = capitalize;
// node_modules/lodash-es/_baseClone.js
init_process();
// node_modules/lodash-es/_Stack.js
init_process();
// node_modules/lodash-es/_stackClear.js
init_process();
function stackClear() {
this.__data__ = new ListCache_default(), this.size = 0;
}
var stackClear_default = stackClear;
// node_modules/lodash-es/_stackDelete.js
init_process();
function stackDelete(key) {
var data = this.__data__, result = data.delete(key);
return this.size = data.size, result;
}
var stackDelete_default = stackDelete;
// node_modules/lodash-es/_stackGet.js
init_process();
function stackGet(key) {
return this.__data__.get(key);
}
var stackGet_default = stackGet;
// node_modules/lodash-es/_stackHas.js
init_process();
function stackHas(key) {
return this.__data__.has(key);
}
var stackHas_default = stackHas;
// node_modules/lodash-es/_stackSet.js
init_process();
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache_default) {
var pairs = data.__data__;
if (!Map_default || pairs.length < LARGE_ARRAY_SIZE - 1)
return pairs.push([key, value]), this.size = ++data.size, this;
data = this.__data__ = new MapCache_default(pairs);
}
return data.set(key, value), this.size = data.size, this;
}
var stackSet_default = stackSet;
// node_modules/lodash-es/_Stack.js
function Stack(entries) {
var data = this.__data__ = new ListCache_default(entries);
this.size = data.size;
}
Stack.prototype.clear = stackClear_default;
Stack.prototype.delete = stackDelete_default;
Stack.prototype.get = stackGet_default;
Stack.prototype.has = stackHas_default;
Stack.prototype.set = stackSet_default;
var Stack_default = Stack;
// node_modules/lodash-es/_baseAssign.js
init_process();
function baseAssign(object, source) {
return object && copyObject_default(source, keys_default(source), object);
}
var baseAssign_default = baseAssign;
// node_modules/lodash-es/_baseAssignIn.js
init_process();
function baseAssignIn(object, source) {
return object && copyObject_default(source, keysIn_default(source), object);
}
var baseAssignIn_default = baseAssignIn;
// node_modules/lodash-es/_cloneBuffer.js
init_process();
var freeExports3 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule3 = freeExports3 && typeof module == "object" && module && !module.nodeType && module, moduleExports3 = freeModule3 && freeModule3.exports === freeExports3, Buffer3 = moduleExports3 ? root_default.Buffer : void 0, allocUnsafe = Buffer3 ? Buffer3.allocUnsafe : void 0;
function cloneBuffer(buffer, isDeep) {
if (isDeep)
return buffer.slice();
var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
return buffer.copy(result), result;
}
var cloneBuffer_default = cloneBuffer;
// node_modules/lodash-es/_copySymbols.js
init_process();
// node_modules/lodash-es/_getSymbols.js
init_process();
// node_modules/lodash-es/_arrayFilter.js
init_process();
function arrayFilter(array, predicate) {
for (var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; ++index < length; ) {
var value = array[index];
predicate(value, index, array) && (result[resIndex++] = value);
}
return result;
}
var arrayFilter_default = arrayFilter;
// node_modules/lodash-es/stubArray.js
init_process();
function stubArray() {
return [];
}
var stubArray_default = stubArray;
// node_modules/lodash-es/_getSymbols.js
var objectProto12 = Object.prototype, propertyIsEnumerable2 = objectProto12.propertyIsEnumerable, nativeGetSymbols = Object.getOwnPropertySymbols, getSymbols = nativeGetSymbols ? function(object) {
return object == null ? [] : (object = Object(object), arrayFilter_default(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable2.call(object, symbol);
}));
} : stubArray_default, getSymbols_default = getSymbols;
// node_modules/lodash-es/_copySymbols.js
function copySymbols(source, object) {
return copyObject_default(source, getSymbols_default(source), object);
}
var copySymbols_default = copySymbols;
// node_modules/lodash-es/_copySymbolsIn.js
init_process();
// node_modules/lodash-es/_getSymbolsIn.js
init_process();
var nativeGetSymbols2 = Object.getOwnPropertySymbols, getSymbolsIn = nativeGetSymbols2 ? function(object) {
for (var result = []; object; )
arrayPush_default(result, getSymbols_default(object)), object = getPrototype_default(object);
return result;
} : stubArray_default, getSymbolsIn_default = getSymbolsIn;
// node_modules/lodash-es/_copySymbolsIn.js
function copySymbolsIn(source, object) {
return copyObject_default(source, getSymbolsIn_default(source), object);
}
var copySymbolsIn_default = copySymbolsIn;
// node_modules/lodash-es/_getAllKeys.js
init_process();
// node_modules/lodash-es/_baseGetAllKeys.js
init_process();
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_default(object) ? result : arrayPush_default(result, symbolsFunc(object));
}
var baseGetAllKeys_default = baseGetAllKeys;
// node_modules/lodash-es/_getAllKeys.js
function getAllKeys(object) {
return baseGetAllKeys_default(object, keys_default, getSymbols_default);
}
var getAllKeys_default = getAllKeys;
// node_modules/lodash-es/_getAllKeysIn.js
init_process();
function getAllKeysIn(object) {
return baseGetAllKeys_default(object, keysIn_default, getSymbolsIn_default);
}
var getAllKeysIn_default = getAllKeysIn;
// node_modules/lodash-es/_getTag.js
init_process();
// node_modules/lodash-es/_DataView.js
init_process();
var DataView = getNative_default(root_default, "DataView"), DataView_default = DataView;
// node_modules/lodash-es/_Promise.js
init_process();
var Promise2 = getNative_default(root_default, "Promise"), Promise_default = Promise2;
// node_modules/lodash-es/_Set.js
init_process();
var Set2 = getNative_default(root_default, "Set"), Set_default = Set2;
// node_modules/lodash-es/_getTag.js
var mapTag2 = "[object Map]", objectTag2 = "[object Object]", promiseTag = "[object Promise]", setTag2 = "[object Set]", weakMapTag2 = "[object WeakMap]", dataViewTag2 = "[object DataView]", dataViewCtorString = toSource_default(DataView_default), mapCtorString = toSource_default(Map_default), promiseCtorString = toSource_default(Promise_default), setCtorString = toSource_default(Set_default), weakMapCtorString = toSource_default(WeakMap_default), getTag = baseGetTag_default;
(DataView_default && getTag(new DataView_default(new ArrayBuffer(1))) != dataViewTag2 || Map_default && getTag(new Map_default()) != mapTag2 || Promise_default && getTag(Promise_default.resolve()) != promiseTag || Set_default && getTag(new Set_default()) != setTag2 || WeakMap_default && getTag(new WeakMap_default()) != weakMapTag2) && (getTag = function(value) {
var result = baseGetTag_default(value), Ctor = result == objectTag2 ? value.constructor : void 0, ctorString = Ctor ? toSource_default(Ctor) : "";
if (ctorString)
switch (ctorString) {
case dataViewCtorString:
return dataViewTag2;
case mapCtorString:
return mapTag2;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag2;
case weakMapCtorString:
return weakMapTag2;
}
return result;
});
var getTag_default = getTag;
// node_modules/lodash-es/_initCloneArray.js
init_process();
var objectProto13 = Object.prototype, hasOwnProperty10 = objectProto13.hasOwnProperty;
function initCloneArray(array) {
var length = array.length, result = new array.constructor(length);
return length && typeof array[0] == "string" && hasOwnProperty10.call(array, "index") && (result.index = array.index, result.input = array.input), result;
}
var initCloneArray_default = initCloneArray;
// node_modules/lodash-es/_initCloneByTag.js
init_process();
// node_modules/lodash-es/_cloneArrayBuffer.js
init_process();
// node_modules/lodash-es/_Uint8Array.js
init_process();
var Uint8Array2 = root_default.Uint8Array, Uint8Array_default = Uint8Array2;
// node_modules/lodash-es/_cloneArrayBuffer.js
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
return new Uint8Array_default(result).set(new Uint8Array_default(arrayBuffer)), result;
}
var cloneArrayBuffer_default = cloneArrayBuffer;
// node_modules/lodash-es/_cloneDataView.js
init_process();
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var cloneDataView_default = cloneDataView;
// node_modules/lodash-es/_cloneRegExp.js
init_process();
var reFlags = /\\w*$/;
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
return result.lastIndex = regexp.lastIndex, result;
}
var cloneRegExp_default = cloneRegExp;
// node_modules/lodash-es/_cloneSymbol.js
init_process();
var symbolProto2 = Symbol_default ? Symbol_default.prototype : void 0, symbolValueOf = symbolProto2 ? symbolProto2.valueOf : void 0;
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var cloneSymbol_default = cloneSymbol;
// node_modules/lodash-es/_cloneTypedArray.js
init_process();
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var cloneTypedArray_default = cloneTypedArray;
// node_modules/lodash-es/_initCloneByTag.js
var boolTag2 = "[object Boolean]", dateTag2 = "[object Date]", mapTag3 = "[object Map]", numberTag2 = "[object Number]", regexpTag2 = "[object RegExp]", setTag3 = "[object Set]", stringTag2 = "[object String]", symbolTag2 = "[object Symbol]", arrayBufferTag2 = "[object ArrayBuffer]", dataViewTag3 = "[object DataView]", float32Tag2 = "[object Float32Array]", float64Tag2 = "[object Float64Array]", int8Tag2 = "[object Int8Array]", int16Tag2 = "[object Int16Array]", int32Tag2 = "[object Int32Array]", uint8Tag2 = "[object Uint8Array]", uint8ClampedTag2 = "[object Uint8ClampedArray]", uint16Tag2 = "[object Uint16Array]", uint32Tag2 = "[object Uint32Array]";
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag2:
return cloneArrayBuffer_default(object);
case boolTag2:
case dateTag2:
return new Ctor(+object);
case dataViewTag3:
return cloneDataView_default(object, isDeep);
case float32Tag2:
case float64Tag2:
case int8Tag2:
case int16Tag2:
case int32Tag2:
case uint8Tag2:
case uint8ClampedTag2:
case uint16Tag2:
case uint32Tag2:
return cloneTypedArray_default(object, isDeep);
case mapTag3:
return new Ctor();
case numberTag2:
case stringTag2:
return new Ctor(object);
case regexpTag2:
return cloneRegExp_default(object);
case setTag3:
return new Ctor();
case symbolTag2:
return cloneSymbol_default(object);
}
}
var initCloneByTag_default = initCloneByTag;
// node_modules/lodash-es/_initCloneObject.js
init_process();
function initCloneObject(object) {
return typeof object.constructor == "function" && !isPrototype_default(object) ? baseCreate_default(getPrototype_default(object)) : {};
}
var initCloneObject_default = initCloneObject;
// node_modules/lodash-es/isMap.js
init_process();
// node_modules/lodash-es/_baseIsMap.js
init_process();
var mapTag4 = "[object Map]";
function baseIsMap(value) {
return isObjectLike_default(value) && getTag_default(value) == mapTag4;
}
var baseIsMap_default = baseIsMap;
// node_modules/lodash-es/isMap.js
var nodeIsMap = nodeUtil_default && nodeUtil_default.isMap, isMap = nodeIsMap ? baseUnary_default(nodeIsMap) : baseIsMap_default, isMap_default = isMap;
// node_modules/lodash-es/isSet.js
init_process();
// node_modules/lodash-es/_baseIsSet.js
init_process();
var setTag4 = "[object Set]";
function baseIsSet(value) {
return isObjectLike_default(value) && getTag_default(value) == setTag4;
}
var baseIsSet_default = baseIsSet;
// node_modules/lodash-es/isSet.js
var nodeIsSet = nodeUtil_default && nodeUtil_default.isSet, isSet = nodeIsSet ? baseUnary_default(nodeIsSet) : baseIsSet_default, isSet_default = isSet;
// node_modules/lodash-es/_baseClone.js
var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4, argsTag3 = "[object Arguments]", arrayTag2 = "[object Array]", boolTag3 = "[object Boolean]", dateTag3 = "[object Date]", errorTag2 = "[object Error]", funcTag3 = "[object Function]", genTag2 = "[object GeneratorFunction]", mapTag5 = "[object Map]", numberTag3 = "[object Number]", objectTag3 = "[object Object]", regexpTag3 = "[object RegExp]", setTag5 = "[object Set]", stringTag3 = "[object String]", symbolTag3 = "[object Symbol]", weakMapTag3 = "[object WeakMap]", arrayBufferTag3 = "[object ArrayBuffer]", dataViewTag4 = "[object DataView]", float32Tag3 = "[object Float32Array]", float64Tag3 = "[object Float64Array]", int8Tag3 = "[object Int8Array]", int16Tag3 = "[object Int16Array]", int32Tag3 = "[object Int32Array]", uint8Tag3 = "[object Uint8Array]", uint8ClampedTag3 = "[object Uint8ClampedArray]", uint16Tag3 = "[object Uint16Array]", uint32Tag3 = "[object Uint32Array]", cloneableTags = {};
cloneableTags[argsTag3] = cloneableTags[arrayTag2] = cloneableTags[arrayBufferTag3] = cloneableTags[dataViewTag4] = cloneableTags[boolTag3] = cloneableTags[dateTag3] = cloneableTags[float32Tag3] = cloneableTags[float64Tag3] = cloneableTags[int8Tag3] = cloneableTags[int16Tag3] = cloneableTags[int32Tag3] = cloneableTags[mapTag5] = cloneableTags[numberTag3] = cloneableTags[objectTag3] = cloneableTags[regexpTag3] = cloneableTags[setTag5] = cloneableTags[stringTag3] = cloneableTags[symbolTag3] = cloneableTags[uint8Tag3] = cloneableTags[uint8ClampedTag3] = cloneableTags[uint16Tag3] = cloneableTags[uint32Tag3] = !0;
cloneableTags[errorTag2] = cloneableTags[funcTag3] = cloneableTags[weakMapTag3] = !1;
function baseClone(value, bitmask, customizer, key, object, stack) {
var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer && (result = object ? customizer(value, key, object, stack) : customizer(value)), result !== void 0)
return result;
if (!isObject_default(value))
return value;
var isArr = isArray_default(value);
if (isArr) {
if (result = initCloneArray_default(value), !isDeep)
return copyArray_default(value, result);
} else {
var tag = getTag_default(value), isFunc = tag == funcTag3 || tag == genTag2;
if (isBuffer_default(value))
return cloneBuffer_default(value, isDeep);
if (tag == objectTag3 || tag == argsTag3 || isFunc && !object) {
if (result = isFlat || isFunc ? {} : initCloneObject_default(value), !isDeep)
return isFlat ? copySymbolsIn_default(value, baseAssignIn_default(result, value)) : copySymbols_default(value, baseAssign_default(result, value));
} else {
if (!cloneableTags[tag])
return object ? value : {};
result = initCloneByTag_default(value, tag, isDeep);
}
}
stack || (stack = new Stack_default());
var stacked = stack.get(value);
if (stacked)
return stacked;
stack.set(value, result), isSet_default(value) ? value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
}) : isMap_default(value) && value.forEach(function(subValue, key2) {
result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
});
var keysFunc = isFull ? isFlat ? getAllKeysIn_default : getAllKeys_default : isFlat ? keysIn_default : keys_default, props = isArr ? void 0 : keysFunc(value);
return arrayEach_default(props || value, function(subValue, key2) {
props && (key2 = subValue, subValue = value[key2]), assignValue_default(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
}), result;
}
var baseClone_default = baseClone;
// node_modules/lodash-es/cloneDeep.js
init_process();
var CLONE_DEEP_FLAG2 = 1, CLONE_SYMBOLS_FLAG2 = 4;
function cloneDeep(value) {
return baseClone_default(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2);
}
var cloneDeep_default = cloneDeep;
// node_modules/lodash-es/_baseIteratee.js
init_process();
// node_modules/lodash-es/_baseMatches.js
init_process();
// node_modules/lodash-es/_baseIsMatch.js
init_process();
// node_modules/lodash-es/_baseIsEqual.js
init_process();
// node_modules/lodash-es/_baseIsEqualDeep.js
init_process();
// node_modules/lodash-es/_equalArrays.js
init_process();
// node_modules/lodash-es/_SetCache.js
init_process();
// node_modules/lodash-es/_setCacheAdd.js
init_process();
var HASH_UNDEFINED3 = "__lodash_hash_undefined__";
function setCacheAdd(value) {
return this.__data__.set(value, HASH_UNDEFINED3), this;
}
var setCacheAdd_default = setCacheAdd;
// node_modules/lodash-es/_setCacheHas.js
init_process();
function setCacheHas(value) {
return this.__data__.has(value);
}
var setCacheHas_default = setCacheHas;
// node_modules/lodash-es/_SetCache.js
function SetCache(values) {
var index = -1, length = values == null ? 0 : values.length;
for (this.__data__ = new MapCache_default(); ++index < length; )
this.add(values[index]);
}
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd_default;
SetCache.prototype.has = setCacheHas_default;
var SetCache_default = SetCache;
// node_modules/lodash-es/_arraySome.js
init_process();
function arraySome(array, predicate) {
for (var index = -1, length = array == null ? 0 : array.length; ++index < length; )
if (predicate(array[index], index, array))
return !0;
return !1;
}
var arraySome_default = arraySome;
// node_modules/lodash-es/_cacheHas.js
init_process();
function cacheHas(cache, key) {
return cache.has(key);
}
var cacheHas_default = cacheHas;
// node_modules/lodash-es/_equalArrays.js
var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2;
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength))
return !1;
var arrStacked = stack.get(array), othStacked = stack.get(other);
if (arrStacked && othStacked)
return arrStacked == other && othStacked == array;
var index = -1, result = !0, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache_default() : void 0;
for (stack.set(array, other), stack.set(other, array); ++index < arrLength; ) {
var arrValue = array[index], othValue = other[index];
if (customizer)
var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
if (compared !== void 0) {
if (compared)
continue;
result = !1;
break;
}
if (seen) {
if (!arraySome_default(other, function(othValue2, othIndex) {
if (!cacheHas_default(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack)))
return seen.push(othIndex);
})) {
result = !1;
break;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
result = !1;
break;
}
}
return stack.delete(array), stack.delete(other), result;
}
var equalArrays_default = equalArrays;
// node_modules/lodash-es/_equalByTag.js
init_process();
// node_modules/lodash-es/_mapToArray.js
init_process();
function mapToArray(map) {
var index = -1, result = Array(map.size);
return map.forEach(function(value, key) {
result[++index] = [key, value];
}), result;
}
var mapToArray_default = mapToArray;
// node_modules/lodash-es/_setToArray.js
init_process();
function setToArray(set2) {
var index = -1, result = Array(set2.size);
return set2.forEach(function(value) {
result[++index] = value;
}), result;
}
var setToArray_default = setToArray;
// node_modules/lodash-es/_equalByTag.js
var COMPARE_PARTIAL_FLAG2 = 1, COMPARE_UNORDERED_FLAG2 = 2, boolTag4 = "[object Boolean]", dateTag4 = "[object Date]", errorTag3 = "[object Error]", mapTag6 = "[object Map]", numberTag4 = "[object Number]", regexpTag4 = "[object RegExp]", setTag6 = "[object Set]", stringTag4 = "[object String]", symbolTag4 = "[object Symbol]", arrayBufferTag4 = "[object ArrayBuffer]", dataViewTag5 = "[object DataView]", symbolProto3 = Symbol_default ? Symbol_default.prototype : void 0, symbolValueOf2 = symbolProto3 ? symbolProto3.valueOf : void 0;
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag5:
if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset)
return !1;
object = object.buffer, other = other.buffer;
case arrayBufferTag4:
return !(object.byteLength != other.byteLength || !equalFunc(new Uint8Array_default(object), new Uint8Array_default(other)));
case boolTag4:
case dateTag4:
case numberTag4:
return eq_default(+object, +other);
case errorTag3:
return object.name == other.name && object.message == other.message;
case regexpTag4:
case stringTag4:
return object == other + "";
case mapTag6:
var convert2 = mapToArray_default;
case setTag6:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG2;
if (convert2 || (convert2 = setToArray_default), object.size != other.size && !isPartial)
return !1;
var stacked = stack.get(object);
if (stacked)
return stacked == other;
bitmask |= COMPARE_UNORDERED_FLAG2, stack.set(object, other);
var result = equalArrays_default(convert2(object), convert2(other), bitmask, customizer, equalFunc, stack);
return stack.delete(object), result;
case symbolTag4:
if (symbolValueOf2)
return symbolValueOf2.call(object) == symbolValueOf2.call(other);
}
return !1;
}
var equalByTag_default = equalByTag;
// node_modules/lodash-es/_equalObjects.js
init_process();
var COMPARE_PARTIAL_FLAG3 = 1, objectProto14 = Object.prototype, hasOwnProperty11 = objectProto14.hasOwnProperty;
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG3, objProps = getAllKeys_default(object), objLength = objProps.length, othProps = getAllKeys_default(other), othLength = othProps.length;
if (objLength != othLength && !isPartial)
return !1;
for (var index = objLength; index--; ) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty11.call(other, key)))
return !1;
}
var objStacked = stack.get(object), othStacked = stack.get(other);
if (objStacked && othStacked)
return objStacked == other && othStacked == object;
var result = !0;
stack.set(object, other), stack.set(other, object);
for (var skipCtor = isPartial; ++index < objLength; ) {
key = objProps[index];
var objValue = object[key], othValue = other[key];
if (customizer)
var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
result = !1;
break;
}
skipCtor || (skipCtor = key == "constructor");
}
if (result && !skipCtor) {
var objCtor = object.constructor, othCtor = other.constructor;
objCtor != othCtor && "constructor" in object && "constructor" in other && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor) && (result = !1);
}
return stack.delete(object), stack.delete(other), result;
}
var equalObjects_default = equalObjects;
// node_modules/lodash-es/_baseIsEqualDeep.js
var COMPARE_PARTIAL_FLAG4 = 1, argsTag4 = "[object Arguments]", arrayTag3 = "[object Array]", objectTag4 = "[object Object]", objectProto15 = Object.prototype, hasOwnProperty12 = objectProto15.hasOwnProperty;
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray_default(object), othIsArr = isArray_default(other), objTag = objIsArr ? arrayTag3 : getTag_default(object), othTag = othIsArr ? arrayTag3 : getTag_default(other);
objTag = objTag == argsTag4 ? objectTag4 : objTag, othTag = othTag == argsTag4 ? objectTag4 : othTag;
var objIsObj = objTag == objectTag4, othIsObj = othTag == objectTag4, isSameTag = objTag == othTag;
if (isSameTag && isBuffer_default(object)) {
if (!isBuffer_default(other))
return !1;
objIsArr = !0, objIsObj = !1;
}
if (isSameTag && !objIsObj)
return stack || (stack = new Stack_default()), objIsArr || isTypedArray_default(object) ? equalArrays_default(object, other, bitmask, customizer, equalFunc, stack) : equalByTag_default(object, other, objTag, bitmask, customizer, equalFunc, stack);
if (!(bitmask & COMPARE_PARTIAL_FLAG4)) {
var objIsWrapped = objIsObj && hasOwnProperty12.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty12.call(other, "__wrapped__");
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
return stack || (stack = new Stack_default()), equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
return isSameTag ? (stack || (stack = new Stack_default()), equalObjects_default(object, other, bitmask, customizer, equalFunc, stack)) : !1;
}
var baseIsEqualDeep_default = baseIsEqualDeep;
// node_modules/lodash-es/_baseIsEqual.js
function baseIsEqual(value, other, bitmask, customizer, stack) {
return value === other ? !0 : value == null || other == null || !isObjectLike_default(value) && !isObjectLike_default(other) ? value !== value && other !== other : baseIsEqualDeep_default(value, other, bitmask, customizer, baseIsEqual, stack);
}
var baseIsEqual_default = baseIsEqual;
// node_modules/lodash-es/_baseIsMatch.js
var COMPARE_PARTIAL_FLAG5 = 1, COMPARE_UNORDERED_FLAG3 = 2;
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length, length = index, noCustomizer = !customizer;
if (object == null)
return !length;
for (object = Object(object); index--; ) {
var data = matchData[index];
if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object))
return !1;
}
for (; ++index < length; ) {
data = matchData[index];
var key = data[0], objValue = object[key], srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === void 0 && !(key in object))
return !1;
} else {
var stack = new Stack_default();
if (customizer)
var result = customizer(objValue, srcValue, key, object, source, stack);
if (!(result === void 0 ? baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG5 | COMPARE_UNORDERED_FLAG3, customizer, stack) : result))
return !1;
}
}
return !0;
}
var baseIsMatch_default = baseIsMatch;
// node_modules/lodash-es/_getMatchData.js
init_process();
// node_modules/lodash-es/_isStrictComparable.js
init_process();
function isStrictComparable(value) {
return value === value && !isObject_default(value);
}
var isStrictComparable_default = isStrictComparable;
// node_modules/lodash-es/_getMatchData.js
function getMatchData(object) {
for (var result = keys_default(object), length = result.length; length--; ) {
var key = result[length], value = object[key];
result[length] = [key, value, isStrictComparable_default(value)];
}
return result;
}
var getMatchData_default = getMatchData;
// node_modules/lodash-es/_matchesStrictComparable.js
init_process();
function matchesStrictComparable(key, srcValue) {
return function(object) {
return object == null ? !1 : object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
};
}
var matchesStrictComparable_default = matchesStrictComparable;
// node_modules/lodash-es/_baseMatches.js
function baseMatches(source) {
var matchData = getMatchData_default(source);
return matchData.length == 1 && matchData[0][2] ? matchesStrictComparable_default(matchData[0][0], matchData[0][1]) : function(object) {
return object === source || baseIsMatch_default(object, source, matchData);
};
}
var baseMatches_default = baseMatches;
// node_modules/lodash-es/_baseMatchesProperty.js
init_process();
// node_modules/lodash-es/hasIn.js
init_process();
// node_modules/lodash-es/_baseHasIn.js
init_process();
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
var baseHasIn_default = baseHasIn;
// node_modules/lodash-es/_hasPath.js
init_process();
function hasPath(object, path, hasFunc) {
path = castPath_default(path, object);
for (var index = -1, length = path.length, result = !1; ++index < length; ) {
var key = toKey_default(path[index]);
if (!(result = object != null && hasFunc(object, key)))
break;
object = object[key];
}
return result || ++index != length ? result : (length = object == null ? 0 : object.length, !!length && isLength_default(length) && isIndex_default(key, length) && (isArray_default(object) || isArguments_default(object)));
}
var hasPath_default = hasPath;
// node_modules/lodash-es/hasIn.js
function hasIn(object, path) {
return object != null && hasPath_default(object, path, baseHasIn_default);
}
var hasIn_default = hasIn;
// node_modules/lodash-es/_baseMatchesProperty.js
var COMPARE_PARTIAL_FLAG6 = 1, COMPARE_UNORDERED_FLAG4 = 2;
function baseMatchesProperty(path, srcValue) {
return isKey_default(path) && isStrictComparable_default(srcValue) ? matchesStrictComparable_default(toKey_default(path), srcValue) : function(object) {
var objValue = get_default(object, path);
return objValue === void 0 && objValue === srcValue ? hasIn_default(object, path) : baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG6 | COMPARE_UNORDERED_FLAG4);
};
}
var baseMatchesProperty_default = baseMatchesProperty;
// node_modules/lodash-es/property.js
init_process();
// node_modules/lodash-es/_baseProperty.js
init_process();
function baseProperty(key) {
return function(object) {
return object == null ? void 0 : object[key];
};
}
var baseProperty_default = baseProperty;
// node_modules/lodash-es/_basePropertyDeep.js
init_process();
function basePropertyDeep(path) {
return function(object) {
return baseGet_default(object, path);
};
}
var basePropertyDeep_default = basePropertyDeep;
// node_modules/lodash-es/property.js
function property(path) {
return isKey_default(path) ? baseProperty_default(toKey_default(path)) : basePropertyDeep_default(path);
}
var property_default = property;
// node_modules/lodash-es/_baseIteratee.js
function baseIteratee(value) {
return typeof value == "function" ? value : value == null ? identity_default : typeof value == "object" ? isArray_default(value) ? baseMatchesProperty_default(value[0], value[1]) : baseMatches_default(value) : property_default(value);
}
var baseIteratee_default = baseIteratee;
// node_modules/lodash-es/debounce.js
init_process();
// node_modules/lodash-es/now.js
init_process();
var now = function() {
return root_default.Date.now();
}, now_default = now;
// node_modules/lodash-es/debounce.js
var FUNC_ERROR_TEXT2 = "Expected a function", nativeMax = Math.max, nativeMin = Math.min;
function debounce(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = !1, maxing = !1, trailing = !0;
if (typeof func != "function")
throw new TypeError(FUNC_ERROR_TEXT2);
wait = toNumber_default(wait) || 0, isObject_default(options) && (leading = !!options.leading, maxing = "maxWait" in options, maxWait = maxing ? nativeMax(toNumber_default(options.maxWait) || 0, wait) : maxWait, trailing = "trailing" in options ? !!options.trailing : trailing);
function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
return lastArgs = lastThis = void 0, lastInvokeTime = time, result = func.apply(thisArg, args), result;
}
function leadingEdge(time) {
return lastInvokeTime = time, timerId = setTimeout(timerExpired, wait), leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = now_default();
if (shouldInvoke(time))
return trailingEdge(time);
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
return timerId = void 0, trailing && lastArgs ? invokeFunc(time) : (lastArgs = lastThis = void 0, result);
}
function cancel() {
timerId !== void 0 && clearTimeout(timerId), lastInvokeTime = 0, lastArgs = lastCallTime = lastThis = timerId = void 0;
}
function flush() {
return timerId === void 0 ? result : trailingEdge(now_default());
}
function debounced() {
var time = now_default(), isInvoking = shouldInvoke(time);
if (lastArgs = arguments, lastThis = this, lastCallTime = time, isInvoking) {
if (timerId === void 0)
return leadingEdge(lastCallTime);
if (maxing)
return clearTimeout(timerId), timerId = setTimeout(timerExpired, wait), invokeFunc(lastCallTime);
}
return timerId === void 0 && (timerId = setTimeout(timerExpired, wait)), result;
}
return debounced.cancel = cancel, debounced.flush = flush, debounced;
}
var debounce_default = debounce;
// node_modules/lodash-es/_arrayIncludesWith.js
init_process();
function arrayIncludesWith(array, value, comparator) {
for (var index = -1, length = array == null ? 0 : array.length; ++index < length; )
if (comparator(value, array[index]))
return !0;
return !1;
}
var arrayIncludesWith_default = arrayIncludesWith;
// node_modules/lodash-es/isEqual.js
init_process();
function isEqual(value, other) {
return baseIsEqual_default(value, other);
}
var isEqual_default = isEqual;
// node_modules/lodash-es/isRegExp.js
init_process();
// node_modules/lodash-es/_baseIsRegExp.js
init_process();
var regexpTag5 = "[object RegExp]";
function baseIsRegExp(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == regexpTag5;
}
var baseIsRegExp_default = baseIsRegExp;
// node_modules/lodash-es/isRegExp.js
var nodeIsRegExp = nodeUtil_default && nodeUtil_default.isRegExp, isRegExp = nodeIsRegExp ? baseUnary_default(nodeIsRegExp) : baseIsRegExp_default, isRegExp_default = isRegExp;
// node_modules/lodash-es/_baseSet.js
init_process();
function baseSet(object, path, value, customizer) {
if (!isObject_default(object))
return object;
path = castPath_default(path, object);
for (var index = -1, length = path.length, lastIndex = length - 1, nested = object; nested != null && ++index < length; ) {
var key = toKey_default(path[index]), newValue = value;
if (key === "__proto__" || key === "constructor" || key === "prototype")
return object;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : void 0, newValue === void 0 && (newValue = isObject_default(objValue) ? objValue : isIndex_default(path[index + 1]) ? [] : {});
}
assignValue_default(nested, key, newValue), nested = nested[key];
}
return object;
}
var baseSet_default = baseSet;
// node_modules/lodash-es/_stringSize.js
init_process();
// node_modules/lodash-es/_asciiSize.js
init_process();
var asciiSize = baseProperty_default("length"), asciiSize_default = asciiSize;
// node_modules/lodash-es/_unicodeSize.js
init_process();
var rsAstralRange3 = "\\\\ud800-\\\\udfff", rsComboMarksRange3 = "\\\\u0300-\\\\u036f", reComboHalfMarksRange3 = "\\\\ufe20-\\\\ufe2f", rsComboSymbolsRange3 = "\\\\u20d0-\\\\u20ff", rsComboRange3 = rsComboMarksRange3 + reComboHalfMarksRange3 + rsComboSymbolsRange3, rsVarRange3 = "\\\\ufe0e\\\\ufe0f", rsAstral2 = "[" + rsAstralRange3 + "]", rsCombo2 = "[" + rsComboRange3 + "]", rsFitz2 = "\\\\ud83c[\\\\udffb-\\\\udfff]", rsModifier2 = "(?:" + rsCombo2 + "|" + rsFitz2 + ")", rsNonAstral2 = "[^" + rsAstralRange3 + "]", rsRegional2 = "(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}", rsSurrPair2 = "[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]", rsZWJ3 = "\\\\u200d", reOptMod2 = rsModifier2 + "?", rsOptVar2 = "[" + rsVarRange3 + "]?", rsOptJoin2 = "(?:" + rsZWJ3 + "(?:" + [rsNonAstral2, rsRegional2, rsSurrPair2].join("|") + ")" + rsOptVar2 + reOptMod2 + ")*", rsSeq2 = rsOptVar2 + reOptMod2 + rsOptJoin2, rsSymbol2 = "(?:" + [rsNonAstral2 + rsCombo2 + "?", rsCombo2, rsRegional2, rsSurrPair2, rsAstral2].join("|") + ")", reUnicode2 = RegExp(rsFitz2 + "(?=" + rsFitz2 + ")|" + rsSymbol2 + rsSeq2, "g");
function unicodeSize(string) {
for (var result = reUnicode2.lastIndex = 0; reUnicode2.test(string); )
++result;
return result;
}
var unicodeSize_default = unicodeSize;
// node_modules/lodash-es/_stringSize.js
function stringSize(string) {
return hasUnicode_default(string) ? unicodeSize_default(string) : asciiSize_default(string);
}
var stringSize_default = stringSize;
// node_modules/lodash-es/set.js
init_process();
function set(object, path, value) {
return object == null ? object : baseSet_default(object, path, value);
}
var set_default = set;
// node_modules/lodash-es/truncate.js
init_process();
var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "...", reFlags2 = /\\w*$/;
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION;
if (isObject_default(options)) {
var separator = "separator" in options ? options.separator : separator;
length = "length" in options ? toInteger_default(options.length) : length, omission = "omission" in options ? baseToString_default(options.omission) : omission;
}
string = toString_default(string);
var strLength = string.length;
if (hasUnicode_default(string)) {
var strSymbols = stringToArray_default(string);
strLength = strSymbols.length;
}
if (length >= strLength)
return string;
var end = length - stringSize_default(omission);
if (end < 1)
return omission;
var result = strSymbols ? castSlice_default(strSymbols, 0, end).join("") : string.slice(0, end);
if (separator === void 0)
return result + omission;
if (strSymbols && (end += result.length - end), isRegExp_default(separator)) {
if (string.slice(end).search(separator)) {
var match, substring = result;
for (separator.global || (separator = RegExp(separator.source, toString_default(reFlags2.exec(separator)) + "g")), separator.lastIndex = 0; match = separator.exec(substring); )
var newEnd = match.index;
result = result.slice(0, newEnd === void 0 ? end : newEnd);
}
} else if (string.indexOf(baseToString_default(separator), end) != end) {
var index = result.lastIndexOf(separator);
index > -1 && (result = result.slice(0, index));
}
return result + omission;
}
var truncate_default = truncate;
// node_modules/lodash-es/_baseUniq.js
init_process();
// node_modules/lodash-es/_createSet.js
init_process();
var INFINITY4 = 1 / 0, createSet = Set_default && 1 / setToArray_default(new Set_default([, -0]))[1] == INFINITY4 ? function(values) {
return new Set_default(values);
} : noop_default, createSet_default = createSet;
// node_modules/lodash-es/_baseUniq.js
var LARGE_ARRAY_SIZE2 = 200;
function baseUniq(array, iteratee, comparator) {
var index = -1, includes = arrayIncludes_default, length = array.length, isCommon = !0, result = [], seen = result;
if (comparator)
isCommon = !1, includes = arrayIncludesWith_default;
else if (length >= LARGE_ARRAY_SIZE2) {
var set2 = iteratee ? null : createSet_default(array);
if (set2)
return setToArray_default(set2);
isCommon = !1, includes = cacheHas_default, seen = new SetCache_default();
} else
seen = iteratee ? [] : result;
outer:
for (; ++index < length; ) {
var value = array[index], computed = iteratee ? iteratee(value) : value;
if (value = comparator || value !== 0 ? value : 0, isCommon && computed === computed) {
for (var seenIndex = seen.length; seenIndex--; )
if (seen[seenIndex] === computed)
continue outer;
iteratee && seen.push(computed), result.push(value);
} else includes(seen, computed, comparator) || (seen !== result && seen.push(computed), result.push(value));
}
return result;
}
var baseUniq_default = baseUniq;
// node_modules/lodash-es/uniqBy.js
init_process();
function uniqBy(array, iteratee) {
return array && array.length ? baseUniq_default(array, baseIteratee_default(iteratee, 2)) : [];
}
var uniqBy_default = uniqBy;
// src-copilot/frontend-chat/components/tools-ui/ItemSelectionTable.jsx
var ItemSelectionTable = ({
status,
itemContainerList,
setItemContainerList,
oldItemContainerList
}) => {
let isThisToolMessageLast = AssistantUI.useMessage((m) => m.isLast), isDiffView = !!oldItemContainerList, itemsToIterate = itemContainerList, keySet = /* @__PURE__ */ new Set();
itemContainerList.forEach((itemContainer) => {
Object.keys(itemContainer.item).forEach((key) => keySet.add(key));
}), isDiffView && oldItemContainerList.forEach((itemContainer) => {
Object.keys(itemContainer.item).forEach((key) => keySet.add(key));
});
let allItemKeys = ["uuid", ...Array.from(keySet).filter((k) => k !== "uuid")], formatStringValue = (value, key) => {
if (value === void 0) return "";
if (value === null) return "null";
if (typeof value == "boolean") return value.toString();
try {
if (isNaN(value) && typeof value == "string" && isNaN(Number(value))) {
let date = new Date(value);
if (isNaN(date.getTime())) throw new Error("Invalid date");
return date.toLocaleString();
}
} catch {
}
return typeof value == "object" ? JSON.stringify(value) : value.toString();
}, handleCheckedChange = (checked, index) => {
let newList = [...itemContainerList];
newList[index].checked = checked, setItemContainerList(newList);
}, renderCell = (itemContainer, index, key) => {
let valueToDisplay = itemContainer.item[key];
if (isDiffView) {
let oldValue = oldItemContainerList[index].item[key], isChanged = key in itemContainer.item;
if (isChanged && oldValue !== valueToDisplay) {
let StringDiff = window.StringDiff;
return /* @__PURE__ */ React.createElement(
StringDiff,
{
method: "diffSentences",
styles: {
added: {
backgroundColor: "#0bbf7d"
},
removed: {
backgroundColor: "#ff6b6b"
}
},
oldValue: formatStringValue(oldValue),
newValue: formatStringValue(valueToDisplay),
showDiff: !0
}
);
}
isChanged || (valueToDisplay = oldValue);
}
return key.toLowerCase().includes("uuid") ? /* @__PURE__ */ React.createElement(TruncatedUUID, { value: valueToDisplay }) : formatStringValue(valueToDisplay);
}, { Table, Checkbox } = window.RadixUI, { CheckIcon, InfoCircledIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(Table.Root, null, /* @__PURE__ */ React.createElement(Table.Header, null, /* @__PURE__ */ React.createElement(Table.Row, null, /* @__PURE__ */ React.createElement(Table.ColumnHeaderCell, { style: { verticalAlign: "middle" } }, /* @__PURE__ */ React.createElement(CheckIcon, null)), allItemKeys.map((key) => /* @__PURE__ */ React.createElement(Table.ColumnHeaderCell, { key }, key)))), /* @__PURE__ */ React.createElement(Table.Body, null, itemsToIterate.map((itemContainer, index) => /* @__PURE__ */ React.createElement(Table.Row, { key: index }, /* @__PURE__ */ React.createElement(Table.RowHeaderCell, null, /* @__PURE__ */ React.createElement(
Checkbox,
{
checked: itemContainer.checked,
disabled: status === "requires-action" || !isThisToolMessageLast,
onCheckedChange: (checked) => handleCheckedChange(checked, index)
}
)), allItemKeys.map((key) => /* @__PURE__ */ React.createElement(Table.Cell, { key }, renderCell(itemContainer, index, key)))))));
}, TruncatedUUID = ({ value }) => {
let truncated = truncate_default(value, { length: 5, omission: "..." }), { InfoCircledIcon } = window.RadixIcons, { Flex, Tooltip } = window.RadixUI;
return /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, /* @__PURE__ */ React.createElement("span", null, truncated), /* @__PURE__ */ React.createElement(Tooltip, { content: value || "New UUID" }, /* @__PURE__ */ React.createElement(Flex, { align: "center", css: { cursor: "help" } }, /* @__PURE__ */ React.createElement(InfoCircledIcon, null))));
};
// src-copilot/frontend-chat/components/tools-ui/ToolFooter.jsx
init_process();
var ToolFooter = ({
submitButtonText = "Submit",
cancelButtonText = "Cancel",
status,
setFormState,
shouldDisplayNoteSelector = !1,
noteSelectionArr,
currentNoteSelectionUUID,
setCurrentNoteSelectionUUID,
disableNoteSelector = !1
}) => {
let isThisToolMessageLast = AssistantUI.useMessage((m) => m.isLast), isActionDestructive = submitButtonText.toLowerCase().includes("delete") || submitButtonText.toLowerCase().includes("remove"), { Flex, Button } = window.RadixUI;
return /* @__PURE__ */ React.createElement(Flex, { gap: "10px", justify: "between", style: { marginTop: "10px" } }, shouldDisplayNoteSelector ? /* @__PURE__ */ React.createElement(
NoteSelector,
{
noteSelectionArr,
currentNoteSelectionUUID,
setCurrentNoteSelectionUUID,
disableNoteSelector,
status
}
) : /* @__PURE__ */ React.createElement("span", null), /* @__PURE__ */ React.createElement(Flex, { justify: "end", align: "center" }, /* @__PURE__ */ React.createElement(
Button,
{
variant: "ghost",
color: "red",
highContrast: !0,
disabled: status === "requires-action" || !isThisToolMessageLast,
onClick: () => {
setFormState("canceled");
},
style: { marginRight: "10px" }
},
cancelButtonText
), /* @__PURE__ */ React.createElement(
Button,
{
color: isActionDestructive ? "red" : "primary",
disabled: status === "requires-action" || !isThisToolMessageLast,
onClick: () => {
setFormState("submitted");
}
},
submitButtonText
)));
}, NoteSelector = ({
noteSelectionArr = [],
currentNoteSelectionUUID,
setCurrentNoteSelectionUUID,
status,
disableNoteSelector
}) => {
let isThisToolMessageLast = AssistantUI.useMessage((m) => m.isLast), currentNote = noteSelectionArr.find((note) => note.uuid === currentNoteSelectionUUID), displayTitle = currentNote != null && currentNote.title ? truncate_default(currentNote.title, { length: 12 }) : "Select Note", { Select } = window.RadixUI, { FileTextIcon } = window.RadixIcons, isDisabled = status === "requires-action" || !isThisToolMessageLast || disableNoteSelector, [open, setOpen] = React.useState(!1), selectRef = React.useRef(null);
return React.useEffect(() => {
let handleClickOutside = (event) => {
selectRef.current && !selectRef.current.contains(event.target) && setOpen(!1);
};
return open && document.addEventListener("mousedown", handleClickOutside), () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [open]), /* @__PURE__ */ React.createElement(
Select.Root,
{
open,
disabled: isDisabled,
value: currentNoteSelectionUUID,
onValueChange: (value) => {
console.log(value), setCurrentNoteSelectionUUID(value), setOpen(!1);
},
className: "note-selector"
},
/* @__PURE__ */ React.createElement(
Select.Trigger,
{
onClick: (e) => {
isDisabled || setOpen(!open);
}
},
/* @__PURE__ */ React.createElement(
FileTextIcon,
{
style: {
display: "inline-block",
marginRight: "5px",
marginTop: "-4px"
}
}
),
displayTitle
),
/* @__PURE__ */ React.createElement(Select.Content, { position: "popper", sideOffset: 5, ref: selectRef }, noteSelectionArr.map((note) => /* @__PURE__ */ React.createElement(Select.Item, { key: note.uuid, value: note.uuid, className: "select-item" }, /* @__PURE__ */ React.createElement("span", null, note.title), /* @__PURE__ */ React.createElement("span", { style: { fontSize: "8px", display: "block", lineHeight: "1" } }, note.uuid))))
);
};
// src-copilot/frontend-chat/components/tools-ui/ToolCardResultMessage.jsx
init_process();
var ToolCardResultMessage = ({ children, icon, text, result, input, toolName, color = !1, disabled = !1 }) => {
let [isCollapsed, setIsCollapsed] = React.useState(!0), [resolvedIcon, setResolvedIcon] = React.useState(icon), toggleCollapse = () => {
setIsCollapsed(!isCollapsed);
};
React.useEffect(() => {
if (window.RadixIcons && !icon) {
let { CheckCircledIcon } = window.RadixIcons;
setResolvedIcon(/* @__PURE__ */ React.createElement(CheckCircledIcon, null));
}
}, [icon]);
let { Text, Button, ChevronDownIcon, ScrollArea, Code, Flex, Separator } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Flex, { justify: "between", align: "center" }, !children && /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, resolvedIcon, text && (typeof text == "string" ? /* @__PURE__ */ React.createElement(Text, { color }, text) : text)), children, /* @__PURE__ */ React.createElement(Button, { onClick: toggleCollapse, size: "1", variant: "soft", disabled }, /* @__PURE__ */ React.createElement(ChevronDownIcon, { style: { transform: isCollapsed ? "rotate(0deg)" : "rotate(180deg)" } }))), !isCollapsed && /* @__PURE__ */ React.createElement("div", { style: { marginTop: "6px", position: "relative" } }, /* @__PURE__ */ React.createElement(ScrollArea, { scrollbars: "horizontal", style: { paddingBottom: "6px" } }, toolName && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Tool ID:"), /* @__PURE__ */ React.createElement(Text, null, toolName), /* @__PURE__ */ React.createElement(Separator, { size: "4", style: { margin: "8px 0" } })), input && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Input:"), /* @__PURE__ */ React.createElement(Code, { highContrast: !0, wrap: "nowrap" }, typeof input == "string" ? input : JSON.stringify(input)), /* @__PURE__ */ React.createElement(Separator, { size: "4", style: { margin: "8px 0" } })), /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Output:"), /* @__PURE__ */ React.createElement(Code, { highContrast: !0, wrap: "nowrap", className: "aui-tool-result" }, typeof result == "string" ? result : JSON.stringify(result)))));
};
// src-copilot/frontend-chat/tools-core/base/createGenericCUDTool.jsx
init_process();
// src-copilot/frontend-chat/components/tools-ui/ToolCardMessage.jsx
init_process();
var ToolCardMessage = ({ icon, text, color = !1 }) => {
let { Text, Flex } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, icon && icon, /* @__PURE__ */ React.createElement(Text, { color }, text)));
};
// src-copilot/frontend-chat/hooks/useGenericToolFormState.jsx
init_process();
// src-copilot/frontend-chat/helpers/errorToString.js
init_process();
var errorToString = (error) => {
let baseMessage = null;
if (typeof error == "string")
baseMessage = error;
else if (error instanceof Error)
baseMessage = error.message;
else if (error && typeof error.message == "string")
baseMessage = error.message;
else if (error && typeof error.error == "string")
baseMessage = error.error;
else if (error != null)
try {
baseMessage = String(error);
} catch {
}
baseMessage || (baseMessage = JSON.stringify(error));
let processedMessage = (typeof baseMessage == "string" ? baseMessage : "").trim(), prefixPattern = /^(Error\\s*:\\s*)+/i;
return processedMessage = processedMessage.replace(prefixPattern, ""), processedMessage = processedMessage.trim(), processedMessage;
};
// src-copilot/frontend-chat/components/tools-ui/ToolCardErrorMessage.jsx
init_process();
var ToolCardErrorMessage = ({ icon, text, toolName, input }) => {
let [isCollapsed, setIsCollapsed] = React.useState(!0), [resolvedIcon, setResolvedIcon] = React.useState(icon), toggleCollapse = () => {
setIsCollapsed(!isCollapsed);
};
React.useEffect(() => {
if (window.RadixIcons && !icon) {
let { ExclamationTriangleIcon } = window.RadixIcons;
setResolvedIcon(/* @__PURE__ */ React.createElement(ExclamationTriangleIcon, null));
}
}, [icon]);
let { Text, Button, ChevronDownIcon, ScrollArea, Code, Flex, Separator } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Flex, { justify: "between", align: "center" }, /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, resolvedIcon && resolvedIcon, text && /* @__PURE__ */ React.createElement(Text, { style: { color: "var(--red-9)" } }, text)), /* @__PURE__ */ React.createElement(Button, { onClick: toggleCollapse, size: "1", variant: "soft" }, /* @__PURE__ */ React.createElement(ChevronDownIcon, { style: { transform: isCollapsed ? "rotate(0deg)" : "rotate(180deg)" } }))), !isCollapsed && /* @__PURE__ */ React.createElement("div", { style: { marginTop: "6px", position: "relative" } }, /* @__PURE__ */ React.createElement(ScrollArea, { scrollbars: "horizontal", style: { paddingBottom: "6px" } }, toolName && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Tool Name:"), /* @__PURE__ */ React.createElement(Text, null, toolName), /* @__PURE__ */ React.createElement(Separator, { size: "4", style: { margin: "8px 0" } })), input && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Input:"), /* @__PURE__ */ React.createElement(Code, { highContrast: !0, wrap: "nowrap" }, typeof input == "string" ? input : JSON.stringify(input, null, 2))))));
};
// src-copilot/frontend-chat/hooks/useGenericToolFormState.jsx
var useGenericToolFormState = (states, params = {}) => {
var _a, _b;
if (!states || typeof states != "object")
throw new Error("useGenericToolFormState: states must be an object");
let stateNames = Object.keys(states);
if (!stateNames.includes("error") || !stateNames.includes("init") || !stateNames.includes("completed") || !stateNames.includes("booting"))
throw new Error("useGenericToolFormState: states must have error, init, completed, and booting states");
if (states != null && states.booting.eventHandler || (_a = states.error) != null && _a.eventHandler || (_b = states.canceled) != null && _b.eventHandler)
throw new Error("useGenericToolFormState: states.booting, states.error, and states.canceled must not have eventHandlers");
let [formState, setFormState] = React.useState(), render = (props) => {
var _a2;
let { ErrorBoundary } = window.ReactErrorBoundary, originalRender = ((_a2 = states[formState]) == null ? void 0 : _a2.renderer) || (() => null);
return /* @__PURE__ */ React.createElement(ErrorBoundary, { fallbackRender: (e) => /* @__PURE__ */ React.createElement(
ToolCardErrorMessage,
{
toolName: params.toolName,
input: params.args,
text: "Unhandled Error occurred: " + errorToString(e),
color: "red"
}
) }, originalRender ? React.createElement(originalRender, props) : null);
}, toolCallId = params.toolCallId, message = AssistantUI.useMessage(), threadRuntime = AssistantUI.useThreadRuntime(), cleanupHasRun = React.useRef(!1);
React.useEffect(() => {
if (formState || params.status.type === "running") return;
let toolStateInChatHistory = get_default(message, \`metadata.custom.toolStateStorage.\${toolCallId}\`);
toolStateInChatHistory && toolStateInChatHistory.formState ? (setFormState(toolStateInChatHistory.formState), params.setFormData(toolStateInChatHistory.formData), params.setFormError(toolStateInChatHistory.formError), (toolStateInChatHistory.formState === "error" || toolStateInChatHistory.formState === "canceled") && (cleanupHasRun.current = !0)) : setFormState("booting");
}, [params.args, params.status, message]);
let { formData, formError } = params;
return React.useEffect(() => {
formState && set_default(message, \`metadata.custom.toolStateStorage.\${toolCallId}\`, {
formState,
formData,
formError
});
}, [formState, formData, formError, message]), React.useEffect(() => {
if (formState !== "booting") return;
let handleBootingToInit = () => {
var _a2;
let allToolCalls = ((_a2 = message.content) == null ? void 0 : _a2.filter((c) => c.type === "tool-call")) || [], toolIndex = allToolCalls.findIndex((tc) => tc.toolCallId === toolCallId), allPreviousToolsCompleted = !0;
for (let i = 0; i < toolIndex; i++) {
let prevToolId = allToolCalls[i].toolCallId, prevToolState = get_default(message, \`metadata.custom.toolStateStorage.\${prevToolId}\`);
if ((prevToolState == null ? void 0 : prevToolState.formState) !== "completed" && (prevToolState == null ? void 0 : prevToolState.formState) !== "error") {
allPreviousToolsCompleted = !1;
break;
}
}
allPreviousToolsCompleted && setFormState("init");
};
return window.addEventListener("onToolStateChangeComplete", handleBootingToInit), handleBootingToInit(), () => {
window.removeEventListener("onToolStateChangeComplete", handleBootingToInit);
};
}, [formState, message]), React.useEffect(() => {
!formState || params.result || (async () => {
var _a2, _b2, _c, _d;
window.dispatchEvent(new CustomEvent("onToolStateChange", { detail: formState })), console.log("onToolStateChange", params.toolCallId, formState);
try {
if ((formState === "error" || formState === "canceled") && !cleanupHasRun.current) {
cleanupHasRun.current = !0;
let allToolCalls = ((_a2 = message.content) == null ? void 0 : _a2.filter((c) => c.type === "tool-call")) || [], currentToolIndex = allToolCalls.findIndex((tc) => tc.toolCallId === toolCallId);
if (currentToolIndex !== -1) {
let subsequentToolCalls = allToolCalls.slice(currentToolIndex + 1);
if (subsequentToolCalls.length > 0) {
let modifiedMessage = cloneDeep_default(message);
modifiedMessage.content = modifiedMessage.content.filter(
(c) => c.type !== "tool-call" || !subsequentToolCalls.some((stc) => stc.toolCallId === c.toolCallId)
), (_c = (_b2 = modifiedMessage.metadata) == null ? void 0 : _b2.custom) != null && _c.toolStateStorage && subsequentToolCalls.forEach((stc) => delete modifiedMessage.metadata.custom.toolStateStorage[stc.toolCallId]);
let threadState = threadRuntime.export(), modifiedMessages = threadState.messages.map(
(msgWrapper) => msgWrapper.message.id === message.id ? { ...msgWrapper, message: modifiedMessage } : msgWrapper
);
threadRuntime.import({ ...threadState, messages: modifiedMessages }), console.log("Removed subsequent tool calls for tool call", toolCallId);
}
}
formState === "error" && threadRuntime.getMesssageById(message.id).getContentPartByToolCallId(toolCallId).addToolResult(\`Error: \${errorToString(formError)}. Tool invocation failed.\`), formState === "canceled" && (threadRuntime.getMesssageById(message.id).getContentPartByToolCallId(toolCallId).addToolResult("Tool invocation canceled by user. Please do not try again immediately."), threadRuntime.cancelRun());
}
(_d = states[formState]) != null && _d.eventHandler && await states[formState].eventHandler({ ...params, formState, setFormState }), window.dispatchEvent(new CustomEvent("onToolStateChangeComplete", { detail: formState })), console.log("onToolStateChangeComplete", params.toolCallId, formState);
} catch (e) {
console.error(e), params.setFormError(e);
}
})();
}, [formState, threadRuntime]), React.useEffect(() => {
params.formError && formState !== "error" && setFormState("error");
}, [params.formError]), React.useEffect(() => {
formState === "canceled" && (params.addResult("Tool invocation canceled by user. Please do not try again immediately."), threadRuntime.cancelRun());
}, [formState]), [formState, setFormState, render];
};
// src-copilot/frontend-chat/hooks/useGenericToolParameters.jsx
init_process();
// src-copilot/frontend-chat/helpers/truncateObjectVal.js
init_process();
function truncateObjectVal(input, limit, truncationSuffix) {
let jsonInput = JSON.stringify(input);
if (jsonInput.length <= limit)
return input;
let output = JSON.parse(jsonInput), strings = [];
(function findStrings(obj, path) {
for (let [key, value] of Object.entries(obj)) {
let currentPath = path.concat(key);
typeof value == "string" && value.length > truncationSuffix.length ? strings.push({ path: currentPath, value }) : typeof value == "object" && value !== null && findStrings(value, currentPath);
}
})(output, []), strings.sort((a, b) => b.value.length - a.value.length);
let overage = jsonInput.length - limit, setByPath = (obj, path, val) => {
let node2 = obj;
for (let i = 0; i < path.length - 1; i++) node2 = node2[path[i]];
node2[path[path.length - 1]] = val;
};
for (let str of strings) {
if (overage <= 0) break;
let originalLength = str.value.length, reductionAmount = Math.min(overage, originalLength - truncationSuffix.length);
if (reductionAmount <= 0) continue;
let newLength = originalLength - reductionAmount, truncatedValue = str.value.substring(0, newLength) + truncationSuffix;
setByPath(output, str.path, truncatedValue), overage -= originalLength - truncatedValue.length;
}
let finalJson = JSON.stringify(output);
finalJson.length > limit && (finalJson = finalJson.substring(0, limit - truncationSuffix.length) + truncationSuffix);
try {
return JSON.parse(finalJson);
} catch {
return finalJson;
}
}
// src-copilot/frontend-chat/hooks/useGenericToolParameters.jsx
var useGenericToolParameters = ({
toolName,
toolCallId,
description,
parameters,
args,
status,
result,
addResult
}) => {
let [formData, setFormData] = React.useState({}), [formError, setFormError] = React.useState(null), threadRuntime = AssistantUI.useThreadRuntime(), abortControllerRef = React.useRef(new AbortController());
return React.useEffect(() => {
(status == null ? void 0 : status.type) === "ended" && (abortControllerRef.current.abort(), abortControllerRef.current = new AbortController());
}, [status == null ? void 0 : status.type]), {
toolName,
toolCallId,
description,
parameters,
args,
status,
result,
addResult: (input, toolResultLengthLimit = 15e3) => typeof input == "string" ? addResult(truncate_default(input, { length: toolResultLengthLimit, omission: "[truncated tool output]" })) : typeof input == "object" && JSON.stringify(input).length > toolResultLengthLimit ? addResult(truncateObjectVal(input, toolResultLengthLimit, "[truncated tool output]")) : addResult(input),
formError,
setFormError,
formData,
setFormData,
threadRuntime,
signal: abortControllerRef.current.signal
};
};
// src-copilot/frontend-chat/components/tools-ui/ToolCardCanceledMessage.jsx
init_process();
var ToolCardCanceledMessage = ({ icon, text, toolName, input }) => {
let [isCollapsed, setIsCollapsed] = React.useState(!0), [resolvedIcon, setResolvedIcon] = React.useState(icon), toggleCollapse = () => {
setIsCollapsed(!isCollapsed);
};
React.useEffect(() => {
if (window.RadixIcons && !icon) {
let { MinusCircledIcon } = window.RadixIcons;
setResolvedIcon(/* @__PURE__ */ React.createElement(MinusCircledIcon, null));
}
}, [icon]);
let { Text, Button, ChevronDownIcon, ScrollArea, Code, Flex, Separator } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Flex, { justify: "between", align: "center" }, /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, resolvedIcon && resolvedIcon, text && /* @__PURE__ */ React.createElement(Text, null, text)), /* @__PURE__ */ React.createElement(Button, { onClick: toggleCollapse, size: "1", variant: "soft" }, /* @__PURE__ */ React.createElement(ChevronDownIcon, { style: { transform: isCollapsed ? "rotate(0deg)" : "rotate(180deg)" } }))), !isCollapsed && /* @__PURE__ */ React.createElement("div", { style: { marginTop: "6px", position: "relative" } }, /* @__PURE__ */ React.createElement(ScrollArea, { scrollbars: "horizontal", style: { paddingBottom: "6px" } }, toolName && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Tool Name:"), /* @__PURE__ */ React.createElement(Text, null, toolName), /* @__PURE__ */ React.createElement(Separator, { size: "4", style: { margin: "8px 0" } })), input && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Input (canceled):"), /* @__PURE__ */ React.createElement(Code, null, JSON.stringify(input, null, 2))))));
};
// src-copilot/frontend-chat/tools-core/base/createGenericCUDTool.jsx
var createGenericCUDTool = ({
toolName,
description,
parameters,
group,
onInit = ({ setFormState }) => {
setFormState("waitingForUserInput");
},
onCompleted = () => {
},
onSubmitted = () => {
},
renderWaitingForUserInput = () => {
},
renderInit = () => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: "Initializing...", icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderSubmitting = () => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: "Processing...", icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderCanceled = ({ args }) => /* @__PURE__ */ React.createElement(
ToolCardCanceledMessage,
{
text: \`\${toolName} tool invocation canceled.\`,
toolName,
input: args
}
),
renderCompleted = () => {
},
renderError = ({ formError, toolName: toolName2, args }) => /* @__PURE__ */ React.createElement(
ToolCardErrorMessage,
{
toolName: toolName2,
input: args,
text: "Error: " + errorToString(formError),
color: "red"
}
)
}) => AssistantUI.makeAssistantToolUI({
toolName,
description,
group,
parameters,
render: ({ args, status, result, addResult, toolCallId }) => {
let allParameters = useGenericToolParameters({
toolName,
toolCallId,
description,
parameters,
args,
status,
result,
addResult
}), [formState, setFormState, formRender] = useGenericToolFormState({
booting: {
eventHandler: null,
renderer: () => null
},
init: {
eventHandler: onInit,
renderer: renderInit
},
waitingForUserInput: {
eventHandler: null,
renderer: renderWaitingForUserInput
},
submitted: {
eventHandler: onSubmitted,
renderer: renderSubmitting
},
completed: {
eventHandler: onCompleted,
renderer: renderCompleted
},
canceled: {
eventHandler: null,
renderer: renderCanceled
},
error: {
eventHandler: null,
renderer: renderError
}
}, allParameters);
return formRender ? formRender({ ...allParameters, formState, setFormState }) : null;
}
});
// src-copilot/frontend-chat/tools/DeleteUserNotes.jsx
var DeleteUserNotes = () => createGenericCUDTool({
toolName: "DeleteUserNotes",
description: "Delete user notes",
parameters: {
type: "object",
properties: {
notes: {
type: "array",
minItems: window.appSettings[LLM_API_URL_SETTING].includes("googleapis") ? "1" : 1,
items: {
type: "object",
properties: {
noteUUID: {
type: "string",
description: "36 digit UUID of the note to delete"
}
},
required: ["noteUUID"]
}
}
}
},
group: "notes",
onInit: async ({ setFormState, formData, setFormData, args }) => {
let notesContainerList = [];
for (let noteItem of args.notes) {
let noteUUID = noteItem.noteUUID, noteTitle = await appConnector.getNoteTitleByUUID(noteUUID);
if (!noteTitle) throw new Error(\`Note \${noteUUID} not found.\`);
let noteTags = await appConnector.getNoteTagsByUUID({ uuid: noteUUID });
notesContainerList.push({
item: {
uuid: noteUUID,
title: noteTitle,
tags: noteTags
},
checked: !0
});
}
setFormData({ ...formData, notesContainerList }), setFormState("waitingForUserInput");
},
renderWaitingForUserInput: ({ formData, setFormData, status, setFormState }) => {
let setNotesContainerList = (notesContainerList) => {
setFormData({ ...formData, notesContainerList });
}, { Text } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Text, null, "Select notes to delete:"), /* @__PURE__ */ React.createElement(
ItemSelectionTable,
{
itemContainerList: formData.notesContainerList,
setItemContainerList: setNotesContainerList,
status
}
), /* @__PURE__ */ React.createElement(
ToolFooter,
{
submitButtonText: "Delete Notes",
cancelButtonText: "Cancel",
status,
setFormState
}
));
},
onSubmitted: async ({ formData, setFormData, setFormError, setFormState, addResult, result }) => {
let lastError = null, selectedItemContainerList = formData.notesContainerList.filter((item) => item.checked), successfulDeletedItems = [], failedItems = [];
for (let selectedItemContainer of selectedItemContainerList)
try {
let result2 = await deleteNote({
noteUUID: selectedItemContainer.item.uuid
}) || selectedItemContainer.item;
successfulDeletedItems.push(result2);
} catch (e) {
failedItems.push(selectedItemContainer.item), lastError = e, console.error(e);
}
if (failedItems.length === selectedItemContainerList.length)
throw "Failed to delete all of the selected notes. Sample error: " + errorToString(lastError);
setFormData({ ...formData, successfulDeletedItems, failedItems, lastError }), setFormState("completed");
},
onCompleted: ({ formData, addResult }) => {
let { successfulDeletedItems, failedItems } = formData, lastError = formData.lastError;
failedItems.length === 0 ? addResult({
resultSummary: \`\${successfulDeletedItems.length} notes deleted successfully.\`,
resultDetail: successfulDeletedItems
}) : addResult({
resultSummary: \`\${successfulDeletedItems.length} notes deleted successfully. \${failedItems.length} notes failed to delete. Error sample: \${errorToString(lastError)}\`,
resultDetail: successfulDeletedItems,
failedResultDetail: failedItems
});
},
renderCompleted: ({ formData, toolName, args }) => {
let { FileTextIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.successfulDeletedItems),
text: \`\${formData.successfulDeletedItems.length} notes deleted successfully.\` + (formData.failedItems.length > 0 ? \`
\${formData.failedItems.length} notes failed to delete.\` : ""),
icon: /* @__PURE__ */ React.createElement(FileTextIcon, null),
toolName,
input: args
}
);
}
}), deleteNote = async ({ noteUUID }) => await appConnector.deleteNote({ uuid: noteUUID });
// src-copilot/frontend-chat/tools/DeleteTasks.jsx
init_process();
// src-copilot/frontend-chat/tools/EditNoteContent.jsx
init_process();
// src-copilot/frontend-chat/hooks/useNoteSelector.jsx
init_process();
var useNoteSelector = ({ args, setFormData, formData }) => {
let [noteSelectionArr, setNoteSelectionArr] = React.useState([]), currentNoteSelectionUUID = formData.currentNoteSelectionUUID || null, setCurrentNoteSelectionUUID = (value) => {
setFormData({ ...formData, currentNoteSelectionUUID: value });
};
return React.useEffect(() => {
(async () => {
var _a;
let noteArray = [];
if (args.noteUUID) {
let noteTitle = await appConnector.getNoteTitleByUUID(args.noteUUID);
noteArray.push({
uuid: args.noteUUID,
selected: !0,
title: noteTitle
});
}
addIfNotPresent(noteArray, userData.currentNoteUUID, userData.currentNoteName), addIfNotPresent(noteArray, userData.dailyJotNoteUUID, userData.dailyJotNoteName), setCurrentNoteSelectionUUID(args.noteUUID || ((_a = noteArray[0]) == null ? void 0 : _a.uuid)), setNoteSelectionArr(noteArray);
})();
}, [args]), [noteSelectionArr, setNoteSelectionArr, currentNoteSelectionUUID, setCurrentNoteSelectionUUID];
}, addIfNotPresent = (noteInfo, uuid, title) => {
uuid && !noteInfo.some((note) => note.uuid === uuid) && noteInfo.push({
uuid,
selected: noteInfo.length === 0,
title
});
};
// src-copilot/aisdk-wrappers/generateText.js
init_process();
async function generateText(model, prompt) {
let { generateText: generateText2 } = await dynamic_import_esm_default("ai");
return await generateText2({
model,
prompt
});
}
// node_modules/@assistant-ui/react/dist/runtimes/edge/converters/index.mjs
init_process();
// node_modules/@assistant-ui/react/dist/runtimes/edge/converters/toCoreMessages.mjs
init_process();
var toCoreMessages = (messages, options = {}) => messages.map((message) => toCoreMessage(message, options)), toCoreMessage = (message, options = {}) => {
var _a;
let includeId = (_a = options.unstable_includeId) != null ? _a : !1, role = message.role;
switch (role) {
case "assistant":
return {
role,
content: message.content.map((part) => {
if (part.type === "ui") throw new Error("UI parts are not supported");
if (part.type === "tool-call") {
let { argsText, ...rest } = part;
return rest;
}
return part;
}),
...includeId ? { unstable_id: message.id } : {}
};
case "user":
return {
role,
content: [
...message.content.map((part) => {
if (part.type === "ui")
throw new Error("UI parts are not supported");
return part;
}),
...message.attachments.map((a) => a.content).flat()
],
...includeId ? { unstable_id: message.id } : {}
};
case "system":
return {
role,
content: message.content,
...includeId ? { unstable_id: message.id } : {}
};
default: {
let unsupportedRole = role;
throw new Error(\`Unknown message role: \${unsupportedRole}\`);
}
}
};
// src-copilot/frontend-chat/components/tools-ui/ExpandableScrollArea.jsx
init_process();
var ExpandableScrollArea = ({ children, style = {}, scrollAreaProps = {} }) => {
let [isExpanded, setIsExpanded] = window.React.useState(!1), { ScrollArea } = window.RadixUI, { EnterFullScreenIcon, ExitFullScreenIcon } = window.RadixIcons, ReactDOM = window.ReactDOM || window.React.ReactDOM, toggleExpand = () => {
setIsExpanded(!isExpanded);
}, expandedStyle = {
...style,
position: "fixed",
top: "0",
left: "0",
width: "100%",
height: "100%",
maxHeight: "100%",
maxWidth: "100%",
minWidth: "100%",
minHeight: "100%",
zIndex: 9999,
background: "#393a3a",
borderRadius: "0",
border: "1px solid #ccc",
padding: "0",
margin: "0",
boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)"
}, normalStyle = {
...style,
position: "relative"
}, iconContainerStyle = {
position: "absolute",
top: "16px",
right: "16px",
zIndex: 1e4,
// Higher than the expanded area's z-index
cursor: "pointer",
background: "var(--white-a6)",
borderRadius: "4px",
padding: "2px",
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "24px",
height: "24px"
}, normalContent = /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
"div",
{
style: iconContainerStyle,
onClick: toggleExpand,
title: "View full page"
},
/* @__PURE__ */ React.createElement(EnterFullScreenIcon, { width: 16, height: 16 })
), /* @__PURE__ */ React.createElement(
ScrollArea,
{
style: normalStyle,
type: "auto",
...scrollAreaProps
},
children
)), expandedContent = /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
ScrollArea,
{
style: expandedStyle,
type: "auto",
...scrollAreaProps
},
children
), /* @__PURE__ */ React.createElement(
"div",
{
style: {
...iconContainerStyle,
position: "fixed",
top: "15px",
right: "15px",
zIndex: 10001
},
onClick: toggleExpand,
title: "Exit full page"
},
/* @__PURE__ */ React.createElement(ExitFullScreenIcon, { width: 16, height: 16 })
));
return console.log("isExpanded", window.ReactDOM), isExpanded ? window.ReactDOM.createPortal(expandedContent, document.body) : normalContent;
};
// src-copilot/frontend-chat/tools/EditNoteContent.jsx
var EditNoteContent = () => createGenericCUDTool({
toolName: "EditNoteContent",
description: \`Prefer this over UpdateUserNotes when only editing content is required. Do not this tool unless user has specifically asked to modify / edit note content.
For instance, DO NOT call this tool if user is asking to summarize note content. Summarization doesn't mean editing note content.\`,
parameters: {
type: "object",
properties: {
noteUUID: {
type: "string",
description: "36 digit UUID of note"
},
editInstruction: {
type: "string",
description: "Very short instruction on how to modify content."
}
},
required: ["noteUUID"]
},
group: "notes",
renderInit: () => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: "Generating content...", icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
onInit: async ({ setFormState, formData, setFormData, args, threadRuntime }) => {
let noteUUID = args.noteUUID, editInstruction = args.editInstruction, currentContent = await appConnector.getNoteContentByUUID(noteUUID), previousConversationJSON = JSON.stringify(toCoreMessages(threadRuntime.getState().messages)), previousConversationString = previousConversationJSON.length > 16e3 ? previousConversationJSON.substring(previousConversationJSON.length - 16e3) : previousConversationJSON, model = await getLLMModel(appSettings), newContent = currentContent;
try {
currentContent.trim() === "" ? newContent = (await generateText(
model,
\`<|im_start|>
Previous conversation history for reference:
\` + previousConversationString + \`<|im_end|>
<|im_start|>
You are a AI content generator tool. You can use markdown. DO NOT reply anything other than the generated text on provided topic. Instructions:
\` + editInstruction
)).text : newContent = (await generateText(
model,
\`<|im_start|>
Previous conversation history for reference:
\` + previousConversationString + \`<|im_end|>
<|im_start|>
You are a AI content editor tool. You take markdown content as input and return modified content.Rules you should to follow for modification:
- You MUST write the entire content including both modified and unmodified bits.
- Output the original bits as is if modification is not required in those parts.
- Follow the instruction as provided. DO not talk about the instruction.
- Do not output anything other than page content.
- The input starts after text "Input:". ONLY treat everything after "Input:" as input content. Do not include earlier text in your output.
EXAMPLE:
Input: Pikachu is an electric-type Pok\\xE9mon. On other hand, bulbasaur is a water-type Pok\\xE9mon.
Instruction: Change Pikachu to Charmander.Output: Charmander is an fire-type Pok\\xE9mon. On other hand, bulbasaur is a water-type Pok\\xE9mon.
<|im_end|>
<|im_start|>
Instruction:
\` + editInstruction + \`Input:
\` + currentContent + \`
<|im_end|>\`
)).text.replaceAll("<|im_start|>", "").replaceAll("<|im_end|>", "");
} catch (e) {
throw console.error(e), "Failed to generate content";
}
setFormData({ ...formData, noteUUID, editInstruction, newContent, currentContent }), setFormState("waitingForUserInput");
},
renderWaitingForUserInput: ({ args, formData, setFormData, status, setFormState }) => {
let [noteSelectionArr, setNoteSelectionArr, currentNoteSelectionUUID, setCurrentNoteSelectionUUID] = useNoteSelector({ args, setFormData, formData }), { Text } = window.RadixUI, StringDiff = window.StringDiff;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Text, null, "Update note content:"), /* @__PURE__ */ React.createElement(
ExpandableScrollArea,
{
style: {
background: "var(--gray-a2)",
width: "100%",
borderRadius: "8px",
minHeight: "100px",
maxHeight: "100px",
marginTop: "10px",
border: "1px solid #ccc",
padding: "5px",
whiteSpace: "pre-wrap"
}
},
/* @__PURE__ */ React.createElement(
StringDiff,
{
method: "diffWords",
styles: {
added: {
backgroundColor: "#0bbf7d"
},
removed: {
backgroundColor: "#ff6b6b"
}
},
oldValue: formData.currentContent,
newValue: formData.newContent,
showDiff: !0
}
)
), /* @__PURE__ */ React.createElement(
ToolFooter,
{
submitButtonText: "Update Content",
cancelButtonText: "Cancel",
status,
setFormState,
shouldDisplayNoteSelector: !0,
disableNoteSelector: !0,
noteSelectionArr,
currentNoteSelectionUUID,
setCurrentNoteSelectionUUID
}
));
},
onSubmitted: async ({ formData, setFormData, setFormState }) => {
let selectedNoteUUID = formData.currentNoteSelectionUUID;
await appConnector.replaceNoteContent({ uuid: selectedNoteUUID }, formData.newContent), setFormState("completed");
},
onCompleted: async ({ formData, addResult, setFormData }) => {
let noteTitle = await appConnector.getNoteTitleByUUID(formData.currentNoteSelectionUUID);
setFormData({ ...formData, noteTitle }), addResult({ resultSummary: \`\${noteTitle} note content updated.\`, newContent: formData.newContent });
},
renderCompleted: ({ formData, toolName, args }) => {
let { FileTextIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: formData.newContent,
text: \`\${formData.noteTitle} note content updated.\`,
icon: /* @__PURE__ */ React.createElement(FileTextIcon, null),
toolName,
input: args
}
);
},
renderCanceled: ({ formData, toolName, args }) => /* @__PURE__ */ React.createElement(
ToolCardCanceledMessage,
{
text: \`\${toolName} tool invocation canceled.\`,
toolName,
input: { note: args.noteUUID, newContent: formData.newContent }
}
)
});
// src-copilot/frontend-chat/tools/UpdateUserTasks.jsx
init_process();
var UpdateUserTasks = () => createGenericCUDTool({
toolName: "UpdateUserTasks",
description: "Update tasks",
parameters: {
type: "object",
properties: {
tasks: {
type: "array",
minItems: window.appSettings[LLM_API_URL_SETTING].includes("googleapis") ? "1" : 1,
items: {
type: "object",
properties: {
taskUUID: {
type: "string",
description: "UUID of the task to update"
},
content: {
type: "string",
description: "Task content"
},
startAt: {
type: "string",
description: "ISO start datetime"
},
endAt: {
type: "string",
description: "ISO end datetime"
},
completedAt: {
type: "string",
description: "ISO completed datetime. Set to current time to mark completed, null to mark uncompleted."
},
dismissedAt: {
type: "string",
description: "ISO dismissed date/time. Set to current time to mark dismissed, null to mark undismissed."
},
hideUntil: {
type: "string",
description: "ISO hide until date/time"
},
score: {
type: "number"
},
important: {
type: "boolean"
},
urgent: {
type: "boolean"
}
},
required: ["taskUUID"]
}
}
}
},
group: "tasks",
onInit: async ({ setFormState, formData, setFormData, args }) => {
if (!args.tasks || !Array.isArray(args.tasks))
throw new Error("Invalid arguments: tasks must be an array");
let tasksContainerList = [];
for (let taskItem of args.tasks) {
let item = { uuid: taskItem.taskUUID };
"content" in taskItem && (item.content = taskItem.content), "startAt" in taskItem && (item.startAt = taskItem.startAt), "endAt" in taskItem && (item.endAt = taskItem.endAt), "completedAt" in taskItem && (item.completedAt = taskItem.completedAt), "dismissedAt" in taskItem && (item.dismissedAt = taskItem.dismissedAt), "hideUntil" in taskItem && (item.hideUntil = taskItem.hideUntil), "score" in taskItem && (item.score = taskItem.score), "important" in taskItem && (item.important = taskItem.important), "urgent" in taskItem && (item.urgent = taskItem.urgent), tasksContainerList.push({
item,
checked: !0
});
}
let oldTasksContainerList = [];
for (let taskItem of args.tasks) {
let taskUUID = taskItem.taskUUID, task = await appConnector.getTask(taskUUID);
if (!task) throw new Error(\`Task \${taskUUID} not found.\`);
oldTasksContainerList.push({
item: {
uuid: taskUUID,
content: task.content,
startAt: typeof task.startAt == "number" ? window.dayjs(task.startAt * 1e3).format() : null,
endAt: typeof task.endAt == "number" ? window.dayjs(task.endAt * 1e3).format() : null,
completedAt: typeof task.completedAt == "number" ? window.dayjs(task.completedAt * 1e3).format() : null,
dismissedAt: typeof task.dismissedAt == "number" ? window.dayjs(task.dismissedAt * 1e3).format() : null,
hideUntil: typeof task.hideUntil == "number" ? window.dayjs(task.hideUntil * 1e3).format() : null,
score: task.score,
important: task.important,
urgent: task.urgent
}
});
}
setFormData({ ...formData, tasksContainerList, oldTasksContainerList }), setFormState("waitingForUserInput");
},
renderWaitingForUserInput: ({ formData, setFormData, status, setFormState }) => {
let setTasksContainerList = (tasksContainerList) => {
setFormData({ ...formData, tasksContainerList });
}, { Text } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Text, null, "Select tasks to update:"), /* @__PURE__ */ React.createElement(
ItemSelectionTable,
{
itemContainerList: formData.tasksContainerList,
setItemContainerList: setTasksContainerList,
oldItemContainerList: formData.oldTasksContainerList,
status
}
), /* @__PURE__ */ React.createElement(
ToolFooter,
{
submitButtonText: "Update Tasks",
cancelButtonText: "Cancel",
status,
setFormState
}
));
},
onSubmitted: async ({ formData, setFormData, setFormError, setFormState, addResult, result }) => {
let lastError = null, selectedItemContainerList = formData.tasksContainerList.filter((item) => item.checked), successfulUpdatedItems = [], failedItems = [];
for (let selectedItemContainer of selectedItemContainerList)
try {
let result2 = await updateTask({
item: selectedItemContainer.item
}) || selectedItemContainer.item;
successfulUpdatedItems.push(result2);
} catch (e) {
failedItems.push(selectedItemContainer.item), lastError = e, console.error(e);
}
if (failedItems.length === selectedItemContainerList.length)
throw "Failed to update all of the selected tasks. Sample error: " + errorToString(lastError);
setFormData({ ...formData, successfulUpdatedItems, failedItems, lastError }), setFormState("completed");
},
onCompleted: ({ formData, addResult }) => {
let { successfulUpdatedItems, failedItems } = formData, lastError = formData.lastError;
failedItems.length === 0 ? addResult({
resultSummary: \`\${successfulUpdatedItems.length} tasks updated successfully.\`,
resultDetail: successfulUpdatedItems
}) : addResult({
resultSummary: \`\${successfulUpdatedItems.length} tasks updated successfully. \${failedItems.length} tasks failed to update. Error sample: \${errorToString(lastError)}\`,
resultDetail: successfulUpdatedItems,
failedResultDetail: failedItems
});
},
renderCompleted: ({ formData, toolName, args }) => {
let { CheckboxIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.successfulUpdatedItems),
text: \`\${formData.successfulUpdatedItems.length} tasks updated successfully.\` + (formData.failedItems.length > 0 ? \`
\${formData.failedItems.length} tasks failed to update.\` : ""),
icon: /* @__PURE__ */ React.createElement(CheckboxIcon, null),
toolName,
input: args
}
);
}
}), updateTask = async ({ item }) => {
let oldTaskContent = await appConnector.getTask(item.uuid).then((task) => task.content);
if (!item.uuid) throw new Error("Task UUID is required.");
console.log("taskupdateobj", item), "content" in item && item.content !== oldTaskContent && await appConnector.updateTask(item.uuid, {
content: item.content
}), "startAt" in item && await appConnector.updateTask(item.uuid, {
startAt: item.startAt ? Date.parse(item.startAt) / 1e3 : null
}), "endAt" in item && await appConnector.updateTask(item.uuid, {
endAt: item.endAt ? Date.parse(item.endAt) / 1e3 : null
}), "completedAt" in item && await appConnector.updateTask(item.uuid, {
completedAt: item.completedAt ? Date.parse(item.completedAt) / 1e3 : null
}), "dismissedAt" in item && await appConnector.updateTask(item.uuid, {
dismissedAt: item.dismissedAt ? Date.parse(item.dismissedAt) / 1e3 : null
}), "hideUntil" in item && await appConnector.updateTask(item.uuid, {
hideUntil: item.hideUntil ? Date.parse(item.hideUntil) / 1e3 : null
}), "score" in item && await appConnector.updateTask(item.uuid, {
score: item.score
}), "important" in item && await appConnector.updateTask(item.uuid, {
important: item.important
}), "urgent" in item && await appConnector.updateTask(item.uuid, {
urgent: item.urgent
});
};
// src-copilot/frontend-chat/tools/UpdateUserNotes.jsx
init_process();
var UpdateUserNotes = () => createGenericCUDTool({
toolName: "UpdateUserNotes",
description: "Update notes",
parameters: {
type: "object",
properties: {
notes: {
type: "array",
minItems: window.appSettings[LLM_API_URL_SETTING].includes("googleapis") ? "1" : 1,
items: {
type: "object",
properties: {
noteUUID: {
type: "string",
description: "Note UUID"
},
noteTitle: {
type: "string",
description: "Note title"
},
noteContent: {
type: "string",
description: "Note content"
},
tags: {
type: "array",
items: {
type: "string"
},
description: "Tag list (replaces all existing tags - omit to keep current tags)"
}
},
required: ["noteUUID"]
}
}
}
},
group: "notes",
onInit: async ({ setFormState, formData, setFormData, args }) => {
if (!args.notes || !Array.isArray(args.notes))
throw new Error("Invalid arguments: notes must be an array");
let notesContainerList = [];
for (let noteItem of args.notes) {
let item = { uuid: noteItem.noteUUID };
"noteTitle" in noteItem && (item.title = noteItem.noteTitle), "noteContent" in noteItem && (item.content = noteItem.noteContent), "tags" in noteItem && (item.tags = noteItem.tags), notesContainerList.push({
item,
checked: !0
});
}
let oldNotesContainerList = [];
for (let noteItem of args.notes) {
let noteUUID = noteItem.noteUUID, noteTitle = await appConnector.getNoteTitleByUUID(noteUUID), noteTags = await appConnector.getNoteTagsByUUID({ uuid: noteUUID }), noteContent = await appConnector.getNoteContentByUUID(noteUUID);
if (!noteTitle) throw new Error(\`Note \${noteUUID} not found.\`);
oldNotesContainerList.push({
item: {
uuid: noteUUID,
title: noteTitle,
tags: noteTags,
content: noteContent
}
});
}
setFormData({ ...formData, notesContainerList, oldNotesContainerList }), setFormState("waitingForUserInput");
},
renderWaitingForUserInput: ({ formData, setFormData, status, setFormState }) => {
let setNotesContainerList = (notesContainerList) => {
setFormData({ ...formData, notesContainerList });
}, { Text } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Text, null, "Select notes to update:"), /* @__PURE__ */ React.createElement(
ItemSelectionTable,
{
itemContainerList: formData.notesContainerList,
setItemContainerList: setNotesContainerList,
oldItemContainerList: formData.oldNotesContainerList,
status
}
), /* @__PURE__ */ React.createElement(
ToolFooter,
{
submitButtonText: "Update Notes",
cancelButtonText: "Cancel",
status,
setFormState
}
));
},
onSubmitted: async ({ formData, setFormData, setFormError, setFormState, addResult, result }) => {
let lastError = null, selectedItemContainerList = formData.notesContainerList.filter((item) => item.checked), successfulUpdatedItems = [], failedItems = [];
for (let selectedItemContainer of selectedItemContainerList)
try {
let result2 = await updateNote({
item: selectedItemContainer.item
}) || selectedItemContainer.item;
successfulUpdatedItems.push(result2);
} catch (e) {
failedItems.push(selectedItemContainer.item), lastError = e, console.error(e);
}
if (failedItems.length === selectedItemContainerList.length)
throw "Failed to update all of the selected notes. Sample error: " + errorToString(lastError);
setFormData({ ...formData, successfulUpdatedItems, failedItems, lastError }), setFormState("completed");
},
onCompleted: ({ formData, addResult }) => {
let { successfulUpdatedItems, failedItems } = formData, lastError = formData.lastError;
failedItems.length === 0 ? addResult({
resultSummary: \`\${successfulUpdatedItems.length} notes updated successfully.\`,
resultDetail: successfulUpdatedItems
}) : addResult({
resultSummary: \`\${successfulUpdatedItems.length} notes updated successfully. \${failedItems.length} notes failed to update. Error sample: \${errorToString(lastError)}\`,
resultDetail: successfulUpdatedItems,
failedResultDetail: failedItems
});
},
renderCompleted: ({ formData, toolName, args }) => {
let { FileTextIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.successfulUpdatedItems),
text: \`\${formData.successfulUpdatedItems.length} notes updated successfully.\` + (formData.failedItems.length > 0 ? \`
\${formData.failedItems.length} notes failed to update.\` : ""),
icon: /* @__PURE__ */ React.createElement(FileTextIcon, null),
toolName,
input: args
}
);
}
}), updateNote = async ({ item }) => {
let oldNoteTitle = await appConnector.getNoteTitleByUUID(item.uuid);
if ("title" in item && item.title !== oldNoteTitle && await appConnector.setNoteName({ uuid: item.uuid }, item.title), "content" in item && await appConnector.replaceNoteContent({ uuid: item.uuid }, item.content), "tags" in item) {
let oldTags = await appConnector.getNoteTagsByUUID({ uuid: item.uuid });
for (let tag of item.tags)
oldTags.includes(tag) || await appConnector.addNoteTag({ uuid: item.uuid }, tag);
for (let tag of oldTags)
item.tags.includes(tag) || await appConnector.removeNoteTag({ uuid: item.uuid }, tag);
}
};
// src-copilot/frontend-chat/tools/CreateNewNotes.jsx
init_process();
var CreateNewNotes = () => createGenericCUDTool({
toolName: "CreateNewNotes",
description: "Create new notes in amplenote",
parameters: {
type: "object",
properties: {
notes: {
type: "array",
minItems: window.appSettings[LLM_API_URL_SETTING].includes("googleapis") ? "1" : 1,
items: {
type: "object",
properties: {
noteName: {
type: "string"
},
noteTags: {
type: "array",
items: {
type: "string"
}
},
noteContent: {
type: "string"
}
},
required: ["noteName"]
}
}
}
},
group: "notes",
onInit: ({ setFormState, formData, setFormData, args }) => {
setFormData({ ...formData, notesContainerList: args.notes.map((note) => ({
item: note,
checked: !0
})) }), setFormState("waitingForUserInput");
},
renderWaitingForUserInput: ({ args, formData, setFormData, status, setFormState }) => {
let setNotesContainerList = (notesContainerList) => {
setFormData({ ...formData, notesContainerList });
}, { Text } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Text, null, "Select notes to create:"), /* @__PURE__ */ React.createElement(
ItemSelectionTable,
{
itemContainerList: formData.notesContainerList,
setItemContainerList: setNotesContainerList,
status
}
), /* @__PURE__ */ React.createElement(
ToolFooter,
{
submitButtonText: "Create Notes",
cancelButtonText: "Cancel",
status,
setFormState
}
));
},
onSubmitted: async ({ formData, setFormData, setFormError, setFormState, addResult, result }) => {
let lastError = null, selectedItemContainerList = formData.notesContainerList.filter((item) => item.checked), successfulCreatedItems = [], failedItems = [];
for (let selectedItemContainer of selectedItemContainerList)
try {
let result2 = await createNote({
item: selectedItemContainer.item
}) || selectedItemContainer.item;
successfulCreatedItems.push(result2);
} catch (e) {
failedItems.push(selectedItemContainer.item), lastError = e, console.error(e);
}
if (failedItems.length === selectedItemContainerList.length)
throw "Failed to create all items. Sample error: " + errorToString(lastError);
setFormData({ ...formData, successfulCreatedItems, failedItems, lastError }), setFormState("completed");
},
onCompleted: ({ formData, addResult }) => {
let { successfulCreatedItems, failedItems } = formData, lastError = formData.lastError;
failedItems.length === 0 ? addResult({
resultSummary: \`\${successfulCreatedItems.length} notes created successfully.\`,
resultDetail: successfulCreatedItems
}) : addResult({
resultSummary: \`\${successfulCreatedItems.length} notes created successfully. \${failedItems.length} notes failed to create. Error sample: \${errorToString(lastError)}\`,
resultDetail: successfulCreatedItems,
failedResultDetail: failedItems
});
},
renderCompleted: ({ formData, toolName, args }) => {
let { FileTextIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.successfulCreatedItems),
text: \`\${formData.successfulCreatedItems.length} notes created successfully.\` + (formData.failedItems.length > 0 ? \`
\${formData.failedItems.length} notes failed to create.\` : ""),
icon: /* @__PURE__ */ React.createElement(FileTextIcon, null),
toolName,
input: args
}
);
}
}), createNote = async ({ item }) => {
let noteUUID = await appConnector.createNote(item.noteName, item.noteTags || []);
if (!noteUUID) throw new Error("Failed to create note");
return item.noteContent && await appConnector.insertNoteContent({ uuid: noteUUID }, item.noteContent), {
...item,
noteUUID
};
};
// src-copilot/frontend-chat/tools/FetchNoteDetailByNoteUUID.jsx
init_process();
// src-copilot/frontend-chat/tools-core/base/createGenericReadTool.jsx
init_process();
var createGenericReadTool = ({
toolName,
description,
parameters,
group,
onInit = ({ setFormState }) => {
},
onCompleted = () => {
},
renderInit = () => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: "Processing...", icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderCompleted = () => {
},
renderError = ({ formError, toolName: toolName2, args }) => /* @__PURE__ */ React.createElement(
ToolCardErrorMessage,
{
toolName: toolName2,
input: args,
text: "Error: " + errorToString(formError),
color: "red"
}
)
}) => AssistantUI.makeAssistantToolUI({
toolName,
description,
group,
parameters,
render: ({ args, result, addResult, status, toolCallId }) => {
let allParameters = useGenericToolParameters({
toolName,
toolCallId,
description,
parameters,
args,
status,
result,
addResult
}), [formState, setFormState, formRender] = useGenericToolFormState({
booting: {
eventHandler: null,
renderer: () => null
},
init: {
eventHandler: onInit,
renderer: renderInit
},
completed: {
eventHandler: onCompleted,
renderer: renderCompleted
},
error: {
eventHandler: null,
renderer: renderError
}
}, allParameters);
return formRender ? formRender({ ...allParameters, formState, setFormState }) : null;
}
});
// src-copilot/frontend-chat/tools/FetchNoteDetailByNoteUUID.jsx
var FetchNoteDetailByNoteUUID = () => createGenericReadTool({
toolName: "FetchNoteDetailByNoteUUID",
description: "Get title, backlinks, tags and full content of notes.",
parameters: {
type: "object",
properties: {
noteUUIDList: {
type: "array",
items: {
type: "string",
description: "36 digit UUID of note"
}
},
includeContent: {
type: "boolean",
description: "set true if full content is needed"
}
},
required: ["noteUUIDList"]
},
group: "notes",
onInit: async ({ args, formData, setFormData, setFormState }) => {
let noteUUIDList = args.noteUUIDList, noteInfoList = [];
for (let noteUUID of noteUUIDList) {
let noteTitle = await appConnector.getNoteTitleByUUID(noteUUID);
if (!noteTitle) {
noteInfoList.push({ error: \`Note \${noteUUID} not found.\` });
continue;
}
let backlinks = await appConnector.getNoteBacklinksByUUID({ uuid: noteUUID }), tags = await appConnector.getNoteTagsByUUID({ uuid: noteUUID }), noteInfo = { noteUUID, noteTitle, tags, backlinks };
args.includeContent && (noteInfo.noteContent = await appConnector.getNoteContentByUUID(noteUUID)), noteInfoList.push(noteInfo);
}
if (noteInfoList.every((noteInfo) => noteInfo.error))
throw new Error("Failed to fetch all notes. Sample error: " + noteInfoList[0].error);
setFormData({ ...formData, noteInfoList }), setFormState("completed");
},
onCompleted: ({ addResult, formData }) => {
let { noteInfoList } = formData;
addResult({ resultSummary: "Note info fetched successfully.", resultDetail: noteInfoList }, 42e3);
},
renderInit: ({ args }) => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: "Fetching note details...", icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderCompleted: ({ formData, toolName, args }) => {
let { FileTextIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.noteInfoList),
text: "Note info fetched successfully.",
icon: /* @__PURE__ */ React.createElement(FileTextIcon, null),
toolName,
input: args
}
);
}
});
// src-copilot/frontend-chat/tools/SearchNotesByTitleTagsContent.jsx
init_process();
// src-copilot/markdown/stripYAMLFromMarkdown.js
init_process();
// src-copilot/markdown/markdown-parser.js
init_process();
var remarkGfm, unified, remarkFrontmatter, remarkParse, pipe, pipeWithYaml;
async function parse(markdownText, { yaml = !1 } = {}) {
return (!remarkGfm || !unified || !remarkFrontmatter || !remarkParse) && ([remarkGfm, unified, remarkFrontmatter, remarkParse] = await dynamicImportExternalPluginBundle("remarkBundle.js"), unified = unified.unified, remarkGfm = remarkGfm.default, remarkFrontmatter = remarkFrontmatter.default, remarkParse = remarkParse.default), !pipe && !yaml && (pipe = unified().use(remarkParse).use(remarkGfm)), !pipeWithYaml && yaml && (pipeWithYaml = unified().use(remarkParse).use(remarkGfm).use(remarkFrontmatter, ["yaml"])), await (yaml ? pipeWithYaml : pipe).parse(markdownText);
}
// node_modules/unist-util-visit/index.js
init_process();
// node_modules/unist-util-visit/lib/index.js
init_process();
// node_modules/unist-util-visit-parents/index.js
init_process();
// node_modules/unist-util-visit-parents/lib/index.js
init_process();
// node_modules/unist-util-is/index.js
init_process();
// node_modules/unist-util-is/lib/index.js
init_process();
var convert = (
// Note: overloads in JSDoc can\u2019t yet use different \`@template\`s.
/**
* @type {(
* (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &
* (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &
* (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &
* ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &
* ((test?: Test) => Check)
* )}
*/
/**
* @param {Test} [test]
* @returns {Check}
*/
function(test) {
if (test == null)
return ok;
if (typeof test == "function")
return castFactory(test);
if (typeof test == "object")
return Array.isArray(test) ? anyFactory(test) : propsFactory(test);
if (typeof test == "string")
return typeFactory(test);
throw new Error("Expected function, string, or object as test");
}
);
function anyFactory(tests) {
let checks = [], index = -1;
for (; ++index < tests.length; )
checks[index] = convert(tests[index]);
return castFactory(any);
function any(...parameters) {
let index2 = -1;
for (; ++index2 < checks.length; )
if (checks[index2].apply(this, parameters)) return !0;
return !1;
}
}
function propsFactory(check) {
let checkAsRecord = (
/** @type {Record<string, unknown>} */
check
);
return castFactory(all2);
function all2(node2) {
let nodeAsRecord = (
/** @type {Record<string, unknown>} */
/** @type {unknown} */
node2
), key;
for (key in check)
if (nodeAsRecord[key] !== checkAsRecord[key]) return !1;
return !0;
}
}
function typeFactory(check) {
return castFactory(type);
function type(node2) {
return node2 && node2.type === check;
}
}
function castFactory(testFunction) {
return check;
function check(value, index, parent) {
return !!(looksLikeANode(value) && testFunction.call(
this,
value,
typeof index == "number" ? index : void 0,
parent || void 0
));
}
}
function ok() {
return !0;
}
function looksLikeANode(value) {
return value !== null && typeof value == "object" && "type" in value;
}
// node_modules/unist-util-visit-parents/lib/index.js
var empty = [], CONTINUE = !0, EXIT = !1, SKIP = "skip";
function visitParents(tree, test, visitor, reverse) {
let check;
typeof test == "function" && typeof visitor != "function" ? (reverse = visitor, visitor = test) : check = test;
let is2 = convert(check), step = reverse ? -1 : 1;
factory(tree, void 0, [])();
function factory(node2, index, parents) {
let value = (
/** @type {Record<string, unknown>} */
node2 && typeof node2 == "object" ? node2 : {}
);
if (typeof value.type == "string") {
let name = (
// \`hast\`
typeof value.tagName == "string" ? value.tagName : (
// \`xast\`
typeof value.name == "string" ? value.name : void 0
)
);
Object.defineProperty(visit2, "name", {
value: "node (" + (node2.type + (name ? "<" + name + ">" : "")) + ")"
});
}
return visit2;
function visit2() {
let result = empty, subresult, offset, grandparents;
if ((!test || is2(node2, index, parents[parents.length - 1] || void 0)) && (result = toResult(visitor(node2, parents)), result[0] === EXIT))
return result;
if ("children" in node2 && node2.children) {
let nodeAsParent = (
/** @type {UnistParent} */
node2
);
if (nodeAsParent.children && result[0] !== SKIP)
for (offset = (reverse ? nodeAsParent.children.length : -1) + step, grandparents = parents.concat(nodeAsParent); offset > -1 && offset < nodeAsParent.children.length; ) {
let child = nodeAsParent.children[offset];
if (subresult = factory(child, offset, grandparents)(), subresult[0] === EXIT)
return subresult;
offset = typeof subresult[1] == "number" ? subresult[1] : offset + step;
}
}
return result;
}
}
}
function toResult(value) {
return Array.isArray(value) ? value : typeof value == "number" ? [CONTINUE, value] : value == null ? empty : [value];
}
// node_modules/unist-util-visit/lib/index.js
function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
let reverse, test, visitor;
typeof testOrVisitor == "function" && typeof visitorOrReverse != "function" ? (test = void 0, visitor = testOrVisitor, reverse = visitorOrReverse) : (test = testOrVisitor, visitor = visitorOrReverse, reverse = maybeReverse), visitParents(tree, test, overload, reverse);
function overload(node2, parents) {
let parent = parents[parents.length - 1], index = parent ? parent.children.indexOf(node2) : void 0;
return visitor(node2, index, parent);
}
}
// node_modules/mdast-util-to-string/index.js
init_process();
// node_modules/mdast-util-to-string/lib/index.js
init_process();
var emptyOptions = {};
function toString2(value, options) {
let settings = options || emptyOptions, includeImageAlt = typeof settings.includeImageAlt == "boolean" ? settings.includeImageAlt : !0, includeHtml = typeof settings.includeHtml == "boolean" ? settings.includeHtml : !0;
return one(value, includeImageAlt, includeHtml);
}
function one(value, includeImageAlt, includeHtml) {
if (node(value)) {
if ("value" in value)
return value.type === "html" && !includeHtml ? "" : value.value;
if (includeImageAlt && "alt" in value && value.alt)
return value.alt;
if ("children" in value)
return all(value.children, includeImageAlt, includeHtml);
}
return Array.isArray(value) ? all(value, includeImageAlt, includeHtml) : "";
}
function all(values, includeImageAlt, includeHtml) {
let result = [], index = -1;
for (; ++index < values.length; )
result[index] = one(values[index], includeImageAlt, includeHtml);
return result.join("");
}
function node(value) {
return !!(value && typeof value == "object");
}
// src-copilot/markdown/stripYAMLFromMarkdown.js
var stripYAMLFromMarkdown = async (markdownText) => {
let root2 = await parse(markdownText, { yaml: !0 }), textContent = "";
return visit(root2, (node2) => {
if (node2.type === "yaml")
return "skip";
if (node2.type === "root" || node2.type === "paragraph")
return "continue";
if (node2.type === "image")
textContent += \`
\`;
else {
let nodeValue = node2.position ? markdownText.substring(node2.position.start.offset, node2.position.end.offset) : toString2(node2);
return textContent += nodeValue + \`
\`, "skip";
}
}), console.log("stripYAMLFromMarkdown", markdownText, textContent.trim()), textContent.trim();
};
// src-copilot/frontend-chat/helpers/processAndMergeCopilotDBResults.js
init_process();
var processAndMergeCopilotDBResults = async (results) => {
let filteredResults = results.sort((a, b) => a.id.localeCompare(b.id));
if (filteredResults.length === 0)
return [];
let mergedResults = [], currentResult = filteredResults[0];
for (let i = 1; i < filteredResults.length; i++) {
let nextResult = filteredResults[i];
if (currentResult.noteUUID === nextResult.noteUUID) {
currentResult.similarity = Math.max(currentResult.similarity, nextResult.similarity), currentResult.actualNoteContentPart = await stripYAMLFromMarkdown(currentResult.actualNoteContentPart);
try {
nextResult.id !== currentResult.id.split("##")[0] + "##" + (parseInt(currentResult.id.split("##")[1]) + 1) && (currentResult.actualNoteContentPart += \`
<<Redacted>>\`);
} catch {
}
currentResult.actualNoteContentPart += \`
\` + await stripYAMLFromMarkdown(nextResult.actualNoteContentPart);
} else
mergedResults.push(currentResult), currentResult = nextResult;
}
return mergedResults.push(currentResult), mergedResults.map((result) => ({
noteTitle: result.noteTitle,
noteUUID: result.noteUUID,
actualNoteContentPart: result.actualNoteContentPart,
tags: result.noteTags ? result.noteTags : []
}));
};
// src-copilot/frontend-chat/tools/SearchNotesByTitleTagsContent.jsx
var SearchNotesByTitleTagsContent = () => createGenericReadTool({
toolName: "SearchNotesByTitleTagsContent",
description: "Use to get noteUUID from title / tags OR search note content. Only provide required parameters. Returns list of note uuids.",
parameters: {
type: "object",
properties: {
noteContent: {
type: "string",
description: "Search string"
},
noteTitle: {
type: "string",
description: "Title to filter by"
},
tags: {
type: "array",
items: {
type: "string"
},
description: "Tags to filter notes by"
},
isArchived: {
type: "boolean",
description: "When true, only search archived notes (Default: null)"
},
isSharedByMe: {
type: "boolean",
description: "When true, only search notes shared by user (Default: null)"
},
isSharedWithMe: {
type: "boolean",
description: "When true, only search notes shared with user (Default: null)"
},
strictSearch: {
type: "boolean",
description: "When true, strictly match tags and title"
},
limitSearchResults: {
type: "number",
description: "Search result limit (Default: 10)"
}
}
},
group: "notes",
renderInit: ({ args, formData }) => {
let { copilotDBSearchError } = formData, { Flex, Text, Spinner } = window.RadixUI, { ExclamationTriangleIcon } = window.RadixIcons;
return copilotDBSearchError ? /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "2" }, /* @__PURE__ */ React.createElement(Flex, { style: { alignItems: "center", gap: "8px", padding: "8px", backgroundColor: "rgba(0, 0, 0, 0.05)", borderRadius: "4px" } }, /* @__PURE__ */ React.createElement(ExclamationTriangleIcon, null), /* @__PURE__ */ React.createElement(Text, { style: { color: "crimson" } }, "CopilotDB search failed: ", errorToString(formData.copilotDBSearchError))), /* @__PURE__ */ React.createElement(Flex, { style: { alignItems: "center", gap: "8px" } }, /* @__PURE__ */ React.createElement(Spinner, null), /* @__PURE__ */ React.createElement(Text, null, "Searching user notes using fallback amplenote built-in search...")))) : /* @__PURE__ */ React.createElement(
ToolCardMessage,
{
text: "Searching user notes using CopilotDB...",
icon: /* @__PURE__ */ React.createElement(Spinner, null)
}
);
},
onInit: async ({ args, formData, setFormData, setFormState, signal }) => {
let copilotDBSearchError = null, searchResults0 = [];
try {
if (args.noteContent && args.noteContent.trim() !== "") {
args.limitSearchResults = args.limitSearchResults || 10;
let results = await appConnector.searchNotesInCopilotDB(args.noteContent, "query", {
limit: Math.floor(args.limitSearchResults * 3 / 2),
isArchived: args.isArchived,
isSharedByMe: args.isSharedByMe,
isSharedWithMe: args.isSharedWithMe
});
searchResults0.push(...await processAndMergeCopilotDBResults(results));
}
} catch (e) {
copilotDBSearchError = e, setFormData({ ...formData, copilotDBSearchError }), console.error(copilotDBSearchError);
}
let groups = [];
args.isArchived === !0 && groups.push("archived"), args.isSharedByMe === !0 && groups.push("shared"), args.isSharedWithMe === !0 && groups.push("shareReceived");
let searchResults1 = args.noteTitle ? [await appConnector.findNote({
name: args.noteTitle
})] : [], searchResults2 = args.noteTitle ? await appConnector.filterNotes({
query: args.noteTitle,
...groups.length > 0 && { group: groups.join(",") }
}) : [], searchResults3 = args.noteContent ? await appConnector.filterNotes({
query: args.noteContent,
...groups.length > 0 && { group: groups.join(",") }
}) : [], searchResults4 = args.tags ? await appConnector.filterNotes({
tag: args.tags.join(","),
...groups.length > 0 && { group: groups.join(",") }
}) : [], searchResults5 = !args.noteTitle && !args.noteContent && groups.length > 0 ? await appConnector.filterNotes({
group: groups.join(",")
}) : [], amplenoteSearchResults = [...searchResults1, ...searchResults2, ...searchResults3, ...searchResults4, ...searchResults5].slice(0, (args.limitSearchResults || 10) * 4);
for (let result of amplenoteSearchResults) {
if (!args.noteContent || args.noteContent.trim() === "") continue;
let matchedParts = await appConnector.getMatchedPartWithFuzzySearch(result.noteUUID || result.uuid, args.noteContent.trim());
matchedParts.length > 0 && (result.actualNoteContentPart = await stripYAMLFromMarkdown(matchedParts[0]));
}
let uuidCounts = {}, allSearchResults = [...searchResults0, ...amplenoteSearchResults].filter((x) => x && (x.uuid || x.noteUUID)), allSearchResultsFilteredByGroup = await Promise.all(allSearchResults.filter(async (result) => {
let satisfiesGroup = !0;
if (groups.includes("archived")) {
let isArchived = await appConnector.filterNotes({
group: "archived",
query: result.uuid
});
satisfiesGroup = satisfiesGroup && isArchived && isArchived.length > 0;
}
if (groups.includes("shared")) {
let isShared = await appConnector.filterNotes({
group: "shared",
query: result.uuid
});
satisfiesGroup = satisfiesGroup && isShared && isShared.length > 0;
}
if (groups.includes("shareReceived")) {
let isShareReceived = await appConnector.filterNotes({
group: "shareReceived",
query: result.uuid
});
satisfiesGroup = satisfiesGroup && isShareReceived && isShareReceived.length > 0;
}
return satisfiesGroup;
}));
allSearchResultsFilteredByGroup.forEach((result) => {
uuidCounts[result.uuid] = (uuidCounts[result.uuid] || 0) + 1;
});
let uniqueResultsSortedByCount = uniqBy_default(allSearchResultsFilteredByGroup, "uuid").sort((a, b) => uuidCounts[b.uuid] !== uuidCounts[a.uuid] ? uuidCounts[b.uuid] - uuidCounts[a.uuid] : a.uuid.localeCompare(b.uuid)), searchResultsMapped = Array.from(uniqueResultsSortedByCount).map((note) => ({
uuid: note.uuid || note.noteUUID,
title: note.name || note.title || note.noteTitle,
tags: args.tags && note.tags && typeof note.tags == "string" ? note.tags.split(",") : note.tags,
...note.actualNoteContentPart && { actualNoteContentPart: note.actualNoteContentPart }
}));
args.strictSearch && (searchResultsMapped = searchResultsMapped.filter((note) => {
let matchesTitle = !0, matchesTags = !0;
return args.noteTitle && (note.title = note.title || "Untitled Note", matchesTitle = note.title.toLowerCase().includes(args.noteTitle.toLowerCase())), args.tags && args.tags.length > 0 && (note.tags = note.tags || [], matchesTags = args.tags.every(
(tag) => note.tags && note.tags.some(
(noteTag) => noteTag.toLowerCase() === tag.toLowerCase()
)
)), matchesTitle && matchesTags;
})), args.limitSearchResults = args.limitSearchResults || 10, args.limitSearchResults && (searchResultsMapped = searchResultsMapped.slice(0, args.limitSearchResults)), setFormData({
...formData,
searchResults: searchResultsMapped,
copilotDBSearchError
}), setFormState("completed");
},
onCompleted: ({ addResult, formData }) => {
let { searchResults } = formData;
addResult({ resultSummary: "Search completed.", searchResults }, 3e4);
},
renderCompleted: ({ formData, toolName, args }) => {
let { Flex, Text } = window.RadixUI, { MagnifyingGlassIcon, ExclamationTriangleIcon } = window.RadixIcons;
return formData.copilotDBSearchError ? /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.searchResults),
toolName,
input: args
},
/* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "2" }, /* @__PURE__ */ React.createElement(Flex, { style: { alignItems: "center", gap: "8px", padding: "8px", backgroundColor: "rgba(0, 0, 0, 0.05)", borderRadius: "4px" } }, /* @__PURE__ */ React.createElement(ExclamationTriangleIcon, null), /* @__PURE__ */ React.createElement(Text, { style: { color: "crimson" } }, "CopilotDB search failed: ", errorToString(formData.copilotDBSearchError))), /* @__PURE__ */ React.createElement(Flex, { style: { alignItems: "center", gap: "8px" } }, /* @__PURE__ */ React.createElement(MagnifyingGlassIcon, null), /* @__PURE__ */ React.createElement(Text, null, "Search completed using fallback amplenote built-in search. ", formData.searchResults.length, " results fetched.")))
) : /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.searchResults),
icon: /* @__PURE__ */ React.createElement(MagnifyingGlassIcon, null),
toolName,
text: \`Search completed! \${formData.searchResults.length} results fetched.\`,
input: args
}
);
}
});
// src-copilot/frontend-chat/tools/WebBrowser.jsx
init_process();
var WebBrowser = () => createGenericReadTool({
toolName: "WebBrowser",
description: "Read entire webpage content. Don't call this again if page content is already fetched.",
parameters: {
type: "object",
properties: {
url: {
type: "string"
}
},
required: ["url"]
},
group: "web",
onInit: async ({ args, formData, setFormData, setFormState, signal }) => {
let url = args.url, pageContent = await getWebPageContent(url, signal);
setFormData({ ...formData, pageContent }), setFormState("completed");
},
onCompleted: ({ addResult, formData }) => {
let { pageContent } = formData;
addResult({ resultSummary: "Page content fetched successfully.", pageContent });
},
renderInit: ({ args }) => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: \`Fetching page content for \${args.url}...\`, icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderCompleted: ({ formData, toolName, args }) => {
let { GlobeIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: formData.pageContent,
text: "Page content fetched successfully.",
icon: /* @__PURE__ */ React.createElement(GlobeIcon, null),
toolName,
input: args
}
);
}
}), getWebPageContent = async (url, signal) => {
let response = await fetch(\`https://r.jina.ai/\${url.trim()}\`, {
signal
});
if (response.status !== 200)
throw new Error("Failed to fetch web page content");
return await response.text();
};
// src-copilot/frontend-chat/tools/WebSearch.jsx
init_process();
// common-utils/cors-helpers.js
init_process();
function getCorsBypassUrl(url) {
return "https://plugins.amplenote.com/cors-proxy?apiurl=" + url;
}
var isUrlNotWorkingMap = /* @__PURE__ */ new Map();
async function fetchWithFallback(urls, options, retryInvalidUrls = !0) {
var _a;
for (let i = 0; i < urls.length; i++) {
let url = urls[i], baseUrl;
try {
if (baseUrl = (_a = url.match(/^https?:\\/\\/[^#?\\/]+/)) == null ? void 0 : _a[0], !retryInvalidUrls && isUrlNotWorkingMap.has(baseUrl))
throw isUrlNotWorkingMap.get(baseUrl);
return await fetch(url, options);
} catch (e) {
if (isUrlNotWorkingMap.set(baseUrl, e), i === urls.length - 1 || !String(e.message).includes("CORS"))
throw e;
}
}
}
// src-copilot/frontend-chat/tools/WebSearch.jsx
var WebSearch = () => createGenericReadTool({
toolName: "WebSearch",
description: "Search web for information. Use only when asked to search or to answer questions about current events.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "Search string"
}
},
required: ["query"]
},
group: "web",
onInit: async ({ args, formData, setFormData, setFormState, signal }) => {
let searchResults = await search(args.query, signal);
setFormData({ ...formData, searchResults }), setFormState("completed");
},
onCompleted: ({ addResult, formData }) => {
let { searchResults } = formData;
addResult({ resultSummary: "Search completed.", searchResults });
},
renderInit: ({ args }) => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: \`Searching web for \${args.query}...\`, icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderCompleted: ({ formData, toolName, args }) => {
let { GlobeIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.searchResults),
text: "Search completed!",
icon: /* @__PURE__ */ React.createElement(GlobeIcon, null),
toolName,
input: args
}
);
}
}), search = async (query, signal) => {
let response = await fetchWithFallback([
\`https://actions.sider.ai/googleGPT/search_with_rerank?query=\${encodeURIComponent(query)}\`,
getCorsBypassUrl(\`https://search.projectsegfau.lt/search?q=\${encodeURIComponent(query)}&format=json\`),
\`https://api.duckduckgo.com/?q=\${encodeURIComponent(query)}&format=json\`
]);
if (response.status !== 200)
throw new Error("Failed to fetch web search results");
return await response.json();
};
// src-copilot/frontend-chat/tools/FetchUserTasks.jsx
init_process();
var FetchUserTasks = () => createGenericReadTool({
toolName: "FetchUserTasks",
description: "Query to fetch information about existing tasks.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: \`Sql Select statement (duckdb - see examples) to search tasks from user_tasks table.
Available fields: completedAt, dismissedAt, endAt, hideUntil, startAt (TIMESTAMP)
content, noteUUID, taskUUID, taskDomainUUID, taskDomainName (VARCHAR)
urgent, important (BOOLEAN)
score (DOUBLE)
Examples:
Find tasks for 25th december: SELECT * FROM user_tasks WHERE DATE(startAt) = '2024-12-25';
Find tasks completed after 25th december 5pm: SELECT * FROM user_tasks WHERE completedAt > TIMESTAMPTZ '2025-07-16T17:00:00+05:30';
Find task by content: SELECT * FROM user_tasks WHERE regexp_matches(content, '(shop|buy)', 'i');
Find urgent tasks: SELECT * FROM user_tasks WHERE urgent = true;
Find incomplete tasks: SELECT * FROM user_tasks WHERE completedAt IS NULL;
\`
}
},
required: ["query"]
},
group: "tasks",
onInit: async ({ args, formData, setFormData, setFormState }) => {
try {
let result = await appConnector.searchUserTasks(args.query);
if (result.success)
setFormData({ ...formData, queryResult: result.results }), setFormState("completed");
else
throw new Error(result.error || "Failed to search tasks");
} catch (error) {
console.error("Error searching tasks:", error), setFormData({ ...formData, error: error.message, queryResult: [] }), setFormState("error");
}
},
onCompleted: ({ addResult, formData }) => {
let { queryResult } = formData;
addResult({
resultSummary: \`Query completed. Found \${queryResult.length} matching results.\`,
resultDetail: queryResult
});
},
renderInit: ({ args }) => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: "Searching for tasks...", icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderCompleted: ({ formData, toolName, args }) => {
let { CheckboxIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.queryResult),
text: \`\${formData.queryResult.length} tasks found.\`,
icon: /* @__PURE__ */ React.createElement(CheckboxIcon, null),
toolName,
input: args
}
);
},
renderError: ({ formData, toolName, args }) => {
let { ExclamationTriangleIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: formData.error || "Unknown error occurred",
text: \`Error searching tasks: \${formData.error || "Unknown error"}\`,
icon: /* @__PURE__ */ React.createElement(ExclamationTriangleIcon, null),
toolName,
input: args
}
);
}
});
// src-copilot/frontend-chat/tools/InsertTasksToNote.jsx
init_process();
var InsertTasksToNote = () => createGenericCUDTool({
toolName: "InsertTasksToNote",
description: "Create tasks and insert them to note",
parameters: {
type: "object",
properties: {
tasks: {
type: "array",
minItems: window.appSettings[LLM_API_URL_SETTING].includes("googleapis") ? "1" : 1,
items: {
type: "object",
properties: {
content: {
type: "string",
description: "Short description of task"
},
startAt: {
type: "string",
description: "Start date and time of the task in ISO format"
},
endAt: {
type: "string",
description: "End date and time of the task in ISO format (Optional)"
},
score: {
type: "number",
description: "Optional score"
}
},
required: ["content"]
}
},
noteUUID: {
type: "string",
description: "36 digit UUID of note to insert the task into."
}
},
required: ["tasks", "noteUUID"]
},
group: "tasks",
onInit: ({ setFormState, formData, setFormData, args }) => {
setFormData({ ...formData, tasksContainerList: args.tasks.map((task) => ({
item: task,
checked: !0
})) }), setFormState("waitingForUserInput");
},
renderWaitingForUserInput: ({ args, formData, setFormData, status, setFormState }) => {
let setTasksContainerList = (tasksContainerList) => {
setFormData({ ...formData, tasksContainerList });
}, [noteSelectionArr, setNoteSelectionArr, currentNoteSelectionUUID, setCurrentNoteSelectionUUID] = useNoteSelector({ args, setFormData, formData }), { Text } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Text, null, "Select tasks to insert into note:"), /* @__PURE__ */ React.createElement(
ItemSelectionTable,
{
itemContainerList: formData.tasksContainerList,
setItemContainerList: setTasksContainerList,
status
}
), /* @__PURE__ */ React.createElement(
ToolFooter,
{
submitButtonText: "Insert Tasks",
cancelButtonText: "Cancel",
status,
setFormState,
shouldDisplayNoteSelector: !0,
noteSelectionArr,
currentNoteSelectionUUID,
setCurrentNoteSelectionUUID
}
));
},
onSubmitted: async ({ formData, setFormData, setFormState, addResult, result }) => {
let lastError = null, selectedItemContainerList = formData.tasksContainerList.filter((item) => item.checked), selectedNoteUUID = formData.currentNoteSelectionUUID, successfulInsertedItems = [], failedItems = [];
for (let selectedItemContainer of selectedItemContainerList)
try {
let result2 = await insertTasksToNote({
selectedNoteUUID,
item: selectedItemContainer.item
}) || selectedItemContainer.item;
successfulInsertedItems.push(result2);
} catch (e) {
failedItems.push(selectedItemContainer.item), lastError = e, console.error(e);
}
if (failedItems.length === selectedItemContainerList.length) {
let lastErrorMessage = lastError.message || lastError;
throw "Failed to insert all of the selected tasks. Sample error: " + errorToString(lastErrorMessage);
}
setFormData({ ...formData, successfulInsertedItems, failedItems, lastError }), setFormState("completed");
},
onCompleted: async ({ formData, addResult, setFormData }) => {
let { successfulInsertedItems, failedItems } = formData, lastError = formData.lastError, selectedNoteUUID = formData.currentNoteSelectionUUID, selectedNoteTitle = await appConnector.getNoteTitleByUUID(selectedNoteUUID);
setFormData({ ...formData, selectedNoteTitle }), failedItems.length === 0 ? addResult({
resultSummary: \`\${successfulInsertedItems.length} tasks inserted successfully into note \${selectedNoteTitle} (uuid: \${selectedNoteUUID}).\`,
resultDetails: successfulInsertedItems
}) : addResult({
resultSummary: \`\${successfulInsertedItems.length} tasks inserted successfully into note \${selectedNoteTitle} (uuid: \${selectedNoteUUID}).\${failedItems.length} tasks failed to insert into note.Error sample: \${errorToString(lastError)}\`,
resultDetails: successfulInsertedItems,
failedResultDetails: failedItems
});
},
renderCompleted: ({ formData, args, toolName }) => {
let { CheckboxIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.successfulInsertedItems),
text: \`\${formData.successfulInsertedItems.length} tasks inserted successfully into note \${formData.selectedNoteTitle}.\` + (formData.failedItems.length > 0 ? \`
\${formData.failedItems.length} tasks failed to insert.\` : ""),
icon: /* @__PURE__ */ React.createElement(CheckboxIcon, null),
toolName,
input: args
}
);
}
}), insertTasksToNote = async ({ selectedNoteUUID, item }) => {
let taskUUID = await appConnector.insertTask({ uuid: selectedNoteUUID }, {
content: item.content
});
if (!taskUUID) throw new Error("Failed to insert task");
return item.startAt && await appConnector.updateTask(taskUUID, {
startAt: Date.parse(item.startAt) / 1e3
// convert to timestamp
}), item.endAt && await appConnector.updateTask(taskUUID, {
endAt: Date.parse(item.endAt) / 1e3
// convert to timestamp
}), item.score && await appConnector.updateTask(taskUUID, {
score: item.score
}), {
...item,
taskUUID
};
};
// src-copilot/frontend-chat/tools/SearchHelpCenter.jsx
init_process();
var SearchHelpCenter = () => createGenericReadTool({
toolName: "SearchHelpCenter",
description: "Search help center",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "Search string"
}
},
required: ["query"]
},
group: "help",
onInit: async ({ args, formData, setFormData, setFormState, signal }) => {
let results = await appConnector.searchHelpCenter(args.query, {
limit: 10
}), searchResults = await processAndMergeCopilotDBResults(results);
setFormData({ ...formData, searchResults }), setFormState("completed");
},
onCompleted: ({ addResult, formData }) => {
let { searchResults } = formData;
addResult({ resultSummary: "Help Center search completed.", searchResults }, 3e4);
},
renderInit: () => {
let { Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardMessage, { text: "Searching help center...", icon: /* @__PURE__ */ React.createElement(Spinner, null) });
},
renderCompleted: ({ formData, toolName, args }) => {
let { QuestionMarkCircledIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: JSON.stringify(formData.searchResults),
text: \`Help Center search completed! Found \${formData.searchResults.length} pages.\`,
icon: /* @__PURE__ */ React.createElement(QuestionMarkCircledIcon, null),
toolName,
input: args
}
);
}
});
// src-copilot/frontend-chat/tools-core/mcp/getAllMCPTools.jsx
init_process();
// src-copilot/frontend-chat/tools-core/mcp/createMCPToolFromObj.jsx
init_process();
function createMCPToolFromObj(mcpServerUrl, toolName, toolObj) {
var _a, _b, _c, _d;
return createGenericCUDTool({
toolName: \`mcp-\${toolName}\`,
description: toolObj.description,
parameters: {
type: "object",
properties: (_b = (_a = toolObj.parameters) == null ? void 0 : _a.jsonSchema) == null ? void 0 : _b.properties,
required: (_d = (_c = toolObj.parameters) == null ? void 0 : _c.jsonSchema) == null ? void 0 : _d.required
},
group: "mcp",
renderWaitingForUserInput: ({ args, status, setFormState }) => {
let { Text, ScrollArea, Separator, Code } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ToolCardContainer, null, /* @__PURE__ */ React.createElement(Text, null, "The following action will be performed using MCP Server:"), /* @__PURE__ */ React.createElement(ScrollArea, { scrollbars: "horizontal", style: { paddingTop: "6px", paddingBottom: "6px" } }, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "MCP Server:"), /* @__PURE__ */ React.createElement(Text, null, mcpServerUrl), /* @__PURE__ */ React.createElement(Separator, { size: "4", style: { margin: "8px 0" } }), /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Tool ID:"), /* @__PURE__ */ React.createElement(Text, null, toolName), /* @__PURE__ */ React.createElement(Separator, { size: "4", style: { margin: "8px 0" } }), /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)", marginBottom: "4px", display: "block" } }, "Input:"), /* @__PURE__ */ React.createElement(Code, { highContrast: !0, wrap: "nowrap" }, JSON.stringify(args))), /* @__PURE__ */ React.createElement(
ToolFooter,
{
submitButtonText: "Proceed",
cancelButtonText: "Cancel",
status,
setFormState
}
));
},
onSubmitted: async ({ args, formData, setFormData, setFormState }) => {
let mcpCallResult = await toolObj.execute(args);
console.log(mcpCallResult), setFormData({ ...formData, mcpCallResult: mcpCallResult.content[0].text || mcpCallResult }), setFormState("completed");
},
onCompleted: ({ formData, addResult }) => {
addResult({ resultSummary: "Tool call successful.", toolOutput: formData.mcpCallResult });
},
renderCompleted: ({ formData, toolName: toolName2, args }) => {
let { MixIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
result: formData.mcpCallResult,
text: \`mcp/\${toolName2} tool call completed successfully.\`,
icon: /* @__PURE__ */ React.createElement(MixIcon, null),
toolName: \`mcp/\${toolName2}\`,
input: args
}
);
}
});
}
// src-copilot/frontend-chat/tools-core/mcp/getAllMCPTools.jsx
async function getAllMCPTools() {
var _a;
let mcpServerList = ((_a = window.appSettings[MCP_SERVER_URL_LIST_SETTING]) == null ? void 0 : _a.split(",")) || [], toolList = [];
if (mcpServerList.length > 0) {
let { experimental_createMCPClient } = await dynamic_import_esm_default("ai");
for (let mcpServer of mcpServerList)
if (mcpServer.trim() !== "")
try {
let toolSet = await (await experimental_createMCPClient({
transport: {
type: "sse",
url: mcpServer
}
})).tools();
Object.keys(toolSet).forEach((key) => {
toolList.push(createMCPToolFromObj(mcpServer, key, toolSet[key]));
});
} catch {
throw new Error(\`Failed to connect to \${mcpServer}\`);
}
}
return toolList;
}
// src-copilot/frontend-chat/tools-core/registry/ToolRegistry.js
var _ToolRegistry = class _ToolRegistry {
static async registerInbuiltTools() {
_ToolRegistry.tools = [
..._ToolRegistry.tools,
InsertTasksToNote(),
FetchUserTasks(),
WebSearch(),
WebBrowser(),
CreateNewNotes(),
FetchNoteDetailByNoteUUID(),
SearchNotesByTitleTagsContent(),
UpdateUserNotes(),
UpdateUserTasks(),
EditNoteContent(),
// DeleteTasks(), // No api support for deleting task yet
DeleteUserNotes(),
SearchHelpCenter()
];
}
static async registerMCPTools() {
let mcpTools = await getAllMCPTools();
_ToolRegistry.tools = [..._ToolRegistry.tools, ...mcpTools];
}
static getTool(toolName) {
return _ToolRegistry.tools.find((tool) => tool.toolName === toolName);
}
static getToolsByGroup(groupName) {
return _ToolRegistry.tools.filter((tool) => tool.unstable_tool.group === groupName);
}
static getAllTools() {
return _ToolRegistry.tools;
}
};
__publicField(_ToolRegistry, "tools", []);
var ToolRegistry = _ToolRegistry;
// src-copilot/frontend-chat/tools-core/registry/ToolGroupRegistry.js
init_process();
var _ToolGroupRegistry = class _ToolGroupRegistry {
static updateAllGroups() {
_ToolGroupRegistry.groups = [];
let allTools = ToolRegistry.getAllTools(), uniqueGroups = [...new Set(allTools.map((tool) => tool.unstable_tool.group).filter((group) => group))];
for (let groupName of uniqueGroups) {
let groupTools = ToolRegistry.getToolsByGroup(groupName), description = this.getGroupDescription(groupName, groupTools);
_ToolGroupRegistry.groups.push({
name: groupName,
description,
toolCount: groupTools.length
});
}
}
static getGroupDescription(groupName, tools) {
let toolNames = tools.map((tool) => tool.unstable_tool.toolName).join("<br />");
return ({
tasks: "<b>Enables tools for amplenote tasks:</b><br />",
notes: "<b>Enables tools for amplenote notes:</b><br />",
web: "<b>Enables tools for searching the web:</b><br />",
help: "<b>Enables tools for the help center:</b><br />",
mcp: "<b>Enables MCP (Model Context Protocol) tools:</b><br />"
}[groupName] || \`<b>Enables \${groupName} tools:</b><br />\`) + toolNames.trim();
}
static getToolsByGroup(groupName) {
return ToolRegistry.getToolsByGroup(groupName);
}
static getGroup(groupName) {
return _ToolGroupRegistry.groups.find((group) => group.name === groupName);
}
static getAllGroupNames() {
return _ToolGroupRegistry.groups.map((group) => group.name);
}
static getAllGroups() {
return _ToolGroupRegistry.groups;
}
};
__publicField(_ToolGroupRegistry, "groups", []);
var ToolGroupRegistry = _ToolGroupRegistry;
// src-copilot/frontend-chat/hooks/useToolRegistries.js
var useToolRegistries = () => {
let [toolGroupNames, setToolGroupNames] = React.useState([]), [tools, setTools] = React.useState([]);
return React.useEffect(() => {
(async () => {
try {
await ToolRegistry.registerInbuiltTools(), ToolGroupRegistry.updateAllGroups(), setToolGroupNames(ToolGroupRegistry.getAllGroupNames()), setTools(ToolRegistry.getAllTools()), await ToolRegistry.registerMCPTools(), ToolGroupRegistry.updateAllGroups(), setToolGroupNames(ToolGroupRegistry.getAllGroupNames()), setTools(ToolRegistry.getAllTools());
} catch (e) {
console.error("Failed to initialize tool registries:", e), appConnector.alert("Error: " + errorToString(e));
}
})();
}, []), { toolGroupNames, tools };
};
// src-copilot/frontend-chat/context/ChatAppContext.jsx
var getChatAppContext = () => (window.ChatAppContext || (window.ChatAppContext = React.createContext({})), window.ChatAppContext), ChatAppContextProvider = ({ children }) => {
let ChatAppContext = getChatAppContext(), [threadNewMsgComposerRef, setThreadNewMsgComposerRef] = React.useState(null), [remoteThreadLoaded, setRemoteThreadLoaded] = React.useState(!1), [chatHistoryLoaded, setChatHistoryLoaded] = React.useState(!1), [isChatHistoryOverlayOpen, setIsChatHistoryOverlayOpen] = React.useState(!1), [initialAttachmentProcessed, setInitialAttachmentProcessed] = React.useState(!1), { toolGroupNames, tools } = useToolRegistries(), [enabledToolGroups, setEnabledToolGroups] = React.useState(/* @__PURE__ */ new Set()), lastLoadedChatHistoryThreadId = React.useRef(null);
return /* @__PURE__ */ React.createElement(ChatAppContext.Provider, { value: {
threadNewMsgComposerRef,
setThreadNewMsgComposerRef,
remoteThreadLoaded,
setRemoteThreadLoaded,
chatHistoryLoaded,
setChatHistoryLoaded,
isChatHistoryOverlayOpen,
setIsChatHistoryOverlayOpen,
initialAttachmentProcessed,
setInitialAttachmentProcessed,
toolGroupNames,
tools,
enabledToolGroups,
setEnabledToolGroups,
lastLoadedChatHistoryThreadId
} }, children);
};
// src-copilot/frontend-chat/hooks/useEnabledTools.jsx
init_process();
var useEnabledTools = () => {
let { enabledToolGroups, setEnabledToolGroups, lastLoadedChatHistoryThreadId } = React.useContext(getChatAppContext()), threadListItemRuntime = AssistantUI.useThreadListItemRuntime(), saveEnabledToolGroups = React.useCallback(async (threadId, newEnabledToolGroupsSet) => {
try {
let thread = await appConnector.getChatThreadFromCopilotDB(threadId);
if (thread) {
let updatedThread = {
...thread,
enabledToolGroups: [...newEnabledToolGroupsSet]
// db needs array
};
await appConnector.saveChatThreadToCopilotDB(updatedThread);
}
} catch (error) {
console.error("Failed to save enabled tools:", error);
}
}, []);
React.useEffect(() => {
let loadEnabledToolGroupsFromDB = async (threadId) => {
if (threadId) {
if (lastLoadedChatHistoryThreadId.current === threadId) {
console.log("Skipping reload for same thread:", threadId);
return;
}
console.log("Loading enabled tools for thread:", threadId, "lastLoaded:", lastLoadedChatHistoryThreadId.current);
try {
let thread = await appConnector.getChatThreadFromCopilotDB(threadId);
thread != null && thread.enabledToolGroups ? setEnabledToolGroups(new Set(thread.enabledToolGroups)) : setEnabledToolGroups(/* @__PURE__ */ new Set());
} catch {
setEnabledToolGroups(/* @__PURE__ */ new Set());
} finally {
lastLoadedChatHistoryThreadId.current = threadId, console.log("Set lastLoadedChatHistoryThreadId to:", threadId);
}
}
}, loadEnabledToolsForCurrentThread = async () => {
let threadId = threadListItemRuntime.getState().remoteId;
await loadEnabledToolGroupsFromDB(threadId);
}, unsubscribe = threadListItemRuntime.subscribe(loadEnabledToolsForCurrentThread);
return loadEnabledToolsForCurrentThread(), () => unsubscribe();
}, [threadListItemRuntime]);
let toggleToolGroup = React.useCallback(async (toolGroup) => {
let threadId = threadListItemRuntime.getState().remoteId;
setEnabledToolGroups((prev) => {
let newSet = new Set(prev);
return newSet.has(toolGroup) ? newSet.delete(toolGroup) : newSet.add(toolGroup), saveEnabledToolGroups(threadId, newSet), newSet;
});
}, [setEnabledToolGroups, saveEnabledToolGroups, threadListItemRuntime]), enableToolGroup = React.useCallback(async (toolGroup) => {
let threadId = threadListItemRuntime.getState().remoteId;
setEnabledToolGroups((prev) => {
let newSet = new Set(prev);
return newSet.add(toolGroup), saveEnabledToolGroups(threadId, newSet), newSet;
});
}, [setEnabledToolGroups, saveEnabledToolGroups, threadListItemRuntime]), isToolGroupEnabled = React.useCallback((toolGroup) => enabledToolGroups.has(toolGroup), [enabledToolGroups]);
return {
toggleToolGroup,
enableToolGroup,
isToolGroupEnabled
};
};
// src-copilot/frontend-chat/hooks/useTributeSetup.jsx
var useTributeSetup = (textareaRef, toolGroupNames) => {
let { enableToolGroup } = useEnabledTools(), composerRuntime = AssistantUI.useComposerRuntime();
React.useEffect(() => {
if (!textareaRef.current) return;
let style = document.createElement("style");
style.textContent = \`
.tribute-container > ul {
background-color: #434A54;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
color: #FFFFFF;
margin: 10px;
padding: 0;
list-style: none;
}
.tribute-item {
padding: 8px;
cursor: pointer;
border-bottom: 1px solid #333333;
}
.tribute-item:hover {
background-color: #2d4759;
}
.tribute-item-selected {
background-color: #2d4759;
color: #FFFFFF;
}
\`, document.body.append(style);
let tribute = new window.Tribute({
trigger: "@",
values: toolGroupNames.map((toolGroup) => ({
key: toolGroup,
value: toolGroup
})),
noMatchTemplate: null,
containerClass: "tribute-container",
itemClass: "tribute-item",
selectClass: "tribute-item-selected",
allowSpaces: !1,
menuItemLimit: 4,
replaceTextSuffix: " "
});
tribute.attach(textareaRef.current);
let tributeOnReplace = (event) => {
let selectedToolGroup = event.detail.item.original.value;
enableToolGroup(selectedToolGroup);
let currentTextAreaValue = textareaRef.current.value;
composerRuntime.setText(currentTextAreaValue);
};
return textareaRef.current.addEventListener("tribute-replaced", tributeOnReplace), () => {
textareaRef.current && (tribute.detach(textareaRef.current), textareaRef.current.removeEventListener("tribute-replaced", tributeOnReplace));
};
}, [textareaRef, toolGroupNames]);
};
// src-copilot/frontend-chat/components/FileAttachmentDisplay.jsx
init_process();
var FileAttachmentDisplay = (args) => {
let canRemove = AssistantUI.useAttachment((a) => a.source !== "message"), attachmentFile = AssistantUI.useAttachment((a) => a.file), { FileIcon, FileTextIcon, CheckboxIcon, CursorTextIcon } = window.RadixIcons, fileTypeName = null, fileIcon = null;
switch (attachmentFile.type) {
case "text/amplenote-task":
fileTypeName = "Amplenote Task", fileIcon = /* @__PURE__ */ React.createElement(CheckboxIcon, null);
break;
case "text/amplenote-note":
fileTypeName = "Amplenote Note", fileIcon = /* @__PURE__ */ React.createElement(FileTextIcon, null);
break;
case "text/amplenote-selection":
fileTypeName = "Current Selection", fileIcon = /* @__PURE__ */ React.createElement(CursorTextIcon, null);
break;
default:
fileTypeName = "File", fileIcon = /* @__PURE__ */ React.createElement(FileIcon, null);
break;
}
let { AttachmentUI, AttachmentPrimitive } = window.AssistantUI;
return /* @__PURE__ */ React.createElement(AttachmentUI.Root, null, /* @__PURE__ */ React.createElement("div", { className: "aui-attachment-content" }, /* @__PURE__ */ React.createElement("span", { className: "aui-avatar-root aui-attachment-thumb" }, /* @__PURE__ */ React.createElement("span", null, fileIcon)), /* @__PURE__ */ React.createElement("div", { className: "aui-attachment-text" }, /* @__PURE__ */ React.createElement("p", { className: "aui-attachment-name" }, /* @__PURE__ */ React.createElement(AttachmentPrimitive.Name, null)), /* @__PURE__ */ React.createElement("p", { className: "aui-attachment-type" }, fileTypeName))), canRemove && /* @__PURE__ */ React.createElement(AttachmentUI.Remove, null));
};
// src-copilot/frontend-chat/components/ComposerOptionsDropdown.jsx
init_process();
var ComposerOptionsDropdown = () => {
let { toolGroupNames } = React.useContext(getChatAppContext()), { toggleToolGroup, isToolGroupEnabled } = useEnabledTools(), [isOpen, setIsOpen] = React.useState(!1), composerRuntime = AssistantUI.useComposerRuntime();
React.useEffect(() => {
let styleEl = document.createElement("style");
return styleEl.innerText = \`
/* Tool checkbox items with reduced padding */
.composer-options-checkbox-item {
display: flex !important;
align-items: center !important;
gap: 6px !important;
padding: 4px 8px !important;
border-radius: var(--radius-2) !important;
color: var(--gray-12) !important;
font-size: var(--font-size-2) !important;
line-height: var(--line-height-2) !important;
font-weight: var(--font-weight-regular) !important;
user-select: none !important;
}
.composer-options-checkbox-item:hover {
background-color: var(--accent-a3) !important;
}
.composer-options-item-indicator {
width: 16px;
height: 16px;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.composer-options-category-info {
display: flex;
align-items: center;
justify-content: space-between;
flex: 1;
}
.composer-options-category-info span {
user-select: none !important;
}
.composer-options-info-icon {
opacity: 0.6;
cursor: help;
transition: opacity 0.2s;
margin-left: auto;
flex-shrink: 0;
}
.composer-options-info-icon:hover {
opacity: 1;
}
/* Fix tooltip z-index and enable HTML rendering */
[data-radix-tooltip-content] {
z-index: 50000 !important;
}
/* Fix button alignment */
.aui-composer-add-attachment {
align-self: center !important;
}
/* Tools header styling */
.composer-options-tools-header {
display: flex !important;
align-items: center !important;
gap: 6px !important;
padding: 6px 8px !important;
color: var(--gray-11) !important;
font-size: var(--font-size-1) !important;
font-weight: var(--font-weight-medium) !important;
text-transform: uppercase !important;
letter-spacing: 0.05em !important;
}
/* Improve dropdown content styling */
[data-radix-dropdown-menu-content] {
min-width: 200px !important;
padding: 4px !important;
}
\`.replace(/\\s+/g, " ").trim(), document.body.appendChild(styleEl), () => {
document.body.contains(styleEl) && document.body.removeChild(styleEl);
};
}, []);
let handleFileUpload = React.useCallback(() => {
let input = document.createElement("input");
input.type = "file", input.multiple = !0, input.hidden = !0;
let attachmentAccept = composerRuntime.getAttachmentAccept();
attachmentAccept !== "*" && (input.accept = attachmentAccept), document.body.appendChild(input), input.onchange = (e) => {
let fileList = e.target.files;
if (fileList) {
for (let file of fileList)
composerRuntime.addAttachment(file);
document.body.removeChild(input);
}
}, input.oncancel = () => {
(!input.files || input.files.length === 0) && document.body.removeChild(input);
}, input.click(), setIsOpen(!1);
}, [composerRuntime]), handleAddNote = React.useCallback(async () => {
try {
let selectedNote = await window.appConnector.prompt("", {
inputs: [
{ label: "Select note to add to chat", type: "note" }
]
});
if (!selectedNote) return;
let selectedNoteUUID = selectedNote.uuid, noteContent = await window.appConnector.getNoteContentByUUID(selectedNoteUUID);
if (!noteContent) return;
await window.appConnector.sendMessageToEmbed(
"attachments",
{ type: "note", noteUUID: selectedNoteUUID, noteTitle: selectedNote.name, noteContent }
), setIsOpen(!1);
} catch (error) {
console.error("Error adding note:", error), setIsOpen(!1);
}
}, []), { DropdownMenu, Checkbox, Tooltip, Button } = window.RadixUI, { InfoCircledIcon, PlusIcon, UploadIcon, FilePlusIcon, ChevronRightIcon, MixerHorizontalIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(DropdownMenu.Root, { open: isOpen, onOpenChange: setIsOpen }, /* @__PURE__ */ React.createElement(DropdownMenu.Trigger, { asChild: !0 }, /* @__PURE__ */ React.createElement(
Button,
{
variant: "ghost",
size: "2",
className: "aui-composer-add-attachment",
style: {
borderRadius: "50%",
width: "32px",
height: "32px",
padding: "0",
margin: "0"
}
},
/* @__PURE__ */ React.createElement(PlusIcon, { width: "16", height: "16" })
)), /* @__PURE__ */ React.createElement(DropdownMenu.Content, { side: "top" }, /* @__PURE__ */ React.createElement(DropdownMenu.Label, { className: "composer-options-tools-header" }, /* @__PURE__ */ React.createElement(MixerHorizontalIcon, { width: "12", height: "12" }), "Tool Groups"), toolGroupNames.map((toolName) => {
var _a;
return /* @__PURE__ */ React.createElement(
"div",
{
key: toolName,
className: "composer-options-checkbox-item",
onClick: (e) => {
e.preventDefault(), e.stopPropagation(), toggleToolGroup(toolName);
},
style: { cursor: "pointer" }
},
/* @__PURE__ */ React.createElement("div", { className: "composer-options-item-indicator" }, /* @__PURE__ */ React.createElement(
Checkbox,
{
checked: isToolGroupEnabled(toolName),
size: "1"
}
)),
/* @__PURE__ */ React.createElement("div", { className: "composer-options-category-info" }, /* @__PURE__ */ React.createElement("span", null, toolName), /* @__PURE__ */ React.createElement(Tooltip, { content: /* @__PURE__ */ React.createElement("div", { dangerouslySetInnerHTML: { __html: (_a = ToolGroupRegistry.getGroup(toolName)) == null ? void 0 : _a.description } }) }, /* @__PURE__ */ React.createElement(
InfoCircledIcon,
{
className: "composer-options-info-icon",
width: "14",
height: "14"
}
)))
);
}), /* @__PURE__ */ React.createElement(DropdownMenu.Separator, null), /* @__PURE__ */ React.createElement(DropdownMenu.Sub, null, /* @__PURE__ */ React.createElement(DropdownMenu.SubTrigger, null, /* @__PURE__ */ React.createElement(PlusIcon, { width: "16", height: "16" }), "Add context"), /* @__PURE__ */ React.createElement(DropdownMenu.SubContent, null, /* @__PURE__ */ React.createElement(DropdownMenu.Item, { onSelect: handleFileUpload }, /* @__PURE__ */ React.createElement(UploadIcon, { width: "16", height: "16" }), "Upload attachments"), /* @__PURE__ */ React.createElement(DropdownMenu.Separator, null), /* @__PURE__ */ React.createElement(DropdownMenu.Item, { onSelect: handleAddNote }, /* @__PURE__ */ React.createElement(FilePlusIcon, { width: "16", height: "16" }), "Add note to chat")))));
};
// src-copilot/frontend-chat/components/SpeechToTextComposerButton.jsx
init_process();
// src-copilot/frontend-chat/hooks/useSpeechToTextForComposer.js
init_process();
var useSpeechToTextForComposer = (threadRuntime) => {
let { useState, useEffect, useRef } = window.React, [isRecording, setIsRecording] = useState(!1), [isSupported, setIsSupported] = useState(!1), [isInitialized, setIsInitialized] = useState(!1), confirmedTextRef = useRef(""), partialTextRef = useRef(""), baseComposerTextRef = useRef("");
useEffect(() => ((async () => {
try {
let availabilityResult = await window.appConnector.checkVoskletMicrophoneAvailability();
setIsSupported(availabilityResult.isAvailable), availabilityResult.isAvailable || console.warn("Microphone not available:", availabilityResult.message);
} catch (error) {
console.warn("Failed to check microphone availability:", error), setIsSupported(!1);
}
})(), () => {
isInitialized && (window.appConnector.stopVoskletRecording().catch(console.error), window.appConnector.cleanupVoskletSpeechToText().catch(console.error));
}), [isInitialized]), useEffect(() => {
if (!isRecording) return;
let interval = setInterval(async () => {
try {
let updated = !1;
for (; ; ) {
let resultMessage = await window.appConnector.receiveMessageFromPlugin("vosklet-result");
if (!resultMessage) break;
if (typeof resultMessage.text == "string") {
let chunk = resultMessage.text.trim();
chunk && (confirmedTextRef.current = confirmedTextRef.current ? \`\${confirmedTextRef.current} \${chunk}\` : chunk, partialTextRef.current = "", updated = !0);
}
}
let latestPartial = null;
for (; ; ) {
let partialMessage = await window.appConnector.receiveMessageFromPlugin("vosklet-partial");
if (partialMessage === null) break;
latestPartial = partialMessage;
}
latestPartial && typeof latestPartial.text == "string" && (partialTextRef.current = latestPartial.text.trim(), updated = !0);
let errorMessage = await window.appConnector.receiveMessageFromPlugin("vosklet-error");
if (errorMessage) {
console.error("Vosklet error:", errorMessage.error), setIsRecording(!1);
return;
}
if (updated) {
let combined = [confirmedTextRef.current, partialTextRef.current].filter(Boolean).join(" ");
if (combined) {
let newText = baseComposerTextRef.current ? \`\${baseComposerTextRef.current} \${combined}\` : combined;
threadRuntime.composer.setText(newText);
}
}
} catch (error) {
console.error("Error polling for Vosklet messages:", error);
}
}, 200);
return () => clearInterval(interval);
}, [isRecording, threadRuntime]);
let flushVoskletMessages = async () => {
try {
let channels = ["vosklet-partial", "vosklet-result", "vosklet-error", "vosklet-ready"];
for (let channel of channels)
for (; await window.appConnector.receiveMessageFromPlugin(channel) != null; )
;
} catch (e) {
console.warn("Failed to flush initial Vosklet messages", e);
}
}, cleanupExistingVosklet = async () => {
try {
await window.appConnector.stopVoskletRecording(), await window.appConnector.cleanupVoskletSpeechToText();
} catch (error) {
console.warn("No existing Vosklet session to cleanup:", error);
}
};
return {
isRecording,
isSupported,
toggleRecording: async () => {
if (isSupported)
try {
if (isRecording)
await window.appConnector.stopVoskletRecording(), await window.appConnector.cleanupVoskletSpeechToText(), setIsRecording(!1), setIsInitialized(!1), confirmedTextRef.current = "", partialTextRef.current = "", baseComposerTextRef.current = "";
else {
await cleanupExistingVosklet();
let initResult = await window.appConnector.initializeVoskletSpeechToText();
if (!initResult.success) {
console.error("Failed to initialize Vosklet:", initResult.error);
return;
}
let startResult = await window.appConnector.startVoskletRecording({
partialResult: "vosklet-partial",
result: "vosklet-result",
error: "vosklet-error",
ready: "vosklet-ready"
});
if (!startResult.success) {
console.error("Failed to start recording:", startResult.error);
return;
}
baseComposerTextRef.current = threadRuntime.composer.getState().text, setIsInitialized(!0), setIsRecording(!0), await flushVoskletMessages();
}
} catch (error) {
console.error("Error toggling recording:", error), setIsRecording(!1), setIsInitialized(!1);
}
}
};
};
// src-copilot/frontend-chat/components/SpeechToTextComposerButton.jsx
var SpeechToTextComposerButton = () => {
let threadRuntime = AssistantUI.useThreadRuntime(), hasComposerText = AssistantUI.useComposer((composer) => composer.text).trim().length > 0, isLLMCallRunning = AssistantUI.useThread((thread) => thread.isRunning), isToolCallRunning = AssistantUI.useThread((thread) => {
var _a;
if (thread.messages.length > 0) {
let lastMsg = thread.messages[thread.messages.length - 1];
return ((_a = lastMsg == null ? void 0 : lastMsg.status) == null ? void 0 : _a.type) === "requires-action";
}
}), { isRecording, isSupported, toggleRecording } = useSpeechToTextForComposer(threadRuntime), showSendButton = !(isLLMCallRunning || isToolCallRunning) || isToolCallRunning && hasComposerText;
return isSupported ? /* @__PURE__ */ React.createElement(
"button",
{
type: "button",
onClick: toggleRecording,
className: "aui-button aui-button-icon",
title: "Dictate",
style: {
padding: "8px",
border: "none",
background: "transparent",
cursor: "pointer",
borderRadius: "6px",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
minWidth: "32px",
minHeight: "32px",
transition: "all 0.2s ease",
color: isRecording ? "#ef4444" : "var(--aui-muted-foreground)",
opacity: isRecording ? 1 : 0.7,
alignSelf: "center"
},
onMouseEnter: (e) => {
isRecording || (e.target.style.opacity = "1");
},
onMouseLeave: (e) => {
isRecording || (e.target.style.opacity = "0.7");
}
},
/* @__PURE__ */ React.createElement(
"svg",
{
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
fill: "currentColor",
width: "14",
height: "14",
style: {
animation: isRecording ? "pulse 1.5s ease-in-out infinite" : "none"
}
},
/* @__PURE__ */ React.createElement("path", { d: "M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" }),
/* @__PURE__ */ React.createElement("path", { d: "M19 10v2a7 7 0 0 1-14 0v-2a1 1 0 0 1 2 0v2a5 5 0 0 0 10 0v-2a1 1 0 0 1 2 0z" }),
/* @__PURE__ */ React.createElement("path", { d: "M13 21h-2a1 1 0 0 1 0-2h2a1 1 0 0 1 0 2z" })
),
/* @__PURE__ */ React.createElement("style", { jsx: !0 }, \`
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}
\`)
) : null;
};
// src-copilot/frontend-chat/components/CustomComposer.jsx
var CustomComposer = () => {
let allowAttachments = useAllowAttachments(), threadRuntime = AssistantUI.useThreadRuntime(), textareaRef = React.useRef(null), isLLMCallRunning = AssistantUI.useThread((thread) => thread.isRunning), isToolCallRunning = AssistantUI.useThread((thread) => {
var _a;
if (thread.messages.length > 0) {
let lastMsg = thread.messages[thread.messages.length - 1];
return ((_a = lastMsg == null ? void 0 : lastMsg.status) == null ? void 0 : _a.type) === "requires-action";
}
}), hasComposerText = AssistantUI.useComposer((composer) => composer.text).trim().length > 0, { toolGroupNames, chatHistoryLoaded } = React.useContext(getChatAppContext());
useTributeSetup(textareaRef, toolGroupNames), React.useEffect(() => {
textareaRef.current && textareaRef.current.addEventListener("keydown", (e) => {
let isTributeDisplayed = document.querySelector(".tribute-container");
isTributeDisplayed = isTributeDisplayed && isTributeDisplayed.style.display !== "none", e.key === "Enter" && !e.shiftKey && !isTributeDisplayed && threadRuntime.composer.getState().text.trim() && (e.preventDefault(), e.stopPropagation(), threadRuntime.composer.send());
});
}, [threadRuntime, textareaRef]), React.useEffect(() => {
chatHistoryLoaded && textareaRef.current && textareaRef.current.focus();
}, [chatHistoryLoaded]);
let { setThreadNewMsgComposerRef } = React.useContext(getChatAppContext());
React.useEffect(() => {
setThreadNewMsgComposerRef(textareaRef);
}, [textareaRef, setThreadNewMsgComposerRef]);
let showSendButton = !(isLLMCallRunning || isToolCallRunning) || isToolCallRunning && hasComposerText, showCancelButton = !showSendButton, { Composer } = window.AssistantUI;
return /* @__PURE__ */ React.createElement(Composer.Root, null, allowAttachments && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
Composer.Attachments,
{
components: {
File: FileAttachmentDisplay
}
}
), /* @__PURE__ */ React.createElement(ComposerOptionsDropdown, null)), /* @__PURE__ */ React.createElement(Composer.Input, { ref: textareaRef }), /* @__PURE__ */ React.createElement(SpeechToTextComposerButton, null), showSendButton && /* @__PURE__ */ React.createElement(Composer.Send, null), showCancelButton && /* @__PURE__ */ React.createElement(
"button",
{
disabled: isToolCallRunning,
className: "aui-button aui-button-primary aui-button-icon aui-composer-cancel",
type: "button",
onClick: () => threadRuntime.cancelRun(),
"data-state": "closed"
},
/* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 16 16", fill: "currentColor", width: "16", height: "16" }, /* @__PURE__ */ React.createElement("rect", { width: "10", height: "10", x: "3", y: "3", rx: "2" })),
/* @__PURE__ */ React.createElement("span", { className: "aui-sr-only" }, "Cancel")
));
}, useAllowAttachments = () => AssistantUI.useThreadRuntime().getState().capabilities.attachments;
// src-copilot/frontend-chat/ChatAppHeader.jsx
init_process();
// src-copilot/markdown/replaceParagraphTextInMarkdown.jsx
init_process();
var replaceParagraphTextInMarkdown = async (markdownText, replaceFunc) => {
let ast = await parse(markdownText), result = markdownText, textNodes = [];
return visitParents(ast, (node2, ancestors) => {
node2.type === "text" && ancestors.some((parent) => parent.type === "paragraph") && textNodes.push(node2);
}), textNodes.sort((a, b) => b.position.start.offset - a.position.start.offset), textNodes.forEach((node2) => {
let { start, end } = node2.position, startIndex = start.offset, endIndex = end.offset;
result = result.slice(0, startIndex) + replaceFunc(node2.value) + result.slice(endIndex);
}), result;
};
// src-copilot/frontend-chat/ChatAppHeader.jsx
var ChatAppHeader = () => {
let runtime = AssistantUI.useAssistantRuntime(), onClickNewChat = React.useCallback(() => runtime.threads.switchToNewThread(), [runtime]), { Box, Tooltip, Button, Popover } = window.RadixUI, { PlusIcon, MagicWandIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(Box, { style: {
display: "flex",
justifyContent: "flex-end",
paddingRight: "4px",
position: "sticky",
top: 0,
zIndex: "1000",
backgroundColor: "var(--color-background)"
} }, /* @__PURE__ */ React.createElement(Popover.Root, null, /* @__PURE__ */ React.createElement(Tooltip, { content: "Prompt Library", style: { padding: "2px" } }, /* @__PURE__ */ React.createElement(Popover.Trigger, { asChild: !0 }, /* @__PURE__ */ React.createElement(Button, { variant: "ghost", size: "1", style: { margin: "2px", paddingTop: "5px" }, className: "user-prompt-library-button" }, /* @__PURE__ */ React.createElement(MagicWandIcon, { width: "13", height: "13" })))), /* @__PURE__ */ React.createElement(
Popover.Content,
{
align: "start",
sideOffset: 4,
style: { width: "360px" }
},
/* @__PURE__ */ React.createElement(UserPromptLibrary, null)
)), /* @__PURE__ */ React.createElement(ChatInterfaceMenu, null), /* @__PURE__ */ React.createElement(Tooltip, { content: "New chat" }, /* @__PURE__ */ React.createElement(
Button,
{
variant: "ghost",
size: "1",
style: { marginRight: "4px", margin: "2px" },
onClick: onClickNewChat
},
/* @__PURE__ */ React.createElement(PlusIcon, null)
)));
}, ChatInterfaceMenu = () => {
let threadRuntime = AssistantUI.useThreadRuntime(), [threadMessages, setThreadMessages] = React.useState([]);
threadRuntime.subscribe(() => {
setThreadMessages(threadRuntime.getState().messages || []);
});
let threadMessagesLength = threadMessages == null ? void 0 : threadMessages.length, threadId = AssistantUI.useThreadListItemRuntime().getState().id, [exportNoteExists, setExportNoteExists] = React.useState(!1), [exportNoteName, setExportNoteName] = React.useState(\`Copilot chat - \${threadId}\`), { setIsChatHistoryOverlayOpen, toolGroupNames } = React.useContext(getChatAppContext());
React.useEffect(() => {
setExportNoteName(\`Copilot chat - \${threadId}\`);
}, [threadId]), React.useEffect(() => {
(async () => {
try {
let note = await window.appConnector.findNote({ name: exportNoteName });
setExportNoteExists(!!note);
} catch {
}
})();
}, [exportNoteName]);
let handleExportAsNote = React.useCallback(async () => {
let noteContent = "";
for (let message of threadMessages) {
noteContent += \`<mark style="color:undefined;">**\${capitalize_default(message.role)}**<!-- {"cycleColor":"\${message.role === "assistant" ? "59" : "57"}"} --></mark>
\`;
for (let contentPart of message.content)
if (contentPart.type === "text") {
let tempText = contentPart.text;
for (let groupName of toolGroupNames) {
let toolGroup = ToolGroupRegistry.getGroup(groupName);
tempText = await replaceParagraphTextInMarkdown(tempText, (oldVal) => oldVal.replaceAll("@" + groupName, "\`@" + toolGroup.name + "\`"));
}
noteContent += tempText + \`
\`;
} else contentPart.type === "tool-call" && (noteContent += \`\\xABTool call: \${contentPart.toolName}\\xBB
\`);
}
let note = await appConnector.findNote({ name: exportNoteName });
if (!note && (note = await appConnector.createNote(exportNoteName, []), note = await appConnector.findNote({ name: exportNoteName }), !note || !note.uuid))
throw new Error(\`Failed to create note: \${exportNoteName}\`);
setExportNoteExists(!0), await appConnector.replaceNoteContent({ uuid: note.uuid }, noteContent), await appConnector.navigate(\`https://www.amplenote.com/notes/\${note.uuid}\`), await appConnector.alert(\`Chat exported to note: \${exportNoteName}\`);
}, [threadMessages, threadId, setExportNoteExists, exportNoteName, toolGroupNames]), handleExportAsJSON = React.useCallback(async () => {
let jsonContent = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(threadMessages, null, 2));
await appConnector.saveFile({ data: jsonContent, name: threadId + ".json" });
}, [threadMessages, threadId, exportNoteName]), { Flex, Text, Box, Popover, DropdownMenu, Button } = window.RadixUI, { DropdownMenuIcon, CodeIcon, Share2Icon, FilePlusIcon, CounterClockwiseClockIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(DropdownMenu.Root, null, /* @__PURE__ */ React.createElement(DropdownMenu.Trigger, null, /* @__PURE__ */ React.createElement(Button, { variant: "ghost", size: "1", style: { margin: "2px" } }, /* @__PURE__ */ React.createElement(DropdownMenuIcon, null))), /* @__PURE__ */ React.createElement(DropdownMenu.Content, null, /* @__PURE__ */ React.createElement(DropdownMenu.Item, { onClick: () => setIsChatHistoryOverlayOpen(!0) }, /* @__PURE__ */ React.createElement(CounterClockwiseClockIcon, null), " Chat History"), /* @__PURE__ */ React.createElement(DropdownMenu.Sub, null, /* @__PURE__ */ React.createElement(DropdownMenu.SubTrigger, { disabled: threadMessagesLength === 0 }, /* @__PURE__ */ React.createElement(Share2Icon, null), " Export chat as"), /* @__PURE__ */ React.createElement(DropdownMenu.SubContent, null, /* @__PURE__ */ React.createElement(DropdownMenu.Item, { onClick: handleExportAsNote }, /* @__PURE__ */ React.createElement(Flex, { style: { alignItems: "center" } }, /* @__PURE__ */ React.createElement(FilePlusIcon, null), /* @__PURE__ */ React.createElement(Flex, { style: { flexDirection: "column", marginLeft: "8px" } }, /* @__PURE__ */ React.createElement(Flex, { style: { alignItems: "center" } }, exportNoteExists ? "Update Note" : "New Note"), /* @__PURE__ */ React.createElement(Text, { size: "1", style: { color: "var(--gray-11)" } }, exportNoteName)))), /* @__PURE__ */ React.createElement(DropdownMenu.Separator, null), /* @__PURE__ */ React.createElement(DropdownMenu.Item, { onClick: handleExportAsJSON }, /* @__PURE__ */ React.createElement(Flex, { style: { alignItems: "center" } }, /* @__PURE__ */ React.createElement(CodeIcon, null), /* @__PURE__ */ React.createElement(Text, { style: { marginLeft: "8px" } }, "Download JSON"))))))));
}, UserPromptLibrary = () => {
let composer = AssistantUI.useComposerRuntime(), [userPromptList, setUserPromptList] = React.useState(null), { threadNewMsgComposerRef } = React.useContext(getChatAppContext());
React.useEffect(() => {
(async () => {
try {
let settings = await window.appConnector.getSettings();
setUserPromptList(JSON.parse(settings[USER_PROMPT_LIST_SETTING]).sort((a, b) => b.usageCount - a.usageCount));
} catch (e) {
setUserPromptList([]), console.error(e);
}
})();
}, []);
let handleInsertPrompt = React.useCallback((prompt) => {
composer.setText(prompt.message), threadNewMsgComposerRef.current.focus();
let newPromptList = userPromptList.map((prompt2) => prompt2.uuid === prompt.uuid ? { ...prompt, usageCount: prompt.usageCount + 1 } : prompt2);
setUserPromptList(newPromptList), window.appConnector.setSetting(USER_PROMPT_LIST_SETTING, JSON.stringify(newPromptList));
}, [composer, userPromptList]), handleAddPrompt = React.useCallback(async () => {
let promptText = await window.appConnector.prompt("Enter prompt:", {
inputs: [
{ label: "Enter custom prompt:", type: "text", value: "" }
]
});
if (!promptText) return;
let promptObject = {
uuid: Math.random().toString(36).substring(7),
message: promptText.trim(),
usageCount: 0
};
await window.appConnector.setSetting(USER_PROMPT_LIST_SETTING, JSON.stringify([...userPromptList, promptObject])), setUserPromptList([...userPromptList, promptObject]);
}, [userPromptList]), handleEditPrompt = React.useCallback(async (e, prompt) => {
e.stopPropagation();
let editedText = await window.appConnector.prompt("Edit prompt:", {
inputs: [
{ label: "Edit prompt:", type: "text", value: prompt.message }
]
});
if (!editedText || editedText.trim() === prompt.message) return;
let updatedPromptList = userPromptList.map(
(p) => p.uuid === prompt.uuid ? { ...p, message: editedText.trim() } : p
);
await window.appConnector.setSetting(USER_PROMPT_LIST_SETTING, JSON.stringify(updatedPromptList)), setUserPromptList(updatedPromptList);
}, [userPromptList]), handleDeletePrompt = React.useCallback(async (e, prompt) => {
e.stopPropagation(), await window.appConnector.prompt("Are you sure you want to delete this prompt?", {
inputs: []
}) && (await window.appConnector.setSetting(USER_PROMPT_LIST_SETTING, JSON.stringify(userPromptList.filter((p) => p.uuid !== prompt.uuid))), setUserPromptList(userPromptList.filter((p) => p.uuid !== prompt.uuid)));
}, [userPromptList]);
if (!userPromptList) return null;
let { Button, ScrollArea, Text, Box, Card, Flex, IconButton, DropdownMenu } = window.RadixUI, { TrashIcon, DotsHorizontalIcon, Pencil1Icon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ScrollArea, { style: { maxHeight: "320px" }, type: "auto" }, /* @__PURE__ */ React.createElement(Box, { style: { padding: "8px" } }, userPromptList.map((prompt) => /* @__PURE__ */ React.createElement(Card, { asChild: !0, key: prompt.uuid, style: { padding: "8px", margin: "6px" }, className: "user-prompt-card" }, /* @__PURE__ */ React.createElement("a", { href: "#", onClick: () => handleInsertPrompt(prompt) }, /* @__PURE__ */ React.createElement(Flex, { justify: "between", align: "start", style: { padding: "2px", minHeight: "33px" } }, /* @__PURE__ */ React.createElement(Text, { style: { fontSize: "11px", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", textOverflow: "ellipsis", flex: 1 } }, prompt.message), /* @__PURE__ */ React.createElement(DropdownMenu.Root, null, /* @__PURE__ */ React.createElement(DropdownMenu.Trigger, { asChild: !0 }, /* @__PURE__ */ React.createElement(
IconButton,
{
variant: "soft",
size: "1",
onClick: (e) => e.stopPropagation()
},
/* @__PURE__ */ React.createElement(DotsHorizontalIcon, null)
)), /* @__PURE__ */ React.createElement(DropdownMenu.Content, { align: "end", sideOffset: -4, size: "1", variant: "soft" }, /* @__PURE__ */ React.createElement(
DropdownMenu.Item,
{
onClick: (e) => handleEditPrompt(e, prompt)
},
/* @__PURE__ */ React.createElement(Pencil1Icon, { width: "14", height: "14" }),
" Edit"
), /* @__PURE__ */ React.createElement(DropdownMenu.Separator, null), /* @__PURE__ */ React.createElement(
DropdownMenu.Item,
{
onClick: (e) => handleDeletePrompt(e, prompt),
color: "red"
},
/* @__PURE__ */ React.createElement(TrashIcon, { width: "14", height: "14" }),
" Delete"
))))))), userPromptList.length === 0 && /* @__PURE__ */ React.createElement(Text, { style: { textAlign: "center", color: "var(--color-text-muted)" } }, "No saved prompts yet"))), /* @__PURE__ */ React.createElement(Box, { style: { marginTop: "16px" } }, /* @__PURE__ */ React.createElement(
Button,
{
className: "user-prompt-library-add-button",
onClick: handleAddPrompt,
variant: "soft",
size: "1",
style: { width: "100%" }
},
"Add New Prompt"
)));
};
// src-copilot/frontend-chat/hooks/useAssistantAvatar.jsx
init_process();
var useAssistantAvatar = () => {
let [assistantAvatar, setAssistantAvatar] = React.useState({ fallback: "" });
return React.useEffect(() => {
(async () => {
let assistantAvatarSrc = window.appSettings[CUSTOM_LLM_AVATAR_SETTING];
assistantAvatarSrc ? await isValidImageUrl(assistantAvatarSrc) ? setAssistantAvatar({ src: assistantAvatarSrc }) : (setAssistantAvatar({ fallback: "A" }), console.error(\`Invalid image URL: \${assistantAvatarSrc}\`)) : setAssistantAvatar({ fallback: "A" });
})();
}, []), assistantAvatar;
}, isValidImageUrl = async (url) => !url || url.trim() === "" ? !1 : new Promise((resolve) => {
let img = new Image();
img.onload = () => resolve(!0), img.onerror = () => resolve(!1), img.src = url;
});
// src-copilot/frontend-chat/hooks/useModelContext.jsx
init_process();
// src-copilot/aisdk-wrappers/utils/convertUIToolsToDummyServerTools.js
init_process();
var convertUIToolsToDummyServerTools = (tools) => tools.reduce((acc, tool) => (acc[tool.unstable_tool.toolName] = {
description: tool.unstable_tool.description,
parameters: tool.unstable_tool.parameters,
execute: async (args) => {
}
}, acc), {});
// src-copilot/frontend-chat/helpers/getSystemMessage.js
init_process();
function getSystemMessage(currentMessages, enabledTools) {
if (currentMessages.some(
(message) => message.attachments && message.attachments.length > 0 && message.attachments.some((attachment) => attachment.type === "image")
)) return null;
let lastMessage = currentMessages[currentMessages.length - 1] || null, messageContainsAttachments = currentMessages.some(
(message) => message.attachments && message.attachments.length > 0
), isNotesToolGroupEnabled = enabledTools.includes("notes"), isTasksToolGroupEnabled = enabledTools.includes("tasks");
function getToolUsageMessage() {
if (enabledTools.length === 0)
return \`
No tools are enabled currently. If tools are required, ask to enable them. Tool groups that can be enabled by user: "@tasks", "@notes", "@help" and "@web".\`;
let toolUsageMessage = "";
return toolUsageMessage += \`Your primary goal is to help users efficiently, adhering strictly to the following instructions and utilizing your available tools.
\`, toolUsageMessage += \`Tool Usage Instructions:-
- NEVER say the tool name and uuid string to user. For example, instead of saying that you'll use WebSearch tool, just say I'll search the web.
- No need to ask permission before using a tool
- Formulate an plan for your future self at the start. However, DON'T repeat yourself after a tool call, pick up where you left off.
- Execute multiple tool calls in parallel if feasible; avoid when dependent on prior outputs (e.g. UUIDs)
\` + (isNotesToolGroupEnabled || isTasksToolGroupEnabled ? "- When requested to perform tasks, don't make assumptions. First, gather as much context as needed by calling tools." : ""), toolUsageMessage;
}
function getToolResultDisplayInstruction() {
let resultDisplayInstruction = "Note:- ";
if (lastMessage) {
let lastContentContainsWebSearch = lastMessage && lastMessage.content.some((obj) => obj.toolName === "WebSearch"), lastContentContainsSearchNote = lastMessage && lastMessage.content.some((obj) => obj.toolName === "SearchNotesByTitleTagsContent"), lastContentContainsSearchHelpCenter = lastMessage && lastMessage.content.some((obj) => obj.toolName === "SearchHelpCenter");
lastContentContainsWebSearch && (resultDisplayInstruction += \`If the user is asking a question, provide comprehensive answer using information from search results.
List relevant links at end for reference.\`), lastContentContainsSearchNote && (resultDisplayInstruction += "The search result only contains the matched portion of the note content. If full context is required, use the FetchNoteDetailByNoteUUID tool to retrieve the complete note content."), lastContentContainsSearchNote && (resultDisplayInstruction += \`If the user is asking a question, provide comprehensive answer using information from search results.
List relevant note links in markdown at end for reference. To link to a note, use syntax: [Page Title](https://www.amplenote.com/notes/{noteUUID}).\`), lastContentContainsSearchHelpCenter && (resultDisplayInstruction += \`If the user is asking a question, provide comprehensive answer using information from search results.
Use markdown image syntax to include images in your answer when relevant.
List relevant help center links at end for reference.\`);
}
return resultDisplayInstruction;
}
let terminology = [
isTasksToolGroupEnabled || isNotesToolGroupEnabled ? "Daily Jot: Note tagged with #daily-jots for storing daily thoughts." : "",
isNotesToolGroupEnabled ? "Note: Markdown pages stored in amplenote." : "",
isTasksToolGroupEnabled || isNotesToolGroupEnabled ? "Note / Task UUID: 36 character internal id required for some tools." : "",
isTasksToolGroupEnabled ? \`Task: Stored in notes, viewable in Agenda and Calendar views.
Task Domain: Organizational containers for tasks.\` : ""
].filter(Boolean).join(\`
\`).trim(), userInfo = [
window.userData.dailyJotNoteUUID ? \`Today's daily jot note UUID: \${window.userData.dailyJotNoteUUID}\` : "",
window.userData.currentNoteUUID ? \`Current Note UUID: \${window.userData.currentNoteUUID}\` : "",
messageContainsAttachments && window.userData.currentNoteUUID ? "Attached note takes priority over current note to fulfill user request." : ""
].filter(Boolean).join(\`
\`).trim();
return \`
You are Ample Copilot, a automated ai agent inside note-taking productivity app - Amplenote. \${getToolUsageMessage()}
\${terminology ? \`Terminology:-
\${terminology}\` : ""}
\${window.appSettings[CUSTOM_LLM_INSTRUCTION_SETTING] && window.appSettings[CUSTOM_LLM_INSTRUCTION_SETTING].trim() !== "" ? \`Additional Instruction from user:-
\` + window.appSettings[CUSTOM_LLM_INSTRUCTION_SETTING].trim().replaceAll(/\\s+/gm, " ").trim() : ""}
\${getToolResultDisplayInstruction()}
\${userInfo ? \`User info:-
\${userInfo}\` : ""}
\${Intl.DateTimeFormat().resolvedOptions().timeZone ? \`Timezone: \${Intl.DateTimeFormat().resolvedOptions().timeZone}
\` : ""}
Current time: \${window.dayjs().format()}
\`.trim().replaceAll(/^[ \\t]+/gm, "").trim();
}
// src-copilot/frontend-chat/helpers/tool-group-mentions.js
init_process();
function createGroupMentionRegex(groupName) {
let escapedGroupName = groupName.replace(/[.*+?^\${}()|[\\]\\\\]/g, "\\\\$&");
return new RegExp(\`(^|\\\\s|\\\\n|\\\\(|\\\\[)@\${escapedGroupName}(\\\\s|\\\\n|!|\\\\?|\\\\)|]|\\\\.|$)\`, "g");
}
function findToolGroupMentions(text, groupNames) {
let mentions = [];
for (let groupName of groupNames) {
let regex = createGroupMentionRegex(groupName), match;
for (; (match = regex.exec(text)) !== null; )
mentions.push({
groupName,
start: match.index,
end: match.index + match[0].length,
fullMatch: match[0],
prefix: match[1],
// The character before @groupName
suffix: match[2],
// The character after @groupName
mentionStart: match.index + match[1].length,
// Start of @groupName
mentionEnd: match.index + match[1].length + groupName.length + 1
// End of @groupName
});
}
return mentions.sort((a, b) => a.start - b.start);
}
function getMentionedGroupNames(text, groupNames) {
let mentionedGroups = /* @__PURE__ */ new Set();
for (let groupName of groupNames)
createGroupMentionRegex(groupName).test(text) && mentionedGroups.add(groupName);
return Array.from(mentionedGroups);
}
function processToolGroupMentions(text, groupNames, replacementFn) {
let mentions = findToolGroupMentions(text, groupNames);
if (mentions.length === 0)
return [text];
let result = [], lastIndex = 0;
for (let mention of mentions) {
mention.start > lastIndex && result.push(text.substring(lastIndex, mention.start)), mention.prefix && result.push(mention.prefix);
let replacement = replacementFn(mention.groupName, mention);
result.push(replacement), mention.suffix && result.push(mention.suffix), lastIndex = mention.end;
}
return lastIndex < text.length && result.push(text.substring(lastIndex)), result;
}
// src-copilot/frontend-chat/hooks/useModelContext.jsx
function useModelContext() {
let runtime = AssistantUI.useAssistantRuntime(), { enabledToolGroups } = React.useContext(getChatAppContext()), { enableToolGroup } = useEnabledTools(), modelContextUnsubscribe = React.useRef(null);
React.useEffect(() => {
modelContextUnsubscribe.current && (modelContextUnsubscribe.current(), modelContextUnsubscribe.current = null);
let unsubscribeFromThread = runtime.thread.subscribe(() => {
let currentMessages = runtime.thread.getState().messages;
modelContextUnsubscribe.current && modelContextUnsubscribe.current(), modelContextUnsubscribe.current = runtime.registerModelContextProvider({
getModelContext: () => {
let enabledTools = [], allGroupNames = ToolGroupRegistry.getAllGroupNames();
for (let groupName of allGroupNames)
if (enabledToolGroups.has(groupName)) {
let groupTools = ToolGroupRegistry.getToolsByGroup(groupName);
enabledTools.push(...groupTools);
}
let lastUserMessage = currentMessages.filter((msg) => msg.role === "user").pop();
if (lastUserMessage && lastUserMessage.content) {
for (let contentPart of lastUserMessage.content)
if (contentPart.type === "text" && contentPart.text) {
let mentionedGroups = getMentionedGroupNames(contentPart.text, allGroupNames);
for (let groupName of mentionedGroups) {
let groupTools = ToolGroupRegistry.getToolsByGroup(groupName);
enabledTools.push(...groupTools), enableToolGroup(groupName);
}
}
}
let systemMsg = getSystemMessage(currentMessages, enabledTools);
return {
priority: Date.now(),
tools: enabledTools.length > 0 ? convertUIToolsToDummyServerTools([...enabledTools]) : null,
system: systemMsg
};
}
});
});
return () => {
unsubscribeFromThread(), modelContextUnsubscribe.current && (modelContextUnsubscribe.current(), modelContextUnsubscribe.current = null);
};
}, [runtime, enabledToolGroups]);
}
// src-copilot/frontend-chat/components/UserMessage.jsx
init_process();
// src-copilot/frontend-chat/components/makeCustomMarkdownText.jsx
init_process();
var makeCustomMarkdownText = async ({ overrideComponents, ...rest } = {}) => {
let { makeMarkdownText } = window.AssistantUIMarkdown, [remarkGfm2] = await dynamicImportExternalPluginBundle("remarkBundle.js");
return makeMarkdownText({
components: {
SyntaxHighlighter: ({ code, components, language }) => {
let { Pre, Code } = components, [HighlightJS, setHighlightJS] = React.useState(null);
return React.useEffect(() => {
(async () => {
if (!HighlightJS)
if (window.HighlightJS)
setHighlightJS(window.HighlightJS);
else {
await dynamicImportCSS("highlight.js/styles/github.css");
let hljs = await dynamic_import_esm_default("highlight.js");
setHighlightJS(hljs.default), window.HighlightJS = hljs.default;
}
})();
}, [HighlightJS]), /* @__PURE__ */ React.createElement(Pre, null, HighlightJS === null ? /* @__PURE__ */ React.createElement(Code, null, code) : /* @__PURE__ */ React.createElement(Code, { dangerouslySetInnerHTML: {
__html: HighlightJS.highlight(code, {
language: HighlightJS.getLanguage(language) ? language : "plaintext"
}).value
} }));
},
p: ({ node: node2, children, ...props }) => {
let processToolGroupMentionTags = (text) => {
let { toolGroupNames } = React.useContext(getChatAppContext());
return processToolGroupMentions(text, toolGroupNames, (groupName, mention) => {
let toolGroup = ToolGroupRegistry.getGroup(groupName);
return /* @__PURE__ */ React.createElement(ToolGroupMentionComponent, { key: mention.start, ...toolGroup }, groupName);
});
};
return children = Array.isArray(children) ? children.map((child) => typeof child != "string" ? child : processToolGroupMentionTags(child)) : typeof children == "string" ? processToolGroupMentionTags(children) : children, // pre-wrap added to preserve new lines
/* @__PURE__ */ React.createElement("div", { className: "aui-md-p", ...props, style: { ...props == null ? void 0 : props.style, whiteSpace: "pre-wrap" } }, children);
},
a: ({ node: node2, children, href, ...props }) => /* @__PURE__ */ React.createElement(
"a",
{
className: "aui-md-a",
...props,
href,
onClick: async (e) => {
e.preventDefault(), await appConnector.navigate(href) || appConnector.alert(\`Failed to open link due to amplenote restrictions: \${href}
Please right click on the link and select "Open link in new tab".\`);
}
},
children
),
CodeHeader: ({ ...args }) => /* @__PURE__ */ React.createElement(AssistantUIMarkdown.CodeHeader, { ...args }),
...overrideComponents
},
remarkPlugins: [remarkGfm2.default],
rehypePlugins: [rehypeCompressTextNodes],
...rest
});
}, rehypeCompressTextNodes = () => {
let isOfTypeText = (node2) => node2.type === "text" || node2.type === "raw";
return (tree) => {
visit(tree, "element", (node2) => {
if (!node2.children) return;
let compressedChildren = [];
for (let child of node2.children) {
let lastChild = compressedChildren.slice(-1)[0];
lastChild && isOfTypeText(lastChild) && isOfTypeText(child) ? (lastChild.value += child.value, lastChild.position = null, lastChild.type = "text") : compressedChildren.push(child);
}
node2.children = compressedChildren;
});
};
}, ToolGroupMentionComponent = ({ children, description }) => {
let { Text, Tooltip, Popover } = window.RadixUI;
return /* @__PURE__ */ React.createElement(Popover.Root, null, /* @__PURE__ */ React.createElement(Tooltip, { content: "Click to open tool group documentation" }, /* @__PURE__ */ React.createElement(Popover.Trigger, { asChild: !0 }, /* @__PURE__ */ React.createElement(Text, { as: "a", className: "tool_group_mention", style: { cursor: "pointer" } }, "@", children))), /* @__PURE__ */ React.createElement(Popover.Content, { size: "1", style: { maxHeight: "140px", overflowY: "auto", maxWidth: "260px" } }, /* @__PURE__ */ React.createElement(Text, { size: "1", style: { whiteSpace: "pre-wrap" }, asChild: !0 }, /* @__PURE__ */ React.createElement("span", { dangerouslySetInnerHTML: { __html: description } }))));
};
// src-copilot/frontend-chat/components/UserMessage.jsx
var UserMessage = () => {
let { UserMessage: UserMessage2, MessagePrimitive, UserActionBar, BranchPicker } = window.AssistantUI;
return /* @__PURE__ */ React.createElement(UserMessage2.Root, null, /* @__PURE__ */ React.createElement(UserMessage2.Attachments, { components: { File: FileAttachmentDisplay } }), /* @__PURE__ */ React.createElement(MessagePrimitive.If, { hasContent: !0 }, /* @__PURE__ */ React.createElement(UserActionBar, null), /* @__PURE__ */ React.createElement(UserMessageContent, null)), /* @__PURE__ */ React.createElement(BranchPicker, null));
}, UserMessageContentWrapper = ({ children, ...props }) => /* @__PURE__ */ React.createElement("div", { className: "aui-user-message-content", ...props }, children), UserMessageContent = (props) => {
let { MessagePrimitive } = window.AssistantUI;
return /* @__PURE__ */ React.createElement(UserMessageContentWrapper, { ...props }, /* @__PURE__ */ React.createElement(
MessagePrimitive.Content,
{
components: {
Text: UserMessageText
}
}
));
}, UserMessageText = ({ text }) => {
let [children, setChildren] = React.useState(null), { toolGroupNames } = React.useContext(getChatAppContext());
return React.useEffect(() => {
(async () => {
let result = processToolGroupMentions(text, toolGroupNames, (groupName, mention) => {
let toolGroup = ToolGroupRegistry.getGroup(groupName);
return /* @__PURE__ */ React.createElement(ToolGroupMentionComponent, { key: mention.start, ...toolGroup }, groupName);
});
setChildren(result);
})();
}, [text, toolGroupNames]), // pre-wrap added to preserve new lines
/* @__PURE__ */ React.createElement("div", { className: "aui-md-p", style: { whiteSpace: "pre-wrap" } }, children);
};
// src-copilot/frontend-chat/hooks/useAmplenoteAttachments.jsx
init_process();
var useAmplenoteAttachments = () => {
let threadRuntime = AssistantUI.useThreadRuntime(), composer = AssistantUI.useComposer(), assistantRuntime = AssistantUI.useAssistantRuntime(), { chatHistoryLoaded, setInitialAttachmentProcessed } = React.useContext(getChatAppContext()), { enableToolGroup } = useEnabledTools();
React.useEffect(() => {
let processAttachments = async () => {
if (!chatHistoryLoaded) return;
let attachment = await window.appConnector.receiveMessageFromPlugin("attachments");
if (!attachment) {
setInitialAttachmentProcessed(!0);
return;
}
let attachmentExists = (attachmentId) => composer.attachments.some((attachment2) => attachment2.id === attachmentId), addAttachmentIfNotExists = async (file) => {
attachment && (attachmentExists(file.name) || await threadRuntime.composer.addAttachment(file));
};
if (attachment.type === "image") {
if (!attachment.src) return;
let response;
try {
response = await fetch(attachment.src);
} catch {
if (response = await fetch(getCorsBypassUrl(attachment.src)), !response.ok)
throw new Error("Both initial and bypass fetch failed");
}
let blob = await response.blob(), fileName = attachment.src.split("/").pop(), file = new File([blob], fileName, { type: "image/jpeg" });
await addAttachmentIfNotExists(file);
} else if (attachment.type === "note") {
let noteUUID = attachment.noteUUID, noteName = attachment.noteTitle || "Untitled Note", noteContent = attachment.noteContent, file = new File([
\`Attached note title: \${noteName}
Attached note UUID: \${noteUUID}
Attached note content: \${noteContent.length > 8e3 ? "Content too long. Use note detail tool to get full content if required." : noteContent}\`
], noteName, { type: "text/amplenote-note" });
await addAttachmentIfNotExists(file), await new Promise((resolve) => setTimeout(resolve, 60)), await enableToolGroup("notes");
} else if (attachment.type === "selection") {
let noteUUID = attachment.noteUUID, selectionContent = attachment.selectionContent, file = new File([
\`Selection made in note with UUID: \${noteUUID}
Selected text: \${selectionContent}\`
], selectionContent, { type: "text/amplenote-selection" });
await addAttachmentIfNotExists(file), await new Promise((resolve) => setTimeout(resolve, 60)), await enableToolGroup("notes");
} else if (attachment.type === "task") {
let taskUUID = attachment.taskUUID, file = new File([
\`Attached task UUID: \${taskUUID}\` + (attachment.taskContent ? \`
Task content: \${attachment.taskContent}\` : "") + (attachment.taskStartAt ? \`
Task start at: \${attachment.taskStartAt}\` : "") + (attachment.taskEndAt ? \`
Task end at: \${attachment.taskEndAt}\` : "") + (attachment.completedAt ? \`
Task completed at: \${attachment.completedAt}\` : "") + (attachment.dismissedAt ? \`
Task dismissed at: \${attachment.dismissedAt}\` : "") + (attachment.hideUntil ? \`
Task hide until: \${attachment.hideUntil}\` : "") + (attachment.taskScore ? \`
Task score: \${attachment.taskScore}\` : "") + (attachment.important ? \`
Task important: \${attachment.important}\` : "") + (attachment.urgent ? \`
Task urgent: \${attachment.urgent}\` : "")
], taskUUID, { type: "text/amplenote-task" });
await addAttachmentIfNotExists(file), await new Promise((resolve) => setTimeout(resolve, 60)), await enableToolGroup("tasks");
} else if (attachment.type === "new-chat") {
let message = attachment.message || [];
await assistantRuntime.threads.switchToNewThread(), await threadRuntime.import({ messages: message });
let composerText = message.composerText;
composerText && await composer.setText(composerText);
}
};
processAttachments();
let intervalId = setInterval(processAttachments, 300);
return () => clearInterval(intervalId);
}, [composer, threadRuntime, chatHistoryLoaded]);
};
// src-copilot/frontend-chat/hooks/useUserDataPolling.jsx
init_process();
function useUserDataPolling() {
let runtime = AssistantUI.useAssistantRuntime();
React.useEffect(() => {
let updateUserData = async () => {
window.appConnector.getUserCurrentNoteData().then(async (userData2) => {
window.userData = { ...window.userData, ...userData2 };
}), window.appConnector.getUserDailyJotNote().then(async (userData2) => {
window.userData = { ...window.userData, ...userData2 };
});
};
updateUserData();
let intervalId = setInterval(() => updateUserData(), 4e3), unsubscribe = runtime.thread.subscribe(() => updateUserData());
return () => {
clearInterval(intervalId), unsubscribe();
};
}, [runtime]);
}
// src-copilot/frontend-chat/hooks/useIntervalPingPlugin.jsx
init_process();
function useIntervalPingPlugin(enabled = !0) {
React.useEffect(() => {
if (!enabled) return;
let intervalId = setInterval(() => {
window.appConnector.ping();
}, 300);
return window.appConnector.ping(), () => clearInterval(intervalId);
}, [enabled]);
}
// src-copilot/frontend-chat/ChatHistoryOverlay.jsx
init_process();
// src-copilot/frontend-chat/components/ThreadCard.jsx
init_process();
function ThreadCard({ thread, onDelete, onClick, isCurrentThread }) {
var _a;
let { Card, Flex, Text, IconButton, Separator, Code } = window.RadixUI, { TrashIcon, Pencil1Icon, PlusIcon, ChatBubbleIcon } = window.RadixIcons, firstMessage = getThreadContent(thread), handleClick = (e) => {
e.preventDefault(), !isCurrentThread && (onClick == null || onClick(thread.id));
}, handleDelete = (e) => {
e.preventDefault(), !isCurrentThread && (onDelete == null || onDelete(thread.id));
};
return /* @__PURE__ */ React.createElement(
Card,
{
style: {
padding: "12px",
marginBottom: "4px",
minHeight: "120px",
maxHeight: "120px",
maxWidth: "100%",
display: "flex",
flexDirection: "column",
cursor: isCurrentThread ? "not-allowed" : "pointer"
},
disabled: isCurrentThread,
asChild: !0
},
/* @__PURE__ */ React.createElement("a", { href: "#", onClick: handleClick, className: "thread-card" }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "2", style: { flex: 1 } }, /* @__PURE__ */ React.createElement(Flex, { justify: "between", align: "center", style: { marginBottom: "4px" } }, /* @__PURE__ */ React.createElement(
Text,
{
size: "4",
weight: "bold",
trim: "both",
style: { flex: 1, marginRight: "12px" },
color: isCurrentThread ? "green" : !1,
truncate: !0
},
/* @__PURE__ */ React.createElement(ChatBubbleIcon, { style: { marginRight: "4px" } }),
((_a = thread.title) == null ? void 0 : _a.trim()) || "Untitled Thread"
), /* @__PURE__ */ React.createElement(Flex, { gap: "3", align: "center" }, /* @__PURE__ */ React.createElement(Text, { size: "1", color: "gray", style: { display: "flex", alignItems: "center" } }, /* @__PURE__ */ React.createElement(PlusIcon, { width: 14, height: 14, style: { marginRight: "2px" } }), new Date(thread.created).toLocaleDateString(), " ", new Date(thread.created).toLocaleTimeString()), /* @__PURE__ */ React.createElement(Separator, { orientation: "vertical" }), /* @__PURE__ */ React.createElement(Text, { size: "1", color: "gray", style: { display: "flex", alignItems: "center" } }, /* @__PURE__ */ React.createElement(Pencil1Icon, { width: 14, height: 14, style: { marginRight: "2px" } }), new Date(thread.updated).toLocaleDateString(), " ", new Date(thread.updated).toLocaleTimeString()), isCurrentThread ? /* @__PURE__ */ React.createElement(Code, { size: "1", color: "green", variant: "solid" }, "CURRENT") : /* @__PURE__ */ React.createElement(
IconButton,
{
onClick: handleDelete,
variant: "solid",
size: "1",
color: "red"
},
/* @__PURE__ */ React.createElement(TrashIcon, { width: 14, height: 14 })
))), /* @__PURE__ */ React.createElement("p", { style: { margin: 0, color: "#666", fontSize: "14px", whiteSpace: "pre-wrap", overflow: "hidden" } }, firstMessage)))
);
}
var getThreadContent = (thread) => {
if (!thread.messages || thread.messages.length === 0) return "No messages";
let content = "";
for (let message of thread.messages.messages)
content += \`\${message.message.role}: \${message.message.content.map((contentPart) => contentPart.text).join("")}
\`;
return content;
};
// src-copilot/frontend-chat/ChatHistoryOverlay.jsx
function ChatHistoryOverlay() {
let assistantRuntime = AssistantUI.useAssistantRuntime(), [allRemoteThreads, setAllRemoteThreads] = React.useState([]), [searchTerm, setSearchTerm] = React.useState(""), [filteredThreads, setFilteredThreads] = React.useState([]), { setIsChatHistoryOverlayOpen } = React.useContext(getChatAppContext());
React.useEffect(() => {
(async () => {
try {
let allRemoteThreads2 = await appConnector.getAllChatThreadsFromCopilotDB();
setAllRemoteThreads(allRemoteThreads2);
} catch (e) {
console.error(e);
}
})();
}, []), React.useEffect(() => {
(async () => {
if (!searchTerm || searchTerm.trim() === "")
return setFilteredThreads(allRemoteThreads);
let fuse = window.fusejs || (await dynamic_import_esm_default("fuse.js")).default;
window.fusejs = fuse;
let fuseObj = new fuse(allRemoteThreads, { keys: ["messages.messages.message.content.text"], threshold: 0.4 });
setFilteredThreads(fuseObj.search(searchTerm, { limit: 10 }).map((result) => result.item));
})();
}, [allRemoteThreads, searchTerm]);
let handleDeleteThread = async (threadId) => {
await assistantRuntime.threads.getItemById(threadId).delete();
let allRemoteThreads2 = await appConnector.getAllChatThreadsFromCopilotDB();
setAllRemoteThreads(allRemoteThreads2);
}, handleSwitchToThread = async (threadId) => {
await assistantRuntime.threads.switchToThread(threadId), setIsChatHistoryOverlayOpen(!1);
}, { Box, Flex, TextField, IconButton } = window.RadixUI, { MagnifyingGlassIcon, Cross2Icon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("style", null, \`
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.slide-in {
animation: slideIn 0.12s ease-out;
}
\`), /* @__PURE__ */ React.createElement(
Box,
{
className: "slide-in",
style: {
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(39, 47, 53,0.95)",
zIndex: 2e3
}
},
/* @__PURE__ */ React.createElement(Box, { style: {
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column"
} }, /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2", style: {
padding: "16px",
borderBottom: "1px solid #e5e7eb"
} }, /* @__PURE__ */ React.createElement(
IconButton,
{
variant: "soft",
onClick: () => setIsChatHistoryOverlayOpen(!1),
style: { padding: "6px", marginRight: "4px" }
},
/* @__PURE__ */ React.createElement(Cross2Icon, { width: 20, height: 20 })
), /* @__PURE__ */ React.createElement(
TextField.Root,
{
placeholder: "Search chat history...",
variant: "soft",
value: searchTerm,
onChange: (e) => setSearchTerm(e.target.value),
style: {
width: "100%",
padding: "8px 12px",
fontSize: "16px",
flex: 1
},
className: "search-input",
autoFocus: !0
},
/* @__PURE__ */ React.createElement(TextField.Slot, { style: { paddingLeft: "2px" } }, /* @__PURE__ */ React.createElement(MagnifyingGlassIcon, { height: "16", width: "16" })),
searchTerm && /* @__PURE__ */ React.createElement(TextField.Slot, { style: { paddingRight: "0px" } }, /* @__PURE__ */ React.createElement(
Cross2Icon,
{
height: "16",
width: "16",
style: {
cursor: "pointer",
opacity: 0.7
},
onClick: () => setSearchTerm("")
}
))
)), /* @__PURE__ */ React.createElement(Box, { style: {
flex: 1,
overflowY: "auto",
padding: "16px"
} }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "2" }, filteredThreads.map((thread) => /* @__PURE__ */ React.createElement(
ThreadCard,
{
key: thread.remoteId,
thread,
isCurrentThread: thread.remoteId === assistantRuntime.threads.mainItem.getState().remoteId,
onClick: () => handleSwitchToThread(thread.remoteId),
onDelete: () => handleDeleteThread(thread.remoteId)
}
)))))
));
}
// src-copilot/frontend-chat/hooks/useCustomChatHistoryManager.jsx
init_process();
var useCustomChatHistoryManager = () => {
let assistantRuntime = AssistantUI.useAssistantRuntime(), threadRuntime = AssistantUI.useThreadRuntime(), threadListItemRuntime = AssistantUI.useThreadListItemRuntime(), { remoteThreadLoaded, setChatHistoryLoaded } = React.useContext(getChatAppContext()), lastLoadedThreadId = React.useRef(null);
React.useEffect(() => {
if (!remoteThreadLoaded) return;
(async () => {
try {
let lastThread = await appConnector.getLastOpenedChatThreadFromCopilotDB();
lastThread ? await assistantRuntime.threads.switchToThread(lastThread.remoteId) : await assistantRuntime.threads.switchToNewThread();
} catch (e) {
console.error("Error loading initial thread:", e), setChatHistoryLoaded(!0);
}
})();
}, [assistantRuntime, remoteThreadLoaded, setChatHistoryLoaded]), React.useEffect(() => {
let debouncedUpdate = debounce_default(async () => {
try {
let mainThreadId = assistantRuntime.threads.getState().mainThreadId, remoteThread = await appConnector.getChatThreadFromCopilotDB(mainThreadId);
if (!remoteThread) return;
let exportMessages = assistantRuntime.thread.export();
if (exportMessages.messages.length < 1 || isEqual_default(remoteThread.messages, exportMessages))
return;
remoteThread.messages = exportMessages, remoteThread.updated = (/* @__PURE__ */ new Date()).toISOString(), remoteThread.opened = (/* @__PURE__ */ new Date()).toISOString(), await appConnector.saveChatThreadToCopilotDB(remoteThread);
} catch (e) {
console.error("Error persisting thread to backend:", e);
}
}, 1e3, {
leading: !0,
trailing: !0
}), unsubscribe = assistantRuntime.thread.subscribe(debouncedUpdate);
return () => {
debouncedUpdate.cancel(), unsubscribe();
};
}, [assistantRuntime]), React.useEffect(() => {
let loadThreadMessages = async () => {
try {
let threadId = threadListItemRuntime.getState().remoteId;
if (lastLoadedThreadId.current === threadId) return;
lastLoadedThreadId.current = threadId, setChatHistoryLoaded(!1);
let remoteThread = await appConnector.getChatThreadFromCopilotDB(threadId);
threadListItemRuntime.getState().remoteId === threadId && remoteThread && remoteThread.messages ? await threadRuntime.import(remoteThread.messages) : threadListItemRuntime.getState().status === "new" && await threadRuntime.import({ messages: [] }), remoteThread && (remoteThread.opened = (/* @__PURE__ */ new Date()).toISOString(), await appConnector.saveChatThreadToCopilotDB(remoteThread)), threadId && setChatHistoryLoaded(!0);
} catch (e) {
console.error("Error loading thread from backend:", e), setChatHistoryLoaded(!0);
}
}, unsubscribe = threadListItemRuntime.subscribe(loadThreadMessages);
return remoteThreadLoaded && loadThreadMessages(), () => unsubscribe();
}, [threadListItemRuntime, threadRuntime, remoteThreadLoaded, setChatHistoryLoaded]);
};
// src-copilot/frontend-chat/components/CustomEditComposer.jsx
init_process();
var CustomEditComposer = () => {
let textareaRef = React.useRef(null), { toolGroupNames } = React.useContext(getChatAppContext());
return useTributeSetup(textareaRef, toolGroupNames), /* @__PURE__ */ React.createElement(AssistantUI.EditComposer.Root, null, /* @__PURE__ */ React.createElement(AssistantUI.EditComposer.Input, { ref: textareaRef }), /* @__PURE__ */ React.createElement(AssistantUI.EditComposer.Footer, null, /* @__PURE__ */ React.createElement(AssistantUI.EditComposer.Send, null), /* @__PURE__ */ React.createElement(AssistantUI.EditComposer.Cancel, null)));
};
// src-copilot/frontend-chat/tools/CustomToolFallback.jsx
init_process();
var CustomToolFallback = (toolInfoObj) => {
if (toolInfoObj.toolName.startsWith("mcp-")) {
if (toolInfoObj.status.type === "complete") {
let { MixIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
ToolCardResultMessage,
{
text: \`mcp/\${toolInfoObj.toolName} tool call completed successfully.\`,
icon: /* @__PURE__ */ React.createElement(MixIcon, null),
toolName: \`mcp/\${toolInfoObj.toolName}\`,
input: toolInfoObj.args,
disabled: !0
}
);
}
return null;
}
return /* @__PURE__ */ React.createElement(
ToolCardErrorMessage,
{
text: \`Unknown tool: \${toolInfoObj.toolName}\`
}
);
};
// src-copilot/frontend-chat/ChatAppWindow.jsx
var ChatAppWindow = () => {
let assistantAvatar = useAssistantAvatar(), suggestions = useChatSuggestions(), { chatHistoryLoaded, isChatHistoryOverlayOpen, tools, initialAttachmentProcessed } = React.useContext(getChatAppContext());
useModelContext(), useAmplenoteAttachments(), useCustomChatHistoryManager(), useUserDataPolling(), useIntervalPingPlugin();
let { Thread } = window.AssistantUI;
return /* @__PURE__ */ React.createElement("div", { style: { display: "flex", flexDirection: "column" } }, chatHistoryLoaded && initialAttachmentProcessed && isChatHistoryOverlayOpen && /* @__PURE__ */ React.createElement(ChatHistoryOverlay, null), /* @__PURE__ */ React.createElement(ChatAppHeader, null), chatHistoryLoaded && initialAttachmentProcessed && /* @__PURE__ */ React.createElement(
Thread,
{
welcome: {
suggestions
},
assistantMessage: { components: {
Text: AssistantUIMarkdownComponent,
ToolFallback: CustomToolFallback
} },
assistantAvatar,
tools,
components: {
Composer: CustomComposer,
UserMessage,
EditComposer: CustomEditComposer
}
}
));
};
// src-copilot/frontend-chat/components/RemoteAssistantRuntimeProvider.jsx
init_process();
// src-copilot/frontend-chat/hooks/useInnerRuntime.jsx
init_process();
// src-copilot/frontend-chat/hooks/useCustomDangerousInBrowserRuntime.jsx
init_process();
var useCustomDangerousInBrowserRuntime = (options) => {
let { localRuntimeOptions, otherOptions } = AssistantUIUtils.splitLocalRuntimeOptions(options), [adapter] = React.useState(() => {
let adapter2 = new AssistantUIUtils.DangerousInBrowserAdapter(otherOptions), originalRun = adapter2.run;
return adapter2.run = async function* (...args) {
var _a;
try {
for await (let chunk of originalRun.call(this, ...args))
yield chunk;
} catch (e) {
throw e.name !== "AbortError" && (console.error(e), (_a = options.onError) == null || _a.call(options, e), yield {
content: [{ type: "text", text: "Error Occurred." }],
status: { type: "running" }
}), e;
}
}, adapter2;
});
return AssistantUI.useLocalRuntime(adapter, localRuntimeOptions);
};
// src-copilot/frontend-chat/components/AmplenoteAttachmentAdapter.jsx
init_process();
var AmplenoteAttachmentAdapter = class {
constructor() {
__publicField(this, "accept", "text/amplenote-note,text/amplenote-selection,text/amplenote-task");
}
async add(state) {
return {
id: state.file.name,
type: "file",
name: state.file.name,
contentType: state.file.type,
file: state.file,
status: { type: "requires-action", reason: "composer-send" }
};
}
async send(attachment) {
let contentText = await getFileText(attachment.file);
return {
...attachment,
status: { type: "complete" },
content: [
{
type: "text",
text: contentText
}
]
};
}
async remove() {
}
}, getFileText = (file) => new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result), reader.onerror = (error) => reject(error), reader.readAsText(file);
});
// src-copilot/frontend-chat/components/SimplePdfAttachmentAdapter.jsx
init_process();
var SimplePdfAttachmentAdapter = class {
constructor() {
__publicField(this, "accept", "application/pdf");
}
async add(state) {
return {
id: state.file.name,
type: "file",
name: state.file.name,
contentType: state.file.type,
file: state.file,
status: { type: "requires-action", reason: "composer-send" }
};
}
async send(attachment) {
return {
...attachment,
status: { type: "complete" },
content: [
{
type: "file",
data: await getFileDataURL(attachment.file),
mimeType: attachment.contentType
}
]
};
}
async remove() {
}
}, getFileDataURL = (file) => new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result), reader.onerror = (error) => reject(error), reader.readAsDataURL(file);
});
// src-copilot/frontend-chat/hooks/useInnerRuntime.jsx
var useInnerRuntime = () => useCustomDangerousInBrowserRuntime({
model: window.LLM_MODEL,
maxSteps: 8,
...appSettings[LLM_MAX_TOKENS_SETTING] && String(appSettings[LLM_MAX_TOKENS_SETTING]).trim() !== "" && Number(appSettings[LLM_MAX_TOKENS_SETTING]) !== 0 && !isNaN(Number(appSettings[LLM_MAX_TOKENS_SETTING])) && {
maxTokens: Number(appSettings[LLM_MAX_TOKENS_SETTING])
},
adapters: {
attachments: new AssistantUI.CompositeAttachmentAdapter([
new AssistantUI.SimpleImageAttachmentAdapter(),
new AssistantUI.SimpleTextAttachmentAdapter(),
new SimplePdfAttachmentAdapter(),
new AmplenoteAttachmentAdapter()
])
},
onFinish: async (result) => {
window.dispatchEvent(new CustomEvent("onLLMCallFinish", { detail: result })), console.log("onLLMCallFinish", result);
},
onError: async (error) => {
appConnector.alert(\`Error: \${errorToString(error)}\`);
}
});
// src-copilot/frontend-chat/components/RemoteAssistantRuntimeProvider.jsx
var RemoteAssistantRuntimeProvider = ({ children }) => {
let innerRuntimeHook = React.useCallback(useInnerRuntime, []), callbacksRef = React.useRef(/* @__PURE__ */ new Set()), { remoteThreadLoaded, setRemoteThreadLoaded } = React.useContext(getChatAppContext()), runtime = AssistantUI.unstable_useRemoteThreadListRuntime({
runtimeHook: innerRuntimeHook,
list: async () => {
let remoteThreads = await appConnector.getAllChatThreadsFromCopilotDB();
return setRemoteThreadLoaded(!0), {
threads: remoteThreads
};
},
delete: async (threadId) => {
await appConnector.deleteChatThreadFromCopilotDB(threadId);
},
// TODO: Implement rename, archive, unarchive
subscribe: (handler) => (callbacksRef.current.add(handler), () => callbacksRef.current.delete(handler)),
initialize: async (threadId) => {
if (await appConnector.getChatThreadFromCopilotDB(threadId))
throw "Thread already exists in remote storage. Cannot initialize as new thread.";
let thread = {
id: threadId,
remoteId: threadId,
name: \`Copilot Chat - \${threadId}\`,
created: (/* @__PURE__ */ new Date()).toISOString(),
updated: (/* @__PURE__ */ new Date()).toISOString(),
opened: (/* @__PURE__ */ new Date()).toISOString(),
status: "regular"
};
return remoteThreadLoaded && await appConnector.saveChatThreadToCopilotDB(thread), thread;
}
}), { AssistantRuntimeProvider } = window.AssistantUI;
return /* @__PURE__ */ React.createElement(AssistantRuntimeProvider, { runtime }, children);
};
// src-copilot/frontend-chat/ChatApp.jsx
var ChatApp = () => {
let { Theme } = window.RadixUI;
return /* @__PURE__ */ React.createElement(ChatAppContextProvider, null, /* @__PURE__ */ React.createElement(Theme, { appearance: "dark", accentColor: "blue" }, /* @__PURE__ */ React.createElement(RemoteAssistantRuntimeProvider, null, /* @__PURE__ */ React.createElement(ChatAppWindow, null))));
};
// src-copilot/embed/chat.jsx
window.appConnector = new Proxy({}, {
get: function(target, prop, receiver) {
return prop in target ? target[prop] : async function(...args) {
return ["getUserCurrentNoteData", "getUserDailyJotNote", "receiveMessageFromPlugin", "ping"].includes(prop) || window.dispatchEvent(new CustomEvent("callAmplenotePlugin", { detail: [prop, ...args] })), await window.callAmplenotePlugin(prop, ...args);
};
}
});
window.appSettings = window.appSettings || {};
window.userData = window.userData || {};
var body = document.body, html = document.documentElement;
window.addEventListener("resize", function() {
let iframeHeight = Math.min(html.clientHeight, html.scrollHeight);
Object.assign(body.style, {
margin: "0"
});
let appInnerContainer = document.querySelector(".app-container > div > div");
appInnerContainer && Object.assign(appInnerContainer.style, {
height: \`\${iframeHeight}px\`,
overflow: "hidden"
});
});
setInterval(() => window.dispatchEvent(new Event("resize")), 100);
(async () => {
try {
showEmbedLoader(), overwriteWithAmplenoteStyle();
let cssLoaded = Promise.all([
dynamicImportCSS("@assistant-ui/react/dist/styles/index.css"),
dynamicImportCSS("@radix-ui/themes/styles.css"),
dynamicImportCSS("@assistant-ui/react-markdown/dist/styles/markdown.css")
]), [
React2,
ReactDOM,
AssistantUI2,
RadixUI,
AssistantUIMarkdown2,
RadixIcons,
StringDiffModule,
dayjs,
tributejs,
ReactErrorBoundary,
AssistantUIUtils2
] = await dynamicImportExternalPluginBundle("assistantUIBundle.js");
if (window.AssistantUIMarkdown = AssistantUIMarkdown2, window.AssistantUIMarkdownComponent = await makeCustomMarkdownText(), window.React = React2, window.ReactDOM = ReactDOM, window.AssistantUI = AssistantUI2, window.RadixUI = RadixUI, window.AssistantUIUtils = AssistantUIUtils2, window.RadixIcons = RadixIcons, window.StringDiff = StringDiffModule.StringDiff, window.dayjs = dayjs.default, window.Tribute = tributejs.default, window.ReactErrorBoundary = ReactErrorBoundary, console.log("Loaded ReactErrorBoundary", ReactErrorBoundary), await parse(""), window.appSettings = await appConnector.getSettings(), window.LLM_MODEL = await getLLMModel(window.appSettings), hideEmbedLoader(), !React2 || !window.ReactDOM)
throw new Error("Failed to load React or ReactDOM");
document.querySelector(".app-container") && window.ReactDOM.createRoot(document.querySelector(".app-container")).render(/* @__PURE__ */ React2.createElement(ChatApp, null));
} catch (e) {
window.document.body.innerHTML = '<div class="error" style="color: red; font-size: 20px; padding: 20px;">Error during init: ' + e.message + "</div>", console.error(e);
} finally {
await new Promise((resolve) => setTimeout(resolve, 1600)), window.dispatchEvent(new CustomEvent("appLoaded"));
}
})();
return plugin;
})()
<\/script>
</body>
</html>`;
var search_default = `<html lang="en">
<head>
<title>Copilot Search</title>
<link rel="icon" href="data:,">
<link href="https://cdn.jsdelivr.net/npm/@radix-ui/themes@3.1.6/styles.min.css" rel="stylesheet">
</head>
<body>
<div class="app-container"></div>
<script>(() => {
// src-copilot/constants.js
var LLM_MAX_TOKENS_SETTING = "LLM Max Tokens (Optional)";
// src-copilot/frontend-chat/overwriteWithAmplenoteStyle.js
var overwriteWithAmplenoteStyle = () => {
let body2 = document.body, styleEl = document.createElement("style");
styleEl.innerText = \`
.dark, .dark-theme, :is(.dark, .dark-theme) :where(.radix-themes:not(.light, .light-theme)) {
--color-background: #272f35;
}
.dark, .dark-theme {
--gray-1: #292f33;
--gray-2: #2f3539;
--gray-3: #343c43;
--gray-4: #36414b;
--gray-5: #3a4651;
--gray-6: #3e4d5a;
--gray-7: #455968;
--gray-8: #577084;
--gray-9: #617b8f;
--gray-10: #6d8599;
--gray-11: #a7bac9;
--gray-12: #eaeff3;
--gray-a1: #d12f0003;
--gray-a2: #f4c99b0a;
--gray-a3: #e0e8fc12;
--gray-a4: #b0d3fe1c;
--gray-a5: #aed2fb24;
--gray-a6: #a4d2fe2f;
--gray-a7: #9dd4fe41;
--gray-a8: #a1d4ff64;
--gray-a9: #a8d9ff72;
--gray-a10: #b3dbfd7f;
--gray-a11: #d6ecffbb;
--gray-a12: #f7fbfff0;
--gray-contrast: #FFFFFF;
--gray-surface: rgba(0, 0, 0, 0.05);
--gray-indicator: #617b8f;
--gray-track: #617b8f;
}
@supports (color: color(display-p3 1 1 1)) {
@media (color-gamut: p3) {
.dark, .dark-theme {
--gray-1: oklch(30% 0.0115 242.8);
--gray-2: oklch(32.3% 0.0119 242.8);
--gray-3: oklch(35.3% 0.0166 242.8);
--gray-4: oklch(37.1% 0.0213 242.8);
--gray-5: oklch(38.8% 0.024 242.8);
--gray-6: oklch(41.2% 0.0288 242.8);
--gray-7: oklch(45.3% 0.035 242.8);
--gray-8: oklch(53.4% 0.0433 242.8);
--gray-9: oklch(57% 0.0433 242.8);
--gray-10: oklch(60.5% 0.0412 242.8);
--gray-11: oklch(77.9% 0.0302 242.8);
--gray-12: oklch(94.9% 0.0081 242.8);
--gray-a1: color(display-p3 0.9451 0.1843 0 / 0.005);
--gray-a2: color(display-p3 0.9961 0.898 0.8 / 0.033);
--gray-a3: color(display-p3 0.902 0.9255 1 / 0.069);
--gray-a4: color(display-p3 0.698 0.8353 0.9961 / 0.109);
--gray-a5: color(display-p3 0.702 0.8353 1 / 0.138);
--gray-a6: color(display-p3 0.6784 0.8275 1 / 0.183);
--gray-a7: color(display-p3 0.6588 0.8235 1 / 0.252);
--gray-a8: color(display-p3 0.6824 0.8392 1 / 0.385);
--gray-a9: color(display-p3 0.7059 0.8549 1 / 0.439);
--gray-a10: color(display-p3 0.749 0.8706 1 / 0.488);
--gray-a11: color(display-p3 0.8667 0.9294 1 / 0.725);
--gray-a12: color(display-p3 0.9725 0.9843 1 / 0.941);
--gray-contrast: #FFFFFF;
--gray-surface: color(display-p3 0 0 0 / 5%);
--gray-indicator: oklch(57% 0.0433 242.8);
--gray-track: oklch(57% 0.0433 242.8);
}
}
}
.dark, .dark-theme {
--accent-1: #252f3c;
--accent-2: #253141;
--accent-3: #223e64;
--accent-4: #1a467f;
--accent-5: #1e508f;
--accent-6: #275b9e;
--accent-7: #2e68b2;
--accent-8: #3277cf;
--accent-9: #0080ff;
--accent-10: #3378d0;
--accent-11: #7cbaff;
--accent-12: #cbe3ff;
--accent-a1: #002ffc09;
--accent-a2: #084ff510;
--accent-a3: #126ffc3c;
--accent-a4: #046dfe5e;
--accent-a5: #1379ff72;
--accent-a6: #2784ff85;
--accent-a7: #328bff9e;
--accent-a8: #368dffc3;
--accent-a9: #0080ff;
--accent-a10: #378effc4;
--accent-a11: #7cbaff;
--accent-a12: #cbe3ff;
--accent-contrast: #fff;
--accent-surface: #24334d80;
--accent-indicator: #0080ff;
--accent-track: #0080ff;
}
@supports (color: color(display-p3 1 1 1)) {
@media (color-gamut: p3) {
.dark, .dark-theme {
--accent-1: oklch(30% 0.0278 256.1);
--accent-2: oklch(31% 0.0325 256.1);
--accent-3: oklch(36.2% 0.074 256.1);
--accent-4: oklch(39.6% 0.1073 256.1);
--accent-5: oklch(43.2% 0.1173 256.1);
--accent-6: oklch(47.1% 0.1224 256.1);
--accent-7: oklch(51.7% 0.1323 256.1);
--accent-8: oklch(57% 0.1522 256.1);
--accent-9: oklch(61.5% 0.2108 256.1);
--accent-10: oklch(57.3% 0.1522 256.1);
--accent-11: oklch(78% 0.1427 256.1);
--accent-12: oklch(90.8% 0.0525 256.1);
--accent-a1: color(display-p3 0 0.1882 0.9882 / 0.035);
--accent-a2: color(display-p3 0.0314 0.3176 0.9922 / 0.06);
--accent-a3: color(display-p3 0.1608 0.4314 1 / 0.222);
--accent-a4: color(display-p3 0.1294 0.4275 1 / 0.35);
--accent-a5: color(display-p3 0.1882 0.4824 1 / 0.424);
--accent-a6: color(display-p3 0.2549 0.5216 1 / 0.498);
--accent-a7: color(display-p3 0.2902 0.5529 1 / 0.597);
--accent-a8: color(display-p3 0.3098 0.5569 1 / 0.734);
--accent-a9: color(display-p3 0.2157 0.5059 1 / 0.961);
--accent-a10: color(display-p3 0.3137 0.5647 1 / 0.739);
--accent-a11: color(display-p3 0.5529 0.7373 0.9961 / 0.971);
--accent-a12: color(display-p3 0.8235 0.8941 1 / 0.986);
--accent-contrast: #fff;
--accent-surface: color(display-p3 0.1529 0.1961 0.2902 / 0.5);
--accent-indicator: oklch(61.5% 0.2108 256.1);
--accent-track: oklch(61.5% 0.2108 256.1);
}
}
}\`.replace(/\\s+/g, " ").trim(), styleEl.innerText += \`
.app-container .radix-themes {
--default-font-size: 14px;
}
\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl);
let styleEl2 = document.createElement("style");
styleEl2.innerText = \`
.dark {
--aui-background: 210, 10%, 18%;
--aui-foreground: 210, 10%, 94%;
--aui-card: 210, 10%, 20%;
--aui-card-foreground: 210, 10%, 94%;
--aui-popover: 210, 10%, 22%;
--aui-popover-foreground: 210, 10%, 94%;
--aui-border: 210, 10%, 50%;
--aui-input: 210, 10%, 50%;
--aui-ring: 210, 10%, 18%;
--aui-primary: 205 80% 50%;
--aui-primary-foreground: 0, 0%, 100%;
--aui-secondary: 205, 10%, 94%;
--aui-secondary-foreground: 205, 10%, 18%;
--aui-muted-foreground: 205, 10%, 50%;
--aui-accent: 205, 100%, 50%;
--aui-accent-foreground: 0, 0%, 100%;
--aui-destructive: 0, 84%, 60%;
--aui-destructive-foreground: 0, 0%, 98%;
--aui-radius: 0.3rem;
}\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl2);
let styleEl3 = document.createElement("style");
styleEl3.innerText = \`
.tool_group_mention {
background-color: var(--accent-a3);
border-radius: var(--aui-radius);
}
div.aui-user-message-content {
border-radius: 1.25rem;
}
.aui-composer-root, .aui-thread-welcome-suggestion {
background-color: rgb(39, 47, 53);
}
.aui-composer-cancel {
background-color: hsl(var(--aui-destructive));
color: hsl(var(--aui-destructive-foreground));
}
.aui-composer-cancel:hover,
.aui-composer-cancel:focus,
.aui-composer-cancel:active {
background-color: hsla(var(--aui-destructive), 0.9);
}
.aui-composer-cancel:disabled {
background-color: hsla(var(--aui-destructive), 0.5);
color: hsla(var(--aui-destructive-foreground), 0.5);
cursor: not-allowed;
}
.aui-composer-root {
padding-left: 0.325rem;
padding-right: 0.325rem;
}
\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl3);
};
// common-utils/embed-ui.js
function showEmbedLoader() {
window.LoadingStartTime = performance.now();
let overlay = document.createElement("div");
overlay.id = "embed-loader-overlay", overlay.style.cssText = \`
position: fixed;
top: 0;
left: 0;
width: 100%;
/*height: 100%;*/
background-color: rgba(0, 0, 0, 0.5);
z-index: 9998;
animation: fadeIn 0.3s ease-in-out;
\`;
let loader = document.createElement("div");
loader.id = "embed-loader", loader.style.cssText = \`
position: fixed;
left: 50%;
transform: translate(-50%, 0%);
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
z-index: 9999;
\`;
let keyframes = document.createElement("style");
keyframes.textContent = \`
@keyframes spin {
0% { transform: translate(-50%, -50%) rotate(0deg); }
100% { transform: translate(-50%, -50%) rotate(360deg); }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
\`, document.head.appendChild(keyframes), document.body.appendChild(overlay), document.body.appendChild(loader), overlay.style.display = "none", loader.style.display = "none", setTimeout(() => {
document.getElementById("embed-loader") && (loader.style.display = "block"), document.getElementById("embed-loader-overlay") && (overlay.style.display = "block");
}, 240);
}
function hideEmbedLoader() {
window.LoadingEndTime = performance.now(), console.log("Loading time:", window.LoadingEndTime - window.LoadingStartTime);
let loader = document.getElementById("embed-loader"), overlay = document.getElementById("embed-loader-overlay");
loader && loader.remove(), overlay && overlay.remove();
}
// package.json
var package_default = {
name: "amplenote-plugin-dev-env",
author: "debajandhar12",
version: "1.0.0",
type: "module",
repository: "https://github.com/debanjandhar12/my-amplenote-plugins-v2",
dependencies: {
"@ai-sdk/anthropic": "1.2.10",
"@ai-sdk/fireworks": "0.2.13",
"@ai-sdk/google": "1.2.14",
"@ai-sdk/groq": "1.2.8",
"@ai-sdk/openai": "1.3.21",
"@assistant-ui/react": "0.7.65",
"@assistant-ui/react-markdown": "0.7.16",
"@debanjandhar12/markmap-lib": "0.17.0-mod.3",
"@debanjandhar12/markmap-toolbar": "0.17.0-mod.3",
"@debanjandhar12/markmap-view": "0.17.0-mod.3",
"@duckdb/duckdb-wasm": "1.31.0",
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@huggingface/transformers": "3.7.3",
"@omnivore-app/api": "^1.0.4",
"@pinecone-database/pinecone": "4.1.0",
"@radix-ui/react-icons": "1.3.2",
"@radix-ui/themes": "3.2.0",
"@yiuayiu/telegram-markdown-escape": "^0.0.2-1",
ai: "4.3.13",
"apache-arrow": "^20.0.0",
"async-mutex": "0.5.0",
"chart.js": "^4.4.3",
"d3-svg-to-png": "^0.3.1",
"date-fns": "^3.6.0",
dayjs: "1.11.13",
"easy-web-worker": "7.0.2",
"emoji-mart": "^5.6.0",
"fast-dotproduct": "1.3.0",
fflate: "0.8.2",
fparser: "^3.1.0",
"fuse.js": "7.0.0",
idb: "8.0.2",
"iconv-lite": "^0.6.3",
"lodash-es": "^4.17.21",
luxon: "^3.4.4",
"markdown-it": "^14.1.0",
"mdast-util-to-string": "4.0.0",
"my-ample-plugin-external": "1.0.29",
nanoid: "^5.0.7",
"ollama-ai-provider": "1.2.0",
"parquetjs-lite": "^0.8.7",
react: "18.2.0",
"react-dom": "18.2.0",
"react-error-boundary": "5.0.0",
"react-string-diff": "0.2.0",
"react-virtuoso": "4.12.5",
"react-window": "1.8.11",
"remark-frontmatter": "5.0.0",
"remark-gfm": "4.0.0",
"remark-parse": "11.0.0",
"scheduler-polyfill": "1.3.0",
stopword: "3.1.5",
tributejs: "5.1.3",
unified: "11.0.0",
"unist-util-visit": "5.0.0",
"unist-util-visit-parents": "6.0.1",
"vosk-browser": "0.0.8",
zod: "3.23.8"
},
devDependencies: {
"@huggingface/transformers": "3.2.4",
"@playwright/test": "^1.49.1",
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^29.5.0",
"core-js": "^3.38.1",
cors: "^2.8.5",
"cross-fetch": "^4.0.0",
dotenv: "^16.0.3",
esbuild: "0.25.3",
"esbuild-jest2": "0.6.7",
"esbuild-plugin-external-global": "^1.0.1",
"esbuild-plugins-node-modules-polyfill": "1.7.0",
express: "^5.0.1",
"isomorphic-fetch": "^3.0.0",
jest: "^29.5.0",
jsdom: "^24.1.0",
"make-synchronous": "^1.0.0",
"node-fetch": "4.0.0-beta.4",
"p-retry": "6.2.1",
playwright: "^1.49.1",
sinon: "21.0.0",
"jest-allure2-reporter": "2.2.6",
"allure-commandline": "^2.32.0",
open: "^10.2.0"
},
scripts: {
test: "jest --testPathPattern=src-copilot",
"test:watch": "jest --testPathPattern=src-copilot --watch",
"allure:serve": \`npx allure generate --single-file ./allure/results --clean -o ./allure/report && node --input-type=module -e "import('open').then(o => o.default('./allure/report/index.html'))"\`,
"build:prod": "NODE_ENV=production node esbuild.js $(pwd)/src-copilot",
"build:dev": "node esbuild.js $(pwd)/src-copilot --watch --server"
}
};
// common-utils/dynamic-import-esm.js
var dynamicImportExternalPluginBundle = async (fileName) => {
let packageVersion = package_default.dependencies["my-ample-plugin-external"], pkg = \`my-ample-plugin-external/dist/\${fileName}\`, cdnList = getCDNList(pkg), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, packageVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 1e3)), abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return import(url).then((module) => {
if (abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return { module, url };
}).catch((e) => {
throw console.warn(\`Failed to import \${pkg} from \${cdn}: \${e.message}\`), e;
});
});
try {
let result = await Promise.any(importPromises);
abortController.abort();
let module = result.module;
if (!module.versions)
throw new Error(\`Failed to import module: \${fileName}. Returned bundle does not have version property.\`);
for (let [key, value] of Object.entries(module.versions))
if (value !== package_default.dependencies[key])
throw new Error(\`Failed to import module: \${fileName}. Version mismatch for \${key} (expected: \${package_default.dependencies[key]}, actual: \${value})\`);
return console.log(\`Imported \${pkg}@\${packageVersion} from \${result.url}\`), module.default;
} catch {
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
}
};
function getBasePackage(pkg) {
if (pkg.startsWith("@")) {
let [scope, name] = pkg.split("/");
return \`\${scope}/\${name}\`;
}
return pkg.split("/")[0];
}
function resolvePackageVersion(pkg, pkgVersion) {
let basePkg = getBasePackage(pkg), version = pkgVersion || package_default.dependencies[basePkg] || package_default.devDependencies[basePkg] || "latest";
return version.startsWith("^") || version.startsWith("~") ? version.substring(1) : version;
}
function getPackageFolderString(pkg) {
let folders = [];
return pkg.startsWith("@") ? [, , ...folders] = pkg.split("/") : [, ...folders] = pkg.split("/"), folders && folders.length > 0 ? \`/\${folders.join("/")}\` : "";
}
function getCDNList(pkg) {
let basePkg = getBasePackage(pkg);
return basePkg.includes("react") || basePkg.includes("radix") || basePkg.includes("build") || basePkg.includes("dotenv") ? ["https://esm.sh/", "https://legacy.esm.sh/"] : ["https://cdn.jsdelivr.net/npm/", "https://esm.sh/", "https://unpkg.com/"];
}
function buildCDNUrl(cdn, pkg, version) {
let basePkg = getBasePackage(pkg), versionString = version !== "latest" ? \`@\${version}\` : "", folderString = getPackageFolderString(pkg), url = new URL(\`\${cdn}\${basePkg}\${versionString}\${folderString}\`);
if (cdn !== "https://esm.sh/" && (basePkg.includes("react") || basePkg.includes("radix")) && !pkg.endsWith(".css"))
throw new Error(\`React based js packages is not supported in \${cdn}\`);
if (cdn !== "https://legacy.esm.sh/" && basePkg.includes("build"))
throw new Error(\`Build API package is not supported in \${cdn}\`);
cdn === "https://esm.sh/" && (basePkg !== "react-dom" && basePkg !== "react" && url.searchParams.set("bundle-deps", !1), !pkg.endsWith(".css") && pkg !== "build" && url.searchParams.set("deps", \`react@\${package_default.dependencies.react},react-dom@\${package_default.dependencies["react-dom"]}\`));
let urlString = url.toString();
return cdn === "https://cdn.jsdelivr.net/npm/" && !pkg.endsWith(".css") && (urlString += "/+esm"), urlString;
}
var dynamicImportCSS = async (pkg, pkgVersion = null) => {
let resolvedVersion = resolvePackageVersion(pkg, pkgVersion), url = buildCDNUrl("https://cdn.jsdelivr.net/npm/", pkg, resolvedVersion), link = document.createElement("link");
return link.rel = "stylesheet", link.href = url, document.head.appendChild(link), new Promise((resolve) => link.onload = resolve);
};
// src-copilot/frontend-search/components/EndlessScroll.jsx
var EndlessScroll = ({ data, iterationCnt, itemContent }) => {
let { ScrollArea, Flex, Spinner } = window.RadixUI, { Virtuoso } = window.ReactVirtuoso, [currentMultiplier, setCurrentMultiplier] = React.useState(1);
return console.log(data, data.slice(0, iterationCnt * currentMultiplier), currentMultiplier), /* @__PURE__ */ React.createElement(ScrollArea, null, /* @__PURE__ */ React.createElement(
Virtuoso,
{
data: data.slice(0, iterationCnt * currentMultiplier),
useWindowScroll: !0,
itemContent,
endReached: () => {
setTimeout(() => {
data.length > iterationCnt * currentMultiplier && setCurrentMultiplier(currentMultiplier + 1);
}, 1e3);
},
components: {
Footer: () => data.length > iterationCnt * currentMultiplier && /* @__PURE__ */ React.createElement(Flex, { direction: "column", align: "center", justify: "center" }, /* @__PURE__ */ React.createElement(Spinner, { size: "3" }))
},
style: { height: "100%" }
}
));
};
// node_modules/lodash-es/_freeGlobal.js
var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis, freeGlobal_default = freeGlobal;
// node_modules/lodash-es/_root.js
var freeSelf = typeof self == "object" && self && self.Object === Object && self, root = freeGlobal_default || freeSelf || Function("return this")(), root_default = root;
// node_modules/lodash-es/_Symbol.js
var Symbol2 = root_default.Symbol, Symbol_default = Symbol2;
// node_modules/lodash-es/_getRawTag.js
var objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, nativeObjectToString = objectProto.toString, symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = !0;
} catch {
}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
}
var getRawTag_default = getRawTag;
// node_modules/lodash-es/_objectToString.js
var objectProto2 = Object.prototype, nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;
// node_modules/lodash-es/_baseGetTag.js
var nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
return value == null ? value === void 0 ? undefinedTag : nullTag : symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;
// node_modules/lodash-es/isObjectLike.js
function isObjectLike(value) {
return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;
// node_modules/lodash-es/isSymbol.js
var symbolTag = "[object Symbol]";
function isSymbol(value) {
return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
}
var isSymbol_default = isSymbol;
// node_modules/lodash-es/_trimmedEndIndex.js
var reWhitespace = /\\s/;
function trimmedEndIndex(string) {
for (var index = string.length; index-- && reWhitespace.test(string.charAt(index)); )
;
return index;
}
var trimmedEndIndex_default = trimmedEndIndex;
// node_modules/lodash-es/_baseTrim.js
var reTrimStart = /^\\s+/;
function baseTrim(string) {
return string && string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "");
}
var baseTrim_default = baseTrim;
// node_modules/lodash-es/isObject.js
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;
// node_modules/lodash-es/toNumber.js
var NAN = NaN, reIsBadHex = /^[-+]0x[0-9a-f]+$/i, reIsBinary = /^0b[01]+$/i, reIsOctal = /^0o[0-7]+$/i, freeParseInt = parseInt;
function toNumber(value) {
if (typeof value == "number")
return value;
if (isSymbol_default(value))
return NAN;
if (isObject_default(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject_default(other) ? other + "" : other;
}
if (typeof value != "string")
return value === 0 ? value : +value;
value = baseTrim_default(value);
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_default = toNumber;
// node_modules/lodash-es/now.js
var now = function() {
return root_default.Date.now();
}, now_default = now;
// node_modules/lodash-es/debounce.js
var FUNC_ERROR_TEXT = "Expected a function", nativeMax = Math.max, nativeMin = Math.min;
function debounce(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = !1, maxing = !1, trailing = !0;
if (typeof func != "function")
throw new TypeError(FUNC_ERROR_TEXT);
wait = toNumber_default(wait) || 0, isObject_default(options) && (leading = !!options.leading, maxing = "maxWait" in options, maxWait = maxing ? nativeMax(toNumber_default(options.maxWait) || 0, wait) : maxWait, trailing = "trailing" in options ? !!options.trailing : trailing);
function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
return lastArgs = lastThis = void 0, lastInvokeTime = time, result = func.apply(thisArg, args), result;
}
function leadingEdge(time) {
return lastInvokeTime = time, timerId = setTimeout(timerExpired, wait), leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = now_default();
if (shouldInvoke(time))
return trailingEdge(time);
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
return timerId = void 0, trailing && lastArgs ? invokeFunc(time) : (lastArgs = lastThis = void 0, result);
}
function cancel() {
timerId !== void 0 && clearTimeout(timerId), lastInvokeTime = 0, lastArgs = lastCallTime = lastThis = timerId = void 0;
}
function flush() {
return timerId === void 0 ? result : trailingEdge(now_default());
}
function debounced() {
var time = now_default(), isInvoking = shouldInvoke(time);
if (lastArgs = arguments, lastThis = this, lastCallTime = time, isInvoking) {
if (timerId === void 0)
return leadingEdge(lastCallTime);
if (maxing)
return clearTimeout(timerId), timerId = setTimeout(timerExpired, wait), invokeFunc(lastCallTime);
}
return timerId === void 0 && (timerId = setTimeout(timerExpired, wait)), result;
}
return debounced.cancel = cancel, debounced.flush = flush, debounced;
}
var debounce_default = debounce;
// src-copilot/frontend-search/components/NoteCard.jsx
var NoteCard = ({ title, actualNoteContentPart, noteUUID, headingAnchor }) => {
let { Card, Flex, Text } = window.RadixUI, { FileTextIcon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(
Card,
{
style: { padding: "12px", marginBottom: "4px", minHeight: "120px", maxHeight: "160px", maxWidth: "100%" },
asChild: !0
},
/* @__PURE__ */ React.createElement("a", { href: "#", onClick: (e) => {
e.preventDefault(), window.appConnector.navigate(\`https://www.amplenote.com/notes/\${noteUUID}\` + (headingAnchor ? \`#\${encodeURIComponent(headingAnchor)}\` : ""));
}, className: "note-card" }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "2" }, /* @__PURE__ */ React.createElement(Text, { size: "4", weight: "bold", trim: "both", style: { marginBottom: "4px" }, truncate: !0 }, /* @__PURE__ */ React.createElement(FileTextIcon, { style: { marginRight: "4px" } }), (title == null ? void 0 : title.trim()) || "Untitled Note"), /* @__PURE__ */ React.createElement("p", { style: { margin: 0, color: "#666", fontSize: "14px", whiteSpace: "pre-wrap" } }, actualNoteContentPart)))
);
};
// src-copilot/markdown/markdown-parser.js
var remarkGfm, unified, remarkFrontmatter, remarkParse, pipe, pipeWithYaml;
async function parse(markdownText, { yaml = !1 } = {}) {
return (!remarkGfm || !unified || !remarkFrontmatter || !remarkParse) && ([remarkGfm, unified, remarkFrontmatter, remarkParse] = await dynamicImportExternalPluginBundle("remarkBundle.js"), unified = unified.unified, remarkGfm = remarkGfm.default, remarkFrontmatter = remarkFrontmatter.default, remarkParse = remarkParse.default), !pipe && !yaml && (pipe = unified().use(remarkParse).use(remarkGfm)), !pipeWithYaml && yaml && (pipeWithYaml = unified().use(remarkParse).use(remarkGfm).use(remarkFrontmatter, ["yaml"])), await (yaml ? pipeWithYaml : pipe).parse(markdownText);
}
// node_modules/unist-util-is/lib/index.js
var convert = (
// Note: overloads in JSDoc can\u2019t yet use different \`@template\`s.
/**
* @type {(
* (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &
* (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &
* (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &
* ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &
* ((test?: Test) => Check)
* )}
*/
/**
* @param {Test} [test]
* @returns {Check}
*/
function(test) {
if (test == null)
return ok;
if (typeof test == "function")
return castFactory(test);
if (typeof test == "object")
return Array.isArray(test) ? anyFactory(test) : propsFactory(test);
if (typeof test == "string")
return typeFactory(test);
throw new Error("Expected function, string, or object as test");
}
);
function anyFactory(tests) {
let checks = [], index = -1;
for (; ++index < tests.length; )
checks[index] = convert(tests[index]);
return castFactory(any);
function any(...parameters) {
let index2 = -1;
for (; ++index2 < checks.length; )
if (checks[index2].apply(this, parameters)) return !0;
return !1;
}
}
function propsFactory(check) {
let checkAsRecord = (
/** @type {Record<string, unknown>} */
check
);
return castFactory(all2);
function all2(node2) {
let nodeAsRecord = (
/** @type {Record<string, unknown>} */
/** @type {unknown} */
node2
), key;
for (key in check)
if (nodeAsRecord[key] !== checkAsRecord[key]) return !1;
return !0;
}
}
function typeFactory(check) {
return castFactory(type);
function type(node2) {
return node2 && node2.type === check;
}
}
function castFactory(testFunction) {
return check;
function check(value, index, parent) {
return !!(looksLikeANode(value) && testFunction.call(
this,
value,
typeof index == "number" ? index : void 0,
parent || void 0
));
}
}
function ok() {
return !0;
}
function looksLikeANode(value) {
return value !== null && typeof value == "object" && "type" in value;
}
// node_modules/unist-util-visit-parents/lib/index.js
var empty = [], CONTINUE = !0, EXIT = !1, SKIP = "skip";
function visitParents(tree, test, visitor, reverse) {
let check;
typeof test == "function" && typeof visitor != "function" ? (reverse = visitor, visitor = test) : check = test;
let is2 = convert(check), step = reverse ? -1 : 1;
factory(tree, void 0, [])();
function factory(node2, index, parents) {
let value = (
/** @type {Record<string, unknown>} */
node2 && typeof node2 == "object" ? node2 : {}
);
if (typeof value.type == "string") {
let name = (
// \`hast\`
typeof value.tagName == "string" ? value.tagName : (
// \`xast\`
typeof value.name == "string" ? value.name : void 0
)
);
Object.defineProperty(visit2, "name", {
value: "node (" + (node2.type + (name ? "<" + name + ">" : "")) + ")"
});
}
return visit2;
function visit2() {
let result = empty, subresult, offset, grandparents;
if ((!test || is2(node2, index, parents[parents.length - 1] || void 0)) && (result = toResult(visitor(node2, parents)), result[0] === EXIT))
return result;
if ("children" in node2 && node2.children) {
let nodeAsParent = (
/** @type {UnistParent} */
node2
);
if (nodeAsParent.children && result[0] !== SKIP)
for (offset = (reverse ? nodeAsParent.children.length : -1) + step, grandparents = parents.concat(nodeAsParent); offset > -1 && offset < nodeAsParent.children.length; ) {
let child = nodeAsParent.children[offset];
if (subresult = factory(child, offset, grandparents)(), subresult[0] === EXIT)
return subresult;
offset = typeof subresult[1] == "number" ? subresult[1] : offset + step;
}
}
return result;
}
}
}
function toResult(value) {
return Array.isArray(value) ? value : typeof value == "number" ? [CONTINUE, value] : value == null ? empty : [value];
}
// node_modules/unist-util-visit/lib/index.js
function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
let reverse, test, visitor;
typeof testOrVisitor == "function" && typeof visitorOrReverse != "function" ? (test = void 0, visitor = testOrVisitor, reverse = visitorOrReverse) : (test = testOrVisitor, visitor = visitorOrReverse, reverse = maybeReverse), visitParents(tree, test, overload, reverse);
function overload(node2, parents) {
let parent = parents[parents.length - 1], index = parent ? parent.children.indexOf(node2) : void 0;
return visitor(node2, index, parent);
}
}
// node_modules/mdast-util-to-string/lib/index.js
var emptyOptions = {};
function toString(value, options) {
let settings = options || emptyOptions, includeImageAlt = typeof settings.includeImageAlt == "boolean" ? settings.includeImageAlt : !0, includeHtml = typeof settings.includeHtml == "boolean" ? settings.includeHtml : !0;
return one(value, includeImageAlt, includeHtml);
}
function one(value, includeImageAlt, includeHtml) {
if (node(value)) {
if ("value" in value)
return value.type === "html" && !includeHtml ? "" : value.value;
if (includeImageAlt && "alt" in value && value.alt)
return value.alt;
if ("children" in value)
return all(value.children, includeImageAlt, includeHtml);
}
return Array.isArray(value) ? all(value, includeImageAlt, includeHtml) : "";
}
function all(values, includeImageAlt, includeHtml) {
let result = [], index = -1;
for (; ++index < values.length; )
result[index] = one(values[index], includeImageAlt, includeHtml);
return result.join("");
}
function node(value) {
return !!(value && typeof value == "object");
}
// src-copilot/markdown/stripYAMLFromMarkdown.js
var stripYAMLFromMarkdown = async (markdownText) => {
let root2 = await parse(markdownText, { yaml: !0 }), textContent = "";
return visit(root2, (node2) => {
if (node2.type === "yaml")
return "skip";
if (node2.type === "root" || node2.type === "paragraph")
return "continue";
if (node2.type === "image")
textContent += \`
\`;
else {
let nodeValue = node2.position ? markdownText.substring(node2.position.start.offset, node2.position.end.offset) : toString(node2);
return textContent += nodeValue + \`
\`, "skip";
}
}), console.log("stripYAMLFromMarkdown", markdownText, textContent.trim()), textContent.trim();
};
// src-copilot/frontend-search/hooks/processCopilotDBResults.js
var processCopilotDBResults = async (results) => {
let filteredResults = results.reduce((acc, result) => {
let uuid = result.noteUUID;
return (!acc[uuid] || acc[uuid].similarity < result.similarity) && (acc[uuid] = result), acc;
}, {}), uniqueResults = Object.values(filteredResults).sort((a, b) => b.similarity - a.similarity);
return Promise.all(
uniqueResults.map(async (result) => ({
noteTitle: result.noteTitle,
actualNoteContentPart: await stripYAMLFromMarkdown(result.actualNoteContentPart),
noteUUID: result.noteUUID,
tags: result.noteTags ? result.noteTags : [],
headingAnchor: result.headingAnchor
}))
);
};
// src-copilot/frontend-search/hooks/useSearch.jsx
var useSearch = () => {
let [searchText, setSearchText] = React.useState(""), [searchResults, setSearchResults] = React.useState([]), [isLoading, setIsLoading] = React.useState(!1), [error, setError] = React.useState(null), [isSyncing, setIsSyncing] = React.useState(!1), [syncProgressText, setSyncProgressText] = React.useState(""), [syncError, setSyncError] = React.useState(null), [searchOpts, setSearchOpts] = React.useState({
isArchived: null,
isSharedByMe: null,
isSharedWithMe: null,
isTaskListNote: null,
isPublished: null
}), [syncStatus, setSyncStatus] = React.useState("Loading"), updateSyncStatus = async () => {
try {
let status = await window.appConnector.getCopilotDBSyncState();
status === "Syncing" ? await handleSync() : setSyncStatus(status);
} catch {
setSyncStatus("Error");
}
};
React.useEffect(() => {
updateSyncStatus();
}, []), React.useEffect(() => {
(async () => {
let searchTextMsg = await window.appConnector.receiveMessageFromPlugin("searchForTextInSearchInterface");
searchTextMsg !== null && setSearchText(searchTextMsg), await window.appConnector.receiveMessageFromPlugin("startSyncToCopilotDBInSearchInterface") === !0 && handleSync();
})();
}, []);
let performSearch = async (query, queryType, searchOpts2 = {}) => {
let results = await window.appConnector.searchNotesInCopilotDB(query, queryType, searchOpts2);
return await processCopilotDBResults(results);
}, debouncedSearch = React.useMemo(
() => debounce_default(async () => {
setIsLoading(!0), setError(null);
try {
let results, isSpecialSearchText = searchText.match(/^<<Related:\\s*([a-zA-Z0-9-]+)>>$/);
if (isSpecialSearchText) {
let noteUUID = isSpecialSearchText[1], noteTitle = await window.appConnector.getNoteTitleByUUID(noteUUID), noteContent = await window.appConnector.getNoteContentByUUID(noteUUID), noteTags = await window.appConnector.getNoteTagsByUUID({ uuid: noteUUID });
if (!noteContent && !noteTitle && !noteTags)
throw new Error("Could not find note with UUID: " + noteUUID);
results = await performSearch(\`---
title: \${noteTitle || "Untitled Note"}
tags: \${noteTags.join(", ")}
---
\` + noteContent.substring(0, LLM_MAX_TOKENS_SETTING * 3), "passage", searchOpts), results = results.filter((result) => result.noteUUID !== noteUUID);
} else
results = await performSearch(searchText, "query", searchOpts);
setSearchResults(results);
} catch (error2) {
console.error(error2), setError((typeof error2 == "string" ? error2 : error2.message) || "An error occurred while searching");
} finally {
setIsLoading(!1);
}
}, 800),
[searchText, searchOpts, syncStatus]
), handleSearch = React.useCallback(() => {
searchText.trim() === "" ? (setSearchResults([]), setError(null)) : (setIsLoading(!0), debouncedSearch());
}, [debouncedSearch, searchText, searchOpts]), handleSync = async () => {
for (setIsSyncing(!0), setSyncError(null), setSyncProgressText(null); await window.appConnector.receiveMessageFromPlugin("syncNotesProgress") != null; )
;
let syncProgressListenerIntervalId = setInterval(async () => {
let lastSyncProgressText = null;
for (; ; ) {
let syncProgressText2 = await window.appConnector.receiveMessageFromPlugin("syncNotesProgress");
if (syncProgressText2 === null) break;
lastSyncProgressText = syncProgressText2;
}
lastSyncProgressText && setSyncProgressText(lastSyncProgressText);
}, 1e3);
try {
await window.appConnector.syncNotesWithCopilotDB(), searchText.trim() && await handleSearch();
} catch (error2) {
console.error("Sync error:", error2), setSyncError("Failed to sync notes: " + (error2.message || error2));
} finally {
setIsSyncing(!1), updateSyncStatus(), clearInterval(syncProgressListenerIntervalId);
}
};
return React.useEffect(() => (handleSearch(), () => debouncedSearch.cancel()), [searchText, handleSearch, searchOpts]), {
searchText,
setSearchText,
searchResults,
isLoading,
error,
isSyncing,
syncError,
syncProgressText,
handleSync,
searchOpts,
setSearchOpts,
syncStatus
};
};
// src-copilot/frontend-search/SearchApp.jsx
var SearchStatus = ({ isLoading, error, isSyncing, syncError, syncProgressText, searchText, searchResults }) => {
let { Flex, Box, Spinner, Text } = window.RadixUI;
return isSyncing ? /* @__PURE__ */ React.createElement(Box, { style: { padding: "20px", textAlign: "center", backgroundColor: "#0ea5e9", color: "white", borderRadius: "6px" } }, "Syncing notes with CopilotDB...", syncProgressText && /* @__PURE__ */ React.createElement(Box, { style: { marginTop: "4px", backgroundColor: "#0369a1", color: "white", borderRadius: "4px", padding: "10px" } }, /* @__PURE__ */ React.createElement(Text, { size: "1", dangerouslySetInnerHTML: { __html: syncProgressText } }))) : syncError ? /* @__PURE__ */ React.createElement(Box, { style: { padding: "20px", textAlign: "center", color: "#e11d48", backgroundColor: "#ffe4e6", borderRadius: "6px" } }, syncError) : isLoading ? /* @__PURE__ */ React.createElement(Box, { style: { padding: "20px", textAlign: "center" } }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", align: "center", justify: "center" }, /* @__PURE__ */ React.createElement(Spinner, { size: "3" }), /* @__PURE__ */ React.createElement(Text, { color: "gray", size: "2" }, "Searching"))) : error ? /* @__PURE__ */ React.createElement(Box, { style: { padding: "20px", textAlign: "center", color: "#e11d48", backgroundColor: "#ffe4e6", borderRadius: "6px" } }, error) : searchResults.length === 0 ? /* @__PURE__ */ React.createElement(Box, { style: { padding: "20px", textAlign: "center", color: "#666" } }, searchText.trim() ? "No results found" : "Start typing to search your notes") : null;
}, FilterRow = ({ label, isEnabled, value, onChange }) => {
let { Tooltip, Switch, IconButton, Flex } = window.RadixUI, { EyeOpenIcon, EyeClosedIcon } = window.RadixIcons, handleSwitchChange = (checked) => {
onChange(checked ? !0 : null);
}, handleIconClick = () => {
isEnabled && onChange(value !== !0);
};
return /* @__PURE__ */ React.createElement(Flex, { align: "center", justify: "between", style: { width: "100%", padding: "12px", fontSize: "14px", paddingTop: "4px", paddingBottom: "4px" } }, label, /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, /* @__PURE__ */ React.createElement(
Switch,
{
size: "1",
checked: isEnabled,
onCheckedChange: handleSwitchChange
}
), value === null ? /* @__PURE__ */ React.createElement(
IconButton,
{
variant: "soft",
size: "1",
disabled: !0,
onClick: handleIconClick
},
/* @__PURE__ */ React.createElement(EyeOpenIcon, null)
) : /* @__PURE__ */ React.createElement(Tooltip, { content: value === !0 ? "Included" : "Excluded" }, /* @__PURE__ */ React.createElement(
IconButton,
{
variant: "soft",
size: "1",
onClick: handleIconClick
},
/* @__PURE__ */ React.createElement(value === !0 ? EyeOpenIcon : EyeClosedIcon, null)
))));
}, SearchMenu = ({ onSync, isSyncing, searchOpts, setSearchOpts, syncStatus }) => {
let { Text, IconButton, DropdownMenu } = window.RadixUI, { DotsHorizontalIcon } = window.RadixIcons, getSyncStatusColor = (status) => {
switch (status) {
case "Fully Synced":
return "green";
case "Loading":
case "Partially synced":
return "yellow";
default:
return "red";
}
}, handleFilterChange = (key, value) => {
setSearchOpts((prev) => ({ ...prev, [key]: value }));
};
return /* @__PURE__ */ React.createElement(DropdownMenu.Root, null, /* @__PURE__ */ React.createElement(DropdownMenu.Trigger, { asChild: !0 }, /* @__PURE__ */ React.createElement(IconButton, { variant: "ghost", style: { padding: "8px" }, className: "search-menu-button" }, /* @__PURE__ */ React.createElement(DotsHorizontalIcon, null))), /* @__PURE__ */ React.createElement(DropdownMenu.Content, { className: "search-menu-content" }, /* @__PURE__ */ React.createElement(Text, { style: { fontSize: "14px", padding: "4px" }, color: "gray" }, "DB Status: ", /* @__PURE__ */ React.createElement(Text, { color: getSyncStatusColor(syncStatus) }, syncStatus)), /* @__PURE__ */ React.createElement(
DropdownMenu.Item,
{
onSelect: onSync,
disabled: isSyncing
},
isSyncing ? "Syncing..." : "Sync notes with CopilotDB"
), /* @__PURE__ */ React.createElement(DropdownMenu.Separator, null), /* @__PURE__ */ React.createElement(Text, { color: "gray", style: { fontSize: "14px", padding: "4px" } }, "Search Options"), /* @__PURE__ */ React.createElement(
FilterRow,
{
label: "Archived",
isEnabled: searchOpts.isArchived !== null,
value: searchOpts.isArchived,
onChange: (value) => handleFilterChange("isArchived", value)
}
), /* @__PURE__ */ React.createElement(
FilterRow,
{
label: "Task List",
isEnabled: searchOpts.isTaskListNote !== null,
value: searchOpts.isTaskListNote,
onChange: (value) => handleFilterChange("isTaskListNote", value)
}
), /* @__PURE__ */ React.createElement(
FilterRow,
{
label: "Published",
isEnabled: searchOpts.isPublished !== null,
value: searchOpts.isPublished,
onChange: (value) => handleFilterChange("isPublished", value)
}
), /* @__PURE__ */ React.createElement(
FilterRow,
{
label: "Shared by Me",
isEnabled: searchOpts.isSharedByMe !== null,
value: searchOpts.isSharedByMe,
onChange: (value) => handleFilterChange("isSharedByMe", value)
}
), /* @__PURE__ */ React.createElement(
FilterRow,
{
label: "Shared with Me",
isEnabled: searchOpts.isSharedWithMe !== null,
value: searchOpts.isSharedWithMe,
onChange: (value) => handleFilterChange("isSharedWithMe", value)
}
)));
}, SearchApp = () => {
let {
searchText,
setSearchText,
searchResults,
isLoading,
error,
isSyncing,
syncError,
syncProgressText,
handleSync,
searchOpts,
setSearchOpts,
syncStatus
} = useSearch(), { Theme, Flex, TextField } = window.RadixUI, { MagnifyingGlassIcon, Cross2Icon } = window.RadixIcons;
return /* @__PURE__ */ React.createElement(Theme, { appearance: "dark", accentColor: "blue" }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "3", style: { height: "100vh", padding: "16px" } }, /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, /* @__PURE__ */ React.createElement(
TextField.Root,
{
placeholder: "Search notes...",
variant: "soft",
value: searchText,
onChange: (e) => setSearchText(e.target.value),
style: {
width: "100%",
padding: "8px 12px",
fontSize: "16px",
flex: 1
},
className: "search-input",
autoFocus: !0
},
/* @__PURE__ */ React.createElement(TextField.Slot, { style: { paddingLeft: "2px" } }, /* @__PURE__ */ React.createElement(MagnifyingGlassIcon, { height: "16", width: "16" })),
searchText && /* @__PURE__ */ React.createElement(TextField.Slot, { style: { paddingRight: "0px" } }, /* @__PURE__ */ React.createElement(
Cross2Icon,
{
height: "16",
width: "16",
style: {
cursor: "pointer",
opacity: 0.7
},
onClick: () => setSearchText("")
}
))
), /* @__PURE__ */ React.createElement(
SearchMenu,
{
onSync: handleSync,
isSyncing,
searchOpts,
setSearchOpts,
syncStatus
}
)), /* @__PURE__ */ React.createElement(
SearchStatus,
{
isLoading,
error,
isSyncing,
syncProgressText,
syncError,
searchText,
searchResults
}
), !isLoading && !isSyncing && !error && !syncError && searchResults && searchResults.length > 0 && /* @__PURE__ */ React.createElement(
EndlessScroll,
{
iterationCnt: 6,
itemContent: (index) => /* @__PURE__ */ React.createElement(
NoteCard,
{
title: searchResults[index].noteTitle,
actualNoteContentPart: searchResults[index].actualNoteContentPart,
noteUUID: searchResults[index].noteUUID,
headingAnchor: searchResults[index].headingAnchor
}
),
data: searchResults
}
)));
};
// src-copilot/embed/search.jsx
window.appConnector = new Proxy({}, {
get: function(target, prop, receiver) {
return prop in target ? target[prop] : async function(...args) {
return window.dispatchEvent(new CustomEvent("callAmplenotePlugin", [prop, ...args])), await window.callAmplenotePlugin(prop, ...args);
};
}
});
window.appSettings = window.appSettings || {};
var body = document.body, html = document.documentElement;
window.addEventListener("resize", function() {
let iframeHeight = Math.min(html.clientHeight, html.scrollHeight);
Object.assign(body.style, {
margin: "0"
});
let appInnerContainer = document.querySelector(".app-container > div > div");
appInnerContainer && Object.assign(appInnerContainer.style, {
height: \`\${iframeHeight - 24}px\`,
overflow: "hidden"
});
});
setInterval(() => window.dispatchEvent(new Event("resize")), 100);
(async () => {
try {
showEmbedLoader(), overwriteWithAmplenoteStyle();
let cssLoaded = dynamicImportCSS("@radix-ui/themes/styles.css"), [React2, ReactDOM, RadixUI, RadixIcons, ReactVirtuoso] = await dynamicImportExternalPluginBundle("searchUIBundle.js");
if (window.React = React2, window.ReactDOM = ReactDOM, window.RadixUI = RadixUI, window.RadixIcons = RadixIcons, window.ReactVirtuoso = ReactVirtuoso, window.appSettings = await appConnector.getSettings(), parse(""), hideEmbedLoader(), !React2 || !window.ReactDOM)
throw new Error("Failed to load React or ReactDOM");
document.querySelector(".app-container") && window.ReactDOM.createRoot(document.querySelector(".app-container")).render(/* @__PURE__ */ React2.createElement(SearchApp, null));
} catch (e) {
window.document.body.innerHTML = '<div style="color: red; font-size: 20px; padding: 20px;">Error during init: ' + e.message + "</div>", console.error(e);
} finally {
await new Promise((resolve) => setTimeout(resolve, 1600)), window.dispatchEvent(new CustomEvent("appLoaded"));
}
})();
return plugin;
})()
<\/script>
</body>
</html>`;
var speechtotext_default = `<html lang="en">
<head>
<title>Speech to Text</title>
<link rel="icon" href="data:,">
<style>
/* Voice processing animation styles */
.voice-processing-animation {
display: flex;
justify-content: center;
align-items: center;
height: 40px;
width: 40px;
margin: 0 auto;
}
.voice-wave {
background: #0ea5e9;
height: 100%;
width: 5px;
margin: 0 3px;
border-radius: 20px;
animation: wave 1s ease-in-out infinite;
}
.voice-wave:nth-child(2) {
animation-delay: 0.1s;
}
.voice-wave:nth-child(3) {
animation-delay: 0.2s;
}
.voice-wave:nth-child(4) {
animation-delay: 0.3s;
}
.voice-wave:nth-child(5) {
animation-delay: 0.4s;
}
@keyframes wave {
0% {
transform: scaleY(0.2);
}
50% {
transform: scaleY(1);
}
100% {
transform: scaleY(0.2);
}
}
</style>
</head>
<body>
<div class="app-container"></div>
<script>(() => {
// src-copilot/constants.js
var LLM_API_URL_SETTING = "LLM API URL", LLM_API_KEY_SETTING = "LLM API Key", LLM_MODEL_SETTING = "LLM Model";
// src-copilot/frontend-chat/overwriteWithAmplenoteStyle.js
var overwriteWithAmplenoteStyle = () => {
let body2 = document.body, styleEl = document.createElement("style");
styleEl.innerText = \`
.dark, .dark-theme, :is(.dark, .dark-theme) :where(.radix-themes:not(.light, .light-theme)) {
--color-background: #272f35;
}
.dark, .dark-theme {
--gray-1: #292f33;
--gray-2: #2f3539;
--gray-3: #343c43;
--gray-4: #36414b;
--gray-5: #3a4651;
--gray-6: #3e4d5a;
--gray-7: #455968;
--gray-8: #577084;
--gray-9: #617b8f;
--gray-10: #6d8599;
--gray-11: #a7bac9;
--gray-12: #eaeff3;
--gray-a1: #d12f0003;
--gray-a2: #f4c99b0a;
--gray-a3: #e0e8fc12;
--gray-a4: #b0d3fe1c;
--gray-a5: #aed2fb24;
--gray-a6: #a4d2fe2f;
--gray-a7: #9dd4fe41;
--gray-a8: #a1d4ff64;
--gray-a9: #a8d9ff72;
--gray-a10: #b3dbfd7f;
--gray-a11: #d6ecffbb;
--gray-a12: #f7fbfff0;
--gray-contrast: #FFFFFF;
--gray-surface: rgba(0, 0, 0, 0.05);
--gray-indicator: #617b8f;
--gray-track: #617b8f;
}
@supports (color: color(display-p3 1 1 1)) {
@media (color-gamut: p3) {
.dark, .dark-theme {
--gray-1: oklch(30% 0.0115 242.8);
--gray-2: oklch(32.3% 0.0119 242.8);
--gray-3: oklch(35.3% 0.0166 242.8);
--gray-4: oklch(37.1% 0.0213 242.8);
--gray-5: oklch(38.8% 0.024 242.8);
--gray-6: oklch(41.2% 0.0288 242.8);
--gray-7: oklch(45.3% 0.035 242.8);
--gray-8: oklch(53.4% 0.0433 242.8);
--gray-9: oklch(57% 0.0433 242.8);
--gray-10: oklch(60.5% 0.0412 242.8);
--gray-11: oklch(77.9% 0.0302 242.8);
--gray-12: oklch(94.9% 0.0081 242.8);
--gray-a1: color(display-p3 0.9451 0.1843 0 / 0.005);
--gray-a2: color(display-p3 0.9961 0.898 0.8 / 0.033);
--gray-a3: color(display-p3 0.902 0.9255 1 / 0.069);
--gray-a4: color(display-p3 0.698 0.8353 0.9961 / 0.109);
--gray-a5: color(display-p3 0.702 0.8353 1 / 0.138);
--gray-a6: color(display-p3 0.6784 0.8275 1 / 0.183);
--gray-a7: color(display-p3 0.6588 0.8235 1 / 0.252);
--gray-a8: color(display-p3 0.6824 0.8392 1 / 0.385);
--gray-a9: color(display-p3 0.7059 0.8549 1 / 0.439);
--gray-a10: color(display-p3 0.749 0.8706 1 / 0.488);
--gray-a11: color(display-p3 0.8667 0.9294 1 / 0.725);
--gray-a12: color(display-p3 0.9725 0.9843 1 / 0.941);
--gray-contrast: #FFFFFF;
--gray-surface: color(display-p3 0 0 0 / 5%);
--gray-indicator: oklch(57% 0.0433 242.8);
--gray-track: oklch(57% 0.0433 242.8);
}
}
}
.dark, .dark-theme {
--accent-1: #252f3c;
--accent-2: #253141;
--accent-3: #223e64;
--accent-4: #1a467f;
--accent-5: #1e508f;
--accent-6: #275b9e;
--accent-7: #2e68b2;
--accent-8: #3277cf;
--accent-9: #0080ff;
--accent-10: #3378d0;
--accent-11: #7cbaff;
--accent-12: #cbe3ff;
--accent-a1: #002ffc09;
--accent-a2: #084ff510;
--accent-a3: #126ffc3c;
--accent-a4: #046dfe5e;
--accent-a5: #1379ff72;
--accent-a6: #2784ff85;
--accent-a7: #328bff9e;
--accent-a8: #368dffc3;
--accent-a9: #0080ff;
--accent-a10: #378effc4;
--accent-a11: #7cbaff;
--accent-a12: #cbe3ff;
--accent-contrast: #fff;
--accent-surface: #24334d80;
--accent-indicator: #0080ff;
--accent-track: #0080ff;
}
@supports (color: color(display-p3 1 1 1)) {
@media (color-gamut: p3) {
.dark, .dark-theme {
--accent-1: oklch(30% 0.0278 256.1);
--accent-2: oklch(31% 0.0325 256.1);
--accent-3: oklch(36.2% 0.074 256.1);
--accent-4: oklch(39.6% 0.1073 256.1);
--accent-5: oklch(43.2% 0.1173 256.1);
--accent-6: oklch(47.1% 0.1224 256.1);
--accent-7: oklch(51.7% 0.1323 256.1);
--accent-8: oklch(57% 0.1522 256.1);
--accent-9: oklch(61.5% 0.2108 256.1);
--accent-10: oklch(57.3% 0.1522 256.1);
--accent-11: oklch(78% 0.1427 256.1);
--accent-12: oklch(90.8% 0.0525 256.1);
--accent-a1: color(display-p3 0 0.1882 0.9882 / 0.035);
--accent-a2: color(display-p3 0.0314 0.3176 0.9922 / 0.06);
--accent-a3: color(display-p3 0.1608 0.4314 1 / 0.222);
--accent-a4: color(display-p3 0.1294 0.4275 1 / 0.35);
--accent-a5: color(display-p3 0.1882 0.4824 1 / 0.424);
--accent-a6: color(display-p3 0.2549 0.5216 1 / 0.498);
--accent-a7: color(display-p3 0.2902 0.5529 1 / 0.597);
--accent-a8: color(display-p3 0.3098 0.5569 1 / 0.734);
--accent-a9: color(display-p3 0.2157 0.5059 1 / 0.961);
--accent-a10: color(display-p3 0.3137 0.5647 1 / 0.739);
--accent-a11: color(display-p3 0.5529 0.7373 0.9961 / 0.971);
--accent-a12: color(display-p3 0.8235 0.8941 1 / 0.986);
--accent-contrast: #fff;
--accent-surface: color(display-p3 0.1529 0.1961 0.2902 / 0.5);
--accent-indicator: oklch(61.5% 0.2108 256.1);
--accent-track: oklch(61.5% 0.2108 256.1);
}
}
}\`.replace(/\\s+/g, " ").trim(), styleEl.innerText += \`
.app-container .radix-themes {
--default-font-size: 14px;
}
\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl);
let styleEl2 = document.createElement("style");
styleEl2.innerText = \`
.dark {
--aui-background: 210, 10%, 18%;
--aui-foreground: 210, 10%, 94%;
--aui-card: 210, 10%, 20%;
--aui-card-foreground: 210, 10%, 94%;
--aui-popover: 210, 10%, 22%;
--aui-popover-foreground: 210, 10%, 94%;
--aui-border: 210, 10%, 50%;
--aui-input: 210, 10%, 50%;
--aui-ring: 210, 10%, 18%;
--aui-primary: 205 80% 50%;
--aui-primary-foreground: 0, 0%, 100%;
--aui-secondary: 205, 10%, 94%;
--aui-secondary-foreground: 205, 10%, 18%;
--aui-muted-foreground: 205, 10%, 50%;
--aui-accent: 205, 100%, 50%;
--aui-accent-foreground: 0, 0%, 100%;
--aui-destructive: 0, 84%, 60%;
--aui-destructive-foreground: 0, 0%, 98%;
--aui-radius: 0.3rem;
}\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl2);
let styleEl3 = document.createElement("style");
styleEl3.innerText = \`
.tool_group_mention {
background-color: var(--accent-a3);
border-radius: var(--aui-radius);
}
div.aui-user-message-content {
border-radius: 1.25rem;
}
.aui-composer-root, .aui-thread-welcome-suggestion {
background-color: rgb(39, 47, 53);
}
.aui-composer-cancel {
background-color: hsl(var(--aui-destructive));
color: hsl(var(--aui-destructive-foreground));
}
.aui-composer-cancel:hover,
.aui-composer-cancel:focus,
.aui-composer-cancel:active {
background-color: hsla(var(--aui-destructive), 0.9);
}
.aui-composer-cancel:disabled {
background-color: hsla(var(--aui-destructive), 0.5);
color: hsla(var(--aui-destructive-foreground), 0.5);
cursor: not-allowed;
}
.aui-composer-root {
padding-left: 0.325rem;
padding-right: 0.325rem;
}
\`.replace(/\\s+/g, " ").trim(), body2.appendChild(styleEl3);
};
// common-utils/embed-ui.js
function showEmbedLoader() {
window.LoadingStartTime = performance.now();
let overlay = document.createElement("div");
overlay.id = "embed-loader-overlay", overlay.style.cssText = \`
position: fixed;
top: 0;
left: 0;
width: 100%;
/*height: 100%;*/
background-color: rgba(0, 0, 0, 0.5);
z-index: 9998;
animation: fadeIn 0.3s ease-in-out;
\`;
let loader = document.createElement("div");
loader.id = "embed-loader", loader.style.cssText = \`
position: fixed;
left: 50%;
transform: translate(-50%, 0%);
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
z-index: 9999;
\`;
let keyframes = document.createElement("style");
keyframes.textContent = \`
@keyframes spin {
0% { transform: translate(-50%, -50%) rotate(0deg); }
100% { transform: translate(-50%, -50%) rotate(360deg); }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
\`, document.head.appendChild(keyframes), document.body.appendChild(overlay), document.body.appendChild(loader), overlay.style.display = "none", loader.style.display = "none", setTimeout(() => {
document.getElementById("embed-loader") && (loader.style.display = "block"), document.getElementById("embed-loader-overlay") && (overlay.style.display = "block");
}, 240);
}
function hideEmbedLoader() {
window.LoadingEndTime = performance.now(), console.log("Loading time:", window.LoadingEndTime - window.LoadingStartTime);
let loader = document.getElementById("embed-loader"), overlay = document.getElementById("embed-loader-overlay");
loader && loader.remove(), overlay && overlay.remove();
}
// package.json
var package_default = {
name: "amplenote-plugin-dev-env",
author: "debajandhar12",
version: "1.0.0",
type: "module",
repository: "https://github.com/debanjandhar12/my-amplenote-plugins-v2",
dependencies: {
"@ai-sdk/anthropic": "1.2.10",
"@ai-sdk/fireworks": "0.2.13",
"@ai-sdk/google": "1.2.14",
"@ai-sdk/groq": "1.2.8",
"@ai-sdk/openai": "1.3.21",
"@assistant-ui/react": "0.7.65",
"@assistant-ui/react-markdown": "0.7.16",
"@debanjandhar12/markmap-lib": "0.17.0-mod.3",
"@debanjandhar12/markmap-toolbar": "0.17.0-mod.3",
"@debanjandhar12/markmap-view": "0.17.0-mod.3",
"@duckdb/duckdb-wasm": "1.31.0",
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@huggingface/transformers": "3.7.3",
"@omnivore-app/api": "^1.0.4",
"@pinecone-database/pinecone": "4.1.0",
"@radix-ui/react-icons": "1.3.2",
"@radix-ui/themes": "3.2.0",
"@yiuayiu/telegram-markdown-escape": "^0.0.2-1",
ai: "4.3.13",
"apache-arrow": "^20.0.0",
"async-mutex": "0.5.0",
"chart.js": "^4.4.3",
"d3-svg-to-png": "^0.3.1",
"date-fns": "^3.6.0",
dayjs: "1.11.13",
"easy-web-worker": "7.0.2",
"emoji-mart": "^5.6.0",
"fast-dotproduct": "1.3.0",
fflate: "0.8.2",
fparser: "^3.1.0",
"fuse.js": "7.0.0",
idb: "8.0.2",
"iconv-lite": "^0.6.3",
"lodash-es": "^4.17.21",
luxon: "^3.4.4",
"markdown-it": "^14.1.0",
"mdast-util-to-string": "4.0.0",
"my-ample-plugin-external": "1.0.29",
nanoid: "^5.0.7",
"ollama-ai-provider": "1.2.0",
"parquetjs-lite": "^0.8.7",
react: "18.2.0",
"react-dom": "18.2.0",
"react-error-boundary": "5.0.0",
"react-string-diff": "0.2.0",
"react-virtuoso": "4.12.5",
"react-window": "1.8.11",
"remark-frontmatter": "5.0.0",
"remark-gfm": "4.0.0",
"remark-parse": "11.0.0",
"scheduler-polyfill": "1.3.0",
stopword: "3.1.5",
tributejs: "5.1.3",
unified: "11.0.0",
"unist-util-visit": "5.0.0",
"unist-util-visit-parents": "6.0.1",
"vosk-browser": "0.0.8",
zod: "3.23.8"
},
devDependencies: {
"@huggingface/transformers": "3.2.4",
"@playwright/test": "^1.49.1",
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^29.5.0",
"core-js": "^3.38.1",
cors: "^2.8.5",
"cross-fetch": "^4.0.0",
dotenv: "^16.0.3",
esbuild: "0.25.3",
"esbuild-jest2": "0.6.7",
"esbuild-plugin-external-global": "^1.0.1",
"esbuild-plugins-node-modules-polyfill": "1.7.0",
express: "^5.0.1",
"isomorphic-fetch": "^3.0.0",
jest: "^29.5.0",
jsdom: "^24.1.0",
"make-synchronous": "^1.0.0",
"node-fetch": "4.0.0-beta.4",
"p-retry": "6.2.1",
playwright: "^1.49.1",
sinon: "21.0.0",
"jest-allure2-reporter": "2.2.6",
"allure-commandline": "^2.32.0",
open: "^10.2.0"
},
scripts: {
test: "jest --testPathPattern=src-copilot",
"test:watch": "jest --testPathPattern=src-copilot --watch",
"allure:serve": \`npx allure generate --single-file ./allure/results --clean -o ./allure/report && node --input-type=module -e "import('open').then(o => o.default('./allure/report/index.html'))"\`,
"build:prod": "NODE_ENV=production node esbuild.js $(pwd)/src-copilot",
"build:dev": "node esbuild.js $(pwd)/src-copilot --watch --server"
}
};
// common-utils/dynamic-import-esm.js
var dynamicImportExternalPluginBundle = async (fileName) => {
let packageVersion = package_default.dependencies["my-ample-plugin-external"], pkg = \`my-ample-plugin-external/dist/\${fileName}\`, cdnList = getCDNList(pkg), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, packageVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 1e3)), abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return import(url).then((module) => {
if (abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return { module, url };
}).catch((e) => {
throw console.warn(\`Failed to import \${pkg} from \${cdn}: \${e.message}\`), e;
});
});
try {
let result = await Promise.any(importPromises);
abortController.abort();
let module = result.module;
if (!module.versions)
throw new Error(\`Failed to import module: \${fileName}. Returned bundle does not have version property.\`);
for (let [key, value] of Object.entries(module.versions))
if (value !== package_default.dependencies[key])
throw new Error(\`Failed to import module: \${fileName}. Version mismatch for \${key} (expected: \${package_default.dependencies[key]}, actual: \${value})\`);
return console.log(\`Imported \${pkg}@\${packageVersion} from \${result.url}\`), module.default;
} catch {
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
}
};
var dynamicImportESM = async (pkg, pkgVersion = null) => {
let cdnList = getCDNList(pkg), resolvedVersion = resolvePackageVersion(pkg, pkgVersion), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, resolvedVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 2500)), abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return import(url).then((module) => {
if (abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return { module, url };
}).catch((e) => {
throw console.warn(\`Failed to import \${pkg} from \${cdn}: \${e.message}\`), e;
});
});
try {
let result = await Promise.any(importPromises);
return abortController.abort(), console.log(\`Imported \${pkg}@\${resolvedVersion} from \${result.url}\`), result.module;
} catch {
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
}
};
function getBasePackage(pkg) {
if (pkg.startsWith("@")) {
let [scope, name] = pkg.split("/");
return \`\${scope}/\${name}\`;
}
return pkg.split("/")[0];
}
function resolvePackageVersion(pkg, pkgVersion) {
let basePkg = getBasePackage(pkg), version = pkgVersion || package_default.dependencies[basePkg] || package_default.devDependencies[basePkg] || "latest";
return version.startsWith("^") || version.startsWith("~") ? version.substring(1) : version;
}
function getPackageFolderString(pkg) {
let folders = [];
return pkg.startsWith("@") ? [, , ...folders] = pkg.split("/") : [, ...folders] = pkg.split("/"), folders && folders.length > 0 ? \`/\${folders.join("/")}\` : "";
}
function getCDNList(pkg) {
let basePkg = getBasePackage(pkg);
return basePkg.includes("react") || basePkg.includes("radix") || basePkg.includes("build") || basePkg.includes("dotenv") ? ["https://esm.sh/", "https://legacy.esm.sh/"] : ["https://cdn.jsdelivr.net/npm/", "https://esm.sh/", "https://unpkg.com/"];
}
function buildCDNUrl(cdn, pkg, version) {
let basePkg = getBasePackage(pkg), versionString = version !== "latest" ? \`@\${version}\` : "", folderString = getPackageFolderString(pkg), url = new URL(\`\${cdn}\${basePkg}\${versionString}\${folderString}\`);
if (cdn !== "https://esm.sh/" && (basePkg.includes("react") || basePkg.includes("radix")) && !pkg.endsWith(".css"))
throw new Error(\`React based js packages is not supported in \${cdn}\`);
if (cdn !== "https://legacy.esm.sh/" && basePkg.includes("build"))
throw new Error(\`Build API package is not supported in \${cdn}\`);
cdn === "https://esm.sh/" && (basePkg !== "react-dom" && basePkg !== "react" && url.searchParams.set("bundle-deps", !1), !pkg.endsWith(".css") && pkg !== "build" && url.searchParams.set("deps", \`react@\${package_default.dependencies.react},react-dom@\${package_default.dependencies["react-dom"]}\`));
let urlString = url.toString();
return cdn === "https://cdn.jsdelivr.net/npm/" && !pkg.endsWith(".css") && (urlString += "/+esm"), urlString;
}
var dynamicImportCSS = async (pkg, pkgVersion = null) => {
let resolvedVersion = resolvePackageVersion(pkg, pkgVersion), url = buildCDNUrl("https://cdn.jsdelivr.net/npm/", pkg, resolvedVersion), link = document.createElement("link");
return link.rel = "stylesheet", link.href = url, document.head.appendChild(link), new Promise((resolve) => link.onload = resolve);
}, dynamic_import_esm_default = dynamicImportESM;
// src-copilot/frontend-speechtotext/hooks/useSpeechToText.js
var useSpeechToText = () => {
let { useState, useEffect, useRef } = window.React, [status, setStatus] = useState("initializing"), [errorObj, setErrorObj] = useState(null), [transcriptionText, setTranscriptionText] = useState(""), confirmedTextRef = useRef(""), partialTextRef = useRef(""), resetTranscription = () => {
setTranscriptionText(""), confirmedTextRef.current = "", partialTextRef.current = "";
}, setError = (message, type = "UNKNOWN_ERROR") => {
setStatus("error"), setErrorObj({ message, type });
}, flushVoskletMessages = async () => {
try {
let channels = ["vosklet-partial", "vosklet-result", "vosklet-error", "vosklet-ready"];
for (let channel of channels)
for (; await window.appConnector.receiveMessageFromPlugin(channel) != null; )
;
} catch (e) {
console.warn("Failed to flush initial Vosklet messages", e);
}
}, cleanupExistingVosklet = async () => {
try {
await window.appConnector.stopVoskletRecording(), await window.appConnector.cleanupVoskletSpeechToText();
} catch (error) {
console.warn("No existing Vosklet session to cleanup:", error);
}
}, initializeVosklet = async () => {
try {
await cleanupExistingVosklet();
let initResult = await window.appConnector.initializeVoskletSpeechToText();
if (!initResult.success) {
setError(initResult.error, initResult.errorType);
return;
}
let startResult = await window.appConnector.startVoskletRecording({
partialResult: "vosklet-partial",
result: "vosklet-result",
error: "vosklet-error",
ready: "vosklet-ready"
});
if (!startResult.success) {
setError(startResult.error, startResult.errorType);
return;
}
setStatus("processing"), await flushVoskletMessages();
} catch (error) {
console.error("Failed to initialize Vosklet speech-to-text:", error), setError(error.message || "Unknown error", "INITIALIZATION_ERROR");
}
}, stopRecording = async () => {
try {
await window.appConnector.stopVoskletRecording(), await window.appConnector.cleanupVoskletSpeechToText(), setStatus("stopped");
} catch (error) {
console.error("Error stopping recording:", error), setError(error.message || "Failed to stop recording", "STOP_ERROR");
}
}, startNewRecording = async () => {
resetTranscription(), setStatus("initializing"), setErrorObj(null), await initializeVosklet();
};
return useEffect(() => {
initializeVosklet();
}, []), useEffect(() => {
let interval = setInterval(async () => {
if (status === "processing")
try {
let updated = !1;
for (; ; ) {
let resultMessage = await window.appConnector.receiveMessageFromPlugin("vosklet-result");
if (!resultMessage) break;
if (typeof resultMessage.text == "string") {
let chunk = resultMessage.text.trim();
chunk && (confirmedTextRef.current = confirmedTextRef.current ? \`\${confirmedTextRef.current} \${chunk}\` : chunk, partialTextRef.current = "", updated = !0);
}
}
let latestPartial = null;
for (; ; ) {
let partialMessage = await window.appConnector.receiveMessageFromPlugin("vosklet-partial");
if (partialMessage === null) break;
latestPartial = partialMessage;
}
latestPartial && typeof latestPartial.text == "string" && (partialTextRef.current = latestPartial.text.trim(), updated = !0);
let errorMessage = await window.appConnector.receiveMessageFromPlugin("vosklet-error");
if (errorMessage) {
setError(errorMessage.error, errorMessage.errorType);
return;
}
if (updated) {
let combined = [confirmedTextRef.current, partialTextRef.current].filter(Boolean).join(" ");
setTranscriptionText(combined);
}
} catch (error) {
console.error("Error polling for Vosklet messages:", error);
}
}, 200);
return () => clearInterval(interval);
}, [status]), {
status,
errorObj,
transcriptionText,
setTranscriptionText,
resetTranscription,
stopRecording,
startNewRecording
};
};
// src-copilot/frontend-speechtotext/hooks/useCurrentNotePolling.jsx
function useCurrentNotePolling() {
let { useState, useEffect } = window.React, [currentNoteInfo, setCurrentNoteInfo] = useState(null);
return useEffect(() => {
let updateCurrentNoteData = async () => {
try {
let noteData = await window.appConnector.getUserCurrentNoteData();
setCurrentNoteInfo(noteData);
} catch (error) {
console.warn("Failed to get current note data:", error);
}
};
updateCurrentNoteData();
let intervalId = setInterval(updateCurrentNoteData, 4e3);
return () => {
clearInterval(intervalId);
};
}, []), currentNoteInfo;
}
// src-copilot/frontend-speechtotext/views/InitializingView.jsx
var InitializingView = () => {
let { Flex, Text, Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(Flex, { direction: "column", align: "center", justify: "center", gap: "4", style: { height: "100%" } }, /* @__PURE__ */ React.createElement(Spinner, { size: "5" }), /* @__PURE__ */ React.createElement(Text, { size: "3" }, "Initializing speech recognition..."));
};
// src-copilot/aisdk-wrappers/getLLMModel.js
async function getLLMModel(appSettings) {
let apiUrl = appSettings[LLM_API_URL_SETTING], model = appSettings[LLM_MODEL_SETTING], apiKey = appSettings[LLM_API_KEY_SETTING];
if (!apiUrl || !apiUrl.trim()) throw new Error("API URL is not provided. Please check plugin settings.");
if (!model || !model.trim()) throw new Error("Model is not provided. Please check plugin settings.");
if (apiUrl.endsWith("/chat/completion") && (apiUrl = apiUrl.slice(0, -16)), apiUrl = apiUrl.toLowerCase(), model = model.toLowerCase(), apiUrl.includes("groq")) {
let { createGroq } = await dynamic_import_esm_default("@ai-sdk/groq");
return createGroq({
apiKey,
baseURL: apiUrl
// Default: https://api.groq.com/openai/v1
}).languageModel(model);
} else if (apiUrl.includes("localhost")) {
let { createOllama } = await dynamic_import_esm_default("ollama-ai-provider");
return createOllama({
apiKey,
baseURL: apiUrl
// Default: http://localhost:11434/api
}).languageModel(model);
} else if (apiUrl.includes("googleapis")) {
let { createGoogleGenerativeAI } = await dynamic_import_esm_default("@ai-sdk/google");
return createGoogleGenerativeAI({
apiKey,
baseURL: apiUrl
// Default: https://generativelanguage.googleapis.com/v1beta
}).languageModel(model);
} else if (apiUrl.includes("anthropic")) {
let { createAnthropic } = await dynamic_import_esm_default("@ai-sdk/anthropic");
return createAnthropic({
apiKey,
baseURL: apiUrl,
headers: { "anthropic-dangerous-direct-browser-access": "true" }
}).languageModel(model);
} else if (apiUrl.includes("openai") || apiUrl.includes("openrouter")) {
let { createOpenAI } = await dynamic_import_esm_default("@ai-sdk/openai");
return createOpenAI({
apiKey,
baseURL: apiUrl
// Default: https://api.openai.com/v1
}).languageModel(model);
} else if (apiUrl.includes("fireworks")) {
let { createFireworks } = await dynamic_import_esm_default("@ai-sdk/fireworks");
return createFireworks({
apiKey,
baseURL: apiUrl
}).languageModel(model.startsWith("accounts/fireworks/models/") ? model : \`accounts/fireworks/models/\${model}\`);
} else throw new Error("It is likely that incorrect LLM API URL is provided. Please check plugin settings.");
}
// src-copilot/aisdk-wrappers/generateText.js
async function generateText(model, prompt) {
let { generateText: generateText2 } = await dynamic_import_esm_default("ai");
return await generateText2({
model,
prompt
});
}
// src-copilot/frontend-speechtotext/hooks/useAIFixTranscript.js
var useAIFixTranscript = () => {
let { useState } = window.React, [isFixing, setIsFixing] = useState(!1);
return {
isFixing,
fixTranscript: async (text, onTextChange) => {
if (!(!text || !text.trim() || !onTextChange)) {
setIsFixing(!0);
try {
let model = await getLLMModel(window.appSettings), prompt = \`You are an tool that fixes speech-to-text transcription errors. Your task is to:
1. Add proper punctuation (periods, commas, question marks, exclamation marks)
2. Fix capitalization (proper nouns, sentence beginnings)
3. Replace words that appear to be incorrectly transcribed with the most likely intended words based on context
4. Fix mistaken words or filler words or repetitions if they seem like transcription errors
5. Maintain the original meaning and tone
Note: DO NOT return anything other than fixed transcript.
Please fix the following transcript:
\${text}\`, response = await generateText(model, prompt);
onTextChange({ target: { value: response.text } });
} catch (error) {
console.error("Error fixing transcript:", error);
} finally {
setIsFixing(!1);
}
}
}
};
};
// src-copilot/frontend-speechtotext/components/TranscriptionTextArea.jsx
var TranscriptionTextArea = ({ value, onChange = null, placeholder = null, label = null, showFixButton = !1 }) => {
let { TextArea, Text, Card, Button, Spinner } = window.RadixUI, { MagicWandIcon } = window.RadixIcons, { isFixing, fixTranscript } = useAIFixTranscript(), handleAIFix = () => fixTranscript(value, onChange);
return /* @__PURE__ */ React.createElement(Card, { style: { padding: "16px", flex: 1, display: "flex", flexDirection: "column", position: "relative" } }, label && /* @__PURE__ */ React.createElement(Text, { size: "2", color: "gray", style: { marginBottom: "8px" } }, label), /* @__PURE__ */ React.createElement("div", { style: { position: "relative", flex: 1, display: "flex", flexDirection: "column" } }, /* @__PURE__ */ React.createElement(
TextArea,
{
value,
onChange,
readOnly: !onChange,
placeholder,
style: {
flex: 1,
minHeight: "200px",
fontStyle: value ? "normal" : "italic",
color: value ? "inherit" : "gray",
paddingRight: showFixButton && onChange && value && value.trim() ? "60px" : void 0
}
}
), showFixButton && onChange && value && value.trim() && /* @__PURE__ */ React.createElement(
Button,
{
size: "1",
variant: "ghost",
onClick: handleAIFix,
disabled: isFixing,
style: {
position: "absolute",
top: "8px",
right: "8px",
backgroundColor: "rgba(0, 0, 0, 0.1)",
backdropFilter: "blur(4px)",
border: "1px solid rgba(255, 255, 255, 0.2)",
zIndex: 1
},
title: "Fix transcript with AI"
},
isFixing ? /* @__PURE__ */ React.createElement(Spinner, { size: "1" }) : /* @__PURE__ */ React.createElement(MagicWandIcon, { width: "12", height: "12" }),
"Fix"
)));
};
// src-copilot/frontend-speechtotext/views/SpeechProcessingView.jsx
var SpeechProcessingView = ({ transcriptionText, onStop, onClear }) => {
let { Flex, Button, Text } = window.RadixUI;
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Flex, { direction: "column", align: "center", gap: "3", style: { marginBottom: "16px" } }, /* @__PURE__ */ React.createElement("div", { className: "voice-processing-animation" }, [...Array(5)].map((_, i) => /* @__PURE__ */ React.createElement("div", { key: i, className: "voice-wave" }))), /* @__PURE__ */ React.createElement(Text, { size: "3" }, "Listening...")), /* @__PURE__ */ React.createElement(
TranscriptionTextArea,
{
value: transcriptionText || "Say something...",
label: "Transcribed Text:"
}
), /* @__PURE__ */ React.createElement(Flex, { gap: "2", justify: "center" }, /* @__PURE__ */ React.createElement(Button, { size: "3", color: "red", onClick: onStop }, "Stop Recording"), transcriptionText && /* @__PURE__ */ React.createElement(Button, { size: "3", variant: "outline", onClick: onClear }, "Clear")));
};
// src-copilot/frontend-speechtotext/views/StoppedView.jsx
var StoppedView = ({
transcriptionText,
onTranscriptionChange,
currentNoteInfo,
onInsertToCurrent,
onInsertToSelected,
onStartNew,
isInserting,
isInserted
}) => {
let { Flex, Button, Spinner } = window.RadixUI;
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
TranscriptionTextArea,
{
value: transcriptionText || "No text was transcribed.",
onChange: (e) => onTranscriptionChange(e.target.value),
placeholder: "You can edit the transcribed text here...",
label: "Final Transcription:",
showFixButton: !0
}
), /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "2" }, transcriptionText && /* @__PURE__ */ React.createElement(React.Fragment, null, (currentNoteInfo == null ? void 0 : currentNoteInfo.currentNoteUUID) && /* @__PURE__ */ React.createElement(
Button,
{
size: "3",
variant: "solid",
onClick: onInsertToCurrent,
disabled: isInserting || isInserted,
style: { width: "100%" }
},
isInserting ? /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, /* @__PURE__ */ React.createElement(Spinner, { size: "1" }), "Inserting...") : \`Insert to Current Note (\${currentNoteInfo.currentNoteName || "Untitled"})\`
), /* @__PURE__ */ React.createElement(
Button,
{
size: "3",
variant: "outline",
onClick: onInsertToSelected,
color: isInserted ? "green" : "inherit",
disabled: isInserting || isInserted,
style: { width: "100%" }
},
isInserting ? /* @__PURE__ */ React.createElement(Flex, { align: "center", gap: "2" }, /* @__PURE__ */ React.createElement(Spinner, { size: "1" }), "Inserting...") : "Insert to Note..."
)), /* @__PURE__ */ React.createElement(
Button,
{
size: "3",
variant: "outline",
onClick: onStartNew,
style: { width: "100%" }
},
"Start New Recording"
)));
};
// src-copilot/frontend-chat/helpers/errorToString.js
var errorToString = (error) => {
let baseMessage = null;
if (typeof error == "string")
baseMessage = error;
else if (error instanceof Error)
baseMessage = error.message;
else if (error && typeof error.message == "string")
baseMessage = error.message;
else if (error && typeof error.error == "string")
baseMessage = error.error;
else if (error != null)
try {
baseMessage = String(error);
} catch {
}
baseMessage || (baseMessage = JSON.stringify(error));
let processedMessage = (typeof baseMessage == "string" ? baseMessage : "").trim(), prefixPattern = /^(Error\\s*:\\s*)+/i;
return processedMessage = processedMessage.replace(prefixPattern, ""), processedMessage = processedMessage.trim(), processedMessage;
};
// src-copilot/frontend-speechtotext/views/ErrorView.jsx
var ErrorView = ({ errorObj, onTryAgain }) => {
let { Flex, Text, Button } = window.RadixUI;
return /* @__PURE__ */ React.createElement(Flex, { direction: "column", align: "center", justify: "center", gap: "4", style: { height: "100%" } }, /* @__PURE__ */ React.createElement(Text, { size: "3" }, "Error with speech recognition"), /* @__PURE__ */ React.createElement(Text, { size: "2", color: "red" }, errorToString(errorObj)), /* @__PURE__ */ React.createElement(Button, { size: "3", variant: "outline", onClick: onTryAgain }, "Try Again"));
};
// src-copilot/frontend-speechtotext/SpeechToTextApp.jsx
var SpeechToTextApp = () => {
let { useState } = window.React, [isInserting, setIsInserting] = useState(!1), [isInserted, setIsInserted] = useState(!1), { Theme, Flex } = window.RadixUI, {
status,
errorObj,
transcriptionText,
setTranscriptionText,
resetTranscription,
stopRecording,
startNewRecording
} = useSpeechToText(), currentNoteInfo = useCurrentNotePolling(), handleClear = () => {
resetTranscription(), setIsInserted(!1);
}, handleStartNew = async () => {
setIsInserted(!1), await startNewRecording();
}, handleInsertToCurrentNote = async () => {
if (!(currentNoteInfo != null && currentNoteInfo.currentNoteUUID)) {
console.error("No current note available");
return;
}
if (transcriptionText.trim()) {
setIsInserting(!0);
try {
await window.appConnector.insertNoteContent({ uuid: currentNoteInfo.currentNoteUUID }, transcriptionText, { atEnd: !0 }), setIsInserted(!0);
} catch (error) {
console.error("Error inserting text:", error);
} finally {
setIsInserting(!1);
}
}
}, handleInsertToSelectedNote = async () => {
if (transcriptionText.trim()) {
setIsInserting(!0);
try {
let selectedNote = await window.appConnector.prompt("Select a note to insert the transcribed text:", {
inputs: [
{
type: "note",
label: "Select Note"
}
]
});
if (!selectedNote.uuid) {
setIsInserting(!1);
return;
}
await window.appConnector.insertNoteContent({ uuid: selectedNote.uuid }, transcriptionText, { atEnd: !0 }), setIsInserted(!0);
} catch (error) {
console.error("Error inserting text to selected note:", error);
} finally {
setIsInserting(!1);
}
}
};
return /* @__PURE__ */ React.createElement(Theme, { appearance: "dark", accentColor: "blue" }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "4", style: { height: "100vh", padding: "16px" } }, (() => {
switch (status) {
case "initializing":
return /* @__PURE__ */ React.createElement(InitializingView, null);
case "processing":
return /* @__PURE__ */ React.createElement(
SpeechProcessingView,
{
transcriptionText,
onStop: stopRecording,
onClear: handleClear
}
);
case "stopped":
return /* @__PURE__ */ React.createElement(
StoppedView,
{
transcriptionText,
onTranscriptionChange: setTranscriptionText,
currentNoteInfo,
onInsertToCurrent: handleInsertToCurrentNote,
onInsertToSelected: handleInsertToSelectedNote,
onStartNew: handleStartNew,
isInserting,
isInserted
}
);
case "error":
return /* @__PURE__ */ React.createElement(ErrorView, { errorObj, onTryAgain: handleStartNew });
default:
return null;
}
})()));
};
// src-copilot/embed/speechtotext.jsx
window.appConnector = new Proxy({}, {
get: function(target, prop, receiver) {
return prop in target ? target[prop] : async function(...args) {
return window.dispatchEvent(new CustomEvent("callAmplenotePlugin", [prop, ...args])), await window.callAmplenotePlugin(prop, ...args);
};
}
});
window.appSettings = window.appSettings || {};
var body = document.body, html = document.documentElement;
window.addEventListener("resize", function() {
let iframeHeight = Math.min(html.clientHeight, html.scrollHeight);
Object.assign(body.style, {
margin: "0"
});
let appInnerContainer = document.querySelector(".app-container > div > div");
appInnerContainer && Object.assign(appInnerContainer.style, {
height: \`\${iframeHeight - 24}px\`,
overflow: "hidden"
});
});
setInterval(() => window.dispatchEvent(new Event("resize")), 100);
(async () => {
try {
showEmbedLoader(), overwriteWithAmplenoteStyle();
let cssLoaded = dynamicImportCSS("@radix-ui/themes/styles.css"), [React2, ReactDOM, RadixUI, RadixIcons] = await dynamicImportExternalPluginBundle("searchUIBundle.js");
if (window.React = React2, window.ReactDOM = ReactDOM, window.RadixUI = RadixUI, window.RadixIcons = RadixIcons, window.appSettings = await appConnector.getSettings(), hideEmbedLoader(), !React2 || !window.ReactDOM)
throw new Error("Failed to load React or ReactDOM");
document.querySelector(".app-container") && window.ReactDOM.createRoot(document.querySelector(".app-container")).render(/* @__PURE__ */ React2.createElement(SpeechToTextApp, null));
} catch (e) {
window.document.body.innerHTML = '<div style="color: red; font-size: 20px; padding: 20px;">Error during init: ' + e.message + "</div>", console.error(e);
} finally {
await new Promise((resolve) => setTimeout(resolve, 1600)), window.dispatchEvent(new CustomEvent("appLoaded"));
}
})();
return plugin;
})()
<\/script>
</body>
</html>`;
init_process();
var COMMON_EMBED_COMMANDS = {
navigate: async (app, url) => {
if (await app.navigate(url)) return !0;
try {
return window.open(url, "_blank") != null;
} catch {
return !1;
}
},
prompt: async (app, ...args) => await app.prompt(...args),
alert: async (app, ...args) => await app.alert(...args),
getSettings: async (app) => app.settings,
setSetting: async (app, key, value) => app.setSetting(key, value),
getNoteTitleByUUID: async (app, noteUUID) => {
var _a;
return (_a = await app.notes.find(noteUUID)) == null ? void 0 : _a.name;
},
getNoteContentByUUID: async (app, noteUUID) => await app.notes.find(noteUUID) ? await app.getNoteContent({ uuid: noteUUID }) : null,
getNoteBacklinksByUUID: async (app, noteUUID) => {
var _a;
return await ((_a = await app.notes.find(noteUUID)) == null ? void 0 : _a.backlinks());
},
getNoteTagsByUUID: async (app, noteUUID) => {
var _a;
return (_a = await app.notes.find(noteUUID)) == null ? void 0 : _a.tags;
},
getNoteSections: async (app, ...args) => await app.getNoteSections(...args),
insertTask: async (app, ...args) => await app.insertTask(...args),
updateTask: async (app, ...args) => await app.updateTask(...args),
createNote: async (app, ...args) => await app.createNote(...args),
deleteNote: async (app, ...args) => await app.deleteNote(...args),
replaceNoteContent: async (app, ...args) => await app.replaceNoteContent(...args),
setNoteName: async (app, ...args) => await app.setNoteName(...args),
addNoteTag: async (app, ...args) => await app.addNoteTag(...args),
removeNoteTag: async (app, ...args) => await app.removeNoteTag(...args),
insertNoteContent: async (app, ...args) => await app.insertNoteContent(...args),
getTaskDomains: async (app) => await app.getTaskDomains(),
getTaskDomainTasks: async (app, ...args) => await app.getTaskDomainTasks(...args),
getTask: async (app, ...args) => await app.getTask(...args),
findNote: async (app, ...args) => await app.findNote(...args),
filterNotes: async (app, ...args) => await app.filterNotes(...args),
saveFile: async (app, ...args) => {
try {
let { name, data } = args[0];
return data.startsWith("data:") && (data = await (await fetch(data)).blob()), await app.saveFile(data, name);
} catch (e) {
throw e.message;
}
}
};
function createOnEmbedCallHandler(embedCommands = {}, logBlacklistedCommands = []) {
return async function(app, commandName, ...args) {
try {
if (commandName in embedCommands) {
let result = await embedCommands[commandName](app, ...args);
return logBlacklistedCommands.includes(commandName) || console.log("onEmbedCall:", commandName, args, result), result;
}
} catch (e) {
throw app.alert("Error:", e.message || e), console.error("onEmbedCall:", commandName, args, e), e;
}
throw new Error(`Unknown command: ${commandName}`);
};
}
init_process();
init_process();
var package_default = {
name: "amplenote-plugin-dev-env",
author: "debajandhar12",
version: "1.0.0",
type: "module",
repository: "https://github.com/debanjandhar12/my-amplenote-plugins-v2",
dependencies: {
"@ai-sdk/anthropic": "1.2.10",
"@ai-sdk/fireworks": "0.2.13",
"@ai-sdk/google": "1.2.14",
"@ai-sdk/groq": "1.2.8",
"@ai-sdk/openai": "1.3.21",
"@assistant-ui/react": "0.7.65",
"@assistant-ui/react-markdown": "0.7.16",
"@debanjandhar12/markmap-lib": "0.17.0-mod.3",
"@debanjandhar12/markmap-toolbar": "0.17.0-mod.3",
"@debanjandhar12/markmap-view": "0.17.0-mod.3",
"@duckdb/duckdb-wasm": "1.31.0",
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@huggingface/transformers": "3.7.3",
"@omnivore-app/api": "^1.0.4",
"@pinecone-database/pinecone": "4.1.0",
"@radix-ui/react-icons": "1.3.2",
"@radix-ui/themes": "3.2.0",
"@yiuayiu/telegram-markdown-escape": "^0.0.2-1",
ai: "4.3.13",
"apache-arrow": "^20.0.0",
"async-mutex": "0.5.0",
"chart.js": "^4.4.3",
"d3-svg-to-png": "^0.3.1",
"date-fns": "^3.6.0",
dayjs: "1.11.13",
"easy-web-worker": "7.0.2",
"emoji-mart": "^5.6.0",
"fast-dotproduct": "1.3.0",
fflate: "0.8.2",
fparser: "^3.1.0",
"fuse.js": "7.0.0",
idb: "8.0.2",
"iconv-lite": "^0.6.3",
"lodash-es": "^4.17.21",
luxon: "^3.4.4",
"markdown-it": "^14.1.0",
"mdast-util-to-string": "4.0.0",
"my-ample-plugin-external": "1.0.29",
nanoid: "^5.0.7",
"ollama-ai-provider": "1.2.0",
"parquetjs-lite": "^0.8.7",
react: "18.2.0",
"react-dom": "18.2.0",
"react-error-boundary": "5.0.0",
"react-string-diff": "0.2.0",
"react-virtuoso": "4.12.5",
"react-window": "1.8.11",
"remark-frontmatter": "5.0.0",
"remark-gfm": "4.0.0",
"remark-parse": "11.0.0",
"scheduler-polyfill": "1.3.0",
stopword: "3.1.5",
tributejs: "5.1.3",
unified: "11.0.0",
"unist-util-visit": "5.0.0",
"unist-util-visit-parents": "6.0.1",
"vosk-browser": "0.0.8",
zod: "3.23.8"
},
devDependencies: {
"@huggingface/transformers": "3.2.4",
"@playwright/test": "^1.49.1",
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^29.5.0",
"core-js": "^3.38.1",
cors: "^2.8.5",
"cross-fetch": "^4.0.0",
dotenv: "^16.0.3",
esbuild: "0.25.3",
"esbuild-jest2": "0.6.7",
"esbuild-plugin-external-global": "^1.0.1",
"esbuild-plugins-node-modules-polyfill": "1.7.0",
express: "^5.0.1",
"isomorphic-fetch": "^3.0.0",
jest: "^29.5.0",
jsdom: "^24.1.0",
"make-synchronous": "^1.0.0",
"node-fetch": "4.0.0-beta.4",
"p-retry": "6.2.1",
playwright: "^1.49.1",
sinon: "21.0.0",
"jest-allure2-reporter": "2.2.6",
"allure-commandline": "^2.32.0",
open: "^10.2.0"
},
scripts: {
test: "jest --testPathPattern=src-copilot",
"test:watch": "jest --testPathPattern=src-copilot --watch",
"allure:serve": `npx allure generate --single-file ./allure/results --clean -o ./allure/report && node --input-type=module -e "import('open').then(o => o.default('./allure/report/index.html'))"`,
"build:prod": "NODE_ENV=production node esbuild.js $(pwd)/src-copilot",
"build:dev": "node esbuild.js $(pwd)/src-copilot --watch --server"
}
};
var dynamicImportExternalPluginBundle = async (fileName) => {
let packageVersion = package_default.dependencies["my-ample-plugin-external"], pkg = `my-ample-plugin-external/dist/${fileName}`, cdnList = getCDNList(pkg), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, packageVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 1e3)), abortController.signal.aborted)
throw new Error(`Terminating as ${pkg} has already been imported`);
return import(url).then((module2) => {
if (abortController.signal.aborted)
throw new Error(`Terminating as ${pkg} has already been imported`);
return { module: module2, url };
}).catch((e) => {
throw console.warn(`Failed to import ${pkg} from ${cdn}: ${e.message}`), e;
});
});
try {
let result = await Promise.any(importPromises);
abortController.abort();
let module2 = result.module;
if (!module2.versions)
throw new Error(`Failed to import module: ${fileName}. Returned bundle does not have version property.`);
for (let [key, value] of Object.entries(module2.versions))
if (value !== package_default.dependencies[key])
throw new Error(`Failed to import module: ${fileName}. Version mismatch for ${key} (expected: ${package_default.dependencies[key]}, actual: ${value})`);
return console.log(`Imported ${pkg}@${packageVersion} from ${result.url}`), module2.default;
} catch {
throw new Error(`Failed to import ${pkg} from all available CDNs`);
}
}, getJSDeliverBundleUrl = (fileName) => `https://cdn.jsdelivr.net/npm/my-ample-plugin-external@${package_default.dependencies["my-ample-plugin-external"]}/dist/${fileName}`;
var dynamicImportESM = async (pkg, pkgVersion = null) => {
let cdnList = getCDNList(pkg), resolvedVersion = resolvePackageVersion(pkg, pkgVersion), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, resolvedVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 2500)), abortController.signal.aborted)
throw new Error(`Terminating as ${pkg} has already been imported`);
return import(url).then((module2) => {
if (abortController.signal.aborted)
throw new Error(`Terminating as ${pkg} has already been imported`);
return { module: module2, url };
}).catch((e) => {
throw console.warn(`Failed to import ${pkg} from ${cdn}: ${e.message}`), e;
});
});
try {
let result = await Promise.any(importPromises);
return abortController.abort(), console.log(`Imported ${pkg}@${resolvedVersion} from ${result.url}`), result.module;
} catch {
throw new Error(`Failed to import ${pkg} from all available CDNs`);
}
};
function getBasePackage(pkg) {
if (pkg.startsWith("@")) {
let [scope, name] = pkg.split("/");
return `${scope}/${name}`;
}
return pkg.split("/")[0];
}
function resolvePackageVersion(pkg, pkgVersion) {
let basePkg = getBasePackage(pkg), version = pkgVersion || package_default.dependencies[basePkg] || package_default.devDependencies[basePkg] || "latest";
return version.startsWith("^") || version.startsWith("~") ? version.substring(1) : version;
}
function getPackageFolderString(pkg) {
let folders = [];
return pkg.startsWith("@") ? [, , ...folders] = pkg.split("/") : [, ...folders] = pkg.split("/"), folders && folders.length > 0 ? `/${folders.join("/")}` : "";
}
function getCDNList(pkg) {
let basePkg = getBasePackage(pkg);
return basePkg.includes("react") || basePkg.includes("radix") || basePkg.includes("build") || basePkg.includes("dotenv") ? ["https://esm.sh/", "https://legacy.esm.sh/"] : ["https://cdn.jsdelivr.net/npm/", "https://esm.sh/", "https://unpkg.com/"];
}
function buildCDNUrl(cdn, pkg, version) {
let basePkg = getBasePackage(pkg), versionString = version !== "latest" ? `@${version}` : "", folderString = getPackageFolderString(pkg), url = new URL(`${cdn}${basePkg}${versionString}${folderString}`);
if (cdn !== "https://esm.sh/" && (basePkg.includes("react") || basePkg.includes("radix")) && !pkg.endsWith(".css"))
throw new Error(`React based js packages is not supported in ${cdn}`);
if (cdn !== "https://legacy.esm.sh/" && basePkg.includes("build"))
throw new Error(`Build API package is not supported in ${cdn}`);
cdn === "https://esm.sh/" && (basePkg !== "react-dom" && basePkg !== "react" && url.searchParams.set("bundle-deps", !1), !pkg.endsWith(".css") && pkg !== "build" && url.searchParams.set("deps", `react@${package_default.dependencies.react},react-dom@${package_default.dependencies["react-dom"]}`));
let urlString = url.toString();
return cdn === "https://cdn.jsdelivr.net/npm/" && !pkg.endsWith(".css") && (urlString += "/+esm"), urlString;
}
var dynamic_import_esm_default = dynamicImportESM;
async function generateText(model, prompt) {
let { generateText: generateText2 } = await dynamic_import_esm_default("ai");
return await generateText2({
model,
prompt
});
}
init_process();
init_process();
var LLM_API_URL_SETTING = "LLM API URL", LLM_API_KEY_SETTING = "LLM API Key", LLM_MODEL_SETTING = "LLM Model", LLM_MAX_TOKENS_SETTING = "LLM Max Tokens (Optional)";
var USER_PROMPT_LIST_SETTING = "User Prompt List (DO NOT CHANGE MANUALLY)", EMBEDDING_API_URL_SETTING = "Embedding API URL (Optional)", EMBEDDING_API_KEY_SETTING = "Embedding API Key (Optional)", MCP_SERVER_URL_LIST_SETTING = "MCP Server List (Optional)", PINECONE_API_KEY_SETTING = "Pinecone API Key (Optional)";
async function getLLMModel(appSettings) {
let apiUrl = appSettings[LLM_API_URL_SETTING], model = appSettings[LLM_MODEL_SETTING], apiKey = appSettings[LLM_API_KEY_SETTING];
if (!apiUrl || !apiUrl.trim()) throw new Error("API URL is not provided. Please check plugin settings.");
if (!model || !model.trim()) throw new Error("Model is not provided. Please check plugin settings.");
if (apiUrl.endsWith("/chat/completion") && (apiUrl = apiUrl.slice(0, -16)), apiUrl = apiUrl.toLowerCase(), model = model.toLowerCase(), apiUrl.includes("groq")) {
let { createGroq } = await dynamic_import_esm_default("@ai-sdk/groq");
return createGroq({
apiKey,
baseURL: apiUrl
}).languageModel(model);
} else if (apiUrl.includes("localhost")) {
let { createOllama } = await dynamic_import_esm_default("ollama-ai-provider");
return createOllama({
apiKey,
baseURL: apiUrl
}).languageModel(model);
} else if (apiUrl.includes("googleapis")) {
let { createGoogleGenerativeAI: createGoogleGenerativeAI2 } = await dynamic_import_esm_default("@ai-sdk/google");
return createGoogleGenerativeAI2({
apiKey,
baseURL: apiUrl
}).languageModel(model);
} else if (apiUrl.includes("anthropic")) {
let { createAnthropic } = await dynamic_import_esm_default("@ai-sdk/anthropic");
return createAnthropic({
apiKey,
baseURL: apiUrl,
headers: { "anthropic-dangerous-direct-browser-access": "true" }
}).languageModel(model);
} else if (apiUrl.includes("openai") || apiUrl.includes("openrouter")) {
let { createOpenAI: createOpenAI2 } = await dynamic_import_esm_default("@ai-sdk/openai");
return createOpenAI2({
apiKey,
baseURL: apiUrl
}).languageModel(model);
} else if (apiUrl.includes("fireworks")) {
let { createFireworks: createFireworks2 } = await dynamic_import_esm_default("@ai-sdk/fireworks");
return createFireworks2({
apiKey,
baseURL: apiUrl
}).languageModel(model.startsWith("accounts/fireworks/models/") ? model : `accounts/fireworks/models/${model}`);
} else throw new Error("It is likely that incorrect LLM API URL is provided. Please check plugin settings.");
}
init_process();
init_process();
init_process();
init_process();
var remarkGfm, unified, remarkFrontmatter, remarkParse, pipe, pipeWithYaml;
async function parse(markdownText, { yaml = !1 } = {}) {
return (!remarkGfm || !unified || !remarkFrontmatter || !remarkParse) && ([remarkGfm, unified, remarkFrontmatter, remarkParse] = await dynamicImportExternalPluginBundle("remarkBundle.js"), unified = unified.unified, remarkGfm = remarkGfm.default, remarkFrontmatter = remarkFrontmatter.default, remarkParse = remarkParse.default), !pipe && !yaml && (pipe = unified().use(remarkParse).use(remarkGfm)), !pipeWithYaml && yaml && (pipeWithYaml = unified().use(remarkParse).use(remarkGfm).use(remarkFrontmatter, ["yaml"])), await (yaml ? pipeWithYaml : pipe).parse(markdownText);
}
init_process();
init_process();
init_process();
init_process();
var convert = (
function(test) {
if (test == null)
return ok;
if (typeof test == "function")
return castFactory(test);
if (typeof test == "object")
return Array.isArray(test) ? anyFactory(test) : propsFactory(test);
if (typeof test == "string")
return typeFactory(test);
throw new Error("Expected function, string, or object as test");
}
);
function anyFactory(tests) {
let checks = [], index = -1;
for (; ++index < tests.length; )
checks[index] = convert(tests[index]);
return castFactory(any);
function any(...parameters) {
let index2 = -1;
for (; ++index2 < checks.length; )
if (checks[index2].apply(this, parameters)) return !0;
return !1;
}
}
function propsFactory(check) {
let checkAsRecord = (
check
);
return castFactory(all2);
function all2(node2) {
let nodeAsRecord = (
node2
), key;
for (key in check)
if (nodeAsRecord[key] !== checkAsRecord[key]) return !1;
return !0;
}
}
function typeFactory(check) {
return castFactory(type);
function type(node2) {
return node2 && node2.type === check;
}
}
function castFactory(testFunction) {
return check;
function check(value, index, parent) {
return !!(looksLikeANode(value) && testFunction.call(
this,
value,
typeof index == "number" ? index : void 0,
parent || void 0
));
}
}
function ok() {
return !0;
}
function looksLikeANode(value) {
return value !== null && typeof value == "object" && "type" in value;
}
var empty = [], CONTINUE = !0, EXIT = !1, SKIP = "skip";
function visitParents(tree, test, visitor, reverse) {
let check;
typeof test == "function" && typeof visitor != "function" ? (reverse = visitor, visitor = test) : check = test;
let is2 = convert(check), step = reverse ? -1 : 1;
factory(tree, void 0, [])();
function factory(node2, index, parents) {
let value = (
node2 && typeof node2 == "object" ? node2 : {}
);
if (typeof value.type == "string") {
let name = (
typeof value.tagName == "string" ? value.tagName : (
typeof value.name == "string" ? value.name : void 0
)
);
Object.defineProperty(visit, "name", {
value: "node (" + (node2.type + (name ? "<" + name + ">" : "")) + ")"
});
}
return visit;
function visit() {
let result = empty, subresult, offset, grandparents;
if ((!test || is2(node2, index, parents[parents.length - 1] || void 0)) && (result = toResult(visitor(node2, parents)), result[0] === EXIT))
return result;
if ("children" in node2 && node2.children) {
let nodeAsParent = (
node2
);
if (nodeAsParent.children && result[0] !== SKIP)
for (offset = (reverse ? nodeAsParent.children.length : -1) + step, grandparents = parents.concat(nodeAsParent); offset > -1 && offset < nodeAsParent.children.length; ) {
let child = nodeAsParent.children[offset];
if (subresult = factory(child, offset, grandparents)(), subresult[0] === EXIT)
return subresult;
offset = typeof subresult[1] == "number" ? subresult[1] : offset + step;
}
}
return result;
}
}
}
function toResult(value) {
return Array.isArray(value) ? value : typeof value == "number" ? [CONTINUE, value] : value == null ? empty : [value];
}
init_process();
init_process();
var emptyOptions = {};
function toString(value, options) {
let settings = options || emptyOptions, includeImageAlt = typeof settings.includeImageAlt == "boolean" ? settings.includeImageAlt : !0, includeHtml = typeof settings.includeHtml == "boolean" ? settings.includeHtml : !0;
return one(value, includeImageAlt, includeHtml);
}
function one(value, includeImageAlt, includeHtml) {
if (node(value)) {
if ("value" in value)
return value.type === "html" && !includeHtml ? "" : value.value;
if (includeImageAlt && "alt" in value && value.alt)
return value.alt;
if ("children" in value)
return all(value.children, includeImageAlt, includeHtml);
}
return Array.isArray(value) ? all(value, includeImageAlt, includeHtml) : "";
}
function all(values, includeImageAlt, includeHtml) {
let result = [], index = -1;
for (; ++index < values.length; )
result[index] = one(values[index], includeImageAlt, includeHtml);
return result.join("");
}
function node(value) {
return !!(value && typeof value == "object");
}
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis, freeGlobal_default = freeGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self, root = freeGlobal_default || freeSelf || Function("return this")(), root_default = root;
var Symbol2 = root_default.Symbol, Symbol_default = Symbol2;
init_process();
var objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, nativeObjectToString = objectProto.toString, symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = !0;
} catch {
}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
}
var getRawTag_default = getRawTag;
init_process();
var objectProto2 = Object.prototype, nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;
var nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
return value == null ? value === void 0 ? undefinedTag : nullTag : symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;
init_process();
function isObjectLike(value) {
return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;
var symbolTag = "[object Symbol]";
function isSymbol(value) {
return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
}
var isSymbol_default = isSymbol;
init_process();
init_process();
function arrayMap(array, iteratee) {
for (var index = -1, length = array == null ? 0 : array.length, result = Array(length); ++index < length; )
result[index] = iteratee(array[index], index, array);
return result;
}
var arrayMap_default = arrayMap;
init_process();
var isArray = Array.isArray, isArray_default = isArray;
var INFINITY = 1 / 0, symbolProto = Symbol_default ? Symbol_default.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
function baseToString(value) {
if (typeof value == "string")
return value;
if (isArray_default(value))
return arrayMap_default(value, baseToString) + "";
if (isSymbol_default(value))
return symbolToString ? symbolToString.call(value) : "";
var result = value + "";
return result == "0" && 1 / value == -INFINITY ? "-0" : result;
}
var baseToString_default = baseToString;
init_process();
init_process();
init_process();
init_process();
init_process();
var reWhitespace = /\s/;
function trimmedEndIndex(string) {
for (var index = string.length; index-- && reWhitespace.test(string.charAt(index)); )
;
return index;
}
var trimmedEndIndex_default = trimmedEndIndex;
var reTrimStart = /^\s+/;
function baseTrim(string) {
return string && string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "");
}
var baseTrim_default = baseTrim;
init_process();
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;
var NAN = NaN, reIsBadHex = /^[-+]0x[0-9a-f]+$/i, reIsBinary = /^0b[01]+$/i, reIsOctal = /^0o[0-7]+$/i, freeParseInt = parseInt;
function toNumber(value) {
if (typeof value == "number")
return value;
if (isSymbol_default(value))
return NAN;
if (isObject_default(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject_default(other) ? other + "" : other;
}
if (typeof value != "string")
return value === 0 ? value : +value;
value = baseTrim_default(value);
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_default = toNumber;
var INFINITY2 = 1 / 0, MAX_INTEGER = 17976931348623157e292;
function toFinite(value) {
if (!value)
return value === 0 ? value : 0;
if (value = toNumber_default(value), value === INFINITY2 || value === -INFINITY2) {
var sign = value < 0 ? -1 : 1;
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
var toFinite_default = toFinite;
function toInteger(value) {
var result = toFinite_default(value), remainder = result % 1;
return result === result ? remainder ? result - remainder : result : 0;
}
var toInteger_default = toInteger;
init_process();
var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
function isFunction(value) {
if (!isObject_default(value))
return !1;
var tag = baseGetTag_default(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_default = isFunction;
init_process();
var MAX_SAFE_INTEGER = 9007199254740991, reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
var type = typeof value;
return length = length == null ? MAX_SAFE_INTEGER : length, !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
var isIndex_default = isIndex;
init_process();
function eq(value, other) {
return value === other || value !== value && other !== other;
}
var eq_default = eq;
init_process();
init_process();
init_process();
var MAX_SAFE_INTEGER2 = 9007199254740991;
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
}
var isLength_default = isLength;
function isArrayLike(value) {
return value != null && isLength_default(value.length) && !isFunction_default(value);
}
var isArrayLike_default = isArrayLike;
function isIterateeCall(value, index, object) {
if (!isObject_default(object))
return !1;
var type = typeof index;
return (type == "number" ? isArrayLike_default(object) && isIndex_default(index, object.length) : type == "string" && index in object) ? eq_default(object[index], value) : !1;
}
var isIterateeCall_default = isIterateeCall;
init_process();
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var baseUnary_default = baseUnary;
init_process();
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports, freeProcess = moduleExports && freeGlobal_default.process, nodeUtil = function() {
try {
var types = freeModule && freeModule.require && freeModule.require("util").types;
return types || freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch {
}
}(), nodeUtil_default = nodeUtil;
init_process();
function toString2(value) {
return value == null ? "" : baseToString_default(value);
}
var toString_default = toString2;
init_process();
init_process();
function baseSlice(array, start, end) {
var index = -1, length = array.length;
start < 0 && (start = -start > length ? 0 : length + start), end = end > length ? length : end, end < 0 && (end += length), length = start > end ? 0 : end - start >>> 0, start >>>= 0;
for (var result = Array(length); ++index < length; )
result[index] = array[index + start];
return result;
}
var baseSlice_default = baseSlice;
function castSlice(array, start, end) {
var length = array.length;
return end = end === void 0 ? length : end, !start && end >= length ? array : baseSlice_default(array, start, end);
}
var castSlice_default = castSlice;
init_process();
var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = "\\ufe0e\\ufe0f", rsZWJ = "\\u200d", reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]");
function hasUnicode(string) {
return reHasUnicode.test(string);
}
var hasUnicode_default = hasUnicode;
init_process();
init_process();
function asciiToArray(string) {
return string.split("");
}
var asciiToArray_default = asciiToArray;
init_process();
var rsAstralRange2 = "\\ud800-\\udfff", rsComboMarksRange2 = "\\u0300-\\u036f", reComboHalfMarksRange2 = "\\ufe20-\\ufe2f", rsComboSymbolsRange2 = "\\u20d0-\\u20ff", rsComboRange2 = rsComboMarksRange2 + reComboHalfMarksRange2 + rsComboSymbolsRange2, rsVarRange2 = "\\ufe0e\\ufe0f", rsAstral = "[" + rsAstralRange2 + "]", rsCombo = "[" + rsComboRange2 + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange2 + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsZWJ2 = "\\u200d", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange2 + "]?", rsOptJoin = "(?:" + rsZWJ2 + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")", reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
var unicodeToArray_default = unicodeToArray;
function stringToArray(string) {
return hasUnicode_default(string) ? unicodeToArray_default(string) : asciiToArray_default(string);
}
var stringToArray_default = stringToArray;
init_process();
var nativeCeil = Math.ceil, nativeMax = Math.max;
function chunk(array, size, guard) {
(guard ? isIterateeCall_default(array, size, guard) : size === void 0) ? size = 1 : size = nativeMax(toInteger_default(size), 0);
var length = array == null ? 0 : array.length;
if (!length || size < 1)
return [];
for (var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); index < length; )
result[resIndex++] = baseSlice_default(array, index, index += size);
return result;
}
var chunk_default = chunk;
init_process();
function baseProperty(key) {
return function(object) {
return object == null ? void 0 : object[key];
};
}
var baseProperty_default = baseProperty;
init_process();
init_process();
var now = function() {
return root_default.Date.now();
}, now_default = now;
var FUNC_ERROR_TEXT = "Expected a function", nativeMax2 = Math.max, nativeMin = Math.min;
function debounce(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = !1, maxing = !1, trailing = !0;
if (typeof func != "function")
throw new TypeError(FUNC_ERROR_TEXT);
wait = toNumber_default(wait) || 0, isObject_default(options) && (leading = !!options.leading, maxing = "maxWait" in options, maxWait = maxing ? nativeMax2(toNumber_default(options.maxWait) || 0, wait) : maxWait, trailing = "trailing" in options ? !!options.trailing : trailing);
function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
return lastArgs = lastThis = void 0, lastInvokeTime = time, result = func.apply(thisArg, args), result;
}
function leadingEdge(time) {
return lastInvokeTime = time, timerId = setTimeout(timerExpired, wait), leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = now_default();
if (shouldInvoke(time))
return trailingEdge(time);
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
return timerId = void 0, trailing && lastArgs ? invokeFunc(time) : (lastArgs = lastThis = void 0, result);
}
function cancel() {
timerId !== void 0 && clearTimeout(timerId), lastInvokeTime = 0, lastArgs = lastCallTime = lastThis = timerId = void 0;
}
function flush() {
return timerId === void 0 ? result : trailingEdge(now_default());
}
function debounced() {
var time = now_default(), isInvoking = shouldInvoke(time);
if (lastArgs = arguments, lastThis = this, lastCallTime = time, isInvoking) {
if (timerId === void 0)
return leadingEdge(lastCallTime);
if (maxing)
return clearTimeout(timerId), timerId = setTimeout(timerExpired, wait), invokeFunc(lastCallTime);
}
return timerId === void 0 && (timerId = setTimeout(timerExpired, wait)), result;
}
return debounced.cancel = cancel, debounced.flush = flush, debounced;
}
var debounce_default = debounce;
init_process();
init_process();
var regexpTag = "[object RegExp]";
function baseIsRegExp(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == regexpTag;
}
var baseIsRegExp_default = baseIsRegExp;
var nodeIsRegExp = nodeUtil_default && nodeUtil_default.isRegExp, isRegExp = nodeIsRegExp ? baseUnary_default(nodeIsRegExp) : baseIsRegExp_default, isRegExp_default = isRegExp;
init_process();
init_process();
var asciiSize = baseProperty_default("length"), asciiSize_default = asciiSize;
init_process();
var rsAstralRange3 = "\\ud800-\\udfff", rsComboMarksRange3 = "\\u0300-\\u036f", reComboHalfMarksRange3 = "\\ufe20-\\ufe2f", rsComboSymbolsRange3 = "\\u20d0-\\u20ff", rsComboRange3 = rsComboMarksRange3 + reComboHalfMarksRange3 + rsComboSymbolsRange3, rsVarRange3 = "\\ufe0e\\ufe0f", rsAstral2 = "[" + rsAstralRange3 + "]", rsCombo2 = "[" + rsComboRange3 + "]", rsFitz2 = "\\ud83c[\\udffb-\\udfff]", rsModifier2 = "(?:" + rsCombo2 + "|" + rsFitz2 + ")", rsNonAstral2 = "[^" + rsAstralRange3 + "]", rsRegional2 = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair2 = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsZWJ3 = "\\u200d", reOptMod2 = rsModifier2 + "?", rsOptVar2 = "[" + rsVarRange3 + "]?", rsOptJoin2 = "(?:" + rsZWJ3 + "(?:" + [rsNonAstral2, rsRegional2, rsSurrPair2].join("|") + ")" + rsOptVar2 + reOptMod2 + ")*", rsSeq2 = rsOptVar2 + reOptMod2 + rsOptJoin2, rsSymbol2 = "(?:" + [rsNonAstral2 + rsCombo2 + "?", rsCombo2, rsRegional2, rsSurrPair2, rsAstral2].join("|") + ")", reUnicode2 = RegExp(rsFitz2 + "(?=" + rsFitz2 + ")|" + rsSymbol2 + rsSeq2, "g");
function unicodeSize(string) {
for (var result = reUnicode2.lastIndex = 0; reUnicode2.test(string); )
++result;
return result;
}
var unicodeSize_default = unicodeSize;
function stringSize(string) {
return hasUnicode_default(string) ? unicodeSize_default(string) : asciiSize_default(string);
}
var stringSize_default = stringSize;
init_process();
var FUNC_ERROR_TEXT2 = "Expected a function";
function throttle(func, wait, options) {
var leading = !0, trailing = !0;
if (typeof func != "function")
throw new TypeError(FUNC_ERROR_TEXT2);
return isObject_default(options) && (leading = "leading" in options ? !!options.leading : leading, trailing = "trailing" in options ? !!options.trailing : trailing), debounce_default(func, wait, {
leading,
maxWait: wait,
trailing
});
}
var throttle_default = throttle;
init_process();
var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "...", reFlags = /\w*$/;
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION;
if (isObject_default(options)) {
var separator = "separator" in options ? options.separator : separator;
length = "length" in options ? toInteger_default(options.length) : length, omission = "omission" in options ? baseToString_default(options.omission) : omission;
}
string = toString_default(string);
var strLength = string.length;
if (hasUnicode_default(string)) {
var strSymbols = stringToArray_default(string);
strLength = strSymbols.length;
}
if (length >= strLength)
return string;
var end = length - stringSize_default(omission);
if (end < 1)
return omission;
var result = strSymbols ? castSlice_default(strSymbols, 0, end).join("") : string.slice(0, end);
if (separator === void 0)
return result + omission;
if (strSymbols && (end += result.length - end), isRegExp_default(separator)) {
if (string.slice(end).search(separator)) {
var match, substring = result;
for (separator.global || (separator = RegExp(separator.source, toString_default(reFlags.exec(separator)) + "g")), separator.lastIndex = 0; match = separator.exec(substring); )
var newEnd = match.index;
result = result.slice(0, newEnd === void 0 ? end : newEnd);
}
} else if (string.indexOf(baseToString_default(separator), end) != end) {
var index = result.lastIndexOf(separator);
index > -1 && (result = result.slice(0, index));
}
return result + omission;
}
var truncate_default = truncate;
init_process();
var searchResultCache = null, debouncedClearSearchResultCache = debounce_default(() => {
searchResultCache = null, console.log("\u{1F504} Cleared search result cache due to inactivity.");
}, 5 * 60 * 1e3);
async function getExtendedNoteHandleProperties(app, note) {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (!searchResultCache) {
searchResultCache = {};
let isArchivedSearch = await app.filterNotes({ group: "archived" });
isArchivedSearch && (searchResultCache.isArchivedNoteUUIDs = new Set(isArchivedSearch.map((n) => n.uuid))), await delay(1e3);
let isTaskListNoteSearch = await app.filterNotes({ group: "taskLists" });
isTaskListNoteSearch && (searchResultCache.isTaskListNoteUUIDs = new Set(isTaskListNoteSearch.map((n) => n.uuid))), await delay(1e3);
let isSharedByMeSearch = await app.filterNotes({ group: "shared" });
isSharedByMeSearch && (searchResultCache.isSharedByMeNoteUUIDs = new Set(isSharedByMeSearch.map((n) => n.uuid))), await delay(1e3);
let isSharedWithMeSearch = await app.filterNotes({ group: "shareReceived" });
isSharedWithMeSearch && (searchResultCache.isSharedWithMeNoteUUIDs = new Set(isSharedWithMeSearch.map((n) => n.uuid)));
}
return debouncedClearSearchResultCache(), {
isArchived: (_b = (_a = searchResultCache.isArchivedNoteUUIDs) == null ? void 0 : _a.has(note.uuid)) != null ? _b : !1,
isTaskListNote: (_d = (_c = searchResultCache.isTaskListNoteUUIDs) == null ? void 0 : _c.has(note.uuid)) != null ? _d : !1,
isSharedByMe: (_f = (_e = searchResultCache.isSharedByMeNoteUUIDs) == null ? void 0 : _e.has(note.uuid)) != null ? _f : !1,
isSharedWithMe: (_h = (_g = searchResultCache.isSharedWithMeNoteUUIDs) == null ? void 0 : _g.has(note.uuid)) != null ? _h : !1,
isPublished: note.published || !1
};
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
init_process();
init_process();
var exports$2 = {}, _dewExec$2 = !1;
function dew$2() {
if (_dewExec$2) return exports$2;
_dewExec$2 = !0, exports$2.byteLength = byteLength, exports$2.toByteArray = toByteArray, exports$2.fromByteArray = fromByteArray;
for (var lookup = [], revLookup = [], Arr = typeof Uint8Array != "undefined" ? Uint8Array : Array, code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", i = 0, len = code.length; i < len; ++i)
lookup[i] = code[i], revLookup[code.charCodeAt(i)] = i;
revLookup[45] = 62, revLookup[95] = 63;
function getLens(b64) {
var len2 = b64.length;
if (len2 % 4 > 0)
throw new Error("Invalid string. Length must be a multiple of 4");
var validLen = b64.indexOf("=");
validLen === -1 && (validLen = len2);
var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
return [validLen, placeHoldersLen];
}
function byteLength(b64) {
var lens = getLens(b64), validLen = lens[0], placeHoldersLen = lens[1];
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function _byteLength(b64, validLen, placeHoldersLen) {
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function toByteArray(b64) {
var tmp, lens = getLens(b64), validLen = lens[0], placeHoldersLen = lens[1], arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)), curByte = 0, len2 = placeHoldersLen > 0 ? validLen - 4 : validLen, i2;
for (i2 = 0; i2 < len2; i2 += 4)
tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)], arr[curByte++] = tmp >> 16 & 255, arr[curByte++] = tmp >> 8 & 255, arr[curByte++] = tmp & 255;
return placeHoldersLen === 2 && (tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4, arr[curByte++] = tmp & 255), placeHoldersLen === 1 && (tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2, arr[curByte++] = tmp >> 8 & 255, arr[curByte++] = tmp & 255), arr;
}
function tripletToBase64(num) {
return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end) {
for (var tmp, output = [], i2 = start; i2 < end; i2 += 3)
tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255), output.push(tripletToBase64(tmp));
return output.join("");
}
function fromByteArray(uint8) {
for (var tmp, len2 = uint8.length, extraBytes = len2 % 3, parts = [], maxChunkLength = 16383, i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength)
parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
return extraBytes === 1 ? (tmp = uint8[len2 - 1], parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==")) : extraBytes === 2 && (tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1], parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=")), parts.join("");
}
return exports$2;
}
var exports$1 = {}, _dewExec$1 = !1;
function dew$1() {
return _dewExec$1 || (_dewExec$1 = !0, exports$1.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? nBytes - 1 : 0, d = isLE ? -1 : 1, s = buffer[offset + i];
for (i += d, e = s & (1 << -nBits) - 1, s >>= -nBits, nBits += eLen; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8)
;
for (m = e & (1 << -nBits) - 1, e >>= -nBits, nBits += mLen; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8)
;
if (e === 0)
e = 1 - eBias;
else {
if (e === eMax)
return m ? NaN : (s ? -1 : 1) * (1 / 0);
m = m + Math.pow(2, mLen), e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}, exports$1.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, i = isLE ? 0 : nBytes - 1, d = isLE ? 1 : -1, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
for (value = Math.abs(value), isNaN(value) || value === 1 / 0 ? (m = isNaN(value) ? 1 : 0, e = eMax) : (e = Math.floor(Math.log(value) / Math.LN2), value * (c = Math.pow(2, -e)) < 1 && (e--, c *= 2), e + eBias >= 1 ? value += rt / c : value += rt * Math.pow(2, 1 - eBias), value * c >= 2 && (e++, c /= 2), e + eBias >= eMax ? (m = 0, e = eMax) : e + eBias >= 1 ? (m = (value * c - 1) * Math.pow(2, mLen), e = e + eBias) : (m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen), e = 0)); mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8)
;
for (e = e << mLen | m, eLen += mLen; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8)
;
buffer[offset + i - d] |= s * 128;
}), exports$1;
}
var exports2 = {}, _dewExec = !1;
function dew() {
if (_dewExec) return exports2;
_dewExec = !0;
let base64 = dew$2(), ieee754 = dew$1(), customInspectSymbol = typeof Symbol == "function" && typeof Symbol.for == "function" ? Symbol.for("nodejs.util.inspect.custom") : null;
exports2.Buffer = Buffer22, exports2.SlowBuffer = SlowBuffer, exports2.INSPECT_MAX_BYTES = 50;
let K_MAX_LENGTH = 2147483647;
exports2.kMaxLength = K_MAX_LENGTH, Buffer22.TYPED_ARRAY_SUPPORT = typedArraySupport(), !Buffer22.TYPED_ARRAY_SUPPORT && typeof console != "undefined" && typeof console.error == "function" && console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
function typedArraySupport() {
try {
let arr = new Uint8Array(1), proto = {
foo: function() {
return 42;
}
};
return Object.setPrototypeOf(proto, Uint8Array.prototype), Object.setPrototypeOf(arr, proto), arr.foo() === 42;
} catch {
return !1;
}
}
Object.defineProperty(Buffer22.prototype, "parent", {
enumerable: !0,
get: function() {
if (Buffer22.isBuffer(this))
return this.buffer;
}
}), Object.defineProperty(Buffer22.prototype, "offset", {
enumerable: !0,
get: function() {
if (Buffer22.isBuffer(this))
return this.byteOffset;
}
});
function createBuffer(length) {
if (length > K_MAX_LENGTH)
throw new RangeError('The value "' + length + '" is invalid for option "size"');
let buf = new Uint8Array(length);
return Object.setPrototypeOf(buf, Buffer22.prototype), buf;
}
function Buffer22(arg, encodingOrOffset, length) {
if (typeof arg == "number") {
if (typeof encodingOrOffset == "string")
throw new TypeError('The "string" argument must be of type string. Received type number');
return allocUnsafe(arg);
}
return from(arg, encodingOrOffset, length);
}
Buffer22.poolSize = 8192;
function from(value, encodingOrOffset, length) {
if (typeof value == "string")
return fromString(value, encodingOrOffset);
if (ArrayBuffer.isView(value))
return fromArrayView(value);
if (value == null)
throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer) || typeof SharedArrayBuffer != "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer)))
return fromArrayBuffer(value, encodingOrOffset, length);
if (typeof value == "number")
throw new TypeError('The "value" argument must not be of type number. Received type number');
let valueOf = value.valueOf && value.valueOf();
if (valueOf != null && valueOf !== value)
return Buffer22.from(valueOf, encodingOrOffset, length);
let b = fromObject(value);
if (b) return b;
if (typeof Symbol != "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] == "function")
return Buffer22.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
}
Buffer22.from = function(value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length);
}, Object.setPrototypeOf(Buffer22.prototype, Uint8Array.prototype), Object.setPrototypeOf(Buffer22, Uint8Array);
function assertSize(size) {
if (typeof size != "number")
throw new TypeError('"size" argument must be of type number');
if (size < 0)
throw new RangeError('The value "' + size + '" is invalid for option "size"');
}
function alloc(size, fill, encoding) {
return assertSize(size), size <= 0 ? createBuffer(size) : fill !== void 0 ? typeof encoding == "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) : createBuffer(size);
}
Buffer22.alloc = function(size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
return assertSize(size), createBuffer(size < 0 ? 0 : checked(size) | 0);
}
Buffer22.allocUnsafe = function(size) {
return allocUnsafe(size);
}, Buffer22.allocUnsafeSlow = function(size) {
return allocUnsafe(size);
};
function fromString(string, encoding) {
if ((typeof encoding != "string" || encoding === "") && (encoding = "utf8"), !Buffer22.isEncoding(encoding))
throw new TypeError("Unknown encoding: " + encoding);
let length = byteLength(string, encoding) | 0, buf = createBuffer(length), actual = buf.write(string, encoding);
return actual !== length && (buf = buf.slice(0, actual)), buf;
}
function fromArrayLike(array) {
let length = array.length < 0 ? 0 : checked(array.length) | 0, buf = createBuffer(length);
for (let i = 0; i < length; i += 1)
buf[i] = array[i] & 255;
return buf;
}
function fromArrayView(arrayView) {
if (isInstance(arrayView, Uint8Array)) {
let copy = new Uint8Array(arrayView);
return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
}
return fromArrayLike(arrayView);
}
function fromArrayBuffer(array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset)
throw new RangeError('"offset" is outside of buffer bounds');
if (array.byteLength < byteOffset + (length || 0))
throw new RangeError('"length" is outside of buffer bounds');
let buf;
return byteOffset === void 0 && length === void 0 ? buf = new Uint8Array(array) : length === void 0 ? buf = new Uint8Array(array, byteOffset) : buf = new Uint8Array(array, byteOffset, length), Object.setPrototypeOf(buf, Buffer22.prototype), buf;
}
function fromObject(obj) {
if (Buffer22.isBuffer(obj)) {
let len = checked(obj.length) | 0, buf = createBuffer(len);
return buf.length === 0 || obj.copy(buf, 0, 0, len), buf;
}
if (obj.length !== void 0)
return typeof obj.length != "number" || numberIsNaN(obj.length) ? createBuffer(0) : fromArrayLike(obj);
if (obj.type === "Buffer" && Array.isArray(obj.data))
return fromArrayLike(obj.data);
}
function checked(length) {
if (length >= K_MAX_LENGTH)
throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
return length | 0;
}
function SlowBuffer(length) {
return +length != length && (length = 0), Buffer22.alloc(+length);
}
Buffer22.isBuffer = function(b) {
return b != null && b._isBuffer === !0 && b !== Buffer22.prototype;
}, Buffer22.compare = function(a, b) {
if (isInstance(a, Uint8Array) && (a = Buffer22.from(a, a.offset, a.byteLength)), isInstance(b, Uint8Array) && (b = Buffer22.from(b, b.offset, b.byteLength)), !Buffer22.isBuffer(a) || !Buffer22.isBuffer(b))
throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
if (a === b) return 0;
let x = a.length, y = b.length;
for (let i = 0, len = Math.min(x, y); i < len; ++i)
if (a[i] !== b[i]) {
x = a[i], y = b[i];
break;
}
return x < y ? -1 : y < x ? 1 : 0;
}, Buffer22.isEncoding = function(encoding) {
switch (String(encoding).toLowerCase()) {
case "hex":
case "utf8":
case "utf-8":
case "ascii":
case "latin1":
case "binary":
case "base64":
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return !0;
default:
return !1;
}
}, Buffer22.concat = function(list, length) {
if (!Array.isArray(list))
throw new TypeError('"list" argument must be an Array of Buffers');
if (list.length === 0)
return Buffer22.alloc(0);
let i;
if (length === void 0)
for (length = 0, i = 0; i < list.length; ++i)
length += list[i].length;
let buffer = Buffer22.allocUnsafe(length), pos = 0;
for (i = 0; i < list.length; ++i) {
let buf = list[i];
if (isInstance(buf, Uint8Array))
pos + buf.length > buffer.length ? (Buffer22.isBuffer(buf) || (buf = Buffer22.from(buf)), buf.copy(buffer, pos)) : Uint8Array.prototype.set.call(buffer, buf, pos);
else if (Buffer22.isBuffer(buf))
buf.copy(buffer, pos);
else
throw new TypeError('"list" argument must be an Array of Buffers');
pos += buf.length;
}
return buffer;
};
function byteLength(string, encoding) {
if (Buffer22.isBuffer(string))
return string.length;
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer))
return string.byteLength;
if (typeof string != "string")
throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string);
let len = string.length, mustMatch = arguments.length > 2 && arguments[2] === !0;
if (!mustMatch && len === 0) return 0;
let loweredCase = !1;
for (; ; )
switch (encoding) {
case "ascii":
case "latin1":
case "binary":
return len;
case "utf8":
case "utf-8":
return utf8ToBytes(string).length;
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return len * 2;
case "hex":
return len >>> 1;
case "base64":
return base64ToBytes(string).length;
default:
if (loweredCase)
return mustMatch ? -1 : utf8ToBytes(string).length;
encoding = ("" + encoding).toLowerCase(), loweredCase = !0;
}
}
Buffer22.byteLength = byteLength;
function slowToString(encoding, start, end) {
let loweredCase = !1;
if ((start === void 0 || start < 0) && (start = 0), start > this.length || ((end === void 0 || end > this.length) && (end = this.length), end <= 0) || (end >>>= 0, start >>>= 0, end <= start))
return "";
for (encoding || (encoding = "utf8"); ; )
switch (encoding) {
case "hex":
return hexSlice(this, start, end);
case "utf8":
case "utf-8":
return utf8Slice(this, start, end);
case "ascii":
return asciiSlice(this, start, end);
case "latin1":
case "binary":
return latin1Slice(this, start, end);
case "base64":
return base64Slice(this, start, end);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = (encoding + "").toLowerCase(), loweredCase = !0;
}
}
Buffer22.prototype._isBuffer = !0;
function swap(b, n, m) {
let i = b[n];
b[n] = b[m], b[m] = i;
}
Buffer22.prototype.swap16 = function() {
let len = this.length;
if (len % 2 !== 0)
throw new RangeError("Buffer size must be a multiple of 16-bits");
for (let i = 0; i < len; i += 2)
swap(this, i, i + 1);
return this;
}, Buffer22.prototype.swap32 = function() {
let len = this.length;
if (len % 4 !== 0)
throw new RangeError("Buffer size must be a multiple of 32-bits");
for (let i = 0; i < len; i += 4)
swap(this, i, i + 3), swap(this, i + 1, i + 2);
return this;
}, Buffer22.prototype.swap64 = function() {
let len = this.length;
if (len % 8 !== 0)
throw new RangeError("Buffer size must be a multiple of 64-bits");
for (let i = 0; i < len; i += 8)
swap(this, i, i + 7), swap(this, i + 1, i + 6), swap(this, i + 2, i + 5), swap(this, i + 3, i + 4);
return this;
}, Buffer22.prototype.toString = function() {
let length = this.length;
return length === 0 ? "" : arguments.length === 0 ? utf8Slice(this, 0, length) : slowToString.apply(this, arguments);
}, Buffer22.prototype.toLocaleString = Buffer22.prototype.toString, Buffer22.prototype.equals = function(b) {
if (!Buffer22.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
return this === b ? !0 : Buffer22.compare(this, b) === 0;
}, Buffer22.prototype.inspect = function() {
let str = "", max = exports2.INSPECT_MAX_BYTES;
return str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(), this.length > max && (str += " ... "), "<Buffer " + str + ">";
}, customInspectSymbol && (Buffer22.prototype[customInspectSymbol] = Buffer22.prototype.inspect), Buffer22.prototype.compare = function(target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array) && (target = Buffer22.from(target, target.offset, target.byteLength)), !Buffer22.isBuffer(target))
throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target);
if (start === void 0 && (start = 0), end === void 0 && (end = target ? target.length : 0), thisStart === void 0 && (thisStart = 0), thisEnd === void 0 && (thisEnd = this.length), start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length)
throw new RangeError("out of range index");
if (thisStart >= thisEnd && start >= end)
return 0;
if (thisStart >= thisEnd)
return -1;
if (start >= end)
return 1;
if (start >>>= 0, end >>>= 0, thisStart >>>= 0, thisEnd >>>= 0, this === target) return 0;
let x = thisEnd - thisStart, y = end - start, len = Math.min(x, y), thisCopy = this.slice(thisStart, thisEnd), targetCopy = target.slice(start, end);
for (let i = 0; i < len; ++i)
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i], y = targetCopy[i];
break;
}
return x < y ? -1 : y < x ? 1 : 0;
};
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
if (buffer.length === 0) return -1;
if (typeof byteOffset == "string" ? (encoding = byteOffset, byteOffset = 0) : byteOffset > 2147483647 ? byteOffset = 2147483647 : byteOffset < -2147483648 && (byteOffset = -2147483648), byteOffset = +byteOffset, numberIsNaN(byteOffset) && (byteOffset = dir ? 0 : buffer.length - 1), byteOffset < 0 && (byteOffset = buffer.length + byteOffset), byteOffset >= buffer.length) {
if (dir) return -1;
byteOffset = buffer.length - 1;
} else if (byteOffset < 0)
if (dir) byteOffset = 0;
else return -1;
if (typeof val == "string" && (val = Buffer22.from(val, encoding)), Buffer22.isBuffer(val))
return val.length === 0 ? -1 : arrayIndexOf(buffer, val, byteOffset, encoding, dir);
if (typeof val == "number")
return val = val & 255, typeof Uint8Array.prototype.indexOf == "function" ? dir ? Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) : Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) : arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
let indexSize = 1, arrLength = arr.length, valLength = val.length;
if (encoding !== void 0 && (encoding = String(encoding).toLowerCase(), encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le")) {
if (arr.length < 2 || val.length < 2)
return -1;
indexSize = 2, arrLength /= 2, valLength /= 2, byteOffset /= 2;
}
function read(buf, i2) {
return indexSize === 1 ? buf[i2] : buf.readUInt16BE(i2 * indexSize);
}
let i;
if (dir) {
let foundIndex = -1;
for (i = byteOffset; i < arrLength; i++)
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1 && (foundIndex = i), i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else
foundIndex !== -1 && (i -= i - foundIndex), foundIndex = -1;
} else
for (byteOffset + valLength > arrLength && (byteOffset = arrLength - valLength), i = byteOffset; i >= 0; i--) {
let found = !0;
for (let j = 0; j < valLength; j++)
if (read(arr, i + j) !== read(val, j)) {
found = !1;
break;
}
if (found) return i;
}
return -1;
}
Buffer22.prototype.includes = function(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
}, Buffer22.prototype.indexOf = function(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, !0);
}, Buffer22.prototype.lastIndexOf = function(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, !1);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
let remaining = buf.length - offset;
length ? (length = Number(length), length > remaining && (length = remaining)) : length = remaining;
let strLen = string.length;
length > strLen / 2 && (length = strLen / 2);
let i;
for (i = 0; i < length; ++i) {
let parsed = parseInt(string.substr(i * 2, 2), 16);
if (numberIsNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer22.prototype.write = function(string, offset, length, encoding) {
if (offset === void 0)
encoding = "utf8", length = this.length, offset = 0;
else if (length === void 0 && typeof offset == "string")
encoding = offset, length = this.length, offset = 0;
else if (isFinite(offset))
offset = offset >>> 0, isFinite(length) ? (length = length >>> 0, encoding === void 0 && (encoding = "utf8")) : (encoding = length, length = void 0);
else
throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
let remaining = this.length - offset;
if ((length === void 0 || length > remaining) && (length = remaining), string.length > 0 && (length < 0 || offset < 0) || offset > this.length)
throw new RangeError("Attempt to write outside buffer bounds");
encoding || (encoding = "utf8");
let loweredCase = !1;
for (; ; )
switch (encoding) {
case "hex":
return hexWrite(this, string, offset, length);
case "utf8":
case "utf-8":
return utf8Write(this, string, offset, length);
case "ascii":
case "latin1":
case "binary":
return asciiWrite(this, string, offset, length);
case "base64":
return base64Write(this, string, offset, length);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
encoding = ("" + encoding).toLowerCase(), loweredCase = !0;
}
}, Buffer22.prototype.toJSON = function() {
return {
type: "Buffer",
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
function base64Slice(buf, start, end) {
return start === 0 && end === buf.length ? base64.fromByteArray(buf) : base64.fromByteArray(buf.slice(start, end));
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
let res = [], i = start;
for (; i < end; ) {
let firstByte = buf[i], codePoint = null, bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
if (i + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
firstByte < 128 && (codePoint = firstByte);
break;
case 2:
secondByte = buf[i + 1], (secondByte & 192) === 128 && (tempCodePoint = (firstByte & 31) << 6 | secondByte & 63, tempCodePoint > 127 && (codePoint = tempCodePoint));
break;
case 3:
secondByte = buf[i + 1], thirdByte = buf[i + 2], (secondByte & 192) === 128 && (thirdByte & 192) === 128 && (tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63, tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343) && (codePoint = tempCodePoint));
break;
case 4:
secondByte = buf[i + 1], thirdByte = buf[i + 2], fourthByte = buf[i + 3], (secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128 && (tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63, tempCodePoint > 65535 && tempCodePoint < 1114112 && (codePoint = tempCodePoint));
}
}
codePoint === null ? (codePoint = 65533, bytesPerSequence = 1) : codePoint > 65535 && (codePoint -= 65536, res.push(codePoint >>> 10 & 1023 | 55296), codePoint = 56320 | codePoint & 1023), res.push(codePoint), i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
let MAX_ARGUMENTS_LENGTH = 4096;
function decodeCodePointsArray(codePoints) {
let len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH)
return String.fromCharCode.apply(String, codePoints);
let res = "", i = 0;
for (; i < len; )
res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
return res;
}
function asciiSlice(buf, start, end) {
let ret = "";
end = Math.min(buf.length, end);
for (let i = start; i < end; ++i)
ret += String.fromCharCode(buf[i] & 127);
return ret;
}
function latin1Slice(buf, start, end) {
let ret = "";
end = Math.min(buf.length, end);
for (let i = start; i < end; ++i)
ret += String.fromCharCode(buf[i]);
return ret;
}
function hexSlice(buf, start, end) {
let len = buf.length;
(!start || start < 0) && (start = 0), (!end || end < 0 || end > len) && (end = len);
let out = "";
for (let i = start; i < end; ++i)
out += hexSliceLookupTable[buf[i]];
return out;
}
function utf16leSlice(buf, start, end) {
let bytes = buf.slice(start, end), res = "";
for (let i = 0; i < bytes.length - 1; i += 2)
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
return res;
}
Buffer22.prototype.slice = function(start, end) {
let len = this.length;
start = ~~start, end = end === void 0 ? len : ~~end, start < 0 ? (start += len, start < 0 && (start = 0)) : start > len && (start = len), end < 0 ? (end += len, end < 0 && (end = 0)) : end > len && (end = len), end < start && (end = start);
let newBuf = this.subarray(start, end);
return Object.setPrototypeOf(newBuf, Buffer22.prototype), newBuf;
};
function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
}
Buffer22.prototype.readUintLE = Buffer22.prototype.readUIntLE = function(offset, byteLength2, noAssert) {
offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, noAssert || checkOffset(offset, byteLength2, this.length);
let val = this[offset], mul = 1, i = 0;
for (; ++i < byteLength2 && (mul *= 256); )
val += this[offset + i] * mul;
return val;
}, Buffer22.prototype.readUintBE = Buffer22.prototype.readUIntBE = function(offset, byteLength2, noAssert) {
offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, noAssert || checkOffset(offset, byteLength2, this.length);
let val = this[offset + --byteLength2], mul = 1;
for (; byteLength2 > 0 && (mul *= 256); )
val += this[offset + --byteLength2] * mul;
return val;
}, Buffer22.prototype.readUint8 = Buffer22.prototype.readUInt8 = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 1, this.length), this[offset];
}, Buffer22.prototype.readUint16LE = Buffer22.prototype.readUInt16LE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 2, this.length), this[offset] | this[offset + 1] << 8;
}, Buffer22.prototype.readUint16BE = Buffer22.prototype.readUInt16BE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 2, this.length), this[offset] << 8 | this[offset + 1];
}, Buffer22.prototype.readUint32LE = Buffer22.prototype.readUInt32LE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 4, this.length), (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
}, Buffer22.prototype.readUint32BE = Buffer22.prototype.readUInt32BE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 4, this.length), this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
}, Buffer22.prototype.readBigUInt64LE = defineBigIntMethod(function(offset) {
offset = offset >>> 0, validateNumber(offset, "offset");
let first = this[offset], last = this[offset + 7];
(first === void 0 || last === void 0) && boundsError(offset, this.length - 8);
let lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24, hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
return BigInt(lo) + (BigInt(hi) << BigInt(32));
}), Buffer22.prototype.readBigUInt64BE = defineBigIntMethod(function(offset) {
offset = offset >>> 0, validateNumber(offset, "offset");
let first = this[offset], last = this[offset + 7];
(first === void 0 || last === void 0) && boundsError(offset, this.length - 8);
let hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset], lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
return (BigInt(hi) << BigInt(32)) + BigInt(lo);
}), Buffer22.prototype.readIntLE = function(offset, byteLength2, noAssert) {
offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, noAssert || checkOffset(offset, byteLength2, this.length);
let val = this[offset], mul = 1, i = 0;
for (; ++i < byteLength2 && (mul *= 256); )
val += this[offset + i] * mul;
return mul *= 128, val >= mul && (val -= Math.pow(2, 8 * byteLength2)), val;
}, Buffer22.prototype.readIntBE = function(offset, byteLength2, noAssert) {
offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, noAssert || checkOffset(offset, byteLength2, this.length);
let i = byteLength2, mul = 1, val = this[offset + --i];
for (; i > 0 && (mul *= 256); )
val += this[offset + --i] * mul;
return mul *= 128, val >= mul && (val -= Math.pow(2, 8 * byteLength2)), val;
}, Buffer22.prototype.readInt8 = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 1, this.length), this[offset] & 128 ? (255 - this[offset] + 1) * -1 : this[offset];
}, Buffer22.prototype.readInt16LE = function(offset, noAssert) {
offset = offset >>> 0, noAssert || checkOffset(offset, 2, this.length);
let val = this[offset] | this[offset + 1] << 8;
return val & 32768 ? val | 4294901760 : val;
}, Buffer22.prototype.readInt16BE = function(offset, noAssert) {
offset = offset >>> 0, noAssert || checkOffset(offset, 2, this.length);
let val = this[offset + 1] | this[offset] << 8;
return val & 32768 ? val | 4294901760 : val;
}, Buffer22.prototype.readInt32LE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 4, this.length), this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
}, Buffer22.prototype.readInt32BE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 4, this.length), this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
}, Buffer22.prototype.readBigInt64LE = defineBigIntMethod(function(offset) {
offset = offset >>> 0, validateNumber(offset, "offset");
let first = this[offset], last = this[offset + 7];
(first === void 0 || last === void 0) && boundsError(offset, this.length - 8);
let val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
}), Buffer22.prototype.readBigInt64BE = defineBigIntMethod(function(offset) {
offset = offset >>> 0, validateNumber(offset, "offset");
let first = this[offset], last = this[offset + 7];
(first === void 0 || last === void 0) && boundsError(offset, this.length - 8);
let val = (first << 24) +
this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
}), Buffer22.prototype.readFloatLE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 4, this.length), ieee754.read(this, offset, !0, 23, 4);
}, Buffer22.prototype.readFloatBE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 4, this.length), ieee754.read(this, offset, !1, 23, 4);
}, Buffer22.prototype.readDoubleLE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 8, this.length), ieee754.read(this, offset, !0, 52, 8);
}, Buffer22.prototype.readDoubleBE = function(offset, noAssert) {
return offset = offset >>> 0, noAssert || checkOffset(offset, 8, this.length), ieee754.read(this, offset, !1, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer22.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError("Index out of range");
}
Buffer22.prototype.writeUintLE = Buffer22.prototype.writeUIntLE = function(value, offset, byteLength2, noAssert) {
if (value = +value, offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert) {
let maxBytes = Math.pow(2, 8 * byteLength2) - 1;
checkInt(this, value, offset, byteLength2, maxBytes, 0);
}
let mul = 1, i = 0;
for (this[offset] = value & 255; ++i < byteLength2 && (mul *= 256); )
this[offset + i] = value / mul & 255;
return offset + byteLength2;
}, Buffer22.prototype.writeUintBE = Buffer22.prototype.writeUIntBE = function(value, offset, byteLength2, noAssert) {
if (value = +value, offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert) {
let maxBytes = Math.pow(2, 8 * byteLength2) - 1;
checkInt(this, value, offset, byteLength2, maxBytes, 0);
}
let i = byteLength2 - 1, mul = 1;
for (this[offset + i] = value & 255; --i >= 0 && (mul *= 256); )
this[offset + i] = value / mul & 255;
return offset + byteLength2;
}, Buffer22.prototype.writeUint8 = Buffer22.prototype.writeUInt8 = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 1, 255, 0), this[offset] = value & 255, offset + 1;
}, Buffer22.prototype.writeUint16LE = Buffer22.prototype.writeUInt16LE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 2, 65535, 0), this[offset] = value & 255, this[offset + 1] = value >>> 8, offset + 2;
}, Buffer22.prototype.writeUint16BE = Buffer22.prototype.writeUInt16BE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 2, 65535, 0), this[offset] = value >>> 8, this[offset + 1] = value & 255, offset + 2;
}, Buffer22.prototype.writeUint32LE = Buffer22.prototype.writeUInt32LE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 4, 4294967295, 0), this[offset + 3] = value >>> 24, this[offset + 2] = value >>> 16, this[offset + 1] = value >>> 8, this[offset] = value & 255, offset + 4;
}, Buffer22.prototype.writeUint32BE = Buffer22.prototype.writeUInt32BE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 4, 4294967295, 0), this[offset] = value >>> 24, this[offset + 1] = value >>> 16, this[offset + 2] = value >>> 8, this[offset + 3] = value & 255, offset + 4;
};
function wrtBigUInt64LE(buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7);
let lo = Number(value & BigInt(4294967295));
buf[offset++] = lo, lo = lo >> 8, buf[offset++] = lo, lo = lo >> 8, buf[offset++] = lo, lo = lo >> 8, buf[offset++] = lo;
let hi = Number(value >> BigInt(32) & BigInt(4294967295));
return buf[offset++] = hi, hi = hi >> 8, buf[offset++] = hi, hi = hi >> 8, buf[offset++] = hi, hi = hi >> 8, buf[offset++] = hi, offset;
}
function wrtBigUInt64BE(buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7);
let lo = Number(value & BigInt(4294967295));
buf[offset + 7] = lo, lo = lo >> 8, buf[offset + 6] = lo, lo = lo >> 8, buf[offset + 5] = lo, lo = lo >> 8, buf[offset + 4] = lo;
let hi = Number(value >> BigInt(32) & BigInt(4294967295));
return buf[offset + 3] = hi, hi = hi >> 8, buf[offset + 2] = hi, hi = hi >> 8, buf[offset + 1] = hi, hi = hi >> 8, buf[offset] = hi, offset + 8;
}
Buffer22.prototype.writeBigUInt64LE = defineBigIntMethod(function(value, offset = 0) {
return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
}), Buffer22.prototype.writeBigUInt64BE = defineBigIntMethod(function(value, offset = 0) {
return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
}), Buffer22.prototype.writeIntLE = function(value, offset, byteLength2, noAssert) {
if (value = +value, offset = offset >>> 0, !noAssert) {
let limit = Math.pow(2, 8 * byteLength2 - 1);
checkInt(this, value, offset, byteLength2, limit - 1, -limit);
}
let i = 0, mul = 1, sub = 0;
for (this[offset] = value & 255; ++i < byteLength2 && (mul *= 256); )
value < 0 && sub === 0 && this[offset + i - 1] !== 0 && (sub = 1), this[offset + i] = (value / mul >> 0) - sub & 255;
return offset + byteLength2;
}, Buffer22.prototype.writeIntBE = function(value, offset, byteLength2, noAssert) {
if (value = +value, offset = offset >>> 0, !noAssert) {
let limit = Math.pow(2, 8 * byteLength2 - 1);
checkInt(this, value, offset, byteLength2, limit - 1, -limit);
}
let i = byteLength2 - 1, mul = 1, sub = 0;
for (this[offset + i] = value & 255; --i >= 0 && (mul *= 256); )
value < 0 && sub === 0 && this[offset + i + 1] !== 0 && (sub = 1), this[offset + i] = (value / mul >> 0) - sub & 255;
return offset + byteLength2;
}, Buffer22.prototype.writeInt8 = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 1, 127, -128), value < 0 && (value = 255 + value + 1), this[offset] = value & 255, offset + 1;
}, Buffer22.prototype.writeInt16LE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 2, 32767, -32768), this[offset] = value & 255, this[offset + 1] = value >>> 8, offset + 2;
}, Buffer22.prototype.writeInt16BE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 2, 32767, -32768), this[offset] = value >>> 8, this[offset + 1] = value & 255, offset + 2;
}, Buffer22.prototype.writeInt32LE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 4, 2147483647, -2147483648), this[offset] = value & 255, this[offset + 1] = value >>> 8, this[offset + 2] = value >>> 16, this[offset + 3] = value >>> 24, offset + 4;
}, Buffer22.prototype.writeInt32BE = function(value, offset, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkInt(this, value, offset, 4, 2147483647, -2147483648), value < 0 && (value = 4294967295 + value + 1), this[offset] = value >>> 24, this[offset + 1] = value >>> 16, this[offset + 2] = value >>> 8, this[offset + 3] = value & 255, offset + 4;
}, Buffer22.prototype.writeBigInt64LE = defineBigIntMethod(function(value, offset = 0) {
return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
}), Buffer22.prototype.writeBigInt64BE = defineBigIntMethod(function(value, offset = 0) {
return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
});
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError("Index out of range");
if (offset < 0) throw new RangeError("Index out of range");
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkIEEE754(buf, value, offset, 4), ieee754.write(buf, value, offset, littleEndian, 23, 4), offset + 4;
}
Buffer22.prototype.writeFloatLE = function(value, offset, noAssert) {
return writeFloat(this, value, offset, !0, noAssert);
}, Buffer22.prototype.writeFloatBE = function(value, offset, noAssert) {
return writeFloat(this, value, offset, !1, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
return value = +value, offset = offset >>> 0, noAssert || checkIEEE754(buf, value, offset, 8), ieee754.write(buf, value, offset, littleEndian, 52, 8), offset + 8;
}
Buffer22.prototype.writeDoubleLE = function(value, offset, noAssert) {
return writeDouble(this, value, offset, !0, noAssert);
}, Buffer22.prototype.writeDoubleBE = function(value, offset, noAssert) {
return writeDouble(this, value, offset, !1, noAssert);
}, Buffer22.prototype.copy = function(target, targetStart, start, end) {
if (!Buffer22.isBuffer(target)) throw new TypeError("argument should be a Buffer");
if (start || (start = 0), !end && end !== 0 && (end = this.length), targetStart >= target.length && (targetStart = target.length), targetStart || (targetStart = 0), end > 0 && end < start && (end = start), end === start || target.length === 0 || this.length === 0) return 0;
if (targetStart < 0)
throw new RangeError("targetStart out of bounds");
if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
if (end < 0) throw new RangeError("sourceEnd out of bounds");
end > this.length && (end = this.length), target.length - targetStart < end - start && (end = target.length - targetStart + start);
let len = end - start;
return this === target && typeof Uint8Array.prototype.copyWithin == "function" ? this.copyWithin(targetStart, start, end) : Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart), len;
}, Buffer22.prototype.fill = function(val, start, end, encoding) {
if (typeof val == "string") {
if (typeof start == "string" ? (encoding = start, start = 0, end = this.length) : typeof end == "string" && (encoding = end, end = this.length), encoding !== void 0 && typeof encoding != "string")
throw new TypeError("encoding must be a string");
if (typeof encoding == "string" && !Buffer22.isEncoding(encoding))
throw new TypeError("Unknown encoding: " + encoding);
if (val.length === 1) {
let code = val.charCodeAt(0);
(encoding === "utf8" && code < 128 || encoding === "latin1") && (val = code);
}
} else typeof val == "number" ? val = val & 255 : typeof val == "boolean" && (val = Number(val));
if (start < 0 || this.length < start || this.length < end)
throw new RangeError("Out of range index");
if (end <= start)
return this;
start = start >>> 0, end = end === void 0 ? this.length : end >>> 0, val || (val = 0);
let i;
if (typeof val == "number")
for (i = start; i < end; ++i)
this[i] = val;
else {
let bytes = Buffer22.isBuffer(val) ? val : Buffer22.from(val, encoding), len = bytes.length;
if (len === 0)
throw new TypeError('The value "' + val + '" is invalid for argument "value"');
for (i = 0; i < end - start; ++i)
this[i + start] = bytes[i % len];
}
return this;
};
let errors = {};
function E(sym, getMessage, Base) {
errors[sym] = class extends Base {
constructor() {
super(), Object.defineProperty(this, "message", {
value: getMessage.apply(this, arguments),
writable: !0,
configurable: !0
}), this.name = `${this.name} [${sym}]`, this.stack, delete this.name;
}
get code() {
return sym;
}
set code(value) {
Object.defineProperty(this, "code", {
configurable: !0,
enumerable: !0,
value,
writable: !0
});
}
toString() {
return `${this.name} [${sym}]: ${this.message}`;
}
};
}
E("ERR_BUFFER_OUT_OF_BOUNDS", function(name) {
return name ? `${name} is outside of buffer bounds` : "Attempt to access memory outside buffer bounds";
}, RangeError), E("ERR_INVALID_ARG_TYPE", function(name, actual) {
return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
}, TypeError), E("ERR_OUT_OF_RANGE", function(str, range, input) {
let msg = `The value of "${str}" is out of range.`, received = input;
return Number.isInteger(input) && Math.abs(input) > 2 ** 32 ? received = addNumericalSeparator(String(input)) : typeof input == "bigint" && (received = String(input), (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) && (received = addNumericalSeparator(received)), received += "n"), msg += ` It must be ${range}. Received ${received}`, msg;
}, RangeError);
function addNumericalSeparator(val) {
let res = "", i = val.length, start = val[0] === "-" ? 1 : 0;
for (; i >= start + 4; i -= 3)
res = `_${val.slice(i - 3, i)}${res}`;
return `${val.slice(0, i)}${res}`;
}
function checkBounds(buf, offset, byteLength2) {
validateNumber(offset, "offset"), (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) && boundsError(offset, buf.length - (byteLength2 + 1));
}
function checkIntBI(value, min, max, buf, offset, byteLength2) {
if (value > max || value < min) {
let n = typeof min == "bigint" ? "n" : "", range;
throw min === 0 || min === BigInt(0) ? range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}` : range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`, new errors.ERR_OUT_OF_RANGE("value", range, value);
}
checkBounds(buf, offset, byteLength2);
}
function validateNumber(value, name) {
if (typeof value != "number")
throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value);
}
function boundsError(value, length, type) {
throw Math.floor(value) !== value ? (validateNumber(value, type), new errors.ERR_OUT_OF_RANGE("offset", "an integer", value)) : length < 0 ? new errors.ERR_BUFFER_OUT_OF_BOUNDS() : new errors.ERR_OUT_OF_RANGE("offset", `>= 0 and <= ${length}`, value);
}
let INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
if (str = str.split("=")[0], str = str.trim().replace(INVALID_BASE64_RE, ""), str.length < 2) return "";
for (; str.length % 4 !== 0; )
str = str + "=";
return str;
}
function utf8ToBytes(string, units) {
units = units || 1 / 0;
let codePoint, length = string.length, leadSurrogate = null, bytes = [];
for (let i = 0; i < length; ++i) {
if (codePoint = string.charCodeAt(i), codePoint > 55295 && codePoint < 57344) {
if (!leadSurrogate) {
if (codePoint > 56319) {
(units -= 3) > -1 && bytes.push(239, 191, 189);
continue;
} else if (i + 1 === length) {
(units -= 3) > -1 && bytes.push(239, 191, 189);
continue;
}
leadSurrogate = codePoint;
continue;
}
if (codePoint < 56320) {
(units -= 3) > -1 && bytes.push(239, 191, 189), leadSurrogate = codePoint;
continue;
}
codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
} else leadSurrogate && (units -= 3) > -1 && bytes.push(239, 191, 189);
if (leadSurrogate = null, codePoint < 128) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 2048) {
if ((units -= 2) < 0) break;
bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
} else if (codePoint < 65536) {
if ((units -= 3) < 0) break;
bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
} else if (codePoint < 1114112) {
if ((units -= 4) < 0) break;
bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
} else
throw new Error("Invalid code point");
}
return bytes;
}
function asciiToBytes(str) {
let byteArray = [];
for (let i = 0; i < str.length; ++i)
byteArray.push(str.charCodeAt(i) & 255);
return byteArray;
}
function utf16leToBytes(str, units) {
let c, hi, lo, byteArray = [];
for (let i = 0; i < str.length && !((units -= 2) < 0); ++i)
c = str.charCodeAt(i), hi = c >> 8, lo = c % 256, byteArray.push(lo), byteArray.push(hi);
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
let i;
for (i = 0; i < length && !(i + offset >= dst.length || i >= src.length); ++i)
dst[i + offset] = src[i];
return i;
}
function isInstance(obj, type) {
return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
}
function numberIsNaN(obj) {
return obj !== obj;
}
let hexSliceLookupTable = function() {
let alphabet = "0123456789abcdef", table = new Array(256);
for (let i = 0; i < 16; ++i) {
let i16 = i * 16;
for (let j = 0; j < 16; ++j)
table[i16 + j] = alphabet[i] + alphabet[j];
}
return table;
}();
function defineBigIntMethod(fn) {
return typeof BigInt == "undefined" ? BufferBigIntNotDefined : fn;
}
function BufferBigIntNotDefined() {
throw new Error("BigInt not supported");
}
return exports2;
}
var exports22 = dew();
exports22.Buffer;
exports22.SlowBuffer;
exports22.INSPECT_MAX_BYTES;
exports22.kMaxLength;
var Buffer2 = exports22.Buffer, INSPECT_MAX_BYTES = exports22.INSPECT_MAX_BYTES, kMaxLength = exports22.kMaxLength;
function sanitizeText(text) {
return !text || typeof text != "string" ? text : Buffer2.from(text, "utf8").toString("utf8");
}
var Splitter = class {
constructor(maxTokens) {
if (!maxTokens || maxTokens <= 0)
throw new Error("maxTokens must be a positive integer");
this.maxTokens = maxTokens, this.splitRecordList = [], this.noteContent = "", this.noteProperties = {}, this.noteImages = [];
}
_createNewChunk(note, headers, isFirstSplit = !1) {
let lastHeader = headers.length > 0 ? headers[headers.length - 1] : null, lastHeaderText = lastHeader ? toString(lastHeader) : "";
return {
id: note.uuid + "##" + (this.splitRecordList.length + 1).toString().padStart(4, "0"),
actualNoteContentPart: "",
processedNoteContent: "",
noteUUID: note.uuid,
noteTitle: note.name || note.title || "Untitled Note",
noteTags: note.tags || [],
headingAnchor: lastHeaderText ? lastHeaderText.trim().replaceAll(" ", "_") : null,
embedding: [],
...this.noteProperties,
tempData: {
isFirstSplit,
headers,
addedTokenCount: 0,
startOffset: null,
endOffset: null
}
};
}
_getFrontMatter(splitRecord) {
var _a;
let headerHierarchy = ((_a = splitRecord.tempData.headers) == null ? void 0 : _a.length) > 0 ? splitRecord.tempData.headers.map((header) => `${"#".repeat(header.depth)} ${toString(header)}`).join(" > ") : "";
return `---
title: ${truncate_default(splitRecord.noteTitle, { length: 50 })}
` + (splitRecord.tempData.isFirstSplit && splitRecord.noteTags && isArray_default(splitRecord.noteTags) ? `tags: ${splitRecord.noteTags.slice(0, 4).filter((x) => x.length < 10).join(", ")}
` : "") + (headerHierarchy ? `headers: ${truncate_default(headerHierarchy, { length: 64 })}
` : "") + `---
`;
}
async _collectNoteInfo(app, note) {
this.noteContent = await app.getNoteContent({ uuid: note.uuid }), this.noteProperties = await getExtendedNoteHandleProperties(app, note), this.noteImages = await app.getNoteImages({ uuid: note.uuid });
}
_appendContentToChunk(cleanedContent, currentChunk, note, node2) {
var _a, _b;
if (!cleanedContent) return currentChunk;
node2 && node2.position && typeof ((_a = node2.position.start) == null ? void 0 : _a.offset) == "number" && typeof ((_b = node2.position.end) == null ? void 0 : _b.offset) == "number" && (currentChunk.tempData.startOffset === null && (currentChunk.tempData.startOffset = node2.position.start.offset), currentChunk.tempData.endOffset = node2.position.end.offset);
let tokens = this.tokenize(cleanedContent);
for (; tokens.length > 0; ) {
let remainingSpace = this.maxTokens - currentChunk.tempData.addedTokenCount;
if (remainingSpace <= 0) {
this.splitRecordList.push(currentChunk), currentChunk = this._createNewChunk(note, currentChunk.tempData.headers);
continue;
}
let tokensToAdd = tokens.slice(0, remainingSpace);
if (tokensToAdd.length === 0 && tokens.length > 0)
break;
let contentToAdd = tokensToAdd.join("");
currentChunk.processedNoteContent += contentToAdd, currentChunk.tempData.addedTokenCount += tokensToAdd.length, tokens = tokens.slice(tokensToAdd.length);
}
return currentChunk;
}
async splitNote(app, note, rebalanceChunksThreshold = 0.7) {
var _a;
if (note != null && note.vault || (_a = note == null ? void 0 : note.uuid) != null && _a.startsWith("local-")) return [];
if (this.splitRecordList = [], await this._collectNoteInfo(app, note), typeof this.noteContent != "string")
return console.warn(`[Splitter] Note content is not a string for note ${note.uuid}. Skipping chunking.`), [];
if (this.noteContent.length === 0)
return [];
let root2 = await parse(this.noteContent.substring(0, this.maxTokens * 630)), currentChunk = this._createNewChunk(note, [], !0), processedNodeCount = 0, MAX_NODES_TO_PROCESS = 5e4;
return visitParents(root2, (node2, ancestors) => {
var _a2, _b, _c;
if (++processedNodeCount > MAX_NODES_TO_PROCESS)
return console.warn(`[Splitter] Exceeded MAX_NODES_TO_PROCESS for note ${note.uuid}. Halting traversal to prevent performance issues.`), !1;
let parent = ancestors[ancestors.length - 1], currentHeaders = ancestors.filter((a) => a.type === "heading");
if (node2.type === "heading") {
let headersIncludingCurrent = [...currentHeaders, node2];
if (currentChunk.tempData.addedTokenCount > 0)
this.splitRecordList.push(currentChunk), currentChunk = this._createNewChunk(note, headersIncludingCurrent);
else {
let wasFirstSplit = currentChunk.tempData.isFirstSplit;
currentChunk = this._createNewChunk(note, headersIncludingCurrent, wasFirstSplit);
}
let headerText = toString(node2) + `
`;
return currentChunk = this._appendContentToChunk(headerText, currentChunk, note, node2), "skip";
}
if (node2.type === "code" && node2.position && node2.position.end.offset - node2.position.start.offset > this.maxTokens * 6)
return console.warn("[Splitter] Skipping code block due to length", node2), "skip";
if (["root", "paragraph", "listItem"].includes(node2.type))
return "continue";
let cleanedText;
if (node2.type === "image") {
let imageObj = this.noteImages.find((img) => img.src.trim() === node2.url.trim()), alt = ((_a2 = imageObj == null ? void 0 : imageObj.text) == null ? void 0 : _a2.replaceAll(`
`, " ")) || node2.alt || "";
cleanedText = `[Image: ${truncate_default(alt, { length: 128 })}]`;
} else if (node2.type === "link") {
let alt = "";
if (((_b = node2.children) == null ? void 0 : _b.length) > 0)
try {
alt = toString(node2.children[0], { includeHtml: !1 });
} catch {
}
try {
let url = new URL(node2.url);
cleanedText = `[${alt}](${url.origin})\``;
} catch {
cleanedText = `[${alt}](${node2.url})`;
}
} else
try {
cleanedText = toString(node2, { includeHtml: !1 });
} catch {
return console.warn(`[Splitter] Failed to convert node to string for note ${note.uuid}. Skipping chunking.`), "skip";
}
return cleanedText = cleanedText.replace(/\\(?=\n|$)/g, ""), parent && ((_c = parent.children) == null ? void 0 : _c.includes(node2)) && !["text", "inlineCode"].includes(node2.type) && (cleanedText += `
`), cleanedText.endsWith(" ") || cleanedText.endsWith(`
`) || (cleanedText += " "), currentChunk = this._appendContentToChunk(cleanedText, currentChunk, note, node2), "skip";
}), currentChunk.tempData.addedTokenCount > 0 && this.splitRecordList.push(currentChunk), this.splitRecordList.length > 1 && this._rebalanceChunks(rebalanceChunksThreshold), this._enrichChunks(), this.splitRecordList;
}
_rebalanceChunks(rebalanceChunksThreshold) {
if (rebalanceChunksThreshold < 0 || rebalanceChunksThreshold > 1) throw new Error("rebalanceChunksThreshold must be between 0 and 1");
if (this.splitRecordList.length < 2) return;
let rebalancedChunks = [], accumulator = this.splitRecordList[0];
for (let i = 1; i < this.splitRecordList.length; i++) {
let nextChunk = this.splitRecordList[i], combinedTokenCount = accumulator.tempData.addedTokenCount + nextChunk.tempData.addedTokenCount;
combinedTokenCount < this.maxTokens && nextChunk.tempData.addedTokenCount < this.maxTokens * rebalanceChunksThreshold ? (accumulator.processedNoteContent += `
` + nextChunk.processedNoteContent, accumulator.tempData.startOffset != null && nextChunk.tempData.endOffset != null && (accumulator.tempData.endOffset = nextChunk.tempData.endOffset), accumulator.tempData.addedTokenCount = combinedTokenCount + 1) : (rebalancedChunks.push(accumulator), accumulator = nextChunk);
}
rebalancedChunks.push(accumulator), this.splitRecordList = rebalancedChunks;
}
_enrichChunks() {
this.splitRecordList = this.splitRecordList.filter((chunk2) => chunk2.tempData.addedTokenCount > 0), this.splitRecordList.length === 1 && this.splitRecordList[0].processedNoteContent.trim().length === 0 && (this.splitRecordList[0].processedNoteContent = "This note is empty. It does not have any content.");
for (let chunk2 of this.splitRecordList)
chunk2.tempData.startOffset != null && chunk2.tempData.endOffset != null && (chunk2.actualNoteContentPart = this.noteContent.substring(chunk2.tempData.startOffset, chunk2.tempData.endOffset)), chunk2.processedNoteContent = (this._getFrontMatter(chunk2) + chunk2.processedNoteContent).trim(), chunk2.actualNoteContentPart = (chunk2.actualNoteContentPart || chunk2.processedNoteContent).trim(), this._sanitizeRecord(chunk2), delete chunk2.tempData;
}
_sanitizeRecord(record) {
record.processedNoteContent && (record.processedNoteContent = sanitizeText(record.processedNoteContent)), record.actualNoteContentPart && (record.actualNoteContentPart = sanitizeText(record.actualNoteContentPart)), record.noteTitle && (record.noteTitle = sanitizeText(record.noteTitle)), record.headingAnchor && (record.headingAnchor = sanitizeText(record.headingAnchor)), Array.isArray(record.noteTags) && (record.noteTags = record.noteTags.map((tag) => sanitizeText(tag)));
}
tokenize(content) {
return (content.match(/[\w]+|[^\s\w]|\s+/g) || []).flatMap((token) => {
if (token.length <= 12) return [token];
let chunks = [];
for (let i = 0; i < token.length; i += 12)
chunks.push(token.slice(i, i + 12));
return chunks;
});
}
};
init_process();
function getEmbeddingProviderName(app) {
if (!app) throw new Error("app object must be passed to this function");
try {
app.settings[PINECONE_API_KEY_SETTING] && app.settings[PINECONE_API_KEY_SETTING].trim() !== "" && (app.setSetting(EMBEDDING_API_URL_SETTING, "https://api.pinecone.io/embed"), app.settings[EMBEDDING_API_URL_SETTING] = "https://api.pinecone.io/embed", app.setSetting(EMBEDDING_API_KEY_SETTING, app.settings[PINECONE_API_KEY_SETTING]), app.settings[EMBEDDING_API_KEY_SETTING] = app.settings[PINECONE_API_KEY_SETTING], app.setSetting(PINECONE_API_KEY_SETTING, ""));
} catch (e) {
console.error(e);
}
let embedApiUrl = app.settings[EMBEDDING_API_URL_SETTING] || "";
if (embedApiUrl.includes("api.openai.com"))
return "openai";
if (embedApiUrl.includes("googleapis"))
return "google";
if (embedApiUrl.includes("localhost"))
return "ollama";
if (embedApiUrl.includes("fireworks"))
return "fireworks";
if (embedApiUrl.includes("pinecone"))
return "pinecone";
if (embedApiUrl.trim() === "" || embedApiUrl.trim() === "local")
return "local";
throw new Error(`Embedding provider ${embedApiUrl} not supported. Please set correct API URL or keep it empty to use in-browser local embedding model.`);
}
init_process();
(function() {
var t = ["user-blocking", "user-visible", "background"];
class i {
constructor() {
this.t = new MessageChannel(), this.i = this.t.port2, this.l = {}, this.o = 1, this.t.port1.onmessage = (t2) => this.h(t2);
}
u(t2) {
var i2 = this.o++;
return this.l[i2] = t2, this.i.postMessage(i2), i2;
}
p(t2) {
delete this.l[t2];
}
h(t2) {
var i2 = t2.data;
if (i2 in this.l) {
var r2 = this.l[i2];
delete this.l[i2], r2();
}
}
}
function r() {
return r.v || (r.v = new i()), r.v;
}
class s {
constructor(t2, i2, r2) {
r2 === void 0 && (r2 = 0), this.k = t2, this.T = null, this.C = null, this.m = !1, this._(i2, r2);
}
isIdleCallback() {
return this.T === 0;
}
I() {
return this.T === 2;
}
cancel() {
if (!this.m) switch (this.m = !0, this.T) {
case 0:
cancelIdleCallback(this.C);
break;
case 1:
clearTimeout(this.C);
break;
case 2:
r().p(this.C);
break;
default:
throw new TypeError("Unknown CallbackType");
}
}
_(i2, s2) {
if (s2 && s2 > 0) return this.T = 1, void (this.C = setTimeout(() => {
this.P();
}, s2));
if (!t.includes(i2)) throw new TypeError("Invalid task priority : " + i2);
return i2 === "background" && typeof requestIdleCallback == "function" ? (this.T = 0, void (this.C = requestIdleCallback(() => {
this.P();
}))) : typeof MessageChannel == "function" ? (this.T = 2, void (this.C = r().u(() => {
this.P();
}))) : (this.T = 1, void (this.C = setTimeout(() => {
this.P();
})));
}
P() {
this.m || this.k();
}
}
var e = 0;
class n {
constructor() {
this.j = null, this.M = null;
}
isEmpty() {
return this.j == null;
}
push(t2) {
if (typeof t2 != "object") throw new TypeError("Task must be an Object");
t2.A = e++, this.isEmpty() ? (t2.N = null, this.j = t2) : (t2.N = this.M, this.M.O = t2), t2.O = null, this.M = t2;
}
takeNextTask() {
if (this.isEmpty()) return null;
var t2 = this.j;
return this.q(t2), t2;
}
merge(t2, i2) {
if (typeof i2 != "function") throw new TypeError("Must provide a selector function.");
if (t2 == null) throw new Error("sourceQueue cannot be null");
for (var r2 = this.j, s2 = null, e2 = t2.j; e2; ) {
var n2 = e2;
if (e2 = e2.O, i2(n2)) {
for (t2.q(n2); r2 && r2.A < n2.A; ) s2 = r2, r2 = r2.O;
this.D(n2, s2), s2 = n2;
}
}
}
D(t2, i2) {
if (i2 != this.M) {
var r2 = i2 ? i2.O : this.j;
t2.O = r2, r2.N = t2, t2.N = i2, i2 != null ? i2.O = t2 : this.j = t2;
} else this.push(t2);
}
q(t2) {
if (t2 == null) throw new Error("Expected task to be non-null");
t2 === this.j && (this.j = t2.O), t2 === this.M && (this.M = this.M.N), t2.O && (t2.O.N = t2.N), t2.N && (t2.N.O = t2.O);
}
}
class l extends Event {
constructor(i2, r2) {
if (!r2 || !t.includes(r2.previousPriority)) throw new TypeError("Invalid task priority: '" + r2.previousPriority + "'");
super(i2), this.previousPriority = r2.previousPriority;
}
}
class o extends AbortController {
constructor(i2) {
if (i2 === void 0 && (i2 = {}), super(), i2 == null && (i2 = {}), typeof i2 != "object") throw new TypeError("'init' is not an object");
var r2, s2, e2 = i2.priority === void 0 ? "user-visible" : i2.priority;
if (!t.includes(e2)) throw new TypeError("Invalid task priority: '" + e2 + "'");
this.H = e2, this.R = !1, s2 = (r2 = this).signal, Object.defineProperties(s2, { priority: { get: function() {
return r2.H;
}, enumerable: !0 }, onprioritychange: { value: null, writable: !0, enumerable: !0 } }), s2.addEventListener("prioritychange", (t2) => {
s2.onprioritychange && s2.onprioritychange(t2);
});
}
setPriority(i2) {
if (!t.includes(i2)) throw new TypeError("Invalid task priority: " + i2);
if (this.R) throw new DOMException("", "NotAllowedError");
if (this.signal.priority !== i2) {
this.R = !0;
var r2 = this.H;
this.H = i2;
var s2 = new l("prioritychange", { previousPriority: r2 });
this.signal.dispatchEvent(s2), this.R = !1;
}
}
}
self.scheduler === void 0 ? (self.scheduler = new class {
constructor() {
this.S = {}, t.forEach((t2) => {
this.S[t2] = [new n(), new n()];
}), this.U = null, this.W = new WeakMap();
}
yield() {
return this.B(() => {
}, { priority: "user-visible" }, !0);
}
postTask(t2, i2) {
return this.B(t2, i2, !1);
}
B(i2, r2, s2) {
if ((r2 = Object.assign({}, r2)).signal !== void 0) {
if (r2.signal === null || !("aborted" in r2.signal) || typeof r2.signal.addEventListener != "function") return Promise.reject(new TypeError("'signal' is not a valid 'AbortSignal'"));
if (r2.signal && r2.signal.priority && !t.includes(r2.signal.priority)) return Promise.reject(new TypeError("Invalid task priority: '" + r2.signal.priority + "'"));
}
if (r2.priority !== void 0 && (r2.priority === null || !t.includes(r2.priority))) return Promise.reject(new TypeError("Invalid task priority: '" + r2.priority + "'"));
if (r2.delay === void 0 && (r2.delay = 0), r2.delay = Number(r2.delay), r2.delay < 0) return Promise.reject(new TypeError("'delay' must be a positive number."));
var e2 = { callback: i2, options: r2, resolve: null, reject: null, hostCallback: null, abortCallback: null, onTaskCompleted: function() {
this.options.signal && this.abortCallback && (this.options.signal.removeEventListener("abort", this.abortCallback), this.abortCallback = null);
}, onTaskAborted: function() {
this.hostCallback && (this.hostCallback.cancel(), this.hostCallback = null), this.options.signal.removeEventListener("abort", this.abortCallback), this.abortCallback = null, this.reject(this.options.signal.reason);
}, isAborted: function() {
return this.options.signal && this.options.signal.aborted;
}, isContinuation: s2 }, n2 = new Promise((t2, i3) => {
e2.resolve = t2, e2.reject = i3;
});
return this._(e2), n2;
}
_(t2) {
var i2 = t2.options.signal;
if (i2) {
if (i2.aborted) return void t2.reject(i2.reason);
t2.abortCallback = () => {
t2.onTaskAborted();
}, i2.addEventListener("abort", t2.abortCallback);
}
t2.options.delay > 0 ? t2.hostCallback = new s(() => {
t2.hostCallback = null, this.F(t2);
}, null, t2.options.delay) : (this.G(t2), this.J());
}
F(t2) {
this.G(t2), this.U && (this.U.cancel(), this.U = null), this.K();
}
L(t2) {
var i2 = this.W.get(t2);
if (i2 === void 0) throw new Error("Attempting to change priority on an unregistered signal");
if (i2 !== t2.priority) {
for (var r2 = 0; r2 < 2; r2++) this.S[t2.priority][r2].merge(this.S[i2][r2], (i3) => i3.options.signal === t2);
this.W.set(t2, t2.priority);
}
}
K() {
this.U = null, this.V(), this.J();
}
J() {
var { priority: t2 } = this.X();
t2 != null && (t2 !== "background" && this.U && this.U.isIdleCallback() && (this.U.cancel(), this.U = null), this.U || (this.U = new s(() => {
this.K();
}, t2, 0)));
}
G(i2) {
var r2;
if (!t.includes(r2 = i2.options.priority ? i2.options.priority : i2.options.signal && i2.options.signal.priority ? i2.options.signal.priority : "user-visible")) throw new TypeError("Invalid task priority: " + r2);
if (i2.options.signal && i2.options.signal.priority) {
var s2 = i2.options.signal;
this.W.has(s2) || (s2.addEventListener("prioritychange", () => {
this.L(s2);
}), this.W.set(s2, s2.priority));
}
this.S[r2][i2.isContinuation ? 0 : 1].push(i2);
}
V() {
var t2 = null;
do {
var { priority: i2, type: r2 } = this.X();
if (i2 == null) return;
t2 = this.S[i2][r2].takeNextTask();
} while (t2.isAborted());
try {
var s2 = t2.callback();
t2.resolve(s2);
} catch (i3) {
t2.reject(i3);
} finally {
t2.onTaskCompleted();
}
}
X() {
for (var i2 = 0; i2 < t.length; i2++) for (var r2 = t[i2], s2 = 0; s2 < 2; s2++) if (!this.S[r2][s2].isEmpty()) return { priority: r2, type: s2 };
return { priority: null, type: 0 };
}
}(), self.TaskController = o, self.TaskPriorityChangeEvent = l) : self.scheduler.yield || (self.scheduler.yield = function() {
return self.scheduler.postTask(() => {
}, { priority: "user-blocking" });
});
})();
init_process();
init_process();
init_process();
var EmbeddingGeneratorBase = class {
constructor(modelName, costPerMillionToken, isGeneratedEmbeddingNormalized, maxConcurrency = 1) {
__publicField(this, "COST_PER_MILLION_TOKEN", null);
__publicField(this, "MODEL_NAME", null);
__publicField(this, "MAX_CONCURRENCY", null);
__publicField(this, "IS_GENERATED_EMBEDDING_NORMALIZED", null);
this.COST_PER_MILLION_TOKEN = costPerMillionToken, this.MODEL_NAME = modelName, this.IS_GENERATED_EMBEDDING_NORMALIZED = isGeneratedEmbeddingNormalized, this.MAX_CONCURRENCY = maxConcurrency;
}
async generateEmbedding(app, textArray, inputType) {
throw new Error("Not implemented");
}
async getEmbeddingCost(app, textArrayCount) {
if (this.COST_PER_MILLION_TOKEN === null)
throw new Error("Cost per million tokens not set");
return textArrayCount * 512 / 1e6 * this.COST_PER_MILLION_TOKEN;
}
getProcessedTextArray(textArray, inputType, prefixForPassage, prefixForQuery) {
if (typeof textArray == "string" && (textArray = [textArray]), inputType.toLowerCase() === "passage")
textArray = textArray.map((text) => prefixForPassage + text);
else if (inputType.toLowerCase() === "query")
textArray = textArray.map((text) => prefixForQuery + text);
else
throw new Error("Invalid input type");
return textArray;
}
};
var createOpenAI, embedMany, OpenAIEmbeddingGenerator = class extends EmbeddingGeneratorBase {
constructor() {
super("text-embedding-3-small", 0.02, !0, 64);
}
async generateEmbedding(app, textArray, inputType) {
createOpenAI || (createOpenAI = (await dynamic_import_esm_default("@ai-sdk/openai")).createOpenAI), embedMany || (embedMany = (await dynamic_import_esm_default("ai")).embedMany), textArray = this.getProcessedTextArray(
textArray,
inputType,
"",
""
);
let { embeddings } = await embedMany({
model: createOpenAI({
apiKey: app.settings[EMBEDDING_API_KEY_SETTING]
}).embedding(this.MODEL_NAME),
values: textArray
});
return embeddings.map((embedding) => new Float32Array(embedding));
}
};
init_process();
var LocalEmbeddingGenerator_worker_default = `// package.json
var package_default = {
name: "amplenote-plugin-dev-env",
author: "debajandhar12",
version: "1.0.0",
type: "module",
repository: "https://github.com/debanjandhar12/my-amplenote-plugins-v2",
dependencies: {
"@ai-sdk/anthropic": "1.2.10",
"@ai-sdk/fireworks": "0.2.13",
"@ai-sdk/google": "1.2.14",
"@ai-sdk/groq": "1.2.8",
"@ai-sdk/openai": "1.3.21",
"@assistant-ui/react": "0.7.65",
"@assistant-ui/react-markdown": "0.7.16",
"@debanjandhar12/markmap-lib": "0.17.0-mod.3",
"@debanjandhar12/markmap-toolbar": "0.17.0-mod.3",
"@debanjandhar12/markmap-view": "0.17.0-mod.3",
"@duckdb/duckdb-wasm": "1.31.0",
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@huggingface/transformers": "3.7.3",
"@omnivore-app/api": "^1.0.4",
"@pinecone-database/pinecone": "4.1.0",
"@radix-ui/react-icons": "1.3.2",
"@radix-ui/themes": "3.2.0",
"@yiuayiu/telegram-markdown-escape": "^0.0.2-1",
ai: "4.3.13",
"apache-arrow": "^20.0.0",
"async-mutex": "0.5.0",
"chart.js": "^4.4.3",
"d3-svg-to-png": "^0.3.1",
"date-fns": "^3.6.0",
dayjs: "1.11.13",
"easy-web-worker": "7.0.2",
"emoji-mart": "^5.6.0",
"fast-dotproduct": "1.3.0",
fflate: "0.8.2",
fparser: "^3.1.0",
"fuse.js": "7.0.0",
idb: "8.0.2",
"iconv-lite": "^0.6.3",
"lodash-es": "^4.17.21",
luxon: "^3.4.4",
"markdown-it": "^14.1.0",
"mdast-util-to-string": "4.0.0",
"my-ample-plugin-external": "1.0.29",
nanoid: "^5.0.7",
"ollama-ai-provider": "1.2.0",
"parquetjs-lite": "^0.8.7",
react: "18.2.0",
"react-dom": "18.2.0",
"react-error-boundary": "5.0.0",
"react-string-diff": "0.2.0",
"react-virtuoso": "4.12.5",
"react-window": "1.8.11",
"remark-frontmatter": "5.0.0",
"remark-gfm": "4.0.0",
"remark-parse": "11.0.0",
"scheduler-polyfill": "1.3.0",
stopword: "3.1.5",
tributejs: "5.1.3",
unified: "11.0.0",
"unist-util-visit": "5.0.0",
"unist-util-visit-parents": "6.0.1",
"vosk-browser": "0.0.8",
zod: "3.23.8"
},
devDependencies: {
"@huggingface/transformers": "3.2.4",
"@playwright/test": "^1.49.1",
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^29.5.0",
"core-js": "^3.38.1",
cors: "^2.8.5",
"cross-fetch": "^4.0.0",
dotenv: "^16.0.3",
esbuild: "0.25.3",
"esbuild-jest2": "0.6.7",
"esbuild-plugin-external-global": "^1.0.1",
"esbuild-plugins-node-modules-polyfill": "1.7.0",
express: "^5.0.1",
"isomorphic-fetch": "^3.0.0",
jest: "^29.5.0",
jsdom: "^24.1.0",
"make-synchronous": "^1.0.0",
"node-fetch": "4.0.0-beta.4",
"p-retry": "6.2.1",
playwright: "^1.49.1",
sinon: "21.0.0",
"jest-allure2-reporter": "2.2.6",
"allure-commandline": "^2.32.0",
open: "^10.2.0"
},
scripts: {
test: "jest --testPathPattern=src-copilot",
"test:watch": "jest --testPathPattern=src-copilot --watch",
"allure:serve": \`npx allure generate --single-file ./allure/results --clean -o ./allure/report && node --input-type=module -e "import('open').then(o => o.default('./allure/report/index.html'))"\`,
"build:prod": "NODE_ENV=production node esbuild.js $(pwd)/src-copilot",
"build:dev": "node esbuild.js $(pwd)/src-copilot --watch --server"
}
};
// common-utils/dynamic-import-esm.js
var dynamicImportESM = async (pkg, pkgVersion = null) => {
let cdnList = getCDNList(pkg), resolvedVersion = resolvePackageVersion(pkg, pkgVersion), abortController = new AbortController(), importPromises = cdnList.map(async (cdn, index) => {
let url = buildCDNUrl(cdn, pkg, resolvedVersion);
if (index > 0 && await new Promise((resolve) => setTimeout(resolve, 2500)), abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return import(url).then((module) => {
if (abortController.signal.aborted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return { module, url };
}).catch((e) => {
throw console.warn(\`Failed to import \${pkg} from \${cdn}: \${e.message}\`), e;
});
});
try {
let result = await Promise.any(importPromises);
return abortController.abort(), console.log(\`Imported \${pkg}@\${resolvedVersion} from \${result.url}\`), result.module;
} catch {
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
}
};
function getBasePackage(pkg) {
if (pkg.startsWith("@")) {
let [scope, name] = pkg.split("/");
return \`\${scope}/\${name}\`;
}
return pkg.split("/")[0];
}
function resolvePackageVersion(pkg, pkgVersion) {
let basePkg = getBasePackage(pkg), version = pkgVersion || package_default.dependencies[basePkg] || package_default.devDependencies[basePkg] || "latest";
return version.startsWith("^") || version.startsWith("~") ? version.substring(1) : version;
}
function getPackageFolderString(pkg) {
let folders = [];
return pkg.startsWith("@") ? [, , ...folders] = pkg.split("/") : [, ...folders] = pkg.split("/"), folders && folders.length > 0 ? \`/\${folders.join("/")}\` : "";
}
function getCDNList(pkg) {
let basePkg = getBasePackage(pkg);
return basePkg.includes("react") || basePkg.includes("radix") || basePkg.includes("build") || basePkg.includes("dotenv") ? ["https://esm.sh/", "https://legacy.esm.sh/"] : ["https://cdn.jsdelivr.net/npm/", "https://esm.sh/", "https://unpkg.com/"];
}
function buildCDNUrl(cdn, pkg, version) {
let basePkg = getBasePackage(pkg), versionString = version !== "latest" ? \`@\${version}\` : "", folderString = getPackageFolderString(pkg), url = new URL(\`\${cdn}\${basePkg}\${versionString}\${folderString}\`);
if (cdn !== "https://esm.sh/" && (basePkg.includes("react") || basePkg.includes("radix")) && !pkg.endsWith(".css"))
throw new Error(\`React based js packages is not supported in \${cdn}\`);
if (cdn !== "https://legacy.esm.sh/" && basePkg.includes("build"))
throw new Error(\`Build API package is not supported in \${cdn}\`);
cdn === "https://esm.sh/" && (basePkg !== "react-dom" && basePkg !== "react" && url.searchParams.set("bundle-deps", !1), !pkg.endsWith(".css") && pkg !== "build" && url.searchParams.set("deps", \`react@\${package_default.dependencies.react},react-dom@\${package_default.dependencies["react-dom"]}\`));
let urlString = url.toString();
return cdn === "https://cdn.jsdelivr.net/npm/" && !pkg.endsWith(".css") && (urlString += "/+esm"), urlString;
}
var dynamic_import_esm_default = dynamicImportESM;
// src-copilot/CopilotDB/embeddings/LocalEmbeddingGenerator.worker.js
var embeddingPipe, embeddingPipeModel, mutex;
onmessage = async (e) => {
let { messageId, textArray, model, webGpuAvailable } = e.data;
try {
let result = await generateEmbedding(textArray, { model, webGpuAvailable });
postMessage({ messageId, result });
} catch (err) {
postMessage({ messageId, error: err.toString() });
}
};
async function generateEmbedding(textArray, opts) {
if (!mutex) {
let asyncMutexPkg = await dynamic_import_esm_default("async-mutex");
mutex = new asyncMutexPkg.Mutex();
}
let release = await mutex.acquire();
if (!embeddingPipe || embeddingPipeModel !== opts.model) {
let huggingfacePkg = await dynamic_import_esm_default("@huggingface/transformers");
huggingfacePkg.env.useWorker = !1;
let pipeline = huggingfacePkg.pipeline;
embeddingPipe = await pipeline("feature-extraction", opts.model, {
dtype: opts.webGpuAvailable ? "fp16" : "q8",
device: opts.webGpuAvailable ? "webgpu" : "wasm"
}), embeddingPipeModel = opts.model;
}
let output = await embeddingPipe(textArray, {
pooling: "mean",
normalize: !0,
truncate: !0,
max_length: 1280
});
release();
let [batchSize, embeddingDim] = output.dims;
return Array.from(
{ length: batchSize },
(_, i) => output.data.slice(i * embeddingDim, (i + 1) * embeddingDim)
);
}
`;
init_process();
function createWorkerFromString(workerCode) {
try {
let blob = new Blob([workerCode], { type: "application/javascript" });
return new Worker(URL.createObjectURL(blob), { type: "module" });
} catch {
let dataURL = `data:application/javascript;base64,${btoa(workerCode)}`;
return new Worker(dataURL, { type: "module" });
}
}
var LocalEmbeddingGenerator = class extends EmbeddingGeneratorBase {
constructor() {
super("Xenova/jina-embeddings-v2-small-en", 0, !0, Math.max((navigator == null ? void 0 : navigator.hardwareConcurrency) - 2 || 1, 1));
}
async generateEmbedding(app, textArray, inputType) {
let embeddings;
return await scheduler.postTask(async () => {
await LocalEmbeddingWorkerManager.initLocalEmbeddingWorker(), textArray = this.getProcessedTextArray(
textArray,
inputType,
"",
""
), embeddings = await LocalEmbeddingWorkerManager.generateEmbeddingUsingWorker(textArray, this.MODEL_NAME);
}, { priority: "user-visible" }), embeddings;
}
async isWebGpuAvailable() {
try {
window.gpuAdapter == null && navigator.gpu && (window.gpuAdapter = await navigator.gpu.requestAdapter() || !1);
} catch {
}
return window.gpuAdapter !== !1 && window.gpuAdapter !== null && window.gpuAdapter !== void 0 && window.gpuAdapter.features.has("shader-f16");
}
}, _LocalEmbeddingWorkerManager = class _LocalEmbeddingWorkerManager {
static isWorkerSupported() {
return window.Worker;
}
static initLocalEmbeddingWorker() {
if (!_LocalEmbeddingWorkerManager.embeddingWorker) {
if (!_LocalEmbeddingWorkerManager.isWorkerSupported())
throw new Error("Worker is not supported in current browser. It is required for local embedding. Please use a different embedding provider.");
_LocalEmbeddingWorkerManager.embeddingWorker = createWorkerFromString(LocalEmbeddingGenerator_worker_default), _LocalEmbeddingWorkerManager.embeddingWorker.onmessage = (event) => {
let { messageId, error, result } = event.data;
if (_LocalEmbeddingWorkerManager.messagePromises.has(messageId)) {
let { resolve, reject } = _LocalEmbeddingWorkerManager.messagePromises.get(messageId);
error ? reject(new Error(error)) : resolve(result), _LocalEmbeddingWorkerManager.messagePromises.delete(messageId);
}
};
}
}
static async generateEmbeddingUsingWorker(textArray, model) {
_LocalEmbeddingWorkerManager.embeddingWorker || _LocalEmbeddingWorkerManager.initLocalEmbeddingWorker();
let messageId = Date.now() + Math.random(), promise = new Promise((resolve, reject) => {
_LocalEmbeddingWorkerManager.messagePromises.set(messageId, { resolve, reject });
}), webGpuAvailable = await new LocalEmbeddingGenerator().isWebGpuAvailable();
return _LocalEmbeddingWorkerManager.embeddingWorker.postMessage({
textArray,
model,
webGpuAvailable,
messageId
}), promise;
}
};
__publicField(_LocalEmbeddingWorkerManager, "embeddingWorker", null), __publicField(_LocalEmbeddingWorkerManager, "messagePromises", new Map());
var LocalEmbeddingWorkerManager = _LocalEmbeddingWorkerManager;
init_process();
var createFireworks, embedMany2, FireworksEmbeddingGenerator = class extends EmbeddingGeneratorBase {
constructor() {
super("nomic-ai/nomic-embed-text-v1.5", 8e-3, !1, 64);
}
async generateEmbedding(app, textArray, inputType) {
createFireworks || (createFireworks = (await dynamic_import_esm_default("@ai-sdk/fireworks")).createFireworks), embedMany2 || (embedMany2 = (await dynamic_import_esm_default("ai")).embedMany), textArray = this.getProcessedTextArray(
textArray,
inputType,
"search_query: ",
"search_query: "
);
let { embeddings } = await embedMany2({
model: createFireworks({
apiKey: app.settings[EMBEDDING_API_KEY_SETTING]
}).textEmbeddingModel(this.MODEL_NAME),
values: textArray
});
return embeddings.map((embedding) => new Float32Array(embedding));
}
};
init_process();
var OllamaEmbeddingGenerator = class extends EmbeddingGeneratorBase {
constructor() {
super("jina/jina-embeddings-v2-small-en", 0, !0, 1);
}
async generateEmbedding(app, textArray, inputType) {
let textArrayMod = this.getProcessedTextArray(
textArray,
inputType,
"",
""
), { createOllama } = await dynamic_import_esm_default("ollama-ai-provider"), embeddingModel = createOllama({
basePath: app.settings[EMBEDDING_API_URL_SETTING]
}).embedding("jina/jina-embeddings-v2-small-en", {
pooling: "mean",
normalize: !0,
truncate: !0,
max_length: 1280
}), embeddings = [];
for (let i = 0; i < textArrayMod.length; i++) {
let originalText = textArrayMod[i];
for (let attempts = 1; ; attempts++)
try {
embeddings.push((await embeddingModel.doEmbed({
values: [textArrayMod[i]]
})).embeddings[0]);
break;
} catch (e) {
if (attempts === 6) throw e;
attempts >= 3 && console.log("Failed to embed text, retrying...", originalText);
let currentLength = textArrayMod[i].length;
textArrayMod[i] = textArrayMod[i].substring(0, Math.floor(currentLength * 0.75));
}
}
return embeddings.map((embedding) => new Float32Array(embedding));
}
};
init_process();
var PineconeEmbeddingGenerator = class extends EmbeddingGeneratorBase {
constructor() {
super("llama-text-embed-v2", 0, !0, 64);
}
async generateEmbedding(app, textArray, inputType) {
return textArray = this.getProcessedTextArray(textArray, inputType, "", ""), (await this._fetchWithRetry(app, textArray, inputType)).map((embedding) => new Float32Array(embedding.values));
}
async _fetchWithRetry(app, textArray, inputType) {
try {
return await this._fetchEmbedding(app, textArray, inputType);
} catch (e) {
let errorMessage = (e.message || "").toLowerCase();
if (errorMessage.includes("rate limit") || errorMessage.includes("max embedding tokens") || errorMessage.includes("failed to reach Pinecone"))
return console.warn("Pinecone embedding rate limit error detected. Waiting for 60 seconds...", e), await this._handleRateLimit(), await this._fetchEmbedding(app, textArray, inputType);
throw e;
}
}
async _fetchEmbedding(app, textArray, inputType) {
let res = await fetch("https://api.pinecone.io/embed", {
headers: {
accept: "*/*",
"api-key": app.settings[EMBEDDING_API_KEY_SETTING],
"content-type": "application/json",
"x-pinecone-api-version": "2024-10"
},
body: JSON.stringify({
model: this.MODEL_NAME,
inputs: textArray.map((input) => ({ text: input })),
parameters: {
input_type: inputType.toLowerCase(),
truncate: "END"
}
}),
method: "POST"
});
if (!res.ok) {
let text = await res.text();
throw new Error(text);
}
return (await res.json()).data;
}
async _handleRateLimit() {
await new Promise((resolve) => setTimeout(resolve, 6e4));
}
};
init_process();
var createGoogleGenerativeAI, embedMany3, GoogleEmbeddingGenerator = class extends EmbeddingGeneratorBase {
constructor() {
super("text-embedding-004", 0, !0, 64);
}
async generateEmbedding(app, textArray, inputType) {
createGoogleGenerativeAI || (createGoogleGenerativeAI = (await dynamic_import_esm_default("@ai-sdk/google")).createGoogleGenerativeAI), embedMany3 || (embedMany3 = (await dynamic_import_esm_default("ai")).embedMany), textArray = this.getProcessedTextArray(
textArray,
inputType,
"",
""
);
let { embeddings } = await embedMany3({
model: createGoogleGenerativeAI({
apiKey: app.settings[EMBEDDING_API_KEY_SETTING]
}).textEmbeddingModel(this.MODEL_NAME, {
taskType: inputType.toLowerCase() === "query" ? "RETRIEVAL_QUERY" : "RETRIEVAL_DOCUMENT"
}),
values: textArray
});
return embeddings.map((embedding) => new Float32Array(embedding));
}
};
var EmbeddingGeneratorFactory = class {
static async create(app) {
let embeddingProviderName = getEmbeddingProviderName(app);
switch (embeddingProviderName) {
case "openai":
return new OpenAIEmbeddingGenerator();
case "fireworks":
return new FireworksEmbeddingGenerator();
case "ollama":
return new OllamaEmbeddingGenerator();
case "pinecone":
return new PineconeEmbeddingGenerator();
case "google":
return new GoogleEmbeddingGenerator();
case "local":
return new LocalEmbeddingGenerator();
}
throw new Error(`Embedding provider ${embeddingProviderName} not supported.`);
}
};
init_process();
init_process();
var E_TIMEOUT = new Error("timeout while waiting for mutex to become available"), E_ALREADY_LOCKED = new Error("mutex already locked"), E_CANCELED = new Error("request for lock canceled"), __awaiter$2 = function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}, Semaphore = class {
constructor(_value, _cancelError = E_CANCELED) {
this._value = _value, this._cancelError = _cancelError, this._queue = [], this._weightedWaiters = [];
}
acquire(weight = 1, priority = 0) {
if (weight <= 0)
throw new Error(`invalid weight ${weight}: must be positive`);
return new Promise((resolve, reject) => {
let task = { resolve, reject, weight, priority }, i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
i === -1 && weight <= this._value ? this._dispatchItem(task) : this._queue.splice(i + 1, 0, task);
});
}
runExclusive(callback_1) {
return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {
let [value, release] = yield this.acquire(weight, priority);
try {
return yield callback(value);
} finally {
release();
}
});
}
waitForUnlock(weight = 1, priority = 0) {
if (weight <= 0)
throw new Error(`invalid weight ${weight}: must be positive`);
return this._couldLockImmediately(weight, priority) ? Promise.resolve() : new Promise((resolve) => {
this._weightedWaiters[weight - 1] || (this._weightedWaiters[weight - 1] = []), insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });
});
}
isLocked() {
return this._value <= 0;
}
getValue() {
return this._value;
}
setValue(value) {
this._value = value, this._dispatchQueue();
}
release(weight = 1) {
if (weight <= 0)
throw new Error(`invalid weight ${weight}: must be positive`);
this._value += weight, this._dispatchQueue();
}
cancel() {
this._queue.forEach((entry) => entry.reject(this._cancelError)), this._queue = [];
}
_dispatchQueue() {
for (this._drainUnlockWaiters(); this._queue.length > 0 && this._queue[0].weight <= this._value; )
this._dispatchItem(this._queue.shift()), this._drainUnlockWaiters();
}
_dispatchItem(item) {
let previousValue = this._value;
this._value -= item.weight, item.resolve([previousValue, this._newReleaser(item.weight)]);
}
_newReleaser(weight) {
let called = !1;
return () => {
called || (called = !0, this.release(weight));
};
}
_drainUnlockWaiters() {
if (this._queue.length === 0)
for (let weight = this._value; weight > 0; weight--) {
let waiters = this._weightedWaiters[weight - 1];
waiters && (waiters.forEach((waiter) => waiter.resolve()), this._weightedWaiters[weight - 1] = []);
}
else {
let queuedPriority = this._queue[0].priority;
for (let weight = this._value; weight > 0; weight--) {
let waiters = this._weightedWaiters[weight - 1];
if (!waiters)
continue;
let i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);
(i === -1 ? waiters : waiters.splice(0, i)).forEach((waiter) => waiter.resolve());
}
}
}
_couldLockImmediately(weight, priority) {
return (this._queue.length === 0 || this._queue[0].priority < priority) && weight <= this._value;
}
};
function insertSorted(a, v) {
let i = findIndexFromEnd(a, (other) => v.priority <= other.priority);
a.splice(i + 1, 0, v);
}
function findIndexFromEnd(a, predicate) {
for (let i = a.length - 1; i >= 0; i--)
if (predicate(a[i]))
return i;
return -1;
}
var __awaiter$1 = function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}, Mutex = class {
constructor(cancelError) {
this._semaphore = new Semaphore(1, cancelError);
}
acquire() {
return __awaiter$1(this, arguments, void 0, function* (priority = 0) {
let [, releaser] = yield this._semaphore.acquire(1, priority);
return releaser;
});
}
runExclusive(callback, priority = 0) {
return this._semaphore.runExclusive(() => callback(), 1, priority);
}
isLocked() {
return this._semaphore.isLocked();
}
waitForUnlock(priority = 0) {
return this._semaphore.waitForUnlock(1, priority);
}
release() {
this._semaphore.isLocked() && this._semaphore.release();
}
cancel() {
return this._semaphore.cancel();
}
};
var db, isTerminated = !0, currentCollectionName, lock_count = 0, copilotdb_channel, mutex = new Mutex(), DuckDBConnectionController = class {
static async getCollectionInstance(collectionName, opts = { persistent: !0 }) {
return mutex.runExclusive(async () => {
if (!db) {
let {
AsyncDuckDB,
createWorker,
getJsDelivrBundles,
selectBundle,
ConsoleLogger,
VoidLogger
} = await dynamic_import_esm_default("@duckdb/duckdb-wasm"), JSDELIVR_BUNDLES = getJsDelivrBundles(), bundle = await selectBundle(JSDELIVR_BUNDLES), worker_url = bundle.mainWorker;
if (!worker_url)
throw new Error("Could not determine main duckdb worker URL from bundle.");
let worker = await createWorker(worker_url), logger = new VoidLogger();
db = new AsyncDuckDB(logger, worker), await db.instantiate(bundle.mainModule, bundle.pthreadWorker);
}
if (currentCollectionName === collectionName)
return db;
try {
await db.flushFiles(), await db.dropFiles(), await db.reset();
} catch (e) {
console.log(e);
}
try {
copilotdb_channel.postMessage({ type: "command", message: "forceTerminate" });
} catch {
}
await new Promise((resolve) => setTimeout(resolve, 1e3)), await db.open({
path: opts.persistent ? `opfs://${collectionName}.db` : `./${collectionName}.db`,
accessMode: 3,
filesystem: {
forceFullHTTPReads: !0
},
opfs: { fileHandling: "auto" }
});
let conn = await db.connect();
return await conn.query("SET temp_directory='opfs://tmp'"), await conn.close(), currentCollectionName = collectionName, isTerminated = !1, db;
});
}
static isTerminated() {
return isTerminated;
}
static async forceTerminate() {
if (db) {
lock_count = 0;
try {
await db.flushFiles(), await db.dropFiles(), await db.reset();
} catch (e) {
console.log(e);
}
await db.terminate(), db = null, currentCollectionName = null, isTerminated = !0;
}
}
static async lockAutoTerminate() {
db && (lock_count++, debouncedTerminate.cancel());
}
static async unlockAutoTerminate() {
db && (lock_count = Math.max(0, lock_count - 1), lock_count === 0 && debouncedTerminate());
}
}, debouncedTerminate = debounce_default(() => {
lock_count === 0 && DuckDBConnectionController.forceTerminate();
}, 5 * 60 * 1e3);
try {
copilotdb_channel = new BroadcastChannel("copilot_channel"), copilotdb_channel.onmessage = async (event) => {
event.data && typeof event.data == "object" && event.data.type === "command" && event.data.message === "forceTerminate" && lock_count === 0 && (await DuckDBConnectionController.forceTerminate(), console.log("CopilotDB DuckDBConnectionController forceTerminate called from another tab"));
};
} catch {
}
init_process();
init_process();
var OPFSUtils = class _OPFSUtils {
static async checkSupport() {
if (!navigator.storage || !navigator.storage.getDirectory)
return !1;
try {
await navigator.storage.getDirectory();
} catch {
return !1;
}
return !0;
}
static async askStoragePermission() {
try {
return await navigator.storage.persist();
} catch {
return !1;
}
}
static async isPersisted() {
return !!await navigator.storage.persist();
}
static async getRoot() {
if (!navigator.storage || !navigator.storage.getDirectory) {
let error = new Error("OPFS API not supported in this environment.");
throw console.error(error), error;
}
try {
return await navigator.storage.getDirectory();
} catch (error) {
throw console.error("Error getting OPFS root directory:", error), error;
}
}
static async doesFileExists(fileName) {
if (!fileName || typeof fileName != "string")
return console.warn("Invalid fileName provided to doesFileExists."), !1;
try {
return await (await _OPFSUtils.getRoot()).getFileHandle(fileName, { create: !1 }), !0;
} catch (error) {
if (error.name === "NotFoundError")
return !1;
throw console.error(`Error checking existence of file '${fileName}':`, error), error;
}
}
static async getFileList() {
let fileList = [];
try {
let root2 = await _OPFSUtils.getRoot();
for await (let entry of root2.entries()) {
let [name, handle] = entry;
if (handle.kind === "file")
try {
let file = await handle.getFile();
fileList.push({
fileName: name,
fileSizeMB: Math.round(file.size / 1024 / 1024)
});
} catch (fileError) {
console.warn(`Could not get details for file '${name}':`, fileError);
}
}
return fileList;
} catch (error) {
throw console.error("Error listing files from OPFS root:", error), error;
}
}
static async getRemainingStorageSpace() {
try {
if ("storage" in navigator && "estimate" in navigator.storage) {
let estimate = await navigator.storage.estimate(), usedMB = Math.round((estimate.usage || 0) / 1024 / 1024), quotaMB = Math.round((estimate.quota || 0) / 1024 / 1024), remainingMB = quotaMB - usedMB;
return `Used: ${usedMB}MB, Quota: ${quotaMB}MB, Remaining: ${remainingMB}MB`;
} else
return "Storage estimate not available";
} catch (error) {
return console.error("Error getting storage space:", error), "Error getting storage space";
}
}
static async deleteFile(fileName) {
if (!fileName || typeof fileName != "string")
throw new Error("Invalid fileName provided to deleteFile.");
try {
return await (await _OPFSUtils.getRoot()).removeEntry(fileName), !0;
} catch (error) {
if (error.name === "NotFoundError")
return !1;
throw console.error(`Error deleting file '${fileName}':`, error), error;
}
}
};
init_process();
init_process();
var num123 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], numFas = ["\u06F1", "\u06F2", "\u06F3", "\u06F4", "\u06F5", "\u06F6", "\u06F7", "\u06F8", "\u06F9", "\u06F0"], numKor = ["\uFF10", "\uFF11", "\uFF12", "\uFF13", "\uFF14", "\uFF15", "\uFF16", "\uFF17", "\uFF18", "\uFF19"], numMya = ["\u1040", "\u1041", "\u1042", "\u1043", "\u1044", "\u1045", "\u1046", "\u1047", "\u1048", "\u1049"], numTel = ["\u0C66", "\u0C67", "\u0C68", "\u0C69", "\u0C6A", "\u0C6B", "\u0C6C", "\u0C6D", "\u0C6E", "\u0C6F"], _123 = [...num123, ...numFas, ...numKor, ...numMya, ...numTel];
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
var eng = [
"about",
"after",
"all",
"also",
"am",
"an",
"and",
"another",
"any",
"are",
"as",
"at",
"be",
"because",
"been",
"before",
"being",
"between",
"both",
"but",
"by",
"came",
"can",
"come",
"could",
"did",
"do",
"each",
"for",
"from",
"get",
"got",
"has",
"had",
"he",
"have",
"her",
"here",
"him",
"himself",
"his",
"how",
"if",
"in",
"into",
"is",
"it",
"like",
"make",
"many",
"me",
"might",
"more",
"most",
"much",
"must",
"my",
"never",
"now",
"of",
"on",
"only",
"or",
"other",
"our",
"out",
"over",
"said",
"same",
"should",
"since",
"some",
"still",
"such",
"take",
"than",
"that",
"the",
"their",
"them",
"then",
"there",
"these",
"they",
"this",
"those",
"through",
"to",
"too",
"under",
"up",
"very",
"was",
"way",
"we",
"well",
"were",
"what",
"where",
"which",
"while",
"who",
"with",
"would",
"you",
"your",
"a",
"i"
];
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
init_process();
var _DuckDBNotesManager = class _DuckDBNotesManager {
async _performInit() {
if (!(this.db && !DuckDBConnectionController.isTerminated()))
try {
this.db = await DuckDBConnectionController.getCollectionInstance(_DuckDBNotesManager.dbFileName, { persistent: !0 });
let conn = await this.db.connect();
if (await this._getConfigValue(conn, "COPILOT_DB_INDEX_VERSION") !== String(54) && (await this._resetTables(conn), await this._createTables(conn), await this._setConfigValue(conn, "COPILOT_DB_INDEX_VERSION", 54), await conn.query("CHECKPOINT")), await conn.close(), await OPFSUtils.doesFileExists(`${_DuckDBNotesManager.dbFileName}.db`) === !1)
throw new Error("DuckDB file not created in OPFS after all init operations");
} catch (e) {
throw console.error("DuckDBManager init error:", e), e;
}
}
async _createTables(conn) {
await conn.query(`
CREATE TABLE IF NOT EXISTS user_note_embeddings (
id VARCHAR PRIMARY KEY,
actualNoteContentPart VARCHAR,
embedding FLOAT[],
headingAnchor VARCHAR,
isArchived BOOLEAN,
isPublished BOOLEAN,
isSharedByMe BOOLEAN,
isSharedWithMe BOOLEAN,
isTaskListNote BOOLEAN,
noteTags VARCHAR[],
noteTitle VARCHAR,
noteUUID VARCHAR,
processedNoteContent VARCHAR
)
`), await conn.query(`
CREATE INDEX IF NOT EXISTS idx_user_note_embeddings_uuid ON user_note_embeddings(noteUUID)
`), await conn.query(`
CREATE TABLE IF NOT EXISTS db_config (
key VARCHAR PRIMARY KEY,
value VARCHAR
)
`), await conn.query(`
CREATE INDEX IF NOT EXISTS idx_db_config_key ON db_config(key)
`);
}
async _resetTables(conn) {
try {
await conn.query("DROP TABLE IF EXISTS db_config"), await conn.query("DROP TABLE IF EXISTS user_note_embeddings"), console.log("DuckDBManager resetTables completed");
} catch (e) {
console.error("Error resetting tables:", e);
}
}
async resetDB() {
let conn = await this.db.connect();
await this._resetTables(conn), await this._createTables(conn), await this._setConfigValue(conn, "COPILOT_DB_INDEX_VERSION", 54), await conn.query("CHECKPOINT;"), conn.close(), console.log("CopilotDB resetDB");
}
async getActualNoteCount() {
let conn;
try {
return conn = await this.db.connect(), (await conn.query("SELECT approx_count_distinct(DISTINCT noteUUID)::INTEGER AS count FROM user_note_embeddings")).toArray()[0].count;
} catch (e) {
throw console.error("Failed to get note count in note embeddings:", e), e;
} finally {
conn && await conn.close();
}
}
async putMultipleNoteEmbedding(noteEmbeddingObjArr) {
let errors = [], conn = await this.db.connect();
await conn.query("BEGIN TRANSACTION");
let stmt = await conn.prepare(`
INSERT OR REPLACE INTO user_note_embeddings (
id, actualNoteContentPart, embedding, headingAnchor, isArchived,
isPublished, isSharedByMe, isSharedWithMe, isTaskListNote,
noteTags, noteTitle, noteUUID, processedNoteContent
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
for (let [index, noteEmbeddingObj] of noteEmbeddingObjArr.entries())
try {
if (!noteEmbeddingObj.id)
throw new Error('Note embedding object must have an "id" property.');
if (!noteEmbeddingObj.noteUUID)
throw new Error('Note embedding object must have a "noteUUID" property.');
if (!noteEmbeddingObj.actualNoteContentPart)
throw new Error('Note embedding object must have an "actualNoteContentPart" property.');
if (!noteEmbeddingObj.processedNoteContent)
throw new Error('Note embedding object must have a "processedNoteContent" property.');
if (!noteEmbeddingObj.embedding)
throw new Error('Note embedding object must have an "embedding" property.');
if (typeof noteEmbeddingObj.embedding == "string")
throw new Error('Note embedding object "embedding" property cannot be a string.');
if (noteEmbeddingObj.noteTags && !isArray_default(noteEmbeddingObj.noteTags))
throw new Error('Note embedding object "noteTags" property must be an array of strings.');
(noteEmbeddingObj.embedding instanceof Float32Array || noteEmbeddingObj.embedding instanceof Float64Array) && (noteEmbeddingObj.embedding = Array.from(noteEmbeddingObj.embedding)), await stmt.query(
noteEmbeddingObj.id,
noteEmbeddingObj.actualNoteContentPart,
JSON.stringify(noteEmbeddingObj.embedding),
noteEmbeddingObj.headingAnchor,
noteEmbeddingObj.isArchived,
noteEmbeddingObj.isPublished,
noteEmbeddingObj.isSharedByMe,
noteEmbeddingObj.isSharedWithMe,
noteEmbeddingObj.isTaskListNote,
JSON.stringify(noteEmbeddingObj.noteTags),
noteEmbeddingObj.noteTitle,
noteEmbeddingObj.noteUUID,
noteEmbeddingObj.processedNoteContent
);
} catch (e) {
errors.push({
message: `Failed to process item at index ${index} (id: ${noteEmbeddingObj.id || "N/A"})Error Reason: ${e == null ? void 0 : e.message}`,
cause: e,
item: noteEmbeddingObj
});
}
if (errors.length > 0) {
try {
await conn.query("ROLLBACK"), await stmt.close(), conn.close();
} catch (e) {
console.warn(e);
}
throw errors[0];
}
await conn.query("COMMIT"), await conn.query("CHECKPOINT"), await stmt.close(), conn.close();
}
async searchNoteRecordByRRF(query, embedding, { limit = 10, thresholdSimilarity = 0, isArchived = null, isSharedByMe = null, isSharedWithMe = null, isTaskListNote = null } = {}) {
let conn, stmt;
try {
conn = await this.db.connect();
let conditions = [], params = [];
isArchived !== null && (conditions.push("isArchived = ?"), params.push(isArchived)), isSharedByMe !== null && (conditions.push("isSharedByMe = ?"), params.push(isSharedByMe)), isSharedWithMe !== null && (conditions.push("isSharedWithMe = ?"), params.push(isSharedWithMe)), isTaskListNote !== null && (conditions.push("isTaskListNote = ?"), params.push(isTaskListNote));
let whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "", ftsScanLimit = 128;
if (stmt = await conn.prepare(`
WITH
query_stems AS (
-- 1. Pre-process the search query string
SELECT list_distinct(
list_transform(
list_filter(
string_split(
regexp_replace(
regexp_replace(lower(?), '[^a-z0-9s]', ' ', 'g'),
's+', ' ', 'g'
),
' '
),
word -> word IS NOT NULL AND length(trim(word)) > 1 AND
-- remove stop words
NOT list_contains([${eng.map((word) => `'${word.replace(/'/g, "''")}'`).join(",")}], word) AND
-- only include words with at least one alphabetic character
regexp_matches(word, '[a-z]')
),
x -> stem(x, 'porter')
)
) AS stems
),
-- 2. Get top embedding matches with initial filtering
embed_candidates AS (
SELECT
id,
actualNoteContentPart,
embedding,
headingAnchor,
isSharedByMe,
isSharedWithMe,
isTaskListNote,
noteTags,
noteTitle,
noteUUID,
processedNoteContent,
list_dot_product(embedding, ?) AS embedding_similarity,
ROW_NUMBER() OVER (
ORDER BY
embedding_similarity DESC
) AS embed_rank
FROM
user_note_embeddings ${whereClause}
ORDER BY
embedding_similarity DESC
LIMIT ?
),
-- 3. Calculate document stems for IDF computation
candidate_doc_stems AS (
SELECT
id,
list_distinct(
list_transform(
list_filter(
string_split(
regexp_replace(
regexp_replace(lower(COALESCE(processedNoteContent, '')), '[^a-z0-9s]', ' ', 'g'),
's+', ' ', 'g'
),
' '
),
word -> word IS NOT NULL AND length(trim(word)) > 1 AND
-- remove stop words
NOT list_contains([${eng.map((word) => `'${word.replace(/'/g, "''")}'`).join(",")}], word) AND
-- only include words with at least one alphabetic character
regexp_matches(word, '[a-z]')
),
x -> stem(x, 'porter')
)
) AS doc_stems
FROM
embed_candidates
),
-- 4. Calculate smoothened IDF scores for query terms
candidate_doc_count AS (
SELECT COUNT(*) AS total_docs FROM candidate_doc_stems
),
query_term_idf AS (
SELECT
q.stem,
-- Smoothed IDF formula: log((N + 1.0) / (df + 1.0)) + 1.0
log((cdc.total_docs + 1.0) / (COUNT(cds.id) + 1.0)) + 1.0 AS idf_score
FROM
(SELECT unnest(stems) AS stem FROM query_stems) AS q
CROSS JOIN
candidate_doc_count cdc
LEFT JOIN
candidate_doc_stems cds ON list_contains(cds.doc_stems, q.stem)
GROUP BY
q.stem, cdc.total_docs
),
-- 5. Calculate scores for all candidates
fts_scored AS (
SELECT
ec.*,
cds.doc_stems,
(SELECT stems FROM query_stems) AS query_stems,
COALESCE((
SELECT
SUM(qti.idf_score)
FROM
query_term_idf qti
WHERE
list_contains(cds.doc_stems, qti.stem)
), 0) AS fts_score
FROM
embed_candidates ec
JOIN candidate_doc_stems cds ON ec.id = cds.id
),
-- 6. Calculate Ranks
ranked_scores AS (
SELECT
*,
ROW_NUMBER() OVER (
ORDER BY
fts_score DESC,
embedding_similarity DESC
) as fts_rank
FROM
fts_scored
WHERE
embedding_similarity > ?
),
-- 7. Calculate Final RRF Score
final_scores AS (
SELECT
*,
(
(0.45 * COALESCE(1.0 / (60 + fts_rank), 0)) + (0.55 * COALESCE(1.0 / (60 + embed_rank), 0))
) * (61 / 2) AS similarity
FROM
ranked_scores
)
SELECT
id,
actualNoteContentPart,
embedding,
headingAnchor,
isSharedByMe,
isSharedWithMe,
isTaskListNote,
noteTags,
noteTitle,
noteUUID,
processedNoteContent,
embedding_similarity,
fts_score,
similarity,
-- Debug information
-- doc_stems,
-- query_stems,
-- embed_rank,
-- fts_rank
FROM
final_scores
ORDER BY
similarity DESC
LIMIT ?;
`), (embedding instanceof Float32Array || embedding instanceof Float64Array) && (embedding = Array.from(embedding)), !isArray_default(embedding))
throw new Error("Embedding must be an array of numbers.");
let embeddingStr = JSON.stringify(embedding), jsonResults = (await stmt.query(
truncate_default(query, { length: 128 }),
embeddingStr,
...params,
ftsScanLimit,
thresholdSimilarity,
limit
)).toArray().map((row) => row.toJSON());
return jsonResults.forEach((row) => {
row.embedding && (row.embedding = row.embedding.toArray()), row.embedding instanceof Float32Array || (row.embedding = new Float32Array(row.embedding)), row.noteTags && (row.noteTags = row.noteTags.toArray()), row.doc_stems && (row.doc_stems = row.doc_stems.toArray()), row.query_stems && (row.query_stems = row.query_stems.toArray());
}), jsonResults;
} catch (e) {
throw console.error("Failed to search note embedding:", e), e;
} finally {
stmt && await stmt.close(), conn && await conn.close();
}
}
async deleteNoteRecordByNoteUUIDList(noteUUIDArr) {
if (!noteUUIDArr || noteUUIDArr.length === 0) {
console.log("No note UUIDs provided to delete. Skipping.");
return;
}
let conn;
try {
conn = await this.db.connect();
let stmt = await conn.prepare("DELETE FROM user_note_embeddings WHERE noteUUID IN ?");
await stmt.query(JSON.stringify(noteUUIDArr)), await stmt.close();
} catch (e) {
throw console.error("Failed to delete note embedding:", e), e;
} finally {
conn && await conn.close();
}
}
async deleteNoteRecordByNoteUUIDNotInList(noteUUIDArr) {
if (!noteUUIDArr || noteUUIDArr.length === 0) {
console.log("No note UUIDs provided to keep. Skipping to avoid deleting all records.");
return;
}
let conn;
try {
conn = await this.db.connect();
let stmt = await conn.prepare("DELETE FROM user_note_embeddings WHERE noteUUID NOT IN ?");
await stmt.query(JSON.stringify(noteUUIDArr)), await stmt.close();
} catch (e) {
throw console.error("Failed to delete note embeddings not in list:", e), e;
} finally {
conn && await conn.close();
}
}
async getNotesRecordCount() {
let conn;
try {
return conn = await this.db.connect(), (await conn.query("SELECT COUNT(*)::INTEGER AS count FROM user_note_embeddings")).toArray()[0].count;
} catch (error) {
throw console.error("Failed to get all notes embeddings count:", error), error;
} finally {
conn && await conn.close();
}
}
async _getConfigValue(conn, key) {
let result = null;
try {
let stmt = await conn.prepare("SELECT value FROM db_config WHERE key = ?");
result = await stmt.query(String(key)), await stmt.close();
} catch {
}
let rows = result ? result.toArray() : [];
return rows.length > 0 ? rows[0].value : null;
}
async _setConfigValue(conn, key, value) {
let stmt = await conn.prepare("INSERT OR REPLACE INTO db_config (key, value) VALUES (?, ?)");
await stmt.query(String(key), String(value)), await stmt.close();
}
async getConfigValue(key) {
let conn;
try {
return conn = await this.db.connect(), await this._getConfigValue(conn, key);
} catch (e) {
throw console.error("Failed to get config value:", e), e;
} finally {
conn && await conn.close();
}
}
async setConfigValue(key, value) {
let conn;
try {
conn = await this.db.connect(), await this._setConfigValue(conn, key, value), await conn.query("CHECKPOINT;");
} catch (e) {
throw console.error("Failed to set config value:", e), e;
} finally {
conn && await conn.close();
}
}
static async getInstance() {
return _DuckDBNotesManager._instance || (_DuckDBNotesManager._instance = new _DuckDBNotesManager()), await _DuckDBNotesManager._instance._performInit(), _DuckDBNotesManager._instance;
}
};
__publicField(_DuckDBNotesManager, "_instance", null), __publicField(_DuckDBNotesManager, "dbFileName", "CopilotNotesDB");
var DuckDBNotesManager = _DuckDBNotesManager;
var syncNotes = async (app, sendMessageToEmbed) => {
let syncId = 54 + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
try {
let performanceStartTime = performance.now();
if (!await OPFSUtils.checkSupport())
throw new Error("OPFS is not supported in this browser. It is required for CopilotDB.");
if (!await OPFSUtils.isPersisted() && !await OPFSUtils.askStoragePermission() && !await app.prompt("OPFS is not persisted. The browser may delete the indexed data. For better reliability, it's recommended to enable persistent storage. Do you want to ignore this and continue anyway?", {
inputs: []
}))
return;
sendMessageToEmbed(app, "syncNotesProgress", "Starting sync...");
let dbm = await DuckDBNotesManager.getInstance();
await DuckDBConnectionController.lockAutoTerminate(), await writeLogStats(app, null, 0, 0, dbm, syncId, "start");
let embeddingProviderName = getEmbeddingProviderName(app), embeddingGenerator = await EmbeddingGeneratorFactory.create(app), lastSyncTime = await dbm.getConfigValue("lastSyncTime") || ( new Date(0)).toISOString(), lastPluginUUID = await dbm.getConfigValue("lastPluginUUID"), lastEmbeddingModel = await dbm.getConfigValue("lastEmbeddingModel");
(lastPluginUUID !== app.context.pluginUUID || lastEmbeddingModel !== embeddingGenerator.MODEL_NAME) && (await dbm.resetDB(), lastSyncTime = ( new Date(0)).toISOString());
let allNotes = await app.filterNotes({}), targetNotes = filterAndSortNotes(allNotes, lastSyncTime), noteBatches = chunk_default(targetNotes, 48), totalNoteCount = allNotes.length, processedNoteCount = totalNoteCount - targetNotes.length;
await writeLogStats(app, noteBatches, processedNoteCount, totalNoteCount, dbm, syncId, "progress"), sendMessageToEmbed(app, "syncNotesProgress", "Sanitizing database..."), await scheduler.postTask(async () => {
await dbm.deleteNoteRecordByNoteUUIDNotInList(allNotes.map((note) => note.uuid));
}, { priority: "background" });
for (let [batchIndex, noteBatch] of noteBatches.entries()) {
let batchRecords = [];
if (await scheduler.postTask(async () => {
batchRecords = await processNoteBatch(app, noteBatch, sendMessageToEmbed, processedNoteCount, totalNoteCount);
}, { priority: "background" }), batchIndex === 0 && !await confirmEmbeddingCost(app, embeddingGenerator, batchRecords.length * noteBatches.length * 2, sendMessageToEmbed))
return await DuckDBConnectionController.unlockAutoTerminate(), !1;
await scheduler.postTask(async () => {
await processAndStoreEmbeddings(
app,
batchRecords,
embeddingGenerator,
embeddingProviderName,
dbm,
targetNotes,
sendMessageToEmbed,
processedNoteCount,
totalNoteCount
), processedNoteCount += noteBatch.length, await updateSyncConfigs(dbm, app.context.pluginUUID, embeddingGenerator.MODEL_NAME);
}, { priority: "background" });
}
if (targetNotes.length > 0) {
let lastProcessedNote = targetNotes[targetNotes.length - 1], lastNoteTime = new Date(lastProcessedNote.updated || lastProcessedNote.updatedAt).toISOString();
await dbm.setConfigValue("lastSyncTime", lastNoteTime);
}
return sendMessageToEmbed(app, "syncNotesProgress", `${totalNoteCount}/${totalNoteCount}<br />Sync Completed!`), await writeLogStats(app, noteBatches, processedNoteCount, totalNoteCount, dbm, syncId, "end", performance.now() - performanceStartTime), app.alert("Sync completed!"), DuckDBConnectionController.unlockAutoTerminate(), !0;
} catch (e) {
throw console.error("sync error", e), DuckDBConnectionController.unlockAutoTerminate(), await writeLogStats(app, null, 0, 0, null, syncId, "error", null, e), sendMessageToEmbed(app, "syncNotesProgress", `Error: ${e.message}`), app.alert("Sync failed: " + e.message), e;
}
};
function filterAndSortNotes(allNotes, lastSyncTime) {
return allNotes.filter((note) => {
try {
let parsedCreatedAt = new Date(note.created || note.createdAt), parsedUpdatedAt = new Date(note.updated || note.updatedAt), parsedLastSyncTime = new Date(lastSyncTime);
return parsedCreatedAt == null || parsedUpdatedAt == null ? !0 : parsedUpdatedAt > parsedLastSyncTime || parsedCreatedAt > parsedLastSyncTime;
} catch {
return !0;
}
}).sort((a, b) => {
try {
let aParsedUpdatedAt = new Date(a.updated || a.updatedAt), bParsedUpdatedAt = new Date(b.updated || b.updatedAt);
return aParsedUpdatedAt.toISOString() !== bParsedUpdatedAt.toISOString() ? aParsedUpdatedAt - bParsedUpdatedAt : a.uuid.localeCompare(b.uuid);
} catch {
return -1;
}
});
}
async function processNoteBatch(app, noteBatch, sendMessageToEmbed, processedNoteCount, totalNoteCount) {
let batchRecords = [];
sendMessageToEmbed(
app,
"syncNotesProgress",
`Scanning Notes: ${processedNoteCount}/${totalNoteCount}`
);
for (let [index, note] of noteBatch.entries()) {
let splitResultForNote = await new Splitter(1280).splitNote(app, note);
batchRecords.push(...splitResultForNote);
}
return batchRecords;
}
async function confirmEmbeddingCost(app, embeddingGenerator, recordCount, sendMessageToEmbed) {
await new Promise((resolve) => setTimeout(resolve, 120));
let cost = await embeddingGenerator.getEmbeddingCost(app, recordCount);
return cost > 0 ? (sendMessageToEmbed(app, "syncNotesProgress", "Waiting for user confirmation..."), await app.prompt(`The sync operation will cost $${cost} approximately. Do you want to continue?`, {
inputs: []
})) : !0;
}
async function processAndStoreEmbeddings(app, records, embeddingGenerator, embeddingProviderName, dbm, targetNotes, sendMessageToEmbed, processedNoteCount, totalNoteCount) {
if (records.length === 0) return;
let noteUUIDs = [...new Set(records.map((record) => record.noteUUID))];
await dbm.deleteNoteRecordByNoteUUIDList(noteUUIDs);
let chunkSize = embeddingGenerator.MAX_CONCURRENCY, recordsChunks = chunk_default(records, chunkSize);
for (let [chunkIndex, recordChunk] of recordsChunks.entries()) {
let gpuInfo = embeddingProviderName === "local" ? ` with ${await embeddingGenerator.isWebGpuAvailable() ? "gpu" : "cpu"}` : "", localWarning = embeddingProviderName === "local" ? '<br /><small style="opacity: 0.8;">(\u{1F4A1} Enter embedding api url and key in plugin settings for faster sync)</small>' : "";
sendMessageToEmbed(
app,
"syncNotesProgress",
`Generating Embeddings: ${processedNoteCount + Math.floor(noteUUIDs.length / recordsChunks.length * chunkIndex)}/${totalNoteCount}<br />[using ${embeddingProviderName} embedding${gpuInfo}]${localWarning}`
), (await embeddingGenerator.generateEmbedding(
app,
recordChunk.map((record) => record.processedNoteContent),
"passage"
)).forEach((embedding, index) => {
recordChunk[index].embedding = embedding;
}), await dbm.putMultipleNoteEmbedding(recordChunk);
try {
let lastNoteInChunk = recordChunk[recordChunk.length - 1], note = targetNotes.find((n) => n.uuid === lastNoteInChunk.noteUUID);
if (note) {
let parsedUpdatedAt = new Date(note.updated || note.updatedAt);
parsedUpdatedAt.setSeconds(parsedUpdatedAt.getSeconds() - 1), await dbm.setConfigValue("lastSyncTime", parsedUpdatedAt.toISOString());
}
} catch (e) {
console.error("Error updating last sync time:", e);
}
}
}
async function updateSyncConfigs(dbm, pluginUUID, modelName) {
await dbm.setConfigValue("lastPluginUUID", pluginUUID), await dbm.setConfigValue("lastEmbeddingModel", modelName);
}
async function writeLogStats(app, noteBatches, processedNoteCount, totalNoteCount, dbm, syncId, mode, performanceTime, error) {
try {
let userAgent = navigator.userAgent, pluginUUID = app.context.pluginUUID || "unknown", ramInfo = "Memory info not available", usedJSHeapSize = 0, totalJSHeapSize = 0, jsHeapSizeLimit = 0;
performance.memory && (usedJSHeapSize = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024), totalJSHeapSize = Math.round(performance.memory.totalJSHeapSize / 1024 / 1024), jsHeapSizeLimit = Math.round(performance.memory.jsHeapSizeLimit / 1024 / 1024), ramInfo = `Used: ${usedJSHeapSize}MB, Total: ${totalJSHeapSize}MB, Limit: ${jsHeapSizeLimit}MB`);
let storageSpace = "Storage info not available", isPersisted = !1, fileList = [], duckDBRecordCount = 0, embeddingProviderName = "Unknown";
try {
storageSpace = await OPFSUtils.getRemainingStorageSpace(), isPersisted = await OPFSUtils.isPersisted(), fileList = await OPFSUtils.getFileList(), dbm && (duckDBRecordCount = await dbm.getNotesRecordCount()), embeddingProviderName = getEmbeddingProviderName(app);
} catch {
}
let colors = {
start: "green",
progress: "green",
end: "green",
error: "red"
}, modeText = mode.charAt(0).toUpperCase() + mode.slice(1), details = `Plugin UUID: ${pluginUUID}
User Agent: ${userAgent}
RAM: ${ramInfo}
Embedding Provider: ${embeddingProviderName}
OPFS Storage: ${storageSpace}
OPFS Persisted: ${isPersisted}
OPFS Files: ${JSON.stringify(fileList)}`;
mode === "progress" ? details += `
Progress: ${processedNoteCount}/${totalNoteCount}
Remaining Batches: ${(noteBatches == null ? void 0 : noteBatches.length) || 0}
DuckDB Records: ${duckDBRecordCount}` : mode === "end" ? details += `
DuckDB Records: ${duckDBRecordCount}
Performance: ${performanceTime}ms` : mode === "error" && (details += `
Error: ${(error == null ? void 0 : error.message) || "Unknown error"}
Stack: ${(error == null ? void 0 : error.stack) || "No stack trace"}`), console.log(
`%c=== ${modeText} Sync [${syncId}] ===
%c${details}
%c=====================`,
`color: white; background-color: ${colors[mode]}; font-weight: bold; font-size: 14px; padding: 2px;`,
"color: white; background-color: #333; font-size: 13px; padding: 2px;",
`color: white; background-color: ${colors[mode]}; font-weight: bold; font-size: 14px; padding: 2px;`
);
} catch (error2) {
console.error("Error writing log stats:", error2);
}
}
init_process();
init_process();
var getSyncState = async (app, syncNotesPromise2 = null) => {
if (syncNotesPromise2)
return "Syncing";
let dbm = await DuckDBNotesManager.getInstance();
await DuckDBConnectionController.lockAutoTerminate();
let lastPluginUUID = await dbm.getConfigValue("lastPluginUUID"), lastEmbeddingModel = await dbm.getConfigValue("lastEmbeddingModel"), embeddingGenerator = await EmbeddingGeneratorFactory.create(app);
if (lastPluginUUID !== app.context.pluginUUID || lastEmbeddingModel !== embeddingGenerator.MODEL_NAME)
return DuckDBConnectionController.unlockAutoTerminate(), "Not synced";
if (await dbm.getActualNoteCount() === 0)
return DuckDBConnectionController.unlockAutoTerminate(), "Not synced";
let allNotes = await app.filterNotes({}), lastSyncTime = await dbm.getConfigValue("lastSyncTime") || ( new Date(0)).toISOString(), targetNotes = allNotes.filter((note) => {
try {
let parsedCreatedAt = new Date(note.created || note.createdAt), parsedUpdatedAt = new Date(note.updated || note.updatedAt), parsedLastSyncTime = new Date(lastSyncTime);
return parsedCreatedAt == null || parsedUpdatedAt == null ? !0 : parsedUpdatedAt > parsedLastSyncTime || parsedCreatedAt > parsedLastSyncTime;
} catch {
return !0;
}
});
if (targetNotes.length >= allNotes.length / 2)
return DuckDBConnectionController.unlockAutoTerminate(), "Not synced";
let result = targetNotes.length === 0 ? "Fully Synced" : "Partially synced";
return DuckDBConnectionController.unlockAutoTerminate(), result;
};
var searchNotes = async (app, queryText, queryTextType, {
limit = 64,
isArchived = null,
isSharedByMe = null,
isSharedWithMe = null,
isTaskListNote = null
}) => {
if (await getSyncState(app) === "Not synced")
throw new Error("No syncing has been performed, or the last sync is outdated. Please sync your notes with CopilotDB.");
if (!queryText || !queryText.trim()) return [];
let dbm = await DuckDBNotesManager.getInstance();
await DuckDBConnectionController.lockAutoTerminate();
try {
let queryVector = (await (await EmbeddingGeneratorFactory.create(app)).generateEmbedding(app, queryText, queryTextType || "query"))[0], results = await dbm.searchNoteRecordByRRF(queryText, queryVector, {
limit,
isArchived,
isSharedByMe,
isSharedWithMe,
isTaskListNote
});
return DuckDBConnectionController.unlockAutoTerminate(), results;
} catch (e) {
throw DuckDBConnectionController.unlockAutoTerminate(), new Error(`Error querying vectors: ${e}`);
}
};
init_process();
init_process();
var _DuckDBHelpCenterManager = class _DuckDBHelpCenterManager {
async _performInit() {
if (!(this.db && !DuckDBConnectionController.isTerminated()))
try {
this.db = await DuckDBConnectionController.getCollectionInstance("CopilotTempDB", { persistent: !1 });
let conn = await this.db.connect();
await conn.query("CHECKPOINT;"), await conn.close();
} catch (e) {
throw console.error("DuckDBHelpCenterManager init error:", e), e;
}
}
async searchHelpCenterRecordByEmbedding(embedding, { limit = 15, filename = "localHelpCenterEmbeddings.parquet" } = {}) {
let conn, stmt;
try {
conn = await this.db.connect();
let parquetUrl = getJSDeliverBundleUrl(filename);
if (stmt = await conn.prepare(`
SELECT
*,
list_dot_product(embedding, ?) AS similarity
FROM
read_parquet('${parquetUrl}')
ORDER BY
similarity DESC
LIMIT ?;
`), (embedding instanceof Float32Array || embedding instanceof Float64Array) && (embedding = Array.from(embedding)), !isArray_default(embedding))
throw new Error("Embedding must be an array of numbers.");
let rows = (await stmt.query(JSON.stringify(embedding), limit)).toArray(), resArr = [];
return rows.forEach((row) => {
resArr.push({
id: row.id,
noteUUID: row.noteUUID,
noteTitle: row.noteTitle,
actualNoteContentPart: row.actualNoteContentPart,
similarity: row.similarity
});
}), resArr;
} catch (e) {
throw console.error("Failed to search help center records:", e), e;
} finally {
stmt && await stmt.close(), conn && await conn.close();
}
}
static async getInstance() {
return _DuckDBHelpCenterManager._instance || (_DuckDBHelpCenterManager._instance = new _DuckDBHelpCenterManager()), await _DuckDBHelpCenterManager._instance._performInit(), _DuckDBHelpCenterManager._instance;
}
};
__publicField(_DuckDBHelpCenterManager, "_instance", null);
var DuckDBHelpCenterManager = _DuckDBHelpCenterManager;
function calculateHelpCenterFilename(embeddingProviderName) {
if (embeddingProviderName === "local" || embeddingProviderName === "ollama")
return "localHelpCenterEmbeddings.parquet";
if (embeddingProviderName === "openai")
return "openaiHelpCenterEmbeddings.parquet";
if (embeddingProviderName === "google")
return "googleHelpCenterEmbeddings.parquet";
if (embeddingProviderName === "fireworks")
return "fireworksHelpCenterEmbeddings.parquet";
if (embeddingProviderName === "pinecone")
return "pineconeHelpCenterEmbeddings.parquet";
throw new Error(`Embedding provider ${embeddingProviderName} not supported`);
}
var searchHelpCenter = async (app, queryText, { limit = 15 }) => {
if (!queryText || !queryText.trim()) return [];
await DuckDBConnectionController.lockAutoTerminate();
let helpCenterManager = await DuckDBHelpCenterManager.getInstance();
try {
let embeddingProviderName = getEmbeddingProviderName(app), filename = calculateHelpCenterFilename(embeddingProviderName), queryVector = (await (await EmbeddingGeneratorFactory.create(app)).generateEmbedding(app, queryText, "query"))[0], result = await helpCenterManager.searchHelpCenterRecordByEmbedding(queryVector, { limit, filename });
return DuckDBConnectionController.unlockAutoTerminate(), result;
} catch (e) {
throw DuckDBConnectionController.unlockAutoTerminate(), new Error(`Error querying vectors: ${e}`);
}
};
init_process();
init_process();
var _IndexedDBStorageUtils = class _IndexedDBStorageUtils {
static checkSupport() {
try {
return typeof indexedDB != "undefined" && indexedDB !== null;
} catch {
return !1;
}
}
static _getPrefixedKey(key) {
return `${_IndexedDBStorageUtils.KEY_PREFIX}${key}`;
}
static async _openDatabase(key, readOnly = !0) {
return new Promise((resolve, reject) => {
let dbName = _IndexedDBStorageUtils._getPrefixedKey(key), request = indexedDB.open(dbName, _IndexedDBStorageUtils.DB_VERSION);
request.onerror = () => {
var _a;
reject(new Error(`Failed to open IndexedDB database '${dbName}': ${((_a = request.error) == null ? void 0 : _a.message) || "Unknown error"}`));
}, request.onsuccess = () => {
let db2 = request.result;
if (!db2.objectStoreNames.contains(_IndexedDBStorageUtils.STORE_NAME)) {
db2.close(), reject(new Error(`Object store '${_IndexedDBStorageUtils.STORE_NAME}' not found in database '${dbName}'`));
return;
}
resolve(db2);
}, request.onupgradeneeded = (event) => {
let db2 = event.target.result;
db2.objectStoreNames.contains(_IndexedDBStorageUtils.STORE_NAME) || db2.createObjectStore(_IndexedDBStorageUtils.STORE_NAME, { keyPath: "id" });
};
});
}
static _estimateObjectSize(obj) {
try {
return new Blob([JSON.stringify(obj)]).size;
} catch {
return 0;
}
}
static _validateData(data) {
if (typeof data == "function")
throw new Error("Cannot store functions in IndexedDB");
if (typeof data == "symbol")
throw new Error("Cannot store symbols in IndexedDB");
}
static async readJsonFile(key) {
if (!key || typeof key != "string")
throw new Error("Invalid key provided to readJsonFile.");
if (!_IndexedDBStorageUtils.checkSupport())
return console.warn("IndexedDB not supported, returning null for file read"), null;
try {
let dbName = _IndexedDBStorageUtils._getPrefixedKey(key), dbExists = !0;
try {
typeof indexedDB.databases == "function" && (dbExists = (await indexedDB.databases()).some((db3) => db3.name === dbName));
} catch (error) {
console.warn("Cannot check database existence, will attempt to open:", error), dbExists = !0;
}
if (!dbExists)
return null;
let db2;
try {
db2 = await _IndexedDBStorageUtils._openDatabase(key, !0);
} catch (error) {
if (error.message.includes("Object store"))
return console.warn(`Corrupted database detected for key '${key}', deleting it`), await _IndexedDBStorageUtils.deleteFile(key), null;
throw error;
}
return new Promise((resolve, reject) => {
let request = db2.transaction([_IndexedDBStorageUtils.STORE_NAME], "readonly").objectStore(_IndexedDBStorageUtils.STORE_NAME).get("data");
request.onerror = () => {
var _a;
db2.close(), reject(new Error(`Error reading from IndexedDB: ${((_a = request.error) == null ? void 0 : _a.message) || "Unknown error"}`));
}, request.onsuccess = () => {
db2.close();
let result = request.result;
result && "content" in result ? resolve(result.content) : resolve(null);
};
});
} catch (error) {
throw console.error(`Error reading data from IndexedDB with key '${key}':`, error), error;
}
}
static async writeJsonFile(key, data) {
if (!key || typeof key != "string")
throw new Error("Invalid key provided to writeJsonFile.");
if (!_IndexedDBStorageUtils.checkSupport())
return console.warn("IndexedDB not supported, cannot write file"), !1;
try {
_IndexedDBStorageUtils._validateData(data);
let db2;
try {
db2 = await _IndexedDBStorageUtils._openDatabase(key, !1);
} catch (error) {
if (error.message.includes("Object store"))
console.warn(`Corrupted database detected for key '${key}', recreating it`), await _IndexedDBStorageUtils.deleteFile(key), db2 = await _IndexedDBStorageUtils._openDatabase(key, !1);
else
throw error;
}
return new Promise((resolve, reject) => {
let request = db2.transaction([_IndexedDBStorageUtils.STORE_NAME], "readwrite").objectStore(_IndexedDBStorageUtils.STORE_NAME).put({
id: "data",
content: data,
timestamp: Date.now()
});
request.onerror = () => {
db2.close();
let error = request.error;
error && error.name === "QuotaExceededError" ? reject(new Error(`IndexedDB quota exceeded for key '${key}': ${error.message}`)) : error && error.name === "DataCloneError" ? reject(new Error(`Cannot store data in IndexedDB for key '${key}': ${error.message}. Data contains non-serializable values.`)) : reject(new Error(`Error writing to IndexedDB: ${(error == null ? void 0 : error.message) || "Unknown error"}`));
}, request.onsuccess = () => {
db2.close(), resolve(!0);
};
});
} catch (error) {
throw console.error(`Error writing data to IndexedDB with key '${key}':`, error), error;
}
}
static async deleteFile(key) {
if (!key || typeof key != "string")
throw new Error("Invalid key provided to deleteFile.");
if (!_IndexedDBStorageUtils.checkSupport())
return console.warn("IndexedDB not supported, cannot delete file"), !1;
try {
let dbName = _IndexedDBStorageUtils._getPrefixedKey(key), exists = !0;
try {
if (typeof indexedDB.databases == "function" && (exists = (await indexedDB.databases()).some((db2) => db2.name === dbName), !exists))
return !1;
} catch (error) {
console.warn("Cannot check database existence for deletion:", error);
}
return new Promise((resolve, reject) => {
let deleteRequest = indexedDB.deleteDatabase(dbName);
deleteRequest.onerror = () => {
var _a;
reject(new Error(`Error deleting IndexedDB database '${dbName}': ${((_a = deleteRequest.error) == null ? void 0 : _a.message) || "Unknown error"}`));
}, deleteRequest.onsuccess = () => {
resolve(!0);
}, deleteRequest.onblocked = () => {
console.warn(`Delete blocked for database '${dbName}'. Retrying...`);
};
});
} catch (error) {
throw console.error(`Error deleting from IndexedDB with key '${key}':`, error), error;
}
}
static async getFileList() {
if (!_IndexedDBStorageUtils.checkSupport())
return [];
try {
let fileList = [];
try {
if (typeof indexedDB.databases == "function") {
let databases = await indexedDB.databases(), prefixLength = _IndexedDBStorageUtils.KEY_PREFIX.length;
for (let dbInfo of databases)
if (dbInfo.name && dbInfo.name.startsWith(_IndexedDBStorageUtils.KEY_PREFIX)) {
let fileName = dbInfo.name.substring(prefixLength);
try {
let data = await _IndexedDBStorageUtils.readJsonFile(fileName), fileSizeMB = data ? Math.round(_IndexedDBStorageUtils._estimateObjectSize(data) / 1024 / 1024 * 100) / 100 : 0;
fileList.push({
fileName,
fileSizeMB
});
} catch (error) {
console.warn(`Could not read file '${fileName}' for size calculation:`, error), fileList.push({
fileName,
fileSizeMB: 0
});
}
}
} else
console.warn("indexedDB.databases() not supported, returning empty file list");
} catch (error) {
console.warn("Error getting database list:", error);
}
return fileList;
} catch (error) {
throw console.error("Error listing databases from IndexedDB:", error), error;
}
}
static async getRemainingStorageSpace() {
try {
if (!_IndexedDBStorageUtils.checkSupport())
return "IndexedDB not supported";
let usedBytes = 0, fileList = await _IndexedDBStorageUtils.getFileList();
for (let file of fileList)
usedBytes += file.fileSizeMB * 1024 * 1024;
let usedMB = Math.round(usedBytes / 1024 / 1024 * 100) / 100;
if ("storage" in navigator && "estimate" in navigator.storage) {
let estimate = await navigator.storage.estimate(), totalUsedMB = Math.round((estimate.usage || 0) / 1024 / 1024), quotaMB = Math.round((estimate.quota || 0) / 1024 / 1024), remainingMB = quotaMB - totalUsedMB;
return `Copilot Used: ${usedMB}MB, Total Used: ${totalUsedMB}MB, Quota: ${quotaMB}MB, Remaining: ${remainingMB}MB`;
} else
return `Copilot Used: ${usedMB}MB (IndexedDB quota varies by browser and available disk space)`;
} catch (error) {
return console.error("Error getting storage space:", error), "Error getting storage space";
}
}
};
__publicField(_IndexedDBStorageUtils, "KEY_PREFIX", "copilot_json_file_"), __publicField(_IndexedDBStorageUtils, "STORE_NAME", "data"), __publicField(_IndexedDBStorageUtils, "DB_VERSION", 1);
var IndexedDBStorageUtils = _IndexedDBStorageUtils;
init_process();
var _CopilotChatHistoryDB = class _CopilotChatHistoryDB {
constructor() {
__publicField(this, "isInitialized", null);
}
async _performInit() {
if (!this.isInitialized) {
if (this.fileName = "copilot-chat-history.json", this.indexedDBSupported = null, this.threadsCache = {}, this._scheduleSave = throttle_default(this._persistCache.bind(this), 1e3, { leading: !0, trailing: !0 }), this.indexedDBSupported = IndexedDBStorageUtils.checkSupport(), this.indexedDBSupported) {
await this._handleVersionReset();
let data = await IndexedDBStorageUtils.readJsonFile(this.fileName);
data && data.threads && (this.threadsCache = data.threads);
}
this.isInitialized = !0;
}
}
async _persistCache() {
if (this.indexedDBSupported)
try {
let dataToSave = {
version: 54,
threads: this.threadsCache
};
await IndexedDBStorageUtils.writeJsonFile(this.fileName, dataToSave);
} catch (error) {
console.error("Failed to save chat history to IndexedDB:", error);
}
}
async getAllThreads() {
return Object.values(this.threadsCache).sort((a, b) => new Date(b.updated) - new Date(a.updated));
}
async deleteThread(threadId) {
if (!threadId) return !1;
try {
return this.threadsCache[threadId] ? (delete this.threadsCache[threadId], this._scheduleSave(), !0) : !1;
} catch (e) {
return console.error("Failed to delete thread:", e), !1;
}
}
async getThread(threadId) {
return threadId && this.threadsCache[threadId] || null;
}
async putThread(thread) {
this._validateThread(thread);
let threads = this.threadsCache;
for (let threadId in threads) {
if (threadId === thread.remoteId) continue;
let existingThread = threads[threadId];
(!existingThread.messages || !existingThread.messages.messages || existingThread.messages.messages.length === 0) && delete threads[threadId];
}
threads[thread.remoteId] = {
remoteId: thread.remoteId,
name: thread.name,
created: thread.created,
updated: thread.updated,
opened: thread.opened || thread.updated,
status: thread.status,
messages: thread.messages,
enabledToolGroups: thread.enabledToolGroups
};
let threadList = Object.values(threads);
if (threadList.length > 100) {
threadList.sort((a, b) => new Date(a.updated) - new Date(b.updated));
let oldestThread = threadList[0];
delete threads[oldestThread.remoteId];
}
this._scheduleSave();
}
async getLastOpenedThread() {
let threads = Object.values(this.threadsCache);
return threads.length === 0 ? null : threads.sort((a, b) => new Date(b.opened) - new Date(a.opened))[0];
}
async getLastUpdatedThread() {
return (await this.getAllThreads())[0] || null;
}
_validateThread(thread) {
if (!thread.remoteId || !thread.name || !thread.created || !thread.updated || !thread.status)
throw new Error("Invalid thread object");
if (!Date.parse(thread.created) || !Date.parse(thread.updated))
throw new Error("Invalid date format for created or updated");
if (thread.opened && !Date.parse(thread.opened))
throw new Error("Invalid date format for opened");
return !0;
}
async _handleVersionReset() {
if (this.indexedDBSupported)
try {
let data = await IndexedDBStorageUtils.readJsonFile(this.fileName);
if (!data) return;
let currentVersion = data.version || 0;
currentVersion !== 54 && (await IndexedDBStorageUtils.deleteFile(this.fileName), this.threadsCache = {}, console.log(`Chat history reset completed due to version change from ${currentVersion} to ${54}.`));
} catch (error) {
console.error("Error during chat history version check:", error);
}
}
static async getInstance() {
return _CopilotChatHistoryDB._instance || (_CopilotChatHistoryDB._instance = new _CopilotChatHistoryDB()), await _CopilotChatHistoryDB._instance._performInit(), _CopilotChatHistoryDB._instance;
}
};
__publicField(_CopilotChatHistoryDB, "_instance", null);
var CopilotChatHistoryDB = _CopilotChatHistoryDB;
async function clearCopilotDBData(app) {
await DuckDBConnectionController.forceTerminate();
let deletedFiles = [], filesToDelete = (await OPFSUtils.getFileList()).map((file) => file.fileName).filter((fileName) => fileName.endsWith(".db") || fileName.endsWith(".db.wal") || fileName === "copilot-chat-history.json");
for (let fileName of filesToDelete)
try {
await OPFSUtils.deleteFile(fileName) && deletedFiles.push(`${fileName} (opfs)`);
} catch (error) {
throw console.error(`Error deleting ${fileName}:`, error), new Error(`Failed to delete ${fileName}: ${error.message}`);
}
let indexedDBFiles = await IndexedDBStorageUtils.getFileList();
for (let file of indexedDBFiles)
try {
await IndexedDBStorageUtils.deleteFile(file.fileName) && deletedFiles.push(`${file.fileName} (indexeddb)`);
} catch (error) {
throw console.error(`Error deleting IndexedDB key ${file.fileName}:`, error), new Error(`Failed to delete IndexedDB key ${file.fileName}: ${error.message}`);
}
return (await CopilotChatHistoryDB.getInstance()).threadsCache = {}, {
success: !0,
deletedFiles,
message: deletedFiles.length > 0 ? `Successfully deleted ${deletedFiles.length} item(s): ${deletedFiles.join(", ")}` : "No CopilotDB data found to delete"
};
}
init_process();
var import_dayjs = __toESM(require_dayjs_min(), 1);
var _DuckDBUserTasksManager = class _DuckDBUserTasksManager {
async _performInit() {
if (!(this.db && !DuckDBConnectionController.isTerminated()))
try {
this.db = await DuckDBConnectionController.getCollectionInstance("CopilotTempDB", { persistent: !1 });
let conn = await this.db.connect();
await conn.query("CHECKPOINT;"), await conn.close();
} catch (e) {
throw console.error("DuckDBUserTasksManager init error:", e), e;
}
}
async _syncUserTasks(app) {
let conn;
try {
conn = await this.db.connect(), await conn.query("DROP TABLE IF EXISTS user_tasks;"), await conn.query(`
CREATE OR REPLACE TABLE user_tasks (
completedAt TIMESTAMP,
dismissedAt TIMESTAMP,
endAt TIMESTAMP,
hideUntil TIMESTAMP,
startAt TIMESTAMP,
content VARCHAR,
noteUUID VARCHAR,
taskUUID VARCHAR PRIMARY KEY,
taskDomainUUID VARCHAR,
taskDomainName VARCHAR,
urgent BOOLEAN,
important BOOLEAN,
score DOUBLE
);
`);
let allTasks = [], notesArr = [];
await Promise.all([
app.filterNotes({ group: "taskLists" }).then((r) => notesArr.push(...r)).catch((e) => console.error("taskLists", e)),
app.filterNotes({ tag: "daily-jots" }).then((r) => notesArr.push(...r)).catch((e) => console.error("daily-jots", e)),
app.filterNotes({ tag: "today" }).then((r) => notesArr.push(...r)).catch((e) => console.error("today", e))
]);
let notesMap = new Map();
for (let note of notesArr)
notesMap.set(note.uuid, note);
let notes = Array.from(notesMap.values());
for (let note of notes) {
if (!note || !note.uuid) continue;
let tasks = await app.getNoteTasks({ uuid: note.uuid }, { includeDone: !0 });
if (tasks)
for (let task of tasks)
allTasks.push({
completedAt: typeof task.completedAt == "number" ? (0, import_dayjs.default)(task.completedAt * 1e3).format() : null,
dismissedAt: typeof task.dismissedAt == "number" ? (0, import_dayjs.default)(task.dismissedAt * 1e3).format() : null,
endAt: typeof task.endAt == "number" ? (0, import_dayjs.default)(task.endAt * 1e3).format() : null,
hideUntil: typeof task.hideUntil == "number" ? (0, import_dayjs.default)(task.hideUntil * 1e3).format() : null,
startAt: typeof task.startAt == "number" ? (0, import_dayjs.default)(task.startAt * 1e3).format() : null,
content: task.content || null,
noteUUID: task.noteUUID || null,
taskUUID: task.uuid || null,
taskDomainUUID: null,
taskDomainName: null,
urgent: task.urgent || !1,
important: task.important || !1,
score: task.score || 0
});
}
let taskDomains = await app.getTaskDomains();
for (let taskDomain of taskDomains) {
let tasks = await app.getTaskDomainTasks(taskDomain.uuid);
if (tasks)
for (let task of tasks)
allTasks.push({
completedAt: typeof task.completedAt == "number" ? (0, import_dayjs.default)(task.completedAt * 1e3).format() : null,
dismissedAt: typeof task.dismissedAt == "number" ? (0, import_dayjs.default)(task.dismissedAt * 1e3).format() : null,
endAt: typeof task.endAt == "number" ? (0, import_dayjs.default)(task.endAt * 1e3).format() : null,
hideUntil: typeof task.hideUntil == "number" ? (0, import_dayjs.default)(task.hideUntil * 1e3).format() : null,
startAt: typeof task.startAt == "number" ? (0, import_dayjs.default)(task.startAt * 1e3).format() : null,
content: task.content || null,
noteUUID: task.noteUUID || null,
taskUUID: task.uuid || null,
taskDomainUUID: taskDomain.uuid || null,
taskDomainName: taskDomain.name || null,
urgent: task.urgent || !1,
important: task.important || !1,
score: task.score || 0
});
}
if (allTasks.length > 0) {
await conn.query("BEGIN TRANSACTION");
let stmt = await conn.prepare(`
INSERT OR REPLACE INTO user_tasks (
completedAt, dismissedAt, endAt, hideUntil, startAt,
content, noteUUID, taskUUID, taskDomainUUID, taskDomainName,
urgent, important, score
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
for (let task of allTasks)
await stmt.query(
task.completedAt,
task.dismissedAt,
task.endAt,
task.hideUntil,
task.startAt,
task.content,
task.noteUUID,
task.taskUUID,
task.taskDomainUUID,
task.taskDomainName,
task.urgent,
task.important,
task.score
);
await conn.query("COMMIT"), await stmt.close();
}
return allTasks.length;
} catch (e) {
throw console.error("Failed to sync user tasks:", e), e;
} finally {
conn && await conn.close();
}
}
async _validateSQLQuery(sqlQuery, conn) {
try {
console.log("sqlQuery print", sqlQuery);
let parsedData = (await conn.query(`SELECT json_serialize_sql('${sqlQuery.replace(/'/g, "''")}') as parsed`)).toArray()[0], parsed = JSON.parse(parsedData.parsed);
if (parsed.error)
throw new Error("Invalid SQL syntax");
for (let statement of parsed.statements) {
if (!this._isSelectStatement(statement.node))
throw new Error("Only SELECT statements are allowed");
this._validateTableReferences(statement.node);
}
return !0;
} catch (e) {
throw e.message.includes("Only SELECT statements are allowed") || e.message.includes("Invalid SQL syntax") || e.message.includes("Only queries against") ? e : new Error("Invalid SQL query: " + e.message);
}
}
_isSelectStatement(node2) {
return !node2 || !node2.type ? !1 : node2.type === "SELECT_NODE" ? !0 : node2.type === "SET_OPERATION_NODE" ? this._isSelectStatement(node2.left) && this._isSelectStatement(node2.right) : node2.type === "CTE_NODE" ? this._isSelectStatement(node2.query) : !1;
}
_validateTableReferences(node2) {
if (node2) {
if (node2.from_table && this._validateFromClause(node2.from_table), node2.cte_map && node2.cte_map.map)
for (let cte of node2.cte_map.map)
cte.query && this._validateTableReferences(cte.query);
if (node2.select_list)
for (let selectItem of node2.select_list)
selectItem.class === "SUBQUERY" && this._validateTableReferences(selectItem.subquery);
node2.where_clause && this._validateExpressionForSubqueries(node2.where_clause);
}
}
_validateFromClause(fromClause) {
if (fromClause)
if (fromClause.type === "BASE_TABLE") {
if (fromClause.table_name !== "user_tasks")
throw new Error(`Only queries against 'user_tasks' table are allowed. Found: ${fromClause.table_name}`);
} else fromClause.type === "JOIN" ? (this._validateFromClause(fromClause.left), this._validateFromClause(fromClause.right)) : fromClause.type === "SUBQUERY" && this._validateTableReferences(fromClause.subquery);
}
_validateExpressionForSubqueries(expression) {
if (expression && (expression.class === "SUBQUERY" && this._validateTableReferences(expression.subquery), expression.children))
for (let child of expression.children)
this._validateExpressionForSubqueries(child);
}
async _searchUserTasks(sqlQuery) {
let conn;
try {
return conn = await this.db.connect(), await this._validateSQLQuery(sqlQuery, conn), (await conn.query(sqlQuery)).toArray().map((row) => ({
completedAt: typeof row.completedAt == "number" ? (0, import_dayjs.default)(row.completedAt).toISOString() : null,
dismissedAt: typeof row.dismissedAt == "number" ? (0, import_dayjs.default)(row.dismissedAt).toISOString() : null,
endAt: typeof row.endAt == "number" ? (0, import_dayjs.default)(row.endAt).toISOString() : null,
hideUntil: typeof row.hideUntil == "number" ? (0, import_dayjs.default)(row.hideUntil).toISOString() : null,
startAt: typeof row.startAt == "number" ? (0, import_dayjs.default)(row.startAt).toISOString() : null,
content: row.content,
noteUUID: row.noteUUID,
taskUUID: row.taskUUID,
taskDomainUUID: row.taskDomainUUID,
taskDomainName: row.taskDomainName,
urgent: row.urgent,
important: row.important,
score: row.score
}));
} catch (e) {
throw console.error("Failed to search user tasks:", e), e;
} finally {
conn && await conn.close();
}
}
async searchUserTasks(app, sqlQuery) {
try {
let taskCount = await this._syncUserTasks(app);
console.log(`Synced ${taskCount} tasks to temporary table`);
let results = await this._searchUserTasks(sqlQuery);
return {
success: !0,
taskCount,
results,
resultCount: results.length
};
} catch (e) {
return console.error("Failed in searchUserTasks:", e), {
success: !1,
error: e.message || "Unknown error occurred",
taskCount: 0,
results: [],
resultCount: 0
};
}
}
static async getInstance() {
return _DuckDBUserTasksManager._instance || (_DuckDBUserTasksManager._instance = new _DuckDBUserTasksManager()), await _DuckDBUserTasksManager._instance._performInit(), _DuckDBUserTasksManager._instance;
}
};
__publicField(_DuckDBUserTasksManager, "_instance", null);
var DuckDBUserTasksManager = _DuckDBUserTasksManager;
var syncNotesPromise = null, searchNotes2 = async (app, query, queryTextType, opts) => await searchNotes(app, query, queryTextType, opts), syncNotes2 = async (app, sendMessageToEmbed) => (syncNotesPromise || (syncNotesPromise = syncNotes(app, sendMessageToEmbed).finally(() => {
syncNotesPromise = null;
})), syncNotesPromise), getSyncState2 = async (app) => await getSyncState(app, syncNotesPromise), searchHelpCenter2 = async (app, query, opts) => await searchHelpCenter(app, query, opts), clearCopilotDBData2 = async (app) => await clearCopilotDBData(app), getAllChatThreads = async () => await (await CopilotChatHistoryDB.getInstance()).getAllThreads(), deleteChatThread = async (threadId) => await (await CopilotChatHistoryDB.getInstance()).deleteThread(threadId), getChatThread = async (threadId) => await (await CopilotChatHistoryDB.getInstance()).getThread(threadId), saveChatThread = async (thread) => await (await CopilotChatHistoryDB.getInstance()).putThread(thread), getLastUpdatedChatThread = async () => await (await CopilotChatHistoryDB.getInstance()).getLastUpdatedThread(), getLastOpenedChatThread = async () => await (await CopilotChatHistoryDB.getInstance()).getLastOpenedThread(), searchUserTasks = async (app, sqlQuery) => await (await DuckDBUserTasksManager.getInstance()).searchUserTasks(app, sqlQuery);
init_process();
var getMatchedPartWithFuzzySearch = async (app, noteUUID, searchText, limit = 1) => {
let Fuse = (await dynamic_import_esm_default("fuse.js")).default, splitter = new Splitter(1280), note = await app.findNote({ uuid: noteUUID }), splitResult = await splitter.splitNote(app, note, !0);
return new Fuse(splitResult, { keys: ["actualNoteContentPart`"], threshold: 0.4 }).search(searchText, { limit }).map((result) => result.item.actualNoteContentPart);
};
init_process();
async function validatePluginSettings(app) {
let errors = [], settings = app.settings;
settings[LLM_API_URL_SETTING] || errors.push("LLM API URL must be provided.");
let isLLMApiUrlValid = !1;
try {
new URL(settings[LLM_API_URL_SETTING]), isLLMApiUrlValid = !0;
} catch {
errors.push("LLM API URL provided is not a valid URL.");
}
!settings[LLM_API_KEY_SETTING] && !settings[LLM_API_URL_SETTING].includes("localhost") && errors.push("LLM API Key must be provided."), settings[LLM_API_URL_SETTING].trim() || errors.push("LLM API URL cannot be empty.");
try {
isLLMApiUrlValid && await getLLMModel(app.settings);
} catch (e) {
errors.push(e.message);
}
if (settings[LLM_MAX_TOKENS_SETTING] && settings[LLM_MAX_TOKENS_SETTING].trim() !== "" && (isNaN(settings[LLM_MAX_TOKENS_SETTING]) && errors.push("LLM Max Tokens must be a valid number."), Number(settings[LLM_MAX_TOKENS_SETTING]) < 4096 && errors.push("LLM Max Tokens must be greater than or equal to 4096.")), settings[EMBEDDING_API_URL_SETTING].trim()) {
let isEmbeddingUrlValid = !1;
try {
new URL(settings[EMBEDDING_API_URL_SETTING]), isEmbeddingUrlValid = !0;
} catch {
errors.push("Embedding API URL provided is not a valid URL.");
}
!settings[EMBEDDING_API_KEY_SETTING] && !settings[EMBEDDING_API_URL_SETTING].includes("localhost") && errors.push("Embedding API Key must be provided when Embedding API URL is provided.");
try {
isEmbeddingUrlValid && await EmbeddingGeneratorFactory.create(app);
} catch (e) {
errors.push(e.message);
}
}
if (settings[EMBEDDING_API_KEY_SETTING].trim() && !settings[EMBEDDING_API_URL_SETTING].trim() && errors.push("Embedding API URL cannot be empty when Embedding API Key is provided."), settings[MCP_SERVER_URL_LIST_SETTING].trim()) {
let urls = settings[MCP_SERVER_URL_LIST_SETTING].split(",");
for (let url of urls)
if (url.trim() !== "")
try {
new URL(url);
} catch {
errors.push(`MCP Server URL provided is not a valid URL: ${url}`);
}
}
return errors;
}
init_process();
var VoskletSpeechToText = class {
constructor(options = {}) {
this.options = {
modelUrl: "https://ccoreilly.github.io/vosk-browser/models/vosk-model-small-en-us-0.15.tar.gz",
modelName: "vosk-model-small-en-us-0.15",
language: "English",
bufferSize: 4096,
sampleRate: 16e3,
...options
}, this._resetState();
}
_resetState() {
this.voskModule = null, this.model = null, this.recognizer = null, this.audioContext = null, this.micNode = null, this.recognizerNode = null, this.mediaStream = null, this.isInitialized = !1, this.isRecordingActive = !1, this.callbacks = {};
}
async _loadVoskModule() {
try {
let module2 = await dynamic_import_esm_default("vosk-browser");
return console.log("Vosk module methods:", Object.keys(module2)), console.log("Vosk module:", module2), module2;
} catch (error) {
throw new Error(`Failed to load vosk-browser module: ${error.message}`);
}
}
async initialize() {
var _a, _b, _c, _d;
if (!this.isInitialized)
try {
this.voskModule = await this._loadVoskModule(), this.audioContext = new AudioContext({
sampleRate: this.options.sampleRate,
...AudioContext.prototype.setSinkId ? { sinkId: { type: "none" } } : {}
}), this.model = await this.voskModule.createModel(this.options.modelUrl), this.isInitialized = !0, (_b = (_a = this.callbacks).onReady) == null || _b.call(_a);
} catch (error) {
let initError = new Error(`Failed to initialize VoskletSpeechToText: ${error.message}`);
throw initError.type = this._getErrorType(error), (_d = (_c = this.callbacks).onError) == null || _d.call(_c, initError), initError;
}
}
async startRecording(callbacks = {}) {
var _a, _b;
if (!this.isInitialized)
throw new Error("VoskletSpeechToText not initialized. Call initialize() first.");
if (this.isRecordingActive)
throw new Error("Recording is already active");
this.callbacks = callbacks;
try {
await this._setupAudioPipeline(), this.isRecordingActive = !0;
} catch (error) {
let recordingError = new Error(`Failed to start recording: ${error.message}`);
throw recordingError.type = this._getErrorType(error), await this._cleanupRecording(), (_b = (_a = this.callbacks).onError) == null || _b.call(_a, recordingError), recordingError;
}
}
async _setupAudioPipeline() {
this.mediaStream = await navigator.mediaDevices.getUserMedia({
video: !1,
audio: {
echoCancellation: !0,
noiseSuppression: !0,
channelCount: 1,
sampleRate: this.options.sampleRate
}
}), this.recognizer = new this.model.KaldiRecognizer(this.options.sampleRate), this.recognizer.on("result", (message) => {
var _a;
this.callbacks.onResult && ((_a = message.result) != null && _a.text) && this.callbacks.onResult(message.result.text);
}), this.recognizer.on("partialresult", (message) => {
var _a;
this.callbacks.onPartialResult && ((_a = message.result) != null && _a.partial) && this.callbacks.onPartialResult(message.result.partial);
}), this.micNode = this.audioContext.createMediaStreamSource(this.mediaStream), this.recognizerNode = this.audioContext.createScriptProcessor(
this.options.bufferSize,
1,
1
), this.recognizerNode.onaudioprocess = (event) => {
var _a, _b;
try {
this.recognizer && this.isRecordingActive && this.recognizer.acceptWaveform(event.inputBuffer);
} catch (error) {
console.error("Audio processing failed:", error);
let processingError = new Error(`Audio processing failed: ${error.message}`);
processingError.type = "AUDIO_PROCESSING_ERROR", (_b = (_a = this.callbacks).onError) == null || _b.call(_a, processingError);
}
}, this.micNode.connect(this.recognizerNode), this.recognizerNode.connect(this.audioContext.destination);
}
async stopRecording() {
var _a, _b;
if (this.isRecordingActive)
try {
await this._cleanupRecording(), this.isRecordingActive = !1;
} catch (error) {
let stopError = new Error(`Error stopping recording: ${error.message}`);
throw stopError.type = "CLEANUP_ERROR", (_b = (_a = this.callbacks).onError) == null || _b.call(_a, stopError), stopError;
}
}
async cleanup() {
var _a;
try {
await this.stopRecording(), ((_a = this.audioContext) == null ? void 0 : _a.state) !== "closed" && await this.audioContext.close(), this._resetState();
} catch (error) {
let cleanupError = new Error(`Error during cleanup: ${error.message}`);
throw cleanupError.type = "CLEANUP_ERROR", cleanupError;
}
}
async _cleanupRecording() {
try {
this.micNode && (this.micNode.disconnect(), this.micNode = null), this.recognizerNode && (this.recognizerNode.disconnect(), this.recognizerNode.onaudioprocess = null, this.recognizerNode = null), this.mediaStream && (this.mediaStream.getTracks().forEach((track) => track.stop()), this.mediaStream = null), this.recognizer = null;
} catch (error) {
console.error("Error during recording cleanup:", error);
}
}
static async checkMicrophoneAvailability() {
try {
return !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia || !window.AudioContext ? {
isAvailable: !1,
reason: "BROWSER_NOT_SUPPORTED",
message: "Browser does not support required audio APIs"
} : (await navigator.mediaDevices.enumerateDevices()).some((device) => device.kind === "audioinput") ? {
isAvailable: !0,
reason: "AVAILABLE",
message: "Microphone is available"
} : {
isAvailable: !1,
reason: "NO_MICROPHONE_DEVICES",
message: "No microphone devices detected"
};
} catch (error) {
return {
isAvailable: !1,
reason: "DETECTION_ERROR",
message: `Failed to check microphone availability: ${error.message}`
};
}
}
_getErrorType(error) {
let errorMap = {
NotAllowedError: "PERMISSION_ERROR",
PermissionDeniedError: "PERMISSION_ERROR",
NetworkError: "NETWORK_ERROR",
NotSupportedError: "BROWSER_SUPPORT_ERROR"
};
return errorMap[error.name] ? errorMap[error.name] : error.message.includes("fetch") ? "NETWORK_ERROR" : error.message.includes("AudioContext") ? "AUDIO_CONTEXT_ERROR" : error.message.includes("vosk-browser") ? "VOSK_MODULE_ERROR" : "UNKNOWN_ERROR";
}
}, voskletInstance = null;
function getVoskletInstance(options = {}) {
return voskletInstance || (voskletInstance = new VoskletSpeechToText(options)), voskletInstance;
}
function resetVoskletInstance() {
voskletInstance && (voskletInstance.cleanup().catch(console.error), voskletInstance = null);
}
init_process();
async function handleContinue(app) {
let randomUUID = Math.random().toString(36).substring(7);
try {
await app.context.replaceSelection(`${randomUUID}`);
let noteContent = `----
note-title: ${(await app.notes.find(app.context.noteUUID)).name}
----
` + await app.getNoteContent({ uuid: app.context.noteUUID }), nearbyContent = noteContent.substring(noteContent.indexOf(randomUUID) - 800, noteContent.indexOf(randomUUID) + 800);
await app.context.replaceSelection("Generating...");
let prompt = `I want you to act as a fill in the mask tool. You take markdown input text and complete it factually. Only reply with words that should replace [MASK]. NEVER repeat input.
Additional instruction: If the surrounding text is in between a sentence, complete the entire sentence. Otherwise, complete the paragraph. DO NOT repeat the input text.
Examples:
Input:The [MASK] jumps over the lazy dog.
Output:quick brown fox
Input:The quick brown fox jumps[MASK]
Output: over the lazy dog.
Input:On the way, we caught sight of the famous waterfall. [MASK]
Output:A rainbow formed in the mist as we stood there. The sight was truly captivating.
---------------------
Input:
` + nearbyContent.replaceAll(randomUUID, "[MASK]"), response = await generateText(await getLLMModel(app.settings), prompt);
if (response.text) {
let responseText = response.text;
responseText.startsWith("Output:") && !(nearbyContent.toLowerCase().includes("input") || nearbyContent.toLowerCase().includes("output")) && (responseText = responseText.substring(6));
let lastCharInOriginalContent = nearbyContent.substring(noteContent.indexOf(randomUUID) - 1), firstCharInResponse = responseText.substring(0, 1);
lastCharInOriginalContent === firstCharInResponse && firstCharInResponse === " " && (responseText = responseText.substring(1)), await app.context.replaceSelection(responseText);
} else
throw new Error("LLM response is empty");
} catch (e) {
throw e;
} finally {
await app.context.replaceSelection("");
let currentContent = await app.getNoteContent({ uuid: app.context.noteUUID }), cleanedContent = currentContent.replace(`Generating...${randomUUID}`, "");
cleanedContent !== currentContent && await app.replaceNoteContent({ uuid: app.context.noteUUID }, cleanedContent);
}
}
init_process();
async function handleRefineSelection(app, selectionContent) {
let savedPromptList = [];
try {
JSON.parse(app.settings[USER_PROMPT_LIST_SETTING]).sort((a, b) => b.usageCount - a.usageCount).forEach((prompt2, index) => savedPromptList.push({ icon: "auto_fix_high", label: truncate_default(prompt2.message, { length: 96 }), fullLabel: prompt2.message, value: "SavedCustomPrompt" + index }));
} catch {
}
let promptPrefix = await app.prompt("", {
inputs: [
{ label: "Enter prompt type:", type: "select", options: [
{ icon: "summarize", label: "Rephrase", value: "Rephrase the following selected text:" },
{ icon: "unfold_more", label: "Shorten", value: "Shorten the following selected text:" },
{ icon: "unfold_less", label: "Elaborate", value: "Elaborate the following selected text:" },
{ icon: "work", label: "More formal", value: "Make the following selected text more formal:" },
{ icon: "beach_access", label: "More casual", value: "Make the following selected text more casual:" },
{ icon: "healing", label: "Fix grammar", value: "Rectify grammar and spelling in the following selected text:" },
...savedPromptList,
{ icon: "edit", label: "Custom", value: "Custom" }
], value: "Rephrase the following selected text:" }
]
});
if (!promptPrefix || (promptPrefix.startsWith("SavedCustomPrompt") && (promptPrefix = savedPromptList[parseInt(promptPrefix.substring(17))].fullLabel, promptPrefix = `Follow instructions bellow to edit text:
` + promptPrefix, promptPrefix += `
Selected text`), promptPrefix === "Custom" && (promptPrefix = await app.prompt("Enter custom prompt:"), promptPrefix += `
Selected text`, !promptPrefix)))
return;
let prompt = `Only respond with the text that should replace the selection. Do not reply anything other than the edited text.
${promptPrefix}:
` + selectionContent, response = await generateText(await getLLMModel(app.settings), prompt);
if (response.text)
await app.alert(response.text, {
preface: "Copilot response:",
actions: [
{ label: "Replace", value: "replace", icon: "edit" }
]
}) === "replace" && await app.context.replaceSelection(response.text);
else
throw new Error("LLM response is empty");
}
init_process();
init_process();
init_process();
function createGoogleImageModel(apiKey, modelId = "imagen-3.0-generate-002", maxImagesPerCall = 4) {
return {
specificationVersion: "v1",
provider: "google",
modelId,
maxImagesPerCall,
async doGenerate(options) {
var _a, _b, _c, _d;
let { prompt, size } = options, parameters = {
sampleCount: this.maxImagesPerCall
};
if (size) {
let [width, height] = size.split("x").map(Number);
if (width && height)
if (width === height)
parameters.aspectRatio = "1:1";
else if (width > height) {
let ratio = width / height;
ratio >= 1.7 && ratio <= 1.8 ? parameters.aspectRatio = "16:9" : ratio >= 1.3 && ratio <= 1.4 && (parameters.aspectRatio = "4:3");
} else {
let ratio = height / width;
ratio >= 1.7 && ratio <= 1.8 ? parameters.aspectRatio = "9:16" : ratio >= 1.3 && ratio <= 1.4 && (parameters.aspectRatio = "3:4");
}
}
let response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/${this.modelId}:predict?key=${apiKey}`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
instances: [
{
prompt
}
],
parameters
})
}
);
if (!response.ok) {
let errorData = await response.json();
throw new Error(`Google API error: ${((_a = errorData.error) == null ? void 0 : _a.message) || response.statusText}`);
}
return {
images: ((_d = (_c = (_b = (await response.json()).predictions) == null ? void 0 : _b[0]) == null ? void 0 : _c.candidates) == null ? void 0 : _d.map(
(candidate) => candidate.output
)) || [],
warnings: [],
response: {
timestamp: new Date(),
modelId: this.modelId,
headers: Object.fromEntries(response.headers)
}
};
}
};
}
async function getImageModel(appSettings) {
let apiUrl = appSettings[LLM_API_URL_SETTING];
if (!apiUrl) throw new Error("LLM API URL is not provided. Please check and configure plugin settings.");
if (apiUrl.endsWith("/chat/completion") && (apiUrl = apiUrl.slice(0, -16)), apiUrl.includes("api.openai.com")) {
let { createOpenAI: createOpenAI2 } = await dynamic_import_esm_default("@ai-sdk/openai");
return createOpenAI2({
apiKey: appSettings[LLM_API_KEY_SETTING]
}).image("dall-e-2", { maxImagesPerCall: 1 });
} else {
if (apiUrl.includes("googleapis"))
return createGoogleImageModel(
appSettings[LLM_API_KEY_SETTING],
"imagen-3.0-generate-002",
1
);
if (apiUrl.includes("fireworks")) {
let { createFireworks: createFireworks2 } = await dynamic_import_esm_default("@ai-sdk/fireworks");
return createFireworks2({
apiKey: appSettings[LLM_API_KEY_SETTING]
}).image("accounts/fireworks/models/flux-1-schnell-fp8");
}
}
return !1;
}
init_process();
async function generateImage(model, prompt, size = 512) {
let { experimental_generateImage } = await dynamic_import_esm_default("ai");
return await experimental_generateImage({
model,
prompt,
n: 1,
size: `${size}x${size}`
});
}
async function checkImageGenerationAvailability(app) {
try {
if (app.settings[LLM_API_URL_SETTING].trim() !== "")
return !!await getImageModel(app.settings);
} catch (e) {
console.error(e);
}
return !1;
}
async function handleImageGeneration(app) {
let imageModel = await getImageModel(app.settings), [prompt, size] = await app.prompt("", {
inputs: [
{ label: "Image generation instructions:", type: "text", value: "" },
{ label: "Image size:", type: "select", options: [
{ label: "512x512", value: "512" },
{ label: "1024x1024", value: "1024" }
], value: "512" }
]
});
if (!prompt) return;
let response = await generateImage(imageModel, prompt, size);
if (console.log("response", response), response.image) {
let imgUrl = await app.attachNoteMedia({ uuid: app.context.noteUUID }, "data:image/webp;base64," + response.image.base64);
await app.context.replaceSelection(``);
} else
throw new Error("LLM response is empty");
}
var plugin = {
currentNoteUUID: null,
validateSettings: async function(app) {
try {
return await validatePluginSettings(app);
} catch (e) {
console.error(e);
}
},
insertText: {
Continue: async function(app) {
try {
await handleContinue(app);
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Speech to Text": async function(app) {
try {
await plugin.openEmbedStrategy(app, { openSpeechToText: !0 });
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Generate text": async function(app) {
try {
let instructions = await app.prompt("Enter text generation instructions:");
if (!instructions) return;
let prompt = `I want you to generate markdown text based on the following instructions. Do not reply anything other than the generated text on provided topic. Instructions:
` + instructions.trim() + `
`, response = await generateText(await getLLMModel(app.settings), prompt);
if (response.text)
await app.context.replaceSelection(response.text);
else
throw new Error("LLM response is empty");
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Generate image": {
check: async function(app, image) {
return await checkImageGenerationAvailability(app);
},
run: async function(app) {
try {
await handleImageGeneration(app);
} catch (e) {
console.error(e), await app.alert(e);
}
}
}
},
appOption: {
"Search notes using natural language": async function(app) {
try {
await plugin.openEmbedStrategy(app, { trigger: "appOption", openSearch: !0 });
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Sync notes with CopilotDB": async function(app) {
try {
await plugin.sendMessageToEmbed(app, "startSyncToCopilotDBInSearchInterface", !0), await plugin.openEmbedStrategy(app, { trigger: "appOption", openSearch: !0 });
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Chat with Copilot": async function(app) {
try {
await plugin.openEmbedStrategy(app, { trigger: "appOption", openChat: !0 });
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Clear CopilotDB data": async function(app) {
try {
if (!await app.prompt(
`This will permanently delete all CopilotDB data stored in your browser. You will need to sync your notes again to use the search features of this plugin. This will also delete your chat history.
Are you sure you want to continue?`,
{
inputs: []
}
))
return;
let result = await clearCopilotDBData2(app);
await app.alert(`${result.message}`);
} catch (e) {
console.error(e), await app.alert(`Error clearing CopilotDB data: ${e.message || e}`);
}
}
},
replaceText: {
Edit: async function(app, selectionContent) {
try {
let instructions = await app.prompt("Enter edit instructions:");
if (!instructions) return;
let prompt = `I want you to edit the following text based on the following instructions. You can use markdown. DO not reply anything other than the edited text. Instructions:
` + instructions.trim() + `
---------------------
Input:
` + selectionContent.trim(), response = await generateText(await getLLMModel(app.settings), prompt);
if (response.text)
await app.context.replaceSelection(response.text);
else
throw new Error("LLM response is empty");
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Chat with selection": {
check: async function(app, selectionContent) {
return !await plugin.isEmbedOpen(app);
},
run: async function(app, selectionContent) {
var _a;
await plugin.openEmbedStrategy(app, { openChat: !0 }), await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "selection", noteUUID: (_a = app == null ? void 0 : app.context) == null ? void 0 : _a.noteUUID, selectionContent }
);
}
},
"Add selection to chat": {
check: async function(app, selectionContent) {
return await plugin.isEmbedOpen(app);
},
run: async function(app, selectionContent) {
var _a;
await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "selection", noteUUID: (_a = app == null ? void 0 : app.context) == null ? void 0 : _a.noteUUID, selectionContent }
);
}
},
"Refine selection": async function(app, selectionContent) {
try {
await handleRefineSelection(app, selectionContent);
} catch (e) {
console.error(e), await app.alert(e);
}
}
},
noteOption: {
Chat: {
check: async function(app) {
return !await plugin.isEmbedOpen(app);
},
run: async function(app) {
await plugin.openEmbedStrategy(app, { openChat: !0 }), await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "new-chat", message: [] }
);
}
},
"Chat with note": {
check: async function(app, noteUUID) {
return !await plugin.isEmbedOpen(app);
},
run: async function(app, noteUUID) {
await plugin.openEmbedStrategy(app, { openChat: !0 });
let note = await app.findNote({ uuid: noteUUID }), noteContent = await app.getNoteContent({ uuid: noteUUID });
await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "new-chat", message: [] }
), await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "note", noteUUID, noteTitle: note.name, noteContent }
);
}
},
"Add note to chat": {
check: async function(app, noteUUID) {
return await plugin.isEmbedOpen(app);
},
run: async function(app, noteUUID) {
let note = await app.findNote({ uuid: noteUUID }), noteContent = await app.getNoteContent({ uuid: noteUUID });
await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "note", noteUUID, noteTitle: note.name, noteContent }
);
}
},
"Related notes": async function(app, noteUUID) {
try {
plugin.sendMessageToEmbed(app, "searchForTextInSearchInterface", `<<Related: ${noteUUID}>>`), await plugin.openEmbedStrategy(app, { trigger: "appOption", openSearch: !0 });
} catch (e) {
console.error(e), await app.alert(e);
}
}
},
taskOption: {
"Chat with task": {
check: async function(app, taskObj) {
return !await plugin.isEmbedOpen(app);
},
run: async function(app, taskObj) {
await plugin.openEmbedStrategy(app, { openChat: !0 }), await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "new-chat", message: [] }
), await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "task", taskUUID: taskObj.uuid }
);
}
},
"Add task to chat": {
check: async function(app, taskObj) {
return await plugin.isEmbedOpen(app);
},
run: async function(app, taskObj) {
await plugin.sendMessageToEmbed(
app,
"attachments",
{
type: "task",
taskUUID: taskObj.uuid,
taskContent: taskObj.content,
taskStartAt: taskObj.startAt,
taskEndAt: taskObj.endAt,
completedAt: taskObj.completedAt,
dismissedAt: taskObj.dismissedAt,
hideUntil: taskObj.hideUntil,
taskScore: taskObj.score,
important: taskObj.important,
urgent: taskObj.urgent
}
);
}
}
},
imageOption: {
"Chat with image": {
check: async function(app, image) {
return !await plugin.isEmbedOpen(app);
},
run: async function(app, image) {
await plugin.openEmbedStrategy(app, { openChat: !0 }), await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "new-chat", message: [] }
), await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "image", src: image.src }
);
}
},
"Add image to chat": {
check: async function(app, image) {
return await plugin.isEmbedOpen(app);
},
run: async function(app, image) {
await plugin.sendMessageToEmbed(
app,
"attachments",
{ type: "image", src: image.src }
);
}
}
},
openEmbedStrategy: async function(app, args) {
if (window.drawerEmbededArgs = {}, !await app.openSidebarEmbed(1, "sidebar", args)) {
window.drawerEmbededArgs = args, await app.openEmbed("drawer", args);
try {
await app.openSidebarEmbed(1, "sidebar", {});
} catch {
}
app.context.pluginUUID && await app.navigate("https://www.amplenote.com/notes/plugins/" + app.context.pluginUUID);
}
},
renderEmbed: async function(app, source, args) {
if (source === "drawer" && window.drawerEmbededArgs) {
try {
await app.context.updateEmbedArgs(source, window.drawerEmbededArgs);
} catch (e) {
console.error(e);
}
args = window.drawerEmbededArgs;
}
return args.openChat ? chat_default : args.openSearch ? search_default : args.openSpeechToText ? speechtotext_default : null;
},
sendMessageToEmbed: async function(app, channel, message) {
window.messageQueue || (window.messageQueue = {}), window.messageQueue[channel] = window.messageQueue[channel] || [], window.messageQueue[channel].push(message);
},
isEmbedOpen: async function(app) {
return window.lastHeartbeatFromChatEmbed && window.lastHeartbeatFromChatEmbed > Date.now() - 600;
},
onEmbedCall: createOnEmbedCallHandler({
...COMMON_EMBED_COMMANDS,
ping: async function(app) {
return window.lastHeartbeatFromChatEmbed = Date.now(), !0;
},
forceEmbedClose: async function(app) {
return window.lastHeartbeatFromChatEmbed = null, !0;
},
receiveMessageFromPlugin: async function(app, channel) {
return window.messageQueue && window.messageQueue[channel] && window.messageQueue[channel].length > 0 ? window.messageQueue[channel].shift() : null;
},
sendMessageToEmbed: async function(app, channel, message) {
console.log("Sending message to embed:", message), await plugin.sendMessageToEmbed(app, channel, message);
},
getUserCurrentNoteData: async (app) => {
try {
let currentNoteUUID = app.context.noteUUID, currentURL = app.context.url;
if (!currentNoteUUID && currentURL) {
let regex = /amplenote\.com\/notes\/([a-f0-9-]+)/, matches = currentURL.match(regex);
matches && matches.length > 1 && (currentNoteUUID = matches[1]);
}
if (!currentNoteUUID) return { currentNoteUUID: null };
let currentNote = await app.findNote({ uuid: currentNoteUUID });
return currentNote ? { currentNoteUUID: currentNote.uuid, currentNoteName: currentNote.name } : { currentNoteUUID: null };
} catch (e) {
throw "Failed getUserCurrentNoteData - " + e;
}
},
getUserDailyJotNote: async function(app) {
try {
let dailyJotNote = await app.notes.dailyJot(Math.floor(Date.now() / 1e3));
return {
dailyJotNoteUUID: (await dailyJotNote.url()).split("/").pop(),
dailyJotNoteName: dailyJotNote.name
};
} catch (e) {
throw "Failed getUserDailyJotNote - " + e;
}
},
getCopilotDBSyncState: async function(app) {
return await getSyncState2(app);
},
syncNotesWithCopilotDB: async function(app) {
await syncNotes2(app, plugin.sendMessageToEmbed);
},
searchNotesInCopilotDB: async function(app, queryText, queryTextType, opts) {
return await searchNotes2(app, queryText, queryTextType, opts);
},
searchHelpCenter: async function(app, queryText, opts) {
return await searchHelpCenter2(app, queryText, opts);
},
getMatchedPartWithFuzzySearch: async function(app, noteUUID, searchText, limit) {
return await getMatchedPartWithFuzzySearch(app, noteUUID, searchText, limit);
},
getAllChatThreadsFromCopilotDB: async function(app) {
return await getAllChatThreads();
},
deleteChatThreadFromCopilotDB: async function(app, threadId) {
return await deleteChatThread(threadId);
},
getChatThreadFromCopilotDB: async function(app, threadId) {
return await getChatThread(threadId);
},
saveChatThreadToCopilotDB: async function(app, thread) {
return await saveChatThread(thread);
},
getLastUpdatedChatThreadFromCopilotDB: async function(app) {
return await getLastUpdatedChatThread();
},
getLastOpenedChatThreadFromCopilotDB: async function(app) {
return await getLastOpenedChatThread();
},
searchUserTasks: async function(app, sqlQuery) {
return await searchUserTasks(app, sqlQuery);
},
initializeVoskletSpeechToText: async function(app, config = {}) {
try {
return await getVoskletInstance(config).initialize(), { success: !0, message: "Vosklet initialized successfully" };
} catch (error) {
return console.error("Failed to initialize Vosklet:", error), {
success: !1,
error: error.message,
errorType: error.type || "UNKNOWN_ERROR"
};
}
},
startVoskletRecording: async function(app, callbackChannels = {}) {
try {
let voskletAPI = getVoskletInstance(), callbacks = {
onPartialResult: (text) => {
callbackChannels.partialResult && plugin.sendMessageToEmbed(app, callbackChannels.partialResult, {
type: "partialResult",
text,
timestamp: Date.now()
}).catch(console.error);
},
onResult: (text) => {
callbackChannels.result && plugin.sendMessageToEmbed(app, callbackChannels.result, {
type: "result",
text,
timestamp: Date.now()
}).catch(console.error);
},
onError: (error) => {
callbackChannels.error && plugin.sendMessageToEmbed(app, callbackChannels.error, {
type: "error",
error: error.message,
errorType: error.type || "UNKNOWN_ERROR",
timestamp: Date.now()
}).catch(console.error);
},
onReady: () => {
callbackChannels.ready && plugin.sendMessageToEmbed(app, callbackChannels.ready, {
type: "ready",
timestamp: Date.now()
}).catch(console.error);
}
};
return await voskletAPI.startRecording(callbacks), { success: !0, message: "Recording started successfully" };
} catch (error) {
return console.error("Failed to start Vosklet recording:", error), {
success: !1,
error: error.message,
errorType: error.type || "UNKNOWN_ERROR"
};
}
},
stopVoskletRecording: async function(app) {
try {
return await getVoskletInstance().stopRecording(), { success: !0, message: "Recording stopped successfully" };
} catch (error) {
return console.error("Failed to stop Vosklet recording:", error), {
success: !1,
error: error.message,
errorType: error.type || "UNKNOWN_ERROR"
};
}
},
cleanupVoskletSpeechToText: async function(app) {
try {
return resetVoskletInstance(), { success: !0, message: "Vosklet cleanup completed" };
} catch (error) {
return console.error("Failed to cleanup Vosklet:", error), {
success: !1,
error: error.message,
errorType: error.type || "UNKNOWN_ERROR"
};
}
},
checkVoskletMicrophoneAvailability: async function(app) {
try {
return await VoskletSpeechToText.checkMicrophoneAvailability();
} catch (error) {
return console.error("Failed to check microphone availability:", error), {
isAvailable: !1,
reason: "CHECK_ERROR",
message: `Error checking microphone: ${error.message}`
};
}
}
}, [
"getUserCurrentNoteData",
"getUserDailyJotNote",
"getAllChatThreadsFromCopilotDB",
"saveChatThreadToCopilotDB",
"getChatThreadFromCopilotDB",
"getLastOpenedChatThreadFromCopilotDB",
"receiveMessageFromPlugin",
"ping"
])
}, plugin_default = plugin;
return plugin;
})()