@ghostlytools/cli 1.11.2 → 1.11.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -28
- package/SKILL.md +4 -2
- package/dist/assets/{api-CtXgscmK.js → api-BwyFq4lA.js} +2 -2
- package/dist/assets/{api-BM3PsXbB.js → api-MYc6QNRs.js} +306 -114
- package/dist/assets/api-MYc6QNRs.js.map +1 -0
- package/dist/assets/{apiKit-lCTQ0EBG.js → apiKit-CfsNx9ZR.js} +62 -16
- package/dist/assets/apiKit-CfsNx9ZR.js.map +1 -0
- package/dist/assets/{appFetch-BKHy5H8J.js → appFetch-DVYZOZFw.js} +3 -3
- package/dist/assets/{appFetch-BKHy5H8J.js.map → appFetch-DVYZOZFw.js.map} +1 -1
- package/dist/assets/{apps-DO_gAZgm.js → apps-Dbw2Hcko.js} +1 -1
- package/dist/assets/{apps-Do26w3c7.js → apps-h12II1us.js} +150 -57
- package/dist/assets/apps-h12II1us.js.map +1 -0
- package/dist/assets/{arkade-CZrLbz-M.js → arkade-Bw_4PZRG.js} +2 -2
- package/dist/assets/{arkade-CZrLbz-M.js.map → arkade-Bw_4PZRG.js.map} +1 -1
- package/dist/assets/{backup-D21x1f5P.js → backup-CdEzTq5C.js} +1 -1
- package/dist/assets/{backup-j47AzDvG.js → backup-Chvy79SN.js} +60 -55
- package/dist/assets/backup-Chvy79SN.js.map +1 -0
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
- package/dist/assets/{buttons-CiGlBVBT.js → buttons-BgoExb4E.js} +37 -7
- package/dist/assets/buttons-BgoExb4E.js.map +1 -0
- package/dist/assets/buttons-DK2aAGat.js +2 -0
- package/dist/assets/{client-raIncVtF.js → client-DY8tZZWi.js} +28 -8
- package/dist/assets/client-DY8tZZWi.js.map +1 -0
- package/dist/assets/{codec-DcG2AeyE.js → codec-BnMg-Grj.js} +2 -2
- package/dist/assets/{codec-DcG2AeyE.js.map → codec-BnMg-Grj.js.map} +1 -1
- package/dist/assets/{envelope-Dud6lntA.js → envelope-CdV7vHVZ.js} +2 -2
- package/dist/assets/{envelope-Dud6lntA.js.map → envelope-CdV7vHVZ.js.map} +1 -1
- package/dist/assets/{errors-Dt-ZnyOX.js → errors-CAh6GLJZ.js} +27 -2
- package/dist/assets/errors-CAh6GLJZ.js.map +1 -0
- package/dist/assets/{fedimintSdk-DRKRSw14.js → fedimintSdk-CPFfVK-G.js} +2 -2
- package/dist/assets/{fedimintSdk-DRKRSw14.js.map → fedimintSdk-CPFfVK-G.js.map} +1 -1
- package/dist/assets/{fixedHosts-CNX7QiUD.js → fixedHosts-CbgqrIKs.js} +3 -3
- package/dist/assets/{fixedHosts-CNX7QiUD.js.map → fixedHosts-CbgqrIKs.js.map} +1 -1
- package/dist/assets/{host-8RskzQgB.js → host-C0NMNQLl.js} +702 -143
- package/dist/assets/host-C0NMNQLl.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-uAThbFub.js → hyperdhtRelay-Dz7pvcBA.js} +2 -2
- package/dist/assets/{hyperdhtRelay-uAThbFub.js.map → hyperdhtRelay-Dz7pvcBA.js.map} +1 -1
- package/dist/assets/{irohWeb-DGelfgDJ.js → irohWeb-caAj4Dms.js} +19 -12
- package/dist/assets/irohWeb-caAj4Dms.js.map +1 -0
- package/dist/assets/{main-BC33ooYg.js → main-C6t5zrD5.js} +383 -110
- package/dist/assets/main-C6t5zrD5.js.map +1 -0
- package/dist/assets/{mainline-DYrjsS1t.js → mainline-DCuGUSZF.js} +35 -18
- package/dist/assets/mainline-DCuGUSZF.js.map +1 -0
- package/dist/assets/{networkReason-n2oBs4by.js → networkReason-BbQW1Xpc.js} +3 -3
- package/dist/assets/{networkReason-n2oBs4by.js.map → networkReason-BbQW1Xpc.js.map} +1 -1
- package/dist/assets/{nwc-Do3VSlIS.js → nwc-CSDRMZ0e.js} +3 -3
- package/dist/assets/{nwc-Do3VSlIS.js.map → nwc-CSDRMZ0e.js.map} +1 -1
- package/dist/assets/{nwcProvider-Du5aWNIn.js → nwcProvider-PE0wli8n.js} +2 -2
- package/dist/assets/{nwcProvider-Du5aWNIn.js.map → nwcProvider-PE0wli8n.js.map} +1 -1
- package/dist/assets/{ownDid-CwwYu8s2.js → ownDid-C1R5Kd8q.js} +2 -2
- package/dist/assets/{ownDid-CwwYu8s2.js.map → ownDid-C1R5Kd8q.js.map} +1 -1
- package/dist/assets/{ownStatus-D7dB4zJB.js → ownStatus-BoTf5WqQ.js} +27 -9
- package/dist/assets/ownStatus-BoTf5WqQ.js.map +1 -0
- package/dist/assets/{profiles-NyF5FnYF.js → profiles-DszHjEJi.js} +25 -10
- package/dist/assets/profiles-DszHjEJi.js.map +1 -0
- package/dist/assets/{registry-DKDInr0A.js → registry-Da-r6eC3.js} +30 -12
- package/dist/assets/registry-Da-r6eC3.js.map +1 -0
- package/dist/assets/{registry-C734VrO9.js → registry-zUZBSHYv.js} +1 -1
- package/dist/assets/{resolve-3Tqh9AWQ.js → resolve-tUzh4lHh.js} +2 -2
- package/dist/assets/{resolve-3Tqh9AWQ.js.map → resolve-tUzh4lHh.js.map} +1 -1
- package/dist/assets/{secretGuard-B7Hj0Kvz.js → secretGuard-CsVHDdYk.js} +68 -6
- package/dist/assets/{secretGuard-B7Hj0Kvz.js.map → secretGuard-CsVHDdYk.js.map} +1 -1
- package/dist/assets/secretGuard-DCb1I0_B.js +2 -0
- package/dist/assets/{server-B6PQ6iae.js → server-C1jZZ61O.js} +896 -277
- package/dist/assets/server-C1jZZ61O.js.map +1 -0
- package/dist/assets/{src-ChJijTlM.js → src-DJe-OYxd.js} +1010 -236
- package/dist/assets/src-DJe-OYxd.js.map +1 -0
- package/dist/assets/{sshForges-Brf0fslM.js → sshForges-C9zTO72R.js} +4 -3
- package/dist/assets/sshForges-C9zTO72R.js.map +1 -0
- package/dist/assets/{translate-xLme9Rdh.js → translate-CUuC5szR.js} +36 -15
- package/dist/assets/translate-CUuC5szR.js.map +1 -0
- package/dist/assets/{usdt-CSU5KzTV.js → usdt-DI51znt-.js} +3 -3
- package/dist/assets/{usdt-CSU5KzTV.js.map → usdt-DI51znt-.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-BM3PsXbB.js.map +0 -1
- package/dist/assets/apiKit-lCTQ0EBG.js.map +0 -1
- package/dist/assets/apps-Do26w3c7.js.map +0 -1
- package/dist/assets/backup-j47AzDvG.js.map +0 -1
- package/dist/assets/buttons-CiGlBVBT.js.map +0 -1
- package/dist/assets/buttons-D2l2bVCG.js +0 -2
- package/dist/assets/client-raIncVtF.js.map +0 -1
- package/dist/assets/errors-Dt-ZnyOX.js.map +0 -1
- package/dist/assets/host-8RskzQgB.js.map +0 -1
- package/dist/assets/irohWeb-DGelfgDJ.js.map +0 -1
- package/dist/assets/main-BC33ooYg.js.map +0 -1
- package/dist/assets/mainline-DYrjsS1t.js.map +0 -1
- package/dist/assets/ownStatus-D7dB4zJB.js.map +0 -1
- package/dist/assets/profiles-NyF5FnYF.js.map +0 -1
- package/dist/assets/registry-DKDInr0A.js.map +0 -1
- package/dist/assets/secretGuard-DUr6bgKc.js +0 -2
- package/dist/assets/server-B6PQ6iae.js.map +0 -1
- package/dist/assets/src-ChJijTlM.js.map +0 -1
- package/dist/assets/sshForges-Brf0fslM.js.map +0 -1
- package/dist/assets/translate-xLme9Rdh.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ki as IdentityCheckUnavailable, it as parseSshPublicKey, ot as sameSshKey } from "./src-DJe-OYxd.js";
|
|
2
2
|
//#region ../browser/src/proofs/oidc/providers.ts
|
|
3
3
|
var TEST_ISSUER = /^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*\.test$/;
|
|
4
4
|
var MICROSOFT_TENANT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
@@ -17,7 +17,8 @@ var OIDC_PROVIDERS = {
|
|
|
17
17
|
email: { scope: "email" },
|
|
18
18
|
profile: { scope: "profile" }
|
|
19
19
|
},
|
|
20
|
-
alwaysIncluded: "A Google account identifier.",
|
|
20
|
+
alwaysIncluded: "A Google account identifier. For a work or school account Google also adds its organisation’s domain, so one is only accepted with your email shared.",
|
|
21
|
+
disclosing: { hd: "email" },
|
|
21
22
|
extraParams: { prompt: "select_account" },
|
|
22
23
|
clientIds: {
|
|
23
24
|
web: "",
|
|
@@ -257,4 +258,4 @@ async function checkSshForge(forge, login, key, fetcher, signal) {
|
|
|
257
258
|
//#endregion
|
|
258
259
|
export { PUBKY_RELAYS as a, isConfigured as c, providerForIssuer as d, validForgeLogin as i, issuerFor as l, SSH_FORGE_LABEL as n, audiences as o, checkSshForge as r, clientIdFor as s, SSH_FORGE_HOST as t, oidcProviders as u };
|
|
259
260
|
|
|
260
|
-
//# sourceMappingURL=sshForges-
|
|
261
|
+
//# sourceMappingURL=sshForges-C9zTO72R.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sshForges-C9zTO72R.js","names":[],"sources":["../../../browser/src/proofs/oidc/providers.ts","../../../browser/src/proofs/pubkyRelays.ts","../../../browser/src/proofs/sshForges.ts"],"sourcesContent":["/**\n * The OpenID Connect providers Ghostly can ask for a signed ID token. A contact\n * verifies that token against the provider's published keys, with no Ghostly\n * server in between, so a provider is only listed when its ID tokens are signed\n * and its keys and sign-in page are reachable from a browser without a client\n * secret. See docs/wisps/3xx-oidc-proofs.md for the providers that are not\n * (Facebook, X, LinkedIn, GitHub) and why.\n *\n * Client IDs are public configuration, identical in every build, because the\n * contact's app checks `aud` against them. They stay empty until the OAuth\n * clients are registered (docs/OIDC-PROVIDERS.md); a provider without a client\n * ID is neither offered nor accepted.\n */\n\nexport type OidcProviderId = 'google' | 'microsoft' | 'apple' | 'gitlab' | 'twitch' | 'test';\nexport type OidcAlg = 'RS256' | 'ES256';\nexport type OidcPlatform = 'web' | 'extension' | 'desktop';\n/** What the person chooses to put in the token beyond the account identifier. */\nexport type OidcReveal = 'email' | 'profile';\n\nexport interface OidcProvider {\n id: OidcProviderId;\n name: string;\n /** Exact `iss`. Microsoft's contains the tenant: see `issuerFor`. */\n issuer: string;\n /** Other spellings the provider documents for the same issuer. */\n issuerAliases?: string[];\n discovery: string;\n authorizationEndpoint: string;\n /** Pinned rather than discovered, so a changed discovery document cannot redirect key lookup. */\n jwksUri: string;\n /** Only for `code`: the token endpoint, reached with PKCE and no secret. */\n tokenEndpoint?: string;\n /** Best effort after a `code` exchange: the access token Ghostly never wanted is revoked at once. */\n revocationEndpoint?: string;\n /** Pinned per provider; the token header's `alg` must be one of these. */\n algs: OidcAlg[];\n /**\n * `id_token` returns only the signed ID token in the fragment: no access\n * token, no code, nothing to exchange, so no secret. `code id_token` is\n * Apple's shape (its code needs a secret; Ghostly drops it). `code` is for\n * providers without an ID-token-only response, exchanged with PKCE.\n */\n responseType: 'id_token' | 'code id_token' | 'code';\n /** Which extra claims this provider can add, and the scope (or claims request) for each. */\n reveal: Partial<Record<OidcReveal, { scope?: string; claims?: string[] }>>;\n /** What the provider puts in the token whatever the person picks. Shown before sign-in. */\n alwaysIncluded: string;\n /**\n * Claims the provider adds on its own for some accounts that say more than the account, each with the\n * choice that already shares as much. The signature covers the whole token, so such a claim cannot be\n * stripped: a token carrying one the person did not choose to share is turned down before it is used.\n */\n disclosing?: Record<string, OidcReveal>;\n /** Extra authorization parameters, e.g. an account chooser. */\n extraParams?: Record<string, string>;\n /** Client IDs per platform. Desktop signs in through the web callback page, so it uses the web client. */\n clientIds: Partial<Record<OidcPlatform, string>>;\n}\n\nexport const TEST_ISSUER = /^https:\\/\\/[a-z0-9-]+(\\.[a-z0-9-]+)*\\.test$/;\nconst MICROSOFT_TENANT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nexport const OIDC_PROVIDERS: Record<Exclude<OidcProviderId, 'test'>, OidcProvider> = {\n google: {\n id: 'google', name: 'Google',\n issuer: 'https://accounts.google.com', issuerAliases: ['accounts.google.com'],\n discovery: 'https://accounts.google.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',\n jwksUri: 'https://www.googleapis.com/oauth2/v3/certs',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A Google account identifier. For a work or school account Google also adds its organisation’s domain, so one is only accepted with your email shared.',\n // `hd`: a Workspace or Cloud organisation account's domain, in every token Google signs for it.\n disclosing: { hd: 'email' },\n extraParams: { prompt: 'select_account' },\n clientIds: { web: '', extension: '' },\n },\n microsoft: {\n // `common` takes work, school and personal accounts; the issuer names the account's tenant.\n id: 'microsoft', name: 'Microsoft',\n issuer: 'https://login.microsoftonline.com/{tenantid}/v2.0',\n discovery: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',\n authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',\n jwksUri: 'https://login.microsoftonline.com/common/discovery/v2.0/keys',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A Microsoft account identifier and the directory (tenant) the account belongs to.',\n extraParams: { prompt: 'select_account', response_mode: 'fragment' },\n clientIds: { web: '', extension: '' },\n },\n apple: {\n // Apple only returns the ID token in the fragment when no scope is asked\n // for; name and email need `form_post`, which a static page cannot read.\n id: 'apple', name: 'Apple',\n issuer: 'https://appleid.apple.com',\n discovery: 'https://appleid.apple.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://appleid.apple.com/auth/authorize',\n jwksUri: 'https://appleid.apple.com/auth/keys',\n algs: ['RS256'], responseType: 'code id_token',\n reveal: {},\n alwaysIncluded: 'An Apple ID identifier that only Ghostly sees. Apple cannot add your email here without a Ghostly server.',\n extraParams: { response_mode: 'fragment' },\n clientIds: { web: '', extension: '' },\n },\n gitlab: {\n id: 'gitlab', name: 'GitLab',\n issuer: 'https://gitlab.com',\n discovery: 'https://gitlab.com/.well-known/openid-configuration',\n authorizationEndpoint: 'https://gitlab.com/oauth/authorize',\n tokenEndpoint: 'https://gitlab.com/oauth/token',\n revocationEndpoint: 'https://gitlab.com/oauth/revoke',\n jwksUri: 'https://gitlab.com/oauth/discovery/keys',\n algs: ['RS256'], responseType: 'code',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A GitLab.com user ID and the groups you belong to directly: GitLab adds them to every ID token.',\n clientIds: { web: '', extension: '' },\n },\n twitch: {\n // Twitch's email claim needs `user:read:email`, an API scope: not asked for.\n id: 'twitch', name: 'Twitch',\n issuer: 'https://id.twitch.tv/oauth2',\n discovery: 'https://id.twitch.tv/oauth2/.well-known/openid-configuration',\n authorizationEndpoint: 'https://id.twitch.tv/oauth2/authorize',\n jwksUri: 'https://id.twitch.tv/oauth2/keys',\n algs: ['RS256'], responseType: 'id_token',\n reveal: { profile: { claims: ['preferred_username'] } },\n alwaysIncluded: 'A Twitch user ID.',\n extraParams: { force_verify: 'true' },\n clientIds: { web: '', extension: '' },\n },\n};\n\n/**\n * The local issuer the e2e suite runs (e2e/support/oidcIssuer.ts). It exists\n * only in a build made with VITE_OIDC_TEST_ISSUER, and only on a `.test` host\n * (a name reserved for testing, never a real issuer); a release build has no\n * such provider, so a token from it is refused like any unknown issuer.\n */\nexport function testProvider(issuer: string): OidcProvider {\n if (!TEST_ISSUER.test(issuer)) throw new Error('A test issuer lives on a .test host');\n const base = issuer;\n return {\n id: 'test', name: 'Test issuer', issuer: base,\n discovery: `${base}/.well-known/openid-configuration`,\n authorizationEndpoint: `${base}/authorize`,\n jwksUri: `${base}/jwks`,\n algs: ['RS256', 'ES256'], responseType: 'id_token',\n reveal: { email: { scope: 'email' }, profile: { scope: 'profile' } },\n alwaysIncluded: 'A test account identifier.',\n clientIds: { web: 'ghostly-e2e', extension: 'ghostly-e2e', desktop: 'ghostly-e2e' },\n };\n}\n\nfunction configuredTestIssuer(): string | undefined {\n try {\n const value = import.meta.env?.VITE_OIDC_TEST_ISSUER as string | undefined;\n return value && TEST_ISSUER.test(value) ? value : undefined;\n } catch { return undefined; }\n}\n\n/** Every provider this build knows, configured or not. */\nexport function oidcProviders(testIssuer = configuredTestIssuer()): OidcProvider[] {\n return [...Object.values(OIDC_PROVIDERS), ...(testIssuer ? [testProvider(testIssuer)] : [])];\n}\n\nexport function oidcProvider(id: string, testIssuer = configuredTestIssuer()): OidcProvider | undefined {\n return oidcProviders(testIssuer).find(p => p.id === id);\n}\n\n/** Every client ID this provider has, on any platform: a contact may use another platform than the prover. */\nexport function audiences(provider: OidcProvider): string[] {\n return [...new Set(Object.values(provider.clientIds).filter((id): id is string => !!id))];\n}\n\nexport function clientIdFor(provider: OidcProvider, platform: OidcPlatform): string {\n return provider.clientIds[platform] || provider.clientIds.web || '';\n}\n\n/** A provider is offered only once its client ID for this platform exists. */\nexport function isConfigured(provider: OidcProvider, platform: OidcPlatform): boolean {\n return !!clientIdFor(provider, platform);\n}\n\n/** The exact issuer a token from this provider must carry, or undefined when its claims do not name one. */\nexport function issuerFor(provider: OidcProvider, claims: { tid?: unknown }): string[] {\n if (provider.id !== 'microsoft') return [provider.issuer, ...(provider.issuerAliases ?? [])];\n return typeof claims.tid === 'string' && MICROSOFT_TENANT.test(claims.tid) ? [provider.issuer.replace('{tenantid}', claims.tid)] : [];\n}\n\n/** The provider a proof's subject (an issuer, as `OidcProvider.issuer` spells it) names. */\nexport function providerForIssuer(issuer: string, list = oidcProviders()): OidcProvider | undefined {\n return list.find(p => p.issuer === issuer);\n}\n","/**\n * Pkarr relays a Pubky key's records are read from: Pubky's own, the ones the Pubky SDK uses. A module of its own so\n * that naming them (`fixedHosts.ts`) does not bring `./pubky` into the entry: the web app's install leaves that chunk\n * to its first use (`apps/web/src/sw/policy.ts`).\n */\nexport const PUBKY_RELAYS: readonly string[] = [\"https://pkarr.pubky.org\", \"https://pkarr.pubky.app\"];\n","import { IdentityCheckUnavailable, parseSshPublicKey, sameSshKey, type SshPublicKey } from '@ghostly/core';\nimport type { IdentityFetch } from './contract';\n\n/** \"This account publishes that key\", without OAuth: GitHub and GitLab publish every account's SSH\n * public keys, and only the account holder can add one. The verifier's own lookup, through the\n * engine's bounded `ctx.fetch`; it tells the forge (and the network) which account was checked. */\n\nexport type SshForge = 'github' | 'gitlab';\nexport const SSH_FORGE_LABEL: Record<SshForge, string> = { github: 'GitHub', gitlab: 'GitLab' };\n/** The only host each forge lookup contacts, for the privacy line. */\nexport const SSH_FORGE_HOST: Record<SshForge, string> = { github: 'api.github.com', gitlab: 'gitlab.com' };\n\nexport type SshForgeStatus = 'linked' | 'not-listed' | 'no-account';\n\nconst MAX_BODY = 256 * 1024;\nconst MAX_KEYS = 200;\n\nexport function validForgeLogin(forge: SshForge, login: string): boolean {\n if (typeof login !== 'string') return false;\n // GitHub: 1-39 alphanumerics or single inner hyphens. GitLab: letters, digits, _ . - ;\n // not starting with - and not ending in .git/.atom. Capped at 64 so it fits every label.\n return forge === 'github'\n ? /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/.test(login)\n : /^[A-Za-z0-9_.][A-Za-z0-9_.-]{0,63}$/.test(login) && !/\\.(?:git|atom)$/i.test(login);\n}\n\n/** A forge that could not be asked (not reached, limiting lookups, an error or a page that is not its API) is IdentityCheckUnavailable: it says nothing about the key. */\nasync function get(fetcher: IdentityFetch, url: string, signal?: AbortSignal): Promise<{ status: 404 } | { status: 200; body: unknown }> {\n const host = new URL(url).host;\n let response: Awaited<ReturnType<IdentityFetch>>;\n try { response = await fetcher(url, { maxBytes: MAX_BODY, signal }); }\n catch (e) { throw e instanceof IdentityCheckUnavailable ? e : new IdentityCheckUnavailable(`${host} could not be reached: ${e instanceof Error ? e.message : String(e)}`); }\n if (response.status === 404) return { status: 404 };\n if (response.status === 403 || response.status === 429) throw new IdentityCheckUnavailable(`${host} is limiting lookups; check again later`);\n if (response.status !== 200) throw new IdentityCheckUnavailable(`${host} answered HTTP ${response.status}`);\n try { return { status: 200, body: JSON.parse(response.text) }; } catch { throw new IdentityCheckUnavailable(`Unexpected answer from ${host}`); }\n}\n\nfunction keysFrom(body: unknown): SshPublicKey[] {\n if (!Array.isArray(body)) throw new Error('Unexpected key list');\n const keys: SshPublicKey[] = [];\n for (const entry of body.slice(0, MAX_KEYS)) {\n const line = (entry as { key?: unknown } | null)?.key;\n if (typeof line !== 'string') continue;\n try { keys.push(parseSshPublicKey(line)); } catch { /* A key type Ghostly cannot verify never matches. */ }\n }\n return keys;\n}\n\n/** The account's published keys, or null when there is no such account. */\nasync function listKeys(forge: SshForge, login: string, fetcher: IdentityFetch, signal?: AbortSignal): Promise<SshPublicKey[] | null> {\n if (forge === 'github') {\n const r = await get(fetcher, `https://api.github.com/users/${encodeURIComponent(login)}/keys?per_page=100`, signal);\n return r.status === 404 ? null : keysFrom(r.body);\n }\n const users = await get(fetcher, `https://gitlab.com/api/v4/users?username=${encodeURIComponent(login)}`, signal);\n const list = users.status === 200 && Array.isArray(users.body) ? users.body as { id?: unknown; username?: unknown }[] : [];\n const user = list.find(u => typeof u?.username === 'string' && u.username.toLowerCase() === login.toLowerCase());\n if (!user) return null;\n if (!Number.isSafeInteger(user.id) || (user.id as number) <= 0) throw new Error('Unexpected answer from gitlab.com');\n const r = await get(fetcher, `https://gitlab.com/api/v4/users/${user.id as number}/keys?per_page=100`, signal);\n return r.status === 404 ? null : keysFrom(r.body);\n}\n\n// Only concurrent identical lookups share a request. What stays checked is the verifier's stored\n// result, which the app offers to re-check once the provider's `recheck` time has passed.\nconst inFlight = new WeakMap<IdentityFetch, Map<string, Promise<SshPublicKey[] | null>>>();\n\n/** Whether `key` is one of `login`'s published SSH keys. Throws when the forge cannot be asked. */\nexport async function checkSshForge(forge: SshForge, login: string, key: Pick<SshPublicKey, 'blob'>, fetcher: IdentityFetch, signal?: AbortSignal): Promise<SshForgeStatus> {\n if (!validForgeLogin(forge, login)) throw new Error(`Not a ${SSH_FORGE_LABEL[forge]} username`);\n let pending = inFlight.get(fetcher);\n if (!pending) inFlight.set(fetcher, pending = new Map());\n const map = pending, id = `${forge}:${login.toLowerCase()}`;\n let lookup = map.get(id);\n if (!lookup) {\n lookup = listKeys(forge, login, fetcher, signal).finally(() => map.delete(id));\n map.set(id, lookup);\n }\n const keys = await lookup;\n if (!keys) return 'no-account';\n return keys.some(k => sameSshKey(k, key)) ? 'linked' : 'not-listed';\n}\n"],"mappings":";;AA4DA,IAAa,cAAc;AAC3B,IAAM,mBAAmB;AAEzB,IAAa,iBAAwE;CACnF,QAAQ;EACN,IAAI;EAAU,MAAM;EACpB,QAAQ;EAA+B,eAAe,CAAC,qBAAqB;EAC5E,WAAW;EACX,uBAAuB;EACvB,SAAS;EACT,MAAM,CAAC,OAAO;EAAG,cAAc;EAC/B,QAAQ;GAAE,OAAO,EAAE,OAAO,QAAQ;GAAG,SAAS,EAAE,OAAO,UAAU;EAAE;EACnE,gBAAgB;EAEhB,YAAY,EAAE,IAAI,QAAQ;EAC1B,aAAa,EAAE,QAAQ,iBAAiB;EACxC,WAAW;GAAE,KAAK;GAAI,WAAW;EAAG;CACtC;CACA,WAAW;EAET,IAAI;EAAa,MAAM;EACvB,QAAQ;EACR,WAAW;EACX,uBAAuB;EACvB,SAAS;EACT,MAAM,CAAC,OAAO;EAAG,cAAc;EAC/B,QAAQ;GAAE,OAAO,EAAE,OAAO,QAAQ;GAAG,SAAS,EAAE,OAAO,UAAU;EAAE;EACnE,gBAAgB;EAChB,aAAa;GAAE,QAAQ;GAAkB,eAAe;EAAW;EACnE,WAAW;GAAE,KAAK;GAAI,WAAW;EAAG;CACtC;CACA,OAAO;EAGL,IAAI;EAAS,MAAM;EACnB,QAAQ;EACR,WAAW;EACX,uBAAuB;EACvB,S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ors-
|
|
1
|
+
import { co as linkTail, oo as LINK_TRAILING, so as linkStop } from "./src-DJe-OYxd.js";
|
|
2
|
+
import { t as CliError } from "./errors-CAh6GLJZ.js";
|
|
3
3
|
import { t as childEnv } from "./childEnv-K_IzUqQx.js";
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
5
|
import { existsSync } from "node:fs";
|
|
@@ -35,9 +35,9 @@ var CLOSERS = {
|
|
|
35
35
|
};
|
|
36
36
|
/**
|
|
37
37
|
* A link ends where the sentence around it takes over: trailing punctuation ("see https://x.example/a.", "見て
|
|
38
|
-
* https://x.example/a。", in any of the app's languages)
|
|
39
|
-
* ("(https://x.example/a)") are left as text, and so
|
|
40
|
-
* sits in.
|
|
38
|
+
* https://x.example/a。", in any of the app's languages), an emoji or invisible character ("https://x.example/a🔥",
|
|
39
|
+
* `linkTail`) and a closing bracket or quote the link did not open ("(https://x.example/a)") are left as text, and so
|
|
40
|
+
* is a doubled `~~` or `||` closing the strike or spoiler the link sits in.
|
|
41
41
|
*/
|
|
42
42
|
function linkEnd(whole) {
|
|
43
43
|
const url = linkStop(whole);
|
|
@@ -54,7 +54,9 @@ function linkEnd(whole) {
|
|
|
54
54
|
while (end > 0) {
|
|
55
55
|
const last = url[end - 1];
|
|
56
56
|
const opener = CLOSERS[last];
|
|
57
|
-
|
|
57
|
+
const tail = linkTail(url, end);
|
|
58
|
+
if (tail) end -= tail;
|
|
59
|
+
else if (LINK_TRAILING.test(last) || opener && count[last] > count[opener]) {
|
|
58
60
|
if (opener) count[last]--;
|
|
59
61
|
end--;
|
|
60
62
|
} else if ((last === "~" || last === "|") && url[end - 2] === last) end -= 2;
|
|
@@ -97,6 +99,7 @@ function shownUrl(url) {
|
|
|
97
99
|
var link = {
|
|
98
100
|
kind: "link",
|
|
99
101
|
pattern: /https?:\/\/\S+/gi,
|
|
102
|
+
lead: /https?:\/\//gi,
|
|
100
103
|
accept(match) {
|
|
101
104
|
const url = linkEnd(match[0]);
|
|
102
105
|
if (url.length <= match[0].indexOf("//") + 2) return null;
|
|
@@ -104,7 +107,8 @@ var link = {
|
|
|
104
107
|
data: { url },
|
|
105
108
|
end: match.index + url.length
|
|
106
109
|
};
|
|
107
|
-
}
|
|
110
|
+
},
|
|
111
|
+
plain: (atom) => shownUrl(atom.text)
|
|
108
112
|
};
|
|
109
113
|
//#endregion
|
|
110
114
|
//#region ../../apps/ui/src/lib/parse/inline.ts
|
|
@@ -142,15 +146,16 @@ var PUNCT = /[\p{P}\p{S}]/u;
|
|
|
142
146
|
var SPACE = /\s/u;
|
|
143
147
|
var WORD = /[\p{L}\p{N}]/u;
|
|
144
148
|
var compiled = /* @__PURE__ */ new WeakMap();
|
|
145
|
-
function
|
|
146
|
-
let re = compiled.get(
|
|
149
|
+
function globalOf(pattern) {
|
|
150
|
+
let re = compiled.get(pattern);
|
|
147
151
|
if (!re) {
|
|
148
|
-
const { source, flags } =
|
|
152
|
+
const { source, flags } = pattern;
|
|
149
153
|
re = new RegExp(source, flags.includes("g") ? flags : flags + "g");
|
|
150
|
-
compiled.set(
|
|
154
|
+
compiled.set(pattern, re);
|
|
151
155
|
}
|
|
152
156
|
return re;
|
|
153
157
|
}
|
|
158
|
+
var patternOf = (detector) => globalOf(detector.pattern);
|
|
154
159
|
/** The detector's next accepted match in `text` at or after `from`. */
|
|
155
160
|
function findNext(detector, text, from, ctx) {
|
|
156
161
|
const re = patternOf(detector);
|
|
@@ -173,9 +178,20 @@ function findNext(detector, text, from, ctx) {
|
|
|
173
178
|
}
|
|
174
179
|
return null;
|
|
175
180
|
}
|
|
181
|
+
/** The detector's next match at or after `from`, or only where it may start when it has a `lead`. */
|
|
182
|
+
function nextFrom(detector, text, from, ctx) {
|
|
183
|
+
if (!detector.lead) return findNext(detector, text, from, ctx);
|
|
184
|
+
const re = globalOf(detector.lead);
|
|
185
|
+
re.lastIndex = from;
|
|
186
|
+
const hit = re.exec(text);
|
|
187
|
+
return hit ? {
|
|
188
|
+
start: hit.index,
|
|
189
|
+
lead: true
|
|
190
|
+
} : null;
|
|
191
|
+
}
|
|
176
192
|
/** Pass 2: the detectors' atoms in a stretch of text outside code, and the text between them. */
|
|
177
193
|
function detect(text, detectors, ctx, out) {
|
|
178
|
-
const next = detectors.map((d) =>
|
|
194
|
+
const next = detectors.map((d) => nextFrom(d, text, 0, ctx));
|
|
179
195
|
let cursor = 0;
|
|
180
196
|
for (;;) {
|
|
181
197
|
let best = -1;
|
|
@@ -184,7 +200,12 @@ function detect(text, detectors, ctx, out) {
|
|
|
184
200
|
if (found && (best < 0 || found.start < next[best].start)) best = i;
|
|
185
201
|
}
|
|
186
202
|
if (best < 0) break;
|
|
187
|
-
const
|
|
203
|
+
const first = next[best];
|
|
204
|
+
if ("lead" in first) {
|
|
205
|
+
next[best] = findNext(detectors[best], text, first.start, ctx);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const found = first;
|
|
188
209
|
if (found.start > cursor) out.push(text.slice(cursor, found.start));
|
|
189
210
|
const detector = detectors[best];
|
|
190
211
|
out.push({
|
|
@@ -194,7 +215,7 @@ function detect(text, detectors, ctx, out) {
|
|
|
194
215
|
data: found.data
|
|
195
216
|
});
|
|
196
217
|
cursor = found.end;
|
|
197
|
-
for (let i = 0; i < next.length; i++) if (next[i] && next[i].start < cursor) next[i] =
|
|
218
|
+
for (let i = 0; i < next.length; i++) if (next[i] && next[i].start < cursor) next[i] = nextFrom(detectors[i], text, cursor, ctx);
|
|
198
219
|
}
|
|
199
220
|
if (cursor < text.length) out.push(text.slice(cursor));
|
|
200
221
|
}
|
|
@@ -1089,4 +1110,4 @@ function openTranslator({ home, to, detect, warn }) {
|
|
|
1089
1110
|
//#endregion
|
|
1090
1111
|
export { loadDetector, openTranslator, translateAnswer, translateTarget };
|
|
1091
1112
|
|
|
1092
|
-
//# sourceMappingURL=translate-
|
|
1113
|
+
//# sourceMappingURL=translate-CUuC5szR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translate-CUuC5szR.js","names":["EMOJI","runtimePackage"],"sources":["../../../../native/translation/package.json","../../../../apps/ui/src/lib/parse/blob.ts","../../../../apps/ui/src/lib/parse/links.ts","../../../../apps/ui/src/lib/parse/inline.ts","../../../../apps/ui/src/lib/parse/mdlink.ts","../../../../apps/ui/src/lib/parse/mentions.ts","../../../../apps/ui/src/lib/parse/time.ts","../../../../apps/ui/src/lib/parse/detectors.ts","../../../../apps/ui/src/lib/parse/json.ts","../../../../apps/ui/src/lib/parse/blocks.ts","../../../../apps/ui/src/lib/translateWhich.ts","../../src/translate.ts"],"sourcesContent":["{\n \"name\": \"ghostly-translation-native\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": { \"@qvac/translation-nmtcpp\": \"0.21.1\", \"bare-process\": \"4.5.1\", \"bare-runtime\": \"1.36.0\" }\n}\n","import type { Atom, Detector } from \"./types\";\n\n/** How long an unbroken key-like run must be before it folds to one line. */\nexport const BLOB_MIN = 80;\n\n/**\n * A long run with no spaces made of base64, base64url or hex characters: a key, a signature, a token pasted in\n * full. It folds to one line with \"Show all\" and Copy. Links and money come first (a link's path is never a blob,\n * and a Cashu token or an invoice has its own card).\n */\nexport const blob: Detector<\"blob\", null> = {\n kind: \"blob\",\n pattern: new RegExp(`(?<![A-Za-z0-9+/=_-])[A-Za-z0-9+/_-]{${BLOB_MIN},}={0,2}(?![A-Za-z0-9+/=_-])`, \"g\"),\n accept: () => ({ data: null }),\n plain: (atom: Atom<\"blob\", null>) => `${atom.text.slice(0, 12)}…`,\n};\n","import { LINK_TRAILING, linkStop, linkTail } from \"@ghostly/core\";\nimport type { Detector } from \"./types\";\n\nconst CLOSERS: Record<string, string> = { \")\": \"(\", \"]\": \"[\", \"}\": \"{\" };\n\n/**\n * A link ends where the sentence around it takes over: trailing punctuation (\"see https://x.example/a.\", \"見て\n * https://x.example/a。\", in any of the app's languages), an emoji or invisible character (\"https://x.example/a🔥\",\n * `linkTail`) and a closing bracket or quote the link did not open (\"(https://x.example/a)\") are left as text, and so\n * is a doubled `~~` or `||` closing the strike or spoiler the link sits in.\n */\nexport function linkEnd(whole: string): string {\n const url = linkStop(whole);\n const count: Record<string, number> = { \"(\": 0, \")\": 0, \"[\": 0, \"]\": 0, \"{\": 0, \"}\": 0 };\n for (const c of url) if (c in count) count[c]++;\n let end = url.length;\n while (end > 0) {\n const last = url[end - 1];\n const opener = CLOSERS[last];\n const tail = linkTail(url, end);\n if (tail) end -= tail;\n else if (LINK_TRAILING.test(last) || (opener && count[last] > count[opener])) {\n if (opener) count[last]--;\n end--;\n } else if ((last === \"~\" || last === \"|\") && url[end - 2] === last) end -= 2;\n else break;\n }\n return url.slice(0, end);\n}\n\n/**\n * Characters that draw as nothing, which can make a link read as another address: format characters (direction\n * marks and overrides, zero-width ones, the soft hyphen, tags, interlinear annotation, shorthand and musical format\n * controls), everything Unicode marks as ignorable by default (the grapheme joiner, the Hangul fillers, variation\n * selectors, the Khmer inherent vowels, the Mongolian free variation selectors), and the line and paragraph\n * separators. Spelled out as well as by property, so none of them depends on the engine's Unicode version.\n */\nexport const INVISIBLE =\n /[\\p{Cf}\\p{Default_Ignorable_Code_Point}\\u115f\\u1160\\u180e\\u2028\\u2029\\u3164\\uffa0\\ufff9-\\ufffb\\u{1bca0}-\\u{1bca3}\\u{1d173}-\\u{1d17a}\\u{e0000}-\\u{e007f}]|\\u034f|[\\u17b4\\u17b5]|[\\u180b-\\u180d]|\\u180f|[\\ufe00-\\ufe0f]|[\\u{e0100}-\\u{e01ef}]/gu;\n\n/**\n * A link as a bubble shows it. Plain ASCII whose host the browser reads as typed shows as typed. Anything else shows\n * as the browser reads it: the host in punycode (a look-alike \"аpple.com\" reads \"xn--pple-43d.com\"), escapes in it\n * decoded (\"paypal.com%2Eevil.example\" opens \"paypal.com.evil.example\") and other characters percent-encoded, so a\n * right-to-left override inside it cannot turn the address around. A user part (\"www.paypal.com@evil.example\")\n * is left out, so what reads as the host is the one the link opens. What no URL parser takes loses its invisible\n * characters.\n */\nexport function shownUrl(url: string): string {\n let parsed: URL;\n try { parsed = new URL(url); } catch { return url.replace(INVISIBLE, \"\"); }\n if (parsed.username || parsed.password) {\n parsed.username = \"\";\n parsed.password = \"\";\n return parsed.href;\n }\n const typedHost = /^[a-z][a-z\\d+.-]*:\\/\\/([^/?#\\\\]*)/i.exec(url)?.[1].replace(/:\\d*$/, \"\").toLowerCase();\n return /^[\\x21-\\x7e]*$/.test(url) && typedHost === parsed.hostname ? url : parsed.href;\n}\n\n/** Web addresses, over http(s) only: `javascript:` and `data:` never become links. */\nexport const link: Detector<\"link\", { url: string }> = {\n kind: \"link\",\n pattern: /https?:\\/\\/\\S+/gi,\n lead: /https?:\\/\\//gi,\n accept(match) {\n const url = linkEnd(match[0]);\n // \"https://\" and nothing else is not a place.\n if (url.length <= match[0].indexOf(\"//\") + 2) return null;\n return { data: { url }, end: match.index + url.length };\n },\n // The chat list reads it as the bubble shows it, not as typed.\n plain: (atom) => shownUrl(atom.text),\n};\n","import type { Detector, ParseContext, Segment, SpanStyle } from \"./types\";\n\n/**\n * The inline tokenizer: a paragraph's text in, segments out. Three passes, each linear in the text:\n *\n * 1. `code`: backtick spans (a run of N backticks up to the next run of exactly N on the same line). What is\n * inside is never read again: no links, no markers.\n * 2. Detectors, over the text between code spans: links, long blobs, times, and whatever other cards register.\n * What they recognise is opaque too, so a `*` or `_` inside a URL stays part of it.\n * 3. Markers, over what is left: `*bold*` (or `**bold**`), `_italic_` (or `__italic__`), `~~strike~~` and\n * `||spoiler||`, paired within a line. A marker opens after a space, a punctuation mark or the start, before\n * something that is not a space, and closes the other way round, so `snake_case_name`, `2*3*4` and\n * `__init__.py` stay text. Openers left unclosed, and closers with no opener, are text too.\n */\n\n/** What a spoiler reads as where it cannot be tapped: nothing of what it hides. */\nexport const SPOILER_PLAIN = \"▒▒▒\";\n\n/** Which runs of marker characters mean something, and what. A run of any other length is text. */\nconst MARKERS: Record<string, SpanStyle> = { \"*\": \"bold\", \"**\": \"bold\", \"_\": \"italic\", \"__\": \"italic\", \"~~\": \"strike\", \"||\": \"spoiler\" };\nconst MARKER_CHARS = new Set([\"*\", \"_\", \"~\", \"|\"]);\n\n/** Punctuation or a symbol: what a marker may lean on besides a space. */\nconst PUNCT = /[\\p{P}\\p{S}]/u;\nconst SPACE = /\\s/u;\nconst WORD = /[\\p{L}\\p{N}]/u;\n\nconst compiled = new WeakMap<RegExp, RegExp>();\nfunction globalOf(pattern: RegExp): RegExp {\n let re = compiled.get(pattern);\n if (!re) {\n const { source, flags } = pattern;\n re = new RegExp(source, flags.includes(\"g\") ? flags : flags + \"g\");\n compiled.set(pattern, re);\n }\n return re;\n}\nconst patternOf = (detector: Detector) => globalOf(detector.pattern);\n\ntype Found = { start: number; end: number; data: unknown };\n/** Where a detector's next match may start (its `lead`), not yet read: none starts before `start`. */\ntype Lead = { start: number; lead: true };\n\n/** The detector's next accepted match in `text` at or after `from`. */\nfunction findNext(detector: Detector, text: string, from: number, ctx: ParseContext): Found | null {\n const re = patternOf(detector);\n let at = from;\n while (at <= text.length) {\n re.lastIndex = at;\n const match = re.exec(text);\n if (!match) return null;\n const accepted = match[0] ? detector.accept(match, text, ctx) : null;\n const matchEnd = match.index + match[0].length;\n if (accepted) {\n const end = Math.min(accepted.end ?? matchEnd, matchEnd);\n if (end > match.index) return { start: match.index, end, data: accepted.data };\n }\n at = Math.max(matchEnd, match.index + 1);\n }\n return null;\n}\n\ntype Item = { t: \"text\"; s: string } | { t: \"seg\"; seg: Segment } | Mark;\ninterface Mark { t: \"mark\"; run: string; canOpen: boolean; canClose: boolean; pair?: \"open\" | \"close\" }\n\n/** The detector's next match at or after `from`, or only where it may start when it has a `lead`. */\nfunction nextFrom(detector: Detector, text: string, from: number, ctx: ParseContext): Found | Lead | null {\n if (!detector.lead) return findNext(detector, text, from, ctx);\n const re = globalOf(detector.lead);\n re.lastIndex = from;\n const hit = re.exec(text);\n return hit ? { start: hit.index, lead: true } : null;\n}\n\n/** Pass 2: the detectors' atoms in a stretch of text outside code, and the text between them. */\nfunction detect(text: string, detectors: readonly Detector[], ctx: ParseContext, out: (string | Segment)[]) {\n const next = detectors.map((d) => nextFrom(d, text, 0, ctx));\n let cursor = 0;\n for (;;) {\n let best = -1;\n for (let i = 0; i < next.length; i++) {\n const found = next[i];\n if (found && (best < 0 || found.start < next[best]!.start)) best = i;\n }\n if (best < 0) break;\n const first = next[best]!;\n // A lead is read only once it comes first: its match starts there or later, and is looked at again.\n if (\"lead\" in first) { next[best] = findNext(detectors[best], text, first.start, ctx); continue; }\n const found = first;\n if (found.start > cursor) out.push(text.slice(cursor, found.start));\n const detector = detectors[best];\n out.push({ type: \"atom\", kind: detector.kind, text: text.slice(found.start, found.end), data: found.data });\n cursor = found.end;\n // Whatever started inside the atom is gone; look again from its end.\n for (let i = 0; i < next.length; i++) if (next[i] && next[i]!.start < cursor) next[i] = nextFrom(detectors[i], text, cursor, ctx);\n }\n if (cursor < text.length) out.push(text.slice(cursor));\n}\n\n/** Pass 1: code spans. Backtick runs pair with the next run of the same length on the same line. */\nfunction codeSpans(text: string): (string | Segment)[] {\n const out: (string | Segment)[] = [];\n const runs: { at: number; len: number }[] = [];\n for (let i = 0; i < text.length; i++) {\n if (text[i] !== \"`\") continue;\n let j = i;\n while (text[j] === \"`\") j++;\n runs.push({ at: i, len: j - i });\n i = j - 1;\n }\n if (!runs.length) return [text];\n // For each run, the next run of the same length (found right to left, so this stays linear).\n const nextSame = new Array<number>(runs.length).fill(-1);\n const seen = new Map<number, number>();\n for (let i = runs.length - 1; i >= 0; i--) {\n nextSame[i] = seen.get(runs[i].len) ?? -1;\n seen.set(runs[i].len, i);\n }\n // Where each line ends, so a span never crosses one.\n const lineEnd = (at: number) => { const n = text.indexOf(\"\\n\", at); return n < 0 ? text.length : n; };\n let cursor = 0;\n let endOfLine = -1;\n for (let i = 0; i < runs.length; i++) {\n const open = runs[i];\n if (open.at < cursor) continue;\n if (open.at > endOfLine) endOfLine = lineEnd(open.at);\n const j = nextSame[i];\n if (j < 0) continue;\n const close = runs[j];\n const inner = text.slice(open.at + open.len, close.at);\n if (close.at > endOfLine || !inner.trim()) continue;\n if (open.at > cursor) out.push(text.slice(cursor, open.at));\n // As in Markdown, one space on each side lets a span start or end with a backtick.\n out.push({ type: \"code\", text: inner.length > 2 && inner[0] === \" \" && inner[inner.length - 1] === \" \" ? inner.slice(1, -1) : inner });\n cursor = close.at + close.len;\n i = j;\n }\n if (cursor < text.length) out.push(text.slice(cursor));\n return out;\n}\n\n/**\n * Pass 3, splitting: text into plain stretches and marker runs that could open or close something. `before` and\n * `after` are the characters around the text in the message (an atom's or a code span's edge counts as a word\n * character there: \"*see https://x.example*\" closes after the link).\n */\nfunction splitMarkers(text: string, prev: string | undefined, nextChar: string | undefined, items: Item[]) {\n let from = 0;\n for (let i = 0; i < text.length; i++) {\n if (!MARKER_CHARS.has(text[i])) continue;\n let j = i;\n while (text[j] === text[i]) j++;\n const run = text.slice(i, j);\n if (MARKERS[run]) {\n if (i > from) items.push({ t: \"text\", s: text.slice(from, i) });\n const before = i > 0 ? text[i - 1] : prev;\n const after = j < text.length ? text[j] : nextChar;\n const afterNext = j + 1 < text.length ? text[j + 1] : undefined;\n const mark: Mark = {\n t: \"mark\",\n run,\n canOpen: after !== undefined && !SPACE.test(after) && (before === undefined || SPACE.test(before) || (PUNCT.test(before) && before !== run[0])),\n canClose:\n before !== undefined && !SPACE.test(before) && (after === undefined || SPACE.test(after) || (PUNCT.test(after) && after !== run[0]))\n // \"__init__.py\": a full stop or colon followed straight by a word is part of a name, not the sentence.\n && !(after !== undefined && /[.,:;]/.test(after) && afterNext !== undefined && WORD.test(afterNext)),\n };\n items.push(mark);\n from = j;\n }\n i = j - 1;\n }\n if (from < text.length) items.push({ t: \"text\", s: text.slice(from) });\n}\n\n/**\n * The most styles open inside one another. Past it a marker stays text: a peer's message cannot nest spans\n * thousands deep, which every recursive reader of the tree (the bubble, the chat list's preview) would follow.\n */\nexport const MAX_SPAN_DEPTH = 8;\n\n/** Pass 3, pairing: per-run stacks, so a closer finds its opener in O(1) and each marker is dropped at most once. */\nfunction pairMarkers(items: Item[]) {\n // Open markers in order, where each one sits in that list, and the same markers per run.\n const stack: number[] = [];\n const depthOf = new Int32Array(items.length);\n const byRun = new Map<string, number[]>();\n const popTo = (depth: number) => {\n while (stack.length > depth) byRun.get((items[stack.pop()!] as Mark).run)!.pop();\n };\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n if (item.t === \"text\") {\n // Markers pair within a line.\n if (item.s.includes(\"\\n\")) popTo(0);\n continue;\n }\n if (item.t !== \"mark\") continue;\n const openers = byRun.get(item.run);\n if (item.canClose && openers?.length) {\n const opener = openers[openers.length - 1];\n // Whatever opened after it and is still open never closes: \"*a _b* c_\" is bold \"a _b\", then text.\n popTo(depthOf[opener]);\n (items[opener] as Mark).pair = \"open\";\n item.pair = \"close\";\n } else if (item.canOpen && stack.length < MAX_SPAN_DEPTH) {\n depthOf[i] = stack.length;\n stack.push(i);\n if (openers) openers.push(i);\n else byRun.set(item.run, [i]);\n }\n }\n}\n\n/** The paired items as a tree; unpaired markers are text, and neighbouring text is joined. */\nfunction build(items: Item[]): Segment[] {\n const root: Segment[] = [];\n const parents: Segment[][] = [root];\n const push = (seg: Segment) => {\n const list = parents[parents.length - 1];\n const last = list[list.length - 1];\n if (seg.type === \"text\" && last?.type === \"text\") last.text += seg.text;\n else list.push(seg);\n };\n for (const item of items) {\n if (item.t === \"text\") push({ type: \"text\", text: item.s });\n else if (item.t === \"seg\") push(item.seg);\n else if (item.pair === \"open\") {\n const span = { type: \"span\" as const, style: MARKERS[item.run], children: [] as Segment[] };\n push(span);\n parents.push(span.children);\n } else if (item.pair === \"close\") {\n parents.pop();\n } else push({ type: \"text\", text: item.run });\n }\n return root;\n}\n\n/** One paragraph's segments. `detectors` is the registry's list unless a test gives its own. */\nexport function tokenizeInline(text: string, detectors: readonly Detector[], ctx: ParseContext = {}): Segment[] {\n const pieces: (string | Segment)[] = [];\n for (const piece of codeSpans(text)) {\n if (typeof piece === \"string\") detect(piece, detectors, ctx, pieces);\n else pieces.push(piece);\n }\n const items: Item[] = [];\n // What sits on either side of a stretch of text: an atom's or a code span's edge reads as a word character.\n const edge = (piece: string | Segment | undefined, first: boolean) =>\n piece === undefined ? undefined : typeof piece === \"string\" ? piece[first ? 0 : piece.length - 1] : \"a\";\n pieces.forEach((piece, i) => {\n if (typeof piece === \"string\") splitMarkers(piece, edge(pieces[i - 1], false), edge(pieces[i + 1], true), items);\n else items.push({ t: \"seg\", seg: piece });\n });\n pairMarkers(items);\n return build(items);\n}\n","import { SPOILER_PLAIN, tokenizeInline } from \"./inline\";\nimport { INVISIBLE, shownUrl } from \"./links\";\nimport type { Atom, Detector, Segment } from \"./types\";\n\nexport interface MdLinkData {\n url: string;\n /** What the author wrote between the brackets, formatting read (no links or other atoms inside). */\n label: Segment[];\n /** True when the label reads as another address than the link's: the bubble shows the address instead. */\n showUrl: boolean;\n}\n\n/** The link's host as a browser reads it: lower case, punycode, without a leading \"www.\". */\nfunction hostOf(url: string): string | null {\n try {\n return new URL(url).hostname.replace(/^www\\./, \"\");\n } catch {\n return null;\n }\n}\n\n/** Something in a label that reads as a web address or a domain: \"ghostly.tools\", \"https://a.example/x\", \"1.2.3.4\". */\nconst ADDRESS = /(?:[a-z][a-z\\d+.-]{0,20}:\\/\\/)?[\\p{L}\\p{N}][\\p{L}\\p{N}-]{0,62}(?:\\.[\\p{L}\\p{N}][\\p{L}\\p{N}-]{0,62}){1,8}/giu;\n/** Ends in a top-level domain (letters), or is an IPv4 address. \"v1.2\", \"3.14\" and \"e.g.\" are not hosts. */\nconst LOOKS_LIKE_HOST = /\\.\\p{L}[\\p{L}\\p{N}-]{1,62}$|^\\d{1,3}(?:\\.\\d{1,3}){3}$/u;\n/** File extensions no top-level domain uses: \"report.pdf\", \"Node.js\" and \"package.json\" are names, not hosts. */\nconst NOT_A_TLD = /\\.(?:[cm]?js|jsx|tsx?|json|css|html?|txt|log|csv|png|jpe?g|gif|svg|webp|toml|ya?ml|lock|wasm|pdf|rb|go)$/i;\n/** Extensions that are country domains too (Moldova, Paraguay…): a file only as a path's last part (\"docs/CHAT.md\"). */\nconst FILE_IN_PATH = /\\.(?:md|py|rs|sh)$/i;\n/**\n * Characters a browser reads as the dot between a host's labels, and ones that only look like it (Unicode's\n * confusables of \".\" and the middle, raised and word-separator dots fonts draw like it). Read before NFKC (\"˙\" would\n * become a space and an accent) and after it (\"・\" becomes \"・\"). The combining dots stand alone, outside the class.\n */\nconst DOTS =\n /[\\u00b7\\u02d9\\u0660\\u06d4\\u06f0\\u0701\\u0702\\u0f0b\\u0f0c\\u1427\\u16eb\\u2022\\u2024\\u2027\\u2219\\u22c5\\u2e30\\u2e31\\u2e33\\u2e3c\\u3002\\u30fb\\u318d\\ua4f8\\ua60e\\ua78f\\uff0e\\uff61\\u{10a50}\\u2981]|\\u0323|\\u{1d16d}/gu;\n\n/**\n * A whole emoji: a keycap (\"1️⃣\"), a flag drawn from tags (🏴 and its tag letters), or pictographs joined by zero-width\n * joiners, each with its variation selector or skin tone (\"❤️\", \"👩🏽💻\"). Their invisible parts are drawn as part of\n * the emoji, so they hide nothing; the same characters anywhere else still count.\n */\nconst EMOJI =\n /[#*0-9]️?⃣|\\u{1f3f4}[\\u{e0020}-\\u{e007e}]+\\u{e007f}|\\p{Extended_Pictographic}(?:[︎️]|\\p{Emoji_Modifier})?(?:\\p{Extended_Pictographic}(?:[︎️]|\\p{Emoji_Modifier})?)*/gu;\n\n/**\n * Whether a link's text would make a reader think it goes somewhere else: it names a host that is not the link's (nor\n * one the link's host sits under), or it holds an invisible or direction character, which can turn \"moc.lapyap\"\n * into \"paypal.com\" on screen. The text is read as a browser would read a host (\"ghostly。tools\" and \"ghostly.tools\"\n * are \"ghostly.tools\"). File names are left alone (\"report.pdf\", \"docs/CHAT.md\"); anything else that reads as a\n * host counts, which errs on the safe side: the bubble shows the address.\n */\nexport function labelMisleads(label: string, url: string): boolean {\n const target = hostOf(url);\n if (!target) return true;\n if (new RegExp(INVISIBLE.source, \"u\").test(label.replace(EMOJI, \"\"))) return true;\n const text = label.replace(DOTS, \".\").normalize(\"NFKC\").replace(DOTS, \".\");\n for (const found of text.matchAll(ADDRESS)) {\n const written = found[0];\n const bare = written.replace(/^[a-z][a-z\\d+.-]*:\\/\\//i, \"\");\n if (bare === written) {\n if (!LOOKS_LIKE_HOST.test(bare) || NOT_A_TLD.test(bare)) continue;\n // \"docs/CHAT.md\": after a path's slash (not the \"//\" of an address).\n const at = found.index;\n if (FILE_IN_PATH.test(bare) && text[at - 1] === \"/\" && at > 1 && !/[/:]/.test(text[at - 2])) continue;\n }\n const host = hostOf(`https://${bare}`);\n if (!host) return true;\n if (host !== target && !target.endsWith(`.${host}`)) return true;\n }\n return false;\n}\n\n/** A label's words without its markers, for the chat list; `revealed` reads a spoiler's words as a tap shows them. */\nfunction labelText(label: Segment[], revealed = false): string {\n return label\n .map((s) => (s.type === \"span\" ? (s.style === \"spoiler\" && !revealed ? SPOILER_PLAIN : labelText(s.children, revealed)) : s.text))\n .join(\"\");\n}\n\n/**\n * `[text](https://…)`: the text as a link, over http(s) only (`[a](javascript:…)` stays text). The address may hold\n * one pair of brackets (\"…/Foo_(bar)\"); both parts are bounded, so the pattern stays linear.\n */\nexport const mdLink: Detector<\"md-link\", MdLinkData> = {\n kind: \"md-link\",\n pattern: /\\[([^[\\]\\n]{1,200})\\]\\((https?:\\/\\/[^\\s()<>]{1,4096}(?:\\([^\\s()<>]{0,256}\\)[^\\s()<>]{0,1024})?)\\)/gi,\n accept(match) {\n const [, text, url] = match;\n if (!text.trim() || !hostOf(url)) return null;\n const label = tokenizeInline(text, []);\n // The written text, and the words the bubble draws: markers can split a host (\"paypal.**com**\") it shows whole.\n const showUrl = labelMisleads(text, url) || labelMisleads(labelText(label, true), url);\n return { data: { url, label, showUrl } };\n },\n plain(atom: Atom<\"md-link\", MdLinkData>) {\n return atom.data.showUrl ? shownUrl(atom.data.url) : labelText(atom.data.label);\n },\n};\n","import { MENTION_EVERYONE, MENTION_LIMITS, type GroupMention } from \"@ghostly/core\";\nimport type { Atom, Detector } from \"./types\";\n\n/*\n * Mentions in a group's composer and bubbles (WISP 902 § Mentions). The composer keeps which member each \"@Name\"\n * it inserted stands for; on send, every place the text still has that token becomes a mention bound to the\n * member's key. A bubble then shows each mention with the member's name as it is now.\n */\n\n/** A member the picker offers: `name` as the group shows them, `tag` a short piece of their key. */\nexport interface MentionCandidate { key: string; name: string; tag: string }\n/**\n * What the composer inserted: `@${label}` for `key` (`MENTION_EVERYONE` for everyone), at `at` (the UTF-16 index of its\n * \"@\" in the field, moved along as the text changes: `moveChosen`). Without `at`, every place the token stands is it.\n */\nexport interface ChosenMention { key: string; label: string; at?: number }\n/** The \"@…\" being typed at the caret: `start` is the \"@\", `end` the caret (UTF-16 indices, as the textarea has them). */\nexport interface MentionQuery { start: number; end: number; query: string }\n/**\n * A mention as a bubble shows it: its place (code points), the name to show, whether it names me, and what the\n * message has at that place (without the \"@\").\n */\nexport interface MentionView { o: number; l: number; key: string; name: string; me: boolean; written?: string }\n\n/** How much of a name the picker is asked about. */\nconst QUERY_CHARS = 32;\n/**\n * A key is matched from this many characters on, by its start or the piece the picker shows: two letters are found\n * somewhere in most 52-character keys, and \"@Bo\" must not offer Carol.\n */\nconst KEY_QUERY_CHARS = 3;\n/** Rows the picker shows. */\nexport const PICKER_ROWS = 8;\n\n/**\n * The \"@…\" the caret is at the end of, or null: an \"@\" at the start of the text or after a space or an opening\n * bracket (so an address like a@b.example is not one), followed by up to 32 characters with no space or \"@\".\n */\nexport function mentionQueryAt(text: string, caret: number): MentionQuery | null {\n const match = /(?:^|[\\s([{\"'])@([^\\s@]{0,32})$/u.exec(text.slice(0, caret));\n if (!match) return null;\n return { start: caret - match[1].length - 1, end: caret, query: match[1].slice(0, QUERY_CHARS) };\n}\n\nconst fold = (s: string) => s.normalize(\"NFD\").replace(/\\p{M}/gu, \"\").toLowerCase();\n\n/**\n * The members that fit what was typed, best first: a name starting with it, then a word of the name starting with\n * it, then a key starting with it or a shown piece of key containing it (three characters or more). An empty query\n * lists everyone, in the order given.\n */\nexport function filterCandidates(candidates: readonly MentionCandidate[], query: string): MentionCandidate[] {\n const q = fold(query);\n if (!q) return candidates.slice(0, PICKER_ROWS);\n const rank = (c: MentionCandidate) => {\n const name = fold(c.name);\n if (name.startsWith(q)) return 0;\n if (name.split(/[\\s._-]+/u).some(word => word.startsWith(q))) return 1;\n return q.length >= KEY_QUERY_CHARS && (c.key.toLowerCase().startsWith(q) || fold(c.tag).includes(q)) ? 2 : 3;\n };\n return candidates.map(c => ({ c, r: rank(c) })).filter(x => x.r < 3).sort((a, b) => a.r - b.r).map(x => x.c).slice(0, PICKER_ROWS);\n}\n\n/** The text with the query replaced by \"@label \" and the caret after the space. */\nexport function insertMention(text: string, query: MentionQuery, label: string): { text: string; caret: number } {\n const token = `@${label} `;\n const after = text.slice(query.end).replace(/^ /, \"\");\n return { text: text.slice(0, query.start) + token + after, caret: query.start + token.length };\n}\n\n/** What a member's token says after the \"@\": their name, with no \"@\" in it and not longer than a mention may be. */\nexport function mentionLabel(name: string): string {\n const clean = name.replace(/@/g, \"\").replace(/\\s+/g, \" \").trim();\n return Array.from(clean).slice(0, MENTION_LIMITS.chars - 1).join(\"\").trim() || \"member\";\n}\n\nconst wordChar = /[\\p{L}\\p{N}_]/u;\n\n/**\n * The chosen mentions of a field whose text went from `before` to `after`, each moved with the text around it: one\n * whose token the change touched is dropped (edited away). `caret`, where the caret is after the change, tells where\n * it was when the same words stand twice (\"@Bob @Bob\" losing one); without it, or when it does not fit, the change is\n * taken as what lies between the text the two have in common at the start and at the end.\n */\nexport function moveChosen(chosen: readonly ChosenMention[], before: string, after: string, caret?: number | null): ChosenMention[] {\n if (before === after || !chosen.some(c => c.at !== undefined)) return [...chosen];\n const grown = after.length - before.length;\n // The change, as [from, to) in `before` replaced by [from, to + grown) in `after`.\n let from: number, to: number;\n const fits = (f: number, t: number) => f >= 0 && t >= f && t <= before.length && t + grown >= f && t + grown <= after.length\n && before.slice(0, f) === after.slice(0, f) && before.slice(t) === after.slice(t + grown);\n const typed = caret ?? -1;\n if (grown >= 0 && fits(typed - grown, typed - grown)) [from, to] = [typed - grown, typed - grown];\n else if (grown < 0 && fits(typed, typed - grown)) [from, to] = [typed, typed - grown];\n else {\n from = 0;\n while (from < before.length && from < after.length && before[from] === after[from]) from++;\n let tail = 0;\n while (tail < before.length - from && tail < after.length - from && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail++;\n to = before.length - tail;\n }\n return chosen.flatMap(c => {\n if (c.at === undefined) return [c];\n const end = c.at + c.label.length + 1;\n if (end <= from) return [c];\n if (c.at >= to) return [{ ...c, at: c.at + grown }];\n return [];\n });\n}\n\n/**\n * The mentions of a text about to be sent (trimmed, as the group sends it), in code points, in order, at most\n * `MENTION_LIMITS.count`: each chosen token that still stands whole at its place (`at`), bound to the member chosen\n * there, so two members who go by one name are each named where they were picked; a choice with no place names every\n * place its token stands that no other choice holds. A token edited away is simply no mention.\n */\nexport function composeMentions(text: string, chosen: readonly ChosenMention[]): GroupMention[] {\n const trimmed = text.trim();\n const lead = text.length - text.trimStart().length;\n const found: { at: number; end: number; key: string }[] = [];\n const whole = (at: number, label: string) => {\n const end = at + label.length + 1;\n return at >= 0 && trimmed.startsWith(`@${label}`, at) && !(end < trimmed.length && wordChar.test(trimmed[end]));\n };\n const take = (at: number, label: string, key: string) => {\n const end = at + label.length + 1;\n if (found.some(f => at < f.end && end > f.at)) return;\n found.push({ at, end, key });\n };\n // Longer tokens first, so \"@Ann Lee\" wins over \"@Ann\" at the same place.\n const byLength = (a: ChosenMention, b: ChosenMention) => b.label.length - a.label.length;\n for (const { key, label, at } of chosen.filter(c => c.at !== undefined).sort(byLength)) {\n if (whole(at! - lead, label)) take(at! - lead, label, key);\n }\n const tokens = [...new Map(chosen.filter(c => c.at === undefined).map(c => [`${c.key}\\n${c.label}`, c])).values()].sort(byLength);\n for (const { key, label } of tokens) {\n const token = `@${label}`;\n for (let at = trimmed.indexOf(token); at !== -1; at = trimmed.indexOf(token, at + 1)) {\n if (whole(at, label)) take(at, label, key);\n }\n }\n const points = (i: number) => Array.from(trimmed.slice(0, i)).length;\n return found.sort((a, b) => a.at - b.at).slice(0, MENTION_LIMITS.count)\n .map(f => ({ k: f.key, o: points(f.at), l: points(f.end) - points(f.at) }));\n}\n\n/*\n * How a bubble draws them, through the rich text parser: a mention is a place in the message (code points), not a\n * pattern in its text, and a detector only sees stretches of text. So before parsing, each mention's place is\n * replaced by a mark of two private-use characters around its index, and the `member-mention` detector turns each mark\n * back into an atom carrying the mention. Formatting around a mention (\"*@Bob*\") still applies.\n */\nconst OPEN = \"\\uE000\", CLOSE = \"\\uE001\";\n\n/** The text with each mention's place marked (the text as it is when it already holds a mark character). */\nexport function markMentions(text: string, mentions: readonly { o: number; l: number }[]): string {\n if (text.includes(OPEN) || text.includes(CLOSE)) return text;\n const points = Array.from(text);\n let out = \"\", at = 0;\n mentions.forEach((m, i) => {\n if (m.o < at || m.o + m.l > points.length) return;\n out += points.slice(at, m.o).join(\"\") + OPEN + i + CLOSE;\n at = m.o + m.l;\n });\n return out + points.slice(at).join(\"\");\n}\n\n/** A marked mention, as an atom carrying how it shows (`ParseContext.mentions`). */\nexport const mention: Detector<\"member-mention\", MentionView> = {\n kind: \"member-mention\",\n pattern: /\\uE000(\\d{1,2})\\uE001/g,\n accept: (match, _text, ctx) => {\n const view = (ctx.mentions as readonly MentionView[] | undefined)?.[Number(match[1])];\n return view ? { data: view } : null;\n },\n plain: (atom: Atom<\"member-mention\", MentionView>) => `@${atom.data.name}`,\n};\n\n/**\n * Whether what a mention covers reads as a name the chip may show instead: the member's name itself, or one word\n * (the name they went by when it was sent). Anything longer stays as written, since the chip would hide it: a\n * mention of \"@Bob - ignore the card, this invoice is fake\" must not read \"@Bob\".\n */\nfunction readsAsName(written: string, name: string): boolean {\n const fold = (s: string) => s.normalize(\"NFC\").toLowerCase();\n return fold(written) === fold(name) || /^[\\p{L}\\p{M}\\p{N}._-]{1,32}$/u.test(written);\n}\n\n/**\n * A message's mentions as its bubble shows them. A member still in the group goes by their name now, where what\n * was written reads as a name (`readsAsName`); one who is gone, or a mention covering more than a name, by what was\n * written. Mine (and everyone, from someone else) are `me`.\n */\nexport function mentionViews(text: string, mentions: readonly GroupMention[] | undefined, members: readonly { key: string; name: string; me: boolean }[], fromMe: boolean): MentionView[] {\n if (!mentions?.length) return [];\n const points = Array.from(text);\n return mentions.map(m => {\n const written = points.slice(m.o + 1, m.o + m.l).join(\"\");\n if (m.k === MENTION_EVERYONE) return { ...m, key: m.k, name: written || \"everyone\", me: !fromMe, written };\n const member = members.find(x => x.key === m.k);\n const name = member?.name && readsAsName(written, member.name) ? member.name : written;\n return { ...m, key: m.k, name, me: !!member?.me, written };\n });\n}\n","import type { Detector } from \"./types\";\n\n/**\n * Times the reader may want in their own zone: an ISO timestamp with its offset (\"2026-09-25T14:00:00Z\",\n * \"2026-09-25 14:00 +02:00\") and a clock time with a named zone (\"at 14:00 UTC\", \"3pm GMT+2\", \"9:30 am EST\").\n * Conservative on purpose: a time with no zone, a bare number, a score (\"3:2\") or a version (\"v1.14:00\") is text.\n * A clock time with no date means that day where the message was written, the day it was sent.\n */\n\n/** Zone abbreviations read the same way everywhere (no CST, IST or BST, which name several zones). Minutes east of UTC. */\nconst ZONES: Record<string, number> = {\n UTC: 0, GMT: 0, Z: 0,\n EST: -300, EDT: -240, MST: -420, MDT: -360, PST: -480, PDT: -420,\n CET: 60, CEST: 120, EET: 120, EEST: 180, BRT: -180, JST: 540, AEST: 600, AEDT: 660,\n};\nconst NAMED = \"UTC|GMT|EST|EDT|MST|MDT|PST|PDT|CET|CEST|EET|EEST|BRT|JST|AEST|AEDT\";\nconst OFFSET = \"[+-]\\\\d{1,2}(?::?\\\\d{2})?\";\n\nconst ISO = `(\\\\d{4})-(\\\\d{2})-(\\\\d{2})[T ](\\\\d{2}):(\\\\d{2})(?::(\\\\d{2})(?:\\\\.\\\\d{1,9})?)?\\\\s?(Z|UTC|GMT|[+-]\\\\d{2}:?\\\\d{2})`;\nconst CLOCK = `(\\\\d{1,2})(?::(\\\\d{2}))?\\\\s?(?:([ap])\\\\.?m\\\\b\\\\.?)?\\\\s?(?:(UTC|GMT)(${OFFSET})?|(${NAMED}))`;\n\nexport interface TimeData {\n /** The moment written, in ms since the epoch. */\n at: number;\n /** Whether the text carried its date; a clock time alone takes the day it was sent. */\n dated: boolean;\n}\n\n/** Whether a moment is one a date can hold (±8.64e15 ms): a peer picks the time a message was sent. */\nconst isMoment = (ms: number) => !Number.isNaN(new Date(ms).getTime());\n\n/** Minutes east of UTC for \"+02:00\", \"-3\", \"+0530\"; null past ±14 h. */\nfunction offsetMinutes(offset: string): number | null {\n const m = /^([+-])(\\d{1,2})(?::?(\\d{2}))?$/.exec(offset);\n if (!m) return null;\n const minutes = Number(m[2]) * 60 + Number(m[3] ?? 0);\n if (Number(m[2]) > 14 || Number(m[3] ?? 0) > 59) return null;\n return m[1] === \"-\" ? -minutes : minutes;\n}\n\nexport const time: Detector<\"time\", TimeData> = {\n kind: \"time\",\n // Not after a word, a digit, a colon, a dot or a slash, and not before one: \"v1.14:00 UTC\" and \"12:00:00:00\" stay text.\n pattern: new RegExp(`(?<![\\\\w:./+-])(?:${ISO}|${CLOCK})(?![\\\\w:+-])`, \"gi\"),\n accept(m, _text, ctx) {\n if (m[1] !== undefined) {\n const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) => Number(m[i] ?? 0));\n const zone = m[7].toUpperCase();\n const offset = zone in ZONES ? ZONES[zone] : offsetMinutes(zone);\n if (offset === null || month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 59) return null;\n const at = Date.UTC(year, month - 1, day, hour, minute, second) - offset * 60_000;\n // February 30th rolls over into March: not a date anyone wrote.\n if (!isMoment(at) || new Date(at + offset * 60_000).getUTCDate() !== day) return null;\n return { data: { at, dated: true } };\n }\n let hour = Number(m[8]);\n const minute = m[9] === undefined ? 0 : Number(m[9]);\n const meridiem = m[10]?.toLowerCase();\n // A bare hour needs am/pm: \"5 UTC\" could be anything.\n if (m[9] === undefined && !meridiem) return null;\n if (minute > 59) return null;\n if (meridiem) {\n if (hour < 1 || hour > 12) return null;\n hour = (hour % 12) + (meridiem === \"p\" ? 12 : 0);\n } else if (hour > 23) return null;\n const offset = m[13] ? ZONES[m[13].toUpperCase()] : m[12] ? offsetMinutes(m[12]) : 0;\n if (offset === null || offset === undefined) return null;\n // The day it was where the message was written. A sending time no date can hold names no day: the time is text.\n const there = new Date((ctx.sentAt ?? Date.now()) + offset * 60_000);\n if (!isMoment(there.getTime())) return null;\n const at = Date.UTC(there.getUTCFullYear(), there.getUTCMonth(), there.getUTCDate(), hour, minute) - offset * 60_000;\n if (!isMoment(at)) return null;\n return { data: { at, dated: false } };\n },\n};\n","import { blob } from \"./blob\";\nimport { link } from \"./links\";\nimport { mdLink } from \"./mdlink\";\nimport { mention } from \"./mentions\";\nimport { time } from \"./time\";\nimport type { Detector } from \"./types\";\n\n/**\n * Every inline detector, in order of precedence: where two match at the same place, the earlier one here wins;\n * otherwise the match that starts first does. A new kind of atom is one line here (its look, if it needs one, is\n * one line in apps/ui/src/components/rich/views.ts; without one it shows as the text it matched).\n */\nexport const DETECTORS: readonly Detector[] = [\n // Before `link`, though it wins by starting first anyway: \"[text](https://…)\" starts at the bracket.\n mdLink,\n link,\n blob,\n time,\n mention,\n];\n","/**\n * What pretty-printing takes on. Re-indenting adds two spaces a level on every line, so deep nesting grows the text\n * with the square of its depth: 8 KiB of `[` and `]` would come out as about 134 million characters. A message past\n * these bounds shows as it was written.\n */\nexport const JSON_LIMITS = {\n /** Characters of the message, trimmed. */\n inputChars: 4 * 1024,\n /** Levels of nesting. */\n depth: 32,\n /** Characters of the pretty-printed text. */\n outputChars: 64 * 1024,\n} as const;\n\n/**\n * A message that is JSON (an object or an array with something in it) shows pretty-printed. The text is\n * re-indented, not parsed and printed again: a number too big for a double, a duplicate key or an escape stays\n * exactly as written. Null for anything else, and for JSON too big or too deep to lay out (`JSON_LIMITS`).\n */\nexport function prettyJson(text: string): string | null {\n const trimmed = text.trim();\n if (trimmed.length > JSON_LIMITS.inputChars) return null;\n const first = trimmed[0];\n const last = trimmed[trimmed.length - 1];\n if (!((first === \"{\" && last === \"}\") || (first === \"[\" && last === \"]\"))) return null;\n // Counted before parsing, so the parser never walks a deep tree either (brackets inside strings count too, which\n // only ever errs towards plain text).\n let depth = 0;\n for (const c of trimmed) {\n if (c === \"{\" || c === \"[\") { if (++depth > JSON_LIMITS.depth) return null; }\n else if (c === \"}\" || c === \"]\") depth--;\n }\n try {\n const value: unknown = JSON.parse(trimmed);\n if (typeof value !== \"object\" || value === null || Object.keys(value).length === 0) return null;\n } catch {\n return null;\n }\n return reindent(trimmed);\n}\n\n/** Valid JSON, one value per line, two spaces a level; strings are copied as they are. Null past the bounds. */\nfunction reindent(json: string): string | null {\n let out = \"\";\n let depth = 0;\n const newline = () => \"\\n\" + \" \".repeat(depth);\n for (let i = 0; i < json.length; i++) {\n const c = json[i];\n if (c === '\"') {\n let j = i + 1;\n while (json[j] !== '\"') j += json[j] === \"\\\\\" ? 2 : 1;\n out += json.slice(i, j + 1);\n i = j;\n } else if (c === \"{\" || c === \"[\") {\n // An empty object or array stays on its line.\n let j = i + 1;\n while (/\\s/.test(json[j])) j++;\n if (json[j] === (c === \"{\" ? \"}\" : \"]\")) { out += c + json[j]; i = j; continue; }\n if (++depth > JSON_LIMITS.depth) return null;\n out += c + newline();\n } else if (c === \"}\" || c === \"]\") {\n depth--;\n out += newline() + c;\n } else if (c === \",\") out += \",\" + newline();\n else if (c === \":\") out += \": \";\n else if (!/\\s/.test(c)) out += c;\n if (out.length > JSON_LIMITS.outputChars) return null;\n }\n return out;\n}\n","import { DETECTORS } from \"./detectors\";\nimport { tokenizeInline } from \"./inline\";\nimport { prettyJson } from \"./json\";\nimport type { Block, Detector, ListBlock, ListItem, ParseContext } from \"./types\";\n\n/** What may follow an opening fence as a language name (\"```ts\", \"```c++\", \"```objective-c\"). */\nconst LANG = /^[A-Za-z][\\w+#.-]{0,19}$/;\n\n/**\n * A list item's line: an indent, then `-`, `*` or `•`, or a number (at most 9 digits) with `.` or `)`, then a space\n * and something. \"1.5 kg\" and \"-5 °C\" are not items: the marker needs the space.\n */\nconst ITEM = /^( {0,6}|\\t)(?:([-*\\u2022])|(\\d{1,9})([.)])) +(?=\\S)/;\n/** How far in an item's line starts for it to sit under the item before it (one level; deeper counts the same). */\nconst NESTED = 2;\n/** A quote's line: `>` then a space, or `>` alone (an empty line of the quote). */\nconst QUOTE = /^ {0,3}>(?: |$)/;\nconst HEADING = /^(#{1,3}) +(?=\\S)/;\nconst BLANK = /^\\s*$/;\n\n/**\n * The lines of text outside code as blocks: lists, quotes and headings where a line starts with one, paragraphs for\n * the rest. Text with none of them is one paragraph, exactly as written. A blank line next to a list, a quote or a\n * heading is the room around it, which the block's own margin gives, so it goes; the line break between them goes\n * too, the way the one before a fence does. Each line is read once here (twice inside a quote), so this stays linear.\n */\nfunction proseBlocks(text: string, detectors: readonly Detector[], ctx: ParseContext, quotes: boolean): Block[] {\n const inline = (s: string) => tokenizeInline(s, detectors, ctx);\n type Unit = { t: \"para\"; lines: string[] } | { t: \"block\"; block: Block } | { t: \"quote\"; lines: string[]; raw: string[] };\n const units: Unit[] = [];\n const lines = text.split(\"\\n\");\n // The list being read, its last item (text still open to continuation lines) and that item's last child.\n let list: ListBlock | null = null;\n let item: { at: ListItem; text: string[] } | null = null;\n let child: { list: ListBlock; at: ListItem; text: string[] } | null = null;\n const closeChild = () => { if (child) { child.at.segments = inline(child.text.join(\"\\n\")); child = null; } };\n const closeItem = () => { closeChild(); if (item) { item.at.segments = inline(item.text.join(\"\\n\")); item = null; } };\n const closeList = () => { closeItem(); list = null; };\n const last = () => units[units.length - 1];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n // One blank line between items of the same list does not end it (\"9. a\", \"\", \"10. b\" is one list).\n if (list && BLANK.test(line)) {\n const next = ITEM.exec(lines[i + 1] ?? \"\");\n if (next && ((next[1] === \"\\t\" ? NESTED : next[1].length) >= NESTED || (next[3] !== undefined) === list.ordered)) continue;\n }\n const m = ITEM.exec(line);\n if (m) {\n const ordered = m[3] !== undefined;\n const at: ListItem = { marker: ordered ? m[3] + m[4] : \"\\u2022\", ...(ordered ? { number: Number(m[3]) } : {}), segments: [], children: [] };\n const body = line.slice(m[0].length);\n const indent = m[1] === \"\\t\" ? NESTED : m[1].length;\n if (list && item && indent >= NESTED) {\n closeChild();\n const kids = item.at.children;\n let under = kids[kids.length - 1];\n if (!under || under.ordered !== ordered) kids.push(under = { type: \"list\", ordered, items: [] });\n under.items.push(at);\n child = { list: under, at, text: [body] };\n continue;\n }\n if (!list || list.ordered !== ordered) {\n closeList();\n list = { type: \"list\", ordered, items: [] };\n units.push({ t: \"block\", block: list });\n }\n closeItem();\n list.items.push(at);\n item = { at, text: [body] };\n continue;\n }\n // An indented line under an item goes on with it, as a line of its own.\n if (item && /^(?: {2}|\\t)/.test(line) && !BLANK.test(line)) {\n (child ?? item).text.push(line.trimStart());\n continue;\n }\n closeList();\n if (quotes && QUOTE.test(line)) {\n const inner = line.replace(/^ {0,3}> ?/, \"\");\n const unit = last();\n if (unit?.t === \"quote\") { unit.lines.push(inner); unit.raw.push(line); }\n else units.push({ t: \"quote\", lines: [inner], raw: [line] });\n continue;\n }\n const h = HEADING.exec(line);\n if (h) {\n units.push({ t: \"block\", block: { type: \"heading\", level: h[1].length as 1 | 2 | 3, segments: inline(line.slice(h[0].length)) } });\n continue;\n }\n const unit = last();\n if (unit?.t === \"para\") unit.lines.push(line);\n else units.push({ t: \"para\", lines: [line] });\n }\n closeList();\n\n // A quote with nothing in it (\">\" alone) is the text it was, one paragraph with the lines around it.\n const merged: Unit[] = [];\n for (const unit of units) {\n const now: Unit = unit.t === \"quote\" && unit.lines.every((l) => BLANK.test(l)) ? { t: \"para\", lines: unit.raw } : unit;\n const before = merged[merged.length - 1];\n if (now.t === \"para\" && before?.t === \"para\") before.lines.push(...now.lines);\n else merged.push(now);\n }\n\n const blocks: Block[] = [];\n merged.forEach((unit, i) => {\n if (unit.t === \"block\") { blocks.push(unit.block); return; }\n if (unit.t === \"quote\") {\n blocks.push({ type: \"quote\", blocks: proseBlocks(unit.lines.join(\"\\n\"), detectors, ctx, false) });\n return;\n }\n let { lines: body } = unit;\n let from = 0;\n let to = body.length;\n if (i > 0) while (from < to && BLANK.test(body[from])) from++;\n if (i < merged.length - 1) while (to > from && BLANK.test(body[to - 1])) to--;\n body = body.slice(from, to);\n const joined = body.join(\"\\n\");\n if (joined) blocks.push({ type: \"paragraph\", segments: inline(joined) });\n });\n return blocks;\n}\n\n/**\n * A message's text as blocks. A message that is JSON is one pretty-printed block. Otherwise a fence (```) at the\n * start of a line opens a code block, with an optional language name after it, and the next ``` closes it; a fence\n * that never closes is text. Everything else is lists, quotes, headings and paragraphs of inline segments\n * (`proseBlocks`, then `tokenizeInline`).\n */\nexport function parseMessage(text: string, ctx: ParseContext = {}, detectors: readonly Detector[] = DETECTORS): Block[] {\n const json = prettyJson(text);\n if (json !== null) return [{ type: \"codeblock\", code: json, lang: \"json\" }];\n\n const blocks: Block[] = [];\n const paragraph = (from: number, to: number) => {\n if (to > from) blocks.push(...proseBlocks(text.slice(from, to), detectors, ctx, true));\n };\n const fence = /(^|\\n)```/g;\n let cursor = 0;\n for (let found = fence.exec(text); found; found = fence.exec(text)) {\n const open = found.index + found[1].length;\n if (open < cursor) continue;\n const lineEnd = text.indexOf(\"\\n\", open);\n // \"```code```\" on one line is inline code, not a block.\n if (lineEnd < 0) break;\n const info = text.slice(open + 3, lineEnd).trim();\n const lang = LANG.test(info) ? info.toLowerCase() : undefined;\n // Without a language name, what follows the fence is the code's first line (the way chat apps write it).\n const start = lang || !info ? lineEnd + 1 : open + 3;\n const close = text.indexOf(\"```\", start);\n // No closing fence anywhere after this one: none of the later ones closes either.\n if (close < 0) break;\n let code = text.slice(start, close);\n if (code.endsWith(\"\\n\")) code = code.slice(0, -1);\n if (!code.trim()) { fence.lastIndex = close; continue; }\n // The line break before the fence belongs to the block.\n paragraph(cursor, found.index);\n blocks.push({ type: \"codeblock\", code, ...(lang ? { lang } : {}) });\n // The next fence may start on the very next line: look from the line break, which the pattern needs.\n fence.lastIndex = close + 3;\n cursor = close + 3;\n if (text[cursor] === \"\\n\") cursor++;\n }\n paragraph(cursor, text.length);\n return blocks;\n}\n","import { parseMessage, prettyJson, type Block, type Segment } from \"./parse\";\nimport type { Language } from \"./settings\";\nimport type { ChatMessage } from \"./types\";\n\n/*\n * Which received messages are translated, and from which language (docs/AUTO-TRANSLATE.md § Source language). Pure:\n * the detector is passed in, so this file decides and never loads it. The detector is unreliable on short or slangy\n * text (\"ok\" is undetermined, \"lol no way 😂\" came out as Volapük), hence the rules: only received text, only what\n * the detector is sure of, never the app's own language, and never a few letters on their own.\n */\n\n/** One of the detector's guesses, best first: `@qvac/langdetect-text`'s `detectMultiple` gives these. */\nexport interface LanguageGuess {\n /** ISO 639-1, or `und` when it cannot tell. */\n code: string;\n probability: number;\n}\n\nexport type DetectLanguages = (text: string) => readonly LanguageGuess[] | Promise<readonly LanguageGuess[]>;\n\nexport interface TranslateWhichOptions {\n /** What received messages are translated into. */\n appLanguage: Language;\n detect: DetectLanguages;\n /** Whether a model exists from `language` (straight into the app's language, or through English). */\n canTranslate: (language: string) => boolean;\n /** The last language the others in this chat wrote with confidence: what a short message is taken to be in. */\n chatLanguage?: string | null;\n}\n\nexport interface TranslateWhich {\n /** The language to translate the message from, or null: it is shown as it was sent. */\n from: string | null;\n /** The message's language when the detector was sure of it, the app's own included: what the chat remembers. */\n detected: string | null;\n}\n\n/** Fewer letters than this, once emoji, links, numbers and mentions are out, and the detector is not asked. */\nexport const MIN_LETTERS = 4;\n/** The detector's top guess below this probability is no answer. */\nexport const MIN_PROBABILITY = 0.5;\n/** How much of a long message the detector reads: its language shows long before, and the cost grows with it. */\nexport const DETECT_CHARS = 2_000;\n\nconst UNDETERMINED = \"und\";\nconst NONE: TranslateWhich = { from: null, detected: null };\n\n/** A run of letters, digits and token characters with a digit in it: a number, a token, an invoice, an address, a code. */\nconst CODE_RUN = /[A-Za-z0-9_+/=:.-]*\\d[A-Za-z0-9_+/=:.-]*|\\p{N}+/gu;\nconst EMOJI = /\\p{Extended_Pictographic}|\\p{Emoji_Modifier}|\\p{Regional_Indicator}||️/gu;\nconst LETTER = /\\p{L}/gu;\n\nfunction segmentsText(segments: readonly Segment[]): string {\n return segments.map((segment) => {\n if (segment.type === \"text\") return segment.text;\n if (segment.type === \"span\") return segmentsText(segment.children);\n // Code, links and the other atoms (long keys, times, mentions) are never translated, so they say nothing of the language.\n return \" \";\n }).join(\"\");\n}\n\nfunction blockText(block: Block): string {\n switch (block.type) {\n case \"codeblock\": return \" \";\n case \"paragraph\":\n case \"heading\": return segmentsText(block.segments);\n case \"quote\": return block.blocks.map(blockText).join(\" \");\n case \"list\": return block.items.map((item) => [segmentsText(item.segments), ...item.children.map(blockText)].join(\" \")).join(\" \");\n }\n}\n\n/**\n * What of `text` is language, as the detector reads it: without code, links, mentions (`mentions`, by their place in\n * code points), numbers and tokens, and emoji; one space between words. A message that is JSON has none.\n */\nexport function detectableText(text: string, mentions: readonly { o: number; l: number }[] = []): string {\n if (prettyJson(text) !== null) return \"\";\n let unmentioned = text;\n if (mentions.length) {\n const points = Array.from(text);\n for (const { o, l } of mentions) points.fill(\" \", o, Math.min(o + l, points.length));\n unmentioned = points.join(\"\");\n }\n return parseMessage(unmentioned).map(blockText).join(\" \")\n .replace(CODE_RUN, \" \")\n .replace(EMOJI, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nconst baseCode = (code: string) => code.toLowerCase().split(/[-_]/)[0];\n\n/**\n * Whether `message` is translated for reading, and from which language. Only text a contact or member sent: never\n * mine, a system line, a file, a payment, a status card or a call line. A short message (under `MIN_LETTERS`) is\n * taken to be in the chat's language, when it has one; anything else in what the detector is sure of. The app's\n * language and a language with no model are shown as they are.\n */\nexport async function translateFrom(\n message: Pick<ChatMessage, \"sender\" | \"text\" | \"file\" | \"paymentId\" | \"card\" | \"callEvent\" | \"systemEvent\" | \"mentions\">,\n { appLanguage, detect, canTranslate, chatLanguage }: TranslateWhichOptions,\n): Promise<TranslateWhich> {\n if (message.sender !== \"peer\") return NONE;\n if (message.file || message.paymentId || message.card || message.callEvent || message.systemEvent) return NONE;\n\n const text = detectableText(message.text, message.mentions);\n const letters = text.match(LETTER)?.length ?? 0;\n if (letters === 0) return NONE;\n const usable = (language: string | null | undefined) =>\n language && language !== UNDETERMINED && language !== appLanguage && canTranslate(language) ? language : null;\n if (letters < MIN_LETTERS) return { from: usable(chatLanguage && baseCode(chatLanguage)), detected: null };\n\n const top = (await detect(text.slice(0, DETECT_CHARS)))[0];\n if (!top || top.probability < MIN_PROBABILITY) return NONE;\n const detected = baseCode(top.code);\n if (detected === UNDETERMINED) return NONE;\n return { from: usable(detected), detected };\n}\n","import { spawn, type ChildProcessByStdio } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\nimport runtimePackage from \"../../../native/translation/package.json\" with { type: \"json\" };\nimport { translateFrom, type DetectLanguages } from \"../../../apps/ui/src/lib/translateWhich\";\nimport { childEnv } from \"./childEnv\";\nimport { CliError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\n\n/**\n * `--translate <lang>` (docs/AUTO-TRANSLATE.md): received messages get `translation: { from, text }`, made on this machine\n * by the translation runtime (native/translation) the Desktop downloads: `bare runtime.mjs <models>`, one JSON line per\n * request. Which messages, and from which language, is the app's rule (translateWhich.ts): only a contact's or a member's\n * text, never mine, and only what the detector is sure of. Nothing is fetched here. A message's text goes to the runtime\n * only, never to stderr: what is said there is the runtime's own word or a path.\n */\n\n/** The runtime this CLI starts, in `<home>/translation-runtime/<version>/`; models in `<home>/translation-models/<pair>/`, as on Desktop. */\nexport const RUNTIME_VERSION: string = runtimePackage.version;\n\nexport function translationPaths(home: string): { runtime: string; models: string } {\n return { runtime: join(home, \"translation-runtime\", RUNTIME_VERSION), models: join(home, \"translation-models\") };\n}\n\n/** `--translate`'s language, checked before anything starts: an ISO 639 code, as the runtime's pairs take. */\nexport function translateTarget(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\" || !/^[a-z]{2,3}$/.test(value)) throw new CliError(\"usage\", `--translate takes a language code (en, pt, es, ...), not ${JSON.stringify(value)}`);\n return value;\n}\n\n/**\n * The language detector (`@qvac/langdetect-text`'s `detectMultiple`), which the rule takes as a parameter. It is not a\n * dependency of the CLI yet: until it is, `--translate` says so once and prints messages as they are.\n */\nexport async function loadDetector(): Promise<DetectLanguages | null> {\n return null;\n}\n\n/** What the CLI prints of a message, as far as translating it goes (views.ts' MessageJson). */\ninterface ShownMessage {\n chat?: string;\n from?: string;\n text?: unknown;\n file?: unknown;\n paymentId?: unknown;\n card?: unknown;\n event?: unknown;\n mentions?: { offset: number; length: number }[];\n translation?: { from: string; text: string };\n}\n\nexport interface Translator {\n /** The message with `translation` when the rule says so and the runtime answered; else the same object. */\n message<T extends ShownMessage>(message: T): Promise<T & Pick<ShownMessage, \"translation\">>;\n /** The event with its message translated (a join notice is the app's line, not the contact's words). */\n event(event: GhostlyEvent): Promise<GhostlyEvent>;\n /** Ends the runtime's input: it unloads and exits. */\n close(): void;\n}\n\nexport interface TranslatorOptions {\n home: string;\n to: string;\n detect: DetectLanguages | null;\n /** One line to stderr. */\n warn: (line: string) => void;\n}\n\n/** `events` and `chat history` with `--translate`: their events or messages one by one, oldest first, as `listen` takes them. */\nexport async function translateAnswer(answer: Record<string, unknown>, translator: Translator): Promise<Record<string, unknown>> {\n const each = async <T,>(list: T[], one: (item: T) => Promise<T>) => { const out: T[] = []; for (const item of list) out.push(await one(item)); return out; };\n if (Array.isArray(answer.events)) return { ...answer, events: await each(answer.events as GhostlyEvent[], translator.event) };\n if (Array.isArray(answer.messages)) return { ...answer, messages: await each(answer.messages as ShownMessage[], translator.message) };\n return answer;\n}\n\ntype Answer = { id?: unknown; texts?: unknown; error?: unknown } | null;\n\n/** A translator, or null when the detector or the runtime is not there: said once, and messages stay as they are. */\nexport function openTranslator({ home, to, detect, warn }: TranslatorOptions): Translator | null {\n const { runtime, models } = translationPaths(home);\n const bare = join(runtime, process.platform === \"win32\" ? \"bare.exe\" : \"bare\"), script = join(runtime, \"runtime.mjs\");\n // The detector first: without it no runtime or model helps, so nobody is sent to unpack one for nothing.\n if (!detect) {\n warn(\"ghostly: --translate cannot translate in this build of the CLI (it has no language detector yet): messages are printed untranslated\");\n return null;\n }\n if (!existsSync(bare) || !existsSync(script)) {\n warn(`ghostly: no translation runtime in ${runtime}: messages are printed untranslated. Unpack runtime ${RUNTIME_VERSION} there and a model in ${join(models, \"<from>-<to>\")}`);\n return null;\n }\n\n let child: ChildProcessByStdio<Writable, Readable, null> | null = null, next = 0, closed = false, stopped = false;\n const waiting = new Map<number, (answer: Answer) => void>();\n const said = new Set<string>();\n const kill = () => child?.kill();\n\n // Started at the first message to translate, and kept for the ones after it (a model loads once).\n const start = () => {\n const started = spawn(bare, [script, models], { stdio: [\"pipe\", \"pipe\", \"ignore\"], env: childEnv() });\n started.stdin.on(\"error\", () => {});\n createInterface({ input: started.stdout }).on(\"line\", (line) => {\n let answer: Answer;\n try { answer = JSON.parse(line) as Answer; } catch { return; }\n const id = answer?.id as number, done = waiting.get(id);\n waiting.delete(id);\n done?.(answer);\n });\n const gone = (why: string) => {\n if (stopped) return;\n stopped = true;\n child = null;\n if (!closed) warn(`ghostly: the translation runtime stopped (${why}): messages are printed untranslated from here`);\n for (const done of waiting.values()) done(null);\n waiting.clear();\n };\n started.on(\"error\", (error) => gone(error.message));\n started.on(\"exit\", (code, signal) => gone(signal ?? `exit ${code}`));\n process.once(\"exit\", kill);\n return started;\n };\n\n const ask = (pair: string, text: string) => new Promise<string | null>((resolve) => {\n if (closed || stopped) return resolve(null);\n child ??= start();\n const id = ++next;\n waiting.set(id, (answer) => {\n const texts = answer?.texts;\n if (Array.isArray(texts) && typeof texts[0] === \"string\") return resolve(texts[0]);\n // The runtime's errors never carry the text (\"Translation model not downloaded\"): said once per pair.\n if (typeof answer?.error === \"string\" && !said.has(pair)) { said.add(pair); warn(`ghostly: no translation ${pair}: ${answer.error}`); }\n resolve(null);\n });\n child.stdin.write(JSON.stringify({ id, op: \"translate\", pair, texts: [text] }) + \"\\n\");\n });\n\n const has = (pair: string) => existsSync(join(models, pair));\n // Straight into `to`, or through English: the runtime chains es-en and en-pt itself for es-pt.\n const canTranslate = (from: string) => has(`${from}-${to}`) || (from !== \"en\" && to !== \"en\" && has(`${from}-en`) && has(`en-${to}`));\n /** Per chat or group, the last language the others wrote with confidence: a short message is taken to be in it. */\n const languages = new Map<string, string>();\n\n async function message<T extends ShownMessage>(shown: T): Promise<T & Pick<ShownMessage, \"translation\">> {\n if (typeof shown?.text !== \"string\") return shown;\n const place = shown.chat ?? \"\";\n let which: Awaited<ReturnType<typeof translateFrom>>;\n try {\n which = await translateFrom({\n sender: shown.from === \"peer\" ? \"peer\" : \"me\", text: shown.text,\n file: shown.file, paymentId: shown.paymentId, card: shown.card, systemEvent: shown.event,\n mentions: shown.mentions?.map((m) => ({ o: m.offset, l: m.length })),\n } as unknown as Parameters<typeof translateFrom>[0], { appLanguage: to as Parameters<typeof translateFrom>[1][\"appLanguage\"], detect: detect!, canTranslate, chatLanguage: languages.get(place) });\n } catch { return shown; }\n const { from, detected } = which;\n if (detected) languages.set(place, detected);\n if (!from) return shown;\n const text = await ask(`${from}-${to}`, shown.text);\n // The same words back (\"ok\" taken as the chat's Portuguese) are no translation.\n return text === null || text.trim() === shown.text.trim() ? shown : { ...shown, translation: { from, text } };\n }\n\n return {\n message,\n async event(event) {\n const shown = event.message as ShownMessage | undefined;\n if (!shown || typeof shown !== \"object\" || event.type === \"chat.joined\") return event;\n const translated = await message(shown);\n return translated === shown ? event : { ...event, message: translated };\n },\n close() {\n closed = true;\n process.off(\"exit\", kill);\n child?.stdin.end();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;ACUA,IAAa,OAA+B;CAC1C,MAAM;CACN,SAAS,IAAI,OAAO,uEAAgF,GAAG;CACvG,eAAe,EAAE,MAAM,KAAK;CAC5B,QAAQ,SAA6B,GAAG,KAAK,KAAK,MAAM,GAAG,EAAE,EAAE;AACjE;;;ACZA,IAAM,UAAkC;CAAE,KAAK;CAAK,KAAK;CAAK,KAAK;AAAI;;;;;;;AAQvE,SAAgB,QAAQ,OAAuB;CAC7C,MAAM,MAAM,SAAS,KAAK;CAC1B,MAAM,QAAgC;EAAE,KAAK;EAAG,KAAK;EAAG,KAAK;EAAG,KAAK;EAAG,KAAK;EAAG,KAAK;CAAE;CACvF,KAAK,MAAM,KAAK,KAAK,IAAI,KAAK,OAAO,MAAM,EAAE;CAC7C,IAAI,MAAM,IAAI;CACd,OAAO,MAAM,GAAG;EACd,MAAM,OAAO,IAAI,MAAM;EACvB,MAAM,SAAS,QAAQ;EACvB,MAAM,OAAO,SAAS,KAAK,GAAG;EAC9B,IAAI,MAAM,OAAO;OACZ,IAAI,cAAc,KAAK,IAAI,KAAM,UAAU,MAAM,QAAQ,MAAM,SAAU;GAC5E,IAAI,QAAQ,MAAM,KAAK;GACvB;EACF,OAAO,KAAK,SAAS,OAAO,SAAS,QAAQ,IAAI,MAAM,OAAO,MAAM,OAAO;OACtE;CACP;CACA,OAAO,IAAI,MAAM,GAAG,GAAG;AACzB;;;;;;;;AASA,IAAa,YACX;;;;;;;;;AAUF,SAAgB,SAAS,KAAqB;CAC5C,IAAI;CACJ,IAAI;EAAE,SAAS,IAAI,IAAI,GAAG;CAAG,QAAQ;EAAE,OAAO,IAAI,QAAQ,WAAW,EAAE;CAAG;CAC1E,IAAI,OAAO,YAAY,OAAO,UAAU;EACtC,OAAO,WAAW;EAClB,OAA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AAQ,KAAK,KAAK,MAAM,MAAM,KAAK,KAAK,IAAI,QAAQ;GAAE,GAAG;GAAO,aAAa;IAAE;IAAM;GAAK;EAAE;CAC9G;CAEA,OAAO;EACL;EACA,MAAM,MAAM,OAAO;GACjB,MAAM,QAAQ,MAAM;GACpB,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,SAAS,eAAe,OAAO;GAChF,MAAM,aAAa,MAAM,QAAQ,KAAK;GACtC,OAAO,eAAe,QAAQ,QAAQ;IAAE,GAAG;IAAO,SAAS;GAAW;EACxE;EACA,QAAQ;GACN,SAAS;GACT,QAAQ,IAAI,QAAQ,IAAI;GACxB,OAAO,MAAM,IAAI;EACnB;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as sealSeed, n as rpcHost, o as unsealSeed, t as networkReason } from "./networkReason-
|
|
1
|
+
import { an as SEPOLIA_TEST_USDT_FAUCET, in as SEPOLIA_TEST_USDT, mn as validatePaymentTarget, on as TEST_USDT_FAUCET_AMOUNT, or as engineError, rn as PaymentPreflightError, sn as USDT_PUBLIC_RPC, tn as EVM_TEST_CHAINS } from "./src-DJe-OYxd.js";
|
|
2
|
+
import { a as sealSeed, n as rpcHost, o as unsealSeed, t as networkReason } from "./networkReason-BbQW1Xpc.js";
|
|
3
3
|
import { mnemonicToSeedSync } from "@scure/bip39";
|
|
4
4
|
import WalletManagerEvm from "@tetherto/wdk-wallet-evm";
|
|
5
5
|
import { Interface, Transaction, getAddress, keccak256 } from "ethers";
|
|
@@ -410,4 +410,4 @@ var UsdtAdapter = class UsdtAdapter {
|
|
|
410
410
|
//#endregion
|
|
411
411
|
export { UsdtAdapter, wireProvider };
|
|
412
412
|
|
|
413
|
-
//# sourceMappingURL=usdt-
|
|
413
|
+
//# sourceMappingURL=usdt-DI51znt-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usdt-CSU5KzTV.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/usdt.ts"],"sourcesContent":["import { mnemonicToSeedSync } from '@scure/bip39';\nimport WalletManagerEvm, { type WalletAccountEvm } from '@tetherto/wdk-wallet-evm';\nimport { Interface, Transaction, getAddress, keccak256 } from 'ethers';\nimport { ETHEREUM_USDT, EVM_TEST_CHAINS, USDT_PUBLIC_RPC, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, TEST_USDT_FAUCET_AMOUNT, PaymentPreflightError, engineError, validatePaymentTarget, type PaymentAdapter, type PaymentExecution, type PaymentReview, type PaymentTarget } from '@ghostly/core';\nimport { sealSeed, unsealSeed, type EncryptedSeed } from './persistence';\nimport { networkReason, rpcHost } from './networkReason';\n\nexport interface UsdtConfig {\n network: 'ethereum' | 'sepolia' | 'evm-local';\n provider: string;\n chainId: 1 | 11155111 | 31337;\n token: string;\n decimals: number;\n codeHash: string;\n}\nexport interface UsdtPrepared {\n from: string; to: string; data: string; value: string; chainId: number; nonce: number;\n gasLimit: string; maxFeePerGas: string; maxPriorityFeePerGas: string;\n signed?: EncryptedSeed; hash?: string;\n}\nconst faucet = new Interface(['function mint(address token,address to,uint256 amount) returns (uint256)']);\nconst erc20 = new Interface(['function decimals() view returns(uint8)', 'function balanceOf(address) view returns(uint256)', 'function transfer(address,uint256) returns(bool)', 'event Transfer(address indexed from,address indexed to,uint256 value)']);\nconst same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\nconst CONFIRMATIONS = 2;\n/** The JSON-RPC methods that only read: asked again once when they fail (see `UsdtAdapter.rpc`). */\nconst RETRIED_READS = new Set(['eth_chainId', 'eth_getCode', 'eth_call', 'eth_getBalance', 'eth_blockNumber', 'eth_getLogs', 'eth_getTransactionCount', 'eth_estimateGas', 'eth_getBlockByNumber', 'eth_maxPriorityFeePerGas', 'eth_gasPrice', 'eth_feeHistory', 'eth_getTransactionByHash', 'eth_getTransactionReceipt']);\nconst RETRY_AFTER_MS = 1000;\n/** Failures that would fail the same way again at once: not retried. */\nconst FINAL = new WeakSet<object>();\nconst timedOut = (error: unknown) => error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');\n\n/**\n * The `provider` a request carries to the contact. Which RPC pays is the payer's own choice, so it names none of\n * this wallet's: a typed RPC URL may hold an API key (`/v3/<key>`), and every contact would read it. Older apps\n * require a URL here and pay only when it equals their own RPC, so it is the chain's public RPC (the default both\n * start with), and a local test chain's origin, without its path.\n */\nexport function wireProvider(config: Pick<UsdtConfig, 'network' | 'provider'>): string {\n return config.network === 'evm-local' ? new URL(config.provider).origin : USDT_PUBLIC_RPC[config.network];\n}\n\n/** WDK signs locally. Every network call uses the configured RPC, never a peer-supplied URL. */\nexport class UsdtAdapter implements PaymentAdapter<UsdtPrepared> {\n readonly method = 'usdt' as const;\n private manager?: WalletManagerEvm;\n private account?: WalletAccountEvm;\n private mnemonic = '';\n private nextId = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private constructor(readonly config: UsdtConfig) {}\n\n static async inspect(config: Omit<UsdtConfig, 'decimals' | 'codeHash'>): Promise<UsdtConfig> {\n if (config.network === 'ethereum' ? config.chainId !== 1 || !same(config.token, ETHEREUM_USDT) : !(config.network in EVM_TEST_CHAINS) || config.chainId !== EVM_TEST_CHAINS[config.network]) throw new Error('Unsupported USDT network or contract');\n const token = getAddress(config.token);\n const url = new URL(config.provider);\n if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) throw new Error('Use HTTPS or a loopback test RPC');\n const adapter = new UsdtAdapter({...config, token, decimals: 6, codeHash: ''});\n await adapter.chain();\n const code = await adapter.rpc<string>('eth_getCode', [token, 'latest']);\n if (code === '0x') throw new Error('No token contract exists on this chain');\n const result = await adapter.rpc<string>('eth_call', [{to: token, data: erc20.encodeFunctionData('decimals')}, 'latest']);\n const decimals = Number(erc20.decodeFunctionResult('decimals', result)[0]);\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18 || (config.chainId === 1 && decimals !== 6)) throw new Error('Unexpected token decimals');\n return {...config, token, decimals, codeHash: keccak256(code)};\n }\n static async connect(config: UsdtConfig, mnemonic: string): Promise<UsdtAdapter> {\n const inspected = await UsdtAdapter.inspect(config);\n if (inspected.decimals !== config.decimals || inspected.codeHash !== config.codeHash) throw new Error('Token metadata changed; do not use this wallet configuration');\n const adapter = new UsdtAdapter(config);\n adapter.mnemonic = mnemonic;\n // Pass standard BIP-39 seed bytes: WDK's string helper assumes a Node Buffer global.\n const seed = mnemonicToSeedSync(mnemonic);\n try { adapter.manager = new WalletManagerEvm(seed, {provider: {request: ({method, params}) => adapter.rpc(method, params as unknown[] ?? [])}, chainId: config.chainId}); } finally { seed.fill(0); }\n adapter.account = await adapter.manager.getAccount(0);\n return adapter;\n }\n /**\n * A read that fails is asked again, once, a moment later: a public RPC drops a request now and then, and a chain that\n * just made a block can refuse a read of \"latest\" it no longer holds. Without it a network switch, a restore or New\n * gave up on the first such answer. Never a broadcast or anything else that writes, nor a request that did not answer\n * in time (the person would wait twice as long), nor one the server refused as such (4xx).\n */\n async rpc<T>(method: string, params: unknown[] = []): Promise<T> {\n try { return await this.ask<T>(method, params); }\n catch (error) {\n if (!RETRIED_READS.has(method) || FINAL.has(error as object)) throw error;\n await new Promise((resolve) => setTimeout(resolve, RETRY_AFTER_MS));\n return this.ask<T>(method, params);\n }\n }\n private async ask<T>(method: string, params: unknown[]): Promise<T> {\n let response: Response;\n // The browser's words for a request that got no answer (\"Fetch is aborted\") say nothing: the RPC's host does.\n try { response = await fetch(this.config.provider, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({jsonrpc:'2.0',id:++this.nextId,method,params}), signal:AbortSignal.timeout(15000)}); }\n catch (error) {\n const reason = networkReason(error, rpcHost(this.config.provider));\n const thrown = reason ? Object.assign(new Error(reason), {cause: error}) : error;\n if (timedOut(error) && thrown && typeof thrown === 'object') FINAL.add(thrown);\n throw thrown;\n }\n if (!response.ok) { const error = engineError('usdtRpcUnavailable'); if (response.status !== 429 && response.status < 500) FINAL.add(error); throw error; }\n const result = await response.json();\n if (result.error || !Object.prototype.hasOwnProperty.call(result, 'result')) throw new Error('USDT RPC rejected the operation');\n return result.result as T;\n }\n private async chain() {\n if (BigInt(await this.rpc<string>('eth_chainId')) !== BigInt(this.config.chainId)) throw new Error('RPC chain does not match this wallet');\n }\n private async assertToken() {\n await this.chain();\n const code = await this.rpc<string>('eth_getCode', [this.config.token, 'latest']);\n if (code === '0x' || keccak256(code) !== this.config.codeHash) throw new Error('Token contract changed');\n }\n /**\n * Sepolia only: asks Aave's public faucet for test USDT, to this wallet, paid with its own test ETH.\n * Everything is fixed here (chain, contract, token, amount, recipient): nothing comes from outside.\n */\n mintTestTokens(): Promise<string> { return this.serial(async () => {\n if (this.config.chainId !== EVM_TEST_CHAINS.sepolia || !same(this.config.token, SEPOLIA_TEST_USDT)) throw new Error('Test USDT comes from a faucet on Sepolia only');\n await this.chain();\n const account = this.current(), from = await account.getAddress();\n const data = faucet.encodeFunctionData('mint', [SEPOLIA_TEST_USDT, from, BigInt(TEST_USDT_FAUCET_AMOUNT)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount', [from, 'pending'])));\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas', [{ from, to: SEPOLIA_TEST_USDT_FAUCET, data, value: '0x0' }]));\n const block = await this.rpc<{ baseFeePerGas?: string }>('eth_getBlockByNumber', ['latest', false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFeePerGas = BigInt(block.baseFeePerGas) * 2n + priority, gasLimit = (estimate * 120n + 99n) / 100n;\n if (BigInt((await this.balances()).gasBalance) < gasLimit * maxFeePerGas) throw engineError('usdtNeedsSepoliaGas');\n const raw = await account.signTransaction({ type: 2, to: SEPOLIA_TEST_USDT_FAUCET, data, value: 0n, chainId: this.config.chainId, nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas: priority });\n await account.sendTransaction(raw);\n return Transaction.from(raw).hash!;\n }); }\n private current(): WalletAccountEvm { if (!this.account) throw new Error('Unlock the USDT wallet first'); return this.account; }\n address() { return this.current().getAddress(); }\n /**\n * The token and gas balances. The chain and the contract are not asked again here: `connect` checked them, and every\n * payment does before it signs. The wallet reads this every 8 s, and the contract's whole code was most of each read.\n */\n async balances() {\n const address = await this.address();\n const [token, gas] = await Promise.all([this.rpc<string>('eth_call',[{to:this.config.token,data:erc20.encodeFunctionData('balanceOf',[address])},'latest']),this.rpc<string>('eth_getBalance',[address,'pending'])]);\n return {balance:erc20.decodeFunctionResult('balanceOf',token)[0].toString(),gasBalance:BigInt(gas).toString()};\n }\n async target(): Promise<PaymentTarget> {\n const now = Date.now();\n return {method:'usdt',network:this.config.network,provider:wireProvider(this.config),asset:this.config.chainId === 1 ? 'USDT':'TEST-USDT',unit:'token-base',address:await this.address(),chainId:this.config.chainId,token:this.config.token,decimals:this.config.decimals,issuedAt:now,expiresAt:now+15*60*1000};\n }\n /** The request is for this wallet's token on its chain. Its `provider` is not compared: this wallet's own RPC pays. */\n private matches(target: PaymentTarget) {\n validatePaymentTarget(target);\n if (target.method !== 'usdt' || target.network !== this.config.network || target.chainId !== this.config.chainId || !same(target.token!,this.config.token) || target.decimals !== this.config.decimals) throw new Error('Request does not match the configured token and network');\n }\n prepare(target: PaymentTarget, amount: number, feeCap: number) { return this.serial(async () => {\n this.matches(target);\n await this.assertToken();\n const from = await this.address(), to = this.config.token;\n if (same(target.address, from) || same(target.address, to)) throw new Error('Choose a different recipient address');\n const {balance,gasBalance} = await this.balances();\n if (BigInt(balance) < BigInt(amount)) throw engineError('usdtNotEnoughTokens');\n const data = erc20.encodeFunctionData('transfer', [getAddress(target.address),BigInt(amount)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[from,'pending'])));\n if (!Number.isSafeInteger(nonce)) throw new Error('Invalid account nonce');\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas',[{from,to,data,value:'0x0'}]));\n const block = await this.rpc<{baseFeePerGas?:string}>('eth_getBlockByNumber',['latest',false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFee = BigInt(block.baseFeePerGas)*2n + priority;\n const gasLimit = (estimate*120n+99n)/100n;\n const maximum = gasLimit*maxFee;\n if (maximum > BigInt(feeCap) || maximum > BigInt(Number.MAX_SAFE_INTEGER)) throw engineError('usdtGasAboveLimit');\n if (BigInt(gasBalance) < maximum) throw engineError('usdtNotEnoughGas');\n const prepared:UsdtPrepared = {from,to,data,value:'0',chainId:this.config.chainId,nonce,gasLimit:gasLimit.toString(),maxFeePerGas:maxFee.toString(),maxPriorityFeePerGas:priority.toString()};\n return {fee:Number(maximum),prepared,evm:{from,nonce,gasLimit:prepared.gasLimit,maxFeePerGas:prepared.maxFeePerGas,maxPriorityFeePerGas:prepared.maxPriorityFeePerGas,confirmations:CONFIRMATIONS}};\n }); }\n private verifyPrepared(review: PaymentReview, tx: UsdtPrepared) {\n if (tx.chainId !== this.config.chainId || !same(tx.to,this.config.token) || tx.value !== '0' || tx.data !== erc20.encodeFunctionData('transfer',[getAddress(review.address),BigInt(review.amount)]) || BigInt(tx.gasLimit)*BigInt(tx.maxFeePerGas) !== BigInt(review.fee) || review.fee > review.feeCap || tx.nonce !== review.evm?.nonce || !same(tx.from,review.evm?.from ?? '')) throw new Error('Transaction no longer matches the approved review');\n }\n private verifySigned(raw: string, saved: UsdtPrepared) {\n const tx = Transaction.from(raw);\n if (!tx.hash || !tx.from || !same(tx.from,saved.from) || tx.chainId !== BigInt(saved.chainId) || !tx.to || !same(tx.to,saved.to) || tx.data !== saved.data || tx.value !== 0n || tx.nonce !== saved.nonce || tx.gasLimit !== BigInt(saved.gasLimit) || tx.maxFeePerGas !== BigInt(saved.maxFeePerGas) || tx.maxPriorityFeePerGas !== BigInt(saved.maxPriorityFeePerGas)) throw new Error('Signature does not match the approved transaction');\n return tx.hash;\n }\n execute(review: PaymentReview, prepared: UsdtPrepared, persist?:()=>Promise<void>) { return this.serial(async () => {\n let account:WalletAccountEvm;\n try {\n this.matches(review); this.verifyPrepared(review,prepared);\n await this.assertToken(); account=this.current();\n if (!same(await account.getAddress(),prepared.from)) throw new Error('Wrong wallet');\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce !== prepared.nonce) throw new Error('Account nonce changed. Create a new review');\n const balances = await this.balances();\n if (BigInt(balances.balance)<BigInt(review.amount) || BigInt(balances.gasBalance)<BigInt(review.fee)) throw new Error('Token or gas balance changed. Create a new review');\n if (!persist) throw new Error('Durable payment journal required');\n } catch (error) { throw new PaymentPreflightError(error instanceof Error ? error.message : 'Could not validate payment'); }\n const raw = await account.signTransaction({type:2,to:prepared.to,data:prepared.data,value:0n,chainId:prepared.chainId,nonce:prepared.nonce,gasLimit:BigInt(prepared.gasLimit),maxFeePerGas:BigInt(prepared.maxFeePerGas),maxPriorityFeePerGas:BigInt(prepared.maxPriorityFeePerGas)});\n prepared.hash = this.verifySigned(raw,prepared);\n prepared.signed = await sealSeed(raw,this.mnemonic);\n await persist!(); // Nothing may broadcast before the encrypted bytes are durable.\n await account.sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n reconcile(review: PaymentReview, prepared: UsdtPrepared) { return this.serial(async () => {\n await this.assertToken(); this.verifyPrepared(review,prepared);\n if (!prepared.signed || !prepared.hash) return {settled:false,failed:true,error:'No signed transaction was submitted. Create a new review.'};\n const result = await this.receipt(prepared.hash,review,prepared.from);\n if (result.settled || result.failed || result.pending) return result;\n // An uncertain network response permits only replay of exactly the saved bytes.\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce > prepared.nonce) return result;\n const raw = await unsealSeed(prepared.signed,this.mnemonic);\n if (this.verifySigned(raw,prepared) !== prepared.hash || !same(await this.address(),prepared.from)) throw new Error('Recovery wallet mismatch');\n await this.current().sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n async receipt(hash: string, target: PaymentTarget & {amount:number}, expectedFrom?:string): Promise<PaymentExecution> {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash) || target.chainId !== this.config.chainId || !same(target.token ?? '',this.config.token) || target.decimals !== this.config.decimals) throw new Error('Invalid receipt target');\n await this.assertToken();\n const tx = await this.rpc<{from:string;to:string;input:string;value:string;nonce:string}|null>('eth_getTransactionByHash',[hash]);\n if (!tx) return {txid:hash,settled:false};\n if (!same(tx.to,this.config.token) || (expectedFrom && !same(tx.from,expectedFrom)) || BigInt(tx.value)!==0n || tx.input !== erc20.encodeFunctionData('transfer',[getAddress(target.address),BigInt(target.amount)])) throw new Error('Transaction is not the requested token transfer');\n const receipt = await this.rpc<{status:string;blockNumber:string;blockHash:string;logs:Array<{address:string;topics:string[];data:string}>}|null>('eth_getTransactionReceipt',[hash]);\n if (!receipt) return {txid:hash,settled:false,pending:true};\n const block = await this.rpc<{hash:string;timestamp:string}>('eth_getBlockByNumber',[receipt.blockNumber,false]);\n if (!block || block.hash !== receipt.blockHash || BigInt(block.timestamp)*1000n < BigInt((target.issuedAt ?? 0)-1000)) return {txid:hash,settled:false};\n const height = BigInt(await this.rpc<string>('eth_blockNumber'));\n if (height-BigInt(receipt.blockNumber)+1n < BigInt(CONFIRMATIONS)) return {txid:hash,settled:false,pending:true};\n if (BigInt(receipt.status)!==1n) return {txid:hash,settled:false,failed:true,error:'Transaction reverted. Tokens were not sent; gas was spent.'};\n const transfer = receipt.logs.some(log=>{\n if (!same(log.address,this.config.token)) return false;\n try {const event=erc20.parseLog(log);return event?.name==='Transfer' && same(event.args[0],tx.from) && same(event.args[1],target.address) && event.args[2]===BigInt(target.amount);} catch {return false;}\n });\n if (!transfer) throw new Error('Receipt has no matching token Transfer');\n return {txid:hash,settled:true};\n }\n async dispose() { await this.queue.catch(()=>{}); this.account=undefined;this.manager?.dispose();this.manager=undefined;this.mnemonic=''; }\n private serial<T>(work:()=>Promise<T>):Promise<T> { const operation=this.queue.then(work,work);this.queue=operation.catch(()=>{});return operation; }\n}\n"],"mappings":";;;;;;AAoBA,IAAM,SAAS,IAAI,UAAU,CAAC,0EAA0E,CAAC;AACzG,IAAM,QAAQ,IAAI,UAAU;CAAC;CAA2C;CAAqD;CAAoD;AAAuE,CAAC;AACzP,IAAM,QAAQ,GAAW,MAAc,EAAE,YAAY,MAAM,EAAE,YAAY;AACzE,IAAM,gBAAgB;;AAEtB,IAAM,gCAAgB,IAAI,IAAI;CAAC;CAAe;CAAe;CAAY;CAAkB;CAAmB;CAAe;CAA2B;CAAmB;CAAwB;CAA4B;CAAgB;CAAkB;CAA4B;AAA2B,CAAC;AACzT,IAAM,iBAAiB;;AAEvB,IAAM,wBAAQ,IAAI,QAAgB;AAClC,IAAM,YAAY,UAAmB,iBAAiB,UAAU,MAAM,SAAS,gBAAgB,MAAM,SAAS;;;;;;;AAQ9G,SAAgB,aAAa,QAA0D;CACrF,OAAO,OAAO,YAAY,cAAc,IAAI,IAAI,OAAO,QAAQ,CAAC,CAAC,SAAS,gBAAgB,OAAO;AACnG;;AAGA,IAAa,cAAb,MAAa,YAAoD;CAOlC;CAN7B,SAAkB;CAClB;CACA;CACA,WAAmB;CACnB,SAAiB;CACjB,QAAkC,QAAQ,QAAQ;CAClD,YAAoB,QAA6B;EAApB,KAAA,SAAA;CAAqB;CAElD,aAAa,QAAQ,QAAwE;EAC3F,IAAI,OAAO,YAAY,aAAa,OAAO,YAAY,KAAK,CAAC,KAAK,OAAO,OAAA,4CAAoB,IAAI,EAAE,OAAO,WAAW,oBAAoB,OAAO,YAAY,gBAAgB,OAAO,UAAU,MAAM,IAAI,MAAM,sCAAsC;EACnP,MAAM,QAAQ,WAAW,OAAO,KAAK;EACrC,MAAM,MAAM,IAAI,IAAI,OAAO,QAAQ;EACnC,IAAI,IAAI,YAAY,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AI,KAAK,KAAK,MAAM,KAAK,IAAG,OAAO,OAAO,KAAK,MAAM,KAAK,OAAK,OAAO,OAAO,MAAM;GAAE,QAAQ;IAAC,OAAO;GAAM;EAC3M,CACK,GAAU,MAAM,IAAI,MAAM,wCAAwC;EACvE,OAAO;GAAC,MAAK;GAAK,SAAQ;EAAI;CAChC;CACA,MAAM,UAAU;EAAE,MAAM,KAAK,MAAM,YAAU,CAAC,CAAC;EAAG,KAAK,UAAQ,KAAA;EAAU,KAAK,SAAS,QAAQ;EAAE,KAAK,UAAQ,KAAA;EAAU,KAAK,WAAS;CAAI;CAC1I,OAAkB,MAAgC;EAAE,MAAM,YAAU,KAAK,MAAM,KAAK,MAAK,IAAI;EAAE,KAAK,QAAM,UAAU,YAAU,CAAC,CAAC;EAAE,OAAO;CAAW;AACtJ"}
|
|
1
|
+
{"version":3,"file":"usdt-DI51znt-.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/usdt.ts"],"sourcesContent":["import { mnemonicToSeedSync } from '@scure/bip39';\nimport WalletManagerEvm, { type WalletAccountEvm } from '@tetherto/wdk-wallet-evm';\nimport { Interface, Transaction, getAddress, keccak256 } from 'ethers';\nimport { ETHEREUM_USDT, EVM_TEST_CHAINS, USDT_PUBLIC_RPC, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, TEST_USDT_FAUCET_AMOUNT, PaymentPreflightError, engineError, validatePaymentTarget, type PaymentAdapter, type PaymentExecution, type PaymentReview, type PaymentTarget } from '@ghostly/core';\nimport { sealSeed, unsealSeed, type EncryptedSeed } from './persistence';\nimport { networkReason, rpcHost } from './networkReason';\n\nexport interface UsdtConfig {\n network: 'ethereum' | 'sepolia' | 'evm-local';\n provider: string;\n chainId: 1 | 11155111 | 31337;\n token: string;\n decimals: number;\n codeHash: string;\n}\nexport interface UsdtPrepared {\n from: string; to: string; data: string; value: string; chainId: number; nonce: number;\n gasLimit: string; maxFeePerGas: string; maxPriorityFeePerGas: string;\n signed?: EncryptedSeed; hash?: string;\n}\nconst faucet = new Interface(['function mint(address token,address to,uint256 amount) returns (uint256)']);\nconst erc20 = new Interface(['function decimals() view returns(uint8)', 'function balanceOf(address) view returns(uint256)', 'function transfer(address,uint256) returns(bool)', 'event Transfer(address indexed from,address indexed to,uint256 value)']);\nconst same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\nconst CONFIRMATIONS = 2;\n/** The JSON-RPC methods that only read: asked again once when they fail (see `UsdtAdapter.rpc`). */\nconst RETRIED_READS = new Set(['eth_chainId', 'eth_getCode', 'eth_call', 'eth_getBalance', 'eth_blockNumber', 'eth_getLogs', 'eth_getTransactionCount', 'eth_estimateGas', 'eth_getBlockByNumber', 'eth_maxPriorityFeePerGas', 'eth_gasPrice', 'eth_feeHistory', 'eth_getTransactionByHash', 'eth_getTransactionReceipt']);\nconst RETRY_AFTER_MS = 1000;\n/** Failures that would fail the same way again at once: not retried. */\nconst FINAL = new WeakSet<object>();\nconst timedOut = (error: unknown) => error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');\n\n/**\n * The `provider` a request carries to the contact. Which RPC pays is the payer's own choice, so it names none of\n * this wallet's: a typed RPC URL may hold an API key (`/v3/<key>`), and every contact would read it. Older apps\n * require a URL here and pay only when it equals their own RPC, so it is the chain's public RPC (the default both\n * start with), and a local test chain's origin, without its path.\n */\nexport function wireProvider(config: Pick<UsdtConfig, 'network' | 'provider'>): string {\n return config.network === 'evm-local' ? new URL(config.provider).origin : USDT_PUBLIC_RPC[config.network];\n}\n\n/** WDK signs locally. Every network call uses the configured RPC, never a peer-supplied URL. */\nexport class UsdtAdapter implements PaymentAdapter<UsdtPrepared> {\n readonly method = 'usdt' as const;\n private manager?: WalletManagerEvm;\n private account?: WalletAccountEvm;\n private mnemonic = '';\n private nextId = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private constructor(readonly config: UsdtConfig) {}\n\n static async inspect(config: Omit<UsdtConfig, 'decimals' | 'codeHash'>): Promise<UsdtConfig> {\n if (config.network === 'ethereum' ? config.chainId !== 1 || !same(config.token, ETHEREUM_USDT) : !(config.network in EVM_TEST_CHAINS) || config.chainId !== EVM_TEST_CHAINS[config.network]) throw new Error('Unsupported USDT network or contract');\n const token = getAddress(config.token);\n const url = new URL(config.provider);\n if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) throw new Error('Use HTTPS or a loopback test RPC');\n const adapter = new UsdtAdapter({...config, token, decimals: 6, codeHash: ''});\n await adapter.chain();\n const code = await adapter.rpc<string>('eth_getCode', [token, 'latest']);\n if (code === '0x') throw new Error('No token contract exists on this chain');\n const result = await adapter.rpc<string>('eth_call', [{to: token, data: erc20.encodeFunctionData('decimals')}, 'latest']);\n const decimals = Number(erc20.decodeFunctionResult('decimals', result)[0]);\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18 || (config.chainId === 1 && decimals !== 6)) throw new Error('Unexpected token decimals');\n return {...config, token, decimals, codeHash: keccak256(code)};\n }\n static async connect(config: UsdtConfig, mnemonic: string): Promise<UsdtAdapter> {\n const inspected = await UsdtAdapter.inspect(config);\n if (inspected.decimals !== config.decimals || inspected.codeHash !== config.codeHash) throw new Error('Token metadata changed; do not use this wallet configuration');\n const adapter = new UsdtAdapter(config);\n adapter.mnemonic = mnemonic;\n // Pass standard BIP-39 seed bytes: WDK's string helper assumes a Node Buffer global.\n const seed = mnemonicToSeedSync(mnemonic);\n try { adapter.manager = new WalletManagerEvm(seed, {provider: {request: ({method, params}) => adapter.rpc(method, params as unknown[] ?? [])}, chainId: config.chainId}); } finally { seed.fill(0); }\n adapter.account = await adapter.manager.getAccount(0);\n return adapter;\n }\n /**\n * A read that fails is asked again, once, a moment later: a public RPC drops a request now and then, and a chain that\n * just made a block can refuse a read of \"latest\" it no longer holds. Without it a network switch, a restore or New\n * gave up on the first such answer. Never a broadcast or anything else that writes, nor a request that did not answer\n * in time (the person would wait twice as long), nor one the server refused as such (4xx).\n */\n async rpc<T>(method: string, params: unknown[] = []): Promise<T> {\n try { return await this.ask<T>(method, params); }\n catch (error) {\n if (!RETRIED_READS.has(method) || FINAL.has(error as object)) throw error;\n await new Promise((resolve) => setTimeout(resolve, RETRY_AFTER_MS));\n return this.ask<T>(method, params);\n }\n }\n private async ask<T>(method: string, params: unknown[]): Promise<T> {\n let response: Response;\n // The browser's words for a request that got no answer (\"Fetch is aborted\") say nothing: the RPC's host does.\n try { response = await fetch(this.config.provider, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({jsonrpc:'2.0',id:++this.nextId,method,params}), signal:AbortSignal.timeout(15000)}); }\n catch (error) {\n const reason = networkReason(error, rpcHost(this.config.provider));\n const thrown = reason ? Object.assign(new Error(reason), {cause: error}) : error;\n if (timedOut(error) && thrown && typeof thrown === 'object') FINAL.add(thrown);\n throw thrown;\n }\n if (!response.ok) { const error = engineError('usdtRpcUnavailable'); if (response.status !== 429 && response.status < 500) FINAL.add(error); throw error; }\n const result = await response.json();\n if (result.error || !Object.prototype.hasOwnProperty.call(result, 'result')) throw new Error('USDT RPC rejected the operation');\n return result.result as T;\n }\n private async chain() {\n if (BigInt(await this.rpc<string>('eth_chainId')) !== BigInt(this.config.chainId)) throw new Error('RPC chain does not match this wallet');\n }\n private async assertToken() {\n await this.chain();\n const code = await this.rpc<string>('eth_getCode', [this.config.token, 'latest']);\n if (code === '0x' || keccak256(code) !== this.config.codeHash) throw new Error('Token contract changed');\n }\n /**\n * Sepolia only: asks Aave's public faucet for test USDT, to this wallet, paid with its own test ETH.\n * Everything is fixed here (chain, contract, token, amount, recipient): nothing comes from outside.\n */\n mintTestTokens(): Promise<string> { return this.serial(async () => {\n if (this.config.chainId !== EVM_TEST_CHAINS.sepolia || !same(this.config.token, SEPOLIA_TEST_USDT)) throw new Error('Test USDT comes from a faucet on Sepolia only');\n await this.chain();\n const account = this.current(), from = await account.getAddress();\n const data = faucet.encodeFunctionData('mint', [SEPOLIA_TEST_USDT, from, BigInt(TEST_USDT_FAUCET_AMOUNT)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount', [from, 'pending'])));\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas', [{ from, to: SEPOLIA_TEST_USDT_FAUCET, data, value: '0x0' }]));\n const block = await this.rpc<{ baseFeePerGas?: string }>('eth_getBlockByNumber', ['latest', false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFeePerGas = BigInt(block.baseFeePerGas) * 2n + priority, gasLimit = (estimate * 120n + 99n) / 100n;\n if (BigInt((await this.balances()).gasBalance) < gasLimit * maxFeePerGas) throw engineError('usdtNeedsSepoliaGas');\n const raw = await account.signTransaction({ type: 2, to: SEPOLIA_TEST_USDT_FAUCET, data, value: 0n, chainId: this.config.chainId, nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas: priority });\n await account.sendTransaction(raw);\n return Transaction.from(raw).hash!;\n }); }\n private current(): WalletAccountEvm { if (!this.account) throw new Error('Unlock the USDT wallet first'); return this.account; }\n address() { return this.current().getAddress(); }\n /**\n * The token and gas balances. The chain and the contract are not asked again here: `connect` checked them, and every\n * payment does before it signs. The wallet reads this every 8 s, and the contract's whole code was most of each read.\n */\n async balances() {\n const address = await this.address();\n const [token, gas] = await Promise.all([this.rpc<string>('eth_call',[{to:this.config.token,data:erc20.encodeFunctionData('balanceOf',[address])},'latest']),this.rpc<string>('eth_getBalance',[address,'pending'])]);\n return {balance:erc20.decodeFunctionResult('balanceOf',token)[0].toString(),gasBalance:BigInt(gas).toString()};\n }\n async target(): Promise<PaymentTarget> {\n const now = Date.now();\n return {method:'usdt',network:this.config.network,provider:wireProvider(this.config),asset:this.config.chainId === 1 ? 'USDT':'TEST-USDT',unit:'token-base',address:await this.address(),chainId:this.config.chainId,token:this.config.token,decimals:this.config.decimals,issuedAt:now,expiresAt:now+15*60*1000};\n }\n /** The request is for this wallet's token on its chain. Its `provider` is not compared: this wallet's own RPC pays. */\n private matches(target: PaymentTarget) {\n validatePaymentTarget(target);\n if (target.method !== 'usdt' || target.network !== this.config.network || target.chainId !== this.config.chainId || !same(target.token!,this.config.token) || target.decimals !== this.config.decimals) throw new Error('Request does not match the configured token and network');\n }\n prepare(target: PaymentTarget, amount: number, feeCap: number) { return this.serial(async () => {\n this.matches(target);\n await this.assertToken();\n const from = await this.address(), to = this.config.token;\n if (same(target.address, from) || same(target.address, to)) throw new Error('Choose a different recipient address');\n const {balance,gasBalance} = await this.balances();\n if (BigInt(balance) < BigInt(amount)) throw engineError('usdtNotEnoughTokens');\n const data = erc20.encodeFunctionData('transfer', [getAddress(target.address),BigInt(amount)]);\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[from,'pending'])));\n if (!Number.isSafeInteger(nonce)) throw new Error('Invalid account nonce');\n const estimate = BigInt(await this.rpc<string>('eth_estimateGas',[{from,to,data,value:'0x0'}]));\n const block = await this.rpc<{baseFeePerGas?:string}>('eth_getBlockByNumber',['latest',false]);\n if (!block.baseFeePerGas) throw new Error('This wallet requires an EIP-1559 chain');\n const priority = BigInt(await this.rpc<string>('eth_maxPriorityFeePerGas'));\n const maxFee = BigInt(block.baseFeePerGas)*2n + priority;\n const gasLimit = (estimate*120n+99n)/100n;\n const maximum = gasLimit*maxFee;\n if (maximum > BigInt(feeCap) || maximum > BigInt(Number.MAX_SAFE_INTEGER)) throw engineError('usdtGasAboveLimit');\n if (BigInt(gasBalance) < maximum) throw engineError('usdtNotEnoughGas');\n const prepared:UsdtPrepared = {from,to,data,value:'0',chainId:this.config.chainId,nonce,gasLimit:gasLimit.toString(),maxFeePerGas:maxFee.toString(),maxPriorityFeePerGas:priority.toString()};\n return {fee:Number(maximum),prepared,evm:{from,nonce,gasLimit:prepared.gasLimit,maxFeePerGas:prepared.maxFeePerGas,maxPriorityFeePerGas:prepared.maxPriorityFeePerGas,confirmations:CONFIRMATIONS}};\n }); }\n private verifyPrepared(review: PaymentReview, tx: UsdtPrepared) {\n if (tx.chainId !== this.config.chainId || !same(tx.to,this.config.token) || tx.value !== '0' || tx.data !== erc20.encodeFunctionData('transfer',[getAddress(review.address),BigInt(review.amount)]) || BigInt(tx.gasLimit)*BigInt(tx.maxFeePerGas) !== BigInt(review.fee) || review.fee > review.feeCap || tx.nonce !== review.evm?.nonce || !same(tx.from,review.evm?.from ?? '')) throw new Error('Transaction no longer matches the approved review');\n }\n private verifySigned(raw: string, saved: UsdtPrepared) {\n const tx = Transaction.from(raw);\n if (!tx.hash || !tx.from || !same(tx.from,saved.from) || tx.chainId !== BigInt(saved.chainId) || !tx.to || !same(tx.to,saved.to) || tx.data !== saved.data || tx.value !== 0n || tx.nonce !== saved.nonce || tx.gasLimit !== BigInt(saved.gasLimit) || tx.maxFeePerGas !== BigInt(saved.maxFeePerGas) || tx.maxPriorityFeePerGas !== BigInt(saved.maxPriorityFeePerGas)) throw new Error('Signature does not match the approved transaction');\n return tx.hash;\n }\n execute(review: PaymentReview, prepared: UsdtPrepared, persist?:()=>Promise<void>) { return this.serial(async () => {\n let account:WalletAccountEvm;\n try {\n this.matches(review); this.verifyPrepared(review,prepared);\n await this.assertToken(); account=this.current();\n if (!same(await account.getAddress(),prepared.from)) throw new Error('Wrong wallet');\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce !== prepared.nonce) throw new Error('Account nonce changed. Create a new review');\n const balances = await this.balances();\n if (BigInt(balances.balance)<BigInt(review.amount) || BigInt(balances.gasBalance)<BigInt(review.fee)) throw new Error('Token or gas balance changed. Create a new review');\n if (!persist) throw new Error('Durable payment journal required');\n } catch (error) { throw new PaymentPreflightError(error instanceof Error ? error.message : 'Could not validate payment'); }\n const raw = await account.signTransaction({type:2,to:prepared.to,data:prepared.data,value:0n,chainId:prepared.chainId,nonce:prepared.nonce,gasLimit:BigInt(prepared.gasLimit),maxFeePerGas:BigInt(prepared.maxFeePerGas),maxPriorityFeePerGas:BigInt(prepared.maxPriorityFeePerGas)});\n prepared.hash = this.verifySigned(raw,prepared);\n prepared.signed = await sealSeed(raw,this.mnemonic);\n await persist!(); // Nothing may broadcast before the encrypted bytes are durable.\n await account.sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n reconcile(review: PaymentReview, prepared: UsdtPrepared) { return this.serial(async () => {\n await this.assertToken(); this.verifyPrepared(review,prepared);\n if (!prepared.signed || !prepared.hash) return {settled:false,failed:true,error:'No signed transaction was submitted. Create a new review.'};\n const result = await this.receipt(prepared.hash,review,prepared.from);\n if (result.settled || result.failed || result.pending) return result;\n // An uncertain network response permits only replay of exactly the saved bytes.\n const nonce = Number(BigInt(await this.rpc<string>('eth_getTransactionCount',[prepared.from,'pending'])));\n if (nonce > prepared.nonce) return result;\n const raw = await unsealSeed(prepared.signed,this.mnemonic);\n if (this.verifySigned(raw,prepared) !== prepared.hash || !same(await this.address(),prepared.from)) throw new Error('Recovery wallet mismatch');\n await this.current().sendTransaction(raw);\n return this.receipt(prepared.hash,review,prepared.from);\n }); }\n async receipt(hash: string, target: PaymentTarget & {amount:number}, expectedFrom?:string): Promise<PaymentExecution> {\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash) || target.chainId !== this.config.chainId || !same(target.token ?? '',this.config.token) || target.decimals !== this.config.decimals) throw new Error('Invalid receipt target');\n await this.assertToken();\n const tx = await this.rpc<{from:string;to:string;input:string;value:string;nonce:string}|null>('eth_getTransactionByHash',[hash]);\n if (!tx) return {txid:hash,settled:false};\n if (!same(tx.to,this.config.token) || (expectedFrom && !same(tx.from,expectedFrom)) || BigInt(tx.value)!==0n || tx.input !== erc20.encodeFunctionData('transfer',[getAddress(target.address),BigInt(target.amount)])) throw new Error('Transaction is not the requested token transfer');\n const receipt = await this.rpc<{status:string;blockNumber:string;blockHash:string;logs:Array<{address:string;topics:string[];data:string}>}|null>('eth_getTransactionReceipt',[hash]);\n if (!receipt) return {txid:hash,settled:false,pending:true};\n const block = await this.rpc<{hash:string;timestamp:string}>('eth_getBlockByNumber',[receipt.blockNumber,false]);\n if (!block || block.hash !== receipt.blockHash || BigInt(block.timestamp)*1000n < BigInt((target.issuedAt ?? 0)-1000)) return {txid:hash,settled:false};\n const height = BigInt(await this.rpc<string>('eth_blockNumber'));\n if (height-BigInt(receipt.blockNumber)+1n < BigInt(CONFIRMATIONS)) return {txid:hash,settled:false,pending:true};\n if (BigInt(receipt.status)!==1n) return {txid:hash,settled:false,failed:true,error:'Transaction reverted. Tokens were not sent; gas was spent.'};\n const transfer = receipt.logs.some(log=>{\n if (!same(log.address,this.config.token)) return false;\n try {const event=erc20.parseLog(log);return event?.name==='Transfer' && same(event.args[0],tx.from) && same(event.args[1],target.address) && event.args[2]===BigInt(target.amount);} catch {return false;}\n });\n if (!transfer) throw new Error('Receipt has no matching token Transfer');\n return {txid:hash,settled:true};\n }\n async dispose() { await this.queue.catch(()=>{}); this.account=undefined;this.manager?.dispose();this.manager=undefined;this.mnemonic=''; }\n private serial<T>(work:()=>Promise<T>):Promise<T> { const operation=this.queue.then(work,work);this.queue=operation.catch(()=>{});return operation; }\n}\n"],"mappings":";;;;;;AAoBA,IAAM,SAAS,IAAI,UAAU,CAAC,0EAA0E,CAAC;AACzG,IAAM,QAAQ,IAAI,UAAU;CAAC;CAA2C;CAAqD;CAAoD;AAAuE,CAAC;AACzP,IAAM,QAAQ,GAAW,MAAc,EAAE,YAAY,MAAM,EAAE,YAAY;AACzE,IAAM,gBAAgB;;AAEtB,IAAM,gCAAgB,IAAI,IAAI;CAAC;CAAe;CAAe;CAAY;CAAkB;CAAmB;CAAe;CAA2B;CAAmB;CAAwB;CAA4B;CAAgB;CAAkB;CAA4B;AAA2B,CAAC;AACzT,IAAM,iBAAiB;;AAEvB,IAAM,wBAAQ,IAAI,QAAgB;AAClC,IAAM,YAAY,UAAmB,iBAAiB,UAAU,MAAM,SAAS,gBAAgB,MAAM,SAAS;;;;;;;AAQ9G,SAAgB,aAAa,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
enableCompileCache();
|
|
27
|
-
var { run } = await import("./assets/main-
|
|
27
|
+
var { run } = await import("./assets/main-C6t5zrD5.js");
|
|
28
28
|
run(process.argv.slice(2));
|
|
29
29
|
//#endregion
|
|
30
30
|
export {};
|