@ghostlytools/cli 1.10.0 → 1.10.2

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.
Files changed (104) hide show
  1. package/README.md +19 -17
  2. package/SKILL.md +5 -4
  3. package/dist/assets/api-DcE4KylM.js +3 -0
  4. package/dist/assets/{api-BF_KwecF.js → api-EUGHGnRz.js} +108 -49
  5. package/dist/assets/api-EUGHGnRz.js.map +1 -0
  6. package/dist/assets/{apiKit-Du1u2l4x.js → apiKit-CJVp_crp.js} +85 -22
  7. package/dist/assets/apiKit-CJVp_crp.js.map +1 -0
  8. package/dist/assets/{apps-Bti9fDoW.js → apps-C-KbyLCa.js} +1 -1
  9. package/dist/assets/{apps-DwPfp54I.js → apps-C54T_MOT.js} +33 -12
  10. package/dist/assets/apps-C54T_MOT.js.map +1 -0
  11. package/dist/assets/{arkade-DOWpA2Kr.js → arkade-BmxJTa65.js} +2 -2
  12. package/dist/assets/{arkade-DOWpA2Kr.js.map → arkade-BmxJTa65.js.map} +1 -1
  13. package/dist/assets/{backup-DZ_Q1eSu.js → backup-BxSH5BZG.js} +7 -6
  14. package/dist/assets/{backup-DZ_Q1eSu.js.map → backup-BxSH5BZG.js.map} +1 -1
  15. package/dist/assets/{backup-CeRckyl2.js → backup-C0Plp-DF.js} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{buttons-BxIThdg9.js → buttons-B-ZJYdo0.js} +6 -6
  19. package/dist/assets/{buttons-BxIThdg9.js.map → buttons-B-ZJYdo0.js.map} +1 -1
  20. package/dist/assets/buttons-DA3wZfG0.js +2 -0
  21. package/dist/assets/childEnv-BVOQK9EA.js +21 -0
  22. package/dist/assets/childEnv-BVOQK9EA.js.map +1 -0
  23. package/dist/assets/{client-D5E1RQYB.js → client-CDa87uYD.js} +3 -3
  24. package/dist/assets/{client-D5E1RQYB.js.map → client-CDa87uYD.js.map} +1 -1
  25. package/dist/assets/codec-D45W1L8n.js +13 -0
  26. package/dist/assets/codec-D45W1L8n.js.map +1 -0
  27. package/dist/assets/{envelope-CugS9qwQ.js → envelope-C3yFCQa-.js} +3 -12
  28. package/dist/assets/envelope-C3yFCQa-.js.map +1 -0
  29. package/dist/assets/{errors-R4S2SAEM.js → errors-Dt-ZnyOX.js} +3 -1
  30. package/dist/assets/errors-Dt-ZnyOX.js.map +1 -0
  31. package/dist/assets/{fixedHosts-B4E4VrYE.js → fixedHosts-C6nCHjOa.js} +4 -4
  32. package/dist/assets/{fixedHosts-B4E4VrYE.js.map → fixedHosts-C6nCHjOa.js.map} +1 -1
  33. package/dist/assets/{groupFiles-NonOYBKN.js → groupFiles-DYopNE57.js} +217 -178
  34. package/dist/assets/groupFiles-DYopNE57.js.map +1 -0
  35. package/dist/assets/{host-DvcVt5YI.js → host-G5seUwaI.js} +241 -87
  36. package/dist/assets/host-G5seUwaI.js.map +1 -0
  37. package/dist/assets/{hyperdhtRelay-Ce42sR8x.js → hyperdhtRelay-B_uHjg_r.js} +28 -20
  38. package/dist/assets/hyperdhtRelay-B_uHjg_r.js.map +1 -0
  39. package/dist/assets/{irohWeb-C9ChbD-c.js → irohWeb-C-2oslSU.js} +120 -38
  40. package/dist/assets/irohWeb-C-2oslSU.js.map +1 -0
  41. package/dist/assets/{main-4qE381KM.js → main-Dk--nD7X.js} +92 -48
  42. package/dist/assets/main-Dk--nD7X.js.map +1 -0
  43. package/dist/assets/{mainline-DOwZDHVy.js → mainline-HPlVrl8R.js} +5 -5
  44. package/dist/assets/mainline-HPlVrl8R.js.map +1 -0
  45. package/dist/assets/networkReason-CfpO9ayz.js +474 -0
  46. package/dist/assets/networkReason-CfpO9ayz.js.map +1 -0
  47. package/dist/assets/{nwc-CHLWFV1R.js → nwc-BY7BPttn.js} +3 -3
  48. package/dist/assets/{nwc-CHLWFV1R.js.map → nwc-BY7BPttn.js.map} +1 -1
  49. package/dist/assets/{nwcProvider-BlkPOJen.js → nwcProvider-CfpbNUf7.js} +2 -2
  50. package/dist/assets/{nwcProvider-BlkPOJen.js.map → nwcProvider-CfpbNUf7.js.map} +1 -1
  51. package/dist/assets/{ownDid-yXtY_1B5.js → ownDid-DJFZM2cV.js} +2 -2
  52. package/dist/assets/{ownDid-yXtY_1B5.js.map → ownDid-DJFZM2cV.js.map} +1 -1
  53. package/dist/assets/{profiles-vbXHs0Mq.js → profiles-DKmZGXp6.js} +22 -9
  54. package/dist/assets/profiles-DKmZGXp6.js.map +1 -0
  55. package/dist/assets/{registry-chCD0KWS.js → registry-BUm4cAzV.js} +60 -19
  56. package/dist/assets/registry-BUm4cAzV.js.map +1 -0
  57. package/dist/assets/{registry-BN9r2pR4.js → registry-CAzrtV0_.js} +1 -1
  58. package/dist/assets/{resolve-Dtzogt2W.js → resolve-CDD4X68j.js} +5 -3
  59. package/dist/assets/resolve-CDD4X68j.js.map +1 -0
  60. package/dist/assets/{restoredRows-CRYwIx3g.js → restoredRows-YhlbokEE.js} +4 -2
  61. package/dist/assets/restoredRows-YhlbokEE.js.map +1 -0
  62. package/dist/assets/{secretGuard-CSVNxXVW.js → secretGuard-B7Hj0Kvz.js} +2 -2
  63. package/dist/assets/{secretGuard-CSVNxXVW.js.map → secretGuard-B7Hj0Kvz.js.map} +1 -1
  64. package/dist/assets/secretGuard-DUr6bgKc.js +2 -0
  65. package/dist/assets/{server-BZnsm5X5.js → server-DcOsgYDU.js} +1046 -573
  66. package/dist/assets/server-DcOsgYDU.js.map +1 -0
  67. package/dist/assets/{src-DZagapGt.js → src-D31D1_oY.js} +2360 -1673
  68. package/dist/assets/src-D31D1_oY.js.map +1 -0
  69. package/dist/assets/{sshForges-BkTgy5rx.js → sshForges-DerRwMf3.js} +2 -2
  70. package/dist/assets/{sshForges-BkTgy5rx.js.map → sshForges-DerRwMf3.js.map} +1 -1
  71. package/dist/assets/{translate-B9SMd6uf.js → translate-C-sj0VJe.js} +12 -8
  72. package/dist/assets/{translate-B9SMd6uf.js.map → translate-C-sj0VJe.js.map} +1 -1
  73. package/dist/assets/{usdt-BU4ezonh.js → usdt-DwHqp625.js} +3 -3
  74. package/dist/assets/{usdt-BU4ezonh.js.map → usdt-DwHqp625.js.map} +1 -1
  75. package/dist/assets/{waitNotice-B8D8WhbE.js → waitNotice-D52RWbV4.js} +38 -4
  76. package/dist/assets/waitNotice-D52RWbV4.js.map +1 -0
  77. package/dist/assets/{words-jYy7lTcb.js → words-Db9WgatT.js} +3 -3
  78. package/dist/assets/words-Db9WgatT.js.map +1 -0
  79. package/dist/ghostly.mjs +1 -1
  80. package/package.json +1 -1
  81. package/dist/assets/api-BF_KwecF.js.map +0 -1
  82. package/dist/assets/api-DdrA86Ur.js +0 -3
  83. package/dist/assets/apiKit-Du1u2l4x.js.map +0 -1
  84. package/dist/assets/apps-DwPfp54I.js.map +0 -1
  85. package/dist/assets/buttons-D9QBHS9Y.js +0 -2
  86. package/dist/assets/envelope-CugS9qwQ.js.map +0 -1
  87. package/dist/assets/errors-R4S2SAEM.js.map +0 -1
  88. package/dist/assets/groupFiles-NonOYBKN.js.map +0 -1
  89. package/dist/assets/host-DvcVt5YI.js.map +0 -1
  90. package/dist/assets/hyperdhtRelay-Ce42sR8x.js.map +0 -1
  91. package/dist/assets/irohWeb-C9ChbD-c.js.map +0 -1
  92. package/dist/assets/main-4qE381KM.js.map +0 -1
  93. package/dist/assets/mainline-DOwZDHVy.js.map +0 -1
  94. package/dist/assets/networkReason-MInk1Y63.js +0 -154
  95. package/dist/assets/networkReason-MInk1Y63.js.map +0 -1
  96. package/dist/assets/profiles-vbXHs0Mq.js.map +0 -1
  97. package/dist/assets/registry-chCD0KWS.js.map +0 -1
  98. package/dist/assets/resolve-Dtzogt2W.js.map +0 -1
  99. package/dist/assets/restoredRows-CRYwIx3g.js.map +0 -1
  100. package/dist/assets/secretGuard-Q2BKq0q0.js +0 -2
  101. package/dist/assets/server-BZnsm5X5.js.map +0 -1
  102. package/dist/assets/src-DZagapGt.js.map +0 -1
  103. package/dist/assets/waitNotice-B8D8WhbE.js.map +0 -1
  104. package/dist/assets/words-jYy7lTcb.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { Xi as IdentityCheckUnavailable, rt as sameSshKey, tt as parseSshPublicKey } from "./src-DZagapGt.js";
