A node now starts without any region (it only helps others connect, and prints a hint). The owner's sign-in link leads straight to the Regions page when none is followed, visitors get a notice instead of an empty search, and status always lists regions as an array. The Docker image no longer pins Bonn, the NixOS module no longer requires regions, and the VM test now starts without any, chooses the first region over the API and checks it survives a restart. README and the init hint follow. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
6393 lines
222 KiB
JavaScript
6393 lines
222 KiB
JavaScript
// src/jcs.ts
|
||
function canonicalize(value) {
|
||
if (value === null) return "null";
|
||
switch (typeof value) {
|
||
case "boolean":
|
||
return value ? "true" : "false";
|
||
case "number":
|
||
if (!Number.isSafeInteger(value)) {
|
||
throw new Error("jcs: only safe integers are supported");
|
||
}
|
||
return String(value);
|
||
case "string":
|
||
return JSON.stringify(value);
|
||
case "object": {
|
||
if (Array.isArray(value)) {
|
||
return "[" + value.map(canonicalize).join(",") + "]";
|
||
}
|
||
const obj = value;
|
||
const keys = Object.keys(obj).sort();
|
||
return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") + "}";
|
||
}
|
||
default:
|
||
throw new Error("jcs: unsupported value");
|
||
}
|
||
}
|
||
|
||
// src/api.ts
|
||
async function getJSON(url) {
|
||
const res = await fetch(url, { headers: { Accept: "application/json" } });
|
||
if (res.status === 404) return null;
|
||
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
|
||
return res.json();
|
||
}
|
||
async function getStatus() {
|
||
return await getJSON("/api/v1/status");
|
||
}
|
||
async function search(params) {
|
||
const data = await getJSON(`/api/v1/listings?${params}`);
|
||
if (!Array.isArray(data)) throw new Error("unexpected response");
|
||
return data;
|
||
}
|
||
async function getListing(author, id) {
|
||
return getJSON(`/api/v1/listings/${encodeURIComponent(author)}/${encodeURIComponent(id)}`);
|
||
}
|
||
var HttpError = class extends Error {
|
||
status;
|
||
detail;
|
||
constructor(status, detail) {
|
||
super(`${status} ${detail}`);
|
||
this.status = status;
|
||
this.detail = detail;
|
||
}
|
||
};
|
||
async function postMessage(envelope) {
|
||
const res = await fetch("/api/v1/messages", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: canonicalize(envelope)
|
||
// the node only accepts the canonical encoding
|
||
});
|
||
if (res.ok) return;
|
||
let detail = res.statusText;
|
||
try {
|
||
const body = await res.json();
|
||
if (typeof body.error === "string") detail = body.error;
|
||
} catch {
|
||
}
|
||
throw new HttpError(res.status, detail);
|
||
}
|
||
async function pollMailbox(tag, since) {
|
||
const data = await getJSON(`/api/v1/messages?mailbox=${encodeURIComponent(tag)}&since=${since}`);
|
||
if (!Array.isArray(data)) throw new Error("unexpected response");
|
||
return data;
|
||
}
|
||
|
||
// src/dom.ts
|
||
function h(tag, props = null, ...children) {
|
||
const el = document.createElement(tag);
|
||
for (const [key, value] of Object.entries(props ?? {})) {
|
||
if (value === void 0 || value === false) continue;
|
||
if (typeof value === "function") {
|
||
el.addEventListener(key.replace(/^on/, "").toLowerCase(), value);
|
||
} else if (value === true) {
|
||
el.setAttribute(key, "");
|
||
} else {
|
||
el.setAttribute(key, String(value));
|
||
}
|
||
}
|
||
append(el, children);
|
||
return el;
|
||
}
|
||
function append(parent, children) {
|
||
for (const c of children) {
|
||
if (c === null || c === void 0 || c === false) continue;
|
||
parent.appendChild(typeof c === "object" ? c : document.createTextNode(String(c)));
|
||
}
|
||
}
|
||
function clear(el) {
|
||
while (el.firstChild) el.removeChild(el.firstChild);
|
||
}
|
||
function sendOnCtrlEnter(area) {
|
||
area.addEventListener("keydown", (ev) => {
|
||
if (ev.key !== "Enter" || !(ev.ctrlKey || ev.metaKey) || ev.isComposing || area.disabled) return;
|
||
ev.preventDefault();
|
||
area.form?.requestSubmit();
|
||
});
|
||
}
|
||
|
||
// src/i18n.ts
|
||
var de = {
|
||
"app.tagline": "Wohnungen und H\xE4user, getragen von allen. Kostenlos, ohne Konzern.",
|
||
"status.line": "{listings} Anzeigen \xB7 {peers} verbundene Knoten \xB7 Regionen: {regions}",
|
||
"status.noRegions": "noch keine",
|
||
"search.noRegions": "Dieser Knoten folgt noch keiner Region und hat deshalb keine Anzeigen. Wer ihn betreibt, w\xE4hlt Regionen unter \u201EMeine Anzeigen\u201C > \u201ERegionen\u201C.",
|
||
"search.chooseRegions": "Regionen w\xE4hlen",
|
||
"status.unreachable": "Dieser Knoten ist nicht erreichbar.",
|
||
"filter.kind": "Angebot",
|
||
"filter.category": "Art",
|
||
"filter.region": "Gebiet (Geohash)",
|
||
"filter.regionHint": "z. B. u1x f\xFCr den Raum Hamburg, genauer: u1xj",
|
||
"filter.maxPrice": "Preis bis (\u20AC)",
|
||
"filter.minArea": "Fl\xE4che ab (m\xB2)",
|
||
"filter.minRooms": "Zimmer ab",
|
||
"filter.any": "Alle",
|
||
"filter.search": "Suchen",
|
||
"filter.reset": "Zur\xFCcksetzen",
|
||
"kind.rent": "Miete",
|
||
"kind.sale": "Kauf",
|
||
"cat.apartment": "Wohnung",
|
||
"cat.house": "Haus",
|
||
"cat.room": "Zimmer",
|
||
"cat.commercial": "Gewerbe",
|
||
"results.none": "Keine Anzeigen gefunden.",
|
||
"results.loading": "L\xE4dt \u2026",
|
||
"results.more": "Mehr laden",
|
||
"results.hidden": "{n} Ergebnis(se) ausgeblendet, weil die Signatur nicht gepr\xFCft werden konnte.",
|
||
"results.error": "Die Suche ist fehlgeschlagen.",
|
||
"card.perMonth": "/ Monat",
|
||
"card.rooms": "{n} Zimmer",
|
||
"card.area": "{n} m\xB2",
|
||
"badge.ok": "Signatur gepr\xFCft",
|
||
"badge.bad": "Nicht verifiziert",
|
||
"detail.back": "\u2190 Zur\xFCck zur Suche",
|
||
"detail.notFound": "Diese Anzeige gibt es nicht (mehr).",
|
||
"detail.unverified": "Diese Anzeige konnte nicht verifiziert werden und wird deshalb nicht angezeigt. Sie k\xF6nnte gef\xE4lscht oder ver\xE4ndert sein.",
|
||
"detail.features": "Ausstattung",
|
||
"detail.facts": "Eckdaten",
|
||
"detail.kind": "Angebot",
|
||
"detail.category": "Art",
|
||
"detail.area": "Fl\xE4che",
|
||
"detail.rooms": "Zimmer",
|
||
"detail.published": "Ver\xF6ffentlicht",
|
||
"detail.expires": "L\xE4uft ab",
|
||
"detail.version": "Version",
|
||
"detail.location": "Lage (ungef\xE4hr, ca. 1 km)",
|
||
"detail.map": "Auf OpenStreetMap ansehen (externe Seite)",
|
||
"detail.contact": "Kontakt",
|
||
"nav.messages": "Meine Nachrichten",
|
||
"contact.title": "Anbieter kontaktieren",
|
||
"contact.intro": "Deine Nachricht wird verschl\xFCsselt. Das Netzwerk sieht nur, dass jemand zu dieser Anzeige geschrieben hat, nicht wer und nicht was. Du brauchst kein Konto. Die genaue Adresse gibt der Anbieter selbst frei.",
|
||
"contact.rules": "Die erste Nachricht muss kurz sein und darf keine Links enthalten. Das sch\xFCtzt vor Betrug; nach der ersten Antwort des Anbieters entf\xE4llt es.",
|
||
"contact.label": "Deine Nachricht",
|
||
"compose.hint": "Strg+Enter sendet",
|
||
"contact.counter": "{used} / {max} Bytes",
|
||
"contact.send": "Verschl\xFCsselt senden",
|
||
"contact.sending": "Wird vorbereitet \u2026 (eine kleine Rechenaufgabe gegen Spam)",
|
||
"contact.already": "Du hast diesem Anbieter schon geschrieben.",
|
||
"contact.open": "Unterhaltung \xF6ffnen",
|
||
"problem.empty": "Bitte schreibe eine Nachricht.",
|
||
"problem.long": "Die Nachricht ist zu lang.",
|
||
"problem.control": "Die Nachricht enth\xE4lt unerlaubte Sonderzeichen.",
|
||
"problem.invalid": "Die Nachricht enth\xE4lt ung\xFCltige Zeichen.",
|
||
"problem.link": "Die erste Nachricht darf keine Links oder Webadressen enthalten (auch kein \u201EHallo.Ich\u201C ohne Leerzeichen nach dem Punkt).",
|
||
"send.404": "Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Ger\xE4t gewechselt. Lade die Anzeige neu.",
|
||
"send.429": "Zu viele Nachrichten. Bitte warte einen Moment.",
|
||
"send.other": "Senden fehlgeschlagen: {detail}",
|
||
"send.network": "Der Knoten ist nicht erreichbar.",
|
||
"chat.back": "\u2190 Zur Anzeige",
|
||
"chat.all": "\u2190 Alle Nachrichten",
|
||
"chat.title": "Unterhaltung zu: {title}",
|
||
"chat.untitled": "Anzeige {id}",
|
||
"chat.you": "Du",
|
||
"chat.owner": "Anbieter",
|
||
"chat.verified": "Vom Anbieter dieser Anzeige (Signatur gepr\xFCft)",
|
||
"chat.empty": "Noch keine Antwort. Der Anbieter bekommt deine Nachricht, sobald sein Knoten online ist (die Nachricht bleibt bis zu 14 Tage im Netz).",
|
||
"chat.reply": "Antworten",
|
||
"chat.replyRules": "Solange der Anbieter nicht geantwortet hat, gelten die Regeln der ersten Nachricht.",
|
||
"chat.link": "Dein privater Link zu dieser Unterhaltung",
|
||
"chat.linkHelp": "Setze ein Lesezeichen. Wer diesen Link kennt, kann die Unterhaltung lesen, gib ihn also nicht weiter. Ohne den Link und ohne die Daten dieses Browsers ist die Unterhaltung verloren.",
|
||
"chat.noStorage": "Dieser Browser speichert hier nichts (privates Fenster?). Die Unterhaltung geht verloren, wenn du die Seite schlie\xDFt, au\xDFer du merkst dir den Link unten.",
|
||
"chat.gone": "Die Anzeige ist nicht mehr verf\xFCgbar. Antworten des Anbieters kannst du weiter empfangen, aber nicht mehr schreiben.",
|
||
"chat.unverified": "Die Anzeige konnte nicht gepr\xFCft werden, daher kannst du gerade nicht schreiben.",
|
||
"chat.pollError": "Antworten konnten nicht abgerufen werden.",
|
||
"chat.rejected": "{n} Nachricht(en) im Postfach konnten nicht als echt best\xE4tigt werden und werden ignoriert.",
|
||
"chat.limit": "Nicht pr\xFCfbar: ob der Anbieter sein Ger\xE4t inzwischen gesperrt hat.",
|
||
"chat.delete": "Unterhaltung aus diesem Browser l\xF6schen",
|
||
"chat.deleteSure": "Wirklich l\xF6schen? Ohne den Link ist sie dann weg.",
|
||
"chat.deleteYes": "Ja, l\xF6schen",
|
||
"grant.title": "Adresse vom Anbieter freigegeben",
|
||
"grant.address": "Adresse",
|
||
"grant.phone": "Telefon",
|
||
"grant.email": "E-Mail",
|
||
"grant.note": "Hinweis des Anbieters",
|
||
"grant.until": "Angezeigt bis {date}",
|
||
"grant.expired": "Eine Adressfreigabe des Anbieters ist abgelaufen und wird nicht mehr angezeigt.",
|
||
"grant.privacy": "Gib diese Angaben nicht weiter.",
|
||
"inbox.title": "Meine Nachrichten",
|
||
"inbox.none": "Du hast noch keine Unterhaltungen. \xD6ffne eine Anzeige und schreibe dem Anbieter.",
|
||
"inbox.last": "Zuletzt: {date}",
|
||
"inbox.note": "Diese Liste liegt nur in diesem Browser.",
|
||
"nav.owner": "Meine Anzeigen",
|
||
"own.loginTitle": "Anmelden als Anbieter",
|
||
"own.loginHelp": "Beim Start gibt dein Knoten im Terminal einen Anmelde-Link aus. \xD6ffne ihn hier, oder f\xFCge den Token (Datei admin.token im Datenordner) ein. Er bleibt nur in diesem Tab gespeichert.",
|
||
"own.token": "Token",
|
||
"own.login": "Anmelden",
|
||
"own.loginBad": "Der Knoten hat den Token abgelehnt.",
|
||
"own.logout": "Abmelden",
|
||
"reg.title": "Regionen",
|
||
"reg.intro": "Dein Knoten h\xE4lt die Anzeigen dieser Regionen bereit und gibt sie an andere weiter. Suche einen Ort, zum Beispiel Bonn oder Hamburg. Die \xC4nderung gilt sofort und bleibt nach einem Neustart erhalten.",
|
||
"reg.search": "Ort suchen",
|
||
"reg.placeholder": "z. B. Bonn, K\xF6ln, Hamburg",
|
||
"reg.results": "Gefundene Orte",
|
||
"reg.none": "Dazu habe ich keinen Ort gefunden. Pr\xFCfe die Schreibweise, oder gib unten ein Regionsk\xFCrzel ein.",
|
||
"reg.noPlaces": "Die Ortsliste konnte nicht geladen werden. Du kannst unten Regionsk\xFCrzel eingeben.",
|
||
"reg.cellsTitle": "Regionen rund um {place}",
|
||
"reg.cellsHelp": "Eine Region ist ein Gebiet von etwa 100 bis 150 km Breite. Liegt der Ort nahe am Rand, kommt die Nachbarregion dazu, damit dir Anzeigen gleich hinter der Grenze nicht fehlen. Nimm den Haken heraus, was du nicht brauchst.",
|
||
"reg.here": "hier",
|
||
"reg.add": "Hinzuf\xFCgen",
|
||
"reg.chosen": "Ausgew\xE4hlte Regionen",
|
||
"reg.nothing": "Noch keine Region ausgew\xE4hlt.",
|
||
"reg.remove": "{region} entfernen",
|
||
"reg.codes": "Oder Regionsk\xFCrzel eingeben",
|
||
"reg.codesHelp": "F\xFCr alle, die sie kennen: drei Zeichen wie u1j, mehrere mit Komma getrennt.",
|
||
"reg.badCode": "\u201E{code}\u201C ist keine Region: es m\xFCssen genau 3 Zeichen sein (Ziffern und Buchstaben au\xDFer a, i, l, o).",
|
||
"reg.needOne": "W\xE4hle mindestens eine Region.",
|
||
"reg.tooMany": "Das sind zu viele Regionen (h\xF6chstens {max}).",
|
||
"reg.save": "Speichern",
|
||
"reg.saving": "Speichert \u2026",
|
||
"reg.saved": "Gespeichert. Der Knoten folgt jetzt diesen Regionen.",
|
||
"reg.failed": "Das hat nicht geklappt.",
|
||
"reg.signedOut": "Du bist abgemeldet. Melde dich unter \u201EMeine Anzeigen\u201C neu an.",
|
||
"reg.credit": "Ortsnamen: GeoNames (geonames.org), Lizenz CC BY 4.0.",
|
||
"own.listings": "Deine Anzeigen",
|
||
"own.none": "Dein Knoten hat keine aktiven Anzeigen.",
|
||
"own.perMonth": "/ Monat",
|
||
"own.needReply": "{n} brauchen eine Antwort",
|
||
"own.noRequests": "Keine Anfragen",
|
||
"own.allAnswered": "Alle beantwortet",
|
||
"own.addressSaved": "Adresse gespeichert",
|
||
"own.noAddress": "Keine Adresse gespeichert",
|
||
"own.backListings": "\u2190 Anzeigen",
|
||
"own.backRequests": "\u2190 Anfragen",
|
||
"own.pickListing": "W\xE4hle links eine Anzeige.",
|
||
"own.pickRequest": "W\xE4hle eine Anfrage.",
|
||
"own.addrTitle": "Adresse auf deinem Knoten",
|
||
"own.addrHelp": "Wird nie ver\xF6ffentlicht. Nur Personen, denen du sie freigibst, erhalten sie.",
|
||
"own.addrNone": "Noch keine Adresse gespeichert. Ohne sie kannst du keine Adresse freigeben.",
|
||
"own.addrChange": "\xC4ndern",
|
||
"own.addrAdd": "Adresse hinzuf\xFCgen",
|
||
"own.addrSave": "Speichern",
|
||
"own.addrRemove": "Entfernen",
|
||
"own.addrCancel": "Abbrechen",
|
||
"own.fAddress": "Adresse",
|
||
"own.fPhone": "Telefon (optional)",
|
||
"own.fEmail": "E-Mail (optional)",
|
||
"own.requests": "Anfragen",
|
||
"own.request": "Anfrage #{id}",
|
||
"own.filterAll": "Alle {n}",
|
||
"own.filterReply": "Braucht Antwort {n}",
|
||
"own.filterHidden": "Link versteckt {n}",
|
||
"own.noMatch": "Keine Anfragen in dieser Ansicht.",
|
||
"own.stReply": "Braucht Antwort",
|
||
"own.stReplied": "Beantwortet",
|
||
"own.stHidden": "Link versteckt",
|
||
"own.stGrant": "Adresse bis {date}",
|
||
"own.stGrantEnded": "Adresse abgelaufen",
|
||
"own.effort": "Aufwand {n} Bit",
|
||
"own.hiddenPreview": "Ausgeblendet: enth\xE4lt einen Link",
|
||
"own.limitNote": "Pro Anzeige zeigt dein Knoten nur eine begrenzte Zahl neuer Anfragen am Tag; der Rest wartet, die mit dem gr\xF6\xDFten Aufwand zuerst.",
|
||
"own.buyer": "Interessent",
|
||
"own.you": "Du",
|
||
"own.anon": "Anonym, Ende-zu-Ende-verschl\xFCsselt",
|
||
"own.first": "Erste Nachricht dieser Person. Bis du antwortest, darf sie nur kurzen Text ohne Links schicken. Alles wird als reiner Text angezeigt, nie als Link.",
|
||
"own.hiddenMsg": "Ausgeblendet: Eine erste Nachricht muss kurz sein und darf keine Links enthalten.",
|
||
"own.hintAddress": "Die Person fragt m\xF6glicherweise nach der Adresse (Vermutung anhand einzelner W\xF6rter). Mit \u201EAdresse freigeben\u201C schickst du sie.",
|
||
"own.grantSent": "Adresse freigegeben bis {date}",
|
||
"own.reply": "Antwort",
|
||
"own.send": "Senden",
|
||
"own.sending": "Wird gesendet \u2026",
|
||
"own.release": "Adresse freigeben",
|
||
"own.delete": "Unterhaltung l\xF6schen",
|
||
"own.deleteSure": "Wirklich l\xF6schen? Sie wird von deinem Knoten entfernt.",
|
||
"own.deleteYes": "Ja, l\xF6schen",
|
||
"own.sheetTitle": "Adresse freigeben",
|
||
"own.sheetHelp": "Eine signierte Nachricht, nur f\xFCr diese Person sichtbar. Ihr Bildschirm blendet sie nach dem Datum aus. Sie k\xF6nnte sie trotzdem kopiert haben.",
|
||
"own.fNote": "Hinweis an die Person",
|
||
"own.fValid": "Sichtbar f\xFCr",
|
||
"own.days": "{n} Tage",
|
||
"own.day": "1 Tag",
|
||
"own.remember": "Diese Adresse f\xFCr die Anzeige speichern",
|
||
"own.sendAddress": "Adresse senden",
|
||
"own.close": "Schlie\xDFen",
|
||
"own.needAddress": "Bitte gib eine Adresse ein.",
|
||
"own.loadError": "Konnte nicht geladen werden.",
|
||
"own.err": "Fehlgeschlagen: {detail}",
|
||
"own.new": "Neue Anzeige",
|
||
"own.edit": "Bearbeiten",
|
||
"own.renew": "Verl\xE4ngern",
|
||
"own.renewing": "Wird verl\xE4ngert \u2026",
|
||
"own.deleteListing": "Anzeige l\xF6schen",
|
||
"own.deleteListingSure": "Wirklich l\xF6schen? Die Anzeige verschwindet aus dem Netz, und Interessenten k\xF6nnen dich dar\xFCber nicht mehr erreichen.",
|
||
"own.daysLeft": "Noch {n} Tage",
|
||
"own.dayLeft": "Noch 1 Tag",
|
||
"own.expired": "Abgelaufen",
|
||
"own.soon": "L\xE4uft bald ab. \u201EVerl\xE4ngern\u201C stellt sie f\xFCr 30 Tage neu ein.",
|
||
"pub.createTitle": "Anzeige ver\xF6ffentlichen",
|
||
"pub.editTitle": "Anzeige bearbeiten",
|
||
"pub.intro": "Deine Anzeige wird signiert und an die Knoten deiner Region verteilt. Name, genaue Adresse und Kontaktdaten stehen nie darin.",
|
||
"pub.back": "\u2190 Zur\xFCck",
|
||
"pub.title": "Titel",
|
||
"pub.description": "Beschreibung",
|
||
"pub.priceRent": "Miete pro Monat (\u20AC)",
|
||
"pub.priceSale": "Kaufpreis (\u20AC)",
|
||
"pub.area": "Fl\xE4che in m\xB2 (optional)",
|
||
"pub.rooms": "Zimmer (optional, halbe Zimmer m\xF6glich)",
|
||
"pub.features": "Ausstattung (optional, mit Komma getrennt)",
|
||
"pub.location": "Lage",
|
||
"pub.locationHelp": "F\xFCge Koordinaten ein, zum Beispiel 53.5511, 9.9937 (in OpenStreetMap oder deiner Karten-App den Ort anklicken und kopieren; ein Link geht auch). Ver\xF6ffentlicht wird nur ein Gebiet von etwa einem Kilometer, nie die genaue Adresse.",
|
||
"pub.useLocation": "Meinen Standort verwenden",
|
||
"pub.locationShown": "Ver\xF6ffentlicht wird ein Gebiet von etwa {w} \xD7 {h} m um {lat}, {lon} (Code {hash}).",
|
||
"pub.duration": "Sichtbar f\xFCr",
|
||
"pub.addrTitle": "Genaue Adresse (optional)",
|
||
"pub.addrHelp": "Bleibt auf deinem Knoten und wird nie ver\xF6ffentlicht. Du gibst sie sp\xE4ter einzelnen Interessenten frei.",
|
||
"pub.publish": "Ver\xF6ffentlichen",
|
||
"pub.save": "\xC4nderungen speichern",
|
||
"pub.working": "Wird ver\xF6ffentlicht \u2026 (eine kleine Rechenaufgabe, ein paar Sekunden)",
|
||
"pub.notFound": "Diese Anzeige gibt es nicht (mehr).",
|
||
"pub.eTitle": "Bitte gib einen Titel an (h\xF6chstens 120 Zeichen, eine Zeile).",
|
||
"pub.eDescription": "Die Beschreibung ist zu lang (h\xF6chstens 4000 Zeichen) oder enth\xE4lt unerlaubte Zeichen.",
|
||
"pub.ePrice": "Bitte gib einen Betrag gr\xF6\xDFer als 0 an, zum Beispiel 1150 oder 1.150,50.",
|
||
"pub.eArea": "Die Fl\xE4che muss eine ganze Zahl sein (h\xF6chstens 100000).",
|
||
"pub.eRooms": "Zimmer: eine Zahl in halben Schritten, zum Beispiel 2,5.",
|
||
"pub.eFeatures": "H\xF6chstens 20 Merkmale mit je h\xF6chstens 40 Zeichen.",
|
||
"pub.eLocation": "Die Koordinaten konnten nicht gelesen werden. Beispiel: 53.5511, 9.9937",
|
||
"pub.eRegion": "Dein Knoten folgt der Region {region} nicht, du w\xFCrdest also keine Nachrichten zu dieser Anzeige erhalten. Starte den Knoten mit --region {region} oder w\xE4hle einen Ort in {regions}.",
|
||
"pub.eRegionEdit": "Die Region einer Anzeige l\xE4sst sich nicht \xE4ndern. L\xF6sche sie und lege eine neue an.",
|
||
"pub.eAddress": "Die Adresse ist zu lang (h\xF6chstens 300 Bytes).",
|
||
"verify.title": "Pr\xFCfung in deinem Browser",
|
||
"verify.intro": "Diese Pr\xFCfung l\xE4uft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt f\xE4lschen.",
|
||
"verify.limit": "Nicht pr\xFCfbar: ob der Anbieter sein Ger\xE4t inzwischen gesperrt hat. Das wei\xDF nur das Netzwerk; dein Knoten kennt den aktuellen Stand.",
|
||
"verify.format": "Aufbau der Anzeige",
|
||
"verify.certificate": "Ger\xE4tezertifikat des Anbieters ist g\xFCltig",
|
||
"verify.binding": "Zertifikat geh\xF6rt zu diesem Anbieter und Ger\xE4t",
|
||
"verify.validity": "Zeitr\xE4ume (Zertifikat, Anzeige) stimmen",
|
||
"verify.signature": "Signatur passt zum Inhalt",
|
||
"verify.pow": "Rechenaufwand gegen Spam (Proof-of-Work)",
|
||
"verify.owner": "Anbieter (Identit\xE4t)",
|
||
"verify.device": "Ger\xE4t",
|
||
"verify.raw": "Rohdaten (so signiert)",
|
||
"footer.text": "Allmende ist freie Software (AGPL-3.0). Es gibt keinen Betreiber und keine Geb\xFChren."
|
||
};
|
||
var en = {
|
||
"app.tagline": "Homes to rent and buy, run by everyone. Free, with no company behind it.",
|
||
"status.line": "{listings} listings \xB7 {peers} connected nodes \xB7 regions: {regions}",
|
||
"status.noRegions": "none yet",
|
||
"search.noRegions": "This node follows no region yet, so it has no listings. Whoever runs it chooses regions under \u201CMy listings\u201D > \u201CRegions\u201D.",
|
||
"search.chooseRegions": "Choose regions",
|
||
"status.unreachable": "This node is not reachable.",
|
||
"filter.kind": "Offer",
|
||
"filter.category": "Type",
|
||
"filter.region": "Area (geohash)",
|
||
"filter.regionHint": "e.g. u1x for the Hamburg area, more precise: u1xj",
|
||
"filter.maxPrice": "Price up to (\u20AC)",
|
||
"filter.minArea": "Area from (m\xB2)",
|
||
"filter.minRooms": "Rooms from",
|
||
"filter.any": "Any",
|
||
"filter.search": "Search",
|
||
"filter.reset": "Reset",
|
||
"kind.rent": "Rent",
|
||
"kind.sale": "Buy",
|
||
"cat.apartment": "Apartment",
|
||
"cat.house": "House",
|
||
"cat.room": "Room",
|
||
"cat.commercial": "Commercial",
|
||
"results.none": "No listings found.",
|
||
"results.loading": "Loading \u2026",
|
||
"results.more": "Load more",
|
||
"results.hidden": "{n} result(s) hidden because their signature could not be verified.",
|
||
"results.error": "The search failed.",
|
||
"card.perMonth": "/ month",
|
||
"card.rooms": "{n} rooms",
|
||
"card.area": "{n} m\xB2",
|
||
"badge.ok": "Signature verified",
|
||
"badge.bad": "Not verified",
|
||
"detail.back": "\u2190 Back to search",
|
||
"detail.notFound": "This listing does not exist (any more).",
|
||
"detail.unverified": "This listing could not be verified and is therefore not shown. It may be forged or altered.",
|
||
"detail.features": "Features",
|
||
"detail.facts": "Key facts",
|
||
"detail.kind": "Offer",
|
||
"detail.category": "Type",
|
||
"detail.area": "Area",
|
||
"detail.rooms": "Rooms",
|
||
"detail.published": "Published",
|
||
"detail.expires": "Expires",
|
||
"detail.version": "Version",
|
||
"detail.location": "Location (approximate, about 1 km)",
|
||
"detail.map": "View on OpenStreetMap (external site)",
|
||
"detail.contact": "Contact",
|
||
"nav.messages": "My messages",
|
||
"contact.title": "Contact the owner",
|
||
"contact.intro": "Your message is encrypted. The network only sees that someone wrote about this listing, not who and not what. You need no account. The owner releases the exact address themselves.",
|
||
"contact.rules": "The first message must be short and must not contain links. This protects against scams; it ends once the owner has replied.",
|
||
"contact.label": "Your message",
|
||
"compose.hint": "Ctrl+Enter sends",
|
||
"contact.counter": "{used} / {max} bytes",
|
||
"contact.send": "Send encrypted",
|
||
"contact.sending": "Preparing \u2026 (a small puzzle against spam)",
|
||
"contact.already": "You have already written to this owner.",
|
||
"contact.open": "Open conversation",
|
||
"problem.empty": "Please write a message.",
|
||
"problem.long": "The message is too long.",
|
||
"problem.control": "The message contains characters that are not allowed.",
|
||
"problem.invalid": "The message contains invalid characters.",
|
||
"problem.link": 'The first message must not contain links or web addresses (that includes "Hello.I" without a space after the full stop).',
|
||
"send.404": "This node does not know the listing (anymore), or the owner changed device. Reload the listing.",
|
||
"send.429": "Too many messages. Please wait a moment.",
|
||
"send.other": "Sending failed: {detail}",
|
||
"send.network": "The node is not reachable.",
|
||
"chat.back": "\u2190 Back to the listing",
|
||
"chat.all": "\u2190 All messages",
|
||
"chat.title": "Conversation about: {title}",
|
||
"chat.untitled": "Listing {id}",
|
||
"chat.you": "You",
|
||
"chat.owner": "Owner",
|
||
"chat.verified": "From the owner of this listing (signature verified)",
|
||
"chat.empty": "No reply yet. The owner receives your message once their node is online (it stays in the network for up to 14 days).",
|
||
"chat.reply": "Reply",
|
||
"chat.replyRules": "Until the owner has replied, the rules of the first message apply.",
|
||
"chat.link": "Your private link to this conversation",
|
||
"chat.linkHelp": "Bookmark it. Anyone who knows this link can read the conversation, so do not share it. Without the link and without this browser's data, the conversation is lost.",
|
||
"chat.noStorage": "This browser does not store anything here (private window?). The conversation is lost when you close the page unless you keep the link below.",
|
||
"chat.gone": "The listing is no longer available. You can still receive the owner's replies, but not write any more.",
|
||
"chat.unverified": "The listing could not be verified, so you cannot write right now.",
|
||
"chat.pollError": "Replies could not be fetched.",
|
||
"chat.rejected": "{n} message(s) in the mailbox could not be confirmed as genuine and are ignored.",
|
||
"chat.limit": "Cannot be checked: whether the owner has since revoked their device.",
|
||
"chat.delete": "Delete this conversation from this browser",
|
||
"chat.deleteSure": "Really delete? Without the link it is gone.",
|
||
"chat.deleteYes": "Yes, delete",
|
||
"grant.title": "Address released by the owner",
|
||
"grant.address": "Address",
|
||
"grant.phone": "Phone",
|
||
"grant.email": "Email",
|
||
"grant.note": "Note from the owner",
|
||
"grant.until": "Shown until {date}",
|
||
"grant.expired": "An address release from the owner has expired and is no longer shown.",
|
||
"grant.privacy": "Do not pass these details on.",
|
||
"inbox.title": "My messages",
|
||
"inbox.none": "You have no conversations yet. Open a listing and write to the owner.",
|
||
"inbox.last": "Last activity: {date}",
|
||
"inbox.note": "This list is kept only in this browser.",
|
||
"nav.owner": "My listings",
|
||
"own.loginTitle": "Sign in as owner",
|
||
"own.loginHelp": "When it starts, your node prints a sign-in link in the terminal. Open it here, or paste the token (the file admin.token in the data folder). It is kept in this tab only.",
|
||
"own.token": "Token",
|
||
"own.login": "Sign in",
|
||
"own.loginBad": "The node rejected the token.",
|
||
"own.logout": "Sign out",
|
||
"reg.title": "Regions",
|
||
"reg.intro": "Your node keeps the listings of these regions and passes them on to others. Search for a place, for example Bonn or Hamburg. A change applies at once and survives a restart.",
|
||
"reg.search": "Search for a place",
|
||
"reg.placeholder": "e.g. Bonn, Cologne, Hamburg",
|
||
"reg.results": "Places found",
|
||
"reg.none": "I found no place for that. Check the spelling, or enter a region code below.",
|
||
"reg.noPlaces": "The list of places could not be loaded. You can enter region codes below.",
|
||
"reg.cellsTitle": "Regions around {place}",
|
||
"reg.cellsHelp": "A region is an area roughly 100 to 150 km across. If the place is near an edge, the neighbouring region is included so you do not miss listings just across the border. Untick what you do not need.",
|
||
"reg.here": "here",
|
||
"reg.add": "Add",
|
||
"reg.chosen": "Chosen regions",
|
||
"reg.nothing": "No region chosen yet.",
|
||
"reg.remove": "Remove {region}",
|
||
"reg.codes": "Or enter region codes",
|
||
"reg.codesHelp": "For those who know them: three characters like u1j, several separated by commas.",
|
||
"reg.badCode": "\u201C{code}\u201D is not a region: it must be exactly 3 characters (digits and letters except a, i, l, o).",
|
||
"reg.needOne": "Choose at least one region.",
|
||
"reg.tooMany": "That is too many regions (at most {max}).",
|
||
"reg.save": "Save",
|
||
"reg.saving": "Saving \u2026",
|
||
"reg.saved": "Saved. The node now follows these regions.",
|
||
"reg.failed": "That did not work.",
|
||
"reg.signedOut": "You are signed out. Sign in again under \u201CMy listings\u201D.",
|
||
"reg.credit": "Place names: GeoNames (geonames.org), licence CC BY 4.0.",
|
||
"own.listings": "Your listings",
|
||
"own.none": "Your node has no active listings.",
|
||
"own.perMonth": "/ month",
|
||
"own.needReply": "{n} need a reply",
|
||
"own.noRequests": "No requests",
|
||
"own.allAnswered": "All answered",
|
||
"own.addressSaved": "Address saved",
|
||
"own.noAddress": "No address saved",
|
||
"own.backListings": "\u2190 Listings",
|
||
"own.backRequests": "\u2190 Requests",
|
||
"own.pickListing": "Choose a listing on the left.",
|
||
"own.pickRequest": "Choose a request.",
|
||
"own.addrTitle": "Address on your node",
|
||
"own.addrHelp": "Never published. Only people you release it to receive it.",
|
||
"own.addrNone": "No address saved yet. Without one you cannot release an address.",
|
||
"own.addrChange": "Change",
|
||
"own.addrAdd": "Add address",
|
||
"own.addrSave": "Save",
|
||
"own.addrRemove": "Remove",
|
||
"own.addrCancel": "Cancel",
|
||
"own.fAddress": "Address",
|
||
"own.fPhone": "Phone (optional)",
|
||
"own.fEmail": "Email (optional)",
|
||
"own.requests": "Requests",
|
||
"own.request": "Request #{id}",
|
||
"own.filterAll": "All {n}",
|
||
"own.filterReply": "Needs reply {n}",
|
||
"own.filterHidden": "Link hidden {n}",
|
||
"own.noMatch": "No requests in this view.",
|
||
"own.stReply": "Needs reply",
|
||
"own.stReplied": "Replied",
|
||
"own.stHidden": "Link hidden",
|
||
"own.stGrant": "Address until {date}",
|
||
"own.stGrantEnded": "Address expired",
|
||
"own.effort": "Effort {n} bit",
|
||
"own.hiddenPreview": "Hidden: contains a link",
|
||
"own.limitNote": "Your node shows only a limited number of new requests per listing per day; the rest wait, strongest effort first.",
|
||
"own.buyer": "Buyer",
|
||
"own.you": "You",
|
||
"own.anon": "Anonymous, end-to-end encrypted",
|
||
"own.first": "First message from this person. Until you reply they can send short text only, no links. Everything is shown as plain text, never as a link.",
|
||
"own.hiddenMsg": "Hidden: a first message must be short and contain no links.",
|
||
"own.hintAddress": 'This person may be asking for the address (a guess based on a few words). Use "Release address" to send it.',
|
||
"own.grantSent": "Address released until {date}",
|
||
"own.reply": "Reply",
|
||
"own.send": "Send",
|
||
"own.sending": "Sending \u2026",
|
||
"own.release": "Release address",
|
||
"own.delete": "Delete conversation",
|
||
"own.deleteSure": "Really delete? It is removed from your node.",
|
||
"own.deleteYes": "Yes, delete",
|
||
"own.sheetTitle": "Release address",
|
||
"own.sheetHelp": "A signed message, visible only to this person. Their screen hides it after the date. They could still have copied it.",
|
||
"own.fNote": "Note to the buyer",
|
||
"own.fValid": "Visible for",
|
||
"own.days": "{n} days",
|
||
"own.day": "1 day",
|
||
"own.remember": "Save this address for the listing",
|
||
"own.sendAddress": "Send address",
|
||
"own.close": "Close",
|
||
"own.needAddress": "Please enter an address.",
|
||
"own.loadError": "Could not be loaded.",
|
||
"own.err": "Failed: {detail}",
|
||
"own.new": "New listing",
|
||
"own.edit": "Edit",
|
||
"own.renew": "Renew",
|
||
"own.renewing": "Renewing \u2026",
|
||
"own.deleteListing": "Delete listing",
|
||
"own.deleteListingSure": "Really delete? The listing disappears from the network, and people can no longer reach you through it.",
|
||
"own.daysLeft": "{n} days left",
|
||
"own.dayLeft": "1 day left",
|
||
"own.expired": "Expired",
|
||
"own.soon": 'Expires soon. "Renew" publishes it again for 30 days.',
|
||
"pub.createTitle": "Publish a listing",
|
||
"pub.editTitle": "Edit listing",
|
||
"pub.intro": "Your listing is signed and spread to the nodes of your region. It never contains your name, exact address or contact details.",
|
||
"pub.back": "\u2190 Back",
|
||
"pub.title": "Title",
|
||
"pub.description": "Description",
|
||
"pub.priceRent": "Rent per month (\u20AC)",
|
||
"pub.priceSale": "Price (\u20AC)",
|
||
"pub.area": "Area in m\xB2 (optional)",
|
||
"pub.rooms": "Rooms (optional, half rooms allowed)",
|
||
"pub.features": "Features (optional, separated by commas)",
|
||
"pub.location": "Location",
|
||
"pub.locationHelp": "Paste coordinates, for example 53.5511, 9.9937 (click the place in OpenStreetMap or your map app and copy; a link works too). Only an area of about a kilometre is published, never the exact address.",
|
||
"pub.useLocation": "Use my location",
|
||
"pub.locationShown": "An area of about {w} \xD7 {h} m around {lat}, {lon} will be published (code {hash}).",
|
||
"pub.duration": "Visible for",
|
||
"pub.addrTitle": "Exact address (optional)",
|
||
"pub.addrHelp": "Stays on your node and is never published. You release it to individual people later.",
|
||
"pub.publish": "Publish",
|
||
"pub.save": "Save changes",
|
||
"pub.working": "Publishing \u2026 (a small puzzle, a few seconds)",
|
||
"pub.notFound": "This listing does not exist (any more).",
|
||
"pub.eTitle": "Please enter a title (at most 120 characters, one line).",
|
||
"pub.eDescription": "The description is too long (at most 4000 characters) or contains characters that are not allowed.",
|
||
"pub.ePrice": "Please enter an amount above 0, for example 1150 or 1,150.50.",
|
||
"pub.eArea": "The area must be a whole number (at most 100000).",
|
||
"pub.eRooms": "Rooms: a number in half steps, for example 2.5.",
|
||
"pub.eFeatures": "At most 20 features of at most 40 characters each.",
|
||
"pub.eLocation": "The coordinates could not be read. Example: 53.5511, 9.9937",
|
||
"pub.eRegion": "Your node does not follow region {region}, so you would not receive messages about this listing. Start the node with --region {region} or choose a place in {regions}.",
|
||
"pub.eRegionEdit": "A listing's region cannot change. Delete it and create a new one.",
|
||
"pub.eAddress": "The address is too long (at most 300 bytes).",
|
||
"verify.title": "Checked in your browser",
|
||
"verify.intro": "This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
|
||
"verify.limit": "Cannot be checked: whether the owner has since revoked their device. Only the network knows that; your node has the current state.",
|
||
"verify.format": "Structure of the listing",
|
||
"verify.certificate": "Owner's device certificate is valid",
|
||
"verify.binding": "Certificate belongs to this owner and device",
|
||
"verify.validity": "Time windows (certificate, listing) are right",
|
||
"verify.signature": "Signature matches the content",
|
||
"verify.pow": "Anti-spam work (proof-of-work)",
|
||
"verify.owner": "Owner (identity)",
|
||
"verify.device": "Device",
|
||
"verify.raw": "Raw data (as signed)",
|
||
"footer.text": "Allmende is free software (AGPL-3.0). There is no operator and there are no fees."
|
||
};
|
||
function detect() {
|
||
const q = new URLSearchParams(location.search).get("lang");
|
||
if (q === "de" || q === "en") return q;
|
||
return navigator.language?.toLowerCase().startsWith("de") ? "de" : "en";
|
||
}
|
||
var lang = detect();
|
||
var dict = lang === "de" ? de : en;
|
||
function t(key, vars = {}) {
|
||
return dict[key].replace(/\{(\w+)\}/g, (_, name) => String(vars[name] ?? ""));
|
||
}
|
||
|
||
// src/format.ts
|
||
function statusLine(n) {
|
||
return t("status.line", {
|
||
listings: n.listings,
|
||
peers: n.peers,
|
||
regions: n.regions.length ? n.regions.join(", ") : t("status.noRegions")
|
||
});
|
||
}
|
||
function money(cents) {
|
||
return new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(cents / 100);
|
||
}
|
||
function rooms(x2) {
|
||
return t("card.rooms", { n: (x2 / 2).toLocaleString(lang, { maximumFractionDigits: 1 }) });
|
||
}
|
||
function date(unix) {
|
||
return new Date(unix * 1e3).toLocaleDateString(lang, { dateStyle: "medium" });
|
||
}
|
||
function when(unix) {
|
||
const d = new Date(unix * 1e3);
|
||
if (d.toDateString() === new Date(Date.now()).toDateString()) {
|
||
return d.toLocaleTimeString(lang, { hour: "2-digit", minute: "2-digit" });
|
||
}
|
||
return d.toLocaleDateString(lang, { day: "numeric", month: "short" });
|
||
}
|
||
function price(l) {
|
||
if (!l.price) return "";
|
||
const base = money(l.price.amount_cents);
|
||
return l.price.period === "month" ? `${base} ${t("card.perMonth")}` : base;
|
||
}
|
||
function shortKey(hex) {
|
||
return hex.length > 16 ? `${hex.slice(0, 8)}\u2026${hex.slice(-4)}` : hex;
|
||
}
|
||
|
||
// src/geohash.ts
|
||
var ALPHABET = "0123456789bcdefghjkmnpqrstuvwxyz";
|
||
function decodeGeohash(hash) {
|
||
let lat = [-90, 90];
|
||
let lon = [-180, 180];
|
||
let evenBit = true;
|
||
for (const ch of hash) {
|
||
const idx = ALPHABET.indexOf(ch);
|
||
if (idx < 0) return null;
|
||
for (let bit = 4; bit >= 0; bit--) {
|
||
const on = idx >> bit & 1;
|
||
const range = evenBit ? lon : lat;
|
||
const mid = (range[0] + range[1]) / 2;
|
||
if (on) range[0] = mid;
|
||
else range[1] = mid;
|
||
evenBit = !evenBit;
|
||
}
|
||
}
|
||
return {
|
||
lat: (lat[0] + lat[1]) / 2,
|
||
lon: (lon[0] + lon[1]) / 2,
|
||
latErr: (lat[1] - lat[0]) / 2,
|
||
lonErr: (lon[1] - lon[0]) / 2
|
||
};
|
||
}
|
||
function encodeGeohash(lat, lon, precision = 6) {
|
||
let latR = [-90, 90];
|
||
let lonR = [-180, 180];
|
||
let out = "";
|
||
let bits = 0;
|
||
let value = 0;
|
||
let evenBit = true;
|
||
while (out.length < precision) {
|
||
const range = evenBit ? lonR : latR;
|
||
const x = evenBit ? lon : lat;
|
||
const mid = (range[0] + range[1]) / 2;
|
||
value <<= 1;
|
||
if (x >= mid) {
|
||
value |= 1;
|
||
range[0] = mid;
|
||
} else {
|
||
range[1] = mid;
|
||
}
|
||
evenBit = !evenBit;
|
||
if (++bits === 5) {
|
||
out += ALPHABET[value];
|
||
bits = 0;
|
||
value = 0;
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
var NUM = String.raw`[-+]?\d{1,3}(?:\.\d+)?`;
|
||
function parseCoordinates(input) {
|
||
const s = input.trim();
|
||
let a;
|
||
let b;
|
||
let m;
|
||
if (m = new RegExp(String.raw`#map=\d+/(${NUM})/(${NUM})`).exec(s)) [, a, b] = m;
|
||
else if (m = new RegExp(String.raw`mlat=(${NUM})&(?:amp;)?mlon=(${NUM})`).exec(s)) [, a, b] = m;
|
||
else if (m = new RegExp(String.raw`@(${NUM}),(${NUM})`).exec(s)) [, a, b] = m;
|
||
else if (m = new RegExp(String.raw`^(${NUM})\s*[,;]\s*(${NUM})$`).exec(s)) [, a, b] = m;
|
||
else if (m = /^([-+]?\d{1,3},\d+)\s*;\s*([-+]?\d{1,3},\d+)$/.exec(s)) [, a, b] = m.map((x) => x?.replace(",", "."));
|
||
else if (m = /^([-+]?\d{1,3}[.,]\d+)\s+([-+]?\d{1,3}[.,]\d+)$/.exec(s)) [, a, b] = m.map((x) => x?.replace(",", "."));
|
||
if (a === void 0 || b === void 0) return null;
|
||
const lat = Number(a);
|
||
const lon = Number(b);
|
||
if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
|
||
return { lat, lon };
|
||
}
|
||
function cellMetres(hash) {
|
||
const a = decodeGeohash(hash);
|
||
if (!a) return null;
|
||
return {
|
||
height: Math.round(a.latErr * 2 * 111320),
|
||
width: Math.round(a.lonErr * 2 * 111320 * Math.cos(a.lat * Math.PI / 180))
|
||
};
|
||
}
|
||
|
||
// src/fresh.ts
|
||
var FOREGROUND_MS = 8e3;
|
||
function keepFresh(alive, run, ms = FOREGROUND_MS, doc = document) {
|
||
let timer;
|
||
let running = false;
|
||
const stop = () => {
|
||
clearTimeout(timer);
|
||
doc.removeEventListener("visibilitychange", onVisible);
|
||
};
|
||
const schedule = () => {
|
||
clearTimeout(timer);
|
||
timer = setTimeout(() => void fire(), ms);
|
||
};
|
||
const fire = async () => {
|
||
if (!alive()) return stop();
|
||
if (doc.hidden) return;
|
||
if (running) return schedule();
|
||
running = true;
|
||
try {
|
||
await run();
|
||
} catch {
|
||
} finally {
|
||
running = false;
|
||
}
|
||
if (!alive()) return stop();
|
||
schedule();
|
||
};
|
||
const onVisible = () => {
|
||
if (!alive()) return stop();
|
||
if (doc.hidden) {
|
||
clearTimeout(timer);
|
||
return;
|
||
}
|
||
clearTimeout(timer);
|
||
void fire();
|
||
};
|
||
doc.addEventListener("visibilitychange", onVisible);
|
||
schedule();
|
||
}
|
||
|
||
// node_modules/@noble/ciphers/utils.js
|
||
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
||
function isBytes(a) {
|
||
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
||
}
|
||
var atitle = (title) => title ? `"${title}" ` : "";
|
||
function abool(value, title = "") {
|
||
if (typeof value !== "boolean")
|
||
throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
|
||
return value;
|
||
}
|
||
function anumber(n, title = "") {
|
||
if (typeof n !== "number")
|
||
throw new TypeError(atitle(title) + "expected number, got " + typeof n);
|
||
if (!Number.isSafeInteger(n) || n < 0)
|
||
throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
|
||
return n;
|
||
}
|
||
function abytes(value, length, title = "") {
|
||
if (isBytes(value) && (length === void 0 || value.length === length))
|
||
return value;
|
||
if (length !== void 0)
|
||
anumber(length, "length");
|
||
const bytes2 = isBytes(value);
|
||
const ofLen = length !== void 0 ? ` of length ${length}` : "";
|
||
const got = bytes2 ? `length=${value.length}` : `type=${typeof value}`;
|
||
const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
||
if (!bytes2)
|
||
throw new TypeError(message);
|
||
throw new RangeError(message);
|
||
}
|
||
var aobject = (value, label2) => {
|
||
if (value === null || typeof value !== "object" || Array.isArray(value))
|
||
throw new TypeError(label2 === "object" ? "expected valid options object" : `"${label2}" expected object, got type=${typeof value}`);
|
||
};
|
||
function aexists(instance, checkFinished = true) {
|
||
if (instance.destroyed)
|
||
throw new Error("hash was destroyed");
|
||
if (checkFinished && instance.finished)
|
||
throw new Error("digest() was already called");
|
||
}
|
||
function aoutput(out, instance) {
|
||
abytes(out, void 0, "output");
|
||
const min = instance.outputLen;
|
||
if (!(out.length >= min)) {
|
||
throw new RangeError('"output" expected length >= ' + min);
|
||
}
|
||
}
|
||
function u32(arr) {
|
||
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
||
}
|
||
function clean(...arrays) {
|
||
for (let i = 0; i < arrays.length; i++) {
|
||
arrays[i].fill(0);
|
||
}
|
||
}
|
||
function createView(arr) {
|
||
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
||
}
|
||
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
||
function byteSwap(word) {
|
||
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
|
||
}
|
||
function byteSwap32(arr) {
|
||
for (let i = 0; i < arr.length; i++) {
|
||
arr[i] = byteSwap(arr[i]);
|
||
}
|
||
return arr;
|
||
}
|
||
var swap32IfBE = isLE ? (u) => u : byteSwap32;
|
||
function overlapBytes(a, b) {
|
||
if (!a.byteLength || !b.byteLength)
|
||
return false;
|
||
return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
|
||
a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
|
||
b.byteOffset < a.byteOffset + a.byteLength;
|
||
}
|
||
function complexOverlapBytes(input, output) {
|
||
if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
|
||
throw new Error("complex overlap of input and output is not supported");
|
||
}
|
||
function checkOpts(defaults, opts) {
|
||
aobject(defaults, "defaults");
|
||
aobject(opts, "opts");
|
||
const merged = Object.assign(defaults, opts);
|
||
return merged;
|
||
}
|
||
function equalBytes(a, b) {
|
||
a = abytes(a);
|
||
b = abytes(b);
|
||
if (a.length !== b.length)
|
||
return false;
|
||
let diff = 0;
|
||
for (let i = 0; i < a.length; i++)
|
||
diff |= a[i] ^ b[i];
|
||
return diff === 0;
|
||
}
|
||
function wrapMacConstructor(keyLen, macCons, fromMsg) {
|
||
const mac = macCons;
|
||
const getArgs = fromMsg || (() => []);
|
||
const macC = (msg, key) => mac(key, ...getArgs(msg)).update(msg).digest();
|
||
const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
|
||
macC.outputLen = tmp.outputLen;
|
||
macC.blockLen = tmp.blockLen;
|
||
macC.create = (key, ...args) => mac(key, ...args);
|
||
return macC;
|
||
}
|
||
var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
|
||
function wrappedCipher(key, ...args) {
|
||
abytes(key, void 0, "key");
|
||
if (params.nonceLength !== void 0) {
|
||
const nonce = args[0];
|
||
abytes(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
|
||
}
|
||
const tagl = params.tagLength;
|
||
const aadStart = params.nonceLength !== void 0 ? 1 : 0;
|
||
if (!params.withAAD) {
|
||
for (let i = aadStart; i < args.length; i++)
|
||
if (isBytes(args[i]))
|
||
throw new Error("AAD not supported");
|
||
}
|
||
if (params.withAAD && args[aadStart] !== void 0)
|
||
abytes(args[aadStart], void 0, "AAD");
|
||
const cipher = constructor(key, ...args);
|
||
const checkOutput = (fnLength, output) => {
|
||
if (output !== void 0) {
|
||
if (fnLength !== 2)
|
||
throw new Error("cipher output not supported");
|
||
abytes(output, void 0, "output");
|
||
}
|
||
};
|
||
let called = false;
|
||
const wrCipher = {
|
||
encrypt(data, output) {
|
||
if (called)
|
||
throw new Error("cannot encrypt() twice with same key + nonce");
|
||
called = true;
|
||
abytes(data, void 0, "data");
|
||
checkOutput(cipher.encrypt.length, output);
|
||
return cipher.encrypt(data, output);
|
||
},
|
||
decrypt(data, output) {
|
||
abytes(data, void 0, "data");
|
||
if (tagl && data.length < tagl)
|
||
throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
|
||
checkOutput(cipher.decrypt.length, output);
|
||
return cipher.decrypt(data, output);
|
||
}
|
||
};
|
||
return wrCipher;
|
||
}
|
||
Object.assign(wrappedCipher, params);
|
||
return wrappedCipher;
|
||
};
|
||
function getOutput(expectedLength, out, onlyAligned = true) {
|
||
if (out === void 0)
|
||
return new Uint8Array(expectedLength);
|
||
abytes(out, expectedLength, "output");
|
||
if (onlyAligned && !isAligned32(out))
|
||
throw new Error("invalid output, must be aligned");
|
||
return out;
|
||
}
|
||
function u64Lengths(dataLength, aadLength, isLE2) {
|
||
anumber(dataLength);
|
||
anumber(aadLength);
|
||
abool(isLE2);
|
||
const num2 = new Uint8Array(16);
|
||
const view = createView(num2);
|
||
view.setBigUint64(0, BigInt(aadLength), isLE2);
|
||
view.setBigUint64(8, BigInt(dataLength), isLE2);
|
||
return num2;
|
||
}
|
||
function isAligned32(bytes2) {
|
||
return bytes2.byteOffset % 4 === 0;
|
||
}
|
||
function copyBytes(bytes2) {
|
||
return Uint8Array.from(abytes(bytes2));
|
||
}
|
||
|
||
// node_modules/@noble/ciphers/_arx.js
|
||
var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
|
||
var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))();
|
||
var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))();
|
||
function rotl(a, b) {
|
||
return a << b | a >>> 32 - b;
|
||
}
|
||
var BLOCK_LEN = 64;
|
||
var BLOCK_LEN32 = 16;
|
||
var MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
|
||
var U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
|
||
function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
|
||
const len = data.length;
|
||
const block = new Uint8Array(BLOCK_LEN);
|
||
const b32 = u32(block);
|
||
const isAligned = isLE && isAligned32(data) && isAligned32(output);
|
||
const d32 = isAligned ? u32(data) : U32_EMPTY;
|
||
const o32 = isAligned ? u32(output) : U32_EMPTY;
|
||
if (!isLE) {
|
||
for (let pos = 0; pos < len; counter++) {
|
||
core(sigma, key, nonce, b32, counter, rounds);
|
||
swap32IfBE(b32);
|
||
if (counter >= MAX_COUNTER)
|
||
throw new Error("arx: counter overflow");
|
||
const take = Math.min(BLOCK_LEN, len - pos);
|
||
for (let j = 0, posj; j < take; j++) {
|
||
posj = pos + j;
|
||
output[posj] = data[posj] ^ block[j];
|
||
}
|
||
pos += take;
|
||
}
|
||
return;
|
||
}
|
||
for (let pos = 0; pos < len; counter++) {
|
||
core(sigma, key, nonce, b32, counter, rounds);
|
||
if (counter >= MAX_COUNTER)
|
||
throw new Error("arx: counter overflow");
|
||
const take = Math.min(BLOCK_LEN, len - pos);
|
||
if (isAligned && take === BLOCK_LEN) {
|
||
const pos32 = pos / 4;
|
||
if (pos % 4 !== 0)
|
||
throw new Error("arx: invalid block position");
|
||
for (let j = 0, posj; j < BLOCK_LEN32; j++) {
|
||
posj = pos32 + j;
|
||
o32[posj] = d32[posj] ^ b32[j];
|
||
}
|
||
pos += BLOCK_LEN;
|
||
continue;
|
||
}
|
||
for (let j = 0, posj; j < take; j++) {
|
||
posj = pos + j;
|
||
output[posj] = data[posj] ^ block[j];
|
||
}
|
||
pos += take;
|
||
}
|
||
}
|
||
function createCipher(core, opts) {
|
||
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
|
||
if (typeof core !== "function")
|
||
throw new Error("core must be a function");
|
||
anumber(counterLength);
|
||
anumber(rounds);
|
||
abool(counterRight);
|
||
abool(allowShortKeys);
|
||
return (key, nonce, data, output, counter = 0) => {
|
||
abytes(key, void 0, "key");
|
||
abytes(nonce, void 0, "nonce");
|
||
abytes(data, void 0, "data");
|
||
const len = data.length;
|
||
const hasOutput = output !== void 0;
|
||
output = getOutput(len, output, false);
|
||
if (hasOutput)
|
||
complexOverlapBytes(data, output);
|
||
anumber(counter);
|
||
if (counter < 0 || counter >= MAX_COUNTER)
|
||
throw new Error("arx: counter overflow");
|
||
const toClean = [];
|
||
let l = key.length;
|
||
let k;
|
||
let sigma;
|
||
if (l === 32) {
|
||
toClean.push(k = copyBytes(key));
|
||
sigma = sigma32_32;
|
||
} else if (l === 16 && allowShortKeys) {
|
||
k = new Uint8Array(32);
|
||
k.set(key);
|
||
k.set(key, 16);
|
||
sigma = sigma16_32;
|
||
toClean.push(k);
|
||
} else {
|
||
abytes(key, 32, "arx key");
|
||
throw new Error("invalid key size");
|
||
}
|
||
if (!isLE || !isAligned32(nonce))
|
||
toClean.push(nonce = copyBytes(nonce));
|
||
let k32 = u32(k);
|
||
if (extendNonceFn) {
|
||
if (nonce.length !== 24)
|
||
throw new Error("arx: extended nonce must be 24 bytes");
|
||
const n16 = nonce.subarray(0, 16);
|
||
if (isLE)
|
||
extendNonceFn(sigma, k32, u32(n16), k32);
|
||
else {
|
||
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
|
||
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
|
||
clean(sigmaRaw);
|
||
swap32IfBE(k32);
|
||
}
|
||
nonce = nonce.subarray(16);
|
||
} else if (!isLE)
|
||
swap32IfBE(k32);
|
||
const nonceNcLen = 16 - counterLength;
|
||
if (nonceNcLen !== nonce.length)
|
||
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
|
||
if (nonceNcLen !== 12) {
|
||
const nc = new Uint8Array(12);
|
||
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
|
||
nonce = nc;
|
||
toClean.push(nonce);
|
||
}
|
||
const n32 = swap32IfBE(u32(nonce));
|
||
try {
|
||
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
|
||
return output;
|
||
} finally {
|
||
clean(...toClean);
|
||
}
|
||
};
|
||
}
|
||
|
||
// node_modules/@noble/ciphers/_poly1305.js
|
||
function u8to16(a, i) {
|
||
return a[i++] & 255 | (a[i++] & 255) << 8;
|
||
}
|
||
var Poly1305 = class {
|
||
blockLen = 16;
|
||
outputLen = 16;
|
||
buffer = new Uint8Array(16);
|
||
r = new Uint16Array(10);
|
||
// Allocating 1 array with .subarray() here is slower than 3
|
||
h = new Uint16Array(10);
|
||
pad = new Uint16Array(8);
|
||
pos = 0;
|
||
finished = false;
|
||
destroyed = false;
|
||
// Can be speed-up using BigUint64Array, at the cost of complexity
|
||
constructor(key) {
|
||
key = copyBytes(abytes(key, 32, "key"));
|
||
const t0 = u8to16(key, 0);
|
||
const t1 = u8to16(key, 2);
|
||
const t2 = u8to16(key, 4);
|
||
const t3 = u8to16(key, 6);
|
||
const t4 = u8to16(key, 8);
|
||
const t5 = u8to16(key, 10);
|
||
const t6 = u8to16(key, 12);
|
||
const t7 = u8to16(key, 14);
|
||
this.r[0] = t0 & 8191;
|
||
this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
|
||
this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
|
||
this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
|
||
this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
|
||
this.r[5] = t4 >>> 1 & 8190;
|
||
this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
|
||
this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
|
||
this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
|
||
this.r[9] = t7 >>> 5 & 127;
|
||
for (let i = 0; i < 8; i++)
|
||
this.pad[i] = u8to16(key, 16 + 2 * i);
|
||
}
|
||
process(data, offset, isLast = false) {
|
||
const hibit = isLast ? 0 : 1 << 11;
|
||
const { h: h2, r } = this;
|
||
const r0 = r[0];
|
||
const r1 = r[1];
|
||
const r2 = r[2];
|
||
const r3 = r[3];
|
||
const r4 = r[4];
|
||
const r5 = r[5];
|
||
const r6 = r[6];
|
||
const r7 = r[7];
|
||
const r8 = r[8];
|
||
const r9 = r[9];
|
||
const t0 = u8to16(data, offset + 0);
|
||
const t1 = u8to16(data, offset + 2);
|
||
const t2 = u8to16(data, offset + 4);
|
||
const t3 = u8to16(data, offset + 6);
|
||
const t4 = u8to16(data, offset + 8);
|
||
const t5 = u8to16(data, offset + 10);
|
||
const t6 = u8to16(data, offset + 12);
|
||
const t7 = u8to16(data, offset + 14);
|
||
let h0 = h2[0] + (t0 & 8191);
|
||
let h1 = h2[1] + ((t0 >>> 13 | t1 << 3) & 8191);
|
||
let h22 = h2[2] + ((t1 >>> 10 | t2 << 6) & 8191);
|
||
let h3 = h2[3] + ((t2 >>> 7 | t3 << 9) & 8191);
|
||
let h4 = h2[4] + ((t3 >>> 4 | t4 << 12) & 8191);
|
||
let h5 = h2[5] + (t4 >>> 1 & 8191);
|
||
let h6 = h2[6] + ((t4 >>> 14 | t5 << 2) & 8191);
|
||
let h7 = h2[7] + ((t5 >>> 11 | t6 << 5) & 8191);
|
||
let h8 = h2[8] + ((t6 >>> 8 | t7 << 8) & 8191);
|
||
let h9 = h2[9] + (t7 >>> 5 | hibit);
|
||
let c = 0;
|
||
let d0 = c + h0 * r0 + h1 * (5 * r9) + h22 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
|
||
c = d0 >>> 13;
|
||
d0 &= 8191;
|
||
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
|
||
c += d0 >>> 13;
|
||
d0 &= 8191;
|
||
let d1 = c + h0 * r1 + h1 * r0 + h22 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
|
||
c = d1 >>> 13;
|
||
d1 &= 8191;
|
||
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
|
||
c += d1 >>> 13;
|
||
d1 &= 8191;
|
||
let d2 = c + h0 * r2 + h1 * r1 + h22 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
|
||
c = d2 >>> 13;
|
||
d2 &= 8191;
|
||
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
|
||
c += d2 >>> 13;
|
||
d2 &= 8191;
|
||
let d3 = c + h0 * r3 + h1 * r2 + h22 * r1 + h3 * r0 + h4 * (5 * r9);
|
||
c = d3 >>> 13;
|
||
d3 &= 8191;
|
||
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
|
||
c += d3 >>> 13;
|
||
d3 &= 8191;
|
||
let d4 = c + h0 * r4 + h1 * r3 + h22 * r2 + h3 * r1 + h4 * r0;
|
||
c = d4 >>> 13;
|
||
d4 &= 8191;
|
||
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
|
||
c += d4 >>> 13;
|
||
d4 &= 8191;
|
||
let d5 = c + h0 * r5 + h1 * r4 + h22 * r3 + h3 * r2 + h4 * r1;
|
||
c = d5 >>> 13;
|
||
d5 &= 8191;
|
||
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
|
||
c += d5 >>> 13;
|
||
d5 &= 8191;
|
||
let d6 = c + h0 * r6 + h1 * r5 + h22 * r4 + h3 * r3 + h4 * r2;
|
||
c = d6 >>> 13;
|
||
d6 &= 8191;
|
||
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
|
||
c += d6 >>> 13;
|
||
d6 &= 8191;
|
||
let d7 = c + h0 * r7 + h1 * r6 + h22 * r5 + h3 * r4 + h4 * r3;
|
||
c = d7 >>> 13;
|
||
d7 &= 8191;
|
||
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
|
||
c += d7 >>> 13;
|
||
d7 &= 8191;
|
||
let d8 = c + h0 * r8 + h1 * r7 + h22 * r6 + h3 * r5 + h4 * r4;
|
||
c = d8 >>> 13;
|
||
d8 &= 8191;
|
||
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
|
||
c += d8 >>> 13;
|
||
d8 &= 8191;
|
||
let d9 = c + h0 * r9 + h1 * r8 + h22 * r7 + h3 * r6 + h4 * r5;
|
||
c = d9 >>> 13;
|
||
d9 &= 8191;
|
||
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
|
||
c += d9 >>> 13;
|
||
d9 &= 8191;
|
||
c = (c << 2) + c | 0;
|
||
c = c + d0 | 0;
|
||
d0 = c & 8191;
|
||
c = c >>> 13;
|
||
d1 += c;
|
||
h2[0] = d0;
|
||
h2[1] = d1;
|
||
h2[2] = d2;
|
||
h2[3] = d3;
|
||
h2[4] = d4;
|
||
h2[5] = d5;
|
||
h2[6] = d6;
|
||
h2[7] = d7;
|
||
h2[8] = d8;
|
||
h2[9] = d9;
|
||
}
|
||
finalize() {
|
||
const { h: h2, pad: pad2 } = this;
|
||
const g = new Uint16Array(10);
|
||
let c = h2[1] >>> 13;
|
||
h2[1] &= 8191;
|
||
for (let i = 2; i < 10; i++) {
|
||
h2[i] += c;
|
||
c = h2[i] >>> 13;
|
||
h2[i] &= 8191;
|
||
}
|
||
h2[0] += c * 5;
|
||
c = h2[0] >>> 13;
|
||
h2[0] &= 8191;
|
||
h2[1] += c;
|
||
c = h2[1] >>> 13;
|
||
h2[1] &= 8191;
|
||
h2[2] += c;
|
||
g[0] = h2[0] + 5;
|
||
c = g[0] >>> 13;
|
||
g[0] &= 8191;
|
||
for (let i = 1; i < 10; i++) {
|
||
g[i] = h2[i] + c;
|
||
c = g[i] >>> 13;
|
||
g[i] &= 8191;
|
||
}
|
||
g[9] -= 1 << 13;
|
||
let mask = (c ^ 1) - 1;
|
||
for (let i = 0; i < 10; i++)
|
||
g[i] &= mask;
|
||
mask = ~mask;
|
||
for (let i = 0; i < 10; i++)
|
||
h2[i] = h2[i] & mask | g[i];
|
||
h2[0] = (h2[0] | h2[1] << 13) & 65535;
|
||
h2[1] = (h2[1] >>> 3 | h2[2] << 10) & 65535;
|
||
h2[2] = (h2[2] >>> 6 | h2[3] << 7) & 65535;
|
||
h2[3] = (h2[3] >>> 9 | h2[4] << 4) & 65535;
|
||
h2[4] = (h2[4] >>> 12 | h2[5] << 1 | h2[6] << 14) & 65535;
|
||
h2[5] = (h2[6] >>> 2 | h2[7] << 11) & 65535;
|
||
h2[6] = (h2[7] >>> 5 | h2[8] << 8) & 65535;
|
||
h2[7] = (h2[8] >>> 8 | h2[9] << 5) & 65535;
|
||
let f = h2[0] + pad2[0];
|
||
h2[0] = f & 65535;
|
||
for (let i = 1; i < 8; i++) {
|
||
f = (h2[i] + pad2[i] | 0) + (f >>> 16) | 0;
|
||
h2[i] = f & 65535;
|
||
}
|
||
clean(g);
|
||
}
|
||
update(data) {
|
||
aexists(this);
|
||
abytes(data);
|
||
data = copyBytes(data);
|
||
const { buffer, blockLen } = this;
|
||
const len = data.length;
|
||
for (let pos = 0; pos < len; ) {
|
||
const take = Math.min(blockLen - this.pos, len - pos);
|
||
if (take === blockLen) {
|
||
for (; blockLen <= len - pos; pos += blockLen)
|
||
this.process(data, pos);
|
||
continue;
|
||
}
|
||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||
this.pos += take;
|
||
pos += take;
|
||
if (this.pos === blockLen) {
|
||
this.process(buffer, 0, false);
|
||
this.pos = 0;
|
||
}
|
||
}
|
||
return this;
|
||
}
|
||
destroy() {
|
||
this.destroyed = true;
|
||
clean(this.h, this.r, this.buffer, this.pad);
|
||
}
|
||
digestInto(out) {
|
||
aexists(this);
|
||
aoutput(out, this);
|
||
this.finished = true;
|
||
const { buffer, h: h2 } = this;
|
||
let { pos } = this;
|
||
if (pos) {
|
||
buffer[pos++] = 1;
|
||
for (; pos < 16; pos++)
|
||
buffer[pos] = 0;
|
||
this.process(buffer, 0, true);
|
||
}
|
||
this.finalize();
|
||
let opos = 0;
|
||
for (let i = 0; i < 8; i++) {
|
||
out[opos++] = h2[i] >>> 0;
|
||
out[opos++] = h2[i] >>> 8;
|
||
}
|
||
}
|
||
digest() {
|
||
const { buffer, outputLen } = this;
|
||
this.digestInto(buffer);
|
||
const res = buffer.slice(0, outputLen);
|
||
this.destroy();
|
||
return res;
|
||
}
|
||
};
|
||
var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
|
||
|
||
// node_modules/@noble/ciphers/chacha.js
|
||
function chachaCore(s, k, n, out, cnt, rounds = 20) {
|
||
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
|
||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||
for (let r = 0; r < rounds; r += 2) {
|
||
x00 = x00 + x04 | 0;
|
||
x12 = rotl(x12 ^ x00, 16);
|
||
x08 = x08 + x12 | 0;
|
||
x04 = rotl(x04 ^ x08, 12);
|
||
x00 = x00 + x04 | 0;
|
||
x12 = rotl(x12 ^ x00, 8);
|
||
x08 = x08 + x12 | 0;
|
||
x04 = rotl(x04 ^ x08, 7);
|
||
x01 = x01 + x05 | 0;
|
||
x13 = rotl(x13 ^ x01, 16);
|
||
x09 = x09 + x13 | 0;
|
||
x05 = rotl(x05 ^ x09, 12);
|
||
x01 = x01 + x05 | 0;
|
||
x13 = rotl(x13 ^ x01, 8);
|
||
x09 = x09 + x13 | 0;
|
||
x05 = rotl(x05 ^ x09, 7);
|
||
x02 = x02 + x06 | 0;
|
||
x14 = rotl(x14 ^ x02, 16);
|
||
x10 = x10 + x14 | 0;
|
||
x06 = rotl(x06 ^ x10, 12);
|
||
x02 = x02 + x06 | 0;
|
||
x14 = rotl(x14 ^ x02, 8);
|
||
x10 = x10 + x14 | 0;
|
||
x06 = rotl(x06 ^ x10, 7);
|
||
x03 = x03 + x07 | 0;
|
||
x15 = rotl(x15 ^ x03, 16);
|
||
x11 = x11 + x15 | 0;
|
||
x07 = rotl(x07 ^ x11, 12);
|
||
x03 = x03 + x07 | 0;
|
||
x15 = rotl(x15 ^ x03, 8);
|
||
x11 = x11 + x15 | 0;
|
||
x07 = rotl(x07 ^ x11, 7);
|
||
x00 = x00 + x05 | 0;
|
||
x15 = rotl(x15 ^ x00, 16);
|
||
x10 = x10 + x15 | 0;
|
||
x05 = rotl(x05 ^ x10, 12);
|
||
x00 = x00 + x05 | 0;
|
||
x15 = rotl(x15 ^ x00, 8);
|
||
x10 = x10 + x15 | 0;
|
||
x05 = rotl(x05 ^ x10, 7);
|
||
x01 = x01 + x06 | 0;
|
||
x12 = rotl(x12 ^ x01, 16);
|
||
x11 = x11 + x12 | 0;
|
||
x06 = rotl(x06 ^ x11, 12);
|
||
x01 = x01 + x06 | 0;
|
||
x12 = rotl(x12 ^ x01, 8);
|
||
x11 = x11 + x12 | 0;
|
||
x06 = rotl(x06 ^ x11, 7);
|
||
x02 = x02 + x07 | 0;
|
||
x13 = rotl(x13 ^ x02, 16);
|
||
x08 = x08 + x13 | 0;
|
||
x07 = rotl(x07 ^ x08, 12);
|
||
x02 = x02 + x07 | 0;
|
||
x13 = rotl(x13 ^ x02, 8);
|
||
x08 = x08 + x13 | 0;
|
||
x07 = rotl(x07 ^ x08, 7);
|
||
x03 = x03 + x04 | 0;
|
||
x14 = rotl(x14 ^ x03, 16);
|
||
x09 = x09 + x14 | 0;
|
||
x04 = rotl(x04 ^ x09, 12);
|
||
x03 = x03 + x04 | 0;
|
||
x14 = rotl(x14 ^ x03, 8);
|
||
x09 = x09 + x14 | 0;
|
||
x04 = rotl(x04 ^ x09, 7);
|
||
}
|
||
let oi = 0;
|
||
out[oi++] = y00 + x00 | 0;
|
||
out[oi++] = y01 + x01 | 0;
|
||
out[oi++] = y02 + x02 | 0;
|
||
out[oi++] = y03 + x03 | 0;
|
||
out[oi++] = y04 + x04 | 0;
|
||
out[oi++] = y05 + x05 | 0;
|
||
out[oi++] = y06 + x06 | 0;
|
||
out[oi++] = y07 + x07 | 0;
|
||
out[oi++] = y08 + x08 | 0;
|
||
out[oi++] = y09 + x09 | 0;
|
||
out[oi++] = y10 + x10 | 0;
|
||
out[oi++] = y11 + x11 | 0;
|
||
out[oi++] = y12 + x12 | 0;
|
||
out[oi++] = y13 + x13 | 0;
|
||
out[oi++] = y14 + x14 | 0;
|
||
out[oi++] = y15 + x15 | 0;
|
||
}
|
||
var chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
||
counterRight: false,
|
||
counterLength: 4,
|
||
allowShortKeys: false
|
||
});
|
||
var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||
var updatePadded = (h2, msg) => {
|
||
h2.update(msg);
|
||
const leftover = msg.length % 16;
|
||
if (leftover)
|
||
h2.update(ZEROS16.subarray(leftover));
|
||
};
|
||
var ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
|
||
function computeTag(fn, key, nonce, ciphertext, AAD) {
|
||
if (AAD !== void 0)
|
||
abytes(AAD, void 0, "AAD");
|
||
const authKey = fn(key, nonce, ZEROS32);
|
||
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
|
||
const h2 = poly1305.create(authKey);
|
||
if (AAD)
|
||
updatePadded(h2, AAD);
|
||
updatePadded(h2, ciphertext);
|
||
h2.update(lengths);
|
||
const res = h2.digest();
|
||
clean(authKey, lengths);
|
||
return res;
|
||
}
|
||
var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
|
||
const tagLength = 16;
|
||
return {
|
||
encrypt(plaintext, output) {
|
||
const plength = plaintext.length;
|
||
output = getOutput(plength + tagLength, output, false);
|
||
output.set(plaintext);
|
||
const oPlain = output.subarray(0, -tagLength);
|
||
xorStream(key, nonce, oPlain, oPlain, 1);
|
||
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
|
||
output.set(tag, plength);
|
||
clean(tag);
|
||
return output;
|
||
},
|
||
decrypt(ciphertext, output) {
|
||
output = getOutput(ciphertext.length - tagLength, output, false);
|
||
const data = ciphertext.subarray(0, -tagLength);
|
||
const passedTag = ciphertext.subarray(-tagLength);
|
||
const tag = computeTag(xorStream, key, nonce, data, AAD);
|
||
if (!equalBytes(passedTag, tag)) {
|
||
clean(tag);
|
||
throw new Error("invalid tag");
|
||
}
|
||
output.set(ciphertext.subarray(0, -tagLength));
|
||
xorStream(key, nonce, output, output, 1);
|
||
clean(tag);
|
||
return output;
|
||
}
|
||
};
|
||
};
|
||
var chacha20poly1305 = /* @__PURE__ */ wrapCipher(
|
||
{ blockSize: 64, nonceLength: 12, tagLength: 16, withAAD: true },
|
||
/* @__PURE__ */ _poly1305_aead(chacha20)
|
||
);
|
||
|
||
// node_modules/@noble/hashes/_u64.js
|
||
var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
|
||
var _32n = /* @__PURE__ */ BigInt(32);
|
||
function fromBig(n, le = false) {
|
||
if (le)
|
||
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
|
||
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
||
}
|
||
function split(lst, le = false) {
|
||
const len = lst.length;
|
||
let Ah = new Uint32Array(len);
|
||
let Al = new Uint32Array(len);
|
||
for (let i = 0; i < len; i++) {
|
||
const { h: h2, l } = fromBig(lst[i], le);
|
||
[Ah[i], Al[i]] = [h2, l];
|
||
}
|
||
return [Ah, Al];
|
||
}
|
||
var fromNumH = (n) => n / 2 ** 32 | 0;
|
||
var fromNumL = (n) => n >>> 0;
|
||
function setU64FromNum(view, byteOffset, n, isLE2) {
|
||
const h2 = fromNumH(n);
|
||
const l = fromNumL(n);
|
||
view.setUint32(byteOffset, isLE2 ? l : h2, isLE2);
|
||
view.setUint32(byteOffset + 4, isLE2 ? h2 : l, isLE2);
|
||
}
|
||
var shrSH = (h2, _l, s) => h2 >>> s;
|
||
var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
|
||
var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
|
||
var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
|
||
var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
|
||
var rotrBL = (h2, l, s) => h2 >>> s - 32 | l << 64 - s;
|
||
function add(Ah, Al, Bh, Bl) {
|
||
const l = (Al >>> 0) + (Bl >>> 0);
|
||
return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
|
||
}
|
||
var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
|
||
var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
|
||
var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
|
||
var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
|
||
var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
||
var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
|
||
|
||
// node_modules/@noble/hashes/utils.js
|
||
function isBytes2(a) {
|
||
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
||
}
|
||
var atitle2 = (title) => title ? `"${title}" ` : "";
|
||
function anumber2(n, title = "") {
|
||
if (typeof n !== "number")
|
||
throw new TypeError(atitle2(title) + "expected number, got " + typeof n);
|
||
if (!Number.isSafeInteger(n) || n < 0)
|
||
throw new RangeError(atitle2(title) + "expected integer >= 0, got " + n);
|
||
return n;
|
||
}
|
||
function abytes2(value, length, title = "") {
|
||
if (isBytes2(value) && (length === void 0 || value.length === length))
|
||
return value;
|
||
if (length !== void 0)
|
||
anumber2(length, "length");
|
||
const bytes2 = isBytes2(value);
|
||
const ofLen = length !== void 0 ? ` of length ${length}` : "";
|
||
const got = bytes2 ? `length=${value.length}` : `type=${typeof value}`;
|
||
const message = atitle2(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
||
if (!bytes2)
|
||
throw new TypeError(message);
|
||
throw new RangeError(message);
|
||
}
|
||
function ahash(h2) {
|
||
if (typeof h2 !== "function" || typeof h2.create !== "function")
|
||
throw new TypeError("expected hash wrapped by utils.createHasher");
|
||
anumber2(h2.outputLen);
|
||
anumber2(h2.blockLen);
|
||
if (h2.outputLen < 1 || h2.blockLen < 1)
|
||
throw new Error("hash blockLen / outputLen must be >= 1");
|
||
}
|
||
var aobject2 = (value, label2) => {
|
||
if (value === null || typeof value !== "object" || Array.isArray(value))
|
||
throw new TypeError((label2 === "object" ? "" : `"${label2}" `) + "expected object, got type=" + typeof value);
|
||
};
|
||
var aopts = (value, label2) => {
|
||
aobject2(value, label2);
|
||
const proto = Object.getPrototypeOf(value);
|
||
if (proto !== Object.prototype && proto !== null)
|
||
throw new TypeError(`"${label2}" expected plain object`);
|
||
if (Object.hasOwn(value, "__proto__"))
|
||
throw new TypeError(`"${label2}.__proto__" is not allowed`);
|
||
};
|
||
function aexists2(instance, checkFinished = true) {
|
||
if (instance.destroyed)
|
||
throw new Error("hash was destroyed");
|
||
if (checkFinished && instance.finished)
|
||
throw new Error("digest() was already called");
|
||
}
|
||
function aoutput2(out, instance) {
|
||
abytes2(out, void 0, "output");
|
||
const min = instance.outputLen;
|
||
if (!(out.length >= min)) {
|
||
throw new RangeError('"output" expected length >= ' + min);
|
||
}
|
||
}
|
||
function clean2(...arrays) {
|
||
for (let i = 0; i < arrays.length; i++) {
|
||
arrays[i].fill(0);
|
||
}
|
||
}
|
||
function createView2(arr) {
|
||
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
||
}
|
||
function rotr(word, shift) {
|
||
return word << 32 - shift | word >>> shift;
|
||
}
|
||
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
||
// @ts-ignore
|
||
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
||
))();
|
||
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
||
function bytesToHex(bytes2) {
|
||
abytes2(bytes2);
|
||
if (hasHexBuiltin)
|
||
return bytes2.toHex();
|
||
let hex = "";
|
||
for (let i = 0; i < bytes2.length; i++) {
|
||
hex += hexes[bytes2[i]];
|
||
}
|
||
return hex;
|
||
}
|
||
function asciiToBase16(ch) {
|
||
return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
|
||
}
|
||
function hexToBytes(hex) {
|
||
if (typeof hex !== "string")
|
||
throw new TypeError("hex string expected, got " + typeof hex);
|
||
if (hasHexBuiltin) {
|
||
try {
|
||
return Uint8Array.fromHex(hex);
|
||
} catch (error) {
|
||
if (error instanceof SyntaxError)
|
||
throw new RangeError(error.message);
|
||
throw error;
|
||
}
|
||
}
|
||
const hl = hex.length;
|
||
const al = hl / 2;
|
||
if (hl % 2)
|
||
throw new RangeError("hex string expected, got unpadded hex of length " + hl);
|
||
const array = new Uint8Array(al);
|
||
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
||
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
||
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
||
if (n1 === void 0 || n2 === void 0) {
|
||
const char = hex[hi] + hex[hi + 1];
|
||
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
||
}
|
||
array[ai] = n1 * 16 + n2;
|
||
}
|
||
return array;
|
||
}
|
||
function concatBytes(...arrays) {
|
||
let sum = 0;
|
||
for (let i = 0; i < arrays.length; i++) {
|
||
const a = arrays[i];
|
||
abytes2(a);
|
||
sum += a.length;
|
||
}
|
||
const res = new Uint8Array(sum);
|
||
for (let i = 0, pad2 = 0; i < arrays.length; i++) {
|
||
const a = arrays[i];
|
||
res.set(a, pad2);
|
||
pad2 += a.length;
|
||
}
|
||
return res;
|
||
}
|
||
function checkOpts2(defaults, opts, title = "opts") {
|
||
aopts(defaults, "defaults");
|
||
if (opts !== void 0)
|
||
aopts(opts, title);
|
||
const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
|
||
return merged;
|
||
}
|
||
function createHasher(hashCons, info = {}) {
|
||
if (typeof hashCons !== "function")
|
||
throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
|
||
info = checkOpts2({}, info, "info");
|
||
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
||
const tmp = hashCons(void 0);
|
||
hashC.outputLen = tmp.outputLen;
|
||
hashC.blockLen = tmp.blockLen;
|
||
hashC.canXOF = tmp.canXOF;
|
||
hashC.create = (opts) => hashCons(opts);
|
||
Object.assign(hashC, info);
|
||
return Object.freeze(hashC);
|
||
}
|
||
function randomBytes2(bytesLength = 32) {
|
||
anumber2(bytesLength, "bytesLength");
|
||
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
||
if (typeof cr?.getRandomValues !== "function")
|
||
throw new Error("crypto.getRandomValues must be defined");
|
||
if (bytesLength > 65536)
|
||
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
||
return cr.getRandomValues(new Uint8Array(bytesLength));
|
||
}
|
||
var oidNist = (suffix) => ({
|
||
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
|
||
// Larger suffix values would need base-128 OID encoding and a different length byte.
|
||
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
||
});
|
||
|
||
// node_modules/@noble/hashes/_md.js
|
||
function Chi(a, b, c) {
|
||
return a & b ^ ~a & c;
|
||
}
|
||
function Maj(a, b, c) {
|
||
return a & b ^ a & c ^ b & c;
|
||
}
|
||
var HashMD = class {
|
||
blockLen;
|
||
outputLen;
|
||
canXOF = false;
|
||
padOffset;
|
||
isLE;
|
||
// For partial updates less than block size
|
||
buffer;
|
||
view;
|
||
finished = false;
|
||
length = 0;
|
||
pos = 0;
|
||
destroyed = false;
|
||
constructor(blockLen, outputLen, padOffset, isLE2) {
|
||
this.blockLen = blockLen;
|
||
this.outputLen = outputLen;
|
||
this.padOffset = padOffset;
|
||
this.isLE = isLE2;
|
||
this.buffer = new Uint8Array(blockLen);
|
||
this.view = createView2(this.buffer);
|
||
}
|
||
update(data) {
|
||
aexists2(this);
|
||
abytes2(data);
|
||
const { view, buffer, blockLen } = this;
|
||
const len = data.length;
|
||
let processed = false;
|
||
for (let pos = 0; pos < len; ) {
|
||
const take = Math.min(blockLen - this.pos, len - pos);
|
||
if (take === blockLen) {
|
||
const dataView = createView2(data);
|
||
for (; blockLen <= len - pos; pos += blockLen)
|
||
this.process(dataView, pos);
|
||
processed = true;
|
||
continue;
|
||
}
|
||
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
||
this.pos += take;
|
||
pos += take;
|
||
if (this.pos === blockLen) {
|
||
this.process(view, 0);
|
||
this.pos = 0;
|
||
processed = true;
|
||
}
|
||
}
|
||
this.length += data.length;
|
||
if (processed)
|
||
this.roundClean();
|
||
return this;
|
||
}
|
||
digestInto(out) {
|
||
aexists2(this);
|
||
aoutput2(out, this);
|
||
this.finished = true;
|
||
const { buffer, view, blockLen, isLE: isLE2 } = this;
|
||
let { pos } = this;
|
||
buffer[pos++] = 128;
|
||
buffer.fill(0, pos);
|
||
if (this.padOffset > blockLen - pos) {
|
||
this.process(view, 0);
|
||
buffer.fill(0);
|
||
}
|
||
setU64FromNum(view, blockLen - 8, this.length * 8, isLE2);
|
||
this.process(view, 0);
|
||
this.roundClean();
|
||
const oview = out === buffer ? view : createView2(out);
|
||
const len = this.outputLen;
|
||
const outLen = len / 4;
|
||
const state2 = this.get();
|
||
if (len % 4 || outLen > state2.length)
|
||
throw new Error("invalid outputLen");
|
||
for (let i = 0; i < outLen; i++)
|
||
oview.setUint32(4 * i, state2[i], isLE2);
|
||
}
|
||
digest() {
|
||
const { buffer, outputLen } = this;
|
||
this.digestInto(buffer);
|
||
const res = buffer.slice(0, outputLen);
|
||
this.destroy();
|
||
return res;
|
||
}
|
||
_cloneIntoMeta(to) {
|
||
const { buffer, length, finished, destroyed, pos } = this;
|
||
to.destroyed = destroyed;
|
||
to.finished = finished;
|
||
to.length = length;
|
||
to.pos = pos;
|
||
if (pos)
|
||
to.buffer.set(buffer);
|
||
return to;
|
||
}
|
||
clone() {
|
||
return this._cloneInto();
|
||
}
|
||
};
|
||
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
||
1779033703,
|
||
3144134277,
|
||
1013904242,
|
||
2773480762,
|
||
1359893119,
|
||
2600822924,
|
||
528734635,
|
||
1541459225
|
||
]);
|
||
var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
|
||
1779033703,
|
||
4089235720,
|
||
3144134277,
|
||
2227873595,
|
||
1013904242,
|
||
4271175723,
|
||
2773480762,
|
||
1595750129,
|
||
1359893119,
|
||
2917565137,
|
||
2600822924,
|
||
725511199,
|
||
528734635,
|
||
4215389547,
|
||
1541459225,
|
||
327033209
|
||
]);
|
||
|
||
// node_modules/@noble/hashes/sha2.js
|
||
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
||
1116352408,
|
||
1899447441,
|
||
3049323471,
|
||
3921009573,
|
||
961987163,
|
||
1508970993,
|
||
2453635748,
|
||
2870763221,
|
||
3624381080,
|
||
310598401,
|
||
607225278,
|
||
1426881987,
|
||
1925078388,
|
||
2162078206,
|
||
2614888103,
|
||
3248222580,
|
||
3835390401,
|
||
4022224774,
|
||
264347078,
|
||
604807628,
|
||
770255983,
|
||
1249150122,
|
||
1555081692,
|
||
1996064986,
|
||
2554220882,
|
||
2821834349,
|
||
2952996808,
|
||
3210313671,
|
||
3336571891,
|
||
3584528711,
|
||
113926993,
|
||
338241895,
|
||
666307205,
|
||
773529912,
|
||
1294757372,
|
||
1396182291,
|
||
1695183700,
|
||
1986661051,
|
||
2177026350,
|
||
2456956037,
|
||
2730485921,
|
||
2820302411,
|
||
3259730800,
|
||
3345764771,
|
||
3516065817,
|
||
3600352804,
|
||
4094571909,
|
||
275423344,
|
||
430227734,
|
||
506948616,
|
||
659060556,
|
||
883997877,
|
||
958139571,
|
||
1322822218,
|
||
1537002063,
|
||
1747873779,
|
||
1955562222,
|
||
2024104815,
|
||
2227730452,
|
||
2361852424,
|
||
2428436474,
|
||
2756734187,
|
||
3204031479,
|
||
3329325298
|
||
]);
|
||
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
||
var SHA2_32B = class extends HashMD {
|
||
// We cannot use array here since array allows indexing by variable
|
||
// which means optimizer/compiler cannot use registers.
|
||
// Numeric initializers matter: starting the fields as `undefined` changes
|
||
// V8's field representation and makes sha256 3x slower (measured).
|
||
A = 0;
|
||
B = 0;
|
||
C = 0;
|
||
D = 0;
|
||
E = 0;
|
||
F = 0;
|
||
G = 0;
|
||
H = 0;
|
||
constructor(outputLen, IV) {
|
||
super(64, outputLen, 8, false);
|
||
this.A = IV[0] | 0;
|
||
this.B = IV[1] | 0;
|
||
this.C = IV[2] | 0;
|
||
this.D = IV[3] | 0;
|
||
this.E = IV[4] | 0;
|
||
this.F = IV[5] | 0;
|
||
this.G = IV[6] | 0;
|
||
this.H = IV[7] | 0;
|
||
}
|
||
get() {
|
||
const { A, B, C, D, E, F, G, H } = this;
|
||
return [A, B, C, D, E, F, G, H];
|
||
}
|
||
// prettier-ignore
|
||
set(A, B, C, D, E, F, G, H) {
|
||
this.A = A | 0;
|
||
this.B = B | 0;
|
||
this.C = C | 0;
|
||
this.D = D | 0;
|
||
this.E = E | 0;
|
||
this.F = F | 0;
|
||
this.G = G | 0;
|
||
this.H = H | 0;
|
||
}
|
||
_cloneInto(to) {
|
||
(to ||= new this.constructor()).set(...this.get());
|
||
return this._cloneIntoMeta(to);
|
||
}
|
||
process(view, offset) {
|
||
for (let i = 0; i < 16; i++, offset += 4)
|
||
SHA256_W[i] = view.getUint32(offset, false);
|
||
for (let i = 16; i < 64; i++) {
|
||
const W15 = SHA256_W[i - 15];
|
||
const W2 = SHA256_W[i - 2];
|
||
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
||
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
||
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
||
}
|
||
let { A, B, C, D, E, F, G, H } = this;
|
||
for (let i = 0; i < 64; i++) {
|
||
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
||
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
||
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
||
const T2 = sigma0 + Maj(A, B, C) | 0;
|
||
H = G;
|
||
G = F;
|
||
F = E;
|
||
E = D + T1 | 0;
|
||
D = C;
|
||
C = B;
|
||
B = A;
|
||
A = T1 + T2 | 0;
|
||
}
|
||
A = A + this.A | 0;
|
||
B = B + this.B | 0;
|
||
C = C + this.C | 0;
|
||
D = D + this.D | 0;
|
||
E = E + this.E | 0;
|
||
F = F + this.F | 0;
|
||
G = G + this.G | 0;
|
||
H = H + this.H | 0;
|
||
this.set(A, B, C, D, E, F, G, H);
|
||
}
|
||
roundClean() {
|
||
clean2(SHA256_W);
|
||
}
|
||
destroy() {
|
||
this.destroyed = true;
|
||
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
||
clean2(this.buffer);
|
||
}
|
||
};
|
||
var _SHA256 = class extends SHA2_32B {
|
||
constructor() {
|
||
super(32, SHA256_IV);
|
||
}
|
||
};
|
||
var K512 = /* @__PURE__ */ (() => split([
|
||
"0x428a2f98d728ae22",
|
||
"0x7137449123ef65cd",
|
||
"0xb5c0fbcfec4d3b2f",
|
||
"0xe9b5dba58189dbbc",
|
||
"0x3956c25bf348b538",
|
||
"0x59f111f1b605d019",
|
||
"0x923f82a4af194f9b",
|
||
"0xab1c5ed5da6d8118",
|
||
"0xd807aa98a3030242",
|
||
"0x12835b0145706fbe",
|
||
"0x243185be4ee4b28c",
|
||
"0x550c7dc3d5ffb4e2",
|
||
"0x72be5d74f27b896f",
|
||
"0x80deb1fe3b1696b1",
|
||
"0x9bdc06a725c71235",
|
||
"0xc19bf174cf692694",
|
||
"0xe49b69c19ef14ad2",
|
||
"0xefbe4786384f25e3",
|
||
"0x0fc19dc68b8cd5b5",
|
||
"0x240ca1cc77ac9c65",
|
||
"0x2de92c6f592b0275",
|
||
"0x4a7484aa6ea6e483",
|
||
"0x5cb0a9dcbd41fbd4",
|
||
"0x76f988da831153b5",
|
||
"0x983e5152ee66dfab",
|
||
"0xa831c66d2db43210",
|
||
"0xb00327c898fb213f",
|
||
"0xbf597fc7beef0ee4",
|
||
"0xc6e00bf33da88fc2",
|
||
"0xd5a79147930aa725",
|
||
"0x06ca6351e003826f",
|
||
"0x142929670a0e6e70",
|
||
"0x27b70a8546d22ffc",
|
||
"0x2e1b21385c26c926",
|
||
"0x4d2c6dfc5ac42aed",
|
||
"0x53380d139d95b3df",
|
||
"0x650a73548baf63de",
|
||
"0x766a0abb3c77b2a8",
|
||
"0x81c2c92e47edaee6",
|
||
"0x92722c851482353b",
|
||
"0xa2bfe8a14cf10364",
|
||
"0xa81a664bbc423001",
|
||
"0xc24b8b70d0f89791",
|
||
"0xc76c51a30654be30",
|
||
"0xd192e819d6ef5218",
|
||
"0xd69906245565a910",
|
||
"0xf40e35855771202a",
|
||
"0x106aa07032bbd1b8",
|
||
"0x19a4c116b8d2d0c8",
|
||
"0x1e376c085141ab53",
|
||
"0x2748774cdf8eeb99",
|
||
"0x34b0bcb5e19b48a8",
|
||
"0x391c0cb3c5c95a63",
|
||
"0x4ed8aa4ae3418acb",
|
||
"0x5b9cca4f7763e373",
|
||
"0x682e6ff3d6b2b8a3",
|
||
"0x748f82ee5defb2fc",
|
||
"0x78a5636f43172f60",
|
||
"0x84c87814a1f0ab72",
|
||
"0x8cc702081a6439ec",
|
||
"0x90befffa23631e28",
|
||
"0xa4506cebde82bde9",
|
||
"0xbef9a3f7b2c67915",
|
||
"0xc67178f2e372532b",
|
||
"0xca273eceea26619c",
|
||
"0xd186b8c721c0c207",
|
||
"0xeada7dd6cde0eb1e",
|
||
"0xf57d4f7fee6ed178",
|
||
"0x06f067aa72176fba",
|
||
"0x0a637dc5a2c898a6",
|
||
"0x113f9804bef90dae",
|
||
"0x1b710b35131c471b",
|
||
"0x28db77f523047d84",
|
||
"0x32caab7b40c72493",
|
||
"0x3c9ebe0a15c9bebc",
|
||
"0x431d67c49c100d4c",
|
||
"0x4cc5d4becb3e42b6",
|
||
"0x597f299cfc657e2a",
|
||
"0x5fcb6fab3ad6faec",
|
||
"0x6c44198c4a475817"
|
||
].map((n) => BigInt(n))))();
|
||
var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
|
||
var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
|
||
var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
|
||
var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
|
||
var SHA2_64B = class extends HashMD {
|
||
// We cannot use array here since array allows indexing by variable
|
||
// which means optimizer/compiler cannot use registers.
|
||
// h -- high 32 bits, l -- low 32 bits
|
||
// Numeric initializers matter: starting the fields as `undefined` changes
|
||
// V8's field representation and slows hashing down (measured on sha256).
|
||
Ah = 0;
|
||
Al = 0;
|
||
Bh = 0;
|
||
Bl = 0;
|
||
Ch = 0;
|
||
Cl = 0;
|
||
Dh = 0;
|
||
Dl = 0;
|
||
Eh = 0;
|
||
El = 0;
|
||
Fh = 0;
|
||
Fl = 0;
|
||
Gh = 0;
|
||
Gl = 0;
|
||
Hh = 0;
|
||
Hl = 0;
|
||
constructor(outputLen, IV) {
|
||
super(128, outputLen, 16, false);
|
||
this.Ah = IV[0] | 0;
|
||
this.Al = IV[1] | 0;
|
||
this.Bh = IV[2] | 0;
|
||
this.Bl = IV[3] | 0;
|
||
this.Ch = IV[4] | 0;
|
||
this.Cl = IV[5] | 0;
|
||
this.Dh = IV[6] | 0;
|
||
this.Dl = IV[7] | 0;
|
||
this.Eh = IV[8] | 0;
|
||
this.El = IV[9] | 0;
|
||
this.Fh = IV[10] | 0;
|
||
this.Fl = IV[11] | 0;
|
||
this.Gh = IV[12] | 0;
|
||
this.Gl = IV[13] | 0;
|
||
this.Hh = IV[14] | 0;
|
||
this.Hl = IV[15] | 0;
|
||
}
|
||
// prettier-ignore
|
||
get() {
|
||
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
|
||
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
|
||
}
|
||
// prettier-ignore
|
||
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
|
||
this.Ah = Ah | 0;
|
||
this.Al = Al | 0;
|
||
this.Bh = Bh | 0;
|
||
this.Bl = Bl | 0;
|
||
this.Ch = Ch | 0;
|
||
this.Cl = Cl | 0;
|
||
this.Dh = Dh | 0;
|
||
this.Dl = Dl | 0;
|
||
this.Eh = Eh | 0;
|
||
this.El = El | 0;
|
||
this.Fh = Fh | 0;
|
||
this.Fl = Fl | 0;
|
||
this.Gh = Gh | 0;
|
||
this.Gl = Gl | 0;
|
||
this.Hh = Hh | 0;
|
||
this.Hl = Hl | 0;
|
||
}
|
||
_cloneInto(to) {
|
||
(to ||= new this.constructor()).set(...this.get());
|
||
return this._cloneIntoMeta(to);
|
||
}
|
||
process(view, offset) {
|
||
for (let i = 0; i < 16; i++, offset += 4) {
|
||
SHA512_W_H[i] = view.getUint32(offset);
|
||
SHA512_W_L[i] = view.getUint32(offset += 4);
|
||
}
|
||
for (let i = 16; i < 80; i++) {
|
||
const W15h = SHA512_W_H[i - 15] | 0;
|
||
const W15l = SHA512_W_L[i - 15] | 0;
|
||
const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
|
||
const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
|
||
const W2h = SHA512_W_H[i - 2] | 0;
|
||
const W2l = SHA512_W_L[i - 2] | 0;
|
||
const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
|
||
const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
|
||
const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
|
||
const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
|
||
SHA512_W_H[i] = SUMh | 0;
|
||
SHA512_W_L[i] = SUMl | 0;
|
||
}
|
||
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
|
||
for (let i = 0; i < 80; i++) {
|
||
const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
|
||
const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
|
||
const CHIh = Eh & Fh ^ ~Eh & Gh;
|
||
const CHIl = El & Fl ^ ~El & Gl;
|
||
const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
|
||
const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
|
||
const T1l = T1ll | 0;
|
||
const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
|
||
const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
|
||
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
|
||
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
|
||
Hh = Gh | 0;
|
||
Hl = Gl | 0;
|
||
Gh = Fh | 0;
|
||
Gl = Fl | 0;
|
||
Fh = Eh | 0;
|
||
Fl = El | 0;
|
||
({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
|
||
Dh = Ch | 0;
|
||
Dl = Cl | 0;
|
||
Ch = Bh | 0;
|
||
Cl = Bl | 0;
|
||
Bh = Ah | 0;
|
||
Bl = Al | 0;
|
||
const All = add3L(T1l, sigma0l, MAJl);
|
||
Ah = add3H(All, T1h, sigma0h, MAJh);
|
||
Al = All | 0;
|
||
}
|
||
({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
|
||
({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
|
||
({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
|
||
({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
|
||
({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
|
||
({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
|
||
({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
|
||
({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
|
||
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
|
||
}
|
||
roundClean() {
|
||
clean2(SHA512_W_H, SHA512_W_L);
|
||
}
|
||
destroy() {
|
||
this.destroyed = true;
|
||
clean2(this.buffer);
|
||
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||
}
|
||
};
|
||
var _SHA512 = class extends SHA2_64B {
|
||
constructor() {
|
||
super(64, SHA512_IV);
|
||
}
|
||
};
|
||
var sha256 = /* @__PURE__ */ createHasher(
|
||
() => new _SHA256(),
|
||
/* @__PURE__ */ oidNist(1)
|
||
);
|
||
var sha512 = /* @__PURE__ */ createHasher(
|
||
() => new _SHA512(),
|
||
/* @__PURE__ */ oidNist(3)
|
||
);
|
||
|
||
// node_modules/@noble/curves/utils.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
function aarray(item, title, inner = () => {
|
||
}) {
|
||
if (!Array.isArray(item))
|
||
throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
|
||
for (let i = 0; i < item.length; i++)
|
||
inner(item[i], `${title}[${i}]`);
|
||
return item;
|
||
}
|
||
var abytes3 = (value, length, title) => abytes2(value, length, title);
|
||
var anumber3 = anumber2;
|
||
function aobject3(value, title = "object") {
|
||
if (value === null || typeof value !== "object" || Array.isArray(value))
|
||
throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
|
||
return value;
|
||
}
|
||
function afunction(value, title) {
|
||
if (typeof value !== "function")
|
||
throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
|
||
return value;
|
||
}
|
||
var bytesToHex2 = bytesToHex;
|
||
var concatBytes2 = (...arrays) => concatBytes(...arrays);
|
||
var hexToBytes2 = (hex) => hexToBytes(hex);
|
||
var isBytes3 = isBytes2;
|
||
var randomBytes3 = (bytesLength) => randomBytes2(bytesLength);
|
||
var _0n = /* @__PURE__ */ BigInt(0);
|
||
var _1n = /* @__PURE__ */ BigInt(1);
|
||
var atitle3 = (title) => title ? `"${title}" ` : "";
|
||
function abool2(value, title = "") {
|
||
if (typeof value !== "boolean")
|
||
throw new TypeError(atitle3(title) + "expected boolean, got type=" + typeof value);
|
||
return value;
|
||
}
|
||
function abignumber(n) {
|
||
if (typeof n === "bigint") {
|
||
if (!isPosBig(n))
|
||
throw new RangeError("positive bigint expected, got " + n);
|
||
} else
|
||
anumber3(n);
|
||
return n;
|
||
}
|
||
function asafenumber(value, title = "") {
|
||
if (typeof value !== "number") {
|
||
const prefix = title && `"${title}" `;
|
||
throw new TypeError(prefix + "expected number, got type=" + typeof value);
|
||
}
|
||
if (!Number.isSafeInteger(value)) {
|
||
const prefix = title && `"${title}" `;
|
||
throw new RangeError(prefix + "expected safe integer, got " + value);
|
||
}
|
||
}
|
||
function hexToNumber(hex) {
|
||
if (typeof hex !== "string")
|
||
throw new TypeError("hex string expected, got " + typeof hex);
|
||
return hex === "" ? _0n : BigInt("0x" + hex);
|
||
}
|
||
function bytesToNumberBE(bytes2) {
|
||
return hexToNumber(bytesToHex(bytes2));
|
||
}
|
||
function bytesToNumberLE(bytes2) {
|
||
return hexToNumber(bytesToHex(copyBytes2(abytes2(bytes2)).reverse()));
|
||
}
|
||
function numberToBytesBE(n, len) {
|
||
anumber2(len);
|
||
if (len === 0)
|
||
throw new Error("zero output length is invalid");
|
||
n = abignumber(n);
|
||
const expectedLen = len * 2;
|
||
const hex = n.toString(16);
|
||
if (hex.length > expectedLen)
|
||
throw new RangeError("number is too large");
|
||
return hexToBytes(hex.padStart(expectedLen, "0"));
|
||
}
|
||
function numberToBytesLE(n, len) {
|
||
return numberToBytesBE(n, len).reverse();
|
||
}
|
||
function copyBytes2(bytes2) {
|
||
return Uint8Array.from(abytes3(bytes2));
|
||
}
|
||
function isPosBig(n) {
|
||
return typeof n === "bigint" && _0n <= n;
|
||
}
|
||
function inRange(n, min, max) {
|
||
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
||
}
|
||
function aInRange(title, n, min, max) {
|
||
if (!inRange(n, min, max))
|
||
throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
||
}
|
||
function bitLen(n) {
|
||
if (n < _0n)
|
||
throw new Error("expected non-negative bigint, got " + n);
|
||
return n === _0n ? 0 : n.toString(2).length;
|
||
}
|
||
var bitMask = (n) => {
|
||
asafenumber(n, "n");
|
||
return (_1n << BigInt(n)) - _1n;
|
||
};
|
||
function validateObject(object, fields = {}, optFields = {}, title = "object") {
|
||
aobject3(object, title);
|
||
aobject3(fields, "fields");
|
||
aobject3(optFields, "optFields");
|
||
function checkField(fieldName, expectedType, isOpt) {
|
||
const label2 = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
|
||
const val = object[fieldName];
|
||
if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
|
||
throw new TypeError(`${label2} is invalid: expected own property`);
|
||
}
|
||
if (isOpt && val === void 0)
|
||
return;
|
||
const current = typeof val;
|
||
if (current !== expectedType || val === null)
|
||
throw new TypeError(`${label2} is invalid: expected ${expectedType}, got ${current}`);
|
||
}
|
||
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
||
iter(fields, false);
|
||
iter(optFields, true);
|
||
}
|
||
|
||
// node_modules/@noble/curves/abstract/modular.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n2 = /* @__PURE__ */ BigInt(0);
|
||
var _1n2 = /* @__PURE__ */ BigInt(1);
|
||
var _2n = /* @__PURE__ */ BigInt(2);
|
||
var _3n = /* @__PURE__ */ BigInt(3);
|
||
var _4n = /* @__PURE__ */ BigInt(4);
|
||
var _5n = /* @__PURE__ */ BigInt(5);
|
||
var _7n = /* @__PURE__ */ BigInt(7);
|
||
var _8n = /* @__PURE__ */ BigInt(8);
|
||
var _9n = /* @__PURE__ */ BigInt(9);
|
||
var _15n = /* @__PURE__ */ BigInt(15);
|
||
var _16n = /* @__PURE__ */ BigInt(16);
|
||
var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
|
||
function mod(a, b) {
|
||
if (b <= _0n2)
|
||
throw new Error("mod: expected positive modulus, got " + b);
|
||
const result = a % b;
|
||
return result >= _0n2 ? result : b + result;
|
||
}
|
||
function pow(num2, power, modulo) {
|
||
if (modulo <= _1n2)
|
||
throw new Error("pow: expected modulus > 1, got " + modulo);
|
||
if (typeof power !== "bigint")
|
||
throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
|
||
if (power < _0n2)
|
||
throw new Error("invalid exponent, negatives unsupported");
|
||
if (power === _0n2)
|
||
return _1n2;
|
||
if (power === _1n2)
|
||
return num2;
|
||
let d = num2 % modulo;
|
||
if (d < _0n2)
|
||
d += modulo;
|
||
if (power < POW_WINDOWED_MIN) {
|
||
let p2 = _1n2;
|
||
while (power > _0n2) {
|
||
if (power & _1n2)
|
||
p2 = p2 * d % modulo;
|
||
d = d * d % modulo;
|
||
power >>= _1n2;
|
||
}
|
||
return p2;
|
||
}
|
||
const digits = [];
|
||
while (power > _0n2) {
|
||
digits.push(Number(power & _15n));
|
||
power >>= _4n;
|
||
}
|
||
const table = new Array(16);
|
||
table[0] = _1n2;
|
||
table[1] = d;
|
||
for (let i = 2; i < 16; i++)
|
||
table[i] = table[i - 1] * d % modulo;
|
||
let p = table[digits[digits.length - 1]];
|
||
for (let w = digits.length - 2; w >= 0; w--) {
|
||
p = p * p % modulo;
|
||
p = p * p % modulo;
|
||
p = p * p % modulo;
|
||
p = p * p % modulo;
|
||
const digit = digits[w];
|
||
if (digit !== 0)
|
||
p = p * table[digit] % modulo;
|
||
}
|
||
return p;
|
||
}
|
||
function pow2(x, power, modulo) {
|
||
if (modulo <= _1n2)
|
||
throw new Error("pow2: expected modulus > 1, got " + modulo);
|
||
if (power < _0n2)
|
||
throw new Error("pow2: expected non-negative exponent, got " + power);
|
||
let res = x;
|
||
while (power-- > _0n2) {
|
||
res *= res;
|
||
res %= modulo;
|
||
}
|
||
return res;
|
||
}
|
||
function invert(number, modulo) {
|
||
if (number === _0n2)
|
||
throw new Error("invert: expected non-zero number");
|
||
if (modulo <= _1n2)
|
||
throw new Error("invert: expected modulus > 1, got " + modulo);
|
||
let a = mod(number, modulo);
|
||
let b = modulo;
|
||
let x = _0n2, u = _1n2;
|
||
while (a !== _0n2) {
|
||
const q = b / a;
|
||
const r = b - a * q;
|
||
const m = x - u * q;
|
||
b = a, a = r, x = u, u = m;
|
||
}
|
||
const gcd = b;
|
||
if (gcd !== _1n2)
|
||
throw new Error("invert: does not exist");
|
||
return mod(x, modulo);
|
||
}
|
||
function assertIsSquare(Fp2, root, n) {
|
||
const F = Fp2;
|
||
if (!F.eql(F.sqr(root), n))
|
||
throw new Error("Cannot find square root");
|
||
}
|
||
function aoddModulus(order, fnName) {
|
||
if ((order & _1n2) === _0n2)
|
||
throw new Error(fnName + ": expected odd modulus, got " + order);
|
||
}
|
||
function sqrt3mod4(Fp2, n) {
|
||
const F = Fp2;
|
||
const p1div4 = (F.ORDER + _1n2) / _4n;
|
||
const root = F.pow(n, p1div4);
|
||
assertIsSquare(F, root, n);
|
||
return root;
|
||
}
|
||
function sqrt5mod8(Fp2, n) {
|
||
const F = Fp2;
|
||
const p5div8 = (F.ORDER - _5n) / _8n;
|
||
const n2 = F.mul(n, _2n);
|
||
const v = F.pow(n2, p5div8);
|
||
const nv = F.mul(n, v);
|
||
const i = F.mul(F.mul(nv, _2n), v);
|
||
const root = F.mul(nv, F.sub(i, F.ONE));
|
||
assertIsSquare(F, root, n);
|
||
return root;
|
||
}
|
||
function sqrt9mod16(P) {
|
||
const Fp_ = Field(P);
|
||
const tn = tonelliShanks(P);
|
||
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
||
const c2 = tn(Fp_, c1);
|
||
const c3 = tn(Fp_, Fp_.neg(c1));
|
||
const c4 = (P + _7n) / _16n;
|
||
return ((Fp2, n) => {
|
||
const F = Fp2;
|
||
let tv1 = F.pow(n, c4);
|
||
let tv2 = F.mul(tv1, c1);
|
||
const tv3 = F.mul(tv1, c2);
|
||
const tv4 = F.mul(tv1, c3);
|
||
const e1 = F.eql(F.sqr(tv2), n);
|
||
const e2 = F.eql(F.sqr(tv3), n);
|
||
tv1 = F.cmov(tv1, tv2, e1);
|
||
tv2 = F.cmov(tv4, tv3, e2);
|
||
const e3 = F.eql(F.sqr(tv2), n);
|
||
const root = F.cmov(tv1, tv2, e3);
|
||
assertIsSquare(F, root, n);
|
||
return root;
|
||
});
|
||
}
|
||
function tonelliShanks(P) {
|
||
if (P < _3n)
|
||
throw new Error("sqrt is not defined for small field");
|
||
aoddModulus(P, "tonelliShanks");
|
||
let Q = P - _1n2;
|
||
let S = 0;
|
||
while (Q % _2n === _0n2) {
|
||
Q /= _2n;
|
||
S++;
|
||
}
|
||
let Z = _2n;
|
||
const _Fp = Field(P);
|
||
while (FpLegendre(_Fp, Z) === 1) {
|
||
if (Z++ > 1e3)
|
||
throw new Error("Cannot find square root: probably non-prime P");
|
||
}
|
||
if (S === 1)
|
||
return sqrt3mod4;
|
||
let cc = _Fp.pow(Z, Q);
|
||
const Q1div2 = (Q + _1n2) / _2n;
|
||
return function tonelliSlow(Fp2, n) {
|
||
const F = Fp2;
|
||
if (F.is0(n))
|
||
return n;
|
||
if (FpLegendre(F, n) !== 1)
|
||
throw new Error("Cannot find square root");
|
||
let M = S;
|
||
let c = F.mul(F.ONE, cc);
|
||
let t2 = F.pow(n, Q);
|
||
let R = F.pow(n, Q1div2);
|
||
while (!F.eql(t2, F.ONE)) {
|
||
if (F.is0(t2))
|
||
throw new Error("Cannot find square root: probably non-prime P");
|
||
let i = 1;
|
||
let t_tmp = F.sqr(t2);
|
||
while (!F.eql(t_tmp, F.ONE)) {
|
||
i++;
|
||
t_tmp = F.sqr(t_tmp);
|
||
if (i === M)
|
||
throw new Error("Cannot find square root");
|
||
}
|
||
const exponent = _1n2 << BigInt(M - i - 1);
|
||
const b = F.pow(c, exponent);
|
||
M = i;
|
||
c = F.sqr(b);
|
||
t2 = F.mul(t2, c);
|
||
R = F.mul(R, b);
|
||
}
|
||
return R;
|
||
};
|
||
}
|
||
function FpSqrt(P) {
|
||
aoddModulus(P, "Fp.sqrt");
|
||
if (P % _4n === _3n)
|
||
return sqrt3mod4;
|
||
if (P % _8n === _5n)
|
||
return sqrt5mod8;
|
||
if (P % _16n === _9n)
|
||
return sqrt9mod16(P);
|
||
return tonelliShanks(P);
|
||
}
|
||
var isNegativeLE = (num2, modulo) => (mod(num2, modulo) & _1n2) === _1n2;
|
||
var FIELD_FIELDS = [
|
||
"create",
|
||
"isValid",
|
||
"is0",
|
||
"neg",
|
||
"inv",
|
||
"sqrt",
|
||
"sqr",
|
||
"eql",
|
||
"add",
|
||
"sub",
|
||
"mul",
|
||
"pow",
|
||
"div",
|
||
"addN",
|
||
"subN",
|
||
"mulN",
|
||
"sqrN"
|
||
];
|
||
function validateField(field3) {
|
||
aobject3(field3, "field");
|
||
if (typeof field3.ORDER !== "bigint")
|
||
throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field3.ORDER);
|
||
asafenumber(field3.BYTES, "BYTES");
|
||
asafenumber(field3.BITS, "BITS");
|
||
for (const name of FIELD_FIELDS)
|
||
afunction(field3[name], "field." + name);
|
||
if (field3.BYTES < 1 || field3.BITS < 1)
|
||
throw new Error("invalid field: expected BYTES/BITS > 0");
|
||
if (field3.ORDER <= _1n2)
|
||
throw new Error("invalid field: expected ORDER > 1, got " + field3.ORDER);
|
||
return field3;
|
||
}
|
||
function FpInvertBatch(Fp2, nums, passZero = false) {
|
||
validateField(Fp2);
|
||
aarray(nums, "nums");
|
||
abool2(passZero, "passZero");
|
||
const F = Fp2;
|
||
const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
|
||
const multipliedAcc = nums.reduce((acc, num2, i) => {
|
||
if (F.is0(num2))
|
||
return acc;
|
||
inverted[i] = acc;
|
||
return F.mul(acc, num2);
|
||
}, F.ONE);
|
||
const invertedAcc = F.inv(multipliedAcc);
|
||
nums.reduceRight((acc, num2, i) => {
|
||
if (F.is0(num2))
|
||
return acc;
|
||
inverted[i] = F.mul(acc, inverted[i]);
|
||
return F.mul(acc, num2);
|
||
}, invertedAcc);
|
||
return inverted;
|
||
}
|
||
function FpLegendre(Fp2, n) {
|
||
validateField(Fp2);
|
||
const F = Fp2;
|
||
aoddModulus(F.ORDER, "FpLegendre");
|
||
const p1mod2 = (F.ORDER - _1n2) / _2n;
|
||
const powered = F.pow(n, p1mod2);
|
||
const yes = F.eql(powered, F.ONE);
|
||
const zero = F.eql(powered, F.ZERO);
|
||
const no = F.eql(powered, F.neg(F.ONE));
|
||
if (!yes && !zero && !no)
|
||
throw new Error("invalid Legendre symbol result");
|
||
return yes ? 1 : zero ? 0 : -1;
|
||
}
|
||
function nLength(n, nBitLength) {
|
||
if (nBitLength !== void 0)
|
||
anumber3(nBitLength);
|
||
if (n <= _0n2)
|
||
throw new Error("invalid n length: expected positive n, got " + n);
|
||
if (nBitLength !== void 0 && nBitLength < 1)
|
||
throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
|
||
const bits = bitLen(n);
|
||
if (nBitLength !== void 0 && nBitLength < bits)
|
||
throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
|
||
const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
|
||
const nByteLength = Math.ceil(_nBitLength / 8);
|
||
return { nBitLength: _nBitLength, nByteLength };
|
||
}
|
||
var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
|
||
var _Field = class {
|
||
ORDER;
|
||
BITS;
|
||
BYTES;
|
||
isLE;
|
||
ZERO = _0n2;
|
||
ONE = _1n2;
|
||
_lengths;
|
||
_mod;
|
||
constructor(ORDER, opts = {}) {
|
||
if (ORDER <= _1n2)
|
||
throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
|
||
let _nbitLength = void 0;
|
||
this.isLE = false;
|
||
if (opts != null && typeof opts === "object") {
|
||
if (typeof opts.BITS === "number")
|
||
_nbitLength = opts.BITS;
|
||
if (typeof opts.sqrt === "function")
|
||
Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
|
||
if (typeof opts.isLE === "boolean")
|
||
this.isLE = opts.isLE;
|
||
if (opts.allowedLengths)
|
||
this._lengths = Object.freeze(opts.allowedLengths.slice());
|
||
if (typeof opts.modFromBytes === "boolean")
|
||
this._mod = opts.modFromBytes;
|
||
}
|
||
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
||
if (nByteLength > 2048)
|
||
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
||
this.ORDER = ORDER;
|
||
this.BITS = nBitLength;
|
||
this.BYTES = nByteLength;
|
||
Object.freeze(this);
|
||
}
|
||
create(num2) {
|
||
return mod(num2, this.ORDER);
|
||
}
|
||
isValid(num2) {
|
||
if (typeof num2 !== "bigint")
|
||
throw new TypeError("invalid field element: expected bigint, got " + typeof num2);
|
||
return _0n2 <= num2 && num2 < this.ORDER;
|
||
}
|
||
is0(num2) {
|
||
return num2 === _0n2;
|
||
}
|
||
// is valid and invertible
|
||
isValidNot0(num2) {
|
||
return !this.is0(num2) && this.isValid(num2);
|
||
}
|
||
isOdd(num2) {
|
||
return (num2 & _1n2) === _1n2;
|
||
}
|
||
neg(num2) {
|
||
return mod(-num2, this.ORDER);
|
||
}
|
||
eql(lhs, rhs) {
|
||
return lhs === rhs;
|
||
}
|
||
sqr(num2) {
|
||
return mod(num2 * num2, this.ORDER);
|
||
}
|
||
add(lhs, rhs) {
|
||
return mod(lhs + rhs, this.ORDER);
|
||
}
|
||
sub(lhs, rhs) {
|
||
return mod(lhs - rhs, this.ORDER);
|
||
}
|
||
mul(lhs, rhs) {
|
||
return mod(lhs * rhs, this.ORDER);
|
||
}
|
||
pow(num2, power) {
|
||
return pow(num2, power, this.ORDER);
|
||
}
|
||
div(lhs, rhs) {
|
||
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
||
}
|
||
// Same as above, but doesn't normalize
|
||
sqrN(num2) {
|
||
return num2 * num2;
|
||
}
|
||
addN(lhs, rhs) {
|
||
return lhs + rhs;
|
||
}
|
||
subN(lhs, rhs) {
|
||
return lhs - rhs;
|
||
}
|
||
mulN(lhs, rhs) {
|
||
return lhs * rhs;
|
||
}
|
||
inv(num2) {
|
||
return invert(num2, this.ORDER);
|
||
}
|
||
sqrt(num2) {
|
||
let sqrt = FIELD_SQRT.get(this);
|
||
if (!sqrt)
|
||
FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
|
||
return sqrt(this, num2);
|
||
}
|
||
toBytes(num2) {
|
||
return this.isLE ? numberToBytesLE(num2, this.BYTES) : numberToBytesBE(num2, this.BYTES);
|
||
}
|
||
fromBytes(bytes2, skipValidation = false) {
|
||
abytes3(bytes2);
|
||
const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
|
||
if (allowedLengths) {
|
||
if (bytes2.length < 1 || !allowedLengths.includes(bytes2.length) || bytes2.length > BYTES) {
|
||
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes2.length);
|
||
}
|
||
const padded = new Uint8Array(BYTES);
|
||
padded.set(bytes2, isLE2 ? 0 : padded.length - bytes2.length);
|
||
bytes2 = padded;
|
||
}
|
||
if (bytes2.length !== BYTES)
|
||
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes2.length);
|
||
let scalar = isLE2 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2);
|
||
if (modFromBytes)
|
||
scalar = mod(scalar, ORDER);
|
||
if (!skipValidation) {
|
||
if (!this.isValid(scalar))
|
||
throw new Error("invalid field element: outside of range 0..ORDER");
|
||
}
|
||
return scalar;
|
||
}
|
||
// TODO: we don't need it here, move out to separate fn
|
||
invertBatch(lst) {
|
||
return FpInvertBatch(this, lst, true);
|
||
}
|
||
// We can't move this out because Fp6, Fp12 implement it
|
||
// and it's unclear what to return in there.
|
||
cmov(a, b, condition) {
|
||
abool2(condition, "condition");
|
||
return condition ? b : a;
|
||
}
|
||
};
|
||
function Field(ORDER, opts = {}) {
|
||
Object.freeze(_Field.prototype);
|
||
return new _Field(ORDER, opts);
|
||
}
|
||
|
||
// node_modules/@noble/curves/abstract/curve.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n3 = /* @__PURE__ */ BigInt(0);
|
||
var _1n3 = /* @__PURE__ */ BigInt(1);
|
||
var _4n2 = /* @__PURE__ */ BigInt(4);
|
||
var BLIND_BYTES = 16;
|
||
var BLIND_BITS = 128;
|
||
var FW_WINDOW = 5;
|
||
var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
|
||
function validatePointCons(Point) {
|
||
const pc = Point;
|
||
if (typeof pc !== "function")
|
||
throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
|
||
afunction(pc.fromAffine, "Point.fromAffine");
|
||
afunction(pc.fromBytes, "Point.fromBytes");
|
||
afunction(pc.fromHex, "Point.fromHex");
|
||
aobject3(pc.BASE, "Point.BASE");
|
||
aobject3(pc.ZERO, "Point.ZERO");
|
||
validateField(pc.Fp);
|
||
validateField(pc.Fn);
|
||
}
|
||
function normalizeZ(c, points) {
|
||
validatePointCons(c);
|
||
validateMSMPoints(points, c);
|
||
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
||
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
||
}
|
||
function validateW(W, bits, min = 1) {
|
||
if (!Number.isSafeInteger(W) || W < min || W > bits)
|
||
throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
|
||
}
|
||
function validateTableBytes(numPoints, fpBytes) {
|
||
const bytes2 = numPoints * (4 * fpBytes + 128);
|
||
if (bytes2 > TABLE_BYTES_MAX)
|
||
throw new Error("invalid window size: table would need ~" + Math.ceil(bytes2 / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
|
||
}
|
||
function probeRandomBytes(randomBytes4, length) {
|
||
if (randomBytes4 === void 0)
|
||
return void 0;
|
||
afunction(randomBytes4, "randomBytes");
|
||
try {
|
||
const probe = randomBytes4(length);
|
||
if (!isBytes3(probe) || probe.length !== length)
|
||
return void 0;
|
||
} catch {
|
||
return void 0;
|
||
}
|
||
return randomBytes4;
|
||
}
|
||
function validateMSMPoints(points, c) {
|
||
aarray(points, "points");
|
||
points.forEach((p, i) => {
|
||
if (!(p instanceof c))
|
||
throw new Error("invalid point at index " + i);
|
||
});
|
||
}
|
||
function validateMSMScalars(scalars, field3, maxScalar) {
|
||
if (!Array.isArray(scalars))
|
||
throw new Error("array of scalars expected");
|
||
scalars.forEach((s, i) => {
|
||
const ok = maxScalar === void 0 ? field3.isValid(s) : isPosBig(s) && s < maxScalar;
|
||
if (!ok)
|
||
throw new Error("invalid scalar at index " + i);
|
||
});
|
||
}
|
||
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
||
function getWindowSize(P) {
|
||
return pointWindowSizes.get(P) || 1;
|
||
}
|
||
function oddMultiples(p, size) {
|
||
const dbl = p.double();
|
||
const t2 = [p];
|
||
for (let j = 1; j < size; j++)
|
||
t2.push(t2[j - 1].add(dbl));
|
||
return t2;
|
||
}
|
||
function wnafDigits(n, W) {
|
||
const size = 2 ** W;
|
||
const half = size / 2;
|
||
const mask = BigInt(size - 1);
|
||
const d = [];
|
||
while (n > _0n3) {
|
||
let w = 0;
|
||
if (n & _1n3) {
|
||
w = Number(n & mask);
|
||
if (w >= half)
|
||
w -= size;
|
||
n -= BigInt(w);
|
||
}
|
||
d.push(w);
|
||
n >>= _1n3;
|
||
}
|
||
return d;
|
||
}
|
||
function signedWindowDigits(n, W, windows) {
|
||
const size = 2 ** W;
|
||
const half = size / 2;
|
||
const mask = BigInt(size - 1);
|
||
const shiftBy = BigInt(W);
|
||
const d = [];
|
||
for (let w = 0; w < windows; w++) {
|
||
let v = Number(n & mask);
|
||
n >>= shiftBy;
|
||
if (v > half) {
|
||
v -= size;
|
||
n += _1n3;
|
||
}
|
||
d.push(v);
|
||
}
|
||
if (n !== _0n3)
|
||
throw new Error("invalid wnaf");
|
||
return d;
|
||
}
|
||
function wnafWalk(zero, tables, digits) {
|
||
let max = 0;
|
||
for (const d of digits)
|
||
max = Math.max(max, d.length);
|
||
let acc = zero;
|
||
for (let bit = max - 1; bit >= 0; bit--) {
|
||
if (bit !== max - 1)
|
||
acc = acc.double();
|
||
for (let i = 0; i < digits.length; i++) {
|
||
const w = digits[i][bit];
|
||
if (w) {
|
||
const item = tables[i][Math.abs(w) - 1 >> 1];
|
||
acc = acc.add(w < 0 ? item.negate() : item);
|
||
}
|
||
}
|
||
}
|
||
return acc;
|
||
}
|
||
var ScalarMultiplier = class {
|
||
Point;
|
||
BASE;
|
||
ZERO;
|
||
randomBytes;
|
||
wnafPrecomputes = /* @__PURE__ */ new WeakMap();
|
||
baseCanBeBlinded;
|
||
bits;
|
||
// Parametrized with a given Point class (not individual point)
|
||
constructor(Point, randomBytes4) {
|
||
validatePointCons(Point);
|
||
this.randomBytes = probeRandomBytes(randomBytes4, BLIND_BYTES);
|
||
this.Point = Point;
|
||
this.BASE = Point.BASE;
|
||
this.ZERO = Point.ZERO;
|
||
this.bits = Point.Fn.BITS;
|
||
}
|
||
/**
|
||
* Creates a signed fixed-window wNAF precomputation table: for every window w, the
|
||
* multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
|
||
* so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
|
||
* window absorbs the final carry of signed-digit recoding.
|
||
* For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
|
||
* @param point - Point instance
|
||
* @param W - window size
|
||
* @param bits - scalar bitlength the table must cover
|
||
*/
|
||
buildWnafTable(point, W, bits) {
|
||
const windows = Math.ceil(bits / W) + 1;
|
||
const half = 2 ** (W - 1);
|
||
const comp = [];
|
||
let base = point;
|
||
for (let w = 0; w < windows; w++) {
|
||
let acc = base;
|
||
for (let i = 0; i < half; i++) {
|
||
comp.push(acc);
|
||
acc = acc.add(base);
|
||
}
|
||
base = comp[comp.length - 1].double();
|
||
}
|
||
return { W, bits, windows, comp };
|
||
}
|
||
/**
|
||
* Implements ec multiplication using precomputed signed fixed-window wNAF tables.
|
||
* Constant-time: fixed window count with one table addition per window — zero digits feed
|
||
* the fake accumulator — and no doublings; the lookup scans the whole window slice.
|
||
* Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
|
||
* {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
|
||
* signedWindowDigits throws if `n` exceeds the table.
|
||
* @returns real and fake (for const-time) points
|
||
*/
|
||
wnafCachedCT(precomputes, n) {
|
||
const { W, windows, comp } = precomputes;
|
||
const half = 2 ** (W - 1);
|
||
const digits = signedWindowDigits(n, W, windows);
|
||
let p = this.ZERO;
|
||
let f = this.BASE;
|
||
for (let w = 0; w < windows; w++) {
|
||
const digit = digits[w];
|
||
const start = w * half;
|
||
const idx = Math.abs(digit) - 1;
|
||
let sel = comp[start];
|
||
for (let i = 1; i < half; i++)
|
||
sel = i === idx ? comp[start + i] : sel;
|
||
const neg = sel.negate();
|
||
if (digit === 0)
|
||
f = f.add(comp[start]);
|
||
else
|
||
p = p.add(digit < 0 ? neg : sel);
|
||
}
|
||
return { p, f };
|
||
}
|
||
// Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
|
||
// `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
|
||
// incompatible `transform(...)` layouts and expect a separate cache entry.
|
||
getWnafPrecomputes(W, point, bits, transform) {
|
||
let entries = this.wnafPrecomputes.get(point);
|
||
let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
|
||
if (!comp) {
|
||
comp = this.buildWnafTable(point, W, bits);
|
||
if (typeof transform === "function")
|
||
comp = { ...comp, comp: transform(comp.comp) };
|
||
if (!entries) {
|
||
entries = [];
|
||
this.wnafPrecomputes.set(point, entries);
|
||
}
|
||
entries.push(comp);
|
||
}
|
||
return comp;
|
||
}
|
||
assertPoint(point) {
|
||
if (!(point instanceof this.Point))
|
||
throw new TypeError('"point" expected Point instance, got type=' + typeof point);
|
||
}
|
||
// Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
|
||
// callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
|
||
// Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
|
||
validateMulInput(point, scalar) {
|
||
this.assertPoint(point);
|
||
if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
|
||
throw new Error("invalid scalar");
|
||
}
|
||
// Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
|
||
// ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
|
||
// multiply. `n` must be < 2^bits.
|
||
runCT(point, n, bits, transform) {
|
||
const W = getWindowSize(point);
|
||
if (W === 1)
|
||
return this.fixedWindowCT(point, n, bits);
|
||
return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
|
||
}
|
||
mulCT(point, scalar, transform) {
|
||
this.validateMulInput(point, scalar);
|
||
return this.runCT(point, scalar, this.bits, transform);
|
||
}
|
||
mulCTBlinded(point, scalar, transform) {
|
||
this.validateMulInput(point, scalar);
|
||
if (this.randomBytes === void 0)
|
||
throw new Error("randomBytes is required for scalar blinding");
|
||
const bits = this.Point.Fn.BITS + BLIND_BITS;
|
||
const blind = this.randomBytes(BLIND_BYTES);
|
||
if (!isBytes3(blind) || blind.length !== BLIND_BYTES)
|
||
throw new Error("randomBytes returned invalid byte array");
|
||
blind[0] = blind[0] & 63 | 128;
|
||
const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
|
||
return this.runCT(point, n, bits, transform);
|
||
}
|
||
/**
|
||
* Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
|
||
* A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
|
||
* far cheaper to build for a single use. The point-operation sequence is independent of `n`:
|
||
* build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
|
||
* every table entry, and one addition (adds the identity when the window digit is 0 — never
|
||
* skipped).
|
||
*
|
||
* `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
|
||
* add), which holds for the Weierstrass/Edwards point types used here. The table is left in
|
||
* projective form (no normalizeZ): normalizing this small a table costs more than the
|
||
* mixed-add savings it would buy for a single multiply.
|
||
* @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
|
||
* (this path needs no fake accumulator — its op-count is already scalar-independent).
|
||
*/
|
||
fixedWindowCT(point, n, bits) {
|
||
const W = FW_WINDOW;
|
||
const size = 1 << W;
|
||
const mask = bitMask(W);
|
||
const table = new Array(size);
|
||
table[0] = this.ZERO;
|
||
for (let i = 1; i < size; i++)
|
||
table[i] = table[i - 1].add(point);
|
||
const windows = Math.ceil(bits / W);
|
||
let acc = this.ZERO;
|
||
for (let window2 = windows - 1; window2 >= 0; window2--) {
|
||
if (window2 !== windows - 1)
|
||
for (let d = 0; d < W; d++)
|
||
acc = acc.double();
|
||
const digit = Number(n >> BigInt(window2 * W) & mask);
|
||
let sel = table[0];
|
||
for (let i = 1; i < size; i++)
|
||
sel = i === digit ? table[i] : sel;
|
||
acc = acc.add(sel);
|
||
}
|
||
return { p: acc, f: acc };
|
||
}
|
||
shouldBlind(point, cofactor) {
|
||
if (this.randomBytes === void 0)
|
||
return false;
|
||
if (cofactor === _1n3)
|
||
return true;
|
||
if (point !== this.BASE)
|
||
return false;
|
||
if (this.baseCanBeBlinded === void 0)
|
||
this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
|
||
return this.baseCanBeBlinded;
|
||
}
|
||
mulSecret(point, scalar, cofactor, transform) {
|
||
return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
|
||
}
|
||
mulUnsafe(point, scalar, transform) {
|
||
this.assertPoint(point);
|
||
if (!isPosBig(scalar))
|
||
throw new Error("invalid scalar");
|
||
const W = getWindowSize(point);
|
||
if (W === 1 || scalar >= this.Point.Fn.ORDER)
|
||
return mulAddUnsafe(this.Point, [point], [scalar], true);
|
||
const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
|
||
return this.wnafCachedCT(precomputes, scalar).p;
|
||
}
|
||
// Remembers the window size used for precomputed wNAF multiplication of the given point
|
||
// and drops any previously built tables. Usually only the base point is precomputed.
|
||
// W=1 resets the point to the un-precomputed (table-less) paths.
|
||
// W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
|
||
setWindowSize(point, W) {
|
||
this.assertPoint(point);
|
||
validateW(W, this.bits);
|
||
const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
|
||
validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
|
||
pointWindowSizes.set(point, W);
|
||
this.wnafPrecomputes.delete(point);
|
||
}
|
||
// True when a window size is set: tables themselves are built lazily on first multiply.
|
||
hasWindowSize(point) {
|
||
return getWindowSize(point) !== 1;
|
||
}
|
||
};
|
||
function mulAddUnsafe(c, points, scalars, allowOversized = false) {
|
||
validatePointCons(c);
|
||
validateMSMPoints(points, c);
|
||
abool2(allowOversized, "allowOversized");
|
||
validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
|
||
if (points.length !== scalars.length)
|
||
throw new Error("arrays of points and scalars must have equal length");
|
||
const tables = points.map((p) => oddMultiples(p, 4));
|
||
const digits = scalars.map((n) => wnafDigits(n, 4));
|
||
return wnafWalk(c.ZERO, tables, digits);
|
||
}
|
||
function createField(order, field3, isLE2) {
|
||
if (field3) {
|
||
if (field3.ORDER !== order)
|
||
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
||
validateField(field3);
|
||
return field3;
|
||
} else {
|
||
return Field(order, { isLE: isLE2 });
|
||
}
|
||
}
|
||
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
||
if (type !== "weierstrass" && type !== "edwards")
|
||
throw new Error('expected curve type "weierstrass" or "edwards"');
|
||
if (FpFnLE === void 0)
|
||
FpFnLE = type === "edwards";
|
||
if (!CURVE || typeof CURVE !== "object")
|
||
throw new Error(`expected valid ${type} CURVE object`);
|
||
validateObject(curveOpts);
|
||
for (const p of ["p", "n", "h"]) {
|
||
const val = CURVE[p];
|
||
if (!(isPosBig(val) && val !== _0n3))
|
||
throw new Error(`CURVE.${p} must be positive bigint`);
|
||
}
|
||
const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
||
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
||
const _b = type === "weierstrass" ? "b" : "d";
|
||
const params = ["Gx", "Gy", "a", _b];
|
||
for (const p of params) {
|
||
if (!Fp2.isValid(CURVE[p]))
|
||
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
||
}
|
||
CURVE = Object.freeze(Object.assign({}, CURVE));
|
||
return { CURVE, Fp: Fp2, Fn };
|
||
}
|
||
function createKeygen(randomSecretKey, getPublicKey) {
|
||
return function keygen(seed) {
|
||
const secretKey = randomSecretKey(seed);
|
||
return { secretKey, publicKey: getPublicKey(secretKey) };
|
||
};
|
||
}
|
||
|
||
// node_modules/@noble/curves/abstract/edwards.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n4 = /* @__PURE__ */ BigInt(0);
|
||
var _1n4 = /* @__PURE__ */ BigInt(1);
|
||
var _2n2 = /* @__PURE__ */ BigInt(2);
|
||
var _4n3 = /* @__PURE__ */ BigInt(4);
|
||
var _8n2 = /* @__PURE__ */ BigInt(8);
|
||
function isEdValidXY(Fp2, CURVE, x, y) {
|
||
const x2 = Fp2.sqr(x);
|
||
const y2 = Fp2.sqr(y);
|
||
const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
|
||
const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
|
||
return Fp2.eql(left, right);
|
||
}
|
||
function edwards(params, extraOpts = {}) {
|
||
validateObject(extraOpts, {}, {}, "extraOpts");
|
||
const opts = extraOpts;
|
||
const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
|
||
const { Fp: Fp2, Fn } = validated;
|
||
let CURVE = validated.CURVE;
|
||
const { h: cofactor } = CURVE;
|
||
if (FpLegendre(Fp2, CURVE.a) !== 1)
|
||
throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
|
||
if (FpLegendre(Fp2, CURVE.d) !== -1)
|
||
throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
|
||
validateObject(opts, {}, { uvRatio: "function", randomBytes: "function" });
|
||
const randomBytes4 = opts.randomBytes === void 0 ? randomBytes3 : opts.randomBytes;
|
||
const MASK = _2n2 << BigInt(Fp2.BYTES * 8) - _1n4;
|
||
function isOdd(n) {
|
||
if (!Fp2.isOdd)
|
||
throw new Error("Field does not have .isOdd()");
|
||
return Fp2.isOdd(n);
|
||
}
|
||
const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
|
||
try {
|
||
return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
|
||
} catch (e2) {
|
||
return { isValid: false, value: _0n4 };
|
||
}
|
||
} : opts.uvRatio;
|
||
if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
|
||
throw new Error("bad curve params: generator point");
|
||
const mulA = Fp2.eql(CURVE.a, Fp2.neg(Fp2.ONE)) ? (x) => Fp2.neg(x) : Fp2.eql(CURVE.a, Fp2.ONE) ? (x) => x : (x) => Fp2.mul(CURVE.a, x);
|
||
function acoord(title, n, banZero = false) {
|
||
const min = banZero ? _1n4 : _0n4;
|
||
aInRange("coordinate " + title, n, min, MASK);
|
||
return n;
|
||
}
|
||
function aedpoint(other) {
|
||
if (!(other instanceof Point))
|
||
throw new Error("EdwardsPoint expected");
|
||
}
|
||
class Point {
|
||
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy));
|
||
static ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO);
|
||
static Fp = Fp2;
|
||
static Fn = Fn;
|
||
X;
|
||
Y;
|
||
Z;
|
||
T;
|
||
constructor(X, Y, Z, T) {
|
||
this.X = acoord("x", X);
|
||
this.Y = acoord("y", Y);
|
||
this.Z = acoord("z", Z, true);
|
||
this.T = acoord("t", T);
|
||
Object.freeze(this);
|
||
}
|
||
static CURVE() {
|
||
return CURVE;
|
||
}
|
||
/**
|
||
* Create one extended Edwards point from affine coordinates.
|
||
* Does NOT validate that the point is on-curve or torsion-free.
|
||
* Use `.assertValidity()` on adversarial inputs.
|
||
*/
|
||
static fromAffine(p) {
|
||
if (p instanceof Point)
|
||
throw new Error("extended point not allowed");
|
||
const { x, y } = p || {};
|
||
acoord("x", x);
|
||
acoord("y", y);
|
||
return new Point(x, y, Fp2.ONE, Fp2.mul(x, y));
|
||
}
|
||
// Uses algo from RFC8032 5.1.3.
|
||
static fromBytes(bytes2, zip215 = false) {
|
||
const len = Fp2.BYTES;
|
||
const { a, d } = CURVE;
|
||
bytes2 = copyBytes2(abytes3(bytes2, len, "point"));
|
||
abool2(zip215, "zip215");
|
||
const normed = copyBytes2(bytes2);
|
||
const lastByte = bytes2[len - 1];
|
||
normed[len - 1] = lastByte & ~128;
|
||
const y = bytesToNumberLE(normed);
|
||
const max = zip215 ? MASK : Fp2.ORDER;
|
||
aInRange("point.y", y, _0n4, max);
|
||
const y2 = Fp2.sqr(y);
|
||
const u = Fp2.sub(y2, Fp2.ONE);
|
||
const v = Fp2.sub(Fp2.mulN(d, y2), a);
|
||
let { isValid, value: x } = uvRatio2(u, v);
|
||
if (!isValid)
|
||
throw new Error("bad point: invalid y coordinate");
|
||
const isXOdd = isOdd(x);
|
||
const isLastByteOdd = (lastByte & 128) !== 0;
|
||
if (!zip215 && Fp2.is0(x) && isLastByteOdd)
|
||
throw new Error("bad point: x=0 and x_0=1");
|
||
if (isLastByteOdd !== isXOdd)
|
||
x = Fp2.neg(x);
|
||
return Point.fromAffine({ x, y });
|
||
}
|
||
static fromHex(hex, zip215 = false) {
|
||
return Point.fromBytes(hexToBytes2(hex), zip215);
|
||
}
|
||
get x() {
|
||
return this.toAffine().x;
|
||
}
|
||
get y() {
|
||
return this.toAffine().y;
|
||
}
|
||
precompute(windowSize = 6, isLazy = true) {
|
||
wnaf.setWindowSize(this, windowSize);
|
||
if (!isLazy)
|
||
this.multiply(_2n2);
|
||
return this;
|
||
}
|
||
// Useful in fromAffine() - not for fromBytes(), which always created valid points.
|
||
assertValidity() {
|
||
const p = this;
|
||
const { a, d } = CURVE;
|
||
if (p.is0())
|
||
throw new Error("bad point: ZERO");
|
||
const { X, Y, Z, T } = p;
|
||
const X2 = Fp2.sqr(X);
|
||
const Y2 = Fp2.sqr(Y);
|
||
const Z2 = Fp2.sqr(Z);
|
||
const Z4 = Fp2.sqr(Z2);
|
||
const aX2 = Fp2.mul(X2, a);
|
||
const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
|
||
const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
|
||
if (!Fp2.eql(left, right))
|
||
throw new Error("bad point: equation left != right (1)");
|
||
const XY = Fp2.mul(X, Y);
|
||
const ZT = Fp2.mul(Z, T);
|
||
if (!Fp2.eql(XY, ZT))
|
||
throw new Error("bad point: equation left != right (2)");
|
||
}
|
||
// Compare one point to another.
|
||
equals(other) {
|
||
aedpoint(other);
|
||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||
const { X: X2, Y: Y2, Z: Z2 } = other;
|
||
const X1Z2 = Fp2.mul(X1, Z2);
|
||
const X2Z1 = Fp2.mul(X2, Z1);
|
||
const Y1Z2 = Fp2.mul(Y1, Z2);
|
||
const Y2Z1 = Fp2.mul(Y2, Z1);
|
||
return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
|
||
}
|
||
is0() {
|
||
return this.equals(Point.ZERO);
|
||
}
|
||
negate() {
|
||
return new Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
|
||
}
|
||
// Fast algo for doubling Extended Point.
|
||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
|
||
// Cost: 4M + 4S + 1*a + 6add + 1*2.
|
||
double() {
|
||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||
const A = Fp2.sqr(X1);
|
||
const B = Fp2.sqr(Y1);
|
||
const C = Fp2.mul(Fp2.sqr(Z1), _2n2);
|
||
const D = mulA(A);
|
||
const x1y1 = Fp2.addN(X1, Y1);
|
||
const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B);
|
||
const G = Fp2.addN(D, B);
|
||
const F = Fp2.subN(G, C);
|
||
const H = Fp2.subN(D, B);
|
||
const X3 = Fp2.mul(E, F);
|
||
const Y3 = Fp2.mul(G, H);
|
||
const T3 = Fp2.mul(E, H);
|
||
const Z3 = Fp2.mul(F, G);
|
||
return new Point(X3, Y3, Z3, T3);
|
||
}
|
||
// Fast algo for adding 2 Extended Points.
|
||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
|
||
// Cost: 9M + 1*a + 1*d + 7add.
|
||
add(other) {
|
||
aedpoint(other);
|
||
const { d } = CURVE;
|
||
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
|
||
const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
|
||
const A = Fp2.mul(X1, X2);
|
||
const B = Fp2.mul(Y1, Y2);
|
||
const C = Fp2.mul(Fp2.mulN(T1, d), T2);
|
||
const D = Fp2.mul(Z1, Z2);
|
||
const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B);
|
||
const F = Fp2.subN(D, C);
|
||
const G = Fp2.addN(D, C);
|
||
const H = Fp2.sub(B, mulA(A));
|
||
const X3 = Fp2.mul(E, F);
|
||
const Y3 = Fp2.mul(G, H);
|
||
const T3 = Fp2.mul(E, H);
|
||
const Z3 = Fp2.mul(F, G);
|
||
return new Point(X3, Y3, Z3, T3);
|
||
}
|
||
subtract(other) {
|
||
aedpoint(other);
|
||
return this.add(other.negate());
|
||
}
|
||
// Constant-time multiplication.
|
||
multiply(scalar) {
|
||
if (!Fn.isValidNot0(scalar))
|
||
throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
|
||
const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
|
||
return normalize([p, f])[0];
|
||
}
|
||
// Non-constant-time multiplication. Uses double-and-add algorithm.
|
||
// It's faster, but should only be used when you don't care about
|
||
// an exposed private key e.g. sig verification.
|
||
// Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
|
||
// n and larger values are rejected instead of being reduced mod n to the identity point.
|
||
multiplyUnsafe(scalar) {
|
||
if (!Fn.isValid(scalar))
|
||
throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
|
||
if (scalar === _0n4)
|
||
return Point.ZERO;
|
||
if (this.is0() || scalar === _1n4)
|
||
return this;
|
||
return wnaf.mulUnsafe(this, scalar, normalize);
|
||
}
|
||
// Checks if point is of small order.
|
||
// If you add something to small order point, you will have "dirty"
|
||
// point with torsion component.
|
||
// Clears cofactor and checks if the result is 0.
|
||
isSmallOrder() {
|
||
return this.clearCofactor().is0();
|
||
}
|
||
// Multiplies point by curve order and checks if the result is 0.
|
||
// Returns `false` is the point is dirty.
|
||
isTorsionFree() {
|
||
return wnaf.mulUnsafe(this, CURVE.n).is0();
|
||
}
|
||
// Converts Extended point to default (x, y) coordinates.
|
||
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
||
toAffine(invertedZ) {
|
||
const p = this;
|
||
let iz = invertedZ;
|
||
if (iz != null && typeof iz !== "bigint")
|
||
throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
|
||
const { X, Y, Z } = p;
|
||
const is0 = p.is0();
|
||
if (iz == null)
|
||
iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
|
||
const x = Fp2.mul(X, iz);
|
||
const y = Fp2.mul(Y, iz);
|
||
const zz = Fp2.mul(Z, iz);
|
||
if (is0)
|
||
return { x: Fp2.ZERO, y: Fp2.ONE };
|
||
if (!Fp2.eql(zz, Fp2.ONE))
|
||
throw new Error("invZ was invalid");
|
||
return { x, y };
|
||
}
|
||
clearCofactor() {
|
||
if (cofactor === _1n4)
|
||
return this;
|
||
if (cofactor === _2n2)
|
||
return this.double();
|
||
if (cofactor === _4n3)
|
||
return this.double().double();
|
||
if (cofactor === _8n2)
|
||
return this.double().double().double();
|
||
return this.multiplyUnsafe(cofactor);
|
||
}
|
||
toBytes() {
|
||
const { x, y } = this.toAffine();
|
||
const bytes2 = Fp2.toBytes(y);
|
||
bytes2[bytes2.length - 1] |= isOdd(x) ? 128 : 0;
|
||
return bytes2;
|
||
}
|
||
toHex() {
|
||
return bytesToHex2(this.toBytes());
|
||
}
|
||
toString() {
|
||
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
||
}
|
||
}
|
||
const normalize = (points) => normalizeZ(Point, points);
|
||
const wnaf = new ScalarMultiplier(Point, randomBytes4);
|
||
if (wnaf.bits >= 6)
|
||
Point.BASE.precompute(6);
|
||
Object.freeze(Point.prototype);
|
||
Object.freeze(Point);
|
||
return Point;
|
||
}
|
||
function eddsa(Point, cHash, eddsaOpts = {}) {
|
||
validatePointCons(Point);
|
||
if (typeof cHash !== "function")
|
||
throw new Error('"hash" function param is required');
|
||
const hash = cHash;
|
||
const opts = eddsaOpts;
|
||
validateObject(opts, {}, {
|
||
adjustScalarBytes: "function",
|
||
randomBytes: "function",
|
||
domain: "function",
|
||
prehash: "function",
|
||
zip215: "boolean",
|
||
mapToCurve: "function",
|
||
toMontgomery: "function",
|
||
toMontgomerySecret: "function"
|
||
});
|
||
const { prehash } = opts;
|
||
const { BASE, Fp: Fp2, Fn } = Point;
|
||
const outputLen = hash.outputLen;
|
||
const expectedLen = 2 * Fp2.BYTES;
|
||
if (outputLen !== void 0) {
|
||
asafenumber(outputLen, "hash.outputLen");
|
||
if (outputLen !== expectedLen)
|
||
throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
|
||
}
|
||
const randomBytes4 = opts.randomBytes === void 0 ? randomBytes3 : opts.randomBytes;
|
||
const toMontgomery2 = opts.toMontgomery;
|
||
const toMontgomerySecret2 = opts.toMontgomerySecret;
|
||
const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes2) => bytes2 : opts.adjustScalarBytes;
|
||
const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
|
||
abool2(phflag, "phflag");
|
||
if (ctx.length || phflag)
|
||
throw new Error("Contexts/pre-hash are not supported");
|
||
return data;
|
||
} : opts.domain;
|
||
function modN_LE(hash2) {
|
||
return Fn.create(bytesToNumberLE(hash2));
|
||
}
|
||
function getPrivateScalar(key) {
|
||
const len = lengths.secretKey;
|
||
abytes3(key, lengths.secretKey, "secretKey");
|
||
const hashed = abytes3(hash(key), 2 * len, "hashedSecretKey");
|
||
const head = adjustScalarBytes2(hashed.slice(0, len));
|
||
const prefix = hashed.slice(len, 2 * len);
|
||
const scalar = modN_LE(head);
|
||
return { head, prefix, scalar };
|
||
}
|
||
function getExtendedPublicKey(secretKey) {
|
||
const { head, prefix, scalar } = getPrivateScalar(secretKey);
|
||
const point = BASE.multiply(scalar);
|
||
const pointBytes = point.toBytes();
|
||
return { head, prefix, scalar, point, pointBytes };
|
||
}
|
||
function getPublicKey(secretKey) {
|
||
return getExtendedPublicKey(secretKey).pointBytes;
|
||
}
|
||
function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
|
||
const msg = concatBytes2(...msgs);
|
||
return modN_LE(hash(domain(msg, abytes3(context, void 0, "context"), !!prehash)));
|
||
}
|
||
function sign(msg, secretKey, options = {}) {
|
||
validateObject(options, {}, {}, "options");
|
||
msg = copyBytes2(abytes3(msg, void 0, "message"));
|
||
if (prehash)
|
||
msg = prehash(msg);
|
||
const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
|
||
const r = hashDomainToScalar(options.context, prefix, msg);
|
||
const R = BASE.multiply(r).toBytes();
|
||
const k = hashDomainToScalar(options.context, R, pointBytes, msg);
|
||
const s = Fn.create(r + k * scalar);
|
||
if (!Fn.isValid(s))
|
||
throw new Error("sign failed: invalid s");
|
||
const rs = concatBytes2(R, Fn.toBytes(s));
|
||
return abytes3(rs, lengths.signature, "result");
|
||
}
|
||
const verifyOpts2 = {
|
||
zip215: opts.zip215
|
||
};
|
||
function verify(sig, msg, publicKey, options = verifyOpts2) {
|
||
validateObject(options);
|
||
const { context } = options;
|
||
const zip215 = options.zip215 === void 0 ? !!verifyOpts2.zip215 : options.zip215;
|
||
const len = lengths.signature;
|
||
sig = abytes3(sig, len, "signature");
|
||
msg = abytes3(msg, void 0, "message");
|
||
publicKey = abytes3(publicKey, lengths.publicKey, "publicKey");
|
||
if (zip215 !== void 0)
|
||
abool2(zip215, "zip215");
|
||
if (prehash)
|
||
msg = prehash(msg);
|
||
const mid = len / 2;
|
||
const r = sig.subarray(0, mid);
|
||
const s = bytesToNumberLE(sig.subarray(mid, len));
|
||
let A, R, SB;
|
||
try {
|
||
A = Point.fromBytes(publicKey, zip215);
|
||
R = Point.fromBytes(r, zip215);
|
||
SB = BASE.multiplyUnsafe(s);
|
||
} catch (error) {
|
||
return false;
|
||
}
|
||
if (!zip215 && A.isSmallOrder())
|
||
return false;
|
||
const k = hashDomainToScalar(context, r, publicKey, msg);
|
||
const RkA = R.add(A.multiplyUnsafe(k));
|
||
return RkA.subtract(SB).clearCofactor().is0();
|
||
}
|
||
const _size = Fp2.BYTES;
|
||
const lengths = {
|
||
secretKey: _size,
|
||
publicKey: _size,
|
||
signature: 2 * _size,
|
||
seed: _size
|
||
};
|
||
function randomSecretKey(seed) {
|
||
seed = seed === void 0 ? randomBytes4(lengths.seed) : seed;
|
||
return abytes3(seed, lengths.seed, "seed");
|
||
}
|
||
function isValidSecretKey(key) {
|
||
return isBytes3(key) && key.length === lengths.secretKey;
|
||
}
|
||
function isValidPublicKey(key, zip215) {
|
||
try {
|
||
return !!Point.fromBytes(key, zip215 === void 0 ? verifyOpts2.zip215 : zip215);
|
||
} catch (error) {
|
||
return false;
|
||
}
|
||
}
|
||
const utils = {
|
||
getExtendedPublicKey,
|
||
randomSecretKey,
|
||
isValidSecretKey,
|
||
isValidPublicKey,
|
||
/** Converts an Edwards public key to a companion Montgomery public key. */
|
||
toMontgomery(publicKey) {
|
||
if (toMontgomery2 === void 0)
|
||
throw new Error("Montgomery conversion is not supported for this curve");
|
||
return toMontgomery2(Point.fromBytes(publicKey));
|
||
},
|
||
toMontgomerySecret(secretKey) {
|
||
if (toMontgomerySecret2 === void 0)
|
||
throw new Error("Montgomery conversion is not supported for this curve");
|
||
return toMontgomerySecret2(secretKey);
|
||
}
|
||
};
|
||
Object.freeze(lengths);
|
||
Object.freeze(utils);
|
||
return Object.freeze({
|
||
keygen: createKeygen(randomSecretKey, getPublicKey),
|
||
getPublicKey,
|
||
sign,
|
||
verify,
|
||
utils,
|
||
Point,
|
||
lengths
|
||
});
|
||
}
|
||
|
||
// node_modules/@noble/curves/abstract/montgomery.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n5 = /* @__PURE__ */ BigInt(0);
|
||
var _1n5 = /* @__PURE__ */ BigInt(1);
|
||
var _2n3 = /* @__PURE__ */ BigInt(2);
|
||
function cmask(P, swap) {
|
||
return P + swap - (swap >> _1n5 << _1n5);
|
||
}
|
||
function cswap(P) {
|
||
const offset = BigInt(6) * P;
|
||
return (mask, x_2, x_3) => {
|
||
const sum = x_2 + x_3;
|
||
const d = offset + x_3 - x_2;
|
||
const a = (d * mask + x_2) % P;
|
||
return { x_2: a, x_3: sum - a };
|
||
};
|
||
}
|
||
function validateOpts(curve) {
|
||
validateObject(curve, {
|
||
P: "bigint",
|
||
type: "string",
|
||
adjustScalarBytes: "function",
|
||
powPminus2: "function"
|
||
}, {
|
||
randomBytes: "function",
|
||
scalarMultBase: "function"
|
||
});
|
||
return Object.freeze({ ...curve });
|
||
}
|
||
function montgomery(curveDef) {
|
||
const CURVE = validateOpts(curveDef);
|
||
const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
|
||
const mulBaseHook = CURVE.scalarMultBase;
|
||
const is25519 = type === "x25519";
|
||
if (!is25519 && type !== "x448")
|
||
throw new Error("invalid type");
|
||
const randomBytes_ = rand === void 0 ? randomBytes3 : rand;
|
||
const montgomeryBits = is25519 ? 255 : 448;
|
||
const swap = cswap(P);
|
||
const fieldLen = is25519 ? 32 : 56;
|
||
const Gu = is25519 ? BigInt(9) : BigInt(5);
|
||
const a24 = is25519 ? BigInt(121665) : BigInt(39081);
|
||
const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
|
||
const maxAdded = is25519 ? BigInt(8) * (_2n3 ** BigInt(251) - _1n5) : BigInt(4) * (_2n3 ** BigInt(445) - _1n5);
|
||
const maxScalar = minScalar + maxAdded + _1n5;
|
||
const modP = (n) => mod(n, P);
|
||
const GuBytes = encodeU(Gu);
|
||
function encodeU(u) {
|
||
return numberToBytesLE(modP(u), fieldLen);
|
||
}
|
||
function decodeU(u) {
|
||
const _u = copyBytes2(abytes3(u, fieldLen, "uCoordinate"));
|
||
if (is25519)
|
||
_u[31] &= 127;
|
||
return modP(bytesToNumberLE(_u));
|
||
}
|
||
function decodeScalar(scalar) {
|
||
return bytesToNumberLE(adjustScalarBytes2(copyBytes2(abytes3(scalar, fieldLen, "scalar"))));
|
||
}
|
||
const lowOrderU = new Set(is25519 ? [
|
||
_0n5,
|
||
_1n5,
|
||
P - _1n5,
|
||
BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),
|
||
BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")
|
||
] : [_0n5, _1n5, P - _1n5]);
|
||
function scalarMult(scalar, u) {
|
||
const pointU = decodeU(u);
|
||
if (lowOrderU.has(pointU))
|
||
throw new Error("invalid private or public key received");
|
||
const pu = montgomeryLadder(pointU, decodeScalar(scalar));
|
||
if (pu === _0n5)
|
||
throw new Error("invalid private or public key received");
|
||
return encodeU(pu);
|
||
}
|
||
function scalarMultBase(scalar) {
|
||
if (mulBaseHook === void 0)
|
||
return scalarMult(scalar, GuBytes);
|
||
const k = decodeScalar(scalar);
|
||
aInRange("scalar", k, minScalar, maxScalar);
|
||
const pu = modP(mulBaseHook(k));
|
||
if (pu === _0n5)
|
||
throw new Error("invalid private or public key received");
|
||
return encodeU(pu);
|
||
}
|
||
const getPublicKey = scalarMultBase;
|
||
const getSharedSecret = scalarMult;
|
||
function montgomeryLadder(u, scalar) {
|
||
aInRange("u", u, _0n5, P);
|
||
aInRange("scalar", scalar, minScalar, maxScalar);
|
||
const k = scalar;
|
||
const x_1 = u;
|
||
let x_2 = _1n5;
|
||
let z_2 = _0n5;
|
||
let x_3 = u;
|
||
let z_3 = _1n5;
|
||
const kx = k ^ k >> _1n5;
|
||
for (let t2 = BigInt(montgomeryBits - 1); t2 >= _0n5; t2--) {
|
||
const mask2 = cmask(P, kx >> t2);
|
||
({ x_2, x_3 } = swap(mask2, x_2, x_3));
|
||
({ x_2: z_2, x_3: z_3 } = swap(mask2, z_2, z_3));
|
||
const A = x_2 + z_2;
|
||
const AA = modP(A * A);
|
||
const B = x_2 - z_2;
|
||
const BB = modP(B * B);
|
||
const E = AA - BB;
|
||
const C = x_3 + z_3;
|
||
const D = x_3 - z_3;
|
||
const DA = modP(D * A);
|
||
const CB = modP(C * B);
|
||
const dacb = DA + CB;
|
||
const da_cb = DA - CB;
|
||
x_3 = modP(dacb * dacb);
|
||
z_3 = modP(x_1 * modP(da_cb * da_cb));
|
||
x_2 = modP(AA * BB);
|
||
z_2 = modP(E * (AA + modP(a24 * E)));
|
||
}
|
||
const mask = cmask(P, k);
|
||
({ x_2, x_3 } = swap(mask, x_2, x_3));
|
||
({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));
|
||
const z2 = powPminus2(z_2);
|
||
return modP(x_2 * z2);
|
||
}
|
||
const lengths = {
|
||
secretKey: fieldLen,
|
||
publicKey: fieldLen,
|
||
seed: fieldLen
|
||
};
|
||
const randomSecretKey = (seed) => {
|
||
seed = seed === void 0 ? randomBytes_(fieldLen) : seed;
|
||
abytes3(seed, lengths.seed, "seed");
|
||
return seed;
|
||
};
|
||
const utils = { randomSecretKey };
|
||
Object.freeze(lengths);
|
||
Object.freeze(utils);
|
||
return Object.freeze({
|
||
keygen: createKeygen(randomSecretKey, getPublicKey),
|
||
getSharedSecret,
|
||
getPublicKey,
|
||
scalarMult,
|
||
scalarMultBase,
|
||
utils,
|
||
GuBytes: GuBytes.slice(),
|
||
lengths
|
||
});
|
||
}
|
||
|
||
// node_modules/@noble/curves/ed25519.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n6 = /* @__PURE__ */ BigInt(0);
|
||
var _1n6 = /* @__PURE__ */ BigInt(1);
|
||
var _2n4 = /* @__PURE__ */ BigInt(2);
|
||
var _3n2 = /* @__PURE__ */ BigInt(3);
|
||
var _5n2 = /* @__PURE__ */ BigInt(5);
|
||
var _8n3 = /* @__PURE__ */ BigInt(8);
|
||
var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
|
||
var ed25519_CURVE = /* @__PURE__ */ (() => ({
|
||
p: ed25519_CURVE_p,
|
||
n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
|
||
h: _8n3,
|
||
a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
|
||
d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
|
||
Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
|
||
Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
|
||
}))();
|
||
function ed25519_pow_2_252_3(x) {
|
||
const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
|
||
const P = ed25519_CURVE_p;
|
||
const x2 = x * x % P;
|
||
const b2 = x2 * x % P;
|
||
const b4 = pow2(b2, _2n4, P) * b2 % P;
|
||
const b5 = pow2(b4, _1n6, P) * x % P;
|
||
const b10 = pow2(b5, _5n2, P) * b5 % P;
|
||
const b20 = pow2(b10, _10n, P) * b10 % P;
|
||
const b40 = pow2(b20, _20n, P) * b20 % P;
|
||
const b80 = pow2(b40, _40n, P) * b40 % P;
|
||
const b160 = pow2(b80, _80n, P) * b80 % P;
|
||
const b240 = pow2(b160, _80n, P) * b80 % P;
|
||
const b250 = pow2(b240, _10n, P) * b10 % P;
|
||
const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
|
||
return { pow_p_5_8, b2 };
|
||
}
|
||
function adjustScalarBytes(bytes2) {
|
||
bytes2[0] &= 248;
|
||
bytes2[31] &= 127;
|
||
bytes2[31] |= 64;
|
||
return bytes2;
|
||
}
|
||
var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
|
||
function uvRatio(u, v) {
|
||
const P = ed25519_CURVE_p;
|
||
const v3 = mod(v * v * v, P);
|
||
const v7 = mod(v3 * v3 * v, P);
|
||
const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
|
||
let x = mod(u * v3 * pow3, P);
|
||
const vx2 = mod(v * x * x, P);
|
||
const root1 = x;
|
||
const root2 = mod(x * ED25519_SQRT_M1, P);
|
||
const useRoot1 = vx2 === u;
|
||
const useRoot2 = vx2 === mod(-u, P);
|
||
const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
|
||
if (useRoot1)
|
||
x = root1;
|
||
if (useRoot2 || noRoot)
|
||
x = root2;
|
||
if (isNegativeLE(x, P))
|
||
x = mod(-x, P);
|
||
return { isValid: useRoot1 || useRoot2, value: x };
|
||
}
|
||
var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
|
||
var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
|
||
function toMontgomery(point) {
|
||
const { y } = point;
|
||
return Fp.toBytes(Fp.div(_1n6 + y, _1n6 - y));
|
||
}
|
||
function toMontgomerySecret(secretKey) {
|
||
const size = ed25519_Point.Fp.BYTES;
|
||
abytes2(secretKey, size);
|
||
return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);
|
||
}
|
||
function ed(opts) {
|
||
return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));
|
||
}
|
||
var ed25519 = /* @__PURE__ */ ed({});
|
||
var x25519 = /* @__PURE__ */ (() => {
|
||
const P = ed25519_CURVE_p;
|
||
const powPminus2 = (x) => {
|
||
const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
|
||
return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
|
||
};
|
||
return montgomery({
|
||
P,
|
||
type: "x25519",
|
||
powPminus2,
|
||
adjustScalarBytes,
|
||
// ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached
|
||
// base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.
|
||
// Same construction as libsodium's crypto_scalarmult_curve25519_base.
|
||
scalarMultBase: (k) => {
|
||
const kn = mod(k, ed25519_Point.Fn.ORDER);
|
||
if (kn === _0n6)
|
||
return _0n6;
|
||
const p = ed25519_Point.BASE.multiply(kn);
|
||
return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);
|
||
}
|
||
});
|
||
})();
|
||
|
||
// node_modules/@noble/hashes/hmac.js
|
||
var _HMAC = class {
|
||
oHash;
|
||
iHash;
|
||
blockLen;
|
||
outputLen;
|
||
canXOF = false;
|
||
finished = false;
|
||
destroyed = false;
|
||
constructor(hash, key) {
|
||
ahash(hash);
|
||
abytes2(key, void 0, "key");
|
||
this.iHash = hash.create();
|
||
if (typeof this.iHash.update !== "function")
|
||
throw new Error("expected Hash instance");
|
||
this.blockLen = this.iHash.blockLen;
|
||
this.outputLen = this.iHash.outputLen;
|
||
const blockLen = this.blockLen;
|
||
const pad2 = new Uint8Array(blockLen);
|
||
pad2.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
||
for (let i = 0; i < pad2.length; i++)
|
||
pad2[i] ^= 54;
|
||
this.iHash.update(pad2);
|
||
this.oHash = hash.create();
|
||
for (let i = 0; i < pad2.length; i++)
|
||
pad2[i] ^= 54 ^ 92;
|
||
this.oHash.update(pad2);
|
||
clean2(pad2);
|
||
}
|
||
update(buf) {
|
||
aexists2(this);
|
||
this.iHash.update(buf);
|
||
return this;
|
||
}
|
||
digestInto(out) {
|
||
aexists2(this);
|
||
aoutput2(out, this);
|
||
this.finished = true;
|
||
const buf = out.subarray(0, this.outputLen);
|
||
this.iHash.digestInto(buf);
|
||
this.oHash.update(buf);
|
||
this.oHash.digestInto(buf);
|
||
this.destroy();
|
||
}
|
||
digest() {
|
||
const out = new Uint8Array(this.oHash.outputLen);
|
||
this.digestInto(out);
|
||
return out;
|
||
}
|
||
_cloneInto(to) {
|
||
to ||= Object.create(Object.getPrototypeOf(this), {});
|
||
const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
|
||
to = to;
|
||
to.finished = finished;
|
||
to.destroyed = destroyed;
|
||
to.blockLen = blockLen;
|
||
to.outputLen = outputLen;
|
||
to.canXOF = canXOF;
|
||
to.oHash = oHash._cloneInto(to.oHash);
|
||
to.iHash = iHash._cloneInto(to.iHash);
|
||
return to;
|
||
}
|
||
clone() {
|
||
return this._cloneInto();
|
||
}
|
||
destroy() {
|
||
this.destroyed = true;
|
||
this.oHash.destroy();
|
||
this.iHash.destroy();
|
||
}
|
||
};
|
||
var hmac = /* @__PURE__ */ (() => {
|
||
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
|
||
hmac_.create = (hash, key) => new _HMAC(hash, key);
|
||
return hmac_;
|
||
})();
|
||
|
||
// node_modules/@noble/hashes/hkdf.js
|
||
var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
|
||
var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
|
||
function expand(hash, prk, info, length = 32, _recycled) {
|
||
ahash(hash);
|
||
anumber2(length, "length");
|
||
abytes2(prk, void 0, "prk");
|
||
const olen = hash.outputLen;
|
||
if (prk.length < olen)
|
||
throw new Error('"prk" must be at least HashLen octets');
|
||
if (length > 255 * olen)
|
||
throw new Error("Length must be <= 255*HashLen");
|
||
const blocks = Math.ceil(length / olen);
|
||
if (info === void 0)
|
||
info = EMPTY_BUFFER;
|
||
else
|
||
abytes2(info, void 0, "info");
|
||
if (!blocks) {
|
||
if (_recycled)
|
||
clean2(prk);
|
||
return new Uint8Array();
|
||
}
|
||
const okm = _recycled && blocks === 1 ? prk : new Uint8Array(blocks * olen);
|
||
const { iHash, oHash } = hmac.create(hash, prk);
|
||
const T = _recycled ? prk : new Uint8Array(olen);
|
||
const worker = blocks > 1 ? _recycled?.iHash || hash.create() : void 0;
|
||
for (let counter = 0; counter < blocks - 1; counter++) {
|
||
HKDF_COUNTER[0] = counter + 1;
|
||
const iWork = iHash._cloneInto(worker);
|
||
if (counter)
|
||
iWork.update(T);
|
||
iWork.update(info).update(HKDF_COUNTER).digestInto(T);
|
||
oHash._cloneInto(worker).update(T).digestInto(T);
|
||
okm.set(T, olen * counter);
|
||
}
|
||
HKDF_COUNTER[0] = blocks;
|
||
if (blocks > 1)
|
||
iHash.update(T);
|
||
iHash.update(info).update(HKDF_COUNTER).digestInto(T);
|
||
oHash.update(T).digestInto(T);
|
||
okm.set(T, olen * (blocks - 1));
|
||
iHash.destroy();
|
||
oHash.destroy();
|
||
worker?.destroy();
|
||
if (T !== okm)
|
||
clean2(T);
|
||
clean2(HKDF_COUNTER);
|
||
if (length === okm.length)
|
||
return okm;
|
||
const res = okm.slice(0, length);
|
||
clean2(okm);
|
||
return res;
|
||
}
|
||
var hkdf = (hash, ikm, salt, info, length) => {
|
||
ahash(hash);
|
||
if (salt === void 0)
|
||
salt = new Uint8Array(hash.outputLen);
|
||
const HMAC = hmac.create(hash, salt).update(ikm);
|
||
return expand(hash, HMAC.digest(), info, length, HMAC);
|
||
};
|
||
|
||
// src/verify.ts
|
||
var LISTING_CONTEXT = "allmende-listing-v1\n";
|
||
var CERT_CONTEXT = "allmende-cert-v1\n";
|
||
var DAY = 86400;
|
||
var MAX_CERT_LIFETIME = 366 * DAY;
|
||
var MAX_LISTING_LIFETIME = 30 * DAY;
|
||
var MAX_CLOCK_SKEW = 10 * 60;
|
||
var enc = new TextEncoder();
|
||
function hexBytes(s, bytes2) {
|
||
if (typeof s !== "string" || s.length !== bytes2 * 2 || !/^[0-9a-f]+$/.test(s)) {
|
||
return null;
|
||
}
|
||
const out = new Uint8Array(bytes2);
|
||
for (let i = 0; i < bytes2; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
||
return out;
|
||
}
|
||
function leadingZeroBits(bytes2) {
|
||
let n = 0;
|
||
for (const b of bytes2) {
|
||
if (b === 0) {
|
||
n += 8;
|
||
continue;
|
||
}
|
||
return n + Math.clz32(b) - 24;
|
||
}
|
||
return n;
|
||
}
|
||
function without(o, key) {
|
||
const copy = { ...o };
|
||
delete copy[key];
|
||
return copy;
|
||
}
|
||
function isObject(v) {
|
||
return typeof v === "object" && v !== null && !Array.isArray(v);
|
||
}
|
||
function safeInt(v) {
|
||
return typeof v === "number" && Number.isSafeInteger(v);
|
||
}
|
||
function signedBy(context, signed, sigHex, pubHex) {
|
||
const sig = hexBytes(sigHex, 64);
|
||
const pub = hexBytes(pubHex, 32);
|
||
if (!sig || !pub) return false;
|
||
try {
|
||
const msg = enc.encode(context + canonicalize(signed));
|
||
return ed25519.verify(sig, msg, pub);
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
function verifyListing(input, opts) {
|
||
const checks = [];
|
||
const add2 = (id, ok, info = "") => checks.push({ id, ok, info });
|
||
let powBits = 0;
|
||
const finish = () => ({ ok: checks.every((c2) => c2.ok), checks, powBits });
|
||
if (!isObject(input) || !isObject(input.cert)) {
|
||
add2("format", false, "not a listing object");
|
||
return finish();
|
||
}
|
||
const l = input;
|
||
const c = l.cert;
|
||
const shapeOk = l.v === 1 && hexBytes(l.id, 16) !== null && hexBytes(l.author, 32) !== null && hexBytes(l.device, 32) !== null && hexBytes(l.sig, 64) !== null && safeInt(l.seq) && safeInt(l.created_at) && safeInt(l.expires_at) && safeInt(l.pow) && typeof l.geohash === "string";
|
||
add2("format", shapeOk, shapeOk ? "" : "malformed fields");
|
||
if (!shapeOk) return finish();
|
||
const certShape = c.v === 1 && hexBytes(c.author, 32) !== null && hexBytes(c.device, 32) !== null && safeInt(c.issued_at) && safeInt(c.expires_at) && c.expires_at > c.issued_at && c.expires_at - c.issued_at <= MAX_CERT_LIFETIME;
|
||
const certSig = certShape && signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
|
||
add2(
|
||
"certificate",
|
||
certSig,
|
||
!certShape ? "malformed certificate" : certSig ? "" : "bad certificate signature"
|
||
);
|
||
if (!certSig) return finish();
|
||
const bound = c.author === l.author && c.device === l.device;
|
||
add2("binding", bound, bound ? "" : "certificate is for a different identity or device");
|
||
const reasons = [];
|
||
if (!(c.issued_at <= l.created_at && l.created_at < c.expires_at)) {
|
||
reasons.push("created outside certificate validity");
|
||
}
|
||
if (opts.now >= c.expires_at) reasons.push("certificate expired");
|
||
if (l.expires_at <= l.created_at) reasons.push("expires before it was created");
|
||
if (l.expires_at - l.created_at > MAX_LISTING_LIFETIME) reasons.push("lifetime over 30 days");
|
||
if (l.created_at > opts.now + MAX_CLOCK_SKEW) reasons.push("created in the future");
|
||
if (l.expires_at <= opts.now) reasons.push("expired");
|
||
add2("validity", reasons.length === 0, reasons.join("; "));
|
||
const unsigned = without(l, "sig");
|
||
const sigOk = signedBy(LISTING_CONTEXT, unsigned, l.sig, l.device);
|
||
add2("signature", sigOk, sigOk ? "" : "signature does not match the content");
|
||
try {
|
||
powBits = leadingZeroBits(sha256(enc.encode(canonicalize(unsigned))));
|
||
} catch {
|
||
powBits = 0;
|
||
}
|
||
const powOk = powBits >= opts.minPowBits;
|
||
add2("pow", powOk, `${powBits} bits (network requires ${opts.minPowBits})`);
|
||
return finish();
|
||
}
|
||
|
||
// src/message.ts
|
||
var VERSION = 1;
|
||
var MAX_LIFETIME = 14 * 86400;
|
||
var MAX_PLAIN = 4095;
|
||
var MAX_FIRST_TEXT = 1e3;
|
||
var MAX_TEXT = 2e3;
|
||
var MAX_ADDRESS = 300;
|
||
var MAX_PHONE = 40;
|
||
var MAX_EMAIL = 120;
|
||
var MAX_NOTE = 1e3;
|
||
var MAX_GRANT_VALIDITY = 30 * 86400;
|
||
var DEFAULT_MESSAGE_DIFFICULTY = 14;
|
||
var BUCKETS = [512, 1024, 2048, 4096];
|
||
var TAG = 16;
|
||
var enc2 = new TextEncoder();
|
||
var SEAL_INFO = enc2.encode("allmende-seal-v1");
|
||
var MAILBOX_CONTEXT = "allmende-mailbox-v1\n";
|
||
var REPLY_CONTEXT = "allmende-reply-v1\n";
|
||
function toHex(b) {
|
||
let s = "";
|
||
for (const x of b) s += x.toString(16).padStart(2, "0");
|
||
return s;
|
||
}
|
||
function concat(...parts) {
|
||
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
||
let at = 0;
|
||
for (const p of parts) {
|
||
out.set(p, at);
|
||
at += p.length;
|
||
}
|
||
return out;
|
||
}
|
||
var byteLength = (s) => enc2.encode(s).length;
|
||
var InputError = class extends Error {
|
||
problem;
|
||
constructor(problem) {
|
||
super(`message text rejected: ${problem}`);
|
||
this.problem = problem;
|
||
}
|
||
};
|
||
var HOSTNAME = /[\p{L}\p{N}-]+\.\p{L}{2,}/u;
|
||
function containsLink(s) {
|
||
const l = s.toLowerCase();
|
||
return l.includes("://") || l.includes("www.") || HOSTNAME.test(l);
|
||
}
|
||
function checkBuyerText(text, first) {
|
||
if (text.length === 0) return "empty";
|
||
if (/\p{Cs}/u.test(text)) return "invalid";
|
||
if (/[\p{Cc}]/u.test(text.replace(/\n/g, ""))) return "control";
|
||
if (byteLength(text) > (first ? MAX_FIRST_TEXT : MAX_TEXT)) return "long";
|
||
if (first && containsLink(text)) return "link";
|
||
return null;
|
||
}
|
||
function validField(s, maxBytes, min, newlines) {
|
||
if (typeof s !== "string") return false;
|
||
if (s.length < min || byteLength(s) > maxBytes) return false;
|
||
if (/\p{Cs}/u.test(s)) return false;
|
||
return !/[\p{Cc}]/u.test(newlines ? s.replace(/\n/g, "") : s);
|
||
}
|
||
function threadPublic(secret) {
|
||
return toHex(x25519.getPublicKey(secret));
|
||
}
|
||
function mailbox(threadPubHex) {
|
||
const pub = hexBytes(threadPubHex, 32);
|
||
if (!pub) throw new Error("bad thread key");
|
||
return toHex(sha256(concat(enc2.encode(MAILBOX_CONTEXT), pub)).slice(0, 16));
|
||
}
|
||
function envelopeHash(env) {
|
||
return toHex(sha256(enc2.encode(canonicalize(env))));
|
||
}
|
||
function pad(b) {
|
||
if (b.length > MAX_PLAIN) throw new InputError("long");
|
||
const size = BUCKETS.find((s) => b.length + 1 <= s) ?? BUCKETS[BUCKETS.length - 1];
|
||
const out = new Uint8Array(size);
|
||
out.set(b);
|
||
out[b.length] = 128;
|
||
return out;
|
||
}
|
||
function unpad(b) {
|
||
let end = b.length;
|
||
while (end > 0 && b[end - 1] === 0) end--;
|
||
if (end === 0 || b[end - 1] !== 128) throw new Error("bad padding");
|
||
return b.slice(0, end - 1);
|
||
}
|
||
function aead(shared, epk, rpk, header) {
|
||
const key = hkdf(sha256, shared, concat(epk, rpk), SEAL_INFO, 32);
|
||
return chacha20poly1305(key, new Uint8Array(12), enc2.encode(canonicalize(header)));
|
||
}
|
||
function headerOf(e2) {
|
||
return {
|
||
v: e2.v,
|
||
listing: { author: e2.listing.author, id: e2.listing.id },
|
||
to: e2.to,
|
||
rcpt: e2.rcpt,
|
||
epk: e2.epk,
|
||
created_at: e2.created_at,
|
||
expires_at: e2.expires_at
|
||
};
|
||
}
|
||
var tick = () => new Promise((r) => setTimeout(r, 0));
|
||
async function mine(env, difficulty2) {
|
||
const canon = canonicalize({ ...env, pow: 0 });
|
||
const marker = '"pow":0,';
|
||
const at = canon.indexOf(marker);
|
||
if (at < 0 || canon.indexOf(marker, at + 1) >= 0) throw new Error("unexpected envelope shape");
|
||
const prefix = sha256.create().update(enc2.encode(canon.slice(0, at + 6)));
|
||
const suffix = enc2.encode(canon.slice(at + 7));
|
||
for (let n = 0; n <= Number.MAX_SAFE_INTEGER; n++) {
|
||
const sum = prefix.clone().update(enc2.encode(String(n))).update(suffix).digest();
|
||
if (zeroBits(sum) >= difficulty2) {
|
||
env.pow = n;
|
||
return;
|
||
}
|
||
if (n % 2048 === 2047) await tick();
|
||
}
|
||
throw new Error("proof-of-work exhausted");
|
||
}
|
||
function zeroBits(b) {
|
||
let n = 0;
|
||
for (const x of b) {
|
||
if (x === 0) {
|
||
n += 8;
|
||
continue;
|
||
}
|
||
return n + Math.clz32(x) - 24;
|
||
}
|
||
return n;
|
||
}
|
||
async function buildToOwner(a) {
|
||
const problem = checkBuyerText(a.text, a.first);
|
||
if (problem) throw new InputError(problem);
|
||
const devicePub = hexBytes(a.listing.device, 32);
|
||
if (!devicePub) throw new Error("bad device key");
|
||
const plain = { t: "text", thread: threadPublic(a.threadSecret), n: a.n, sent_at: a.now, text: a.text };
|
||
return sealEnvelope({
|
||
listing: { author: a.listing.author, id: a.listing.id },
|
||
to: "owner",
|
||
rcpt: a.listing.device,
|
||
rpk: ed25519.utils.toMontgomery(devicePub),
|
||
body: enc2.encode(canonicalize(plain)),
|
||
now: a.now,
|
||
difficulty: a.difficulty,
|
||
esk: a.esk
|
||
});
|
||
}
|
||
async function sealEnvelope(a) {
|
||
const esk = a.esk ?? x25519.utils.randomSecretKey();
|
||
const epk = x25519.getPublicKey(esk);
|
||
const env = {
|
||
v: VERSION,
|
||
listing: { author: a.listing.author, id: a.listing.id },
|
||
to: a.to,
|
||
rcpt: a.rcpt,
|
||
epk: toHex(epk),
|
||
created_at: a.now,
|
||
expires_at: a.now + MAX_LIFETIME,
|
||
ct: "",
|
||
pow: 0
|
||
};
|
||
const shared = x25519.getSharedSecret(esk, a.rpk);
|
||
env.ct = toHex(aead(shared, epk, a.rpk, headerOf(env)).encrypt(pad(a.body)));
|
||
await mine(env, a.difficulty);
|
||
return env;
|
||
}
|
||
var fail = (error) => ({ ok: false, error });
|
||
function openReply(input, threadSecret, expect) {
|
||
try {
|
||
return open(input, threadSecret, expect);
|
||
} catch (e2) {
|
||
return fail(e2 instanceof Error ? e2.message : "unreadable");
|
||
}
|
||
}
|
||
function open(input, threadSecret, expect) {
|
||
if (!isObject(input) || !isObject(input.listing)) return fail("not an envelope");
|
||
const e2 = input;
|
||
const threadPub = threadPublic(threadSecret);
|
||
const epk = hexBytes(e2.epk, 32);
|
||
const ct = typeof e2.ct === "string" && /^[0-9a-f]*$/.test(e2.ct) && e2.ct.length % 2 === 0 ? hexBytes(e2.ct, e2.ct.length / 2) : null;
|
||
if (e2.v !== VERSION || e2.to !== "buyer" || e2.rcpt !== mailbox(threadPub) || !epk || !ct || ct.length < TAG + 1 || ct.length > BUCKETS[BUCKETS.length - 1] + TAG || !safeInt(e2.created_at) || !safeInt(e2.expires_at)) {
|
||
return fail("not a reply for this conversation");
|
||
}
|
||
if (e2.listing.author !== expect.author || e2.listing.id !== expect.id) {
|
||
return fail("reply refers to another listing");
|
||
}
|
||
const rpk = x25519.getPublicKey(threadSecret);
|
||
const shared = x25519.getSharedSecret(threadSecret, epk);
|
||
let body;
|
||
try {
|
||
body = unpad(aead(shared, epk, rpk, headerOf(e2)).decrypt(ct));
|
||
} catch {
|
||
return fail("cannot decrypt");
|
||
}
|
||
const text = new TextDecoder("utf-8", { fatal: true }).decode(body);
|
||
const p = JSON.parse(text);
|
||
if (canonicalize(p) !== text) return fail("plaintext is not canonical");
|
||
const bad = checkOwnerPlain(p);
|
||
if (bad) return fail(bad);
|
||
const plain = p;
|
||
if (plain.thread !== threadPub) return fail("reply belongs to another thread");
|
||
if (plain.listing.author !== e2.listing.author || plain.listing.id !== e2.listing.id) {
|
||
return fail("reply refers to another listing");
|
||
}
|
||
const c = plain.cert;
|
||
const certOk = c.v === 1 && hexBytes(c.author, 32) !== null && hexBytes(c.device, 32) !== null && safeInt(c.issued_at) && safeInt(c.expires_at) && c.expires_at > c.issued_at && c.expires_at - c.issued_at <= MAX_CERT_LIFETIME && signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
|
||
if (!certOk) return fail("bad certificate");
|
||
if (c.author !== plain.listing.author || c.device !== plain.device) {
|
||
return fail("certificate does not match the listing's author and the device");
|
||
}
|
||
if (!(c.issued_at <= plain.sent_at && plain.sent_at < c.expires_at)) {
|
||
return fail("sent outside the certificate's validity");
|
||
}
|
||
if (!signedBy(REPLY_CONTEXT, without(plain, "sig"), plain.sig, plain.device)) {
|
||
return fail("bad signature");
|
||
}
|
||
return { ok: true, plain };
|
||
}
|
||
function checkOwnerPlain(p) {
|
||
if (!isObject(p)) return "plaintext is not an object";
|
||
const q = p;
|
||
if (hexBytes(q.thread, 32) === null) return "bad thread";
|
||
if (!safeInt(q.n) || q.n < 1 || !safeInt(q.sent_at) || q.sent_at <= 0) return "bad counter or time";
|
||
if (!isObject(q.listing) || hexBytes(q.listing.author, 32) === null || hexBytes(q.listing.id, 16) === null || hexBytes(q.device, 32) === null || !isObject(q.cert) || hexBytes(q.sig, 64) === null) {
|
||
return "reply is not signed";
|
||
}
|
||
const grantFields = q.address !== void 0 || q.phone !== void 0 || q.email !== void 0 || q.note !== void 0 || q.valid_until !== void 0;
|
||
if (q.t === "text") {
|
||
if (grantFields) return "text with grant fields";
|
||
return validField(q.text, MAX_TEXT, 1, true) ? null : "bad text";
|
||
}
|
||
if (q.t === "grant") {
|
||
if (q.text !== void 0) return "a grant carries its words in note";
|
||
if (!validField(q.address, MAX_ADDRESS, 1, true)) return "bad address";
|
||
if (q.phone !== void 0 && !validField(q.phone, MAX_PHONE, 1, false)) return "bad phone";
|
||
if (q.email !== void 0 && !validField(q.email, MAX_EMAIL, 1, false)) return "bad email";
|
||
if (q.note !== void 0 && !validField(q.note, MAX_NOTE, 1, true)) return "bad note";
|
||
if (!safeInt(q.valid_until) || q.valid_until <= q.sent_at || q.valid_until - q.sent_at > MAX_GRANT_VALIDITY) {
|
||
return "bad validity of the grant";
|
||
}
|
||
return null;
|
||
}
|
||
return "unknown type";
|
||
}
|
||
|
||
// src/state.ts
|
||
var state = {
|
||
/** What the node that served this page says about itself; null until known. */
|
||
node: null,
|
||
/** Bumped on every navigation so late responses for an old view are dropped. */
|
||
generation: 0
|
||
};
|
||
function nowSeconds() {
|
||
return Math.floor(Date.now() / 1e3);
|
||
}
|
||
function verifyOpts() {
|
||
return { now: nowSeconds(), minPowBits: state.node?.difficulty ?? 0 };
|
||
}
|
||
|
||
// src/threads.ts
|
||
var KEY = "allmende.conversations.v1";
|
||
var cache = /* @__PURE__ */ new Map();
|
||
var loaded = false;
|
||
var persistent = true;
|
||
var idOf = (author, id) => `${author}/${id}`;
|
||
var HEX = (n) => new RegExp(`^[0-9a-f]{${n}}$`);
|
||
function wellFormed(c) {
|
||
if (typeof c !== "object" || c === null) return false;
|
||
const x = c;
|
||
return typeof x.author === "string" && HEX(64).test(x.author) && typeof x.id === "string" && HEX(32).test(x.id) && typeof x.secret === "string" && HEX(64).test(x.secret) && typeof x.title === "string" && typeof x.created === "number" && typeof x.updated === "number" && Array.isArray(x.messages) && typeof x.since === "number" && typeof x.seen === "object" && x.seen !== null;
|
||
}
|
||
function load() {
|
||
if (loaded) return;
|
||
loaded = true;
|
||
try {
|
||
const raw = localStorage.getItem(KEY);
|
||
if (!raw) return;
|
||
const parsed = JSON.parse(raw);
|
||
if (typeof parsed !== "object" || parsed === null) return;
|
||
for (const c of Object.values(parsed)) {
|
||
if (wellFormed(c)) cache.set(idOf(c.author, c.id), c);
|
||
}
|
||
} catch {
|
||
persistent = false;
|
||
}
|
||
}
|
||
function flush() {
|
||
try {
|
||
localStorage.setItem(KEY, JSON.stringify(Object.fromEntries(cache)));
|
||
} catch {
|
||
persistent = false;
|
||
}
|
||
}
|
||
function isPersistent() {
|
||
load();
|
||
if (persistent) {
|
||
try {
|
||
localStorage.setItem(KEY + ".probe", "1");
|
||
localStorage.removeItem(KEY + ".probe");
|
||
} catch {
|
||
persistent = false;
|
||
}
|
||
}
|
||
return persistent;
|
||
}
|
||
function getConversation(author, id) {
|
||
load();
|
||
return cache.get(idOf(author, id));
|
||
}
|
||
function saveConversation(c) {
|
||
load();
|
||
cache.set(idOf(c.author, c.id), c);
|
||
flush();
|
||
}
|
||
function deleteConversation(author, id) {
|
||
load();
|
||
cache.delete(idOf(author, id));
|
||
flush();
|
||
}
|
||
function listConversations() {
|
||
load();
|
||
return [...cache.values()].sort((a, b) => b.updated - a.updated);
|
||
}
|
||
function conversationHash(author, id, secret) {
|
||
return `#/c/${author}/${id}/${secret}`;
|
||
}
|
||
|
||
// src/chat.ts
|
||
var OVERLAP = 3600;
|
||
var app = () => document.getElementById("app");
|
||
var fromHex = (s) => Uint8Array.from(s.match(/../g) ?? [], (b) => parseInt(b, 16));
|
||
var difficulty = () => state.node?.message_difficulty ?? DEFAULT_MESSAGE_DIFFICULTY;
|
||
var utf8 = (s) => new TextEncoder().encode(s).length;
|
||
function describe(e2) {
|
||
if (e2 instanceof InputError) return t(`problem.${e2.problem}`);
|
||
if (e2 instanceof HttpError) {
|
||
if (e2.status === 404) return t("send.404");
|
||
if (e2.status === 429) return t("send.429");
|
||
return t("send.other", { detail: e2.detail });
|
||
}
|
||
return t("send.network");
|
||
}
|
||
function composer(opts) {
|
||
const area = h("textarea", { name: "message", rows: 5, "aria-label": t("contact.label"), placeholder: t("compose.hint"), required: true });
|
||
sendOnCtrlEnter(area);
|
||
const counter = h("span", { class: "muted" });
|
||
const problem = h("p", { class: "error", role: "alert" });
|
||
const button = h("button", { type: "submit", class: "btn primary" }, t(opts.button));
|
||
const update = () => {
|
||
const max = opts.first() ? MAX_FIRST_TEXT : MAX_TEXT;
|
||
counter.textContent = t("contact.counter", { used: utf8(area.value), max });
|
||
};
|
||
area.addEventListener("input", update);
|
||
update();
|
||
const form = h(
|
||
"form",
|
||
{
|
||
class: "compose",
|
||
onsubmit: (ev) => {
|
||
ev.preventDefault();
|
||
void (async () => {
|
||
problem.textContent = "";
|
||
const text = area.value.trim();
|
||
const bad = checkBuyerText(text, opts.first());
|
||
if (bad) {
|
||
problem.textContent = t(`problem.${bad}`);
|
||
return;
|
||
}
|
||
button.disabled = true;
|
||
area.disabled = true;
|
||
button.textContent = t("contact.sending");
|
||
try {
|
||
await opts.send(text);
|
||
area.value = "";
|
||
update();
|
||
} catch (e2) {
|
||
problem.textContent = describe(e2);
|
||
} finally {
|
||
button.disabled = false;
|
||
area.disabled = false;
|
||
button.textContent = t(opts.button);
|
||
}
|
||
})();
|
||
}
|
||
},
|
||
area,
|
||
h("div", { class: "actions" }, button, counter),
|
||
problem
|
||
);
|
||
return form;
|
||
}
|
||
async function sendTo(c, listing, text, first) {
|
||
const n = c.messages.filter((m) => m.dir === "out").length + 1;
|
||
const now = nowSeconds();
|
||
const env = await buildToOwner({
|
||
listing,
|
||
threadSecret: fromHex(c.secret),
|
||
text,
|
||
n,
|
||
now,
|
||
difficulty: difficulty(),
|
||
first
|
||
});
|
||
await postMessage(env);
|
||
c.messages.push({ dir: "out", n, sent_at: now, t: "text", text });
|
||
c.updated = now;
|
||
saveConversation(c);
|
||
}
|
||
function contactPanel(l) {
|
||
const existing = getConversation(l.author, l.id);
|
||
if (existing) {
|
||
return h(
|
||
"section",
|
||
{ class: "panel contact" },
|
||
h("h2", null, t("contact.title")),
|
||
h("p", null, t("contact.already")),
|
||
h("a", { class: "btn", href: conversationHash(l.author, l.id, existing.secret) }, t("contact.open"))
|
||
);
|
||
}
|
||
const form = composer({
|
||
first: () => true,
|
||
button: "contact.send",
|
||
send: async (text) => {
|
||
const secret = toHex(crypto.getRandomValues(new Uint8Array(32)));
|
||
const c = {
|
||
author: l.author,
|
||
id: l.id,
|
||
secret,
|
||
title: l.title ?? "",
|
||
created: nowSeconds(),
|
||
updated: nowSeconds(),
|
||
messages: [],
|
||
since: nowSeconds() - OVERLAP,
|
||
seen: {}
|
||
};
|
||
await sendTo(c, l, text, true);
|
||
location.hash = conversationHash(l.author, l.id, secret);
|
||
}
|
||
});
|
||
return h(
|
||
"section",
|
||
{ class: "panel contact" },
|
||
h("h2", null, t("contact.title")),
|
||
h("p", null, t("contact.intro")),
|
||
h("p", { class: "muted" }, t("contact.rules")),
|
||
form
|
||
);
|
||
}
|
||
function grantCard(m) {
|
||
const row = (k, v) => v ? [h("dt", null, t(k)), h("dd", { class: "pre" }, v)] : [];
|
||
return h(
|
||
"div",
|
||
{ class: "grant" },
|
||
h("strong", null, t("grant.title")),
|
||
h(
|
||
"dl",
|
||
{ class: "kv" },
|
||
...row("grant.address", m.address),
|
||
...row("grant.phone", m.phone),
|
||
...row("grant.email", m.email),
|
||
...row("grant.note", m.note)
|
||
),
|
||
h("p", { class: "muted" }, t("grant.until", { date: date(m.valid_until ?? 0) }), " \xB7 ", t("grant.privacy"))
|
||
);
|
||
}
|
||
function bubble(m) {
|
||
const mine2 = m.dir === "out";
|
||
return h(
|
||
"li",
|
||
{ class: `msg ${mine2 ? "out" : "in"}` },
|
||
h("div", { class: "who" }, mine2 ? t("chat.you") : t("chat.owner"), " \xB7 ", new Date(m.sent_at * 1e3).toLocaleString()),
|
||
m.t === "grant" ? grantCard(m) : h("p", { class: "pre" }, m.text ?? ""),
|
||
!mine2 && h("div", { class: "muted small" }, "\u2713 ", t("chat.verified"))
|
||
);
|
||
}
|
||
function stored(p, hash) {
|
||
const m = { dir: "in", n: p.n, sent_at: p.sent_at, t: p.t, hash };
|
||
for (const k of ["text", "address", "phone", "email", "note", "valid_until"]) {
|
||
if (p[k] !== void 0) m[k] = p[k];
|
||
}
|
||
return m;
|
||
}
|
||
async function poll(c) {
|
||
const secret = fromHex(c.secret);
|
||
const envs = await pollMailbox(mailbox(threadPublic(secret)), c.since);
|
||
const now = nowSeconds();
|
||
let rejected = 0;
|
||
let newest = 0;
|
||
for (const raw of envs) {
|
||
let hash;
|
||
try {
|
||
hash = envelopeHash(raw);
|
||
} catch {
|
||
rejected++;
|
||
continue;
|
||
}
|
||
if (hash in c.seen) continue;
|
||
const r = openReply(raw, secret, { author: c.author, id: c.id });
|
||
const env = raw;
|
||
c.seen[hash] = typeof env.expires_at === "number" ? env.expires_at : now + 14 * 86400;
|
||
if (typeof env.created_at === "number") newest = Math.max(newest, env.created_at);
|
||
if (!r.ok) {
|
||
rejected++;
|
||
continue;
|
||
}
|
||
c.messages.push(stored(r.plain, hash));
|
||
c.updated = now;
|
||
}
|
||
for (const [k, exp] of Object.entries(c.seen)) if (exp < now - 86400) delete c.seen[k];
|
||
if (newest > 0) c.since = Math.max(c.since, Math.min(newest, now) - OVERLAP);
|
||
saveConversation(c);
|
||
return rejected;
|
||
}
|
||
async function showConversation(author, id, secret) {
|
||
const gen = state.generation;
|
||
const root = app();
|
||
clear(root);
|
||
let c = getConversation(author, id);
|
||
if (c && c.secret !== secret) c = void 0;
|
||
if (!c) {
|
||
c = {
|
||
author,
|
||
id,
|
||
secret,
|
||
title: "",
|
||
created: nowSeconds(),
|
||
updated: nowSeconds(),
|
||
messages: [],
|
||
since: nowSeconds() - 14 * 86400,
|
||
seen: {}
|
||
};
|
||
}
|
||
const conv = c;
|
||
const heading = h("h1", null, conv.title ? t("chat.title", { title: conv.title }) : t("chat.untitled", { id: id.slice(0, 8) }));
|
||
const list = h("ul", { class: "thread", "aria-live": "polite" });
|
||
const notes = h("div", null);
|
||
const composeSlot = h("div", null);
|
||
const link = location.origin + location.pathname + conversationHash(author, id, secret);
|
||
append(root, [
|
||
h("a", { class: "back", href: `#/l/${author}/${id}` }, t("chat.back")),
|
||
" ",
|
||
h("a", { class: "back", href: "#/messages" }, t("chat.all")),
|
||
heading,
|
||
!isPersistent() && h("p", { class: "error" }, t("chat.noStorage")),
|
||
notes,
|
||
list,
|
||
composeSlot,
|
||
h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h2", null, t("chat.link")),
|
||
h("p", { class: "muted" }, t("chat.linkHelp")),
|
||
h("input", { class: "mono", readonly: true, value: link, "aria-label": t("chat.link"), onfocus: (e2) => e2.target.select() })
|
||
),
|
||
deleteControl(conv)
|
||
]);
|
||
let listing = null;
|
||
let listingProblem = null;
|
||
const render = (rejected, pollFailed) => {
|
||
const now = nowSeconds();
|
||
clear(list);
|
||
clear(notes);
|
||
const shown = [...conv.messages].sort((a, b) => a.sent_at - b.sent_at || (a.dir === "out" ? -1 : 1)).filter((m) => !(m.t === "grant" && (m.valid_until ?? 0) <= now));
|
||
const expired = conv.messages.filter((m) => m.t === "grant" && (m.valid_until ?? 0) <= now).length;
|
||
for (const m of shown) list.append(bubble(m));
|
||
if (!conv.messages.some((m) => m.dir === "in")) list.append(h("li", { class: "muted" }, t("chat.empty")));
|
||
if (expired) notes.append(h("p", { class: "muted" }, t("grant.expired")));
|
||
if (rejected) notes.append(h("p", { class: "error" }, t("chat.rejected", { n: rejected })));
|
||
if (pollFailed) notes.append(h("p", { class: "error" }, t("chat.pollError")));
|
||
if (listingProblem) notes.append(h("p", { class: "muted" }, t(listingProblem)));
|
||
if (conv.messages.some((m) => m.dir === "in")) notes.append(h("p", { class: "muted small" }, t("chat.limit")));
|
||
};
|
||
const renderComposer = () => {
|
||
clear(composeSlot);
|
||
if (!listing) return;
|
||
const repliedTo = () => conv.messages.some((m) => m.dir === "in");
|
||
composeSlot.append(
|
||
h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h2", null, t("chat.reply")),
|
||
!repliedTo() && h("p", { class: "muted" }, t("chat.replyRules")),
|
||
composer({
|
||
first: () => !repliedTo(),
|
||
button: "contact.send",
|
||
send: async (text) => {
|
||
await sendTo(conv, listing, text, !repliedTo());
|
||
if (gen === state.generation) {
|
||
render(0, false);
|
||
renderComposer();
|
||
}
|
||
}
|
||
})
|
||
)
|
||
);
|
||
};
|
||
render(0, false);
|
||
void (async () => {
|
||
try {
|
||
const raw = await getListing(author, id);
|
||
if (gen !== state.generation) return;
|
||
if (raw === null) {
|
||
listingProblem = "chat.gone";
|
||
} else {
|
||
const l = raw;
|
||
const v = verifyListing(raw, verifyOpts());
|
||
if (v.ok && l.author === author && l.id === id) {
|
||
listing = l;
|
||
if (!conv.title && l.title) {
|
||
conv.title = l.title;
|
||
heading.textContent = t("chat.title", { title: l.title });
|
||
if (getConversation(author, id)) saveConversation(conv);
|
||
}
|
||
} else {
|
||
listingProblem = "chat.unverified";
|
||
}
|
||
}
|
||
} catch {
|
||
if (gen !== state.generation) return;
|
||
listingProblem = "chat.unverified";
|
||
}
|
||
render(0, false);
|
||
renderComposer();
|
||
})();
|
||
const cycle = async () => {
|
||
if (gen !== state.generation) return;
|
||
let rejected = 0;
|
||
let failed = false;
|
||
try {
|
||
rejected = await poll(conv);
|
||
} catch {
|
||
failed = true;
|
||
}
|
||
if (gen !== state.generation) return;
|
||
render(rejected, failed);
|
||
};
|
||
await cycle();
|
||
keepFresh(() => gen === state.generation, cycle);
|
||
}
|
||
function deleteControl(c) {
|
||
const slot = h("p", null);
|
||
const ask = () => {
|
||
clear(slot);
|
||
append(slot, [
|
||
t("chat.deleteSure"),
|
||
" ",
|
||
h("button", { type: "button", class: "btn", onclick: () => {
|
||
deleteConversation(c.author, c.id);
|
||
location.hash = "#/messages";
|
||
} }, t("chat.deleteYes"))
|
||
]);
|
||
};
|
||
slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("chat.delete")));
|
||
return slot;
|
||
}
|
||
function showInbox() {
|
||
const root = app();
|
||
clear(root);
|
||
const convs = listConversations();
|
||
append(root, [
|
||
h("a", { class: "back", href: "#/" }, t("detail.back")),
|
||
h("h1", null, t("inbox.title")),
|
||
!isPersistent() && h("p", { class: "error" }, t("chat.noStorage")),
|
||
convs.length === 0 ? h("p", { class: "muted" }, t("inbox.none")) : h(
|
||
"ul",
|
||
{ class: "convs" },
|
||
...convs.map(
|
||
(c) => h(
|
||
"li",
|
||
{ class: "panel" },
|
||
h("a", { href: conversationHash(c.author, c.id, c.secret) }, c.title || t("chat.untitled", { id: c.id.slice(0, 8) })),
|
||
h("div", { class: "muted small" }, t("inbox.last", { date: date(c.updated) }))
|
||
)
|
||
)
|
||
),
|
||
h("p", { class: "muted" }, t("inbox.note"))
|
||
]);
|
||
}
|
||
|
||
// src/draft.ts
|
||
var MAX_LIFETIME_DAYS = 30;
|
||
function draftFromListing(l, days = MAX_LIFETIME_DAYS) {
|
||
const period = l.price?.period === "once" ? "once" : "month";
|
||
const d = {
|
||
kind: l.kind ?? "",
|
||
category: l.category ?? "",
|
||
geohash: l.geohash,
|
||
price: { amount_cents: l.price?.amount_cents ?? 0, currency: "EUR", period },
|
||
area_m2: l.area_m2 ?? 0,
|
||
rooms_x2: l.rooms_x2 ?? 0,
|
||
features: l.features ?? [],
|
||
title: l.title ?? "",
|
||
description: l.description ?? "",
|
||
expires_in_days: days
|
||
};
|
||
if (l.delegate) d.delegate = l.delegate;
|
||
return d;
|
||
}
|
||
|
||
// src/ownerApi.ts
|
||
var TOKEN_KEY = "allmende.owner.token";
|
||
var memory = null;
|
||
function getToken() {
|
||
try {
|
||
return sessionStorage.getItem(TOKEN_KEY) ?? memory;
|
||
} catch {
|
||
return memory;
|
||
}
|
||
}
|
||
function setToken(token) {
|
||
memory = token;
|
||
try {
|
||
sessionStorage.setItem(TOKEN_KEY, token);
|
||
} catch {
|
||
}
|
||
}
|
||
function clearToken() {
|
||
memory = null;
|
||
try {
|
||
sessionStorage.removeItem(TOKEN_KEY);
|
||
} catch {
|
||
}
|
||
}
|
||
var Unauthorized = class extends Error {
|
||
constructor() {
|
||
super("unauthorized");
|
||
}
|
||
};
|
||
async function call(method, path, body) {
|
||
const token = getToken();
|
||
if (!token) throw new Unauthorized();
|
||
const res = await fetch(path, {
|
||
method,
|
||
headers: {
|
||
Authorization: `Bearer ${token}`,
|
||
Accept: "application/json",
|
||
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
||
},
|
||
body: body === void 0 ? void 0 : JSON.stringify(body)
|
||
});
|
||
if (res.status === 401) {
|
||
clearToken();
|
||
throw new Unauthorized();
|
||
}
|
||
if (res.status === 204) return null;
|
||
let data = null;
|
||
try {
|
||
data = await res.json();
|
||
} catch {
|
||
}
|
||
if (!res.ok) {
|
||
const detail = typeof data?.error === "string" ? data.error : res.statusText;
|
||
throw new HttpError(res.status, detail);
|
||
}
|
||
return data;
|
||
}
|
||
var e = encodeURIComponent;
|
||
async function getMine() {
|
||
return await call("GET", "/api/v1/mine");
|
||
}
|
||
async function getThreads(listing) {
|
||
return await call("GET", `/api/v1/inbox?listing=${e(listing)}`);
|
||
}
|
||
async function getMessages(listing, thread) {
|
||
return await call("GET", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
|
||
}
|
||
async function sendReply(listing, thread, r) {
|
||
await call("POST", `/api/v1/inbox/${e(listing)}/${e(thread)}`, r);
|
||
}
|
||
async function deleteThread(listing, thread) {
|
||
await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
|
||
}
|
||
async function getAddress(listing) {
|
||
try {
|
||
return await call("GET", `/api/v1/listings/${e(listing)}/address`);
|
||
} catch (err) {
|
||
if (err instanceof HttpError && err.status === 404) return null;
|
||
throw err;
|
||
}
|
||
}
|
||
async function putAddress(listing, a) {
|
||
await call("PUT", `/api/v1/listings/${e(listing)}/address`, a);
|
||
}
|
||
async function deleteAddress(listing) {
|
||
await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
|
||
}
|
||
async function setRegions(regions) {
|
||
return (await call("PUT", "/api/v1/regions", { regions })).regions;
|
||
}
|
||
async function createListing(d) {
|
||
return await call("POST", "/api/v1/listings", d);
|
||
}
|
||
async function updateListing(id, d) {
|
||
return await call("PUT", `/api/v1/listings/${e(id)}`, d);
|
||
}
|
||
async function deleteListing(id) {
|
||
await call("DELETE", `/api/v1/listings/${e(id)}`);
|
||
}
|
||
async function getOwnListing(author, id) {
|
||
return await getListing(author, id);
|
||
}
|
||
async function renewListing(author, id, days = MAX_LIFETIME_DAYS) {
|
||
const l = await getOwnListing(author, id);
|
||
if (!l || l.tombstone) throw new HttpError(404, "no such listing of yours");
|
||
return updateListing(id, draftFromListing(l, days));
|
||
}
|
||
|
||
// src/owner.ts
|
||
var VALID_DAYS = [1, 3, 7, 14, 30];
|
||
var DEFAULT_DAYS = 7;
|
||
var app2 = () => document.getElementById("app");
|
||
var shortId = (thread) => thread.slice(-4);
|
||
function explain(e2) {
|
||
return t("own.err", { detail: e2 instanceof HttpError ? e2.detail : e2 instanceof Error ? e2.message : "?" });
|
||
}
|
||
function renderLogin(rejected) {
|
||
const root = app2();
|
||
document.body.classList.remove("wide");
|
||
clear(root);
|
||
const input = h("input", { type: "password", name: "token", autocomplete: "off", spellcheck: "false", "aria-label": t("own.token"), required: true });
|
||
append(root, [
|
||
h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h1", null, t("own.loginTitle")),
|
||
h("p", { class: "muted" }, t("own.loginHelp")),
|
||
rejected && h("p", { class: "error", role: "alert" }, t("own.loginBad")),
|
||
h(
|
||
"form",
|
||
{
|
||
class: "stack",
|
||
onsubmit: (ev) => {
|
||
ev.preventDefault();
|
||
const v = input.value.trim();
|
||
if (!v) return;
|
||
setToken(v);
|
||
void showOwner();
|
||
}
|
||
},
|
||
h("label", null, t("own.token"), input),
|
||
h("div", { class: "actions" }, h("button", { type: "submit", class: "btn primary" }, t("own.login")))
|
||
)
|
||
)
|
||
]);
|
||
}
|
||
async function showOwner(listingId, thread) {
|
||
const gen = state.generation;
|
||
if (!getToken()) {
|
||
renderLogin(false);
|
||
return;
|
||
}
|
||
const root = app2();
|
||
document.body.classList.add("wide");
|
||
clear(root);
|
||
const depth = thread ? 3 : listingId ? 2 : 1;
|
||
let mine2 = [];
|
||
let threads = [];
|
||
let msgs = [];
|
||
let filter = "all";
|
||
let loaded3 = false;
|
||
const notice = h("p", { class: "error", role: "alert" });
|
||
const listingsBox = h("div", { class: "olist" });
|
||
const listingsPane = h(
|
||
"section",
|
||
{ class: "pane pane-listings" },
|
||
h("h2", { class: "pane-title" }, t("own.listings")),
|
||
h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))),
|
||
listingsBox,
|
||
h("p", null, h("a", { class: "btn", href: "#/mine/regions" }, t("reg.title"))),
|
||
h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout")))
|
||
);
|
||
const reqTitle = h("h2", { class: "pane-title" });
|
||
const chips = h("div", { class: "chips-row" });
|
||
const reqBox = h("div", { class: "olist" });
|
||
const addr = listingId ? addressCard(listingId, () => void refresh()) : null;
|
||
const bar = listingId ? listingBar(listingId, () => void refresh()) : null;
|
||
const requestsPane = h("section", { class: "pane pane-requests" });
|
||
append(
|
||
requestsPane,
|
||
listingId ? [
|
||
h("a", { class: "back narrow-only", href: "#/mine" }, t("own.backListings")),
|
||
reqTitle,
|
||
bar.root,
|
||
addr.root,
|
||
chips,
|
||
reqBox,
|
||
h("p", { class: "muted small" }, t("own.limitNote"))
|
||
] : [h("p", { class: "muted pick" }, t("own.pickListing"))]
|
||
);
|
||
const msgBox = h("div", { class: "thread", "aria-live": "polite" });
|
||
const threadHead = h("h2", { class: "pane-title" });
|
||
const firstNote = h("p", { class: "note warn" }, t("own.first"));
|
||
const addressHint = h("p", { class: "note hint", hidden: true }, t("own.hintAddress"));
|
||
const threadPane = h("section", { class: "pane pane-thread" });
|
||
if (listingId && thread) {
|
||
append(threadPane, [
|
||
h("a", { class: "back narrow-only", href: `#/mine/${listingId}` }, t("own.backRequests")),
|
||
threadHead,
|
||
h("p", { class: "muted small" }, t("own.anon")),
|
||
msgBox,
|
||
firstNote,
|
||
addressHint,
|
||
composer2(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())),
|
||
deleteControl2(listingId, thread)
|
||
]);
|
||
} else {
|
||
threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : ""));
|
||
}
|
||
append(root, [notice, h("div", { class: `owner depth-${depth}` }, listingsPane, requestsPane, threadPane)]);
|
||
const kindLabel = (k) => k === "rent" || k === "sale" ? t(`kind.${k}`) : k ?? "";
|
||
function renderListings() {
|
||
clear(listingsBox);
|
||
if (loaded3 && mine2.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none")));
|
||
for (const m of mine2) {
|
||
const sub = [kindLabel(m.kind), m.price ? price({ price: m.price }) : ""].filter(Boolean).join(" \xB7 ");
|
||
listingsBox.append(
|
||
h(
|
||
"a",
|
||
{ class: `ocard${m.id === listingId ? " selected" : ""}`, href: `#/mine/${m.id}`, "aria-current": m.id === listingId ? "page" : void 0 },
|
||
h("b", null, m.title || m.id.slice(0, 8)),
|
||
sub && h("span", { class: "muted small" }, sub),
|
||
h(
|
||
"span",
|
||
{ class: "badges" },
|
||
m.needs_reply > 0 ? h("span", { class: "badge warn" }, t("own.needReply", { n: m.needs_reply })) : m.threads === 0 ? h("span", { class: "badge muted" }, t("own.noRequests")) : h("span", { class: "badge ok" }, t("own.allAnswered")),
|
||
m.address_saved ? h("span", { class: "badge ok" }, t("own.addressSaved")) : h("span", { class: "badge warn" }, t("own.noAddress")),
|
||
lifetimeBadge(m.expires_at)
|
||
)
|
||
)
|
||
);
|
||
}
|
||
}
|
||
function status(th) {
|
||
const now = nowSeconds();
|
||
const out = [];
|
||
const allHidden = th.hidden > 0 && th.hidden === th.messages;
|
||
if (th.needs_reply) out.push(h("span", { class: "badge warn" }, t("own.stReply")));
|
||
if (th.hidden > 0) out.push(h("span", { class: "badge bad" }, t("own.stHidden")));
|
||
if (th.grant_until) {
|
||
out.push(
|
||
th.grant_until > now ? h("span", { class: "badge ok" }, t("own.stGrant", { date: date(th.grant_until) })) : h("span", { class: "badge muted" }, t("own.stGrantEnded"))
|
||
);
|
||
} else if (th.replied && !th.needs_reply) {
|
||
out.push(h("span", { class: "badge muted" }, t("own.stReplied")));
|
||
}
|
||
if (!out.length && !allHidden) out.push(h("span", { class: "badge muted" }, t("own.stReplied")));
|
||
return out;
|
||
}
|
||
function preview(th) {
|
||
if (th.preview) return th.preview;
|
||
if (th.last_dir === "in") return t("own.hiddenPreview");
|
||
return th.grant_until ? t("own.grantSent", { date: date(th.grant_until) }) : "";
|
||
}
|
||
function renderRequests() {
|
||
const m = mine2.find((x) => x.id === listingId);
|
||
reqTitle.textContent = m?.title ?? "";
|
||
bar?.update(m);
|
||
const counts = { all: threads.length, reply: threads.filter((x) => x.needs_reply).length, hidden: threads.filter((x) => x.hidden > 0).length };
|
||
clear(chips);
|
||
for (const [f, key] of [["all", "own.filterAll"], ["reply", "own.filterReply"], ["hidden", "own.filterHidden"]]) {
|
||
chips.append(
|
||
h("button", { type: "button", class: `chip${filter === f ? " on" : ""}`, "aria-pressed": filter === f ? "true" : "false", onclick: () => {
|
||
filter = f;
|
||
renderRequests();
|
||
} }, t(key, { n: counts[f] }))
|
||
);
|
||
}
|
||
const shown = threads.filter((x) => filter === "all" || (filter === "reply" ? x.needs_reply : x.hidden > 0));
|
||
clear(reqBox);
|
||
if (loaded3 && shown.length === 0) reqBox.append(h("p", { class: "muted" }, t("own.noMatch")));
|
||
for (const th of shown) {
|
||
reqBox.append(
|
||
h(
|
||
"a",
|
||
{ class: `ocard${th.thread === thread ? " selected" : ""}`, href: `#/mine/${th.listing}/${th.thread}`, "aria-current": th.thread === thread ? "page" : void 0 },
|
||
h("span", { class: "row" }, h("b", null, t("own.request", { id: shortId(th.thread) })), h("span", { class: "muted small" }, when(th.last_at))),
|
||
h("span", { class: th.preview ? "clip" : "clip muted" }, preview(th)),
|
||
h("span", { class: "badges" }, ...status(th), h("span", { class: "muted small" }, t("own.effort", { n: th.effort })))
|
||
)
|
||
);
|
||
}
|
||
}
|
||
function renderThread() {
|
||
if (!thread) return;
|
||
threadHead.textContent = t("own.request", { id: shortId(thread) });
|
||
clear(msgBox);
|
||
for (const m of msgs) msgBox.append(bubble2(m));
|
||
firstNote.hidden = msgs.some((m) => m.dir === "out");
|
||
addressHint.hidden = !asksForAddress(msgs);
|
||
}
|
||
function renderAll() {
|
||
renderListings();
|
||
if (listingId) renderRequests();
|
||
renderThread();
|
||
}
|
||
function logout() {
|
||
clearToken();
|
||
location.hash = "#/";
|
||
}
|
||
async function refresh() {
|
||
try {
|
||
mine2 = await getMine();
|
||
if (listingId) threads = await getThreads(listingId);
|
||
if (listingId && thread) {
|
||
try {
|
||
msgs = await getMessages(listingId, thread);
|
||
} catch (e2) {
|
||
if (e2 instanceof HttpError && e2.status === 404) {
|
||
if (gen === state.generation) location.hash = `#/mine/${listingId}`;
|
||
return;
|
||
}
|
||
throw e2;
|
||
}
|
||
}
|
||
} catch (e2) {
|
||
if (gen !== state.generation) return;
|
||
if (e2 instanceof Unauthorized) renderLogin(true);
|
||
else notice.textContent = t("own.loadError");
|
||
return;
|
||
}
|
||
if (gen !== state.generation) return;
|
||
notice.textContent = "";
|
||
loaded3 = true;
|
||
renderAll();
|
||
}
|
||
renderListings();
|
||
await refresh();
|
||
keepFresh(() => gen === state.generation && getToken() !== null, refresh);
|
||
}
|
||
var DAY2 = 86400;
|
||
var SOON_DAYS = 5;
|
||
var daysLeft = (expiresAt) => Math.ceil((expiresAt - nowSeconds()) / DAY2);
|
||
function lifetimeBadge(expiresAt) {
|
||
const n = daysLeft(expiresAt);
|
||
if (n <= 0) return h("span", { class: "badge bad" }, t("own.expired"));
|
||
return h("span", { class: `badge ${n < SOON_DAYS ? "warn" : "muted"}` }, n === 1 ? t("own.dayLeft") : t("own.daysLeft", { n }));
|
||
}
|
||
function listingBar(listingId, changed) {
|
||
const root = h("div", { class: "listing-bar" });
|
||
const problem = h("p", { class: "error", role: "alert" });
|
||
let current;
|
||
let renewing = false;
|
||
function render() {
|
||
clear(root);
|
||
if (!current) return;
|
||
const soon = daysLeft(current.expires_at) < SOON_DAYS;
|
||
const renew = h("button", { type: "button", class: `btn${soon ? " primary" : ""}`, onclick: () => void doRenew(renew) }, t("own.renew"));
|
||
const del = h("span", null);
|
||
const ask = () => {
|
||
clear(del);
|
||
append(del, [
|
||
t("own.deleteListingSure"),
|
||
" ",
|
||
h(
|
||
"button",
|
||
{
|
||
type: "button",
|
||
class: "btn",
|
||
onclick: () => void deleteListing(listingId).then(() => {
|
||
location.hash = "#/mine";
|
||
}).catch((e2) => {
|
||
problem.textContent = e2 instanceof Unauthorized ? t("own.loginBad") : explain(e2);
|
||
})
|
||
},
|
||
t("own.deleteYes")
|
||
)
|
||
]);
|
||
};
|
||
del.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.deleteListing")));
|
||
append(root, [
|
||
h("p", { class: "badges" }, lifetimeBadge(current.expires_at)),
|
||
soon && h("p", { class: "note warn" }, t("own.soon")),
|
||
h("div", { class: "actions" }, h("a", { class: "btn", href: `#/mine/${listingId}/edit` }, t("own.edit")), renew, del),
|
||
problem
|
||
]);
|
||
}
|
||
async function doRenew(button) {
|
||
if (renewing) return;
|
||
renewing = true;
|
||
problem.textContent = "";
|
||
button.disabled = true;
|
||
button.textContent = t("own.renewing");
|
||
try {
|
||
const author = state.node?.author;
|
||
if (!author) throw new Error("node unknown");
|
||
await renewListing(author, listingId);
|
||
changed();
|
||
} catch (e2) {
|
||
problem.textContent = e2 instanceof Unauthorized ? t("own.loginBad") : explain(e2);
|
||
button.disabled = false;
|
||
button.textContent = t("own.renew");
|
||
} finally {
|
||
renewing = false;
|
||
}
|
||
}
|
||
return {
|
||
root,
|
||
update(m) {
|
||
if (m?.expires_at === current?.expires_at && root.firstChild) return;
|
||
current = m;
|
||
render();
|
||
}
|
||
};
|
||
}
|
||
var ASKS_ADDRESS = /adress|address|anschrift|wo genau|wo liegt|wo befindet|which street|what street|where exactly|where is|where in/i;
|
||
function asksForAddress(msgs) {
|
||
const last = msgs[msgs.length - 1];
|
||
return !!last && last.dir === "in" && !last.hidden && last.type === "text" && ASKS_ADDRESS.test(last.text ?? "");
|
||
}
|
||
function bubble2(m) {
|
||
const mine2 = m.dir === "out";
|
||
const who = mine2 ? t("own.you") : t("own.buyer");
|
||
const head = h("div", { class: "who" }, who, " \xB7 ", when(m.sent_at));
|
||
if (m.hidden) {
|
||
return h("div", { class: "msg in" }, head, h("p", { class: "pre muted" }, t("own.hiddenMsg")));
|
||
}
|
||
if (m.type === "grant") {
|
||
const row = (label2, v) => v ? [h("dt", null, t(label2)), h("dd", { class: "pre" }, v)] : [];
|
||
return h(
|
||
"div",
|
||
{ class: "msg out" },
|
||
head,
|
||
h(
|
||
"div",
|
||
{ class: "grant" },
|
||
h("strong", null, t("own.grantSent", { date: date(m.valid_until ?? 0) })),
|
||
h("dl", { class: "kv" }, ...row("own.fAddress", m.address), ...row("own.fPhone", m.phone), ...row("own.fEmail", m.email), ...row("own.fNote", m.note))
|
||
)
|
||
);
|
||
}
|
||
return h("div", { class: `msg ${mine2 ? "out" : "in"}` }, head, h("p", { class: "pre" }, m.text ?? ""));
|
||
}
|
||
function composer2(listingId, thread, done, release) {
|
||
const area = h("textarea", { rows: 3, "aria-label": t("own.reply"), name: "reply", placeholder: t("compose.hint") });
|
||
sendOnCtrlEnter(area);
|
||
const problem = h("p", { class: "error", role: "alert" });
|
||
const send = h("button", { type: "submit", class: "btn primary" }, t("own.send"));
|
||
const rel = h("button", { type: "button", class: "btn", onclick: () => release(rel) }, t("own.release"));
|
||
return h(
|
||
"form",
|
||
{
|
||
class: "compose",
|
||
onsubmit: (ev) => {
|
||
ev.preventDefault();
|
||
const text = area.value.trim();
|
||
if (!text) return;
|
||
void (async () => {
|
||
problem.textContent = "";
|
||
send.disabled = true;
|
||
send.textContent = t("own.sending");
|
||
try {
|
||
await sendReply(listingId, thread, { type: "text", text });
|
||
area.value = "";
|
||
done();
|
||
} catch (e2) {
|
||
problem.textContent = e2 instanceof Unauthorized ? t("own.loginBad") : explain(e2);
|
||
} finally {
|
||
send.disabled = false;
|
||
send.textContent = t("own.send");
|
||
}
|
||
})();
|
||
}
|
||
},
|
||
area,
|
||
h("div", { class: "actions" }, send, rel),
|
||
problem
|
||
);
|
||
}
|
||
function deleteControl2(listingId, thread) {
|
||
const slot = h("p", null);
|
||
const ask = () => {
|
||
clear(slot);
|
||
append(slot, [
|
||
t("own.deleteSure"),
|
||
" ",
|
||
h("button", { type: "button", class: "btn", onclick: () => void deleteThread(listingId, thread).then(() => location.hash = `#/mine/${listingId}`) }, t("own.deleteYes"))
|
||
]);
|
||
};
|
||
slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.delete")));
|
||
return slot;
|
||
}
|
||
function addressCard(listingId, changed) {
|
||
const root = h("div", { class: "panel addr" });
|
||
let saved = null;
|
||
function show() {
|
||
clear(root);
|
||
append(root, [
|
||
h("strong", null, t("own.addrTitle")),
|
||
saved ? h("p", { class: "pre" }, [saved.address, saved.phone, saved.email].filter(Boolean).join("\n")) : h("p", { class: "muted" }, t("own.addrNone")),
|
||
h("p", { class: "muted small" }, t("own.addrHelp")),
|
||
h("button", { type: "button", class: "btn", onclick: edit }, saved ? t("own.addrChange") : t("own.addrAdd"))
|
||
]);
|
||
}
|
||
function edit() {
|
||
const a = h("input", { name: "address", value: saved?.address ?? "", maxlength: 300, required: true });
|
||
const p = h("input", { name: "phone", value: saved?.phone ?? "", maxlength: 40 });
|
||
const e2 = h("input", { name: "email", value: saved?.email ?? "", maxlength: 120 });
|
||
const problem = h("p", { class: "error", role: "alert" });
|
||
clear(root);
|
||
append(root, [
|
||
h(
|
||
"form",
|
||
{
|
||
class: "stack",
|
||
onsubmit: (ev) => {
|
||
ev.preventDefault();
|
||
void (async () => {
|
||
try {
|
||
const next = { address: a.value.trim(), phone: p.value.trim() || void 0, email: e2.value.trim() || void 0 };
|
||
if (!next.address) {
|
||
problem.textContent = t("own.needAddress");
|
||
return;
|
||
}
|
||
await putAddress(listingId, next);
|
||
saved = next;
|
||
show();
|
||
changed();
|
||
} catch (err) {
|
||
problem.textContent = explain(err);
|
||
}
|
||
})();
|
||
}
|
||
},
|
||
h("label", null, t("own.fAddress"), a),
|
||
h("label", null, t("own.fPhone"), p),
|
||
h("label", null, t("own.fEmail"), e2),
|
||
problem,
|
||
h(
|
||
"div",
|
||
{ class: "actions" },
|
||
h("button", { type: "submit", class: "btn primary" }, t("own.addrSave")),
|
||
h("button", { type: "button", class: "btn", onclick: show }, t("own.addrCancel")),
|
||
saved && h(
|
||
"button",
|
||
{
|
||
type: "button",
|
||
class: "btn",
|
||
onclick: () => void deleteAddress(listingId).then(() => {
|
||
saved = null;
|
||
show();
|
||
changed();
|
||
}).catch((err) => {
|
||
problem.textContent = explain(err);
|
||
})
|
||
},
|
||
t("own.addrRemove")
|
||
)
|
||
)
|
||
)
|
||
]);
|
||
a.focus();
|
||
}
|
||
void getAddress(listingId).then((a) => {
|
||
saved = a;
|
||
show();
|
||
}, () => show());
|
||
show();
|
||
return { root };
|
||
}
|
||
function openSheet(listingId, thread, opener, done) {
|
||
const host = app2();
|
||
const close = () => {
|
||
backdrop.remove();
|
||
opener.focus();
|
||
};
|
||
const address = h("input", { name: "address", maxlength: 300, required: true });
|
||
const phone = h("input", { name: "phone", maxlength: 40 });
|
||
const email = h("input", { name: "email", type: "email", maxlength: 120, autocomplete: "off" });
|
||
const note = h("textarea", { name: "note", rows: 2, maxlength: 1e3 });
|
||
const valid = h("select", { name: "valid" }, ...VALID_DAYS.map((d) => h("option", { value: String(d), selected: d === DEFAULT_DAYS }, d === 1 ? t("own.day") : t("own.days", { n: d }))));
|
||
const remember = h("input", { type: "checkbox", name: "remember" });
|
||
const rememberRow = h("label", { class: "check" }, remember, " ", t("own.remember"));
|
||
const problem = h("p", { class: "error", role: "alert" });
|
||
const send = h("button", { type: "submit", class: "btn primary" }, t("own.sendAddress"));
|
||
let saved = null;
|
||
const form = h(
|
||
"form",
|
||
{
|
||
class: "stack",
|
||
onsubmit: (ev) => {
|
||
ev.preventDefault();
|
||
void (async () => {
|
||
problem.textContent = "";
|
||
const a = address.value.trim();
|
||
if (!a) {
|
||
problem.textContent = t("own.needAddress");
|
||
return;
|
||
}
|
||
send.disabled = true;
|
||
send.textContent = t("own.sending");
|
||
try {
|
||
if (remember.checked && (!saved || saved.address !== a)) {
|
||
await putAddress(listingId, { address: a, phone: phone.value.trim() || void 0, email: email.value.trim() || void 0 });
|
||
}
|
||
await sendReply(listingId, thread, {
|
||
type: "grant",
|
||
address: a,
|
||
phone: phone.value.trim() || void 0,
|
||
email: email.value.trim() || void 0,
|
||
note: note.value.trim() || void 0,
|
||
valid_days: Number(valid.value)
|
||
});
|
||
close();
|
||
done();
|
||
} catch (e2) {
|
||
problem.textContent = explain(e2);
|
||
send.disabled = false;
|
||
send.textContent = t("own.sendAddress");
|
||
}
|
||
})();
|
||
}
|
||
},
|
||
h("label", null, t("own.fAddress"), address),
|
||
h("label", null, t("own.fPhone"), phone),
|
||
h("label", null, t("own.fEmail"), email),
|
||
h("label", null, t("own.fNote"), note),
|
||
h("label", null, t("own.fValid"), valid),
|
||
rememberRow,
|
||
problem,
|
||
h("div", { class: "actions" }, send)
|
||
);
|
||
const closeBtn = h("button", { type: "button", class: "btn close", "aria-label": t("own.close"), onclick: close }, "\xD7");
|
||
const backdrop = h(
|
||
"div",
|
||
{
|
||
class: "backdrop",
|
||
onclick: (ev) => {
|
||
if (ev.target === backdrop) close();
|
||
},
|
||
onkeydown: (ev) => {
|
||
if (ev.key === "Escape") close();
|
||
}
|
||
},
|
||
h("div", { class: "sheet", role: "dialog", "aria-modal": "true", "aria-label": t("own.sheetTitle") }, h("div", { class: "row" }, h("h2", null, t("own.sheetTitle")), closeBtn), h("p", { class: "muted small" }, t("own.sheetHelp")), form)
|
||
);
|
||
host.append(backdrop);
|
||
address.focus();
|
||
void getAddress(listingId).then(
|
||
(a) => {
|
||
saved = a;
|
||
if (a) {
|
||
if (!address.value) address.value = a.address;
|
||
if (!phone.value && a.phone) phone.value = a.phone;
|
||
if (!email.value && a.email) email.value = a.email;
|
||
} else {
|
||
remember.checked = true;
|
||
}
|
||
},
|
||
() => {
|
||
remember.checked = true;
|
||
}
|
||
);
|
||
}
|
||
|
||
// src/parse.ts
|
||
function parseEuros(input) {
|
||
const s = input.replace(/[€\s ]|eur/gi, "");
|
||
if (!/^\d[\d.,]*$/.test(s)) return null;
|
||
const lastDot = s.lastIndexOf(".");
|
||
const lastComma = s.lastIndexOf(",");
|
||
let whole;
|
||
let frac = "";
|
||
if (lastDot >= 0 && lastComma >= 0) {
|
||
const at = Math.max(lastDot, lastComma);
|
||
whole = s.slice(0, at);
|
||
frac = s.slice(at + 1);
|
||
} else if (lastDot >= 0 || lastComma >= 0) {
|
||
const sep = lastDot >= 0 ? "." : ",";
|
||
const parts = s.split(sep);
|
||
const last = parts[parts.length - 1];
|
||
if (parts.length > 2 || last.length === 3) {
|
||
whole = parts.join("");
|
||
} else {
|
||
whole = parts.slice(0, -1).join("");
|
||
frac = last;
|
||
}
|
||
} else {
|
||
whole = s;
|
||
}
|
||
whole = whole.replace(/[.,]/g, "");
|
||
if (!/^\d+$/.test(whole) || frac !== "" && !/^\d{1,2}$/.test(frac)) return null;
|
||
const cents = Number(whole) * 100 + Number(frac.padEnd(2, "0") || "0");
|
||
return Number.isSafeInteger(cents) && cents > 0 ? cents : null;
|
||
}
|
||
function parseRoomsX2(input) {
|
||
const s = input.trim().replace(",", ".");
|
||
if (s === "") return null;
|
||
const n = Number(s);
|
||
if (!Number.isFinite(n) || n < 0 || n > 100 || !Number.isInteger(n * 2)) return null;
|
||
return n * 2;
|
||
}
|
||
|
||
// src/publish.ts
|
||
var app3 = () => document.getElementById("app");
|
||
var DURATIONS = [7, 14, 21, MAX_LIFETIME_DAYS];
|
||
var KINDS = ["rent", "sale"];
|
||
var CATEGORIES = ["apartment", "house", "room", "commercial"];
|
||
var MAX_TITLE = 120;
|
||
var MAX_DESCRIPTION = 4e3;
|
||
var MAX_FEATURES = 20;
|
||
var MAX_FEATURE = 40;
|
||
var MAX_AREA = 1e5;
|
||
var MAX_ADDRESS_BYTES = 300;
|
||
var chars = (s) => [...s].length;
|
||
var bytes = (s) => new TextEncoder().encode(s).length;
|
||
var hasControl = (s, newlines) => newlines ? /[\p{Cc}]/u.test(s.replace(/\n/g, "")) : /\p{Cc}/u.test(s);
|
||
function explain2(e2) {
|
||
return t("own.err", { detail: e2 instanceof HttpError ? e2.detail : e2 instanceof Error ? e2.message : "?" });
|
||
}
|
||
function field(label2, control, help) {
|
||
const err = h("p", { class: "error", role: "alert" });
|
||
const root = h("div", { class: "field" }, h("label", null, label2, control), help && h("p", { class: "muted small" }, help), err);
|
||
return {
|
||
root,
|
||
control,
|
||
error(msg) {
|
||
err.textContent = msg ?? "";
|
||
if (msg) control.setAttribute("aria-invalid", "true");
|
||
else control.removeAttribute("aria-invalid");
|
||
}
|
||
};
|
||
}
|
||
var euros = (cents) => (cents / 100).toLocaleString(lang, { minimumFractionDigits: cents % 100 ? 2 : 0, maximumFractionDigits: 2, useGrouping: false });
|
||
async function showPublish(editId) {
|
||
const gen = state.generation;
|
||
if (!getToken()) {
|
||
renderLogin(false);
|
||
return;
|
||
}
|
||
const root = app3();
|
||
document.body.classList.remove("wide");
|
||
clear(root);
|
||
let old = null;
|
||
if (editId) {
|
||
root.append(h("p", { class: "muted" }, t("results.loading")));
|
||
try {
|
||
const author = state.node?.author;
|
||
if (!author) throw new Error("node unknown");
|
||
old = await getOwnListing(author, editId);
|
||
} catch (e2) {
|
||
if (gen !== state.generation) return;
|
||
clear(root);
|
||
root.append(h("p", { class: "error" }, t("own.loadError")));
|
||
return;
|
||
}
|
||
if (gen !== state.generation) return;
|
||
clear(root);
|
||
if (!old || old.tombstone) {
|
||
root.append(h("a", { class: "back", href: "#/mine" }, t("pub.back")), h("p", { class: "muted" }, t("pub.notFound")));
|
||
return;
|
||
}
|
||
}
|
||
const radios = KINDS.map((k) => h("input", { type: "radio", name: "kind", value: k, checked: (old?.kind ?? "rent") === k }));
|
||
const kindField = h(
|
||
"fieldset",
|
||
{ class: "field" },
|
||
h("legend", null, t("filter.kind")),
|
||
h("div", { class: "radios" }, ...radios.map((r) => h("label", { class: "check" }, r, " ", t(`kind.${r.value}`))))
|
||
);
|
||
const kind = () => radios.find((r) => r.checked)?.value ?? "rent";
|
||
const category = field(
|
||
t("filter.category"),
|
||
h("select", { name: "category" }, ...CATEGORIES.map((c) => h("option", { value: c, selected: (old?.category ?? "apartment") === c }, t(`cat.${c}`))))
|
||
);
|
||
const title = field(t("pub.title"), h("input", { name: "title", maxlength: MAX_TITLE * 2, value: old?.title ?? "", autocomplete: "off" }));
|
||
const description = field(t("pub.description"), h("textarea", { name: "description", rows: 7 }, old?.description ?? ""));
|
||
const priceLabel = h("span", null, t("pub.priceRent"));
|
||
const priceInput = h("input", { name: "price", inputmode: "decimal", value: old?.price ? euros(old.price.amount_cents) : "", autocomplete: "off" });
|
||
const price2 = field("", priceInput);
|
||
price2.root.querySelector("label").prepend(priceLabel);
|
||
const area = field(t("pub.area"), h("input", { name: "area", inputmode: "numeric", value: old?.area_m2 ? String(old.area_m2) : "" }));
|
||
const rooms2 = field(t("pub.rooms"), h("input", { name: "rooms", inputmode: "decimal", value: old?.rooms_x2 ? (old.rooms_x2 / 2).toLocaleString(lang) : "" }));
|
||
const features = field(t("pub.features"), h("input", { name: "features", value: (old?.features ?? []).join(", "), autocomplete: "off" }));
|
||
const syncKind = () => {
|
||
priceLabel.textContent = t(kind() === "rent" ? "pub.priceRent" : "pub.priceSale");
|
||
};
|
||
for (const r of radios) r.addEventListener("change", syncKind);
|
||
const here = old ? decodeGeohash(old.geohash) : null;
|
||
const locInput = h("input", {
|
||
name: "location",
|
||
inputmode: "decimal",
|
||
autocomplete: "off",
|
||
spellcheck: "false",
|
||
placeholder: "53.5511, 9.9937",
|
||
value: here ? `${here.lat.toFixed(5)}, ${here.lon.toFixed(5)}` : ""
|
||
});
|
||
const location_ = field(t("pub.location"), locInput, t("pub.locationHelp"));
|
||
const locPreview = h("p", { class: "muted small", "aria-live": "polite" });
|
||
const showLocation = () => {
|
||
clear(locPreview);
|
||
const pos = parseCoordinates(locInput.value);
|
||
if (!pos) return;
|
||
const g = encodeGeohash(pos.lat, pos.lon);
|
||
const c = cellMetres(g);
|
||
const a = decodeGeohash(g);
|
||
append(locPreview, [
|
||
t("pub.locationShown", { w: c?.width ?? 0, h: c?.height ?? 0, lat: a.lat.toFixed(3), lon: a.lon.toFixed(3), hash: g }),
|
||
" ",
|
||
h(
|
||
"a",
|
||
{
|
||
href: `https://www.openstreetmap.org/?mlat=${a.lat.toFixed(5)}&mlon=${a.lon.toFixed(5)}#map=15/${a.lat.toFixed(5)}/${a.lon.toFixed(5)}`,
|
||
target: "_blank",
|
||
rel: "noopener noreferrer"
|
||
},
|
||
t("detail.map")
|
||
)
|
||
]);
|
||
};
|
||
locInput.addEventListener("input", showLocation);
|
||
showLocation();
|
||
const locate = typeof navigator !== "undefined" && navigator.geolocation && window.isSecureContext ? h(
|
||
"button",
|
||
{
|
||
type: "button",
|
||
class: "btn",
|
||
onclick: () => navigator.geolocation.getCurrentPosition((p) => {
|
||
locInput.value = `${p.coords.latitude.toFixed(5)}, ${p.coords.longitude.toFixed(5)}`;
|
||
showLocation();
|
||
})
|
||
},
|
||
t("pub.useLocation")
|
||
) : null;
|
||
const duration = field(
|
||
t("pub.duration"),
|
||
h("select", { name: "days" }, ...DURATIONS.map((d) => h("option", { value: String(d), selected: d === MAX_LIFETIME_DAYS }, t("own.days", { n: d }))))
|
||
);
|
||
const addr = field(t("own.fAddress"), h("input", { name: "address", autocomplete: "off" }));
|
||
const phone = field(t("own.fPhone"), h("input", { name: "phone", maxlength: 40, autocomplete: "off" }));
|
||
const email = field(t("own.fEmail"), h("input", { name: "email", type: "email", maxlength: 120, autocomplete: "off" }));
|
||
const formError = h("p", { class: "error", role: "alert" });
|
||
const submit = h("button", { type: "submit", class: "btn primary" }, t(editId ? "pub.save" : "pub.publish"));
|
||
let busy = false;
|
||
function read() {
|
||
const fields = [title, description, price2, area, rooms2, features, location_, addr];
|
||
for (const f of fields) f.error(null);
|
||
const bad = [];
|
||
const val = (el) => el.value;
|
||
const titleText = val(title.control).trim();
|
||
if (!titleText || chars(titleText) > MAX_TITLE || hasControl(titleText, false)) bad.push([title, t("pub.eTitle")]);
|
||
const desc = val(description.control).replace(/\r\n?/g, "\n").trim();
|
||
if (chars(desc) > MAX_DESCRIPTION || hasControl(desc, true)) bad.push([description, t("pub.eDescription")]);
|
||
const cents = parseEuros(val(price2.control));
|
||
if (cents === null) bad.push([price2, t("pub.ePrice")]);
|
||
const areaText = val(area.control).trim();
|
||
const areaM2 = areaText === "" ? 0 : /^\d+$/.test(areaText) ? Number(areaText) : -1;
|
||
if (areaM2 < 0 || areaM2 > MAX_AREA) bad.push([area, t("pub.eArea")]);
|
||
const roomsText = val(rooms2.control).trim();
|
||
const roomsX2 = roomsText === "" ? 0 : parseRoomsX2(roomsText);
|
||
if (roomsX2 === null) bad.push([rooms2, t("pub.eRooms")]);
|
||
const list = [...new Set(val(features.control).split(/[,\n]/).map((s) => s.trim()).filter(Boolean))];
|
||
if (list.length > MAX_FEATURES || list.some((f) => chars(f) > MAX_FEATURE || hasControl(f, false))) bad.push([features, t("pub.eFeatures")]);
|
||
let geohash = "";
|
||
const pos = parseCoordinates(val(location_.control));
|
||
if (!pos) {
|
||
bad.push([location_, t("pub.eLocation")]);
|
||
} else {
|
||
geohash = encodeGeohash(pos.lat, pos.lon);
|
||
const region = geohash.slice(0, 3);
|
||
const followed = state.node?.regions;
|
||
if (old && old.geohash.slice(0, 3) !== region) bad.push([location_, t("pub.eRegionEdit")]);
|
||
else if (followed && followed.length > 0 && !followed.includes(region)) {
|
||
bad.push([location_, t("pub.eRegion", { region, regions: followed.join(", ") })]);
|
||
}
|
||
}
|
||
const address = val(addr.control).trim();
|
||
if (!editId && address && (bytes(address) > MAX_ADDRESS_BYTES || hasControl(address, true))) bad.push([addr, t("pub.eAddress")]);
|
||
if (bad.length > 0 || cents === null || roomsX2 === null) {
|
||
for (const [f, msg] of bad) f.error(msg);
|
||
bad[0]?.[0].control.focus();
|
||
return null;
|
||
}
|
||
const k = kind();
|
||
const draft = {
|
||
kind: k,
|
||
category: val(category.control),
|
||
geohash,
|
||
price: { amount_cents: cents, currency: "EUR", period: k === "rent" ? "month" : "once" },
|
||
area_m2: areaM2,
|
||
rooms_x2: roomsX2,
|
||
features: list,
|
||
title: titleText,
|
||
description: desc,
|
||
expires_in_days: Number(val(duration.control))
|
||
};
|
||
if (old?.delegate) draft.delegate = old.delegate;
|
||
const out = { draft };
|
||
if (!editId && address) {
|
||
out.address = { address, phone: val(phone.control).trim() || void 0, email: val(email.control).trim() || void 0 };
|
||
}
|
||
return out;
|
||
}
|
||
const form = h(
|
||
"form",
|
||
{
|
||
class: "form",
|
||
novalidate: true,
|
||
onsubmit: (ev) => {
|
||
ev.preventDefault();
|
||
if (busy) return;
|
||
const r = read();
|
||
if (!r) return;
|
||
void (async () => {
|
||
busy = true;
|
||
formError.textContent = "";
|
||
submit.disabled = true;
|
||
submit.textContent = t("pub.working");
|
||
try {
|
||
const l = editId ? await updateListing(editId, r.draft) : await createListing(r.draft);
|
||
if (r.address) {
|
||
await putAddress(l.id, r.address).catch(() => void 0);
|
||
}
|
||
if (gen === state.generation) location.hash = `#/mine/${l.id}`;
|
||
} catch (e2) {
|
||
if (e2 instanceof Unauthorized) renderLogin(true);
|
||
else formError.textContent = explain2(e2);
|
||
submit.disabled = false;
|
||
submit.textContent = t(editId ? "pub.save" : "pub.publish");
|
||
} finally {
|
||
busy = false;
|
||
}
|
||
})();
|
||
}
|
||
},
|
||
kindField,
|
||
category.root,
|
||
title.root,
|
||
description.root,
|
||
h("div", { class: "grid3" }, price2.root, area.root, rooms2.root),
|
||
features.root,
|
||
location_.root,
|
||
h("div", { class: "actions" }, locate),
|
||
locPreview,
|
||
duration.root,
|
||
!editId && h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h2", null, t("pub.addrTitle")),
|
||
h("p", { class: "muted small" }, t("pub.addrHelp")),
|
||
addr.root,
|
||
h("div", { class: "grid2" }, phone.root, email.root)
|
||
),
|
||
formError,
|
||
h("div", { class: "actions" }, submit, h("a", { class: "btn", href: editId ? `#/mine/${editId}` : "#/mine" }, t("own.addrCancel")))
|
||
);
|
||
append(root, [
|
||
h("a", { class: "back", href: editId ? `#/mine/${editId}` : "#/mine" }, t("pub.back")),
|
||
h("h1", null, t(editId ? "pub.editTitle" : "pub.createTitle")),
|
||
h("p", { class: "muted" }, t("pub.intro")),
|
||
form
|
||
]);
|
||
syncKind();
|
||
}
|
||
|
||
// src/places.ts
|
||
function fold(s) {
|
||
return s.normalize("NFD").replace(/\p{M}/gu, "").replace(/ß/g, "ss").toLowerCase();
|
||
}
|
||
function unTranslit(s) {
|
||
return s.replace(/ae/g, "a").replace(/oe/g, "o").replace(/ue/g, "u");
|
||
}
|
||
function parsePlaces(tsv) {
|
||
const out = [];
|
||
for (const line of tsv.split("\n")) {
|
||
if (!line) continue;
|
||
const [name, ascii, lat, lon, cc, pop, alt] = line.split(" ");
|
||
if (!name || lat === void 0 || lon === void 0) continue;
|
||
const alts = alt ? alt.split("|") : [];
|
||
const keys = [name, ...alts].map(fold);
|
||
if (ascii) keys.push(fold(ascii));
|
||
out.push({ name, lat: Number(lat), lon: Number(lon), cc: cc ?? "", population: Number(pop) || 0, alts, keys });
|
||
}
|
||
return out;
|
||
}
|
||
function score(key, q) {
|
||
if (key === q) return 0;
|
||
if (key.startsWith(q)) return 1;
|
||
if (key.split(/[\s-]+/).some((w) => w.startsWith(q))) return 2;
|
||
return q.length >= 3 && key.includes(q) ? 3 : 4;
|
||
}
|
||
function searchPlaces(places, query, limit = 8) {
|
||
const q1 = fold(query.trim());
|
||
if (q1.length < 2) return [];
|
||
const qs = [.../* @__PURE__ */ new Set([q1, unTranslit(q1)])];
|
||
const hits = [];
|
||
for (const p of places) {
|
||
let best = 4;
|
||
let bestKey = 0;
|
||
for (let i = 0; i < p.keys.length; i++) {
|
||
for (const q of qs) {
|
||
const s = score(p.keys[i], q);
|
||
if (s < best) [best, bestKey] = [s, i];
|
||
}
|
||
}
|
||
if (best < 4) {
|
||
const matched = bestKey >= 1 && bestKey <= p.alts.length ? p.alts[bestKey - 1] : null;
|
||
hits.push({ m: { place: p, matched }, s: best });
|
||
}
|
||
}
|
||
hits.sort((a, b) => a.s - b.s || b.m.place.population - a.m.place.population);
|
||
return hits.slice(0, limit).map((h2) => h2.m);
|
||
}
|
||
var KM_PER_DEGREE = 111.2;
|
||
function cellsNear(lat, lon, km = 40) {
|
||
const cell = (la, lo) => encodeGeohash(Math.max(-89.999, Math.min(89.999, la)), ((lo + 180) % 360 + 360) % 360 - 180, 3);
|
||
const out = [cell(lat, lon)];
|
||
const dLat = 1 / KM_PER_DEGREE;
|
||
const dLon = 1 / (KM_PER_DEGREE * Math.max(0.05, Math.cos(lat * Math.PI / 180)));
|
||
for (const r of [km / 2, km]) {
|
||
for (let i = 0; i < 16; i++) {
|
||
const a = i / 16 * 2 * Math.PI;
|
||
const c = cell(lat + Math.sin(a) * r * dLat, lon + Math.cos(a) * r * dLon);
|
||
if (!out.includes(c)) out.push(c);
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
function biggestPlaceByCell(places) {
|
||
const by = /* @__PURE__ */ new Map();
|
||
for (const p of places) {
|
||
const c = encodeGeohash(p.lat, p.lon, 3);
|
||
const cur = by.get(c);
|
||
if (!cur || p.population > cur.population) by.set(c, p);
|
||
}
|
||
return by;
|
||
}
|
||
var loaded2 = null;
|
||
function loadPlaces() {
|
||
loaded2 ??= fetch("places.tsv").then((r) => {
|
||
if (!r.ok) throw new Error(`${r.status}`);
|
||
return r.text();
|
||
}).then(parsePlaces).catch((e2) => {
|
||
loaded2 = null;
|
||
throw e2;
|
||
});
|
||
return loaded2;
|
||
}
|
||
|
||
// src/regions.ts
|
||
var CODE = /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/;
|
||
var MAX_REGIONS = 20;
|
||
function countryName(cc) {
|
||
try {
|
||
return new Intl.DisplayNames([lang], { type: "region" }).of(cc) ?? cc;
|
||
} catch {
|
||
return cc;
|
||
}
|
||
}
|
||
function errText(e2) {
|
||
if (e2 instanceof Unauthorized) return t("reg.signedOut");
|
||
if (e2 && typeof e2 === "object" && "message" in e2) return String(e2.message);
|
||
return typeof e2 === "string" ? e2 : t("reg.failed");
|
||
}
|
||
function regionPicker(opts) {
|
||
const chosen = [...opts.initial];
|
||
let places = [];
|
||
let biggest = /* @__PURE__ */ new Map();
|
||
const label2 = (code) => {
|
||
const p = biggest.get(code);
|
||
return p ? `${code} \xB7 ${p.name}` : code;
|
||
};
|
||
const chips = h("ul", { class: "rp-chips", "aria-label": t("reg.chosen") });
|
||
const drawChips = () => {
|
||
clear(chips);
|
||
if (chosen.length === 0) append(chips, [h("li", { class: "muted" }, t("reg.nothing"))]);
|
||
for (const code of chosen) {
|
||
append(chips, [
|
||
h(
|
||
"li",
|
||
{ class: "rp-chip" },
|
||
h("span", null, label2(code)),
|
||
h(
|
||
"button",
|
||
{
|
||
type: "button",
|
||
class: "rp-chip-x",
|
||
"aria-label": t("reg.remove", { region: label2(code) }),
|
||
onclick: () => {
|
||
chosen.splice(chosen.indexOf(code), 1);
|
||
drawChips();
|
||
}
|
||
},
|
||
"\xD7"
|
||
)
|
||
)
|
||
]);
|
||
}
|
||
};
|
||
const results = h("ul", { class: "rp-results", role: "listbox", "aria-label": t("reg.results") });
|
||
const cellsBox = h("div", { class: "rp-cells" });
|
||
const hint = h("p", { class: "muted small", "aria-live": "polite" });
|
||
const showCells = (place) => {
|
||
clear(cellsBox);
|
||
clear(results);
|
||
const cells = cellsNear(place.lat, place.lon);
|
||
const boxes = cells.map((code, i) => {
|
||
const box = h("input", { type: "checkbox", name: `cell-${code}`, checked: true, "aria-label": code });
|
||
return { code, box, row: h("label", { class: "rp-cell" }, box, h("span", null, `${label2(code)}${i === 0 ? ` (${t("reg.here")})` : ""}`)) };
|
||
});
|
||
append(cellsBox, [
|
||
h("h2", null, t("reg.cellsTitle", { place: place.name })),
|
||
h("p", { class: "muted small" }, t("reg.cellsHelp")),
|
||
...boxes.map((b) => b.row),
|
||
h(
|
||
"div",
|
||
{ class: "actions" },
|
||
h(
|
||
"button",
|
||
{
|
||
type: "button",
|
||
class: "btn",
|
||
onclick: () => {
|
||
for (const b of boxes) if (b.box.checked && !chosen.includes(b.code)) chosen.push(b.code);
|
||
clear(cellsBox);
|
||
search2.value = "";
|
||
drawChips();
|
||
}
|
||
},
|
||
t("reg.add")
|
||
)
|
||
)
|
||
]);
|
||
};
|
||
const showMatches = (matches) => {
|
||
clear(results);
|
||
for (const m of matches) {
|
||
const p = m.place;
|
||
append(results, [
|
||
h(
|
||
"li",
|
||
{ role: "option" },
|
||
h(
|
||
"button",
|
||
{ type: "button", class: "rp-result", onclick: () => showCells(p) },
|
||
h("strong", null, p.name),
|
||
m.matched ? ` (${m.matched})` : "",
|
||
h("span", { class: "muted" }, ` \xB7 ${countryName(p.cc)}`)
|
||
)
|
||
)
|
||
]);
|
||
}
|
||
};
|
||
const search2 = h("input", {
|
||
type: "search",
|
||
name: "place",
|
||
autocomplete: "off",
|
||
spellcheck: "false",
|
||
placeholder: t("reg.placeholder"),
|
||
"aria-label": t("reg.search"),
|
||
disabled: true
|
||
// until the list of places has loaded: an early search would find nothing
|
||
});
|
||
search2.addEventListener("input", () => {
|
||
clear(cellsBox);
|
||
const q = search2.value;
|
||
if (q.trim().length < 2) {
|
||
clear(results);
|
||
hint.textContent = "";
|
||
return;
|
||
}
|
||
const found = searchPlaces(places, q);
|
||
showMatches(found);
|
||
hint.textContent = found.length === 0 ? t("reg.none") : "";
|
||
});
|
||
void loadPlaces().then(
|
||
(p) => {
|
||
places = p;
|
||
biggest = biggestPlaceByCell(p);
|
||
search2.disabled = false;
|
||
drawChips();
|
||
},
|
||
() => {
|
||
hint.textContent = t("reg.noPlaces");
|
||
}
|
||
);
|
||
const codes = h("input", { type: "text", name: "regions", placeholder: "u1j", autocomplete: "off", spellcheck: "false", "aria-label": t("reg.codes") });
|
||
const problem = h("p", { class: "error", role: "alert" });
|
||
const go = h("button", { type: "submit", class: "btn primary" }, opts.submitLabel);
|
||
const form = h(
|
||
"form",
|
||
{
|
||
class: "stack regions",
|
||
onsubmit: (ev) => {
|
||
ev.preventDefault();
|
||
problem.textContent = "";
|
||
for (const raw of codes.value.split(/[\s,;]+/).filter(Boolean)) {
|
||
const code = raw.toLowerCase();
|
||
if (!CODE.test(code)) {
|
||
problem.textContent = t("reg.badCode", { code: raw });
|
||
return;
|
||
}
|
||
if (!chosen.includes(code)) chosen.push(code);
|
||
}
|
||
codes.value = "";
|
||
drawChips();
|
||
if (chosen.length === 0) {
|
||
problem.textContent = t("reg.needOne");
|
||
return;
|
||
}
|
||
if (chosen.length > MAX_REGIONS) {
|
||
problem.textContent = t("reg.tooMany", { max: MAX_REGIONS });
|
||
return;
|
||
}
|
||
go.disabled = true;
|
||
const label3 = go.textContent;
|
||
go.textContent = t("reg.saving");
|
||
opts.onSubmit([...chosen]).catch((e2) => {
|
||
problem.textContent = errText(e2);
|
||
go.disabled = false;
|
||
go.textContent = label3;
|
||
});
|
||
}
|
||
},
|
||
h("label", null, t("reg.search"), search2),
|
||
hint,
|
||
results,
|
||
cellsBox,
|
||
h("h2", null, t("reg.chosen")),
|
||
chips,
|
||
h("label", null, t("reg.codes"), codes),
|
||
h("p", { class: "muted small" }, t("reg.codesHelp")),
|
||
problem,
|
||
h("div", { class: "actions" }, go),
|
||
h("p", { class: "muted small" }, t("reg.credit"))
|
||
);
|
||
drawChips();
|
||
return form;
|
||
}
|
||
function showRegions(message = "") {
|
||
const root = document.getElementById("app");
|
||
document.body.classList.remove("wide");
|
||
clear(root);
|
||
if (!getToken()) {
|
||
location.hash = "#/mine";
|
||
return;
|
||
}
|
||
const picker = regionPicker({
|
||
initial: state.node?.regions ?? [],
|
||
submitLabel: t("reg.save"),
|
||
onSubmit: async (regions) => {
|
||
const now = await setRegions(regions);
|
||
if (state.node) state.node.regions = now;
|
||
const statusEl2 = document.getElementById("status");
|
||
if (statusEl2 && state.node) statusEl2.textContent = statusLine(state.node);
|
||
showRegions(t("reg.saved"));
|
||
}
|
||
});
|
||
append(root, [
|
||
h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h1", null, t("reg.title")),
|
||
h("p", { class: "muted" }, t("reg.intro")),
|
||
h("p", { class: "ok", role: "status" }, message),
|
||
picker
|
||
)
|
||
]);
|
||
}
|
||
|
||
// src/main.ts
|
||
var PAGE = 20;
|
||
var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
|
||
var app4 = document.getElementById("app");
|
||
var statusEl = document.getElementById("status");
|
||
function label(prefix, value) {
|
||
if (!value) return "";
|
||
const key = `${prefix}.${value}`;
|
||
const known = ["kind.rent", "kind.sale", "cat.apartment", "cat.house", "cat.room", "cat.commercial"];
|
||
return known.includes(key) ? t(key) : value;
|
||
}
|
||
function where(geohash) {
|
||
const a = decodeGeohash(geohash);
|
||
if (!a) return geohash;
|
||
const ns = a.lat >= 0 ? "N" : "S";
|
||
const ew = a.lon >= 0 ? lang === "de" ? "O" : "E" : lang === "de" ? "W" : "W";
|
||
return `${Math.abs(a.lat).toFixed(2)}\xB0 ${ns}, ${Math.abs(a.lon).toFixed(2)}\xB0 ${ew}`;
|
||
}
|
||
function badge(ok) {
|
||
return h("span", { class: ok ? "badge ok" : "badge bad" }, (ok ? "\u2713 " : "\u2717 ") + t(ok ? "badge.ok" : "badge.bad"));
|
||
}
|
||
function num(v) {
|
||
const n = Number((v ?? "").replace(",", "."));
|
||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||
}
|
||
function toApi(p) {
|
||
const q = new URLSearchParams();
|
||
for (const k of ["kind", "category", "geohash"]) {
|
||
const v = p.get(k)?.trim().toLowerCase();
|
||
if (v) q.set(k, v);
|
||
}
|
||
const eur = num(p.get("max_price"));
|
||
if (eur) q.set("max_price", String(Math.round(eur * 100)));
|
||
const area = num(p.get("min_area"));
|
||
if (area) q.set("min_area", String(Math.ceil(area)));
|
||
const r = num(p.get("min_rooms"));
|
||
if (r) q.set("min_rooms", String(Math.ceil(r * 2)));
|
||
return q;
|
||
}
|
||
function field2(text, input, hint) {
|
||
return h("label", { class: "field" }, h("span", { class: "field-label" }, text), input, hint && h("span", { class: "hint" }, hint));
|
||
}
|
||
function select(name, current, options) {
|
||
const el = h("select", { name });
|
||
for (const [value, text] of options) {
|
||
el.append(h("option", { value, selected: value === current }, text));
|
||
}
|
||
return el;
|
||
}
|
||
function searchForm(params) {
|
||
const get = (k) => params.get(k) ?? "";
|
||
const regions = h("datalist", { id: "regions" }, ...(state.node?.regions ?? []).map((r) => h("option", { value: r })));
|
||
const form = h(
|
||
"form",
|
||
{ class: "filters" },
|
||
field2(t("filter.kind"), select("kind", get("kind"), [["", t("filter.any")], ["rent", t("kind.rent")], ["sale", t("kind.sale")]])),
|
||
field2(
|
||
t("filter.category"),
|
||
select("category", get("category"), [
|
||
["", t("filter.any")],
|
||
["apartment", t("cat.apartment")],
|
||
["house", t("cat.house")],
|
||
["room", t("cat.room")],
|
||
["commercial", t("cat.commercial")]
|
||
])
|
||
),
|
||
field2(
|
||
t("filter.region"),
|
||
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: state.node?.regions[0] ?? "u1x" }),
|
||
t("filter.regionHint")
|
||
),
|
||
field2(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
|
||
field2(t("filter.minArea"), h("input", { name: "min_area", type: "number", min: 0, step: 5, value: get("min_area") })),
|
||
field2(t("filter.minRooms"), h("input", { name: "min_rooms", type: "number", min: 0, step: 0.5, value: get("min_rooms") })),
|
||
h(
|
||
"div",
|
||
{ class: "actions" },
|
||
h("button", { type: "submit", class: "btn primary" }, t("filter.search")),
|
||
h("button", { type: "button", class: "btn", onclick: () => navigate("#/") }, t("filter.reset"))
|
||
),
|
||
regions
|
||
);
|
||
form.addEventListener("submit", (e2) => {
|
||
e2.preventDefault();
|
||
const q = new URLSearchParams();
|
||
for (const [k, v] of new FormData(form)) {
|
||
if (typeof v === "string" && v.trim() !== "") q.set(k, v.trim());
|
||
}
|
||
const s = q.toString();
|
||
navigate(s ? `#/?${s}` : "#/");
|
||
});
|
||
return form;
|
||
}
|
||
function navigate(hash) {
|
||
if (location.hash === hash || hash === "#/" && location.hash === "") route();
|
||
else location.hash = hash;
|
||
}
|
||
function card(l) {
|
||
const facts = [
|
||
label("cat", l.category),
|
||
l.area_m2 ? t("card.area", { n: l.area_m2 }) : "",
|
||
l.rooms_x2 ? rooms(l.rooms_x2) : ""
|
||
].filter(Boolean);
|
||
return h(
|
||
"a",
|
||
{ class: "card", href: `#/l/${l.author}/${l.id}` },
|
||
// author and id were verified to be hex
|
||
h("div", { class: "card-top" }, h("h3", null, l.title ?? ""), badge(true)),
|
||
h("p", { class: "price" }, price(l)),
|
||
h("p", { class: "facts" }, facts.join(" \xB7 ")),
|
||
h("p", { class: "muted" }, where(l.geohash))
|
||
);
|
||
}
|
||
async function loadResults(gen, q, root) {
|
||
const cards = h("div", { class: "cards" });
|
||
const foot = h("div", { class: "results-foot" });
|
||
append(root, [cards, foot]);
|
||
let offset = 0;
|
||
let shown = 0;
|
||
let hidden = 0;
|
||
const more = async () => {
|
||
clear(foot);
|
||
foot.append(h("p", { class: "muted" }, t("results.loading")));
|
||
let items;
|
||
try {
|
||
const paged = new URLSearchParams(q);
|
||
paged.set("limit", String(PAGE));
|
||
paged.set("offset", String(offset));
|
||
items = await search(paged);
|
||
} catch {
|
||
if (gen !== state.generation) return;
|
||
clear(foot);
|
||
foot.append(h("p", { class: "error" }, t("results.error")));
|
||
return;
|
||
}
|
||
if (gen !== state.generation) return;
|
||
const opts = verifyOpts();
|
||
for (const raw of items) {
|
||
const verdict = verifyListing(raw, opts);
|
||
if (verdict.ok) {
|
||
cards.append(card(raw));
|
||
shown++;
|
||
} else {
|
||
hidden++;
|
||
}
|
||
}
|
||
offset += items.length;
|
||
clear(foot);
|
||
if (hidden > 0) foot.append(h("p", { class: "warn" }, t("results.hidden", { n: hidden })));
|
||
if (shown === 0 && items.length < PAGE) foot.append(h("p", { class: "muted" }, t("results.none")));
|
||
if (items.length === PAGE) {
|
||
foot.append(h("button", { type: "button", class: "btn", onclick: () => void more() }, t("results.more")));
|
||
}
|
||
};
|
||
await more();
|
||
}
|
||
function showSearch(params) {
|
||
const gen = state.generation;
|
||
clear(app4);
|
||
const results = h("div", { class: "results", "aria-live": "polite" });
|
||
app4.append(h("p", { class: "tagline" }, t("app.tagline")));
|
||
if (state.node && state.node.regions.length === 0) {
|
||
app4.append(
|
||
h(
|
||
"p",
|
||
{ class: "notice", role: "status" },
|
||
t("search.noRegions"),
|
||
" ",
|
||
getToken() ? h("a", { href: "#/mine/regions" }, t("search.chooseRegions")) : null
|
||
)
|
||
);
|
||
}
|
||
app4.append(searchForm(params), results);
|
||
const prefix = params.get("geohash")?.trim().toLowerCase();
|
||
if (prefix && !GEOHASH_PREFIX.test(prefix)) {
|
||
results.append(h("p", { class: "error" }, t("filter.regionHint")));
|
||
return;
|
||
}
|
||
void loadResults(gen, toApi(params), results);
|
||
}
|
||
function checkList(v) {
|
||
return h(
|
||
"ul",
|
||
{ class: "checks" },
|
||
...v.checks.map(
|
||
(c) => h(
|
||
"li",
|
||
{ class: c.ok ? "ok" : "bad" },
|
||
h("span", { class: "mark", "aria-hidden": "true" }, c.ok ? "\u2713" : "\u2717"),
|
||
h("span", null, t(`verify.${c.id}`)),
|
||
c.info && h("span", { class: "muted info" }, c.info)
|
||
)
|
||
)
|
||
);
|
||
}
|
||
function verification(raw, l, v) {
|
||
return h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h2", null, t("verify.title")),
|
||
h("p", { class: "muted" }, t("verify.intro")),
|
||
checkList(v),
|
||
v.ok && h(
|
||
"dl",
|
||
{ class: "kv" },
|
||
h("dt", null, t("verify.owner")),
|
||
h("dd", { class: "mono" }, shortKey(l.author)),
|
||
h("dt", null, t("verify.device")),
|
||
h("dd", { class: "mono" }, shortKey(l.device))
|
||
),
|
||
h("p", { class: "muted" }, t("verify.limit")),
|
||
// Never echo the content of a listing that failed verification, not even as raw data.
|
||
v.ok && h("details", null, h("summary", null, t("verify.raw")), h("pre", null, JSON.stringify(raw, null, 2)))
|
||
);
|
||
}
|
||
function listingBody(l) {
|
||
const area = decodeGeohash(l.geohash);
|
||
const fact = (k, v) => v ? [h("dt", null, t(k)), h("dd", null, v)] : [false];
|
||
const map = area && h(
|
||
"a",
|
||
{
|
||
href: `https://www.openstreetmap.org/?mlat=${area.lat.toFixed(5)}&mlon=${area.lon.toFixed(5)}#map=14/${area.lat.toFixed(5)}/${area.lon.toFixed(5)}`,
|
||
target: "_blank",
|
||
rel: "noopener noreferrer"
|
||
},
|
||
t("detail.map")
|
||
);
|
||
return [
|
||
h("div", { class: "detail-head" }, h("h1", null, l.title ?? ""), badge(true)),
|
||
h("p", { class: "price big" }, price(l)),
|
||
h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h2", null, t("detail.facts")),
|
||
h(
|
||
"dl",
|
||
{ class: "kv" },
|
||
...[
|
||
...fact("detail.kind", label("kind", l.kind)),
|
||
...fact("detail.category", label("cat", l.category)),
|
||
...fact("detail.area", l.area_m2 ? t("card.area", { n: l.area_m2 }) : ""),
|
||
...fact("detail.rooms", l.rooms_x2 ? rooms(l.rooms_x2) : ""),
|
||
...fact("detail.published", date(l.created_at)),
|
||
...fact("detail.expires", date(l.expires_at)),
|
||
...fact("detail.version", String(l.seq)),
|
||
...fact("detail.location", where(l.geohash))
|
||
].filter(Boolean)
|
||
),
|
||
map && h("p", null, map)
|
||
),
|
||
l.description ? h("section", { class: "panel" }, h("p", { class: "desc" }, l.description)) : h("span"),
|
||
l.features?.length ? h("section", { class: "panel" }, h("h2", null, t("detail.features")), h("ul", { class: "chips" }, ...l.features.map((f) => h("li", null, f)))) : h("span"),
|
||
contactPanel(l)
|
||
];
|
||
}
|
||
async function showDetail(author, id) {
|
||
const gen = state.generation;
|
||
clear(app4);
|
||
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
|
||
app4.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
|
||
let raw;
|
||
try {
|
||
raw = await getListing(author, id);
|
||
} catch {
|
||
if (gen !== state.generation) return;
|
||
clear(body);
|
||
body.append(h("p", { class: "error" }, t("results.error")));
|
||
return;
|
||
}
|
||
if (gen !== state.generation) return;
|
||
clear(body);
|
||
if (raw === null) {
|
||
body.append(h("p", { class: "muted" }, t("detail.notFound")));
|
||
return;
|
||
}
|
||
const l = raw;
|
||
let v = verifyListing(raw, verifyOpts());
|
||
if (v.ok && (l.author !== author || l.id !== id)) {
|
||
v = { ...v, ok: false, checks: [...v.checks, { id: "binding", ok: false, info: "not the listing that was requested" }] };
|
||
}
|
||
if (!v.ok) {
|
||
body.append(h("p", { class: "error" }, t("detail.unverified")), verification(raw, l, v));
|
||
return;
|
||
}
|
||
append(body, [...listingBody(l), verification(raw, l, v)]);
|
||
}
|
||
function renderNav() {
|
||
const nav = document.getElementById("nav");
|
||
clear(nav);
|
||
append(nav, [
|
||
h("a", { href: "#/messages" }, t("nav.messages")),
|
||
getToken() && h("a", { href: "#/mine" }, t("nav.owner"))
|
||
]);
|
||
}
|
||
function route() {
|
||
state.generation++;
|
||
const hash = location.hash.replace(/^#/, "") || "/";
|
||
const q = hash.indexOf("?");
|
||
const path = q < 0 ? hash : hash.slice(0, q);
|
||
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
|
||
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
|
||
const c = /^\/c\/([0-9a-f]{64})\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(path);
|
||
const login = /^\/login\/([0-9a-f]{16,128})$/.exec(path);
|
||
const own = /^\/mine(?:\/([0-9a-f]{32})(?:\/([0-9a-f]{64}))?)?$/.exec(path);
|
||
const edit = /^\/mine\/([0-9a-f]{32})\/edit$/.exec(path);
|
||
document.body.classList.remove("wide");
|
||
if (login) {
|
||
setToken(login[1]);
|
||
if (state.node && state.node.regions.length === 0) {
|
||
history.replaceState(null, "", location.pathname + location.search + "#/mine/regions");
|
||
showRegions();
|
||
} else {
|
||
history.replaceState(null, "", location.pathname + location.search + "#/mine");
|
||
void showOwner();
|
||
}
|
||
} else if (m) void showDetail(m[1], m[2]);
|
||
else if (c) void showConversation(c[1], c[2], c[3]);
|
||
else if (path === "/messages") showInbox();
|
||
else if (path === "/mine/regions") showRegions();
|
||
else if (path === "/mine/new") void showPublish();
|
||
else if (edit) void showPublish(edit[1]);
|
||
else if (own) void showOwner(own[1], own[2]);
|
||
else showSearch(params);
|
||
renderNav();
|
||
window.scrollTo(0, 0);
|
||
}
|
||
async function boot() {
|
||
document.documentElement.lang = lang;
|
||
document.getElementById("foot").textContent = t("footer.text");
|
||
try {
|
||
state.node = await getStatus();
|
||
statusEl.textContent = statusLine(state.node);
|
||
} catch {
|
||
statusEl.textContent = t("status.unreachable");
|
||
}
|
||
window.addEventListener("hashchange", route);
|
||
route();
|
||
}
|
||
void boot();
|