@token-dashboard/typeless-usage-uploader 0.1.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/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # Typeless 用量上报
2
+
3
+ 独立的 Typeless 去内容化用量采集与上报 CLI。
4
+
5
+ 默认读取:
6
+
7
+ - `~/Library/Application Support/Typeless/typeless.db`
8
+ - `~/Library/Application Support/Typeless/app-storage.json`
9
+
10
+ 采集端只上传明细记录的时间、字符长度和 Typeless 账号身份,不上传 `refined_text`、音频、窗口标题、URL、debug 信息、referral code 或公钥。
11
+
12
+ ```bash
13
+ typeless-usage-uploader init --backend-url http://localhost:8086
14
+ typeless-usage-uploader status
15
+ typeless-usage-uploader logs
16
+ ```
17
+
18
+ 开发环境:
19
+
20
+ ```bash
21
+ cd typeless-collector
22
+ npm test
23
+ npm run build
24
+ npm run init
25
+ ```
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ if(!process.env.NODE_NO_WARNINGS){process.env.NODE_NO_WARNINGS='1'}
3
+ process.emitWarning=()=>{};
4
+ const{main}=await import('../cli.js');
5
+ await main(process.argv.slice(2));
package/dist/cli.js ADDED
@@ -0,0 +1,373 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { TypelessUsageUploader } from './collector.js';
5
+ import {
6
+ CLI_NAME,
7
+ DEFAULT_BACKEND_URL,
8
+ DEFAULT_CONFIG_FILE,
9
+ PRODUCT_NAME,
10
+ } from './constants.js';
11
+ import { LaunchdServiceManager } from './launchd.js';
12
+ import { formatStatusOutput, mergeRuntimeConfig, saveRuntimeConfig } from './runtime-config.js';
13
+ import { StateDb } from './state-db.js';
14
+
15
+ const HELP_TEXT = `${PRODUCT_NAME}
16
+
17
+ Usage:
18
+ ${CLI_NAME} init [--backend-url <url>] [--interval 300] [--yes]
19
+ ${CLI_NAME} clear [--yes]
20
+ ${CLI_NAME} start
21
+ ${CLI_NAME} stop
22
+ ${CLI_NAME} restart
23
+ ${CLI_NAME} status
24
+ ${CLI_NAME} logs [--lines 100]
25
+ ${CLI_NAME} uninstall
26
+
27
+ Common options:
28
+ --config-file <path> Runtime config path. Default: ${DEFAULT_CONFIG_FILE}
29
+ --backend-url <url> Dashboard backend URL
30
+ --interval <seconds> Scan interval in seconds
31
+ --typeless-db <path> Typeless typeless.db path
32
+ --typeless-storage <path> Typeless app-storage.json path
33
+ --state-db <path> Local SQLite state DB path
34
+ --yes Skip interactive prompts
35
+ --lines <n> Number of log lines for service logs
36
+ -h, --help Show help
37
+ `;
38
+
39
+ class CliOperationalError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = 'CliOperationalError';
43
+ }
44
+ }
45
+
46
+ export const cliDeps = {
47
+ createUploader(runtime) {
48
+ return new TypelessUsageUploader({
49
+ stateDbPath: runtime.stateDbPath,
50
+ backendUrl: runtime.backendUrl,
51
+ typelessDbPath: runtime.typelessDbPath,
52
+ typelessStoragePath: runtime.typelessStoragePath,
53
+ intervalSeconds: runtime.intervalSeconds,
54
+ persistentCollectorIdPath: runtime.persistentCollectorIdPath,
55
+ });
56
+ },
57
+ createServiceManager(runtime) {
58
+ return new LaunchdServiceManager(runtime);
59
+ },
60
+ };
61
+
62
+ export function parseCliArgs(argv) {
63
+ const options = {
64
+ configFile: DEFAULT_CONFIG_FILE,
65
+ interval: undefined,
66
+ yes: false,
67
+ lines: 100,
68
+ };
69
+ const positionals = [];
70
+
71
+ for (let index = 0; index < argv.length; index += 1) {
72
+ const token = argv[index];
73
+ if (!token.startsWith('-')) {
74
+ positionals.push(token);
75
+ continue;
76
+ }
77
+ if (token === '-h' || token === '--help') {
78
+ options.help = true;
79
+ continue;
80
+ }
81
+ if (token === '--yes') {
82
+ options.yes = true;
83
+ continue;
84
+ }
85
+
86
+ const [key, inlineValue] = token.split('=', 2);
87
+ const takesValue = new Set([
88
+ '--config-file',
89
+ '--backend-url',
90
+ '--interval',
91
+ '--typeless-db',
92
+ '--typeless-storage',
93
+ '--state-db',
94
+ '--lines',
95
+ ]);
96
+ if (!takesValue.has(key)) throw new Error(`Unknown argument: ${token}`);
97
+ const value = inlineValue ?? argv[++index];
98
+ if (value == null || value.startsWith('-')) throw new Error(`Missing value for ${key}`);
99
+ assignOption(options, key, value);
100
+ }
101
+
102
+ return {
103
+ command: positionals[0] ?? null,
104
+ subcommand: positionals[1] ?? null,
105
+ extraPositionals: positionals.slice(2),
106
+ options,
107
+ };
108
+ }
109
+
110
+ function assignOption(options, key, value) {
111
+ switch (key) {
112
+ case '--config-file':
113
+ options.configFile = value;
114
+ break;
115
+ case '--backend-url':
116
+ options.backendUrl = value;
117
+ break;
118
+ case '--interval':
119
+ options.interval = parsePositiveInt(value, '--interval');
120
+ break;
121
+ case '--typeless-db':
122
+ options.typelessDbPath = value;
123
+ break;
124
+ case '--typeless-storage':
125
+ options.typelessStoragePath = value;
126
+ break;
127
+ case '--state-db':
128
+ options.stateDbPath = value;
129
+ break;
130
+ case '--lines':
131
+ options.lines = parsePositiveInt(value, '--lines');
132
+ break;
133
+ default:
134
+ throw new Error(`Unknown argument: ${key}`);
135
+ }
136
+ }
137
+
138
+ function parsePositiveInt(value, label) {
139
+ const parsed = Number.parseInt(String(value), 10);
140
+ if (!Number.isFinite(parsed) || parsed <= 0) {
141
+ throw new Error(`${label} must be a positive integer`);
142
+ }
143
+ return parsed;
144
+ }
145
+
146
+ function runtimeOverrides(options) {
147
+ const overrides = {};
148
+ if (options.backendUrl !== undefined) overrides.backendUrl = options.backendUrl;
149
+ if (options.interval !== undefined) overrides.intervalSeconds = options.interval;
150
+ if (options.typelessDbPath !== undefined) overrides.typelessDbPath = options.typelessDbPath;
151
+ if (options.typelessStoragePath !== undefined) {
152
+ overrides.typelessStoragePath = options.typelessStoragePath;
153
+ }
154
+ if (options.stateDbPath !== undefined) overrides.stateDbPath = options.stateDbPath;
155
+ return overrides;
156
+ }
157
+
158
+ function printHelp() {
159
+ console.log(HELP_TEXT);
160
+ }
161
+
162
+ function currentEntryFile() {
163
+ return fileURLToPath(new URL('../bin/typeless-usage-uploader.js', import.meta.url));
164
+ }
165
+
166
+ async function runInit(options) {
167
+ const overrides = runtimeOverrides(options);
168
+ if (!overrides.backendUrl) overrides.backendUrl = DEFAULT_BACKEND_URL;
169
+ let runtime = mergeRuntimeConfig(options.configFile, overrides);
170
+ runtime.entryFile = currentEntryFile();
171
+ runtime = saveRuntimeConfig(runtime);
172
+
173
+ const uploader = cliDeps.createUploader(runtime);
174
+ try {
175
+ const scanResult = await uploader.scanTypeless();
176
+ scanResult.batchesQueued += uploader.stateDb.sealStaleBatches(true);
177
+ await uploader.flushPendingBatches({ failFast: false });
178
+ const manager = cliDeps.createServiceManager(runtime);
179
+ try {
180
+ manager.start();
181
+ console.log(`${PRODUCT_NAME} initialized and started.`);
182
+ } catch (error) {
183
+ console.log(`${PRODUCT_NAME} initialized. Service start skipped: ${error instanceof Error ? error.message : String(error)}`);
184
+ }
185
+ console.log(`Backend: ${runtime.backendUrl}`);
186
+ console.log(`Install root: ${runtime.installRoot}`);
187
+ console.log(`Config file: ${runtime.configFile}`);
188
+ console.log(`Collector ID: ${uploader.identity.collectorId}`);
189
+ console.log(
190
+ `Initial scan: account=${scanResult.accountFound ? 'yes' : 'no'} db=${scanResult.dbFound ? 'yes' : 'no'} changed=${scanResult.changedEvents} deleted=${scanResult.tombstoneEvents}`,
191
+ );
192
+ } finally {
193
+ uploader.close();
194
+ }
195
+ }
196
+
197
+ function loadQueueStats(stateDbPath) {
198
+ if (!fs.existsSync(stateDbPath)) {
199
+ return {
200
+ collectorId: null,
201
+ bufferingBatchCount: 0,
202
+ pendingBatchCount: 0,
203
+ retryingBatchCount: 0,
204
+ queuedEvents: 0,
205
+ oldestPendingAgeSeconds: null,
206
+ };
207
+ }
208
+ const stateDb = new StateDb(stateDbPath);
209
+ try {
210
+ const identity = stateDb.getIdentity();
211
+ return {
212
+ collectorId: identity.collectorId ?? null,
213
+ ...stateDb.getQueueStats(),
214
+ };
215
+ } finally {
216
+ stateDb.close();
217
+ }
218
+ }
219
+
220
+ function printStatus(runtime, status) {
221
+ const payload = {
222
+ ...formatStatusOutput(runtime, status),
223
+ ...loadQueueStats(runtime.stateDbPath),
224
+ };
225
+ const lines = [
226
+ ['Config exists', payload.configExists ? 'yes' : 'no'],
227
+ ['Loaded', payload.loaded ? 'yes' : 'no'],
228
+ ['Running', payload.running ? 'yes' : 'no'],
229
+ ['Auto start on login', payload.autoStartOnLogin ? 'yes' : 'no'],
230
+ ['PID', payload.pid ?? '-'],
231
+ ['State', payload.state ?? '-'],
232
+ ['Last exit code', payload.lastExitCode ?? '-'],
233
+ ['Collector ID', payload.collectorId ?? '-'],
234
+ ['Upload URL', payload.backendUrl ? `${payload.backendUrl}/typeless-usage/upload` : '-'],
235
+ ['Register URL', payload.backendUrl ? `${payload.backendUrl}/typeless-usage/collectors/register` : '-'],
236
+ ['Interval', `${payload.intervalSeconds}s`],
237
+ ['Typeless DB', payload.typelessDbPath],
238
+ ['Typeless storage', payload.typelessStoragePath],
239
+ ['Buffering batches', payload.bufferingBatchCount],
240
+ ['Pending batches', payload.pendingBatchCount],
241
+ ['Retrying batches', payload.retryingBatchCount],
242
+ ['Queued events', payload.queuedEvents],
243
+ [
244
+ 'Oldest pending age',
245
+ payload.oldestPendingAgeSeconds == null
246
+ ? '-'
247
+ : `${payload.oldestPendingAgeSeconds}s`,
248
+ ],
249
+ ['Config file', payload.configFile],
250
+ ['State DB', payload.stateDbPath],
251
+ ['Stdout log', payload.stdoutLogPath],
252
+ ['Stderr log', payload.stderrLogPath],
253
+ ['Service plist', payload.plistPath],
254
+ ['LaunchAgent plist', payload.launchAgentPath],
255
+ ['Label', payload.label],
256
+ ];
257
+ for (const [label, value] of lines) console.log(`${label}: ${value}`);
258
+ }
259
+
260
+ function ensureInitialized(runtime) {
261
+ if (!fs.existsSync(runtime.configFile) || !runtime.entryFile) {
262
+ throw new CliOperationalError(
263
+ `Uploader is not initialized yet. Run \`${CLI_NAME} init\` first.`,
264
+ );
265
+ }
266
+ }
267
+
268
+ async function runClear(options) {
269
+ const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
270
+ const uploader = cliDeps.createUploader(runtime);
271
+ try {
272
+ uploader.resetBackfillState();
273
+ } finally {
274
+ uploader.close();
275
+ }
276
+ console.log('Local Typeless scan state has been cleared.');
277
+ }
278
+
279
+ function runLifecycleCommand(action, options) {
280
+ const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
281
+ const manager = cliDeps.createServiceManager(runtime);
282
+ switch (action) {
283
+ case 'start':
284
+ ensureInitialized(runtime);
285
+ manager.start();
286
+ console.log('Service started.');
287
+ break;
288
+ case 'stop':
289
+ manager.stop();
290
+ console.log('Service stopped.');
291
+ break;
292
+ case 'restart':
293
+ ensureInitialized(runtime);
294
+ manager.restart();
295
+ console.log('Service restarted.');
296
+ break;
297
+ case 'uninstall':
298
+ manager.uninstall();
299
+ console.log('Service uninstalled.');
300
+ break;
301
+ }
302
+ }
303
+
304
+ async function runInternalWorker(options) {
305
+ const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
306
+ const uploader = cliDeps.createUploader(runtime);
307
+ try {
308
+ console.log(
309
+ `[run] backend=${runtime.backendUrl ?? '-'} interval=${runtime.intervalSeconds}s typeless_db=${runtime.typelessDbPath}`,
310
+ );
311
+ await uploader.watch();
312
+ } finally {
313
+ uploader.close();
314
+ }
315
+ }
316
+
317
+ function tailFile(filePath, lines) {
318
+ if (!fs.existsSync(filePath)) return [];
319
+ return fs.readFileSync(filePath, 'utf8')
320
+ .split(/\r?\n/)
321
+ .filter((line, index, array) => !(index === array.length - 1 && line === ''))
322
+ .slice(-lines);
323
+ }
324
+
325
+ export async function main(argv = process.argv.slice(2)) {
326
+ const parsed = parseCliArgs(argv);
327
+ const { command, subcommand, extraPositionals, options } = parsed;
328
+ if (options.help || !command) {
329
+ printHelp();
330
+ return;
331
+ }
332
+ if (subcommand || extraPositionals.length) {
333
+ throw new Error('Unexpected extra arguments.');
334
+ }
335
+
336
+ switch (command) {
337
+ case 'init':
338
+ await runInit(options);
339
+ return;
340
+ case 'clear':
341
+ await runClear(options);
342
+ return;
343
+ case 'start':
344
+ case 'stop':
345
+ case 'restart':
346
+ case 'uninstall':
347
+ runLifecycleCommand(command, options);
348
+ return;
349
+ case 'status': {
350
+ const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
351
+ const manager = cliDeps.createServiceManager(runtime);
352
+ let status;
353
+ try {
354
+ status = manager.status();
355
+ } catch {
356
+ status = { loaded: false, running: false, pid: null, state: null, lastExitCode: null };
357
+ }
358
+ printStatus(runtime, status);
359
+ return;
360
+ }
361
+ case 'logs': {
362
+ const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
363
+ for (const line of tailFile(runtime.stdoutLogPath, options.lines)) console.log(line);
364
+ for (const line of tailFile(runtime.stderrLogPath, options.lines)) console.error(line);
365
+ return;
366
+ }
367
+ case 'run':
368
+ await runInternalWorker(options);
369
+ return;
370
+ default:
371
+ throw new Error(`Unknown command: ${command}`);
372
+ }
373
+ }