1
+ import { ji as IdentityCheckUnavailable, rt as sameSshKey, tt as parseSshPublicKey } from "./src-D31D1_oY.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}$/;
@@ -257,4 +257,4 @@ async function checkSshForge(forge, login, key, fetcher, signal) {
257
257
  //#endregion
258
258
  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
259
 
260
- //# sourceMappingURL=sshForges-BkTgy5rx.js.map
260
+ //# sourceMappingURL=sshForges-DerRwMf3.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sshForges-BkTgy5rx.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 /** 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.',\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":";;AAsDA,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;EAChB,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,SAAS;EACT,MAAM,CAAC,OAAO;EAAG,cAAc;EAC/B,QAAQ,CAAC;EACT,gBAAgB;EAChB,aAAa,EAAE,eAAe,WAAW;EACzC,WAAW;GAAE,KAAK;GAAI,WAAW;EAAG;CACtC;CACA,QAAQ;EACN,IAAI;EAAU,MAAM;EACpB,QAAQ;EACR,WAA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Y,EAAE,SAAS,YAAY,MAAM,MAAM,YAAY,CAAC;CAC/G,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,CAAC,OAAO,cAAc,KAAK,EAAE,KAAM,KAAK,MAAiB,GAAG,MAAM,IAAI,MAAM,mCAAmC;CACnH,MAAM,IAAI,MAAM,IAAI,SAAS,mCAAmC,KAAK,GAAa,qBAAqB,MAAM;CAC7G,OAAO,EAAE,WAAW,MAAM,OAAO,SAAS,EAAE,IAAI;AAClD;AAIA,IAAM,2BAAW,IAAI,QAAoE;;AAGzF,eAAsB,cAAc,OAAiB,OAAe,KAAiC,SAAwB,QAA+C;CAC1K,IAAI,CAAC,gBAAgB,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM,SAAS,gBAAgB,OAAO,UAAU;CAC9F,IAAI,UAAU,SAAS,IAAI,OAAO;CAClC,IAAI,CAAC,SAAS,SAAS,IAAI,SAAS,0BAAU,IAAI,IAAI,CAAC;CACvD,MAAM,MAAM,SAAS,KAAK,GAAG,MAAM,GAAG,MAAM,YAAY;CACxD,IAAI,SAAS,IAAI,IAAI,EAAE;CACvB,IAAI,CAAC,QAAQ;EACX,SAAS,SAAS,OAAO,OAAO,SAAS,MAAM,CAAC,CAAC,cAAc,IAAI,OAAO,EAAE,CAAC;EAC7E,IAAI,IAAI,IAAI,MAAM;CACpB;CACA,MAAM,OAAO,MAAM;CACnB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,MAAK,MAAK,WAAW,GAAG,GAAG,CAAC,IAAI,WAAW;AACzD"}
1
+ {"version":3,"file":"sshForges-DerRwMf3.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 /** 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.',\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":";;AAsDA,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;EAChB,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,SAAS;EACT,MAAM,CAAC,OAAO;EAAG,cAAc;EAC/B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as LINK_TRAILING, Ua as linkStop } from "./src-D31D1_oY.js";
2
+ import { t as CliError } from "./errors-Dt-ZnyOX.js";
3
+ import { t as childEnv } from "./childEnv-BVOQK9EA.js";
3
4
  import { spawn } from "node:child_process";
4
5
  import { existsSync } from "node:fs";
5
6
  import { join } from "node:path";
@@ -971,11 +972,14 @@ function openTranslator({ home, to, detect, warn }) {
971
972
  const said = /* @__PURE__ */ new Set();
972
973
  const kill = () => child?.kill();
973
974
  const start = () => {
974
- const started = spawn(bare, [script, models], { stdio: [
975
- "pipe",
976
- "pipe",
977
- "ignore"
978
- ] });
975
+ const started = spawn(bare, [script, models], {
976
+ stdio: [
977
+ "pipe",
978
+ "pipe",
979
+ "ignore"
980
+ ],
981
+ env: childEnv()
982
+ });
979
983
  started.stdin.on("error", () => {});
980
984
  createInterface({ input: started.stdout }).on("line", (line) => {
981
985
  let answer;
@@ -1083,4 +1087,4 @@ function openTranslator({ home, to, detect, warn }) {
1083
1087
  //#endregion
1084
1088
  export { loadDetector, openTranslator, translateAnswer, translateTarget };
1085
1089
 
1086
- //# sourceMappingURL=translate-B9SMd6uf.js.map
1090
+ //# sourceMappingURL=translate-C-sj0VJe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"translate-B9SMd6uf.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 } 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) and a closing bracket or quote the link did not open\n * (\"(https://x.example/a)\") are left as text, and so is a doubled `~~` or `||` closing the strike or spoiler the link\n * 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 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 shows as typed. Anything else shows as the browser reads it: the host\n * in punycode (a look-alike \"аpple.com\" reads \"xn--pple-43d.com\") 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 return /^[\\x21-\\x7e]*$/.test(url) ? 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 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};\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<Detector, RegExp>();\nfunction patternOf(detector: Detector): RegExp {\n let re = compiled.get(detector);\n if (!re) {\n const { source, flags } = detector.pattern;\n re = new RegExp(source, flags.includes(\"g\") ? flags : flags + \"g\");\n compiled.set(detector, re);\n }\n return re;\n}\n\ntype Found = { start: number; end: number; data: unknown };\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/** 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) => findNext(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 found = next[best]!;\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] = findNext(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 \"・\").\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}]/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 { 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\"] });\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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1B,QAAQ,MAAM,SAAS,SAAS,SAAS;IAAM,MAAM,MAAM;IAC3D,MAAM,MAAM;IAAM,WAAW,MAAM;IAAW,MAAM,MAAM;IAAM,aAAa,MAAM;IACnF,UAAU,MAAM,UAAU,KAAK,OAAO;KAAE,GAAG,EAAE;KAAQ,GAAG,EAAE;IAAO,EAAE;GACrE,GAAqD;IAAE,aAAa;IAAkE;IAAS;IAAc,cAAc,UAAU,IAAI,KAAK;GAAE,CAAC;EACnM,QAAQ;GAAE,OAAO;EAAO;EACxB,MAAM,EAAE,MAAM,aAAa;EAC3B,IAAI,UAAU,UAAU,IAAI,OAAO,QAAQ;EAC3C,IAAI,CAAC,MAAM,OAAO;EAClB,MAAM,OAAO,MAAM,IAAI,GAAG,KAAK,GAAG,MAAM,MAAM,IAAI;EAElD,OAAO,SAAS,QAAQ,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
+ {"version":3,"file":"translate-C-sj0VJe.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 } 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) and a closing bracket or quote the link did not open\n * (\"(https://x.example/a)\") are left as text, and so is a doubled `~~` or `||` closing the strike or spoiler the link\n * 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 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 shows as typed. Anything else shows as the browser reads it: the host\n * in punycode (a look-alike \"аpple.com\" reads \"xn--pple-43d.com\") 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 return /^[\\x21-\\x7e]*$/.test(url) ? 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 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};\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<Detector, RegExp>();\nfunction patternOf(detector: Detector): RegExp {\n let re = compiled.get(detector);\n if (!re) {\n const { source, flags } = detector.pattern;\n re = new RegExp(source, flags.includes(\"g\") ? flags : flags + \"g\");\n compiled.set(detector, re);\n }\n return re;\n}\n\ntype Found = { start: number; end: number; data: unknown };\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/** 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) => findNext(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 found = next[best]!;\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] = findNext(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 \"・\").\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}]/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,IAAI,cAAc,KAAK,IAAI,KAAM,UAAU,MAAM,QAAQ,MAAM,SAAU;GACvE,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;;;;;;;;AASF,SAAgB,SAAS,KAAqB;CAC5C,IAAI;CACJ,IAAI;EAAE,SAAS,IAAI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