@livechatta/sdk 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +218 -0
- package/LICENSE +21 -0
- package/README.md +2558 -2
- package/bin/chatta.mjs +7 -0
- package/bin/lib/cli.d.mts +46 -0
- package/bin/lib/cli.mjs +2088 -0
- package/dist/cjs/livechatta.cjs.js +7258 -0
- package/dist/cjs/livechatta.cjs.js.map +1 -0
- package/dist/cjs/livechatta.cjs.min.js +2 -0
- package/dist/cjs/livechatta.cjs.min.js.map +1 -0
- package/dist/esm/livechatta.esm.js +7077 -0
- package/dist/esm/livechatta.esm.js.map +1 -0
- package/dist/esm/livechatta.esm.min.js +2 -0
- package/dist/esm/livechatta.esm.min.js.map +1 -0
- package/dist/platforms/android/LiveChattaClient.kt +367 -0
- package/dist/platforms/android/LiveChattaHttpAPI.kt +2630 -0
- package/dist/platforms/android/LiveChattaJson.kt +83 -0
- package/dist/platforms/android/LiveChattaModels.kt +22805 -0
- package/dist/platforms/android/LiveChattaSentFrom.kt +30 -0
- package/dist/platforms/android/LiveChattaSocketAPI.kt +2113 -0
- package/dist/platforms/android/LiveChattaTyped.kt +239 -0
- package/dist/platforms/android/LiveChattaWebView.kt +158 -0
- package/dist/platforms/angular/livechatta-bridge.service.d.ts +35 -0
- package/dist/platforms/angular/livechatta-bridge.service.js +1 -0
- package/dist/platforms/angular/livechatta-bridge.service.js.map +1 -0
- package/dist/platforms/angular/livechatta-embed.component.d.ts +46 -0
- package/dist/platforms/angular/livechatta-embed.component.js +1 -0
- package/dist/platforms/angular/livechatta-embed.component.js.map +1 -0
- package/dist/platforms/angular/livechatta.service.d.ts +66 -0
- package/dist/platforms/angular/livechatta.service.js +1 -0
- package/dist/platforms/angular/livechatta.service.js.map +1 -0
- package/dist/platforms/capacitor/CapacitorBridge.d.ts +27 -0
- package/dist/platforms/capacitor/CapacitorBridge.js +1 -0
- package/dist/platforms/capacitor/CapacitorBridge.js.map +1 -0
- package/dist/platforms/capacitor/CapacitorDeepLinks.d.ts +23 -0
- package/dist/platforms/capacitor/CapacitorDeepLinks.js +1 -0
- package/dist/platforms/capacitor/CapacitorDeepLinks.js.map +1 -0
- package/dist/platforms/capacitor/CapacitorPermissions.d.ts +29 -0
- package/dist/platforms/capacitor/CapacitorPermissions.js +1 -0
- package/dist/platforms/capacitor/CapacitorPermissions.js.map +1 -0
- package/dist/platforms/capacitor/CapacitorPush.d.ts +33 -0
- package/dist/platforms/capacitor/CapacitorPush.js +1 -0
- package/dist/platforms/capacitor/CapacitorPush.js.map +1 -0
- package/dist/platforms/capacitor/index.d.ts +24 -0
- package/dist/platforms/capacitor/index.js +1 -0
- package/dist/platforms/capacitor/index.js.map +1 -0
- package/dist/platforms/flutter/livechatta_client.dart +359 -0
- package/dist/platforms/flutter/livechatta_http_api.dart +1942 -0
- package/dist/platforms/flutter/livechatta_json.dart +57 -0
- package/dist/platforms/flutter/livechatta_models.dart +23531 -0
- package/dist/platforms/flutter/livechatta_sent_from.dart +35 -0
- package/dist/platforms/flutter/livechatta_socket_api.dart +1504 -0
- package/dist/platforms/flutter/livechatta_typed.dart +234 -0
- package/dist/platforms/flutter/livechatta_webview.dart +190 -0
- package/dist/platforms/ios/LiveChattaClient.swift +374 -0
- package/dist/platforms/ios/LiveChattaHttpAPI.swift +2431 -0
- package/dist/platforms/ios/LiveChattaJSON.swift +84 -0
- package/dist/platforms/ios/LiveChattaModels.swift +27050 -0
- package/dist/platforms/ios/LiveChattaSentFrom.swift +32 -0
- package/dist/platforms/ios/LiveChattaSocketAPI.swift +1446 -0
- package/dist/platforms/ios/LiveChattaTyped.swift +268 -0
- package/dist/platforms/ios/LiveChattaWebView.swift +191 -0
- package/dist/platforms/nuxt/LiveChattaView.d.ts +1 -0
- package/dist/platforms/nuxt/LiveChattaView.js +1 -0
- package/dist/platforms/nuxt/LiveChattaView.js.map +1 -0
- package/dist/platforms/nuxt/useChattaBridge.d.ts +9 -0
- package/dist/platforms/nuxt/useChattaBridge.js +1 -0
- package/dist/platforms/nuxt/useChattaBridge.js.map +1 -0
- package/dist/platforms/nuxt/useLiveChatta.d.ts +63 -0
- package/dist/platforms/nuxt/useLiveChatta.js +1 -0
- package/dist/platforms/nuxt/useLiveChatta.js.map +1 -0
- package/dist/platforms/react/LiveChattaView.d.ts +58 -0
- package/dist/platforms/react/LiveChattaView.js +1 -0
- package/dist/platforms/react/LiveChattaView.js.map +1 -0
- package/dist/platforms/react/useChattaBridge.d.ts +1 -0
- package/dist/platforms/react/useChattaBridge.js +1 -0
- package/dist/platforms/react/useChattaBridge.js.map +1 -0
- package/dist/platforms/react/useChattaDeepLink.d.ts +2 -0
- package/dist/platforms/react/useChattaDeepLink.js +1 -0
- package/dist/platforms/react/useChattaDeepLink.js.map +1 -0
- package/dist/platforms/react/useChattaPermissions.d.ts +9 -0
- package/dist/platforms/react/useChattaPermissions.js +1 -0
- package/dist/platforms/react/useChattaPermissions.js.map +1 -0
- package/dist/platforms/react/useChattaUnread.d.ts +1 -0
- package/dist/platforms/react/useChattaUnread.js +1 -0
- package/dist/platforms/react/useChattaUnread.js.map +1 -0
- package/dist/platforms/react/useLiveChatta.d.ts +29 -0
- package/dist/platforms/react/useLiveChatta.js +1 -0
- package/dist/platforms/react/useLiveChatta.js.map +1 -0
- package/dist/platforms/react-native/LiveChattaView.d.ts +52 -0
- package/dist/platforms/react-native/LiveChattaView.js +1 -0
- package/dist/platforms/react-native/LiveChattaView.js.map +1 -0
- package/dist/platforms/react-native/useChattaBridge.d.ts +12 -0
- package/dist/platforms/react-native/useChattaBridge.js +1 -0
- package/dist/platforms/react-native/useChattaBridge.js.map +1 -0
- package/dist/platforms/react-native/useLiveChatta.d.ts +29 -0
- package/dist/platforms/react-native/useLiveChatta.js +1 -0
- package/dist/platforms/react-native/useLiveChatta.js.map +1 -0
- package/dist/platforms/svelte/LiveChattaEmbed.d.ts +54 -0
- package/dist/platforms/svelte/LiveChattaEmbed.js +1 -0
- package/dist/platforms/svelte/LiveChattaEmbed.js.map +1 -0
- package/dist/platforms/svelte/chattaBridgeStore.d.ts +19 -0
- package/dist/platforms/svelte/chattaBridgeStore.js +1 -0
- package/dist/platforms/svelte/chattaBridgeStore.js.map +1 -0
- package/dist/platforms/svelte/useLiveChatta.d.ts +61 -0
- package/dist/platforms/svelte/useLiveChatta.js +1 -0
- package/dist/platforms/svelte/useLiveChatta.js.map +1 -0
- package/dist/platforms/tauri/TauriBridge.d.ts +34 -0
- package/dist/platforms/tauri/TauriBridge.js +1 -0
- package/dist/platforms/tauri/TauriBridge.js.map +1 -0
- package/dist/platforms/tauri/TauriDeepLinks.d.ts +29 -0
- package/dist/platforms/tauri/TauriDeepLinks.js +1 -0
- package/dist/platforms/tauri/TauriDeepLinks.js.map +1 -0
- package/dist/platforms/tauri/TauriPermissions.d.ts +21 -0
- package/dist/platforms/tauri/TauriPermissions.js +1 -0
- package/dist/platforms/tauri/TauriPermissions.js.map +1 -0
- package/dist/platforms/tauri/TauriUpdater.d.ts +31 -0
- package/dist/platforms/tauri/TauriUpdater.js +1 -0
- package/dist/platforms/tauri/TauriUpdater.js.map +1 -0
- package/dist/platforms/tauri/index.d.ts +22 -0
- package/dist/platforms/tauri/index.js +1 -0
- package/dist/platforms/tauri/index.js.map +1 -0
- package/dist/platforms/vue/LiveChattaView.d.ts +1 -0
- package/dist/platforms/vue/LiveChattaView.js +1 -0
- package/dist/platforms/vue/LiveChattaView.js.map +1 -0
- package/dist/platforms/vue/useChattaBridge.d.ts +11 -0
- package/dist/platforms/vue/useChattaBridge.js +1 -0
- package/dist/platforms/vue/useChattaBridge.js.map +1 -0
- package/dist/platforms/vue/useChattaDeepLink.d.ts +2 -0
- package/dist/platforms/vue/useChattaDeepLink.js +1 -0
- package/dist/platforms/vue/useChattaDeepLink.js.map +1 -0
- package/dist/platforms/vue/useChattaPermissions.d.ts +9 -0
- package/dist/platforms/vue/useChattaPermissions.js +1 -0
- package/dist/platforms/vue/useChattaPermissions.js.map +1 -0
- package/dist/platforms/vue/useChattaUnread.d.ts +8 -0
- package/dist/platforms/vue/useChattaUnread.js +1 -0
- package/dist/platforms/vue/useChattaUnread.js.map +1 -0
- package/dist/platforms/vue/useLiveChatta.d.ts +58 -0
- package/dist/platforms/vue/useLiveChatta.js +1 -0
- package/dist/platforms/vue/useLiveChatta.js.map +1 -0
- package/dist/platforms/web/LiveChattaEmbed.d.ts +94 -0
- package/dist/platforms/web/LiveChattaEmbed.js +1 -0
- package/dist/platforms/web/LiveChattaEmbed.js.map +1 -0
- package/dist/platforms/web/bridge.d.ts +8 -0
- package/dist/platforms/web/bridge.js +1 -0
- package/dist/platforms/web/bridge.js.map +1 -0
- package/dist/platforms/web/permissions.d.ts +8 -0
- package/dist/platforms/web/permissions.js +1 -0
- package/dist/platforms/web/permissions.js.map +1 -0
- package/dist/types/billing.d.ts +355 -0
- package/dist/types/billing.js +53 -0
- package/dist/types/billing.js.map +1 -0
- package/dist/types/calendar.d.ts +132 -0
- package/dist/types/calendar.js +15 -0
- package/dist/types/calendar.js.map +1 -0
- package/dist/types/chat-core.d.ts +901 -0
- package/dist/types/chat-core.js +98 -0
- package/dist/types/chat-core.js.map +1 -0
- package/dist/types/chat-features.d.ts +775 -0
- package/dist/types/chat-features.js +50 -0
- package/dist/types/chat-features.js.map +1 -0
- package/dist/types/content.d.ts +138 -0
- package/dist/types/content.js +2 -0
- package/dist/types/content.js.map +1 -0
- package/dist/types/core/AutoRefresh.d.ts +68 -0
- package/dist/types/core/Bridge.d.ts +124 -0
- package/dist/types/core/Config.d.ts +26 -0
- package/dist/types/core/DeepLinks.d.ts +38 -0
- package/dist/types/core/EventBus.d.ts +15 -0
- package/dist/types/core/GrantStore.d.ts +29 -0
- package/dist/types/core/LiveChatta.d.ts +128 -0
- package/dist/types/core/Permissions.d.ts +34 -0
- package/dist/types/core/TokenManager.d.ts +25 -0
- package/dist/types/core/events.d.ts +140 -0
- package/dist/types/csat.d.ts +110 -0
- package/dist/types/csat.js +12 -0
- package/dist/types/csat.js.map +1 -0
- package/dist/types/events.d.ts +242 -0
- package/dist/types/events.js +275 -0
- package/dist/types/events.js.map +1 -0
- package/dist/types/extras.d.ts +353 -0
- package/dist/types/extras.js +31 -0
- package/dist/types/extras.js.map +1 -0
- package/dist/types/http/HttpAPI.d.ts +944 -0
- package/dist/types/http/HttpTransport.d.ts +66 -0
- package/dist/types/http/incomingWebhook.d.ts +17 -0
- package/dist/types/incoming-webhooks.d.ts +78 -0
- package/dist/types/incoming-webhooks.js +16 -0
- package/dist/types/incoming-webhooks.js.map +1 -0
- package/dist/types/index.d.ts +15 -0
- package/dist/types/index.js +16 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/liveflex.d.ts +578 -0
- package/dist/types/liveflex.js +7 -0
- package/dist/types/liveflex.js.map +1 -0
- package/dist/types/models.d.ts +1753 -0
- package/dist/types/models.js +148 -0
- package/dist/types/models.js.map +1 -0
- package/dist/types/options.d.ts +190 -0
- package/dist/types/options.js +43 -0
- package/dist/types/options.js.map +1 -0
- package/dist/types/shared-channels.d.ts +236 -0
- package/dist/types/shared-channels.js +50 -0
- package/dist/types/shared-channels.js.map +1 -0
- package/dist/types/socket/SocketAPI.d.ts +1026 -0
- package/dist/types/socket/SocketTransport.d.ts +44 -0
- package/dist/types/types/billing.d.ts +355 -0
- package/dist/types/types/calendar.d.ts +132 -0
- package/dist/types/types/chat-core.d.ts +901 -0
- package/dist/types/types/chat-features.d.ts +775 -0
- package/dist/types/types/content.d.ts +138 -0
- package/dist/types/types/csat.d.ts +110 -0
- package/dist/types/types/events.d.ts +242 -0
- package/dist/types/types/extras.d.ts +353 -0
- package/dist/types/types/incoming-webhooks.d.ts +78 -0
- package/dist/types/types/index.d.ts +15 -0
- package/dist/types/types/liveflex.d.ts +578 -0
- package/dist/types/types/models.d.ts +1753 -0
- package/dist/types/types/options.d.ts +190 -0
- package/dist/types/types/shared-channels.d.ts +236 -0
- package/dist/types/types/workspace-gifs.d.ts +95 -0
- package/dist/types/types/workspace.d.ts +390 -0
- package/dist/types/ui/EmbedConfig.d.ts +38 -0
- package/dist/types/ui/EmbedUI.d.ts +44 -0
- package/dist/types/ui/Launcher.d.ts +122 -0
- package/dist/types/ui/brand.d.ts +27 -0
- package/dist/types/ui/embedMessages.d.ts +23 -0
- package/dist/types/ui/hours.d.ts +35 -0
- package/dist/types/ui/prechat.d.ts +35 -0
- package/dist/types/ui/widgetConfig.d.ts +4 -0
- package/dist/types/utils/crypto.d.ts +6 -0
- package/dist/types/utils/hmac.d.ts +40 -0
- package/dist/types/utils/permissions.d.ts +5 -0
- package/dist/types/utils/platform.d.ts +18 -0
- package/dist/types/utils/visitor.d.ts +2 -0
- package/dist/types/workspace-gifs.d.ts +95 -0
- package/dist/types/workspace-gifs.js +3 -0
- package/dist/types/workspace-gifs.js.map +1 -0
- package/dist/types/workspace.d.ts +390 -0
- package/dist/types/workspace.js +13 -0
- package/dist/types/workspace.js.map +1 -0
- package/dist/umd/livechatta.umd.js +7262 -0
- package/dist/umd/livechatta.umd.js.map +1 -0
- package/dist/umd/livechatta.umd.min.js +2 -0
- package/dist/umd/livechatta.umd.min.js.map +1 -0
- package/package.json +278 -4
package/bin/lib/cli.mjs
ADDED
|
@@ -0,0 +1,2088 @@
|
|
|
1
|
+
// LiveChatta CLI: login, profiles, doctor, links, members, exports, messages, meetings, teams, plans, billing, store, gifts, GIF search, shared channels, incoming webhooks, LiveFlex, security, embed, webhooks.
|
|
2
|
+
// Zero dependencies (Node >= 18: global fetch). Every side effect goes through `io` for tests.
|
|
3
|
+
import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, chmodSync, readdirSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { createHmac, randomUUID } from 'node:crypto';
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_BASE_URL = 'https://api.livechatta.com';
|
|
9
|
+
const BOOL_FLAGS = new Set(['json', 'help', 'floating', 'inline', 'iframe', 'api-key-stdin', 'owner-token-stdin', 'version', 'apply-defaults', 'mine', 'yes', 'crypto', 'wait', 'text-stdin', 'once', 'allow-remote', 'no-admit', 'secret-stdin', 'legacy-secret-header', 'clear', 'sent', 'including-me', 'member-token-stdin', 'pin-stdin', 'show-url', 'token-stdin', 'url-stdin', 'quote']);
|
|
10
|
+
|
|
11
|
+
export const LINK_MODES = ['standard', 'support', 'creator', 'school', 'community', 'tech', 'public', 'private', 'webinar'];
|
|
12
|
+
export const WHO_CAN_JOIN = ['guest', 'members', 'invite'];
|
|
13
|
+
export const LINK_CODE_ERRORS = ['LINK_CODE_TOO_SHORT', 'LINK_CODE_TOO_LONG', 'LINK_CODE_INVALID', 'LINK_CODE_RESERVED', 'LINK_CODE_TAKEN'];
|
|
14
|
+
export const CONVERSATION_MODES = ['standard', 'broadcast', 'announcement', 'qa', 'voice', 'support'];
|
|
15
|
+
export const PLAN_REQUEST_FEATURES = [
|
|
16
|
+
'SSO', 'WHITE_LABEL', 'API_ACCESS', 'WEBINARS', 'AUTOMATION', 'ADVANCED_ANALYTICS', 'HOP_RECORDING', 'LONG_RETENTION', 'DEDICATED_SUPPORT',
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
export const WEBHOOK_EVENTS = [
|
|
20
|
+
'conversation:create', 'conversation:join', 'conversation:leave', 'conversation:lock', 'conversation:unlock', 'conversation:resolve', 'csat:submit',
|
|
21
|
+
'message:send', 'message:edit', 'message:delete', 'message:react', 'message:unreact', 'message:forward',
|
|
22
|
+
'message:pin', 'message:unpin', 'chat-user:create', 'chat-user:delete', 'chat-user:block', 'chat-user:unblock',
|
|
23
|
+
'post:create', 'post:update', 'post:delete', 'post:react', 'story:create', 'story:delete',
|
|
24
|
+
'subscription:paid', 'subscription:failed', 'subscription:renewed', 'subscription:cancelled',
|
|
25
|
+
'payment:paid', 'payment:failed', 'payment:pending', 'feature-payment:paid', 'feature-payment:failed',
|
|
26
|
+
'webinar:register', 'hop:start', 'hop:end', 'hop:participant-join', 'hop:participant-leave',
|
|
27
|
+
'hop:recording-start', 'hop:recording-pause', 'hop:recording-ready',
|
|
28
|
+
'meeting:schedule', 'meeting:update', 'meeting:cancel',
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
export const HELP = `chatta — LiveChatta command line
|
|
32
|
+
|
|
33
|
+
Usage: chatta <command> [options]
|
|
34
|
+
|
|
35
|
+
login [--api-key <key> | --api-key-stdin] [--base-url <url>]
|
|
36
|
+
Verify an API key and save it (~/.config/livechatta/config.json, 0600)
|
|
37
|
+
login --email <you@company.com> [--code <6 digits>] Owner sign-in: send a code, then verify it
|
|
38
|
+
login --totp <code> Finish a sign-in that asked for the authenticator app
|
|
39
|
+
login --owner-token <jwt> | --owner-token-stdin Save an owner token you already have
|
|
40
|
+
logout Forget the saved key and owner token (of this profile)
|
|
41
|
+
whoami Show the profile, base URL and the masked credentials in use
|
|
42
|
+
profiles [--json] Saved profiles; any command takes --profile <name> (or LIVECHATTA_PROFILE)
|
|
43
|
+
doctor [--json] Check the base URL, clock, API key, owner token and webhooks in one go
|
|
44
|
+
completion bash|zsh|fish Print a shell tab-completion script
|
|
45
|
+
members list <linkId> [--search <q>] [--status all|active|blocked|invited] [--limit <n>] [--cursor <c>] [--json] (owner)
|
|
46
|
+
members export <linkId> [--status …] [--out members.csv] Every member as CSV (owner)
|
|
47
|
+
members block <linkId> <memberId> --yes | members unblock <linkId> <memberId> (owner)
|
|
48
|
+
members revoke-invite <linkId> <memberId> --yes [--json] Off an invite-only link's list; blocked too if they joined (owner)
|
|
49
|
+
csat list [--from <ISO>] [--to <ISO>] [--link <linkId>] [--limit <n up to 20>] [--cursor <c>] [--json] Support satisfaction ratings, newest first
|
|
50
|
+
csat summary [--from <ISO>] [--to <ISO>] [--link <linkId>] [--json] Average, satisfied %, response rate, per agent and team
|
|
51
|
+
export <conversationId> [--format json|csv|html|txt] [--email <e>] [--wait] [--json] ZIP of a conversation
|
|
52
|
+
export list [--limit <n>] [--json] Recent exports and their download links
|
|
53
|
+
messages send <conversationId> <text…> | --text-stdin [--json] Send as the API key's owner (scripts, CI alerts)
|
|
54
|
+
messages tail <conversationId> [--since 10m|2h|<ISO>|all] [--once] [--json] Print new messages as they arrive (owner token; polls every 2 s)
|
|
55
|
+
meetings list --link <linkId> [--status upcoming|live|ended|all] [--limit <n up to 100>] [--cursor <c>] [--json] (owner)
|
|
56
|
+
meetings schedule --link <linkId> --title <t> --start <future ISO time> --invitees a@x.com,<memberId>,... (1 to 70)
|
|
57
|
+
[--duration <5-1440 min>] [--description <t>] [--timezone <IANA>] [--no-admit] [--idempotency-key <k>] [--json] (owner)
|
|
58
|
+
meetings cancel <meetingId> --yes [--reason <t up to 300>] [--json] Cancel a meeting; invitees are told. Safe to repeat (owner)
|
|
59
|
+
links list [--search <q>] [--limit <n>] [--cursor <c>] [--json]
|
|
60
|
+
links create --name <name> [--code <address>] [--caption <t>] [--type SINGLE|GROUP|CHANNEL] [--welcome <t>] [--mode <mode>] [--json]
|
|
61
|
+
links code <address> [--json] Is /in/<address> free? Reasons and suggestions (owner)
|
|
62
|
+
links modes [--json] Link and conversation mode catalog (owner token, else API key)
|
|
63
|
+
links who-can-join <linkId> guest|members|invite [--json] (owner)
|
|
64
|
+
links app-origins <linkId> <origin...> | --clear Native app origins allowed to frame the embed, up to 10 (owner)
|
|
65
|
+
links domain <linkId> [set <host> | verify | remove] [--json] Custom domain, white-label plans (owner)
|
|
66
|
+
links theme <linkId> --primary <hex> --secondary <hex> [--footer <t>] [--welcome-image <url|data-uri|file>] [--json] (owner)
|
|
67
|
+
links overview <linkId> [--json] Visitors, conversations, first reply (30 days) (owner)
|
|
68
|
+
links wipe <linkId> --yes Delete every message, keep the link (owner)
|
|
69
|
+
links mode get <code> [--json] Mode and join rules (public)
|
|
70
|
+
links mode set <linkId> <mode> [--apply-defaults] [--json] (owner)
|
|
71
|
+
links channels <code> [--json] Public channels on the join card
|
|
72
|
+
links join-policy <linkId> [--guests on|off] [--email-required on|off]
|
|
73
|
+
[--sign-in-required on|off] [--approval on|off] [--json] (owner)
|
|
74
|
+
links requests list <linkId> [--status pending|approved|denied] [--limit <n>] [--cursor <c>] [--json]
|
|
75
|
+
links requests approve|deny <linkId> <requestId> [--json] Ask to join review (owner)
|
|
76
|
+
conversations mode get <conversationId> [--json] (owner)
|
|
77
|
+
conversations mode set <conversationId> <mode> [--json] (owner)
|
|
78
|
+
conversations visibility get <conversationId> [--json] Private or public group or channel (owner)
|
|
79
|
+
conversations visibility set <conversationId> private|public [--json] Private: not listed, no self-join, members stay (owner)
|
|
80
|
+
teams list [--json] (owner)
|
|
81
|
+
teams create --name <n> [--description <t>] [--link <linkId>] [--members <id,id>] [--json]
|
|
82
|
+
plan request --name <n> --email <e> [--company <c>] [--links <n>] [--members-per-link <n>]
|
|
83
|
+
[--ai-credits <n>] [--features SSO,WHITE_LABEL,…] [--message <t>] [--mine] [--json]
|
|
84
|
+
plan status [--json] Your latest custom plan request (owner)
|
|
85
|
+
store list [--json] Add-ons and AI credit packs with per-day prices (public)
|
|
86
|
+
gifts catalog [--json] Person-to-person gifts (owner)
|
|
87
|
+
gifts earnings [--limit <n>] [--cursor <c>] [--json] Paid gifts, fee and net (owner)
|
|
88
|
+
gifs search <query…> [--source livechatta|provider] [--cursor <c>] [--json] Search GIFs (up to 60 characters; the LiveChatta pack answers when no provider is set)
|
|
89
|
+
gifs trending [--source livechatta|provider] [--cursor <c>] [--json] Trending GIFs (owner)
|
|
90
|
+
shared list --link <linkId> [--cursor <c>] [--json] Channels your workspace shares with another workspace (member)
|
|
91
|
+
shared invite <conversationId> --link <linkId> [--partner <linkCode>] [--hours <1-720>] [--json] Owner or admin; no --partner prints a single-use link once
|
|
92
|
+
shared preview --token <t> | --token-stdin [--json] Look at an invite link before accepting (does not use it up)
|
|
93
|
+
shared accept <sharedChannelId> | --token <t> | --token-stdin --link <linkId> --audience all|picked [--members <id,id>] --yes [--json]
|
|
94
|
+
shared audience <sharedChannelId> --link <linkId> --audience all|picked [--members <id,id>] --yes Change who on your team has the channel
|
|
95
|
+
shared members --link <linkId> [--search <q>] [--channel <sharedChannelId>] [--cursor <c>] [--json] Your people to pick (name and handle only)
|
|
96
|
+
shared leave <sharedChannelId> --link <linkId> --yes [--json] Leave, remove the partner, or cancel or decline an invite (also: shared end)
|
|
97
|
+
shared channel <conversationId> --link <linkId> [--json] The shares of one of your channels
|
|
98
|
+
shared permissions <conversationId> --link <linkId> [--json] What your workspace may do in it, and who is from another workspace
|
|
99
|
+
shared audit <sharedChannelId> --link <linkId> [--cursor <c>] [--json] Your workspace's activity log for a share
|
|
100
|
+
shared dm <conversationId> <memberId> --link <linkId> [--json] Message a person of the other workspace (both links need shared DMs on)
|
|
101
|
+
shared remove-member <conversationId> <memberId> --link <linkId> --yes Host removes one partner member
|
|
102
|
+
shared remove-message <conversationId> <messageId> --link <linkId> --yes Wipe a message for everyone
|
|
103
|
+
shared link-account <accountId> <chatUserId> --yes Bind a teammate to their chat user so they count as staff (owner)
|
|
104
|
+
billing storage [--json] This month's uploads against the allowance (owner)
|
|
105
|
+
billing renewal [--json] Where a bank-transfer or paused plan stands (owner)
|
|
106
|
+
billing renew <subscriptionId> [--method bank_transfer|card] [--json] Checkout link for the next period
|
|
107
|
+
billing pending [--json] Bank transfers not settled yet (plan changes, extra seats) (owner)
|
|
108
|
+
billing storage-renew <purchaseId> on|off [--json] Storage pack auto-renew (owner)
|
|
109
|
+
billing trial [--json] Free trial status (owner)
|
|
110
|
+
billing trial start --plan <planId> [--cycle MONTHLY|QUARTERLY|SEMI_YEARLY|YEARLY] [--json]
|
|
111
|
+
keys list [--limit <n>] [--json]
|
|
112
|
+
keys create --name <n> [--origins acme.com,https://app.acme.com,*.acme.com] [--description <t>] [--json]
|
|
113
|
+
keys update <keyId> [--name <n>] [--origins <list>|none] [--json]
|
|
114
|
+
keys rotate <keyId> --yes [--json] New key, same name and sites; the old one stops (shown once)
|
|
115
|
+
keys revoke <keyId> --yes [--json] Stop a key for good
|
|
116
|
+
keys usage <keyId> [--period 7d|30d|90d] [--json] Requests and errors per day
|
|
117
|
+
security staff-access [--limit <n>] [--cursor <c>] [--json] When LiveChatta staff viewed or acted (owner)
|
|
118
|
+
security grant [--json] Is LiveChatta support allowed in right now? (owner)
|
|
119
|
+
security grant on --mode view|act --hours 1|24|72|168 [--json] Let support in for a while (owner)
|
|
120
|
+
security grant off [--json] Turn support access off; open staff sessions end (owner)
|
|
121
|
+
liveflex [--json] The business LiveFlex balance, payout details and limits (owner)
|
|
122
|
+
liveflex history [--kind fund|withdraw|transfer_in|transfer_out|gift_sent|gift_received|payment|refund] [--limit <n>] [--cursor <c>] [--json]
|
|
123
|
+
liveflex fund <amount> [--crypto] [--json] Buy FlexCoin — checkout link (1.5% fee, max 2 FlexCoin) (owner)
|
|
124
|
+
liveflex send <amount> --to <memberId|business> [--note <t>] [--json] Free FlexCoin send inside the workspace (owner)
|
|
125
|
+
liveflex withdraw <amount> --method bank|crypto [--quote | --yes] [--expect-total <amount>] [--json]
|
|
126
|
+
Cash out FlexCoin to saved payout details (10 min). Without --yes it shows the quote (fee, network fee, total).
|
|
127
|
+
--yes locks the total it has just quoted; --expect-total pins the total you saw (required with --yes for crypto).
|
|
128
|
+
If fees move, it stops (FEES_CHANGED) before anything is taken (owner)
|
|
129
|
+
liveflex request <amount> --to <@handle|$tag|memberId> --chat <conversationId> [--note <t>] [--json] Ask for money (never takes it) (member)
|
|
130
|
+
liveflex request list [--sent] | get|decline|block|cancel <id> Your requests; block stops asks from that person (member)
|
|
131
|
+
liveflex request pay <id> --yes [--pin-stdin] [--code <c>] Pay a request from your LiveFlex (member)
|
|
132
|
+
liveflex split <total> --with <@a,@b,$c> --chat <conversationId> [--including-me] [--shares a=10,b=14] [--note <t>] [--json] (member)
|
|
133
|
+
liveflex split get|cancel <id> [--json] The group card: who has paid (member)
|
|
134
|
+
liveflex standing [list] [--json] Standing payments (yours, or the business's)
|
|
135
|
+
liveflex standing create <amount> --to <@handle|$tag|memberId> --every week|2weeks|month [--from <date>] [--until <date>] [--times <n>] [--note <t>] --yes [--pin-stdin] (member)
|
|
136
|
+
liveflex standing pause|resume|cancel <id> [--json]
|
|
137
|
+
liveflex pots create <title> --chat <conversationId> [--each <amount>] [--goal <amount>] [--by <date>] [--json] (member)
|
|
138
|
+
liveflex pots get <id> | contribute <id> [<amount>] --yes [--pin-stdin] | close <id> --yes | cancel <id> --yes (member)
|
|
139
|
+
liveflex refund <transactionId> [<amount>] [--note <t>] --yes [--pin-stdin] [--key <k>] Give back a payment you received
|
|
140
|
+
liveflex paylink create <amount> --chat <conversationId> --for <description> [--ref <r>] [--json] Staff checkout card (member)
|
|
141
|
+
liveflex paylink get|cancel <id> | pay <id> --method wallet|card [--yes] [--pin-stdin] (member)
|
|
142
|
+
liveflex receipt [<reference>] [--out <file.pdf> | --show-url] [--json] Save one PDF (the signed link prints only with --show-url)
|
|
143
|
+
liveflex statement <YYYY-MM|last> [--format pdf|csv] [--out <file> | --show-url] [--json] Monthly statement (the owner token gets the business's)
|
|
144
|
+
embed snippet --link <code> [--iframe] [--theme light|dark|system] [--primary <hex>]
|
|
145
|
+
[--secondary <hex>] [--position bottom-right|bottom-left] [--greeting <t>] [--title <t>]
|
|
146
|
+
hooks list <conversationId> [--status active|revoked|all] [--cursor <c>] [--json] Incoming webhooks of a group or channel (API key)
|
|
147
|
+
hooks create <conversationId> --name <n> [--bot-name <n>] [--bot-avatar <https url>] [--json] Prints the secret URL once
|
|
148
|
+
hooks rename <conversationId> <hookId> [--name <n>] [--bot-name <n>] [--bot-avatar <https url>]
|
|
149
|
+
hooks regenerate <conversationId> <hookId> --yes The old URL stops at once; the new one prints once
|
|
150
|
+
hooks revoke <conversationId> <hookId> --yes The URL stops for good; old messages stay
|
|
151
|
+
hooks send <text…> [--url-stdin | --url <hookUrl>] [--text-stdin] [--username <n>] [--icon-url <https url>]
|
|
152
|
+
Post a message to an incoming webhook URL (no key needed). The URL comes from LIVECHATTA_HOOK_URL,
|
|
153
|
+
--url-stdin (first line) or --url (warns: it lands in shell history). https only, http for localhost.
|
|
154
|
+
webhooks list [--json]
|
|
155
|
+
webhooks deliveries <webhookId> [--limit <n>] [--json] (owner)
|
|
156
|
+
webhooks retry <webhookId> <deliveryId> (owner)
|
|
157
|
+
webhooks rotate-secret <webhookId> [--json] Prints the new secret once (owner)
|
|
158
|
+
webhooks test <url> [--event message:send] [--secret-stdin] [--legacy-secret-header]
|
|
159
|
+
POST a sample event exactly as LiveChatta delivers it (secret: LIVECHATTA_WEBHOOK_SECRET or stdin)
|
|
160
|
+
webhooks listen <webhookId> [--forward http://localhost:3000/hook] [--allow-remote] [--json]
|
|
161
|
+
Watch real deliveries for 30 min at a time and replay each to your local server (owner).
|
|
162
|
+
Only the signature is forwarded. --legacy-secret-header (local targets only) adds the old X-Webhook-Secret.
|
|
163
|
+
|
|
164
|
+
Link modes: ${LINK_MODES.join(', ')}
|
|
165
|
+
Conversation modes: ${CONVERSATION_MODES.join(', ')}
|
|
166
|
+
Env: LIVECHATTA_API_KEY, LIVECHATTA_OWNER_TOKEN, LIVECHATTA_MEMBER_TOKEN (member commands), LIVECHATTA_BASE_URL, LIVECHATTA_PROFILE, LIVECHATTA_CONFIG (config file path).
|
|
167
|
+
`;
|
|
168
|
+
|
|
169
|
+
export class CliError extends Error {
|
|
170
|
+
constructor(message, code = 1) {
|
|
171
|
+
super(message);
|
|
172
|
+
this.exitCode = code;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** `--a b`, `--a=b`, boolean flags, and positionals. */
|
|
177
|
+
export function parseArgs(argv) {
|
|
178
|
+
const flags = {};
|
|
179
|
+
const positional = [];
|
|
180
|
+
for (let i = 0; i < argv.length; i++) {
|
|
181
|
+
const a = argv[i];
|
|
182
|
+
if (a === '-h') flags.help = true;
|
|
183
|
+
else if (a.startsWith('--')) {
|
|
184
|
+
const eq = a.indexOf('=');
|
|
185
|
+
const key = eq > 0 ? a.slice(2, eq) : a.slice(2);
|
|
186
|
+
if (eq > 0) flags[key] = a.slice(eq + 1);
|
|
187
|
+
else if (BOOL_FLAGS.has(key)) flags[key] = true;
|
|
188
|
+
else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) flags[key] = argv[++i];
|
|
189
|
+
else throw new CliError(`--${key} needs a value`, 2);
|
|
190
|
+
} else positional.push(a);
|
|
191
|
+
}
|
|
192
|
+
return { flags, positional };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const PROFILE_NAME = /^[a-z0-9][a-z0-9_-]{0,31}$/i;
|
|
196
|
+
|
|
197
|
+
/** One config file per profile: config.json is "default", others live in profiles/<name>.json. */
|
|
198
|
+
export function configPath(env, profile) {
|
|
199
|
+
const name = profile || env.LIVECHATTA_PROFILE || '';
|
|
200
|
+
if (name && !PROFILE_NAME.test(name)) throw new CliError('--profile is 1–32 letters, digits, - or _', 2);
|
|
201
|
+
const base = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config');
|
|
202
|
+
if (name && name !== 'default') return join(env.LIVECHATTA_CONFIG ? dirname(env.LIVECHATTA_CONFIG) : join(base, 'livechatta'), 'profiles', `${name}.json`);
|
|
203
|
+
if (env.LIVECHATTA_CONFIG) return env.LIVECHATTA_CONFIG;
|
|
204
|
+
return join(base, 'livechatta', 'config.json');
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function readConfig(path) {
|
|
208
|
+
try {
|
|
209
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
210
|
+
} catch {
|
|
211
|
+
return {};
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function writeConfig(path, cfg) {
|
|
216
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
217
|
+
writeFileSync(path, `${JSON.stringify(cfg, null, 2)}\n`, { mode: 0o600 });
|
|
218
|
+
chmodSync(path, 0o600);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function maskKey(key) {
|
|
222
|
+
if (!key) return '(none)';
|
|
223
|
+
return key.length <= 8 ? '****' : `${key.slice(0, 4)}…${key.slice(-4)}`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function cleanBase(url) {
|
|
227
|
+
const u = String(url || DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
228
|
+
if (!/^https?:\/\//.test(u)) throw new CliError(`Base URL must start with http(s)://, got "${u}"`, 2);
|
|
229
|
+
return u;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Flag > env > saved config > default. */
|
|
233
|
+
export function resolveAuth(flags, env, cfg) {
|
|
234
|
+
return {
|
|
235
|
+
apiKey: flags['api-key'] || env.LIVECHATTA_API_KEY || cfg.apiKey || '',
|
|
236
|
+
ownerToken: flags['owner-token'] || env.LIVECHATTA_OWNER_TOKEN || cfg.ownerToken || '',
|
|
237
|
+
memberToken: flags['member-token'] || env.LIVECHATTA_MEMBER_TOKEN || '',
|
|
238
|
+
baseUrl: cleanBase(flags['base-url'] || env.LIVECHATTA_BASE_URL || cfg.baseUrl),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const ROOTS = { external: '/api/v1/external', api: '/api/v1', root: '' };
|
|
243
|
+
const RELOGIN = 'Run `chatta login --email <you@company.com>` or set LIVECHATTA_OWNER_TOKEN.';
|
|
244
|
+
const NO_OWNER = `No owner token. ${RELOGIN}`;
|
|
245
|
+
|
|
246
|
+
/** API-key call under /api/v1/external (the original CLI surface). */
|
|
247
|
+
function api(io, auth, method, path, opts = {}) {
|
|
248
|
+
return call(io, auth, method, path, { ...opts, cred: 'apiKey', base: 'external' });
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Owner-token call under /api/v1. */
|
|
252
|
+
function ownerApi(io, auth, method, path, opts = {}) {
|
|
253
|
+
return call(io, auth, method, path, { ...opts, cred: 'owner', base: 'api' });
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Chat-member call: your own LiveFlex (requests, splits, pots, pay links). The token never goes in the config file. */
|
|
257
|
+
function memberApi(io, auth, method, path, opts = {}) {
|
|
258
|
+
return call(io, auth, method, path, { ...opts, cred: 'member', base: 'api' });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Member token when set, else the owner token (the business): receipts, statements, standing payments, refunds. */
|
|
262
|
+
function userApi(io, auth, method, path, opts = {}) {
|
|
263
|
+
return call(io, auth, method, path, { ...opts, cred: 'user', base: 'api' });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Public call: /api/v1 by default, `base: 'root'` for /in/:code. */
|
|
267
|
+
function publicApi(io, auth, method, path, opts = {}) {
|
|
268
|
+
return call(io, auth, method, path, { base: 'api', ...opts, cred: 'none' });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function call(io, auth, method, path, { query, body, cred, base, headers: extra }) {
|
|
272
|
+
if (cred === 'apiKey' && !auth.apiKey) throw new CliError('No API key. Run `chatta login --api-key <key>` or set LIVECHATTA_API_KEY.');
|
|
273
|
+
if (cred === 'owner' && !auth.ownerToken) throw new CliError(NO_OWNER);
|
|
274
|
+
if (cred === 'member' && !auth.memberToken) throw new CliError('This is for a chat member. Set LIVECHATTA_MEMBER_TOKEN (or pipe it with --member-token-stdin) to the member sign-in token.');
|
|
275
|
+
if (cred === 'user' && !auth.memberToken && !auth.ownerToken) throw new CliError(`No token. Set LIVECHATTA_MEMBER_TOKEN for your own LiveFlex, or sign in as the owner for the business. ${RELOGIN}`);
|
|
276
|
+
const qs = query ? new URLSearchParams(Object.entries(query).filter(([, v]) => v !== undefined && v !== '')).toString() : '';
|
|
277
|
+
const url = `${auth.baseUrl}${ROOTS[base]}${path}${qs ? `?${qs}` : ''}`;
|
|
278
|
+
const headers = { 'Content-Type': 'application/json', ...extra };
|
|
279
|
+
if (cred === 'apiKey') headers['x-api-key'] = auth.apiKey;
|
|
280
|
+
if (cred === 'owner') headers.Authorization = `Bearer ${auth.ownerToken}`;
|
|
281
|
+
if (cred === 'member') headers.Authorization = `Bearer ${auth.memberToken}`;
|
|
282
|
+
if (cred === 'user') headers.Authorization = `Bearer ${auth.memberToken || auth.ownerToken}`;
|
|
283
|
+
let res;
|
|
284
|
+
try {
|
|
285
|
+
res = await io.fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined });
|
|
286
|
+
} catch (e) {
|
|
287
|
+
throw Object.assign(new CliError(`Could not reach ${auth.baseUrl}: ${e?.message || e}`), { retryable: true });
|
|
288
|
+
}
|
|
289
|
+
const text = await res.text();
|
|
290
|
+
let data = null;
|
|
291
|
+
try {
|
|
292
|
+
data = text ? JSON.parse(text) : null;
|
|
293
|
+
} catch {
|
|
294
|
+
data = text;
|
|
295
|
+
}
|
|
296
|
+
if (cred === 'apiKey' && (res.status === 401 || res.status === 403)) throw new CliError('API key rejected (401/403). Check the key and the base URL.');
|
|
297
|
+
if (cred === 'owner' && res.status === 401) throw new CliError(`Owner token rejected or expired (401). ${RELOGIN}`);
|
|
298
|
+
if (!res.ok) {
|
|
299
|
+
const msg = data && typeof data === 'object' ? [].concat(data.message || data.error || '').join('; ') : '';
|
|
300
|
+
const code = data && typeof data === 'object' && typeof data.code === 'string' ? ` [${data.code}]` : '';
|
|
301
|
+
const apiData = data && typeof data === 'object' ? data : undefined;
|
|
302
|
+
throw Object.assign(new CliError(`${method} ${path} failed: HTTP ${res.status}${code}${msg ? ` — ${msg}` : ''}`), { retryable: res.status >= 500 || res.status === 429, apiCode: apiData?.code, apiData });
|
|
303
|
+
}
|
|
304
|
+
return data;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function listOf(data) {
|
|
308
|
+
if (Array.isArray(data)) return data;
|
|
309
|
+
return data?.results || data?.data || data?.docs || [];
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function table(rows, cols) {
|
|
313
|
+
const w = cols.map((c) => Math.max(c.length, ...rows.map((r) => String(r[c] ?? '').length)));
|
|
314
|
+
const line = (r) => cols.map((c, i) => String(r[c] ?? '').padEnd(w[i])).join(' ').trimEnd();
|
|
315
|
+
return [line(Object.fromEntries(cols.map((c) => [c, c.toUpperCase()]))), ...rows.map(line)].join('\n');
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const HEX = /^#?[0-9a-f]{3}([0-9a-f]{3})?$/i;
|
|
319
|
+
const esc = (s) => String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
320
|
+
const js = (s) => JSON.stringify(String(s)).replace(/</g, '\\u003c');
|
|
321
|
+
|
|
322
|
+
/** HTML for a page: plain iframe (no key needed) or the SDK floating launcher. */
|
|
323
|
+
export function embedSnippet(flags, baseUrl, version) {
|
|
324
|
+
const code = flags.link;
|
|
325
|
+
if (!code || !/^[\w-]{2,64}$/.test(code)) throw new CliError('embed snippet needs --link <code> (letters, digits, - or _)', 2);
|
|
326
|
+
const theme = flags.theme || 'system';
|
|
327
|
+
if (!['light', 'dark', 'system'].includes(theme)) throw new CliError('--theme must be light, dark or system', 2);
|
|
328
|
+
for (const k of ['primary', 'secondary']) {
|
|
329
|
+
if (flags[k] && !HEX.test(flags[k])) throw new CliError(`--${k} must be a hex colour like #0B6E66`, 2);
|
|
330
|
+
}
|
|
331
|
+
const hex = (v) => {
|
|
332
|
+
const h = String(v).replace('#', '').toUpperCase();
|
|
333
|
+
return `#${h.length === 3 ? h.replace(/./g, '$&$&') : h}`;
|
|
334
|
+
};
|
|
335
|
+
if (flags.iframe) {
|
|
336
|
+
const q = new URLSearchParams({ theme });
|
|
337
|
+
if (flags.primary) q.set('primaryColor', hex(flags.primary).slice(1));
|
|
338
|
+
if (flags.secondary) q.set('secondaryColor', hex(flags.secondary).slice(1));
|
|
339
|
+
return `<iframe src="${esc(`${baseUrl}/in/${code}/embed/chat?${q}`)}"\n title="${esc(flags.title || 'Chat')}"\n` +
|
|
340
|
+
' allow="microphone; camera; display-capture; clipboard-write"\n style="width:100%;height:640px;border:0"></iframe>\n';
|
|
341
|
+
}
|
|
342
|
+
const opts = [`floating: true`, `theme: ${js(theme)}`];
|
|
343
|
+
if (flags.position) {
|
|
344
|
+
if (!['bottom-right', 'bottom-left'].includes(flags.position)) throw new CliError('--position must be bottom-right or bottom-left', 2);
|
|
345
|
+
opts.push(`position: ${js(flags.position)}`);
|
|
346
|
+
}
|
|
347
|
+
if (flags.title) opts.push(`title: ${js(flags.title)}`);
|
|
348
|
+
if (flags.greeting) opts.push(`greeting: ${js(flags.greeting)}`);
|
|
349
|
+
if (flags.primary) opts.push(`primaryColor: ${js(hex(flags.primary))}`);
|
|
350
|
+
if (flags.secondary) opts.push(`secondaryColor: ${js(hex(flags.secondary))}`);
|
|
351
|
+
return `<!-- LiveChatta widget. Replace the placeholders; never ship a secret key to a public page you do not control. -->
|
|
352
|
+
<script src="https://unpkg.com/@livechatta/sdk@${version}/dist/umd/livechatta.umd.min.js"></script>
|
|
353
|
+
<script>
|
|
354
|
+
const { LiveChatta } = window.LiveChatta;
|
|
355
|
+
LiveChatta.init({
|
|
356
|
+
linkCode: ${js(code)},
|
|
357
|
+
baseUrl: ${js(baseUrl)},
|
|
358
|
+
apiKey: 'YOUR_API_KEY',
|
|
359
|
+
publicKey: 'YOUR_EMBED_PUBLIC_KEY_PEM',
|
|
360
|
+
chatUsername: 'SIGNED_IN_USER_ID',
|
|
361
|
+
enableSocket: false,
|
|
362
|
+
});
|
|
363
|
+
LiveChatta.ui({ ${opts.join(', ')} });
|
|
364
|
+
</script>
|
|
365
|
+
`;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Sample `data` for a webhook event, shaped like the real payloads. */
|
|
369
|
+
export function sampleWebhookData(event, now) {
|
|
370
|
+
const id = (p) => `${p}${now.getTime().toString(16).padStart(20, '0').slice(-20)}`;
|
|
371
|
+
if (event.startsWith('message:')) {
|
|
372
|
+
return { messageId: id('6a'), conversationId: id('6b'), senderId: id('6c'), message: 'Test message from chatta CLI', createdAt: now.toISOString() };
|
|
373
|
+
}
|
|
374
|
+
if (event.startsWith('conversation:')) return { conversationId: id('6b'), memberId: id('6c'), chatLinkCode: 'test-link' };
|
|
375
|
+
if (event.startsWith('chat-user:')) return { chatUserId: id('6c'), displayName: 'Test User' };
|
|
376
|
+
return { id: id('6d'), test: true };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** `t=<unix>,v1=<hex>`: HMAC-SHA256 of "<t>." + body with the webhook secret, as LiveChatta signs deliveries. */
|
|
380
|
+
export function webhookSignature(secret, body, nowSec) {
|
|
381
|
+
return `t=${nowSec},v1=${createHmac('sha256', secret).update(`${nowSec}.${body}`).digest('hex')}`;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async function webhookTest(io, flags, positional) {
|
|
385
|
+
const url = positional[0];
|
|
386
|
+
if (!url || !/^https?:\/\//.test(url)) throw new CliError('webhooks test needs an http(s) URL: chatta webhooks test https://example.com/hook', 2);
|
|
387
|
+
const event = flags.event || 'message:send';
|
|
388
|
+
if (!WEBHOOK_EVENTS.includes(event)) throw new CliError(`Unknown event "${event}". One of: ${WEBHOOK_EVENTS.join(', ')}`, 2);
|
|
389
|
+
const now = io.now();
|
|
390
|
+
if (flags['legacy-secret-header']) {
|
|
391
|
+
// same rule as `webhooks listen`: the raw secret goes to this machine only, never to a remote host (https or not)
|
|
392
|
+
if (!isLocalHost(new URL(url).hostname)) throw new CliError('--legacy-secret-header only works with a localhost target: it would send your raw secret to a remote host.', 2);
|
|
393
|
+
}
|
|
394
|
+
const secret = await webhookSecretFrom(io, flags);
|
|
395
|
+
if (flags['legacy-secret-header'] && !secret) throw new CliError('--legacy-secret-header needs the secret: set LIVECHATTA_WEBHOOK_SECRET or pass --secret-stdin.', 2);
|
|
396
|
+
const deliveryId = `evt_${(io.randomId ? io.randomId() : randomUUID()).replace(/-/g, '')}`;
|
|
397
|
+
const body = JSON.stringify({ id: deliveryId, event, timestamp: now.toISOString(), data: sampleWebhookData(event, now) });
|
|
398
|
+
const started = Date.now();
|
|
399
|
+
let res;
|
|
400
|
+
try {
|
|
401
|
+
res = await io.fetch(url, {
|
|
402
|
+
method: 'POST',
|
|
403
|
+
headers: {
|
|
404
|
+
'Content-Type': 'application/json',
|
|
405
|
+
'X-Webhook-Event': event,
|
|
406
|
+
'X-Webhook-Attempt': '1',
|
|
407
|
+
'X-Webhook-Id': deliveryId,
|
|
408
|
+
...(secret ? { 'X-Webhook-Signature': webhookSignature(secret, body, Math.floor(now.getTime() / 1000)) } : {}),
|
|
409
|
+
...(flags['legacy-secret-header'] ? { 'X-Webhook-Secret': secret } : {}),
|
|
410
|
+
},
|
|
411
|
+
body,
|
|
412
|
+
redirect: 'manual',
|
|
413
|
+
});
|
|
414
|
+
} catch (e) {
|
|
415
|
+
throw new CliError(`Delivery failed: ${e?.message || e}`);
|
|
416
|
+
}
|
|
417
|
+
const ms = Date.now() - started;
|
|
418
|
+
io.out(`POST ${url}\nevent ${event}\n→ HTTP ${res.status} in ${ms} ms`);
|
|
419
|
+
if (!res.ok) throw new CliError('Endpoint did not return 2xx; LiveChatta would retry up to 10 times over about 29 hours (first after 30 s, then 2 min, 10 min, 30 min, 1 h ...).');
|
|
420
|
+
return 0;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const int = (v, name, min, max) => {
|
|
424
|
+
if (v === undefined) return undefined;
|
|
425
|
+
const n = Number(v);
|
|
426
|
+
if (!Number.isInteger(n) || n < min || n > max) throw new CliError(`--${name} must be a whole number from ${min} to ${max}`, 2);
|
|
427
|
+
return n;
|
|
428
|
+
};
|
|
429
|
+
const csv = (v) => (v === undefined ? undefined : String(v).split(',').map((x) => x.trim()).filter(Boolean));
|
|
430
|
+
const out = (io, flags, data, text) => {
|
|
431
|
+
io.out(flags.json ? JSON.stringify(data, null, 2) : text());
|
|
432
|
+
return 0;
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
/** Owner sign-in: email code (+ authenticator app) or a pasted token; saves the access token 0600. */
|
|
436
|
+
async function ownerLogin(io, flags, cfg, path) {
|
|
437
|
+
const baseUrl = cleanBase(flags['base-url'] || io.env.LIVECHATTA_BASE_URL || cfg.baseUrl);
|
|
438
|
+
const a = { baseUrl };
|
|
439
|
+
const save = (ownerToken, note = '') => {
|
|
440
|
+
const next = { ...cfg, baseUrl, ownerToken };
|
|
441
|
+
delete next.pendingToken;
|
|
442
|
+
writeConfig(path, next);
|
|
443
|
+
io.out(`Signed in to ${baseUrl} as an owner (${maskKey(ownerToken)}). Saved to ${path}${note}`);
|
|
444
|
+
return 0;
|
|
445
|
+
};
|
|
446
|
+
const finish = (res) => {
|
|
447
|
+
if (res?.require2fa && res.pendingToken) {
|
|
448
|
+
writeConfig(path, { ...cfg, baseUrl, pendingToken: res.pendingToken });
|
|
449
|
+
io.out('This account uses an authenticator app. Run: chatta login --totp <code>');
|
|
450
|
+
return 0;
|
|
451
|
+
}
|
|
452
|
+
if (!res?.accessToken) throw new CliError('Sign-in did not return a token.');
|
|
453
|
+
const mins = Number(res.expireInSeconds) > 0 ? Math.round(res.expireInSeconds / 60) : 0;
|
|
454
|
+
return save(res.accessToken, mins ? `\nThe token lasts about ${mins} min; sign in again when it expires.` : '');
|
|
455
|
+
};
|
|
456
|
+
if (flags['owner-token'] || flags['owner-token-stdin']) {
|
|
457
|
+
const token = flags['owner-token-stdin'] ? (await io.readStdin()).trim() : String(flags['owner-token']);
|
|
458
|
+
if (!token) throw new CliError('No owner token given.', 2);
|
|
459
|
+
await ownerApi(io, { ...a, ownerToken: token }, 'GET', '/users/me');
|
|
460
|
+
return save(token);
|
|
461
|
+
}
|
|
462
|
+
if (flags.totp) {
|
|
463
|
+
if (!cfg.pendingToken) throw new CliError('No sign-in is waiting for an authenticator code. Start with chatta login --email <e>.', 2);
|
|
464
|
+
return finish(await publicApi(io, a, 'POST', '/users/2fa/verify', { body: { pendingToken: cfg.pendingToken, token: String(flags.totp) } }));
|
|
465
|
+
}
|
|
466
|
+
const email = String(flags.email || '');
|
|
467
|
+
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) throw new CliError('--email must be an email address', 2);
|
|
468
|
+
if (!flags.code) {
|
|
469
|
+
await publicApi(io, a, 'POST', '/users/sign-in-code', { body: { email } });
|
|
470
|
+
io.out(`If ${email} has a business account, a 6-digit code is on its way (valid 10 min).\nThen run: chatta login --email ${email} --code <code>`);
|
|
471
|
+
return 0;
|
|
472
|
+
}
|
|
473
|
+
if (!/^\d{6}$/.test(String(flags.code))) throw new CliError('--code is the 6-digit code from the email', 2);
|
|
474
|
+
return finish(await publicApi(io, a, 'POST', '/users/sign-in-code/verify', { body: { email, code: String(flags.code) } }));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async function linksMode(io, flags, auth, [action, target, mode]) {
|
|
478
|
+
if (action === 'get') {
|
|
479
|
+
if (!target) throw new CliError('links mode get needs a link code', 2);
|
|
480
|
+
const info = await publicApi(io, auth(), 'GET', `/in/${encodeURIComponent(target)}`, { base: 'root' });
|
|
481
|
+
const jp = info?.joinPolicy || {};
|
|
482
|
+
const rules = ['guests', 'emailRequired', 'signInRequired', 'inviteOnly', 'approval'].filter((k) => jp[k]).join(', ') || 'none';
|
|
483
|
+
return out(io, flags, { code: info?.code, mode: info?.mode ?? null, joinPolicy: jp },
|
|
484
|
+
() => `${info?.name || target} (${info?.code || target})\nmode ${info?.mode || 'standard (pre-modes link)'}\njoin rules ${rules}`);
|
|
485
|
+
}
|
|
486
|
+
if (action === 'set') {
|
|
487
|
+
if (!target || !mode) throw new CliError('links mode set needs <linkId> <mode>', 2);
|
|
488
|
+
if (!LINK_MODES.includes(mode)) throw new CliError(`Unknown link mode "${mode}". One of: ${LINK_MODES.join(', ')}`, 2);
|
|
489
|
+
const body = { mode, ...(flags['apply-defaults'] ? { applyDefaults: true } : {}) };
|
|
490
|
+
const r = await ownerApi(io, auth(), 'PATCH', `/chats/links/${encodeURIComponent(target)}/mode`, { body });
|
|
491
|
+
return out(io, flags, r, () => `Link ${r?.linkId || target} is now "${r?.mode || mode}" (${r?.linkType || '?'}).` +
|
|
492
|
+
(r?.created?.length ? `\nCreated: ${r.created.join(', ')}` : ''));
|
|
493
|
+
}
|
|
494
|
+
throw new CliError('Usage: chatta links mode get <code> | links mode set <linkId> <mode> [--apply-defaults]', 2);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const JOIN_FLAGS = { guests: 'guests', 'email-required': 'emailRequired', 'sign-in-required': 'signInRequired', approval: 'approval' };
|
|
498
|
+
const JOIN_STATUSES = ['pending', 'approved', 'denied'];
|
|
499
|
+
|
|
500
|
+
function onOff(v, name) {
|
|
501
|
+
const t = String(v).toLowerCase();
|
|
502
|
+
if (['on', 'true', 'yes', '1'].includes(t)) return true;
|
|
503
|
+
if (['off', 'false', 'no', '0'].includes(t)) return false;
|
|
504
|
+
throw new CliError(`--${name} must be on or off`, 2);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
async function linksJoinPolicy(io, flags, auth, [linkId]) {
|
|
508
|
+
if (!linkId) throw new CliError('links join-policy needs <linkId>', 2);
|
|
509
|
+
const body = {};
|
|
510
|
+
for (const [flag, key] of Object.entries(JOIN_FLAGS)) if (flags[flag] !== undefined) body[key] = onOff(flags[flag], flag);
|
|
511
|
+
if (!Object.keys(body).length) throw new CliError('links join-policy needs at least one of --guests, --email-required, --sign-in-required, --approval', 2);
|
|
512
|
+
const jp = await ownerApi(io, auth(), 'PATCH', `/chats/links/${encodeURIComponent(linkId)}/join-policy`, { body });
|
|
513
|
+
const on = Object.values(JOIN_FLAGS).concat('inviteOnly').filter((k) => jp?.[k]).join(', ') || 'none';
|
|
514
|
+
return out(io, flags, jp, () => `Join rules for ${linkId}: ${on}`);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async function linksRequests(io, flags, auth, [action, linkId, requestId]) {
|
|
518
|
+
const base = `/chats/links/${encodeURIComponent(linkId || '')}/join-requests`;
|
|
519
|
+
if (action === 'list' && linkId) {
|
|
520
|
+
if (flags.status && !JOIN_STATUSES.includes(flags.status)) throw new CliError(`--status must be one of ${JOIN_STATUSES.join(', ')}`, 2);
|
|
521
|
+
const limit = int(flags.limit, 'limit', 1, 20);
|
|
522
|
+
const page = await ownerApi(io, auth(), 'GET', base, { query: { status: flags.status, limit: limit && String(limit), nextCursor: flags.cursor } });
|
|
523
|
+
const rows = listOf(page).map((r) => ({ id: r._id, name: r.name, email: r.email, status: r.status, asked: r.createdAt || '' }));
|
|
524
|
+
return out(io, flags, page, () => (rows.length ? table(rows, ['id', 'name', 'email', 'status', 'asked']) : 'No requests.') +
|
|
525
|
+
`
|
|
526
|
+
${page?.pending ?? 0} pending` + (page?.nextCursor ? `
|
|
527
|
+
More: chatta links requests list ${linkId} --cursor ${page.nextCursor}` : ''));
|
|
528
|
+
}
|
|
529
|
+
if ((action === 'approve' || action === 'deny') && linkId && requestId) {
|
|
530
|
+
const r = await ownerApi(io, auth(), 'POST', `${base}/${encodeURIComponent(requestId)}/${action}`);
|
|
531
|
+
return out(io, flags, r, () => `${r?.name || requestId} <${r?.email || ''}> is ${r?.status || action}. They get an email.`);
|
|
532
|
+
}
|
|
533
|
+
throw new CliError('Usage: chatta links requests list <linkId> | links requests approve|deny <linkId> <requestId>', 2);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function webhookOwner(io, flags, auth, sub, [id, deliveryId]) {
|
|
537
|
+
if (!id) throw new CliError(`webhooks ${sub} needs <webhookId>`, 2);
|
|
538
|
+
const base = `/chats/webhooks/${encodeURIComponent(id)}`;
|
|
539
|
+
if (sub === 'deliveries') {
|
|
540
|
+
const limit = int(flags.limit, 'limit', 1, 20);
|
|
541
|
+
const data = await ownerApi(io, auth(), 'GET', `${base}/deliveries`, { query: { limit: limit && String(limit) } });
|
|
542
|
+
const rows = listOf(data).map((d) => ({ id: d.id || '-', event: d.event, code: d.code, at: d.at, attempt: d.attempt, retry: d.canRetry ? 'yes' : '' }));
|
|
543
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'event', 'code', 'at', 'attempt', 'retry']) : 'No deliveries yet.'));
|
|
544
|
+
}
|
|
545
|
+
if (sub === 'retry') {
|
|
546
|
+
if (!deliveryId) throw new CliError('webhooks retry needs <webhookId> <deliveryId>', 2);
|
|
547
|
+
await ownerApi(io, auth(), 'POST', `${base}/deliveries/${encodeURIComponent(deliveryId)}/retry`);
|
|
548
|
+
io.out(`Delivery ${deliveryId} queued; it goes out within 30 s.`);
|
|
549
|
+
return 0;
|
|
550
|
+
}
|
|
551
|
+
const r = await ownerApi(io, auth(), 'POST', `${base}/rotate-secret`);
|
|
552
|
+
return out(io, flags, r, () => `New signing secret (shown once, store it now):\n${r?.secret || ''}\nQueued retries use it too. Update your server before the next event.`);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// https only; plain http is allowed for a local server (localhost, 127.0.0.1, [::1]).
|
|
556
|
+
const HOOK_URL = /^(?:https:\/\/[^/\s]+|http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?)\/hooks\/in\/lhk_[A-Za-z0-9_-]{43}\/?$/;
|
|
557
|
+
const HOOK_USAGE = 'Usage: chatta hooks list|create|rename|regenerate|revoke <conversationId> … | hooks send <text…> (see chatta --help)';
|
|
558
|
+
const hookRow = (h) => ({ id: h.id, name: h.name, status: h.status, secret: h.tokenHint, 'last used': h.lastUsedAt ? whenOf(h.lastUsedAt) : 'never', posted: h.messageCount ?? 0, refused: h.rejectedCount ?? 0 });
|
|
559
|
+
|
|
560
|
+
/** Incoming webhooks: a secret URL per group or channel that posts as an app. Management uses the API key; `send` needs only the URL. */
|
|
561
|
+
async function hooks(io, flags, auth, sub, rest) {
|
|
562
|
+
if (sub === 'send') return hooksSend(io, flags, rest);
|
|
563
|
+
const [conversationId, hookId] = rest;
|
|
564
|
+
if (!conversationId || !OBJECT_ID.test(conversationId)) throw new CliError(`hooks ${sub || ''} needs a <conversationId> (24 characters). ${HOOK_USAGE}`, 2);
|
|
565
|
+
const base = `/chats/conversations/${encodeURIComponent(conversationId)}/incoming-webhooks`;
|
|
566
|
+
const named = () => {
|
|
567
|
+
if (!hookId || !OBJECT_ID.test(hookId)) throw new CliError(`hooks ${sub} needs <conversationId> <hookId>`, 2);
|
|
568
|
+
return `${base}/${encodeURIComponent(hookId)}`;
|
|
569
|
+
};
|
|
570
|
+
if (sub === 'list') {
|
|
571
|
+
if (flags.status !== undefined && !['active', 'revoked', 'all'].includes(flags.status)) throw new CliError('--status is active, revoked or all', 2);
|
|
572
|
+
const limit = int(flags.limit, 'limit', 1, 20);
|
|
573
|
+
const data = await api(io, auth(), 'GET', base, { query: { status: flags.status, nextCursor: typeof flags.cursor === 'string' ? flags.cursor : undefined, limit: limit && String(limit) } });
|
|
574
|
+
const rows = listOf(data).map(hookRow);
|
|
575
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'name', 'status', 'secret', 'last used', 'posted', 'refused']) : 'No incoming webhooks.') + more(data, `hooks list ${conversationId}`));
|
|
576
|
+
}
|
|
577
|
+
if (sub === 'create') {
|
|
578
|
+
const name = typeof flags.name === 'string' ? flags.name.trim() : '';
|
|
579
|
+
if (!name || name.length > 60) throw new CliError('hooks create needs --name (1–60 characters)', 2);
|
|
580
|
+
const body = { name, botName: flags['bot-name'], botAvatar: flags['bot-avatar'] };
|
|
581
|
+
Object.keys(body).forEach((k) => body[k] === undefined && delete body[k]);
|
|
582
|
+
const h = await api(io, auth(), 'POST', base, { body });
|
|
583
|
+
return out(io, flags, h, () => `Created "${h?.name || name}" (${h?.id || '-'}).\nWebhook URL (shown once, store it now):\n${h?.url || ''}`);
|
|
584
|
+
}
|
|
585
|
+
if (sub === 'rename') {
|
|
586
|
+
const body = { name: flags.name, botName: flags['bot-name'], botAvatar: flags['bot-avatar'] };
|
|
587
|
+
Object.keys(body).forEach((k) => body[k] === undefined && delete body[k]);
|
|
588
|
+
if (!Object.keys(body).length) throw new CliError('hooks rename needs --name, --bot-name or --bot-avatar', 2);
|
|
589
|
+
const h = await api(io, auth(), 'PATCH', named(), { body });
|
|
590
|
+
return out(io, flags, h, () => `Updated "${h?.name || hookId}".`);
|
|
591
|
+
}
|
|
592
|
+
if (sub === 'regenerate' || sub === 'revoke') {
|
|
593
|
+
const path = named();
|
|
594
|
+
if (!flags.yes) throw new CliError(sub === 'regenerate' ? 'hooks regenerate stops the current URL at once. Add --yes to go ahead.' : 'hooks revoke stops the URL for good. Add --yes to go ahead.', 2);
|
|
595
|
+
const h = sub === 'regenerate' ? await api(io, auth(), 'POST', `${path}/regenerate`, { body: {} }) : await api(io, auth(), 'DELETE', path);
|
|
596
|
+
return out(io, flags, h, () => (sub === 'regenerate'
|
|
597
|
+
? `New URL for "${h?.name || hookId}" (shown once, store it now):\n${h?.url || ''}\nThe old URL stopped.`
|
|
598
|
+
: `Revoked "${h?.name || hookId}". Its URL now answers 404.`));
|
|
599
|
+
}
|
|
600
|
+
throw new CliError(HOOK_USAGE, 2);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** `hooks send`: one POST to the secret URL. The URL is never printed or put in an error; never retried. */
|
|
604
|
+
async function hooksSend(io, flags, rest) {
|
|
605
|
+
if (flags['url-stdin'] && flags['text-stdin']) throw new CliError('hooks send reads one thing from stdin: use --url-stdin or --text-stdin, and give the other another way.', 2);
|
|
606
|
+
if (flags.url && !flags['url-stdin']) io.err('chatta: warning: --url is saved in your shell history and visible to other users, and the URL is a secret. Use LIVECHATTA_HOOK_URL or --url-stdin instead.');
|
|
607
|
+
const fromStdin = flags['url-stdin'] ? String(await io.readStdin()).split(/\r?\n/)[0] : '';
|
|
608
|
+
const url = String(fromStdin || flags.url || io.env.LIVECHATTA_HOOK_URL || '').trim();
|
|
609
|
+
if (!HOOK_URL.test(url)) throw new CliError('hooks send needs an https webhook URL: set LIVECHATTA_HOOK_URL (keeps it out of your shell history), pipe it with --url-stdin, or pass --url https://<host>/hooks/in/lhk_… (plain http only for localhost).', 2);
|
|
610
|
+
const text = flags['text-stdin'] ? (await io.readStdin()).trim() : rest.join(' ').trim();
|
|
611
|
+
if (!text) throw new CliError('hooks send needs the message: chatta hooks send "Deploy finished" (or --text-stdin)', 2);
|
|
612
|
+
const body = { text, ...(flags.username ? { username: String(flags.username) } : {}), ...(flags['icon-url'] ? { icon_url: String(flags['icon-url']) } : {}) };
|
|
613
|
+
let res;
|
|
614
|
+
try {
|
|
615
|
+
res = await io.fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), redirect: 'error' });
|
|
616
|
+
} catch (e) {
|
|
617
|
+
throw Object.assign(new CliError('Could not reach the webhook URL.'), { retryable: true });
|
|
618
|
+
}
|
|
619
|
+
const raw = await res.text();
|
|
620
|
+
if (res.ok) return out(io, flags, { ok: true }, () => 'Posted.'), 0;
|
|
621
|
+
let data = null;
|
|
622
|
+
try { data = raw ? JSON.parse(raw) : null; } catch { data = null; }
|
|
623
|
+
const code = data && typeof data.code === 'string' ? ` [${data.code}]` : '';
|
|
624
|
+
const msg = data && typeof data.message === 'string' ? ` — ${data.message}` : '';
|
|
625
|
+
const wait = Number(res.headers?.get?.('Retry-After')) > 0 ? ` Try again in ${Number(res.headers.get('Retry-After'))}s.` : '';
|
|
626
|
+
throw Object.assign(new CliError(`hooks send failed: HTTP ${res.status}${code}${msg}.${wait}`), { retryable: res.status >= 500 || res.status === 429 });
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async function conversationsMode(io, flags, auth, [action, id, mode]) {
|
|
630
|
+
if (!id || !['get', 'set'].includes(action)) throw new CliError('Usage: chatta conversations mode get|set <conversationId> [<mode>]', 2);
|
|
631
|
+
const path = `/chats/conversations/${encodeURIComponent(id)}`;
|
|
632
|
+
if (action === 'get') {
|
|
633
|
+
const p = await ownerApi(io, auth(), 'GET', `${path}/permissions`);
|
|
634
|
+
return out(io, flags, p, () => `Conversation ${id}: mode ${p?.mode || 'standard'}`);
|
|
635
|
+
}
|
|
636
|
+
if (!CONVERSATION_MODES.includes(mode)) throw new CliError(`Unknown conversation mode "${mode}". One of: ${CONVERSATION_MODES.join(', ')}`, 2);
|
|
637
|
+
const p = await ownerApi(io, auth(), 'PATCH', `${path}/mode`, { body: { mode } });
|
|
638
|
+
return out(io, flags, p, () => `Conversation ${id} is now "${p?.mode || mode}".`);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** Private or public: `isPrivate` on the permissions route (conversation admins or the owner; groups and channels only). */
|
|
642
|
+
async function conversationsVisibility(io, flags, auth, [action, id, value]) {
|
|
643
|
+
if (!id || !['get', 'set'].includes(action)) throw new CliError('Usage: chatta conversations visibility get <conversationId> | set <conversationId> private|public', 2);
|
|
644
|
+
const path = `/chats/conversations/${encodeURIComponent(id)}/permissions`;
|
|
645
|
+
const word = (p) => (p?.isPrivate ? 'private' : 'public');
|
|
646
|
+
if (action === 'get') {
|
|
647
|
+
const p = await ownerApi(io, auth(), 'GET', path);
|
|
648
|
+
return out(io, flags, p, () => `Conversation ${id} is ${word(p)}.`);
|
|
649
|
+
}
|
|
650
|
+
if (!['private', 'public'].includes(value)) throw new CliError('conversations visibility set needs private or public', 2);
|
|
651
|
+
const p = await ownerApi(io, auth(), 'PATCH', path, { body: { isPrivate: value === 'private' } });
|
|
652
|
+
return out(io, flags, p, () => `Conversation ${id} is now ${word(p)}${p?.isPrivate ? ': not listed, nobody new can join on their own, members stay.' : ': listed, and anyone in the workspace can join.'}`);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async function teams(io, flags, auth, sub) {
|
|
656
|
+
if (sub === 'list') {
|
|
657
|
+
const data = await ownerApi(io, auth(), 'GET', '/users/teams');
|
|
658
|
+
const rows = listOf(data).map((t) => ({ id: t._id, name: t.name, members: t.memberCount ?? (t.members || []).length, link: t.chatLink || 'all links' }));
|
|
659
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'name', 'members', 'link']) : 'No teams.') +
|
|
660
|
+
(data?.max ? `\n${rows.length} of ${data.max} teams` : ''));
|
|
661
|
+
}
|
|
662
|
+
if (sub === 'create') {
|
|
663
|
+
const name = flags.name ? String(flags.name) : '';
|
|
664
|
+
if (!name || name.length > 40) throw new CliError('teams create needs --name (1–40 characters)', 2);
|
|
665
|
+
const body = { name, description: flags.description, chatLinkId: flags.link, memberIds: csv(flags.members) };
|
|
666
|
+
Object.keys(body).forEach((k) => body[k] === undefined && delete body[k]);
|
|
667
|
+
const t = await ownerApi(io, auth(), 'POST', '/users/teams', { body });
|
|
668
|
+
return out(io, flags, t, () => `Created team ${t?.name || name}${t?._id ? ` (${t._id})` : ''}.`);
|
|
669
|
+
}
|
|
670
|
+
throw new CliError('Usage: chatta teams list | teams create --name <n>', 2);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** GIF search: `searchGifs` and `trendingGifs` over the owner token; --json prints the page as the server sent it. */
|
|
674
|
+
async function gifs(io, flags, auth, sub, rest) {
|
|
675
|
+
if (sub !== 'search' && sub !== 'trending') throw new CliError('Usage: chatta gifs search <query…> [--source livechatta|provider] [--cursor <c>] | gifs trending [--source livechatta|provider] [--cursor <c>]', 2);
|
|
676
|
+
const q = sub === 'search' ? [flags.q, ...rest].filter((v) => typeof v === 'string' && v).join(' ').trim() : '';
|
|
677
|
+
if (q.length > 60) throw new CliError('gifs search takes at most 60 characters', 2);
|
|
678
|
+
if (flags.source !== undefined && flags.source !== 'livechatta' && flags.source !== 'provider') throw new CliError('--source must be livechatta or provider', 2);
|
|
679
|
+
const query = { nextCursor: typeof flags.cursor === 'string' ? flags.cursor : undefined, source: flags.source };
|
|
680
|
+
if (q) query.q = q;
|
|
681
|
+
const data = await ownerApi(io, auth(), 'GET', `/chats/gifs/${sub}`, { query });
|
|
682
|
+
const rows = listOf(data).map((g) => ({ id: g.id, from: g.provider, title: g.title, size: `${g.width}x${g.height}`, rating: g.rating, url: g.url }));
|
|
683
|
+
const credit = [...new Set(listOf(data).map((g) => g.attribution).filter(Boolean))].join(', ');
|
|
684
|
+
const note = data?.fallback ? `\nNo provider answer, so these are the LiveChatta default GIFs.` : data?.switched ? `\nNo LiveChatta match, so these come from ${data.providerLabel || 'the provider'}.` : '';
|
|
685
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'from', 'title', 'size', 'rating', 'url']) : 'No GIFs found.') + note +
|
|
686
|
+
(credit ? `\n${credit}` : '') + more(data, `gifs ${sub}${q ? ` ${q}` : ''}`));
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const SHARED_SUBS = ['list', 'invite', 'preview', 'accept', 'audience', 'members', 'leave', 'end', 'channel', 'permissions', 'audit', 'dm', 'remove-member', 'remove-message', 'link-account'];
|
|
690
|
+
const sharedRow = (v) => ({
|
|
691
|
+
id: v._id, channel: v.conversationName, side: v.side, status: v.status, with: v.side === 'HOST' ? v.partnerName || '(link invite)' : v.hostName,
|
|
692
|
+
audience: v.audience, members: v.memberCount, expires: isoDay(v.expiresAt), archive: v.archiveConversationId || '',
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
/** Shared channels between workspaces: member token, every call names the workspace (`--link`). Changes ask for --yes and are never retried. */
|
|
696
|
+
async function shared(io, flags, auth, sub, rest) {
|
|
697
|
+
if (!SHARED_SUBS.includes(sub)) throw new CliError(`Usage: chatta shared ${SHARED_SUBS.join(' | ')}`, 2);
|
|
698
|
+
const oid = (v, what) => {
|
|
699
|
+
if (!OBJECT_ID.test(String(v || ''))) throw new CliError(`${what} must be a 24-character id`, 2);
|
|
700
|
+
return String(v);
|
|
701
|
+
};
|
|
702
|
+
if (sub === 'link-account') {
|
|
703
|
+
needYes(flags, 'This makes that chat user count as the teammate, with the access of their team role in shared channels.');
|
|
704
|
+
const body = { accountId: oid(rest[0], 'shared link-account <accountId>'), chatUserId: oid(rest[1], 'shared link-account <chatUserId>') };
|
|
705
|
+
const data = await ownerApi(io, auth(), 'POST', '/chats/chat-users/link-account', { body });
|
|
706
|
+
return out(io, flags, data, () => 'Linked. That teammate now counts as workspace staff for shared channels.');
|
|
707
|
+
}
|
|
708
|
+
const chatLinkId = sub === 'preview' ? '<linkId>' : oid(flags.link, 'shared needs --link <linkId>: the workspace you are signed in to; it');
|
|
709
|
+
const m = (method, path, opts = {}) => memberApi(io, auth(), method, `/shared-channels${path}`, opts);
|
|
710
|
+
const scope = { chatLinkId };
|
|
711
|
+
const audienceBody = () => {
|
|
712
|
+
const audience = String(flags.audience || '').toUpperCase();
|
|
713
|
+
if (!['ALL', 'PICKED'].includes(audience)) throw new CliError('--audience must be all (your whole team) or picked (with --members)', 2);
|
|
714
|
+
const memberIds = csv(flags.members);
|
|
715
|
+
if (audience === 'PICKED' && !memberIds?.length) throw new CliError('--audience picked needs --members <id,id> (up to 500)', 2);
|
|
716
|
+
if (audience === 'ALL' && memberIds?.length) throw new CliError('--members only goes with --audience picked', 2);
|
|
717
|
+
memberIds?.forEach((i) => oid(i, '--members entry'));
|
|
718
|
+
return { chatLinkId, audience, ...(memberIds?.length ? { memberIds } : {}) };
|
|
719
|
+
};
|
|
720
|
+
if (sub === 'list') {
|
|
721
|
+
const data = await m('GET', '', { query: { ...scope, nextCursor: flags.cursor } });
|
|
722
|
+
const rows = listOf(data).map(sharedRow);
|
|
723
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'channel', 'side', 'status', 'with', 'audience', 'members', 'expires', 'archive']) : 'No shared channels.') + more(data, `shared list --link ${chatLinkId}`));
|
|
724
|
+
}
|
|
725
|
+
if (sub === 'invite') {
|
|
726
|
+
const body = { ...scope, conversationId: oid(rest[0], 'shared invite <conversationId>'), partnerLinkCode: flags.partner, expiresInHours: int(flags.hours, 'hours', 1, 720) };
|
|
727
|
+
const data = await m('POST', '', { body: clean(body) });
|
|
728
|
+
return out(io, flags, data, () => {
|
|
729
|
+
const v = data?.sharedChannel || {};
|
|
730
|
+
if (!data?.inviteToken) return `Invited ${v.partnerName || flags.partner}. Their owner or admin sees it under Shared channels and can accept it.\nshare ${v._id}`;
|
|
731
|
+
return `Single-use invite link for "${v.conversationName}". It is shown once and works for one workspace.\n${data.inviteUrl}\nshare ${v._id}`;
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
if (sub === 'preview') {
|
|
735
|
+
if (!flags.token) throw new CliError('shared preview needs --token <t> or --token-stdin', 2);
|
|
736
|
+
const data = await m('POST', '/preview', { body: { token: String(flags.token) } });
|
|
737
|
+
return out(io, flags, data, () => `${data.hostName} invites you to "${data.channelName}" (from ${data.invitedByName || 'their team'}).${data.expiresAt ? ` Open until ${data.expiresAt}.` : ''}\nAccept: chatta shared accept --token-stdin --link ${chatLinkId} --audience all --yes`);
|
|
738
|
+
}
|
|
739
|
+
if (sub === 'accept' || sub === 'audience') {
|
|
740
|
+
const byToken = sub === 'accept' && !rest[0];
|
|
741
|
+
if (byToken && !flags.token) throw new CliError('shared accept needs <sharedChannelId>, or --token <t> / --token-stdin for an invite link', 2);
|
|
742
|
+
const body = audienceBody();
|
|
743
|
+
needYes(flags, sub === 'accept' ? 'Accepting gives people of your workspace a channel run by another workspace; they see each other\'s names and handles only.' : 'This changes who on your team has the channel.');
|
|
744
|
+
const data = byToken
|
|
745
|
+
? await m('POST', '/accept-token', { body: { ...body, token: String(flags.token) } })
|
|
746
|
+
: sub === 'accept'
|
|
747
|
+
? await m('POST', `/${oid(rest[0], 'shared accept <sharedChannelId>')}/accept`, { body })
|
|
748
|
+
: await m('PUT', `/${oid(rest[0], 'shared audience <sharedChannelId>')}/members`, { body });
|
|
749
|
+
return out(io, flags, data, () => `${sub === 'accept' ? 'Accepted' : 'Updated'}: "${data.conversationName}" with ${data.hostName}, ${data.memberCount} of your people have it (audience ${data.audience}).`);
|
|
750
|
+
}
|
|
751
|
+
if (sub === 'members') {
|
|
752
|
+
const data = await m('GET', '/members', { query: { ...scope, q: flags.search, sharedChannelId: flags.channel, nextCursor: flags.cursor } });
|
|
753
|
+
const rows = listOf(data).map((p) => ({ id: p._id, name: p.displayName, handle: p.handle ? `@${p.handle}` : '', has: p.enrolled ? 'yes' : '' }));
|
|
754
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'name', 'handle', 'has']) : 'No members found.') + more(data, `shared members --link ${chatLinkId}`));
|
|
755
|
+
}
|
|
756
|
+
if (sub === 'leave' || sub === 'end') {
|
|
757
|
+
needYes(flags, 'This ends the share: the host removes the partner, a partner leaves, or a pending invite is cancelled or declined. Each side keeps its own history.');
|
|
758
|
+
const data = await m('POST', `/${oid(rest[0], 'shared leave <sharedChannelId>')}/end`, { body: scope });
|
|
759
|
+
return out(io, flags, data, () => `Ended "${data.conversationName}" (${data.status}).${data.archiveConversationId ? ` Your read-only copy: ${data.archiveConversationId}.` : ''}`);
|
|
760
|
+
}
|
|
761
|
+
if (sub === 'channel') {
|
|
762
|
+
const data = await m('GET', `/conversations/${oid(rest[0], 'shared channel <conversationId>')}`, { query: scope });
|
|
763
|
+
const rows = listOf(data).map(sharedRow);
|
|
764
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'channel', 'status', 'with', 'audience', 'members', 'expires']) : 'This channel is not shared.'));
|
|
765
|
+
}
|
|
766
|
+
if (sub === 'permissions') {
|
|
767
|
+
const data = await m('GET', `/conversations/${oid(rest[0], 'shared permissions <conversationId>')}/permissions`, { query: scope });
|
|
768
|
+
return out(io, flags, data, () => (data?.side
|
|
769
|
+
? `side ${data.side}\nremove messages ${data.canRemoveMessages ? 'yes' : 'no'}\nremove members ${data.canRemoveMembers ? 'yes' : 'no'}\nfrom another workspace ${(data.externalIds || []).length}`
|
|
770
|
+
: 'This conversation is not shared with your workspace.'));
|
|
771
|
+
}
|
|
772
|
+
if (sub === 'audit') {
|
|
773
|
+
const data = await m('GET', `/${oid(rest[0], 'shared audit <sharedChannelId>')}/audit`, { query: { ...scope, nextCursor: flags.cursor } });
|
|
774
|
+
const rows = listOf(data).map((r) => ({ at: r.createdAt, action: r.action, by: r.actorName, detail: r.detail }));
|
|
775
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['at', 'action', 'by', 'detail']) : 'Nothing logged yet.') + more(data, `shared audit ${rest[0]} --link ${chatLinkId}`));
|
|
776
|
+
}
|
|
777
|
+
if (sub === 'dm') {
|
|
778
|
+
const body = { ...scope, conversationId: oid(rest[0], 'shared dm <conversationId>'), memberId: oid(rest[1], 'shared dm <memberId>') };
|
|
779
|
+
const data = await m('POST', '/direct', { body });
|
|
780
|
+
return out(io, flags, data, () => (data?.internal ? 'That person is in your own workspace: use a normal direct message.' : `${data?.created ? 'Opened' : 'Already open'}: conversation ${data?.conversationId}`));
|
|
781
|
+
}
|
|
782
|
+
if (sub === 'remove-member') {
|
|
783
|
+
needYes(flags, 'This removes that person of the other workspace from the channel, and they stay out if it is shared again.');
|
|
784
|
+
const body = { ...scope, conversationId: oid(rest[0], 'shared remove-member <conversationId>'), memberId: oid(rest[1], 'shared remove-member <memberId>') };
|
|
785
|
+
const data = await m('POST', '/remove-member', { body });
|
|
786
|
+
return out(io, flags, data, () => `Removed. ${data?.memberCount ?? 0} of their people still have the channel.`);
|
|
787
|
+
}
|
|
788
|
+
needYes(flags, 'This wipes the message for everyone and is logged on both sides.');
|
|
789
|
+
const body = { ...scope, conversationId: oid(rest[0], 'shared remove-message <conversationId>'), messageId: oid(rest[1], 'shared remove-message <messageId>') };
|
|
790
|
+
const data = await m('POST', '/remove-message', { body });
|
|
791
|
+
return out(io, flags, data, () => `Removed message ${data?.messageId}.`);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
async function plan(io, flags, auth, sub) {
|
|
795
|
+
if (sub === 'status') {
|
|
796
|
+
const r = await ownerApi(io, auth(), 'GET', '/plan-requests/me/latest');
|
|
797
|
+
return out(io, flags, r, () => (r?.request
|
|
798
|
+
? `Request ${r.request.id}: ${r.request.status} (sent ${r.request.createdAt}${r.request.statusUpdatedAt ? `, updated ${r.request.statusUpdatedAt}` : ''})`
|
|
799
|
+
: 'No custom plan request yet. Send one: chatta plan request --mine --name <n> --email <e>'));
|
|
800
|
+
}
|
|
801
|
+
if (sub !== 'request') throw new CliError('Usage: chatta plan request --name <n> --email <e> [...] | plan status', 2);
|
|
802
|
+
const contactName = flags.name ? String(flags.name).trim() : '';
|
|
803
|
+
const contactEmail = flags.email ? String(flags.email).trim() : '';
|
|
804
|
+
if (!contactName || contactName.length > 120) throw new CliError('plan request needs --name (your name, ≤ 120 characters)', 2);
|
|
805
|
+
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(contactEmail)) throw new CliError('plan request needs --email <work email>', 2);
|
|
806
|
+
const features = csv(flags.features)?.map((f) => f.toUpperCase());
|
|
807
|
+
const bad = features?.filter((f) => !PLAN_REQUEST_FEATURES.includes(f));
|
|
808
|
+
if (bad?.length) throw new CliError(`Unknown feature ${bad.join(', ')}. One of: ${PLAN_REQUEST_FEATURES.join(', ')}`, 2);
|
|
809
|
+
if (flags.message && String(flags.message).length > 2000) throw new CliError('--message is at most 2000 characters', 2);
|
|
810
|
+
const body = {
|
|
811
|
+
contactName, contactEmail, company: flags.company, features, message: flags.message,
|
|
812
|
+
expectedChatLinks: int(flags.links, 'links', 1, 100000),
|
|
813
|
+
membersPerLink: int(flags['members-per-link'], 'members-per-link', 1, 10000000),
|
|
814
|
+
aiCredits: int(flags['ai-credits'], 'ai-credits', 0, 1000000000),
|
|
815
|
+
};
|
|
816
|
+
Object.keys(body).forEach((k) => body[k] === undefined && delete body[k]);
|
|
817
|
+
const r = flags.mine
|
|
818
|
+
? await ownerApi(io, auth(), 'POST', '/plan-requests/me', { body })
|
|
819
|
+
: await publicApi(io, auth(), 'POST', '/plan-requests', { body });
|
|
820
|
+
return out(io, flags, r, () => `Request ${r?.id || ''} is ${r?.status || 'NEW'}. The LiveChatta team will email ${contactEmail}.` +
|
|
821
|
+
(flags.mine ? '\nFollow it: chatta plan status' : ''));
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const money = (n) => `$${Number(n || 0).toFixed(2)}`;
|
|
825
|
+
const minor = (n, cur) => `${(Number(n || 0) / 100).toFixed(2)} ${cur || ''}`.trim();
|
|
826
|
+
// LiveFlex shows the in-app coin, FlexCoin (1 FlexCoin = $1). Amount unchanged — label only.
|
|
827
|
+
const flexc = (n) => `${(Number(n || 0) / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} FlexCoin`;
|
|
828
|
+
const pageQuery = (flags) => {
|
|
829
|
+
const limit = int(flags.limit, 'limit', 1, 20);
|
|
830
|
+
return { limit: limit && String(limit), nextCursor: flags.cursor };
|
|
831
|
+
};
|
|
832
|
+
const more = (data, cmd) => (data?.nextCursor ? `\nMore: chatta ${cmd} --cursor ${data.nextCursor}` : '');
|
|
833
|
+
const CYCLES = ['MONTHLY', 'QUARTERLY', 'SEMI_YEARLY', 'YEARLY'];
|
|
834
|
+
const gb = (bytes) => `${(Number(bytes || 0) / 1024 ** 3).toFixed(2)} GB`;
|
|
835
|
+
|
|
836
|
+
async function linksCode(io, flags, auth, [code]) {
|
|
837
|
+
if (!code) throw new CliError('links code needs <address>', 2);
|
|
838
|
+
const r = await ownerApi(io, auth(), 'GET', '/chats/links/code-available', { query: { code } });
|
|
839
|
+
return out(io, flags, r, () => (r?.available ? `/in/${r.code} is free.`
|
|
840
|
+
: `/in/${r?.code} is not available (${r?.reason}): ${r?.message}${r?.suggestions?.length ? `\nTry: ${r.suggestions.join(', ')}` : ''}`));
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
async function linksModes(io, flags, auth) {
|
|
844
|
+
const a = auth();
|
|
845
|
+
const cat = a.ownerToken ? await ownerApi(io, a, 'GET', '/chats/links/modes') : await api(io, a, 'GET', '/chat-links/modes');
|
|
846
|
+
const rows = (cat?.linkModes || []).map((m) => ({ mode: m.mode, label: m.label, type: m.conversationType, 'staff-only create': m.staffOnlyCreate ? 'yes' : '', available: m.available === false ? 'plan' : 'yes' }));
|
|
847
|
+
const conv = (cat?.conversationModes || []).map((m) => m.mode).join(', ');
|
|
848
|
+
return out(io, flags, cat, () => `${rows.length ? table(rows, ['mode', 'label', 'type', 'staff-only create', 'available']) : 'No modes.'}\nConversation modes: ${conv}`);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
async function linksWhoCanJoin(io, flags, auth, [linkId, who]) {
|
|
852
|
+
if (!linkId || !WHO_CAN_JOIN.includes(who)) throw new CliError(`links who-can-join needs <linkId> and one of ${WHO_CAN_JOIN.join('|')}`, 2);
|
|
853
|
+
const r = await ownerApi(io, auth(), 'PATCH', `/chats/links/${encodeURIComponent(linkId)}/who-can-join`, { body: { who } });
|
|
854
|
+
return out(io, flags, r, () => `Who can join ${linkId}: ${r?.who || who}`);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
async function linksAppOrigins(io, flags, auth, [linkId, ...origins]) {
|
|
858
|
+
if (!linkId || (!origins.length && !flags.clear)) throw new CliError('Usage: chatta links app-origins <linkId> <origin...> | --clear', 2);
|
|
859
|
+
const list = flags.clear ? [] : origins;
|
|
860
|
+
const r = await ownerApi(io, auth(), 'PUT', `/chats/links/${encodeURIComponent(linkId)}/app-origins`, { body: { origins: list } });
|
|
861
|
+
return out(io, flags, r, () => (r?.origins?.length ? `App origins for ${linkId}: ${r.origins.join(', ')}` : `No app origins on ${linkId}.`));
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
async function linksDomain(io, flags, auth, [linkId, action, host]) {
|
|
865
|
+
if (!linkId) throw new CliError('links domain needs <linkId>', 2);
|
|
866
|
+
const base = `/chats/links/${encodeURIComponent(linkId)}/custom-domain`;
|
|
867
|
+
let r;
|
|
868
|
+
if (!action) r = await ownerApi(io, auth(), 'GET', base);
|
|
869
|
+
else if (action === 'set') {
|
|
870
|
+
if (!host) throw new CliError('links domain set needs <host> (for example help.acme.com)', 2);
|
|
871
|
+
r = await ownerApi(io, auth(), 'PUT', base, { body: { domain: host } });
|
|
872
|
+
} else if (action === 'remove') r = await ownerApi(io, auth(), 'PUT', base, { body: { domain: '' } });
|
|
873
|
+
else if (action === 'verify') r = await ownerApi(io, auth(), 'POST', `${base}/verify`);
|
|
874
|
+
else throw new CliError('Usage: chatta links domain <linkId> [set <host> | verify | remove]', 2);
|
|
875
|
+
return out(io, flags, r, () => (r?.domain
|
|
876
|
+
? `${r.domain}: ${r.verified ? 'verified' : 'not verified'}${r.error ? ` (${r.error})` : ''}\nPoint a CNAME at ${r.target}`
|
|
877
|
+
: `No custom domain. Point a CNAME at ${r?.target} and run: chatta links domain ${linkId} set <host>`));
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** URL and data: values pass through; anything else is read as an image file into a data: URI. */
|
|
881
|
+
function imageValue(v) {
|
|
882
|
+
if (/^(https?:|data:)/i.test(v)) return v;
|
|
883
|
+
const ext = String(v).split('.').pop().toLowerCase();
|
|
884
|
+
const mime = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif' }[ext];
|
|
885
|
+
if (!mime) throw new CliError('--welcome-image must be an https URL, a data: URI or a png/jpg/webp/gif file', 2);
|
|
886
|
+
try {
|
|
887
|
+
return `data:${mime};base64,${readFileSync(v).toString('base64')}`;
|
|
888
|
+
} catch {
|
|
889
|
+
throw new CliError(`Could not read ${v}`, 2);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
async function linksTheme(io, flags, auth, [linkId]) {
|
|
894
|
+
if (!linkId) throw new CliError('links theme needs <linkId>', 2);
|
|
895
|
+
if (!flags.primary || !flags.secondary) throw new CliError('links theme needs --primary and --secondary (the theme is replaced whole)', 2);
|
|
896
|
+
for (const k of ['primary', 'secondary']) if (!HEX.test(flags[k])) throw new CliError(`--${k} must be a hex colour like #0B6E66`, 2);
|
|
897
|
+
if (flags.footer && flags.footer.length > 140) throw new CliError('--footer is at most 140 characters', 2);
|
|
898
|
+
const hex = (v) => `#${String(v).replace('#', '').toUpperCase()}`;
|
|
899
|
+
const body = { primaryColor: hex(flags.primary), secondaryColor: hex(flags.secondary) };
|
|
900
|
+
if (flags.footer) body.footerText = flags.footer;
|
|
901
|
+
if (flags['welcome-image']) body.welcomeImageUrl = imageValue(flags['welcome-image']);
|
|
902
|
+
const r = await ownerApi(io, auth(), 'PATCH', `/chats/links/${encodeURIComponent(linkId)}/theme`, { body });
|
|
903
|
+
return out(io, flags, r, () => `Theme saved for ${r?.name || linkId}.`);
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
async function linksOverview(io, flags, auth, [linkId]) {
|
|
907
|
+
if (!linkId) throw new CliError('links overview needs <linkId>', 2);
|
|
908
|
+
const o = await ownerApi(io, auth(), 'GET', `/chats/links/${encodeURIComponent(linkId)}/overview`);
|
|
909
|
+
const delta = (n) => (n == null ? '' : ` (${n > 0 ? '+' : ''}${n}%)`);
|
|
910
|
+
return out(io, flags, o, () => `Visitors 30d ${o?.visitors30d}${delta(o?.visitorsDeltaPct)}\nConversations ${o?.conversations} (${o?.conversations30d} in 30d${delta(o?.conversationsDeltaPct)})\n` +
|
|
911
|
+
`Messages ${o?.messages}\nFirst reply ${o?.firstReplyMedianMs == null ? 'no data' : `${Math.round(o.firstReplyMedianMs / 1000)} s median`}\nMembers ${o?.members} of ${o?.maxMembers || 'unlimited'}`);
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
async function linksWipe(io, flags, auth, [linkId]) {
|
|
915
|
+
if (!linkId) throw new CliError('links wipe needs <linkId>', 2);
|
|
916
|
+
if (!flags.yes) throw new CliError('links wipe deletes every message on the link for good. Add --yes to confirm.', 2);
|
|
917
|
+
const r = await ownerApi(io, auth(), 'POST', `/chats/links/${encodeURIComponent(linkId)}/wipe-messages`);
|
|
918
|
+
return out(io, flags, r, () => `Deleted ${r?.deleted ?? 0} messages. The link and its conversations are kept.`);
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function originList(v) {
|
|
922
|
+
if (v === 'none') return [];
|
|
923
|
+
const list = String(v).split(',').map((x) => x.trim()).filter(Boolean);
|
|
924
|
+
if (list.length > 20) throw new CliError('At most 20 origins per key', 2);
|
|
925
|
+
return list;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async function keys(io, flags, auth, sub, [keyId]) {
|
|
929
|
+
if (sub === 'list') {
|
|
930
|
+
const d = await ownerApi(io, auth(), 'GET', '/api-keys', { query: pageQuery(flags) });
|
|
931
|
+
const rows = listOf(d).map((k) => ({ id: k._id, name: k.name, status: k.status, origins: (k.allowedOrigins || []).join(',') || 'any' }));
|
|
932
|
+
return out(io, flags, d, () => (rows.length ? table(rows, ['id', 'name', 'status', 'origins']) : 'No API keys.') + more(d, 'keys list'));
|
|
933
|
+
}
|
|
934
|
+
if (sub === 'create') {
|
|
935
|
+
if (!flags.name) throw new CliError('keys create needs --name', 2);
|
|
936
|
+
const body = { name: flags.name, ...(flags.description ? { description: flags.description } : {}), ...(flags.origins ? { allowedOrigins: originList(flags.origins) } : {}) };
|
|
937
|
+
const k = await ownerApi(io, auth(), 'POST', '/api-keys', { body });
|
|
938
|
+
return out(io, flags, k, () => `Created ${k?.name || flags.name} (${k?._id}). Copy the key now; it is shown once.${body.allowedOrigins ? `\nOnly browsers on ${body.allowedOrigins.join(', ')} can use it.` : ''}`);
|
|
939
|
+
}
|
|
940
|
+
if (sub === 'update') {
|
|
941
|
+
if (!keyId) throw new CliError('keys update needs <keyId>', 2);
|
|
942
|
+
const body = { ...(flags.name ? { name: flags.name } : {}), ...(flags.description ? { description: flags.description } : {}), ...(flags.origins ? { allowedOrigins: originList(flags.origins) } : {}) };
|
|
943
|
+
if (!Object.keys(body).length) throw new CliError('keys update needs --name, --description or --origins', 2);
|
|
944
|
+
const k = await ownerApi(io, auth(), 'PATCH', `/api-keys/${encodeURIComponent(keyId)}`, { body });
|
|
945
|
+
return out(io, flags, k, () => `Updated ${k?.name || keyId}${body.allowedOrigins ? (body.allowedOrigins.length ? `: only ${body.allowedOrigins.join(', ')}` : ': any site') : ''}.`);
|
|
946
|
+
}
|
|
947
|
+
if (sub === 'rotate' || sub === 'revoke') {
|
|
948
|
+
if (!keyId) throw new CliError(`keys ${sub} needs <keyId>`, 2);
|
|
949
|
+
if (!flags.yes) throw new CliError(sub === 'rotate' ? 'keys rotate stops the old key once the new one is made. Add --yes to go ahead.' : 'keys revoke stops the key for good. Add --yes to go ahead.', 2);
|
|
950
|
+
const path = `/api-keys/${encodeURIComponent(keyId)}`;
|
|
951
|
+
const k = sub === 'rotate' ? await ownerApi(io, auth(), 'POST', `${path}/rotate`) : await ownerApi(io, auth(), 'DELETE', path);
|
|
952
|
+
return out(io, flags, k, () => (sub === 'rotate'
|
|
953
|
+
? `Rotated ${k?.name || keyId}. New key ${k?._id}: ${k?.key || '(see the dashboard)'}\nCopy it now; it is shown once. The old key has stopped.`
|
|
954
|
+
: `Revoked ${k?.name || keyId}. Anything still using it gets 401.`));
|
|
955
|
+
}
|
|
956
|
+
if (sub === 'usage') {
|
|
957
|
+
if (!keyId) throw new CliError('keys usage needs <keyId>', 2);
|
|
958
|
+
const period = flags.period || '7d';
|
|
959
|
+
if (!['7d', '30d', '90d'].includes(period)) throw new CliError('--period is 7d, 30d or 90d', 2);
|
|
960
|
+
const u = await ownerApi(io, auth(), 'GET', `/api-keys/${encodeURIComponent(keyId)}/usage`, { query: { period } });
|
|
961
|
+
const labels = u?.labels || [];
|
|
962
|
+
const rows = labels.map((d, i) => ({ day: d, requests: u.requests?.[i] ?? 0, errors: u.errors?.[i] ?? 0 }));
|
|
963
|
+
const total = (a) => (a || []).reduce((s, n) => s + (Number(n) || 0), 0);
|
|
964
|
+
return out(io, flags, u, () => `${table(rows, ['day', 'requests', 'errors'])}\n${total(u?.requests)} requests, ${total(u?.errors)} errors in ${period}.`);
|
|
965
|
+
}
|
|
966
|
+
throw new CliError('Usage: chatta keys list | create --name <n> [--origins a,b] | update <keyId> [--origins a,b|none] | rotate <keyId> --yes | revoke <keyId> --yes | usage <keyId> [--period 7d|30d|90d]', 2);
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/** Dollars on the command line → US cents for the API. Whole cents only, no float maths. */
|
|
970
|
+
function cents(v, what) {
|
|
971
|
+
const m = /^\$?(\d{1,9})(?:\.(\d{1,2}))?$/.exec(String(v ?? '').trim());
|
|
972
|
+
const minor = m ? Number(m[1]) * 100 + Number((m[2] || '').padEnd(2, '0')) : 0;
|
|
973
|
+
if (!(minor >= 1)) throw new CliError(`${what} needs an amount in US dollars with at most 2 decimals, e.g. 25 or 12.50`, 2);
|
|
974
|
+
return minor;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
async function securityGrant(io, flags, auth, [action]) {
|
|
978
|
+
let data;
|
|
979
|
+
if (!action) data = await ownerApi(io, auth(), 'GET', '/staff-access/grant');
|
|
980
|
+
else if (action === 'off') data = await ownerApi(io, auth(), 'DELETE', '/staff-access/grant');
|
|
981
|
+
else if (action === 'on') {
|
|
982
|
+
const hours = Number(flags.hours);
|
|
983
|
+
if (!['view', 'act'].includes(flags.mode)) throw new CliError('security grant on needs --mode view|act', 2);
|
|
984
|
+
if (![1, 24, 72, 168].includes(hours)) throw new CliError('--hours must be 1, 24, 72 or 168', 2);
|
|
985
|
+
data = await ownerApi(io, auth(), 'PUT', '/staff-access/grant', { body: { mode: flags.mode, hours } });
|
|
986
|
+
} else throw new CliError('security grant [on|off]', 2);
|
|
987
|
+
return out(io, flags, data, () => (data?.on ? `Support access is ON (${data.mode}) until ${data.until}.` : 'Support access is OFF.'));
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
async function liveflex(io, flags, auth, sub, rest) {
|
|
991
|
+
if (!sub) {
|
|
992
|
+
const w = await ownerApi(io, auth(), 'GET', '/wallet');
|
|
993
|
+
const bank = w?.payoutBank ? `${w.payoutBank.bankName} ••${w.payoutBank.accountLast4}` : 'none';
|
|
994
|
+
const crypto = w?.payoutCrypto ? `${w.payoutCrypto.currency} on ${w.payoutCrypto.network} ${w.payoutCrypto.addressHint}` : 'none';
|
|
995
|
+
const l = w?.withdrawLimits || {};
|
|
996
|
+
return out(io, flags, w, () => [
|
|
997
|
+
`Balance ${flexc(w?.balanceMinor)}${w?.pendingWithdrawMinor ? ` (${flexc(w.pendingWithdrawMinor)} withdrawing)` : ''}`,
|
|
998
|
+
`Bank ${bank}`,
|
|
999
|
+
`Crypto ${crypto}`,
|
|
1000
|
+
`Limits min ${flexc(l.minMinor)} · max ${flexc(l.maxMinor)} · ${flexc(l.dailyMinor)} per 24 h (used ${flexc(l.usedTodayMinor)})`,
|
|
1001
|
+
w?.payoutHoldUntil ? `On hold withdrawals open ${w.payoutHoldUntil}` : '',
|
|
1002
|
+
w?.frozen ? `FROZEN ${w.frozenReason || 'Contact support.'}` : '',
|
|
1003
|
+
].filter(Boolean).join('\n'));
|
|
1004
|
+
}
|
|
1005
|
+
if (sub === 'history') {
|
|
1006
|
+
const data = await ownerApi(io, auth(), 'GET', '/wallet/transactions', { query: { kind: flags.kind, limit: flags.limit, cursor: flags.cursor } });
|
|
1007
|
+
const rows = listOf(data).map((t) => ({ when: t.createdAt, kind: t.kind, amount: flexc(t.amountMinor), fee: t.serviceFeeMinor ? flexc(t.serviceFeeMinor) : '', status: t.status, what: t.description }));
|
|
1008
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['when', 'kind', 'amount', 'fee', 'status', 'what']) : 'No LiveFlex activity yet.') +
|
|
1009
|
+
(data?.hasMore && data?.nextCursor ? `\nMore: chatta liveflex history --cursor ${data.nextCursor}` : ''));
|
|
1010
|
+
}
|
|
1011
|
+
if (sub === 'fund') {
|
|
1012
|
+
const data = await ownerApi(io, auth(), 'POST', '/wallet/fund', { body: { amountMinor: cents(rest[0], 'liveflex fund'), provider: flags.crypto ? 'cryptomus' : 'paystack' } });
|
|
1013
|
+
return out(io, flags, data, () => `Pay ${flexc(data?.totalMinor)} (fee ${flexc(data?.serviceFeeMinor)}):\n${data?.authorizationUrl || '(no link returned)'}\nReference ${data?.reference}`);
|
|
1014
|
+
}
|
|
1015
|
+
if (sub === 'send') {
|
|
1016
|
+
if (!flags.to) throw new CliError('liveflex send needs --to <memberId|business>', 2);
|
|
1017
|
+
const body = { amountMinor: cents(rest[0], 'liveflex send'), note: flags.note, idempotencyKey: `cli_${io.now().getTime().toString(36)}` };
|
|
1018
|
+
if (flags.to === 'business') body.toBusiness = 'business'; else body.recipientId = flags.to;
|
|
1019
|
+
const data = await ownerApi(io, auth(), 'POST', '/wallet/send', { body });
|
|
1020
|
+
return out(io, flags, data, () => `Sent. Reference ${data?.reference}. Balance ${flexc(data?.balanceMinor)}.`);
|
|
1021
|
+
}
|
|
1022
|
+
if (sub === 'withdraw') return liveflexWithdraw(io, flags, auth, rest);
|
|
1023
|
+
if (MONEY_SUBS.includes(sub)) return liveflexMoney(io, flags, auth, sub, rest);
|
|
1024
|
+
throw new CliError('liveflex [history|fund|send|withdraw|request|split|standing|pots|refund|paylink|receipt|statement]', 2);
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/** What a payout costs, from the view's live fee rule (the server's own maths); null when an older server did not send the rule. */
|
|
1028
|
+
export function withdrawQuote(view, amountMinor, method) {
|
|
1029
|
+
const bps = Number(view?.serviceFeeBps);
|
|
1030
|
+
const cap = Number(view?.serviceFeeCapMinor);
|
|
1031
|
+
if (!Number.isFinite(bps) || !Number.isFinite(cap) || view?.serviceFeeBps == null || view?.serviceFeeCapMinor == null) return null;
|
|
1032
|
+
const feeMinor = amountMinor > 0 ? Math.min(cap, Math.round((amountMinor * bps) / 10000)) : 0;
|
|
1033
|
+
const prov = method === 'crypto' && amountMinor > 0 ? Math.max(0, Math.floor(Number(view?.cryptoProviderFeeMinor) || 0)) : 0;
|
|
1034
|
+
return { amountMinor, feeMinor, providerFeeMinor: prov, totalMinor: amountMinor + feeMinor + prov };
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
const quoteLines = (q, method) => [
|
|
1038
|
+
`Pays out ${flexc(q.amountMinor)}`,
|
|
1039
|
+
`Fee ${flexc(q.feeMinor)} on top`,
|
|
1040
|
+
...(method === 'crypto' ? [`Network fee ${flexc(q.providerFeeMinor)} on top`] : []),
|
|
1041
|
+
`Leaves your LiveFlex ${flexc(q.totalMinor)}`,
|
|
1042
|
+
].join('\n');
|
|
1043
|
+
|
|
1044
|
+
/** Withdraw: --yes locks the total just quoted; --expect-total pins the one you saw (needed for crypto). A fee change stops it before anything is taken. */
|
|
1045
|
+
async function liveflexWithdraw(io, flags, auth, rest) {
|
|
1046
|
+
if (!['bank', 'crypto'].includes(flags.method)) throw new CliError('liveflex withdraw needs --method bank|crypto', 2);
|
|
1047
|
+
const amountMinor = cents(rest[0], 'liveflex withdraw');
|
|
1048
|
+
const view = await ownerApi(io, auth(), 'GET', '/wallet');
|
|
1049
|
+
if (flags.method === 'crypto' && view?.cryptoPayoutsEnabled === false) throw new CliError('Crypto payouts are off right now. Use --method bank.', 2);
|
|
1050
|
+
const quote = withdrawQuote(view, amountMinor, flags.method);
|
|
1051
|
+
const expected = flags['expect-total'] !== undefined ? cents(flags['expect-total'], '--expect-total') : quote?.totalMinor;
|
|
1052
|
+
if (quote && flags['expect-total'] !== undefined && expected !== quote.totalMinor) {
|
|
1053
|
+
throw Object.assign(new CliError(`Fees changed: the total is now ${flexc(quote.totalMinor)}, not ${flexc(expected)}. Nothing was taken.\n${quoteLines(quote, flags.method)}\nRun it again with --expect-total ${(quote.totalMinor / 100).toFixed(2)} to accept.`, 1), { apiCode: 'FEES_CHANGED', apiData: { serviceFeeMinor: quote.feeMinor, providerFeeMinor: quote.providerFeeMinor, totalMinor: quote.totalMinor } });
|
|
1054
|
+
}
|
|
1055
|
+
if (flags.quote) {
|
|
1056
|
+
if (!quote) throw new CliError('This server did not send its fee rule, so no quote can be shown. Check `chatta liveflex`.', 1);
|
|
1057
|
+
return out(io, flags, quote, () => quoteLines(quote, flags.method));
|
|
1058
|
+
}
|
|
1059
|
+
if (!flags.yes) {
|
|
1060
|
+
const shown = quote ? `\n${quoteLines(quote, flags.method)}\n` : ` The fee (1.5%, at most 2 FlexCoin)${flags.method === 'crypto' ? ' and a flat network/provider fee' : ''} is charged on top.`;
|
|
1061
|
+
throw new CliError(`This withdraws ${flexc(amountMinor)} to your saved ${flags.method} details.${shown} Add --yes to go ahead.`, 2);
|
|
1062
|
+
}
|
|
1063
|
+
if (flags.method === 'crypto' && flags['expect-total'] === undefined) {
|
|
1064
|
+
const q = quote ? `\n${quoteLines(quote, flags.method)}\n` : ' ';
|
|
1065
|
+
throw new CliError(`A crypto withdrawal needs the total you saw.${q}Add --expect-total <amount> with --yes (the "Leaves your LiveFlex" line).`, 2);
|
|
1066
|
+
}
|
|
1067
|
+
const body = { amountMinor, method: flags.method, ...(expected ? { expectedTotalMinor: expected } : {}) };
|
|
1068
|
+
let data;
|
|
1069
|
+
try {
|
|
1070
|
+
data = await ownerApi(io, auth(), 'POST', '/wallet/withdraw', { body });
|
|
1071
|
+
} catch (e) {
|
|
1072
|
+
if (e?.apiCode !== 'FEES_CHANGED') throw e;
|
|
1073
|
+
const d = e.apiData || {};
|
|
1074
|
+
const now = Number.isFinite(d.totalMinor) ? ` The total is now ${flexc(d.totalMinor)} (fee ${flexc(d.serviceFeeMinor)}${flags.method === 'crypto' ? `, network fee ${flexc(d.providerFeeMinor)}` : ''}).` : '';
|
|
1075
|
+
throw Object.assign(new CliError(`Fees changed after the total of ${flexc(expected)} was locked.${now} Nothing was taken. Run it again to see the new quote.`, 1), { apiCode: 'FEES_CHANGED', apiData: d });
|
|
1076
|
+
}
|
|
1077
|
+
if (data?.approvalRequired) return out(io, flags, data, () => `Sent for team approval. ${data.message || 'The owner has to approve it first.'}${data.approvalId ? ` Approval ${data.approvalId}.` : ''} Nothing has left your LiveFlex yet.`);
|
|
1078
|
+
return out(io, flags, data, () => `${flexc(data?.netMinor)} is on its way to ${data?.destination}. Fee ${flexc(data?.serviceFeeMinor)} on top${data?.providerFeeMinor ? `, network/provider fee ${flexc(data.providerFeeMinor)} on top` : ''}, ${flexc(data?.totalMinor ?? (data?.netMinor || 0) + (data?.serviceFeeMinor || 0) + (data?.providerFeeMinor || 0))} in total from your LiveFlex. Reference ${data?.reference}.`);
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
const MONEY_SUBS = ['request', 'split', 'standing', 'pots', 'refund', 'paylink', 'receipt', 'statement'];
|
|
1082
|
+
const needYes = (flags, what) => {
|
|
1083
|
+
if (!flags.yes) throw new CliError(`${what} Add --yes to go ahead.`, 2);
|
|
1084
|
+
};
|
|
1085
|
+
/** `--member-token` and `--pin` show up in shell history and `ps`; the stdin forms (one line each, token first) do not. */
|
|
1086
|
+
async function secretsFromStdin(io, flags) {
|
|
1087
|
+
if (flags['member-token'] || flags.pin) io.err('chatta: --member-token and --pin are visible to other users and in shell history. Prefer LIVECHATTA_MEMBER_TOKEN, --member-token-stdin and --pin-stdin.');
|
|
1088
|
+
if (flags.token && !flags['token-stdin']) io.err('chatta: --token is visible to other users and in shell history. Prefer --token-stdin (member token on the first line, the invite token on the second).');
|
|
1089
|
+
if (!flags['member-token-stdin'] && !flags['pin-stdin'] && !flags['token-stdin']) return;
|
|
1090
|
+
const lines = String(await io.readStdin()).split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
1091
|
+
if (flags['member-token-stdin']) flags['member-token'] = lines.shift() || '';
|
|
1092
|
+
if (flags['token-stdin']) flags.token = lines.shift() || '';
|
|
1093
|
+
if (flags['pin-stdin']) flags.pin = lines.shift() || '';
|
|
1094
|
+
if ((flags['member-token-stdin'] && !flags['member-token']) || (flags['token-stdin'] && !flags.token) || (flags['pin-stdin'] && !flags.pin)) throw new CliError('Expected the value on standard input (member token first, then the invite token, then the PIN, one per line).', 2);
|
|
1095
|
+
}
|
|
1096
|
+
/** A signed download link is private to you, so it is printed only on request; `--out` saves the file instead. */
|
|
1097
|
+
const hideUrls = (flags, data, keys) => (flags['show-url'] || !data ? data : Object.fromEntries(Object.entries(data).filter(([k]) => !keys.includes(k))));
|
|
1098
|
+
const urlHint = 'Add --out <file> to save it, or --show-url to print the link (it lasts 10 minutes and only opens for you, signed in).';
|
|
1099
|
+
const confirmBody = (flags) => ({ pin: flags.pin, code: flags.code });
|
|
1100
|
+
const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== ''));
|
|
1101
|
+
/** "@bola", "$kaka", a member id, or a bare handle → the API's person fields. */
|
|
1102
|
+
function personOf(v, what) {
|
|
1103
|
+
const t = String(v || '').trim();
|
|
1104
|
+
if (!t) throw new CliError(`${what} needs a person: @handle, $tag or a member id`, 2);
|
|
1105
|
+
if (t.startsWith('$')) return { tag: t.slice(1) };
|
|
1106
|
+
if (/^[a-f0-9]{24}$/i.test(t)) return { id: t };
|
|
1107
|
+
return { handle: t.replace(/^@/, '') };
|
|
1108
|
+
}
|
|
1109
|
+
const dateIso = (v, what) => {
|
|
1110
|
+
if (v === undefined) return undefined;
|
|
1111
|
+
const d = new Date(String(v));
|
|
1112
|
+
if (Number.isNaN(d.getTime())) throw new CliError(`${what} needs a date like 2026-12-01`, 2);
|
|
1113
|
+
return d.toISOString();
|
|
1114
|
+
};
|
|
1115
|
+
const isoDay = (iso) => String(iso || '').slice(0, 10);
|
|
1116
|
+
const reqRow = (r) => ({ id: r.id, status: r.status, from: r.requester?.name, to: r.payer?.name, amount: flexc(r.amountMinor), note: r.note, expires: isoDay(r.expiresAt) });
|
|
1117
|
+
|
|
1118
|
+
/** https and the exact host (and port) of the API base, so the token only goes to the API itself. */
|
|
1119
|
+
function sameSite(base, url) {
|
|
1120
|
+
try {
|
|
1121
|
+
const b = new URL(base);
|
|
1122
|
+
const u = new URL(url);
|
|
1123
|
+
const local = b.hostname === 'localhost' || b.hostname === '127.0.0.1';
|
|
1124
|
+
if (u.protocol !== 'https:' && !(local && u.protocol === b.protocol)) return false;
|
|
1125
|
+
return u.host === b.host && !u.username && !u.password;
|
|
1126
|
+
} catch {
|
|
1127
|
+
return false;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/** Saves a signed link's file. The link lasts 10 minutes and only opens for the signed-in person. */
|
|
1132
|
+
async function saveFile(io, auth, url, path) {
|
|
1133
|
+
const token = auth.memberToken || auth.ownerToken;
|
|
1134
|
+
if (!sameSite(auth.baseUrl, url)) throw new CliError('Refusing to send your token to a download link on another site.');
|
|
1135
|
+
if (!token) throw new CliError(`No token. Set LIVECHATTA_MEMBER_TOKEN to download the file. ${RELOGIN}`);
|
|
1136
|
+
let res;
|
|
1137
|
+
try {
|
|
1138
|
+
res = await io.fetch(url, { method: 'GET', redirect: 'manual', headers: { Authorization: `Bearer ${token}` } });
|
|
1139
|
+
} catch (e) {
|
|
1140
|
+
throw new CliError(`Could not download: ${e?.message || e}`);
|
|
1141
|
+
}
|
|
1142
|
+
if (res.status >= 300 && res.status < 400) throw new CliError('The download link redirected; not following it with your token.');
|
|
1143
|
+
if (!res.ok) throw new CliError(`Download failed (${res.status}). The link lasts 10 minutes; ask for a new one.`);
|
|
1144
|
+
const body = typeof res.arrayBuffer === 'function' ? Buffer.from(await res.arrayBuffer()) : Buffer.from(await res.text());
|
|
1145
|
+
writeFileSync(String(path), body, { mode: 0o600 });
|
|
1146
|
+
return body.length;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
async function liveflexMoney(io, flags, auth, sub, rest) {
|
|
1150
|
+
const [a, b, c] = rest;
|
|
1151
|
+
const id = (v, what) => {
|
|
1152
|
+
if (!v) throw new CliError(`${what} needs an id`, 2);
|
|
1153
|
+
return encodeURIComponent(v);
|
|
1154
|
+
};
|
|
1155
|
+
if (sub === 'request') {
|
|
1156
|
+
if (a === 'list') {
|
|
1157
|
+
const data = await memberApi(io, auth(), 'GET', '/wallet/requests', { query: { box: flags.sent ? 'outgoing' : 'incoming' } });
|
|
1158
|
+
const rows = listOf(data).map(reqRow);
|
|
1159
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'status', 'from', 'to', 'amount', 'note', 'expires']) : 'No requests.'));
|
|
1160
|
+
}
|
|
1161
|
+
if (['get', 'decline', 'cancel', 'block'].includes(a)) {
|
|
1162
|
+
const data = a === 'get'
|
|
1163
|
+
? await memberApi(io, auth(), 'GET', `/wallet/requests/${id(b, `liveflex request ${a}`)}`)
|
|
1164
|
+
: await memberApi(io, auth(), 'POST', `/wallet/requests/${id(b, `liveflex request ${a}`)}/${a}`);
|
|
1165
|
+
return out(io, flags, data, () => `${flexc(data?.amountMinor)} from ${data?.payer?.name} to ${data?.requester?.name}: ${data?.status}.`);
|
|
1166
|
+
}
|
|
1167
|
+
if (a === 'pay') {
|
|
1168
|
+
needYes(flags, 'This pays the request from your LiveFlex.');
|
|
1169
|
+
const data = await memberApi(io, auth(), 'POST', `/wallet/requests/${id(b, 'liveflex request pay')}/pay`, { body: clean(confirmBody(flags)) });
|
|
1170
|
+
return out(io, flags, data, () => `Paid. Reference ${data?.reference}. Balance ${flexc(data?.balanceMinor)}.`);
|
|
1171
|
+
}
|
|
1172
|
+
if (!flags.chat) throw new CliError('liveflex request needs --chat <conversationId>', 2);
|
|
1173
|
+
const body = { conversationId: String(flags.chat), amountMinor: cents(a, 'liveflex request'), note: flags.note, ...personOf(flags.to, 'liveflex request --to') };
|
|
1174
|
+
const data = await memberApi(io, auth(), 'POST', '/wallet/requests', { body: clean(body) });
|
|
1175
|
+
return out(io, flags, data, () => `Asked ${data?.payer?.name} for ${flexc(data?.amountMinor)}. Request ${data?.id} (${data?.status}). Nothing moves until they pay.`);
|
|
1176
|
+
}
|
|
1177
|
+
if (sub === 'split') {
|
|
1178
|
+
if (['get', 'cancel'].includes(a)) {
|
|
1179
|
+
const data = a === 'get'
|
|
1180
|
+
? await memberApi(io, auth(), 'GET', `/wallet/splits/${id(b, `liveflex split ${a}`)}`)
|
|
1181
|
+
: await memberApi(io, auth(), 'POST', `/wallet/splits/${id(b, `liveflex split ${a}`)}/cancel`);
|
|
1182
|
+
return out(io, flags, data, () => `${flexc(data?.totalMinor)} split · ${data?.paidCount ?? 0} paid (${flexc(data?.paidMinor)}) · ${data?.status}
|
|
1183
|
+
` +
|
|
1184
|
+
table((data?.shares || []).map((x) => ({ who: x.name, amount: flexc(x.amountMinor), status: x.status })), ['who', 'amount', 'status']));
|
|
1185
|
+
}
|
|
1186
|
+
if (!flags.chat || !flags.with) throw new CliError('liveflex split needs --with <@a,@b> and --chat <conversationId>', 2);
|
|
1187
|
+
const shares = {};
|
|
1188
|
+
for (const part of String(flags.shares || '').split(',').filter(Boolean)) {
|
|
1189
|
+
const [who, amt] = part.split('=');
|
|
1190
|
+
shares[String(who).replace(/^[@$]/, '').toLowerCase()] = cents(amt, `liveflex split --shares ${who}`);
|
|
1191
|
+
}
|
|
1192
|
+
const payers = String(flags.with).split(',').filter(Boolean).map((w) => {
|
|
1193
|
+
const key = w.replace(/^[@$]/, '').toLowerCase();
|
|
1194
|
+
return { ...personOf(w, 'liveflex split --with'), ...(shares[key] ? { amountMinor: shares[key] } : {}) };
|
|
1195
|
+
});
|
|
1196
|
+
const body = { conversationId: String(flags.chat), totalMinor: cents(a, 'liveflex split'), payers, includeMe: flags['including-me'] ? true : undefined, note: flags.note };
|
|
1197
|
+
const data = await memberApi(io, auth(), 'POST', '/wallet/splits', { body: clean(body) });
|
|
1198
|
+
return out(io, flags, data, () => `Split ${data?.id}: ${(data?.shares || []).map((x) => `${x.name} ${flexc(x.amountMinor)}`).join(', ')}. Your share ${flexc(data?.requesterShareMinor)}. Nothing moves until they pay.`);
|
|
1199
|
+
}
|
|
1200
|
+
if (sub === 'standing') {
|
|
1201
|
+
if (!a || a === 'list') {
|
|
1202
|
+
const data = await userApi(io, auth(), 'GET', '/wallet/standing');
|
|
1203
|
+
const rows = listOf(data).map((r) => ({ id: r.id, status: r.status, who: r.mine === false ? `from ${r.payerName || 'someone'}` : `to ${r.toName}`, amount: flexc(r.amountMinor), every: r.interval, next: isoDay(r.nextRunAt), runs: `${r.runsDone}${r.maxRuns ? `/${r.maxRuns}` : ''}`, mine: r.mine ? 'yes' : 'read-only' }));
|
|
1204
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'status', 'who', 'amount', 'every', 'next', 'runs', 'mine']) : 'No standing payments.'));
|
|
1205
|
+
}
|
|
1206
|
+
if (['pause', 'resume', 'cancel'].includes(a)) {
|
|
1207
|
+
const data = await userApi(io, auth(), 'POST', `/wallet/standing/${id(b, `liveflex standing ${a}`)}/${a}`);
|
|
1208
|
+
return out(io, flags, data, () => `${flexc(data?.amountMinor)} to ${data?.toName}: ${data?.status}.`);
|
|
1209
|
+
}
|
|
1210
|
+
if (a !== 'create') throw new CliError('liveflex standing [list|create|pause|resume|cancel]', 2);
|
|
1211
|
+
const interval = flags.every;
|
|
1212
|
+
if (!['week', '2weeks', 'month'].includes(interval)) throw new CliError('liveflex standing create needs --every week|2weeks|month', 2);
|
|
1213
|
+
const amountMinor = cents(b, 'liveflex standing create');
|
|
1214
|
+
needYes(flags, `This authorises ${flexc(amountMinor)} every ${interval} to ${flags.to || 'them'}${flags.times ? ` for ${flags.times} payments` : flags.until ? ` until ${flags.until}` : ' until you cancel it'}; each payment goes out on its day.`);
|
|
1215
|
+
const times = int(flags.times, 'times', 1, 120);
|
|
1216
|
+
const body = { ...personOf(flags.to, 'liveflex standing create --to'), amountMinor, interval, startAt: dateIso(flags.from, '--from'), until: dateIso(flags.until, '--until'), maxRuns: times, note: flags.note, ...clean(confirmBody(flags)) };
|
|
1217
|
+
const data = await memberApi(io, auth(), 'POST', '/wallet/standing', { body: clean(body) });
|
|
1218
|
+
return out(io, flags, data, () => `Standing payment ${data?.id}: ${flexc(data?.amountMinor)} to ${data?.toName}, first on ${isoDay(data?.nextRunAt)}${data?.totalMinor != null ? `, up to ${flexc(data.totalMinor)} in all` : ', until you cancel'}.`);
|
|
1219
|
+
}
|
|
1220
|
+
if (sub === 'pots') {
|
|
1221
|
+
if (a === 'create') {
|
|
1222
|
+
if (!b || !flags.chat) throw new CliError('liveflex pots create <title> --chat <conversationId>', 2);
|
|
1223
|
+
const body = { conversationId: String(flags.chat), title: b, amountMinor: flags.each ? cents(flags.each, '--each') : undefined, goalMinor: flags.goal ? cents(flags.goal, '--goal') : undefined, closesAt: dateIso(flags.by, '--by') };
|
|
1224
|
+
const data = await memberApi(io, auth(), 'POST', '/wallet/pots', { body: clean(body) });
|
|
1225
|
+
return out(io, flags, data, () => `Pot ${data?.id}: ${data?.title}, closes ${isoDay(data?.closesAt)}. The money is held for the pot until it closes.`);
|
|
1226
|
+
}
|
|
1227
|
+
if (a === 'get') {
|
|
1228
|
+
const data = await memberApi(io, auth(), 'GET', `/wallet/pots/${id(b, 'liveflex pots get')}`);
|
|
1229
|
+
return out(io, flags, data, () => `${data?.title} · ${data?.status} · ${flexc(data?.collectedMinor)} from ${data?.contributorCount} · closes ${isoDay(data?.closesAt)}`);
|
|
1230
|
+
}
|
|
1231
|
+
if (a === 'contribute') {
|
|
1232
|
+
needYes(flags, 'This puts your money in the pot, held until it closes.');
|
|
1233
|
+
const body = { amountMinor: c ? cents(c, 'liveflex pots contribute') : undefined, ...confirmBody(flags) };
|
|
1234
|
+
const data = await memberApi(io, auth(), 'POST', `/wallet/pots/${id(b, 'liveflex pots contribute')}/contribute`, { body: clean(body) });
|
|
1235
|
+
return out(io, flags, data, () => `In. ${data?.title} has ${flexc(data?.collectedMinor)} from ${data?.contributorCount}.`);
|
|
1236
|
+
}
|
|
1237
|
+
if (a === 'close' || a === 'cancel') {
|
|
1238
|
+
needYes(flags, a === 'close' ? 'This closes the pot and pays everything collected to you.' : 'This cancels the pot and refunds everyone.');
|
|
1239
|
+
const data = await memberApi(io, auth(), 'POST', `/wallet/pots/${id(b, `liveflex pots ${a}`)}/${a}`);
|
|
1240
|
+
return out(io, flags, data, () => `${data?.title}: ${data?.status}${data?.paidOutMinor ? `, ${flexc(data.paidOutMinor)} paid out` : ''}.`);
|
|
1241
|
+
}
|
|
1242
|
+
throw new CliError('liveflex pots [create|get|contribute|close|cancel]', 2);
|
|
1243
|
+
}
|
|
1244
|
+
if (sub === 'refund') {
|
|
1245
|
+
if (!a) throw new CliError('liveflex refund needs the transaction id of the payment you received', 2);
|
|
1246
|
+
const amountMinor = b ? cents(b, 'liveflex refund') : undefined;
|
|
1247
|
+
needYes(flags, `This gives ${amountMinor ? flexc(amountMinor) : 'what is left of the payment'} back to the person who sent it.`);
|
|
1248
|
+
const key = flags.key || `cli_${io.now().getTime().toString(36)}`;
|
|
1249
|
+
const data = await userApi(io, auth(), 'POST', `/wallet/transactions/${id(a, 'liveflex refund')}/refund`, { body: clean({ amountMinor, note: flags.note, key, ...confirmBody(flags) }) });
|
|
1250
|
+
if (data?.approvalRequired) return out(io, flags, data, () => data.message);
|
|
1251
|
+
return out(io, flags, data, () => `Refunded. Reference ${data?.reference}. ${flexc(data?.remainingMinor)} of the original is still refundable.`);
|
|
1252
|
+
}
|
|
1253
|
+
if (sub === 'paylink') {
|
|
1254
|
+
if (a === 'create') {
|
|
1255
|
+
if (!flags.chat || !flags.for) throw new CliError('liveflex paylink create <amount> --chat <conversationId> --for <description>', 2);
|
|
1256
|
+
const body = { conversationId: String(flags.chat), amountMinor: cents(b, 'liveflex paylink create'), description: String(flags.for), reference: flags.ref };
|
|
1257
|
+
const data = await memberApi(io, auth(), 'POST', '/wallet/pay-links', { body: clean(body) });
|
|
1258
|
+
return out(io, flags, data, () => `Payment link ${data?.id} posted: ${flexc(data?.amountMinor)} for ${data?.description}. It expires ${isoDay(data?.expiresAt)}.`);
|
|
1259
|
+
}
|
|
1260
|
+
if (a === 'get') {
|
|
1261
|
+
const data = await memberApi(io, auth(), 'GET', `/wallet/pay-links/${id(b, 'liveflex paylink get')}`);
|
|
1262
|
+
return out(io, flags, data, () => `${flexc(data?.amountMinor)} for ${data?.description}: ${data?.status}${data?.paidWith ? ` (${data.paidWith})` : ''}.`);
|
|
1263
|
+
}
|
|
1264
|
+
if (a === 'cancel') {
|
|
1265
|
+
const data = await memberApi(io, auth(), 'POST', `/wallet/pay-links/${id(b, 'liveflex paylink cancel')}/cancel`);
|
|
1266
|
+
return out(io, flags, data, () => `Payment link ${data?.id}: ${data?.status}.`);
|
|
1267
|
+
}
|
|
1268
|
+
if (a === 'pay') {
|
|
1269
|
+
if (!['wallet', 'card'].includes(flags.method)) throw new CliError('liveflex paylink pay needs --method wallet|card', 2);
|
|
1270
|
+
if (flags.method === 'wallet') needYes(flags, 'This pays the link from your LiveFlex.');
|
|
1271
|
+
const data = await memberApi(io, auth(), 'POST', `/wallet/pay-links/${id(b, 'liveflex paylink pay')}/pay`, { body: clean({ method: flags.method, ...confirmBody(flags) }) });
|
|
1272
|
+
return out(io, flags, data, () => (data?.authorizationUrl ? `Pay by card or bank:\n${data.authorizationUrl}` : `Paid. Reference ${data?.reference}. Balance ${flexc(data?.balanceMinor)}.`));
|
|
1273
|
+
}
|
|
1274
|
+
throw new CliError('liveflex paylink [create|get|cancel|pay]', 2);
|
|
1275
|
+
}
|
|
1276
|
+
if (sub === 'receipt') {
|
|
1277
|
+
if (!a) {
|
|
1278
|
+
const data = await userApi(io, auth(), 'GET', '/wallet/receipts');
|
|
1279
|
+
const rows = listOf(data).map((r) => ({ reference: r.reference, what: r.title, amount: flexc(r.amountMinor), when: isoDay(r.createdAt) }));
|
|
1280
|
+
const shown = flags['show-url'] || !data || !Array.isArray(data.results) ? data : { ...data, results: data.results.map((r) => hideUrls(flags, r, ['url'])) };
|
|
1281
|
+
return out(io, flags, shown, () => (rows.length ? `${table(rows, ['reference', 'what', 'amount', 'when'])}\nSave one: chatta liveflex receipt <reference> --out receipt.pdf` : 'No receipts yet.'));
|
|
1282
|
+
}
|
|
1283
|
+
const link = await userApi(io, auth(), 'GET', `/wallet/receipts/${id(a, 'liveflex receipt')}/link`);
|
|
1284
|
+
if (flags.out) {
|
|
1285
|
+
const bytes = await saveFile(io, auth(), link.url, flags.out);
|
|
1286
|
+
return out(io, flags, { reference: a, saved: String(flags.out), bytes }, () => `Saved ${flags.out} (${bytes} bytes).`);
|
|
1287
|
+
}
|
|
1288
|
+
return out(io, flags, hideUrls(flags, link, ['url']), () => `${link?.title} · ${flexc(link?.amountMinor)}\n${flags['show-url'] ? `${link?.url}\nThe link lasts 10 minutes and only opens for you, signed in.` : urlHint}`);
|
|
1289
|
+
}
|
|
1290
|
+
if (sub === 'statement') {
|
|
1291
|
+
if (!a) throw new CliError('liveflex statement needs a month like 2026-10 (or "last")', 2);
|
|
1292
|
+
let month = a;
|
|
1293
|
+
if (a === 'last') {
|
|
1294
|
+
const n = io.now();
|
|
1295
|
+
const d = new Date(Date.UTC(n.getUTCFullYear(), n.getUTCMonth() - 1, 1));
|
|
1296
|
+
month = `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
|
|
1297
|
+
}
|
|
1298
|
+
if (!/^\d{4}-\d{2}$/.test(month)) throw new CliError('liveflex statement needs a month like 2026-10 (or "last")', 2);
|
|
1299
|
+
const format = flags.format || 'pdf';
|
|
1300
|
+
if (!['pdf', 'csv'].includes(format)) throw new CliError('--format is pdf or csv', 2);
|
|
1301
|
+
const links = await userApi(io, auth(), 'GET', `/wallet/statements/${month}/links`);
|
|
1302
|
+
const url = format === 'csv' ? links.csvUrl : links.pdfUrl;
|
|
1303
|
+
if (flags.out) {
|
|
1304
|
+
const bytes = await saveFile(io, auth(), url, flags.out);
|
|
1305
|
+
return out(io, flags, { month, scope: links.scope, saved: String(flags.out), bytes }, () => `Saved the ${links.scope} statement for ${month} to ${flags.out} (${bytes} bytes).`);
|
|
1306
|
+
}
|
|
1307
|
+
return out(io, flags, hideUrls(flags, links, ['pdfUrl', 'csvUrl']), () => `${links.scope} statement ${month}\n${flags['show-url'] ? `PDF ${links.pdfUrl}\nCSV ${links.csvUrl}\nEach link lasts 10 minutes and only opens for you, signed in.` : urlHint}`);
|
|
1308
|
+
}
|
|
1309
|
+
throw new CliError('liveflex [request|split|standing|pots|refund|paylink|receipt|statement]', 2);
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
async function billing(io, flags, auth, sub, [action, ...rest]) {
|
|
1313
|
+
if (sub === 'pending') {
|
|
1314
|
+
const d = await ownerApi(io, auth(), 'GET', '/subscriptions/pending-transfers');
|
|
1315
|
+
const rows = (d?.pending || []).map((p) => ({ reference: p.reference, kind: p.kind, state: p.state, usd: money(p.amountUsd), expires: p.expiresAt }));
|
|
1316
|
+
return out(io, flags, d, () => (rows.length ? table(rows, ['reference', 'kind', 'state', 'usd', 'expires']) : 'No bank transfers waiting.'));
|
|
1317
|
+
}
|
|
1318
|
+
if (sub === 'storage-renew') {
|
|
1319
|
+
const id = action;
|
|
1320
|
+
const state = rest[0];
|
|
1321
|
+
if (!id || !['on', 'off'].includes(state)) throw new CliError('billing storage-renew needs <purchaseId> on|off', 2);
|
|
1322
|
+
const r = await ownerApi(io, auth(), 'POST', `/subscriptions/storage/addons/${encodeURIComponent(id)}/auto-renew`, { body: { autoRenew: state === 'on' } });
|
|
1323
|
+
return out(io, flags, r, () => r?.line || `Auto-renew ${state}.`);
|
|
1324
|
+
}
|
|
1325
|
+
if (sub === 'storage') {
|
|
1326
|
+
const s = await ownerApi(io, auth(), 'GET', '/subscriptions/storage');
|
|
1327
|
+
const cap = s?.capGB === 0 ? 'unlimited' : s?.capGB === -1 ? 'no uploads on this plan' : `${s?.capGB} GB (plan ${s?.planGB} + add-ons ${s?.addonGB})`;
|
|
1328
|
+
return out(io, flags, s, () => `This month ${gb(s?.monthBytes)} of ${cap}${s?.pct != null ? ` · ${s.pct}%` : ''} · ${s?.state}\nResets ${s?.resetsAt}`);
|
|
1329
|
+
}
|
|
1330
|
+
if (sub === 'renewal') {
|
|
1331
|
+
const r = (await ownerApi(io, auth(), 'GET', '/subscriptions/renewal'))?.renewal;
|
|
1332
|
+
return out(io, flags, { renewal: r ?? null }, () => (r
|
|
1333
|
+
? `Subscription ${r.subscriptionId}: ${r.state}, ${r.daysLeft} days left, $${Number(r.amountUsd || 0).toFixed(2)} due` +
|
|
1334
|
+
(r.state === 'current' ? '' : `\nPay: chatta billing renew ${r.subscriptionId}`)
|
|
1335
|
+
: 'Nothing to renew by hand: your plan renews on its card, or there is no paid plan.'));
|
|
1336
|
+
}
|
|
1337
|
+
if (sub === 'renew') {
|
|
1338
|
+
const id = action;
|
|
1339
|
+
if (!id) throw new CliError('billing renew needs <subscriptionId>', 2);
|
|
1340
|
+
if (flags.method && !['bank_transfer', 'card'].includes(flags.method)) throw new CliError('--method must be bank_transfer or card', 2);
|
|
1341
|
+
const r = await ownerApi(io, auth(), 'POST', `/subscriptions/${encodeURIComponent(id)}/renew`, { body: flags.method ? { paymentMethod: flags.method } : {} });
|
|
1342
|
+
return out(io, flags, r, () => `Open this checkout to pay (${r?.paymentMethod || 'bank_transfer'}):\n${r?.authorizationUrl}\nReference ${r?.reference}`);
|
|
1343
|
+
}
|
|
1344
|
+
if (sub === 'trial' && !action) {
|
|
1345
|
+
const t = await ownerApi(io, auth(), 'GET', '/subscriptions/trial');
|
|
1346
|
+
const tr = t?.trial;
|
|
1347
|
+
return out(io, flags, t, () => (tr
|
|
1348
|
+
? `${tr.planName} trial ${tr.status}: ${tr.daysLeft} days left (ends ${tr.endsAt}). ${tr.hasCard ? 'Your saved card is charged then.' : 'Add a card in Billing or the plan pauses.'}`
|
|
1349
|
+
: t?.eligible ? 'No trial yet. Start one: chatta billing trial start --plan <planId>' : 'No free trial available (already used, or a plan is active).'));
|
|
1350
|
+
}
|
|
1351
|
+
if (sub === 'trial' && action === 'start') {
|
|
1352
|
+
if (!flags.plan) throw new CliError('billing trial start needs --plan <planId>', 2);
|
|
1353
|
+
const cycle = flags.cycle ? String(flags.cycle).toUpperCase() : undefined;
|
|
1354
|
+
if (cycle && !CYCLES.includes(cycle)) throw new CliError(`--cycle must be one of ${CYCLES.join(', ')}`, 2);
|
|
1355
|
+
const r = await ownerApi(io, auth(), 'POST', '/subscriptions/trial', { body: { planId: flags.plan, ...(cycle ? { billingCycle: cycle } : {}) } });
|
|
1356
|
+
return out(io, flags, r, () => `${r?.planName} trial started: ${r?.days} days, ends ${r?.trialEndsAt}.`);
|
|
1357
|
+
}
|
|
1358
|
+
throw new CliError('Usage: chatta billing storage | renewal | renew <subscriptionId> | pending | storage-renew <purchaseId> on|off | trial [start --plan <id>]', 2);
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
// ---------- P-N10: members, export, messages, doctor, profiles, completion ----------
|
|
1363
|
+
const MEMBER_STATUSES = ['all', 'active', 'blocked', 'invited'];
|
|
1364
|
+
const csvCell = (v) => {
|
|
1365
|
+
const t = String(v ?? '');
|
|
1366
|
+
return /[",\n\r]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t;
|
|
1367
|
+
};
|
|
1368
|
+
|
|
1369
|
+
async function members(io, flags, auth, sub, [linkId, memberId]) {
|
|
1370
|
+
if (!linkId) throw new CliError(`members ${sub || 'list'} needs <linkId>`, 2);
|
|
1371
|
+
const base = `/chats/links/${encodeURIComponent(linkId)}`;
|
|
1372
|
+
if (sub === 'list' || sub === 'export') {
|
|
1373
|
+
if (flags.status && !MEMBER_STATUSES.includes(flags.status)) throw new CliError(`--status must be one of ${MEMBER_STATUSES.join(', ')}`, 2);
|
|
1374
|
+
if (sub === 'list') {
|
|
1375
|
+
const limit = int(flags.limit, 'limit', 1, 100);
|
|
1376
|
+
const page = await ownerApi(io, auth(), 'GET', `${base}/member-list`, { query: { q: flags.search, status: flags.status, limit: limit && String(limit), nextCursor: flags.cursor } });
|
|
1377
|
+
const rows = listOf(page).map((m) => ({ id: m._id, name: m.name, email: m.email, role: m.role, status: m.status, joined: m.joinedAt || '' }));
|
|
1378
|
+
return out(io, flags, page, () => `${page?.total ?? rows.length} members\n` +
|
|
1379
|
+
(rows.length ? table(rows, ['id', 'name', 'email', 'role', 'status', 'joined']) : 'No members.') +
|
|
1380
|
+
(page?.nextCursor ? `\nMore: chatta members list ${linkId} --cursor ${page.nextCursor}` : ''));
|
|
1381
|
+
}
|
|
1382
|
+
// export: every page, written as CSV (stdout or --out <file>).
|
|
1383
|
+
const all = [];
|
|
1384
|
+
let cursor;
|
|
1385
|
+
for (let i = 0; i < 500; i++) {
|
|
1386
|
+
const page = await ownerApi(io, auth(), 'GET', `${base}/member-list`, { query: { q: flags.search, status: flags.status, limit: '100', nextCursor: cursor } });
|
|
1387
|
+
all.push(...listOf(page));
|
|
1388
|
+
cursor = page?.nextCursor;
|
|
1389
|
+
if (!cursor || !page?.hasMore) break;
|
|
1390
|
+
}
|
|
1391
|
+
const cols = ['_id', 'name', 'email', 'role', 'status', 'joinedAt'];
|
|
1392
|
+
const text = [cols.join(','), ...all.map((m) => cols.map((c) => csvCell(m[c])).join(','))].join('\n') + '\n';
|
|
1393
|
+
if (flags.out) {
|
|
1394
|
+
writeFileSync(String(flags.out), text, { mode: 0o600 });
|
|
1395
|
+
io.out(`Wrote ${all.length} members to ${flags.out}`);
|
|
1396
|
+
} else io.out(text.trimEnd());
|
|
1397
|
+
return 0;
|
|
1398
|
+
}
|
|
1399
|
+
if (sub === 'block' || sub === 'unblock') {
|
|
1400
|
+
if (!memberId) throw new CliError(`members ${sub} needs <linkId> <memberId>`, 2);
|
|
1401
|
+
if (sub === 'block' && !flags.yes) throw new CliError('members block stops them sending in this link. Re-run with --yes.', 2);
|
|
1402
|
+
const r = await ownerApi(io, auth(), 'POST', `${base}/members/${encodeURIComponent(memberId)}/${sub}`);
|
|
1403
|
+
return out(io, flags, r, () => `${sub === 'block' ? 'Blocked' : 'Unblocked'} ${memberId} on ${linkId}.`);
|
|
1404
|
+
}
|
|
1405
|
+
if (sub === 'revoke-invite') {
|
|
1406
|
+
if (!memberId) throw new CliError('members revoke-invite needs <linkId> <memberId>', 2);
|
|
1407
|
+
if (!flags.yes) throw new CliError('members revoke-invite takes them off the invite list (and blocks them if they joined). Re-run with --yes.', 2);
|
|
1408
|
+
const r = await ownerApi(io, auth(), 'DELETE', `${base}/members/${encodeURIComponent(memberId)}/invite`);
|
|
1409
|
+
return out(io, flags, r, () => `Invite revoked for ${memberId} on ${linkId}${r?.blocked ? '; they had joined, so they are blocked too' : ''}.`);
|
|
1410
|
+
}
|
|
1411
|
+
throw new CliError('Usage: chatta members list|export|block|unblock|revoke-invite <linkId> [memberId]', 2);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
/** Support CSAT with the API key: rated requests and the summary for a window (default the last 30 days). */
|
|
1415
|
+
async function csat(io, flags, auth, sub) {
|
|
1416
|
+
const range = { from: flags.from, to: flags.to, chatLinkId: flags.link };
|
|
1417
|
+
for (const k of ['from', 'to']) if (flags[k] !== undefined && Number.isNaN(Date.parse(String(flags[k])))) throw new CliError(`--${k} must be an ISO date`, 2);
|
|
1418
|
+
const pct = (v) => (v === null || v === undefined ? '—' : `${v}%`);
|
|
1419
|
+
if (sub === 'list') {
|
|
1420
|
+
const limit = int(flags.limit, 'limit', 1, 20);
|
|
1421
|
+
const data = await api(io, auth(), 'GET', '/chats/csat', { query: { ...range, limit: limit && String(limit), nextCursor: flags.cursor } });
|
|
1422
|
+
const rows = listOf(data).map((r) => ({ score: `${r.score ?? '—'}/${r.scale || 5}`, agent: r.agentName || '', team: r.teamName || '', rated: r.ratedAt || '', conversation: r.conversationId, comment: r.comment || '' }));
|
|
1423
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['score', 'agent', 'team', 'rated', 'conversation', 'comment']) : 'No ratings in this window.') + more(data, 'csat list'));
|
|
1424
|
+
}
|
|
1425
|
+
if (sub === 'summary') {
|
|
1426
|
+
const s = await api(io, auth(), 'GET', '/chats/csat/summary', { query: range });
|
|
1427
|
+
const groups = (list) => (list || []).map((g) => ({ name: g.name || '(none)', responses: g.responses, average: g.average ?? '—', satisfied: pct(g.satisfiedPct) }));
|
|
1428
|
+
return out(io, flags, s, () => [
|
|
1429
|
+
`Average ${s?.average ?? '—'} / 5 · satisfied ${pct(s?.satisfiedPct)} · ${s?.responses ?? 0} of ${s?.requests ?? 0} rated (${pct(s?.responseRatePct)})`,
|
|
1430
|
+
s?.agents?.length ? `\nAgents\n${table(groups(s.agents), ['name', 'responses', 'average', 'satisfied'])}` : '',
|
|
1431
|
+
s?.teams?.length ? `\nTeams\n${table(groups(s.teams), ['name', 'responses', 'average', 'satisfied'])}` : '',
|
|
1432
|
+
].filter(Boolean).join('\n'));
|
|
1433
|
+
}
|
|
1434
|
+
throw new CliError('Usage: chatta csat list | summary [--from <ISO>] [--to <ISO>] [--link <linkId>]', 2);
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
/** Start a conversation export (ZIP, emailed too); --wait polls until it is ready and prints the download link. */
|
|
1438
|
+
async function exportCmd(io, flags, auth, [conversationId]) {
|
|
1439
|
+
if (conversationId === 'list') {
|
|
1440
|
+
const data = await api(io, auth(), 'GET', '/chats/exports', { query: { limit: String(int(flags.limit, 'limit', 1, 50) || 10) } });
|
|
1441
|
+
const rows = listOf(data).map((x) => ({ id: x._id, conversation: x.conversation?._id || x.conversation || '', status: x.status || (x.zipUrl ? 'ready' : 'pending'), created: x.createdAt, zip: x.zipUrl || '' }));
|
|
1442
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'conversation', 'status', 'created', 'zip']) : 'No exports yet.'));
|
|
1443
|
+
}
|
|
1444
|
+
if (!conversationId) throw new CliError('export needs <conversationId> (or: chatta export list)', 2);
|
|
1445
|
+
if (flags.format && !['json', 'csv', 'html', 'txt'].includes(flags.format)) throw new CliError('--format must be json, csv, html or txt', 2);
|
|
1446
|
+
const started = await api(io, auth(), 'POST', '/chats/exports', { body: { conversationId, email: flags.email, format: flags.format } });
|
|
1447
|
+
const id = started?._id || started?.exportId || '';
|
|
1448
|
+
if (!flags.wait) return out(io, flags, started, () => `Export started${id ? ` (${id})` : ''}. It is emailed when ready; check with: chatta export list`);
|
|
1449
|
+
for (let i = 0; i < 60; i++) {
|
|
1450
|
+
await io.sleep(5000);
|
|
1451
|
+
const list = listOf(await api(io, auth(), 'GET', '/chats/exports', { query: { limit: '20' } }));
|
|
1452
|
+
const hit = list.find((x) => (id && String(x._id) === String(id)) || String(x.conversation?._id || x.conversation) === conversationId);
|
|
1453
|
+
if (hit?.zipUrl) return out(io, flags, hit, () => `Export ready: ${hit.zipUrl}`);
|
|
1454
|
+
if (hit?.status === 'failed') throw new CliError('The export failed. Try again, or contact support.');
|
|
1455
|
+
}
|
|
1456
|
+
throw new CliError('Still preparing after 5 min. It will be emailed; check with: chatta export list');
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
/** Send a message as the API key's owner into a conversation. */
|
|
1460
|
+
async function messages(io, flags, auth, sub, rest) {
|
|
1461
|
+
if (sub === 'tail') return messagesTail(io, flags, auth, rest);
|
|
1462
|
+
if (sub !== 'send') throw new CliError('Usage: chatta messages send <conversationId> <text…> | messages tail <conversationId>', 2);
|
|
1463
|
+
const [conversationId, ...words] = rest;
|
|
1464
|
+
if (!conversationId) throw new CliError('messages send needs <conversationId> <text>', 2);
|
|
1465
|
+
const text = (flags['text-stdin'] ? await io.readStdin() : words.join(' ')).trim();
|
|
1466
|
+
if (!text) throw new CliError('messages send needs some text', 2);
|
|
1467
|
+
const referenceId = `cli-${io.now().getTime().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1468
|
+
const msg = await api(io, auth(), 'POST', '/chats/messages/send', { body: { conversationId, referenceId, message: text } });
|
|
1469
|
+
return out(io, flags, msg, () => `Sent${msg?._id ? ` (${msg._id})` : ''} to ${conversationId}.`);
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// ---------- P-N11: meetings, messages tail, webhooks listen ----------
|
|
1473
|
+
|
|
1474
|
+
const MEETING_STATUSES = ['upcoming', 'live', 'ended', 'all'];
|
|
1475
|
+
const OBJECT_ID = /^[a-f0-9]{24}$/i;
|
|
1476
|
+
const POLL_MS = 2000;
|
|
1477
|
+
const clip = (s, n) => (String(s).length > n ? `${String(s).slice(0, n - 1)}…` : String(s));
|
|
1478
|
+
|
|
1479
|
+
/** "whsec_••••4f2a": only the prefix and last 4 characters ever leave the CLI. */
|
|
1480
|
+
export function maskSecret(v) {
|
|
1481
|
+
const s = String(v || '');
|
|
1482
|
+
if (!s) return '';
|
|
1483
|
+
return `${s.startsWith('whsec_') ? 'whsec_' : ''}••••${s.slice(-4)}`;
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
const ERROR_NUMBER_KEYS = ['statusCode', 'serviceFeeMinor', 'providerFeeMinor', 'totalMinor'];
|
|
1487
|
+
const ERROR_TEXT_KEYS = ['code', 'approvalId'];
|
|
1488
|
+
const TOKEN_RUN = /[A-Za-z0-9+_=-]{32,}/g;
|
|
1489
|
+
|
|
1490
|
+
/** Hides token-like text (hook URLs, lhk_ keys, Bearer values, JWTs, long hex or base64) in a message. */
|
|
1491
|
+
export function scrubText(text) {
|
|
1492
|
+
return String(text ?? '')
|
|
1493
|
+
.replace(/\/hooks\/in\/[^\s/?#"')]+/g, '/hooks/in/[masked]')
|
|
1494
|
+
.replace(/\blhk_[A-Za-z0-9_-]+/g, 'lhk_[masked]')
|
|
1495
|
+
.replace(/\bBearer\s+[^\s"',;]+/gi, 'Bearer [masked]')
|
|
1496
|
+
.replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g, '[masked]')
|
|
1497
|
+
.replace(TOKEN_RUN, (m) => (/[0-9]/.test(m) && /[A-Za-z]/.test(m) ? '[masked]' : m));
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/** What `--json` prints on stderr for a failure: a fixed set of API fields, never the whole response. */
|
|
1501
|
+
export function jsonError(e) {
|
|
1502
|
+
const data = {};
|
|
1503
|
+
for (const k of ERROR_NUMBER_KEYS) if (Number.isFinite(e?.apiData?.[k]) && typeof e.apiData[k] === 'number') data[k] = e.apiData[k];
|
|
1504
|
+
for (const k of ERROR_TEXT_KEYS) if (typeof e?.apiData?.[k] === 'string' && e.apiData[k].length <= 80) data[k] = scrubText(e.apiData[k]);
|
|
1505
|
+
const code = typeof e?.apiCode === 'string' && e.apiCode.length <= 80 ? scrubText(e.apiCode) : undefined;
|
|
1506
|
+
return { error: { message: scrubText(e?.message || e), exitCode: e instanceof CliError ? e.exitCode : 1, ...(code ? { code } : {}), ...(Object.keys(data).length ? { data } : {}) } };
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/** Copy of an API payload with every `secret` field masked (for --json output). */
|
|
1510
|
+
export function maskSecrets(data) {
|
|
1511
|
+
if (Array.isArray(data)) return data.map(maskSecrets);
|
|
1512
|
+
if (data && typeof data === 'object') {
|
|
1513
|
+
return Object.fromEntries(Object.entries(data).map(([k, v]) => [k, k === 'secret' && typeof v === 'string' ? maskSecret(v) : maskSecrets(v)]));
|
|
1514
|
+
}
|
|
1515
|
+
return data;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
const whenOf = (v) => {
|
|
1519
|
+
const d = new Date(v);
|
|
1520
|
+
return Number.isNaN(d.getTime()) ? '' : d.toISOString().replace('.000Z', 'Z');
|
|
1521
|
+
};
|
|
1522
|
+
|
|
1523
|
+
/** `meetings list|schedule|cancel` against the owner-token API (/hops/owner/meetings). */
|
|
1524
|
+
async function meetings(io, flags, auth, sub, rest) {
|
|
1525
|
+
const base = '/hops/owner/meetings';
|
|
1526
|
+
const linkId = () => {
|
|
1527
|
+
if (!flags.link) throw new CliError(`meetings ${sub} needs --link <linkId>`, 2);
|
|
1528
|
+
if (!OBJECT_ID.test(flags.link)) throw new CliError('--link is the 24-character link id (see `chatta links list --json`)', 2);
|
|
1529
|
+
return flags.link;
|
|
1530
|
+
};
|
|
1531
|
+
if (sub === 'list') {
|
|
1532
|
+
const status = flags.status || 'upcoming';
|
|
1533
|
+
if (!MEETING_STATUSES.includes(status)) throw new CliError(`--status must be one of: ${MEETING_STATUSES.join(', ')}`, 2);
|
|
1534
|
+
const link = linkId();
|
|
1535
|
+
const limit = int(flags.limit, 'limit', 1, 100);
|
|
1536
|
+
const data = await ownerApi(io, auth(), 'GET', base, { query: { linkId: link, status, limit: limit && String(limit), nextCursor: flags.cursor } });
|
|
1537
|
+
const rows = listOf(data).map((m) => ({
|
|
1538
|
+
id: m.id || m._id || '-', title: clip(m.title || '', 40), starts: whenOf(m.startAt), min: m.durationMinutes ?? '', status: m.status || '', code: m.code || '',
|
|
1539
|
+
}));
|
|
1540
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'title', 'starts', 'min', 'status', 'code']) : `No ${status === 'all' ? '' : `${status} `}meetings.`) +
|
|
1541
|
+
more(data, `meetings list --link ${link}${status !== 'upcoming' ? ` --status ${status}` : ''}`));
|
|
1542
|
+
}
|
|
1543
|
+
if (sub === 'schedule') {
|
|
1544
|
+
const link = linkId();
|
|
1545
|
+
const title = String(flags.title || '').trim();
|
|
1546
|
+
if (!title) throw new CliError('meetings schedule needs --link <linkId> --title <t> --start <ISO time> --invitees <emails or member ids>', 2);
|
|
1547
|
+
if (title.length > 200) throw new CliError('--title is at most 200 characters', 2);
|
|
1548
|
+
const start = new Date(String(flags.start || ''));
|
|
1549
|
+
if (!flags.start || Number.isNaN(start.getTime())) throw new CliError('--start must be a date and time, e.g. 2026-12-01T15:00:00Z', 2);
|
|
1550
|
+
if (start.getTime() <= io.now().getTime()) throw new CliError('--start must be in the future', 2);
|
|
1551
|
+
const durationMinutes = int(flags.duration, 'duration', 5, 1440) ?? 30;
|
|
1552
|
+
const invitees = csv(flags.invitees) || [];
|
|
1553
|
+
if (!invitees.length) throw new CliError('meetings schedule needs --invitees (at least one email or member id)', 2);
|
|
1554
|
+
if (invitees.length > 70 || invitees.some((x) => x.length > 254 || (x.includes('@') && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(x)))) {
|
|
1555
|
+
throw new CliError('--invitees is up to 70 comma-separated emails or member ids', 2);
|
|
1556
|
+
}
|
|
1557
|
+
if (flags.description && String(flags.description).length > 2000) throw new CliError('--description is at most 2000 characters', 2);
|
|
1558
|
+
if (flags.timezone) {
|
|
1559
|
+
try { new Intl.DateTimeFormat('en', { timeZone: String(flags.timezone) }); } catch { throw new CliError('--timezone must be an IANA zone such as Europe/London', 2); }
|
|
1560
|
+
}
|
|
1561
|
+
const body = { linkId: link, title, startAt: start.toISOString(), durationMinutes, invitees };
|
|
1562
|
+
if (flags.description) body.description = String(flags.description);
|
|
1563
|
+
if (flags['no-admit']) body.requireAdmit = false;
|
|
1564
|
+
if (flags.timezone) body.timezone = String(flags.timezone);
|
|
1565
|
+
// one key per invocation: a retried request replays the first result instead of scheduling twice
|
|
1566
|
+
const key = String(flags['idempotency-key'] || (io.randomId ? io.randomId() : randomUUID()));
|
|
1567
|
+
const m = await ownerApi(io, auth(), 'POST', base, { body, headers: { 'Idempotency-Key': key } });
|
|
1568
|
+
const id = m?.id || m?._id;
|
|
1569
|
+
return out(io, flags, m, () => `Scheduled "${m?.title || title}" for ${whenOf(m?.startAt || start)} (${m?.durationMinutes ?? durationMinutes} min).` +
|
|
1570
|
+
`${id ? `\nMeeting id: ${id}` : ''}${m?.joinUrl ? `\nJoin: ${m.joinUrl}` : ''}` +
|
|
1571
|
+
`${m?.invitedMembers !== undefined || m?.guestsInvited !== undefined ? `\nInvited: ${m.invitedMembers ?? 0} members, ${m.guestsInvited ?? 0} guests` : ''}` +
|
|
1572
|
+
`${m?.occurrences > 1 ? `\nOccurrences: ${m.occurrences}` : ''}`);
|
|
1573
|
+
}
|
|
1574
|
+
if (sub === 'cancel') {
|
|
1575
|
+
const [id] = rest;
|
|
1576
|
+
if (!id) throw new CliError('Usage: chatta meetings cancel <meetingId> [--reason <text>] --yes', 2);
|
|
1577
|
+
if (!flags.yes) throw new CliError('This cancels the meeting and tells the invitees. Add --yes to confirm.', 2);
|
|
1578
|
+
if (flags.reason && String(flags.reason).length > 300) throw new CliError('--reason is at most 300 characters', 2);
|
|
1579
|
+
const r = await ownerApi(io, auth(), 'DELETE', `${base}/${encodeURIComponent(id)}`, { query: { reason: flags.reason ? String(flags.reason) : undefined } });
|
|
1580
|
+
return out(io, flags, r ?? { ok: true, id, status: 'cancelled' }, () => (r?.alreadyCancelled ? `Meeting ${id} was already cancelled.` : `Meeting ${id} cancelled.`));
|
|
1581
|
+
}
|
|
1582
|
+
throw new CliError('Usage: chatta meetings list --link <linkId> | schedule --link <linkId> --title <t> --start <time> --invitees <list> | cancel <meetingId> --yes', 2);
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
/** `--since`: 30s, 10m, 2h, 3d, an ISO time, or "all". */
|
|
1586
|
+
export function parseSince(v, now) {
|
|
1587
|
+
if (v === undefined) return null;
|
|
1588
|
+
if (v === 'all') return new Date(0);
|
|
1589
|
+
const m = /^(\d+)([smhd])$/.exec(String(v));
|
|
1590
|
+
if (m) return new Date(now.getTime() - Number(m[1]) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]]);
|
|
1591
|
+
const d = new Date(String(v));
|
|
1592
|
+
if (Number.isNaN(d.getTime())) throw new CliError('--since is a duration like 10m, 2h, 3d, an ISO time, or "all"', 2);
|
|
1593
|
+
return d;
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
const senderOf = (m) => {
|
|
1597
|
+
const s = m.sender || {};
|
|
1598
|
+
return s.displayName || [s.firstName, s.lastName].filter(Boolean).join(' ') || s.name || s.username || m.senderName || 'unknown';
|
|
1599
|
+
};
|
|
1600
|
+
|
|
1601
|
+
function messageLine(m) {
|
|
1602
|
+
const at = new Date(m.createdAt || m.clientDate || 0);
|
|
1603
|
+
const t = Number.isNaN(at.getTime()) ? '--:--:--' : at.toISOString().slice(11, 19);
|
|
1604
|
+
const files = (m.attachments || []).map((a) => `[${a.type || 'file'}${a.name ? ` ${a.name}` : ''}]`).join(' ');
|
|
1605
|
+
const text = [m.message ?? m.text ?? '', files].filter(Boolean).join(' ').replace(/\s*\n\s*/g, ' ⏎ ');
|
|
1606
|
+
return `[${t}] ${senderOf(m)}: ${text || `(${String(m.messageKind || m.kind || 'message').toLowerCase()})`}`;
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
/** New messages of one conversation, oldest first. The owner route sees everyone's; the API-key route only the key owner's own. */
|
|
1610
|
+
async function fetchFresh(io, a, conversationId, state) {
|
|
1611
|
+
const owner = !!a.ownerToken;
|
|
1612
|
+
const fresh = [];
|
|
1613
|
+
let cursor;
|
|
1614
|
+
for (let page = 0; page < 5; page++) {
|
|
1615
|
+
const query = { chatMessageByConversationIds: conversationId, limit: '50', prevCursor: cursor };
|
|
1616
|
+
const data = await (owner ? ownerApi(io, a, 'GET', '/chats/messages', { query }) : api(io, a, 'GET', '/chats/messages', { query }));
|
|
1617
|
+
const rows = listOf(data);
|
|
1618
|
+
let added = 0;
|
|
1619
|
+
for (const m of rows) {
|
|
1620
|
+
const id = String(m._id || m.id || '');
|
|
1621
|
+
const at = new Date(m.createdAt || m.clientDate || 0);
|
|
1622
|
+
if (!id || state.seen.has(id) || (state.since && at < state.since)) continue;
|
|
1623
|
+
state.seen.add(id);
|
|
1624
|
+
fresh.push(m);
|
|
1625
|
+
added++;
|
|
1626
|
+
}
|
|
1627
|
+
cursor = data?.prevCursor;
|
|
1628
|
+
if (!(rows.length && added === rows.length && cursor)) break;
|
|
1629
|
+
}
|
|
1630
|
+
while (state.seen.size > 5000) state.seen.delete(state.seen.values().next().value);
|
|
1631
|
+
return fresh.sort((x, y) => new Date(x.createdAt || x.clientDate || 0) - new Date(y.createdAt || y.clientDate || 0));
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
/** Poll loop shared by tail and listen: `step()` runs every 2 s; transient failures back off, auth failures end it. */
|
|
1635
|
+
async function pollLoop(io, step) {
|
|
1636
|
+
let failures = 0;
|
|
1637
|
+
while (!io.stopped()) {
|
|
1638
|
+
try {
|
|
1639
|
+
await step();
|
|
1640
|
+
failures = 0;
|
|
1641
|
+
} catch (e) {
|
|
1642
|
+
if (!e?.retryable || ++failures >= 8) throw e;
|
|
1643
|
+
io.err(`chatta: ${e.message} — retrying (${failures}/8)`);
|
|
1644
|
+
}
|
|
1645
|
+
if (io.stopped()) break;
|
|
1646
|
+
await io.sleep(POLL_MS * Math.min(failures + 1, 8));
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
async function messagesTail(io, flags, auth, [conversationId]) {
|
|
1651
|
+
if (!conversationId || !OBJECT_ID.test(conversationId)) throw new CliError('Usage: chatta messages tail <conversationId> [--since 10m] [--once] [--json]', 2);
|
|
1652
|
+
const a = auth();
|
|
1653
|
+
if (!a.ownerToken && !a.apiKey) throw new CliError(`${NO_OWNER} (An API key alone only sees messages sent by the key's owner.)`);
|
|
1654
|
+
if (!a.ownerToken) io.err("chatta: no owner token, so only messages sent by this API key's owner are shown. Run `chatta login --email <you@company.com>` to see everyone.");
|
|
1655
|
+
const now = io.now();
|
|
1656
|
+
const since = parseSince(flags.since, now) || (flags.once ? parseSince('1h', now) : null);
|
|
1657
|
+
const state = { seen: new Set(), since };
|
|
1658
|
+
const show = (m) => io.out(flags.json ? JSON.stringify(m) : messageLine(m));
|
|
1659
|
+
if (!since) {
|
|
1660
|
+
// The first poll only learns what is already there, so old messages are not printed and clock skew cannot hide new ones.
|
|
1661
|
+
await fetchFresh(io, a, conversationId, state);
|
|
1662
|
+
io.err(`Watching ${conversationId} (Ctrl-C to stop)…`);
|
|
1663
|
+
} else {
|
|
1664
|
+
(await fetchFresh(io, a, conversationId, state)).forEach(show);
|
|
1665
|
+
}
|
|
1666
|
+
if (flags.once) return 0;
|
|
1667
|
+
await pollLoop(io, async () => (await fetchFresh(io, a, conversationId, state)).forEach(show));
|
|
1668
|
+
return 0;
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
/** True for localhost, *.localhost, 127.0.0.0/8 and ::1. */
|
|
1672
|
+
export function isLocalHost(hostname) {
|
|
1673
|
+
const h = String(hostname).toLowerCase().replace(/^\[|\]$/g, '');
|
|
1674
|
+
// no *.localhost: a resolver may send it anywhere, and only the literal loopback names are known to stay on this machine
|
|
1675
|
+
return h === 'localhost' || h === '::1' || h === '::ffff:127.0.0.1' || h === '::ffff:7f00:1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
/** Parses --forward; a target that is not local needs --allow-remote and https (deliveries carry message data). */
|
|
1679
|
+
export function forwardTarget(raw, allowRemote) {
|
|
1680
|
+
let u;
|
|
1681
|
+
try { u = new URL(String(raw)); } catch { throw new CliError('--forward must be a URL like http://localhost:3000/hook', 2); }
|
|
1682
|
+
if (!['http:', 'https:'].includes(u.protocol)) throw new CliError('--forward must start with http:// or https://', 2);
|
|
1683
|
+
if (!isLocalHost(u.hostname) && !allowRemote) {
|
|
1684
|
+
throw new CliError(`--forward points to ${u.hostname}, not localhost. Deliveries carry your members' messages; pass --allow-remote if you really mean it.`, 2);
|
|
1685
|
+
}
|
|
1686
|
+
if (!isLocalHost(u.hostname) && u.protocol !== 'https:') {
|
|
1687
|
+
throw new CliError(`--forward ${u.hostname} must use https://: plain http would send your members' messages unencrypted.`, 2);
|
|
1688
|
+
}
|
|
1689
|
+
return u;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/** The webhook secret for `webhooks test` / the legacy header: stdin, then the environment, then --secret (always with a warning). */
|
|
1693
|
+
async function webhookSecretFrom(io, flags) {
|
|
1694
|
+
if (flags.secret) io.err('chatta: warning: --secret is saved in your shell history. Use LIVECHATTA_WEBHOOK_SECRET or --secret-stdin instead.');
|
|
1695
|
+
if (flags['secret-stdin']) return (await io.readStdin()).trim();
|
|
1696
|
+
if (io.env.LIVECHATTA_WEBHOOK_SECRET) return String(io.env.LIVECHATTA_WEBHOOK_SECRET);
|
|
1697
|
+
return flags.secret ? String(flags.secret) : '';
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
async function webhooksListen(io, flags, auth, [id]) {
|
|
1701
|
+
if (!id || !OBJECT_ID.test(id)) throw new CliError('Usage: chatta webhooks listen <webhookId> [--forward http://localhost:3000/hook] [--allow-remote]', 2);
|
|
1702
|
+
if (flags.secret !== undefined) throw new CliError('webhooks listen does not take --secret (it would sit in your shell history). The signature is forwarded as LiveChatta sent it; only --legacy-secret-header needs the secret, from LIVECHATTA_WEBHOOK_SECRET or --secret-stdin.', 2);
|
|
1703
|
+
const legacy = !!flags['legacy-secret-header'];
|
|
1704
|
+
if (legacy && !flags.forward) throw new CliError('--legacy-secret-header only applies together with --forward', 2);
|
|
1705
|
+
if (legacy && flags['allow-remote']) throw new CliError('--legacy-secret-header cannot be combined with --allow-remote: it would send your raw secret off this machine.', 2);
|
|
1706
|
+
const target = flags.forward ? forwardTarget(flags.forward, !!flags['allow-remote']) : null;
|
|
1707
|
+
if (legacy && !isLocalHost(target.hostname)) throw new CliError('--legacy-secret-header only works with a localhost target.', 2);
|
|
1708
|
+
const a = auth();
|
|
1709
|
+
const path = `/chats/webhooks/${encodeURIComponent(id)}`;
|
|
1710
|
+
const hook = await ownerApi(io, a, 'GET', path);
|
|
1711
|
+
const secret = legacy ? (flags['secret-stdin'] ? await webhookSecretFrom(io, flags) : String(io.env.LIVECHATTA_WEBHOOK_SECRET || hook?.secret || '')) : '';
|
|
1712
|
+
if (legacy && !secret) throw new CliError('--legacy-secret-header needs the webhook secret: set LIVECHATTA_WEBHOOK_SECRET or pass --secret-stdin.', 2);
|
|
1713
|
+
const begin = () => ownerApi(io, a, 'POST', `${path}/capture`);
|
|
1714
|
+
const view = await begin();
|
|
1715
|
+
io.err(`Listening to ${hook?.name || hook?.url || id} until ${whenOf(view?.expiresAt)} (renews itself; Ctrl-C to stop).`);
|
|
1716
|
+
if (target) {
|
|
1717
|
+
io.err(`Replaying each delivery to ${target.origin}${target.pathname} with its X-Webhook-Signature${legacy ? ` and the deprecated X-Webhook-Secret ${maskSecret(secret)}` : ' (the secret is not sent)'}.`);
|
|
1718
|
+
if (!isLocalHost(target.hostname)) io.err(`chatta: warning: ${target.hostname} is not local; deliveries carry your members' messages.`);
|
|
1719
|
+
}
|
|
1720
|
+
// start after what is already kept: an old backlog is never replayed
|
|
1721
|
+
let after = Number(view?.lastSeq) || 0;
|
|
1722
|
+
try {
|
|
1723
|
+
await pollLoop(io, async () => {
|
|
1724
|
+
const page = await ownerApi(io, a, 'GET', `${path}/capture`, { query: { after: String(after) } });
|
|
1725
|
+
let stale = 0;
|
|
1726
|
+
const clock = captureClock(page);
|
|
1727
|
+
for (const e of listOf(page)) {
|
|
1728
|
+
after = Math.max(after, Number(e.seq) || 0);
|
|
1729
|
+
if (clock - new Date(e.at).getTime() > WEBHOOK_REPLAY_WINDOW_MS) { stale++; continue; }
|
|
1730
|
+
await showDelivery(io, flags, target, legacy ? secret : '', e);
|
|
1731
|
+
}
|
|
1732
|
+
if (stale) io.err(`Skipped ${stale} deliver${stale === 1 ? 'y' : 'ies'} older than 5 minutes: their signatures would be rejected as replays.`);
|
|
1733
|
+
after = Math.max(after, Number(page?.lastSeq) || 0);
|
|
1734
|
+
const left = page?.expiresAt ? new Date(page.expiresAt).getTime() - io.now().getTime() : 0;
|
|
1735
|
+
if (!page?.active || left < 300_000) await begin();
|
|
1736
|
+
});
|
|
1737
|
+
} finally {
|
|
1738
|
+
await ownerApi(io, a, 'DELETE', `${path}/capture`).catch(() => undefined);
|
|
1739
|
+
io.err('Stopped listening.');
|
|
1740
|
+
}
|
|
1741
|
+
return 0;
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
/** Receivers reject a signature timestamp older than this, so older captured deliveries are not replayed. */
|
|
1745
|
+
export const WEBHOOK_REPLAY_WINDOW_MS = 300_000;
|
|
1746
|
+
|
|
1747
|
+
/** "Now" for ageing entries: the server's clock (`at` is stamped by it), else the newest `at` seen, never this machine's clock. */
|
|
1748
|
+
export function captureClock(page) {
|
|
1749
|
+
const server = Date.parse(page?.serverTime);
|
|
1750
|
+
if (Number.isFinite(server)) return server;
|
|
1751
|
+
const times = listOf(page).map((e) => Date.parse(e.at)).filter(Number.isFinite);
|
|
1752
|
+
return times.length ? Math.max(...times) : 0;
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
async function showDelivery(io, flags, target, legacySecret, e) {
|
|
1756
|
+
const head = `#${e.seq} ${e.event} attempt ${e.attempt}`;
|
|
1757
|
+
if (e.truncated || !e.body) {
|
|
1758
|
+
io.out(flags.json ? JSON.stringify({ seq: e.seq, event: e.event, skipped: 'payload too large' }) : `${head} — payload too large to keep, not replayed`);
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
if (!target) {
|
|
1762
|
+
io.out(flags.json ? JSON.stringify({ seq: e.seq, event: e.event, attempt: e.attempt, body: JSON.parse(e.body) }) : `${head}\n${prettyJson(e.body)}`);
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
const headers = { 'Content-Type': 'application/json', 'X-Webhook-Event': e.event, 'X-Webhook-Attempt': String(e.attempt), 'X-Webhook-Replay': 'chatta-cli' };
|
|
1766
|
+
let deliveryId;
|
|
1767
|
+
try { deliveryId = JSON.parse(e.body)?.id; } catch { deliveryId = undefined; }
|
|
1768
|
+
if (typeof deliveryId === 'string') headers['X-Webhook-Id'] = deliveryId;
|
|
1769
|
+
if (e.signature) headers['X-Webhook-Signature'] = e.signature;
|
|
1770
|
+
if (legacySecret) headers['X-Webhook-Secret'] = legacySecret;
|
|
1771
|
+
const started = Date.now();
|
|
1772
|
+
let result;
|
|
1773
|
+
try {
|
|
1774
|
+
const res = await io.fetch(target.href, { method: 'POST', headers, body: e.body, redirect: 'manual', signal: AbortSignal.timeout(10_000) });
|
|
1775
|
+
result = { status: res.status, ms: Date.now() - started };
|
|
1776
|
+
} catch (err) {
|
|
1777
|
+
result = { error: err?.cause?.code || err?.message || String(err) };
|
|
1778
|
+
}
|
|
1779
|
+
io.out(flags.json ? JSON.stringify({ seq: e.seq, event: e.event, attempt: e.attempt, forwarded: result }) : result.error
|
|
1780
|
+
? `${head} → failed: ${result.error} (is your server running at ${target.host}?)`
|
|
1781
|
+
: `${head} → HTTP ${result.status} in ${result.ms} ms`);
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
function prettyJson(text) {
|
|
1785
|
+
try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
/** One-shot health check: reachability, clock, API key, owner token, webhooks. Exit 1 if anything fails. */
|
|
1789
|
+
async function doctor(io, flags, auth) {
|
|
1790
|
+
const a = auth();
|
|
1791
|
+
const checks = [];
|
|
1792
|
+
const add = (name, ok, detail) => checks.push({ check: name, result: ok === null ? 'skip' : ok ? 'ok' : 'FAIL', detail });
|
|
1793
|
+
let res;
|
|
1794
|
+
try {
|
|
1795
|
+
const t0 = Date.now();
|
|
1796
|
+
res = await io.fetch(`${a.baseUrl}/api/v1/external/version`, { method: 'GET' });
|
|
1797
|
+
add('base URL', res.ok, `${a.baseUrl} → HTTP ${res.status} in ${Date.now() - t0} ms`);
|
|
1798
|
+
} catch (e) {
|
|
1799
|
+
add('base URL', false, `${a.baseUrl} unreachable: ${e?.message || e}`);
|
|
1800
|
+
}
|
|
1801
|
+
const date = res?.headers?.get?.('date');
|
|
1802
|
+
if (date) {
|
|
1803
|
+
const skew = Math.round((io.now().getTime() - new Date(date).getTime()) / 1000);
|
|
1804
|
+
add('clock', Math.abs(skew) <= 120, `${skew >= 0 ? '+' : ''}${skew}s vs server (webhook signatures allow ±5 min)`);
|
|
1805
|
+
} else add('clock', null, 'server sent no Date header');
|
|
1806
|
+
if (a.apiKey) {
|
|
1807
|
+
try { await api(io, a, 'GET', '/chat-links', { query: { limit: '1' } }); add('API key', true, maskKey(a.apiKey)); }
|
|
1808
|
+
catch (e) { add('API key', false, e.message); }
|
|
1809
|
+
} else add('API key', null, 'none saved (chatta login --api-key)');
|
|
1810
|
+
if (a.ownerToken) {
|
|
1811
|
+
try { await ownerApi(io, a, 'GET', '/users/me'); add('owner token', true, maskKey(a.ownerToken)); }
|
|
1812
|
+
catch (e) { add('owner token', false, e.message); }
|
|
1813
|
+
} else add('owner token', null, 'none saved (chatta login --email)');
|
|
1814
|
+
if (a.apiKey) {
|
|
1815
|
+
try {
|
|
1816
|
+
const hooks = listOf(await api(io, a, 'GET', '/chats/webhooks'));
|
|
1817
|
+
const off = hooks.filter((w) => w.status && w.status !== 'active');
|
|
1818
|
+
add('webhooks', off.length === 0, hooks.length ? `${hooks.length} set up${off.length ? `, ${off.length} not active: ${off.map((w) => w.url).join(', ')}` : ', all active'}` : 'none set up');
|
|
1819
|
+
} catch (e) { add('webhooks', false, e.message); }
|
|
1820
|
+
}
|
|
1821
|
+
const failed = checks.some((c) => c.result === 'FAIL');
|
|
1822
|
+
io.out(flags.json ? JSON.stringify({ ok: !failed, checks }, null, 2) : table(checks, ['check', 'result', 'detail']));
|
|
1823
|
+
return failed ? 1 : 0;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
const COMMANDS = ['login', 'logout', 'whoami', 'profiles', 'doctor', 'links', 'conversations', 'members', 'export', 'messages', 'meetings', 'csat', 'teams', 'plan', 'store', 'gifts', 'gifs', 'shared', 'hooks', 'billing', 'keys', 'security', 'liveflex', 'embed', 'webhooks', 'completion'];
|
|
1827
|
+
const SUBCOMMANDS = {
|
|
1828
|
+
links: ['list', 'create', 'code', 'modes', 'who-can-join', 'app-origins', 'domain', 'theme', 'overview', 'wipe', 'mode', 'channels', 'join-policy', 'requests'],
|
|
1829
|
+
members: ['list', 'export', 'block', 'unblock', 'revoke-invite'], csat: ['list', 'summary'], messages: ['send', 'tail'], meetings: ['list', 'schedule', 'cancel'], export: ['list'], keys: ['list', 'create', 'update', 'rotate', 'revoke', 'usage'],
|
|
1830
|
+
hooks: ['list', 'create', 'rename', 'regenerate', 'revoke', 'send'],
|
|
1831
|
+
webhooks: ['list', 'deliveries', 'retry', 'rotate-secret', 'test', 'listen'], billing: ['storage', 'renewal', 'renew', 'pending', 'storage-renew', 'trial'],
|
|
1832
|
+
security: ['staff-access', 'grant'], liveflex: ['history', 'fund', 'send', 'withdraw', 'request', 'split', 'standing', 'pots', 'refund', 'paylink', 'receipt', 'statement'], teams: ['list', 'create'], plan: ['request', 'status'],
|
|
1833
|
+
gifts: ['catalog', 'earnings'], gifs: ['search', 'trending'], shared: SHARED_SUBS, store: ['list'], embed: ['snippet'], conversations: ['mode', 'visibility'], completion: ['bash', 'zsh', 'fish'],
|
|
1834
|
+
};
|
|
1835
|
+
|
|
1836
|
+
/** Shell tab-completion script for bash, zsh or fish. */
|
|
1837
|
+
export function completionScript(shell) {
|
|
1838
|
+
const subs = Object.entries(SUBCOMMANDS);
|
|
1839
|
+
if (shell === 'bash') {
|
|
1840
|
+
return `# chatta bash completion — add to ~/.bashrc: eval "$(chatta completion bash)"
|
|
1841
|
+
_chatta() {
|
|
1842
|
+
local cur="\${COMP_WORDS[COMP_CWORD]}" prev="\${COMP_WORDS[1]}"
|
|
1843
|
+
if [ "$COMP_CWORD" -eq 1 ]; then COMPREPLY=( $(compgen -W "${COMMANDS.join(' ')}" -- "$cur") ); return; fi
|
|
1844
|
+
if [ "$COMP_CWORD" -eq 2 ]; then
|
|
1845
|
+
case "$prev" in
|
|
1846
|
+
${subs.map(([c, l]) => ` ${c}) COMPREPLY=( $(compgen -W "${l.join(' ')}" -- "$cur") );;`).join('\n')}
|
|
1847
|
+
esac
|
|
1848
|
+
fi
|
|
1849
|
+
}
|
|
1850
|
+
complete -F _chatta chatta
|
|
1851
|
+
`;
|
|
1852
|
+
}
|
|
1853
|
+
if (shell === 'zsh') {
|
|
1854
|
+
return `#compdef chatta
|
|
1855
|
+
# chatta zsh completion — add to ~/.zshrc: eval "$(chatta completion zsh)"
|
|
1856
|
+
_chatta() {
|
|
1857
|
+
if (( CURRENT == 2 )); then compadd ${COMMANDS.join(' ')}; return; fi
|
|
1858
|
+
if (( CURRENT == 3 )); then
|
|
1859
|
+
case $words[2] in
|
|
1860
|
+
${subs.map(([c, l]) => ` ${c}) compadd ${l.join(' ')};;`).join('\n')}
|
|
1861
|
+
esac
|
|
1862
|
+
fi
|
|
1863
|
+
}
|
|
1864
|
+
compdef _chatta chatta
|
|
1865
|
+
`;
|
|
1866
|
+
}
|
|
1867
|
+
if (shell === 'fish') {
|
|
1868
|
+
return `# chatta fish completion — save as ~/.config/fish/completions/chatta.fish
|
|
1869
|
+
complete -c chatta -f -n "__fish_use_subcommand" -a "${COMMANDS.join(' ')}"
|
|
1870
|
+
${subs.map(([c, l]) => `complete -c chatta -f -n "__fish_seen_subcommand_from ${c}" -a "${l.join(' ')}"`).join('\n')}
|
|
1871
|
+
`;
|
|
1872
|
+
}
|
|
1873
|
+
throw new CliError('Usage: chatta completion bash|zsh|fish', 2);
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
function profiles(io, flags) {
|
|
1877
|
+
const dir = join(dirname(configPath(io.env, '')), 'profiles');
|
|
1878
|
+
let names = [];
|
|
1879
|
+
try { names = readdirSync(dir).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch { names = []; }
|
|
1880
|
+
const current = flags.profile || io.env.LIVECHATTA_PROFILE || 'default';
|
|
1881
|
+
const rows = ['default', ...names].map((n) => {
|
|
1882
|
+
const c = readConfig(configPath(io.env, n === 'default' ? '' : n));
|
|
1883
|
+
return { profile: n === current ? `${n} *` : n, 'base url': c.baseUrl || DEFAULT_BASE_URL, 'api key': maskKey(c.apiKey), owner: maskKey(c.ownerToken) };
|
|
1884
|
+
});
|
|
1885
|
+
return out(io, flags, rows, () => `${table(rows, ['profile', 'base url', 'api key', 'owner'])}\nUse one: chatta <command> --profile <name> (or LIVECHATTA_PROFILE).`);
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
async function run(argv, io) {
|
|
1889
|
+
const { flags, positional } = parseArgs(argv);
|
|
1890
|
+
const [cmd, sub, ...rest] = positional;
|
|
1891
|
+
if (flags.version) {
|
|
1892
|
+
io.out(io.version);
|
|
1893
|
+
return 0;
|
|
1894
|
+
}
|
|
1895
|
+
if (!cmd || flags.help || cmd === 'help') {
|
|
1896
|
+
io.out(HELP);
|
|
1897
|
+
return cmd || flags.help ? 0 : 2;
|
|
1898
|
+
}
|
|
1899
|
+
const path = configPath(io.env, flags.profile);
|
|
1900
|
+
const cfg = readConfig(path);
|
|
1901
|
+
if (cmd === 'liveflex' || cmd === 'shared') await secretsFromStdin(io, flags);
|
|
1902
|
+
const auth = () => resolveAuth(flags, io.env, cfg);
|
|
1903
|
+
|
|
1904
|
+
if (cmd === 'login' && (flags.email || flags.totp || flags['owner-token'] || flags['owner-token-stdin'])) {
|
|
1905
|
+
return ownerLogin(io, flags, cfg, path);
|
|
1906
|
+
}
|
|
1907
|
+
if (cmd === 'login') {
|
|
1908
|
+
let apiKey = flags['api-key'] || io.env.LIVECHATTA_API_KEY;
|
|
1909
|
+
if (flags['api-key-stdin']) apiKey = (await io.readStdin()).trim();
|
|
1910
|
+
if (!apiKey) throw new CliError('login needs --api-key <key>, --api-key-stdin or LIVECHATTA_API_KEY', 2);
|
|
1911
|
+
const a = { apiKey, baseUrl: cleanBase(flags['base-url'] || io.env.LIVECHATTA_BASE_URL || cfg.baseUrl) };
|
|
1912
|
+
await api(io, a, 'GET', '/chat-links', { query: { limit: '1' } });
|
|
1913
|
+
writeConfig(path, { ...cfg, apiKey: a.apiKey, baseUrl: a.baseUrl });
|
|
1914
|
+
io.out(`Logged in to ${a.baseUrl} with ${maskKey(a.apiKey)}. Saved to ${path}`);
|
|
1915
|
+
return 0;
|
|
1916
|
+
}
|
|
1917
|
+
if (cmd === 'logout') {
|
|
1918
|
+
if (existsSync(path)) rmSync(path);
|
|
1919
|
+
io.out('Logged out.');
|
|
1920
|
+
return 0;
|
|
1921
|
+
}
|
|
1922
|
+
if (cmd === 'whoami') {
|
|
1923
|
+
const a = auth();
|
|
1924
|
+
io.out(`profile ${flags.profile || io.env.LIVECHATTA_PROFILE || 'default'}\nbase URL ${a.baseUrl}\nAPI key ${maskKey(a.apiKey)}\nowner ${maskKey(a.ownerToken)}\nconfig ${path}`);
|
|
1925
|
+
return a.apiKey || a.ownerToken ? 0 : 1;
|
|
1926
|
+
}
|
|
1927
|
+
if (cmd === 'completion') return io.out(completionScript(sub).trimEnd()), 0;
|
|
1928
|
+
if (cmd === 'profiles') return profiles(io, flags);
|
|
1929
|
+
if (cmd === 'doctor') return doctor(io, flags, auth);
|
|
1930
|
+
if (cmd === 'members') return members(io, flags, auth, sub, rest);
|
|
1931
|
+
if (cmd === 'export') return exportCmd(io, flags, auth, [sub, ...rest]);
|
|
1932
|
+
if (cmd === 'messages') return messages(io, flags, auth, sub, rest);
|
|
1933
|
+
if (cmd === 'links' && sub === 'mode') return linksMode(io, flags, auth, rest);
|
|
1934
|
+
if (cmd === 'links' && sub === 'code') return linksCode(io, flags, auth, rest);
|
|
1935
|
+
if (cmd === 'links' && sub === 'modes') return linksModes(io, flags, auth);
|
|
1936
|
+
if (cmd === 'links' && sub === 'who-can-join') return linksWhoCanJoin(io, flags, auth, rest);
|
|
1937
|
+
if (cmd === 'links' && sub === 'app-origins') return linksAppOrigins(io, flags, auth, rest);
|
|
1938
|
+
if (cmd === 'links' && sub === 'domain') return linksDomain(io, flags, auth, rest);
|
|
1939
|
+
if (cmd === 'links' && sub === 'theme') return linksTheme(io, flags, auth, rest);
|
|
1940
|
+
if (cmd === 'links' && sub === 'overview') return linksOverview(io, flags, auth, rest);
|
|
1941
|
+
if (cmd === 'links' && sub === 'wipe') return linksWipe(io, flags, auth, rest);
|
|
1942
|
+
if (cmd === 'keys') return keys(io, flags, auth, sub, rest);
|
|
1943
|
+
if (cmd === 'links' && sub === 'join-policy') return linksJoinPolicy(io, flags, auth, rest);
|
|
1944
|
+
if (cmd === 'links' && sub === 'requests') return linksRequests(io, flags, auth, rest);
|
|
1945
|
+
if (cmd === 'links' && sub === 'channels') {
|
|
1946
|
+
if (!rest[0]) throw new CliError('links channels needs a link code', 2);
|
|
1947
|
+
const p = await publicApi(io, auth(), 'GET', `/in/${encodeURIComponent(rest[0])}/channels`, { base: 'root' });
|
|
1948
|
+
const rows = (p?.channels || []).map((c) => ({
|
|
1949
|
+
channel: c.name, category: c.category || '', mode: c.mode, members: c.members, live: c.live ? 'live' : '',
|
|
1950
|
+
}));
|
|
1951
|
+
return out(io, flags, p, () => `${p?.members ?? 0} members · ${p?.online ?? 0} online\n` +
|
|
1952
|
+
(rows.length ? table(rows, ['channel', 'category', 'mode', 'members', 'live']) : 'No public channels.'));
|
|
1953
|
+
}
|
|
1954
|
+
if (cmd === 'webhooks' && ['deliveries', 'retry', 'rotate-secret'].includes(sub)) return webhookOwner(io, flags, auth, sub, rest);
|
|
1955
|
+
if (cmd === 'webhooks' && sub === 'listen') return webhooksListen(io, flags, auth, rest);
|
|
1956
|
+
if (cmd === 'meetings') return meetings(io, flags, auth, sub, rest);
|
|
1957
|
+
if ((cmd === 'conversations' || cmd === 'conversation') && sub === 'mode') return conversationsMode(io, flags, auth, rest);
|
|
1958
|
+
if ((cmd === 'conversations' || cmd === 'conversation') && sub === 'visibility') return conversationsVisibility(io, flags, auth, rest);
|
|
1959
|
+
if (cmd === 'teams') return teams(io, flags, auth, sub);
|
|
1960
|
+
if (cmd === 'plan') return plan(io, flags, auth, sub);
|
|
1961
|
+
if (cmd === 'gifs') return gifs(io, flags, auth, sub, rest);
|
|
1962
|
+
if (cmd === 'csat') return csat(io, flags, auth, sub);
|
|
1963
|
+
if (cmd === 'shared') return shared(io, flags, auth, sub, rest);
|
|
1964
|
+
if (cmd === 'hooks') return hooks(io, flags, auth, sub, rest);
|
|
1965
|
+
if (cmd === 'store' && sub === 'list') {
|
|
1966
|
+
const data = await publicApi(io, auth(), 'GET', '/subscriptions/features');
|
|
1967
|
+
const rows = listOf(data).map((f) => ({
|
|
1968
|
+
id: f._id, name: f.name, kind: f.category === 'AI_CREDITS' ? 'AI credits' : f.category === 'STORAGE' ? 'storage' : 'add-on',
|
|
1969
|
+
'per day': money(f.pricePerDay), limit: f.usageLimit ? f.usageLimit : 'unlimited',
|
|
1970
|
+
}));
|
|
1971
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['id', 'name', 'kind', 'per day', 'limit']) : 'The store is empty.'));
|
|
1972
|
+
}
|
|
1973
|
+
if (cmd === 'gifts' && sub === 'catalog') {
|
|
1974
|
+
const data = await ownerApi(io, auth(), 'GET', '/gifts/catalog');
|
|
1975
|
+
const rows = listOf(data).map((g) => ({
|
|
1976
|
+
key: g.key, gift: `${g.emoji || ''} ${g.name || ''}`.trim(), price: minor(g.priceMinor, g.currency),
|
|
1977
|
+
}));
|
|
1978
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['key', 'gift', 'price']) : 'No gifts.'));
|
|
1979
|
+
}
|
|
1980
|
+
if (cmd === 'gifts' && sub === 'earnings') {
|
|
1981
|
+
const data = await ownerApi(io, auth(), 'GET', '/gifts/owner', { query: pageQuery(flags) });
|
|
1982
|
+
const t = data?.totals || {};
|
|
1983
|
+
const rows = listOf(data).map((g) => ({
|
|
1984
|
+
paid: g.paidAt, gift: `${g.emoji || ''} ${g.name || ''}`.trim(), from: g.senderName, to: g.recipientName,
|
|
1985
|
+
amount: minor(g.amountMinor, g.currency), fee: minor(g.feeMinor, g.currency), net: minor(g.netMinor, g.currency),
|
|
1986
|
+
}));
|
|
1987
|
+
return out(io, flags, data, () => `${t.count ?? 0} gifts · gross ${minor(t.grossMinor, t.currency)} · fee ${minor(t.feeMinor, t.currency)} · net ${minor(t.netMinor, t.currency)}\n` +
|
|
1988
|
+
(rows.length ? table(rows, ['paid', 'gift', 'from', 'to', 'amount', 'fee', 'net']) : 'No paid gifts yet.') + more(data, 'gifts earnings'));
|
|
1989
|
+
}
|
|
1990
|
+
if (cmd === 'billing') return billing(io, flags, auth, sub, rest);
|
|
1991
|
+
if (cmd === 'security' && sub === 'grant') return securityGrant(io, flags, auth, rest);
|
|
1992
|
+
if (cmd === 'liveflex') return liveflex(io, flags, auth, sub, rest);
|
|
1993
|
+
if (cmd === 'security' && sub === 'staff-access') {
|
|
1994
|
+
const data = await ownerApi(io, auth(), 'GET', '/staff-access', { query: pageQuery(flags) });
|
|
1995
|
+
const rows = listOf(data).map((r) => ({
|
|
1996
|
+
started: r.startedAt, staff: r.staffName, mode: r.mode, status: r.status, minutes: Math.round(Number(r.durationSec || 0) / 60),
|
|
1997
|
+
actions: (r.actions || []).length, reason: r.reason, where: r.where,
|
|
1998
|
+
}));
|
|
1999
|
+
return out(io, flags, data, () => (rows.length ? table(rows, ['started', 'staff', 'mode', 'status', 'minutes', 'actions', 'reason', 'where'])
|
|
2000
|
+
: 'LiveChatta staff have not accessed this account.') + more(data, 'security staff-access'));
|
|
2001
|
+
}
|
|
2002
|
+
if (cmd === 'links' && sub === 'list') {
|
|
2003
|
+
const limit = flags.limit || '20';
|
|
2004
|
+
const data = await api(io, auth(), 'GET', '/chat-links', { query: { chatLinkSearch: flags.search, limit, nextCursor: flags.cursor } });
|
|
2005
|
+
if (flags.json) return io.out(JSON.stringify(data, null, 2)), 0;
|
|
2006
|
+
const rows = listOf(data).map((l) => ({ code: l.code, name: l.name, status: l.status, type: l.conversationType || l.linkType || '', visitors: l.totalVisitors ?? '' }));
|
|
2007
|
+
io.out(rows.length ? table(rows, ['code', 'name', 'status', 'type', 'visitors']) : 'No chat links.');
|
|
2008
|
+
if (data?.nextCursor) io.out(`\nMore: chatta links list --cursor ${data.nextCursor}`);
|
|
2009
|
+
return 0;
|
|
2010
|
+
}
|
|
2011
|
+
if (cmd === 'links' && sub === 'create') {
|
|
2012
|
+
const name = flags.name;
|
|
2013
|
+
if (!name || name.length < 3 || name.length > 50) throw new CliError('links create needs --name (3–50 characters)', 2);
|
|
2014
|
+
const type = flags.type ? String(flags.type).toUpperCase() : undefined;
|
|
2015
|
+
if (type && !['SINGLE', 'GROUP', 'CHANNEL'].includes(type)) throw new CliError('--type must be SINGLE, GROUP or CHANNEL', 2);
|
|
2016
|
+
if (flags.mode && !LINK_MODES.includes(flags.mode)) throw new CliError(`Unknown link mode "${flags.mode}". One of: ${LINK_MODES.join(', ')}`, 2);
|
|
2017
|
+
const body = { name, code: flags.code, caption: flags.caption, conversationType: type, welcomeMessage: flags.welcome, mode: flags.mode };
|
|
2018
|
+
Object.keys(body).forEach((k) => body[k] === undefined && delete body[k]);
|
|
2019
|
+
const link = await api(io, auth(), 'POST', '/chat-links', { body });
|
|
2020
|
+
if (flags.json) return io.out(JSON.stringify(link, null, 2)), 0;
|
|
2021
|
+
io.out(`Created ${link?.name || name}${link?.code ? ` (code ${link.code})` : ''}${link?.mode ? `, mode ${link.mode}` : ''}.`);
|
|
2022
|
+
if (link?.modeResult?.applied === false) io.out(`Warning: ${link.modeResult.warning || 'The mode preset did not apply.'}\nRetry: chatta links mode set ${link._id} ${flags.mode} --apply-defaults`);
|
|
2023
|
+
else if (link?.modeResult?.created?.length) io.out(`Created for you: ${link.modeResult.created.join(', ')}`);
|
|
2024
|
+
if (link?.code) io.out(`Embed it: chatta embed snippet --link ${link.code}`);
|
|
2025
|
+
return 0;
|
|
2026
|
+
}
|
|
2027
|
+
if (cmd === 'embed' && sub === 'snippet') {
|
|
2028
|
+
io.out(embedSnippet(flags, auth().baseUrl, io.version).trimEnd());
|
|
2029
|
+
return 0;
|
|
2030
|
+
}
|
|
2031
|
+
if (cmd === 'webhooks' && sub === 'list') {
|
|
2032
|
+
const data = await api(io, auth(), 'GET', '/chats/webhooks');
|
|
2033
|
+
if (flags.json) return io.out(JSON.stringify(maskSecrets(data), null, 2)), 0;
|
|
2034
|
+
const rows = listOf(data).map((w) => ({ id: w._id, url: w.url, status: w.status, events: (w.events || []).length }));
|
|
2035
|
+
io.out(rows.length ? table(rows, ['id', 'url', 'status', 'events']) : 'No webhooks.');
|
|
2036
|
+
return 0;
|
|
2037
|
+
}
|
|
2038
|
+
if (cmd === 'webhooks' && sub === 'test') return webhookTest(io, flags, rest);
|
|
2039
|
+
throw new CliError(`Unknown command "${positional.join(' ')}". Run chatta --help.`, 2);
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
function pkgVersion() {
|
|
2043
|
+
try {
|
|
2044
|
+
return JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
|
|
2045
|
+
} catch {
|
|
2046
|
+
return 'latest';
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
async function readAll(stream) {
|
|
2051
|
+
let s = '';
|
|
2052
|
+
for await (const chunk of stream) s += chunk;
|
|
2053
|
+
return s;
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
/** Runs the CLI; returns the exit code (0 ok, 1 failure, 2 usage). */
|
|
2057
|
+
export async function main(argv, io = {}) {
|
|
2058
|
+
const ctx = {
|
|
2059
|
+
env: io.env || process.env,
|
|
2060
|
+
fetch: io.fetch || globalThis.fetch,
|
|
2061
|
+
out: io.out || ((s) => process.stdout.write(`${s}\n`)),
|
|
2062
|
+
err: io.err || ((s) => process.stderr.write(`${s}\n`)),
|
|
2063
|
+
now: io.now || (() => new Date()),
|
|
2064
|
+
readStdin: io.readStdin || (() => readAll(process.stdin)),
|
|
2065
|
+
version: io.version || pkgVersion(),
|
|
2066
|
+
stopped: io.stopped || (() => false),
|
|
2067
|
+
randomId: io.randomId,
|
|
2068
|
+
};
|
|
2069
|
+
let onSigint;
|
|
2070
|
+
if (!io.sleep) {
|
|
2071
|
+
// Ctrl-C ends long-running commands (tail, listen) cleanly, waking any sleep at once.
|
|
2072
|
+
const wake = new Set();
|
|
2073
|
+
let stop = false;
|
|
2074
|
+
ctx.stopped = () => stop;
|
|
2075
|
+
ctx.sleep = (ms) => new Promise((r) => { const t = setTimeout(() => { wake.delete(done); r(); }, ms); const done = () => { clearTimeout(t); r(); }; wake.add(done); });
|
|
2076
|
+
onSigint = () => { stop = true; wake.forEach((w) => w()); };
|
|
2077
|
+
process.once('SIGINT', onSigint);
|
|
2078
|
+
} else ctx.sleep = io.sleep;
|
|
2079
|
+
try {
|
|
2080
|
+
return await run(argv, ctx);
|
|
2081
|
+
} catch (e) {
|
|
2082
|
+
if (argv.includes('--json')) ctx.err(JSON.stringify(jsonError(e)));
|
|
2083
|
+
else ctx.err(`chatta: ${e?.message || e}`);
|
|
2084
|
+
return e instanceof CliError ? e.exitCode : 1;
|
|
2085
|
+
} finally {
|
|
2086
|
+
if (onSigint) process.removeListener('SIGINT', onSigint);
|
|
2087
|
+
}
|
|
2088
|
+
}
|