tersejson 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/LICENSE +21 -0
- package/README.md +476 -0
- package/dist/analytics.d.mts +186 -0
- package/dist/analytics.d.ts +186 -0
- package/dist/analytics.js +226 -0
- package/dist/analytics.js.map +1 -0
- package/dist/analytics.mjs +217 -0
- package/dist/analytics.mjs.map +1 -0
- package/dist/client-BQAZg7I8.d.mts +138 -0
- package/dist/client-DOOGwp_p.d.ts +138 -0
- package/dist/client.d.mts +2 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +200 -0
- package/dist/client.js.map +1 -0
- package/dist/client.mjs +188 -0
- package/dist/client.mjs.map +1 -0
- package/dist/express-BoL__Ao6.d.mts +67 -0
- package/dist/express-LSVylWpN.d.ts +67 -0
- package/dist/express.d.mts +4 -0
- package/dist/express.d.ts +4 -0
- package/dist/express.js +522 -0
- package/dist/express.js.map +1 -0
- package/dist/express.mjs +512 -0
- package/dist/express.mjs.map +1 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1001 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +985 -0
- package/dist/index.mjs.map +1 -0
- package/dist/integrations-7WeFO1Lk.d.mts +264 -0
- package/dist/integrations-7WeFO1Lk.d.ts +264 -0
- package/dist/integrations.d.mts +1 -0
- package/dist/integrations.d.ts +1 -0
- package/dist/integrations.js +381 -0
- package/dist/integrations.js.map +1 -0
- package/dist/integrations.mjs +367 -0
- package/dist/integrations.mjs.map +1 -0
- package/dist/types-CzaGQaV7.d.mts +134 -0
- package/dist/types-CzaGQaV7.d.ts +134 -0
- package/package.json +87 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics.ts"],"names":[],"mappings":";AAqHA,IAAM,cAAA,GAAkG;AAAA,EACtG,OAAA,EAAS,KAAA;AAAA,EACT,aAAA,EAAe,KAAA;AAAA,EACf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AAA;AAAA,MACT,aAAA,EAAe,KAAA;AAAA,MACf,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,SAAS,OAAA,CAAQ;AAAA,KAClB,CAAA;AAAA,EACH,CAAA;AAAA;AAAA;AAAA;AAAA,EAKA,KAAA,CAAM,MAAA,EAAgB,OAAA,GAAoC,EAAC,EAAG;AAC5D,IAAA,OAAO,aAAA,CAAc;AAAA,MACnB,GAAG,OAAA;AAAA,MACH,OAAA,EAAS,IAAA;AAAA,MACT,aAAA,EAAe,IAAA;AAAA,MACf;AAAA,KACD,CAAA;AAAA,EACH,CAAA;AAAA;AAAA;AAAA;AAAA,EAKA,QAAA,GAAW;AACT,IAAA,OAAO,eAAA,EAAiB,UAAS,IAAK,IAAA;AAAA,EACxC,CAAA;AAAA;AAAA;AAAA;AAAA,EAKA,UAAA,GAAa;AACX,IAAA,OAAO,eAAA,EAAiB,YAAW,IAAK,2BAAA;AAAA,EAC1C;AACF;AAEA,IAAO,iBAAA,GAAQ","file":"analytics.mjs","sourcesContent":["/**\n * TerseJSON Analytics\n *\n * Opt-in analytics to track compression savings.\n * Data is anonymous and helps improve the library.\n */\n\n/**\n * Compression event data\n */\nexport interface CompressionEvent {\n /** Timestamp of the compression */\n timestamp: number;\n /** Original payload size in bytes */\n originalSize: number;\n /** Compressed payload size in bytes */\n compressedSize: number;\n /** Number of objects in the array */\n objectCount: number;\n /** Number of keys compressed */\n keysCompressed: number;\n /** Route/endpoint (optional, anonymized) */\n endpoint?: string;\n /** Key pattern used */\n keyPattern: string;\n}\n\n/**\n * Aggregated stats for reporting\n */\nexport interface AnalyticsStats {\n /** Total compression events */\n totalEvents: number;\n /** Total bytes before compression */\n totalOriginalBytes: number;\n /** Total bytes after compression */\n totalCompressedBytes: number;\n /** Total bytes saved */\n totalBytesSaved: number;\n /** Average compression ratio (0-1) */\n averageRatio: number;\n /** Total objects processed */\n totalObjects: number;\n /** Session start time */\n sessionStart: number;\n /** Last event time */\n lastEvent: number;\n}\n\n/**\n * Analytics configuration\n */\nexport interface AnalyticsConfig {\n /**\n * Enable analytics collection\n * @default false\n */\n enabled: boolean;\n\n /**\n * Send anonymous stats to tersejson.com\n * Helps improve the library\n * @default false\n */\n reportToCloud: boolean;\n\n /**\n * API key for tersejson.com (optional)\n * Get one at tersejson.com/dashboard\n */\n apiKey?: string;\n\n /**\n * Project/site identifier (optional)\n */\n projectId?: string;\n\n /**\n * Callback for each compression event\n * Use for custom logging/monitoring\n */\n onEvent?: (event: CompressionEvent) => void;\n\n /**\n * Callback for periodic stats summary\n */\n onStats?: (stats: AnalyticsStats) => void;\n\n /**\n * How often to report stats (ms)\n * @default 60000 (1 minute)\n */\n reportInterval?: number;\n\n /**\n * Include endpoint paths in analytics\n * Paths are hashed for privacy\n * @default false\n */\n trackEndpoints?: boolean;\n\n /**\n * Cloud reporting endpoint\n * @default 'https://api.tersejson.com/v1/analytics'\n */\n endpoint?: string;\n\n /**\n * Enable debug logging\n * @default false\n */\n debug?: boolean;\n}\n\n/**\n * Default configuration\n */\nconst DEFAULT_CONFIG: Required<Omit<AnalyticsConfig, 'apiKey' | 'projectId' | 'onEvent' | 'onStats'>> = {\n enabled: false,\n reportToCloud: false,\n reportInterval: 60000,\n trackEndpoints: false,\n endpoint: 'https://api.tersejson.com/v1/analytics',\n debug: false,\n};\n\n/**\n * Analytics collector class\n */\nexport class TerseAnalytics {\n private config: Required<Omit<AnalyticsConfig, 'apiKey' | 'projectId' | 'onEvent' | 'onStats'>> &\n Pick<AnalyticsConfig, 'apiKey' | 'projectId' | 'onEvent' | 'onStats'>;\n private events: CompressionEvent[] = [];\n private stats: AnalyticsStats;\n private reportTimer?: ReturnType<typeof setInterval>;\n private isNode: boolean;\n\n constructor(config: Partial<AnalyticsConfig> = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.isNode = typeof window === 'undefined';\n this.stats = this.createEmptyStats();\n\n if (this.config.enabled && this.config.reportToCloud) {\n this.startReporting();\n }\n }\n\n /**\n * Create empty stats object\n */\n private createEmptyStats(): AnalyticsStats {\n return {\n totalEvents: 0,\n totalOriginalBytes: 0,\n totalCompressedBytes: 0,\n totalBytesSaved: 0,\n averageRatio: 0,\n totalObjects: 0,\n sessionStart: Date.now(),\n lastEvent: Date.now(),\n };\n }\n\n /**\n * Record a compression event\n */\n record(event: Omit<CompressionEvent, 'timestamp'>): void {\n if (!this.config.enabled) return;\n\n const fullEvent: CompressionEvent = {\n ...event,\n timestamp: Date.now(),\n // Hash endpoint for privacy if tracking is enabled\n endpoint: this.config.trackEndpoints && event.endpoint\n ? this.hashEndpoint(event.endpoint)\n : undefined,\n };\n\n // Update stats\n this.stats.totalEvents++;\n this.stats.totalOriginalBytes += event.originalSize;\n this.stats.totalCompressedBytes += event.compressedSize;\n this.stats.totalBytesSaved += (event.originalSize - event.compressedSize);\n this.stats.totalObjects += event.objectCount;\n this.stats.lastEvent = fullEvent.timestamp;\n this.stats.averageRatio = this.stats.totalCompressedBytes / this.stats.totalOriginalBytes;\n\n // Store event for batch reporting\n this.events.push(fullEvent);\n\n // Call event callback\n if (this.config.onEvent) {\n this.config.onEvent(fullEvent);\n }\n\n // Debug logging\n if (this.config.debug) {\n const savings = ((1 - event.compressedSize / event.originalSize) * 100).toFixed(1);\n console.log(`[tersejson:analytics] ${event.originalSize} → ${event.compressedSize} bytes (${savings}% saved)`);\n }\n }\n\n /**\n * Get current stats\n */\n getStats(): AnalyticsStats {\n return { ...this.stats };\n }\n\n /**\n * Get formatted stats summary\n */\n getSummary(): string {\n const stats = this.stats;\n const savedKB = (stats.totalBytesSaved / 1024).toFixed(2);\n const savedPercent = stats.totalOriginalBytes > 0\n ? ((1 - stats.averageRatio) * 100).toFixed(1)\n : '0';\n\n return `TerseJSON Stats: ${stats.totalEvents} compressions, ${savedKB}KB saved (${savedPercent}% avg)`;\n }\n\n /**\n * Reset stats\n */\n reset(): void {\n this.events = [];\n this.stats = this.createEmptyStats();\n }\n\n /**\n * Start periodic reporting to cloud\n */\n private startReporting(): void {\n if (this.reportTimer) return;\n\n this.reportTimer = setInterval(() => {\n this.reportToCloud();\n }, this.config.reportInterval);\n\n // Report on exit (Node.js only)\n if (this.isNode && typeof process !== 'undefined') {\n process.on('beforeExit', () => this.reportToCloud());\n }\n }\n\n /**\n * Stop reporting\n */\n stop(): void {\n if (this.reportTimer) {\n clearInterval(this.reportTimer);\n this.reportTimer = undefined;\n }\n }\n\n /**\n * Report stats to tersejson.com\n */\n private async reportToCloud(): Promise<void> {\n if (!this.config.reportToCloud || this.events.length === 0) return;\n\n const payload = {\n apiKey: this.config.apiKey,\n projectId: this.config.projectId,\n stats: this.stats,\n events: this.events.slice(-100), // Last 100 events only\n meta: {\n version: '0.1.0',\n runtime: this.isNode ? 'node' : 'browser',\n },\n };\n\n try {\n // Use appropriate fetch based on environment\n const fetchFn = this.isNode\n ? (await import('node:https')).request\n : globalThis.fetch;\n\n if (this.isNode) {\n // Node.js - fire and forget\n const url = new URL(this.config.endpoint);\n const req = (fetchFn as typeof import('node:https').request)({\n hostname: url.hostname,\n port: url.port || 443,\n path: url.pathname,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n req.write(JSON.stringify(payload));\n req.end();\n } else {\n // Browser\n (fetchFn as typeof fetch)(this.config.endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n keepalive: true, // Allow sending on page unload\n }).catch(() => {}); // Ignore errors\n }\n\n // Clear reported events\n this.events = [];\n\n // Call stats callback\n if (this.config.onStats) {\n this.config.onStats(this.stats);\n }\n\n if (this.config.debug) {\n console.log('[tersejson:analytics] Reported stats to cloud');\n }\n } catch {\n // Silently fail - analytics should never break the app\n if (this.config.debug) {\n console.log('[tersejson:analytics] Failed to report stats');\n }\n }\n }\n\n /**\n * Hash endpoint for privacy\n */\n private hashEndpoint(endpoint: string): string {\n // Simple hash - just keeps route structure without specifics\n return endpoint\n .replace(/\\/\\d+/g, '/:id')\n .replace(/\\/[a-f0-9-]{36}/gi, '/:uuid')\n .replace(/\\?.*$/, '');\n }\n}\n\n/**\n * Global analytics instance (singleton)\n */\nlet globalAnalytics: TerseAnalytics | null = null;\n\n/**\n * Initialize global analytics\n */\nexport function initAnalytics(config: Partial<AnalyticsConfig>): TerseAnalytics {\n globalAnalytics = new TerseAnalytics(config);\n return globalAnalytics;\n}\n\n/**\n * Get global analytics instance\n */\nexport function getAnalytics(): TerseAnalytics | null {\n return globalAnalytics;\n}\n\n/**\n * Record an event to global analytics (if initialized)\n */\nexport function recordEvent(event: Omit<CompressionEvent, 'timestamp'>): void {\n globalAnalytics?.record(event);\n}\n\n/**\n * Quick setup for common use cases\n */\nexport const analytics = {\n /**\n * Enable local-only analytics (no cloud reporting)\n */\n local(options: { debug?: boolean; onEvent?: AnalyticsConfig['onEvent'] } = {}) {\n return initAnalytics({\n enabled: true,\n reportToCloud: false,\n debug: options.debug,\n onEvent: options.onEvent,\n });\n },\n\n /**\n * Enable cloud analytics with API key\n */\n cloud(apiKey: string, options: Partial<AnalyticsConfig> = {}) {\n return initAnalytics({\n ...options,\n enabled: true,\n reportToCloud: true,\n apiKey,\n });\n },\n\n /**\n * Get current stats\n */\n getStats() {\n return globalAnalytics?.getStats() ?? null;\n },\n\n /**\n * Get formatted summary\n */\n getSummary() {\n return globalAnalytics?.getSummary() ?? 'Analytics not initialized';\n },\n};\n\nexport default analytics;\n"]}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { C as CompressOptions, T as TersePayload, K as KeyPattern, d as KeyGenerator, b as TerseClientOptions, i as isTersePayload } from './types-CzaGQaV7.mjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* TerseJSON Core
|
|
5
|
+
*
|
|
6
|
+
* The core compression and expansion algorithms.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Creates a key generator from a pattern configuration
|
|
11
|
+
*/
|
|
12
|
+
declare function createKeyGenerator(pattern: KeyPattern): {
|
|
13
|
+
generator: KeyGenerator;
|
|
14
|
+
name: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Checks if an array is compressible (array of objects with consistent structure)
|
|
18
|
+
*/
|
|
19
|
+
declare function isCompressibleArray(data: unknown): data is Record<string, unknown>[];
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Compresses an array of objects by replacing keys with short aliases
|
|
23
|
+
*/
|
|
24
|
+
declare function compress<T extends Record<string, unknown>[]>(data: T, options?: CompressOptions): TersePayload<unknown[]>;
|
|
25
|
+
/**
|
|
26
|
+
* Expands a TersePayload back to its original form
|
|
27
|
+
*/
|
|
28
|
+
declare function expand<T = unknown>(payload: TersePayload): T;
|
|
29
|
+
/**
|
|
30
|
+
* Creates a Proxy that transparently maps original keys to short keys
|
|
31
|
+
* This is the magic that makes client-side access seamless
|
|
32
|
+
*/
|
|
33
|
+
declare function createTerseProxy<T extends Record<string, unknown>>(compressed: Record<string, unknown>, keyMap: Record<string, string>): T;
|
|
34
|
+
/**
|
|
35
|
+
* Wraps TersePayload data with Proxies for transparent access
|
|
36
|
+
*/
|
|
37
|
+
declare function wrapWithProxy<T>(payload: TersePayload): T;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* TerseJSON Client
|
|
41
|
+
*
|
|
42
|
+
* Transparent client-side handling of TerseJSON responses.
|
|
43
|
+
* Use the fetch wrapper or manually expand responses.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Process a potential TerseJSON response
|
|
48
|
+
* Automatically detects and expands/proxies terse payloads
|
|
49
|
+
*/
|
|
50
|
+
declare function process<T = unknown>(data: unknown, options?: {
|
|
51
|
+
useProxy?: boolean;
|
|
52
|
+
}): T;
|
|
53
|
+
/**
|
|
54
|
+
* Creates a fetch wrapper that automatically handles TerseJSON responses
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```typescript
|
|
58
|
+
* import { createFetch } from 'tersejson/client';
|
|
59
|
+
*
|
|
60
|
+
* const fetch = createFetch();
|
|
61
|
+
*
|
|
62
|
+
* // Use exactly like regular fetch
|
|
63
|
+
* const users = await fetch('/api/users').then(r => r.json());
|
|
64
|
+
* console.log(users[0].firstName); // Works transparently!
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
declare function createFetch(options?: TerseClientOptions): typeof globalThis.fetch;
|
|
68
|
+
/**
|
|
69
|
+
* Drop-in fetch replacement with TerseJSON support
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* import { fetch } from 'tersejson/client';
|
|
74
|
+
*
|
|
75
|
+
* const users = await fetch('/api/users').then(r => r.json());
|
|
76
|
+
* console.log(users[0].firstName); // Transparent!
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
declare const fetch: typeof globalThis.fetch;
|
|
80
|
+
/**
|
|
81
|
+
* React hook for fetching with TerseJSON support (if using React)
|
|
82
|
+
* Returns a configured fetch function
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```typescript
|
|
86
|
+
* function MyComponent() {
|
|
87
|
+
* const terseFetch = useTerseFetch();
|
|
88
|
+
* // Use in useEffect, etc.
|
|
89
|
+
* }
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
declare function useTerseFetch(options?: TerseClientOptions): typeof globalThis.fetch;
|
|
93
|
+
/**
|
|
94
|
+
* Axios interceptor for TerseJSON support
|
|
95
|
+
*
|
|
96
|
+
* @example
|
|
97
|
+
* ```typescript
|
|
98
|
+
* import axios from 'axios';
|
|
99
|
+
* import { axiosInterceptor } from 'tersejson/client';
|
|
100
|
+
*
|
|
101
|
+
* axios.interceptors.request.use(axiosInterceptor.request);
|
|
102
|
+
* axios.interceptors.response.use(axiosInterceptor.response);
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
declare const axiosInterceptor: {
|
|
106
|
+
request: (config: {
|
|
107
|
+
headers?: Record<string, string>;
|
|
108
|
+
}) => {
|
|
109
|
+
headers?: Record<string, string>;
|
|
110
|
+
};
|
|
111
|
+
response: (response: {
|
|
112
|
+
headers?: Record<string, string>;
|
|
113
|
+
data?: unknown;
|
|
114
|
+
}) => {
|
|
115
|
+
headers?: Record<string, string>;
|
|
116
|
+
data?: unknown;
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
declare const _default: {
|
|
120
|
+
fetch: typeof globalThis.fetch;
|
|
121
|
+
createFetch: typeof createFetch;
|
|
122
|
+
expand: typeof expand;
|
|
123
|
+
proxy: typeof wrapWithProxy;
|
|
124
|
+
process: typeof process;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
declare const client_axiosInterceptor: typeof axiosInterceptor;
|
|
128
|
+
declare const client_createFetch: typeof createFetch;
|
|
129
|
+
declare const client_expand: typeof expand;
|
|
130
|
+
declare const client_fetch: typeof fetch;
|
|
131
|
+
declare const client_isTersePayload: typeof isTersePayload;
|
|
132
|
+
declare const client_process: typeof process;
|
|
133
|
+
declare const client_useTerseFetch: typeof useTerseFetch;
|
|
134
|
+
declare namespace client {
|
|
135
|
+
export { client_axiosInterceptor as axiosInterceptor, client_createFetch as createFetch, _default as default, client_expand as expand, client_fetch as fetch, client_isTersePayload as isTersePayload, client_process as process, wrapWithProxy as proxy, client_useTerseFetch as useTerseFetch };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export { _default as _, createTerseProxy as a, createKeyGenerator as b, compress as c, client as d, expand as e, createFetch as f, fetch as g, axiosInterceptor as h, isCompressibleArray as i, process as p, useTerseFetch as u, wrapWithProxy as w };
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { C as CompressOptions, T as TersePayload, K as KeyPattern, d as KeyGenerator, b as TerseClientOptions, i as isTersePayload } from './types-CzaGQaV7.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* TerseJSON Core
|
|
5
|
+
*
|
|
6
|
+
* The core compression and expansion algorithms.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Creates a key generator from a pattern configuration
|
|
11
|
+
*/
|
|
12
|
+
declare function createKeyGenerator(pattern: KeyPattern): {
|
|
13
|
+
generator: KeyGenerator;
|
|
14
|
+
name: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Checks if an array is compressible (array of objects with consistent structure)
|
|
18
|
+
*/
|
|
19
|
+
declare function isCompressibleArray(data: unknown): data is Record<string, unknown>[];
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Compresses an array of objects by replacing keys with short aliases
|
|
23
|
+
*/
|
|
24
|
+
declare function compress<T extends Record<string, unknown>[]>(data: T, options?: CompressOptions): TersePayload<unknown[]>;
|
|
25
|
+
/**
|
|
26
|
+
* Expands a TersePayload back to its original form
|
|
27
|
+
*/
|
|
28
|
+
declare function expand<T = unknown>(payload: TersePayload): T;
|
|
29
|
+
/**
|
|
30
|
+
* Creates a Proxy that transparently maps original keys to short keys
|
|
31
|
+
* This is the magic that makes client-side access seamless
|
|
32
|
+
*/
|
|
33
|
+
declare function createTerseProxy<T extends Record<string, unknown>>(compressed: Record<string, unknown>, keyMap: Record<string, string>): T;
|
|
34
|
+
/**
|
|
35
|
+
* Wraps TersePayload data with Proxies for transparent access
|
|
36
|
+
*/
|
|
37
|
+
declare function wrapWithProxy<T>(payload: TersePayload): T;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* TerseJSON Client
|
|
41
|
+
*
|
|
42
|
+
* Transparent client-side handling of TerseJSON responses.
|
|
43
|
+
* Use the fetch wrapper or manually expand responses.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Process a potential TerseJSON response
|
|
48
|
+
* Automatically detects and expands/proxies terse payloads
|
|
49
|
+
*/
|
|
50
|
+
declare function process<T = unknown>(data: unknown, options?: {
|
|
51
|
+
useProxy?: boolean;
|
|
52
|
+
}): T;
|
|
53
|
+
/**
|
|
54
|
+
* Creates a fetch wrapper that automatically handles TerseJSON responses
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```typescript
|
|
58
|
+
* import { createFetch } from 'tersejson/client';
|
|
59
|
+
*
|
|
60
|
+
* const fetch = createFetch();
|
|
61
|
+
*
|
|
62
|
+
* // Use exactly like regular fetch
|
|
63
|
+
* const users = await fetch('/api/users').then(r => r.json());
|
|
64
|
+
* console.log(users[0].firstName); // Works transparently!
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
declare function createFetch(options?: TerseClientOptions): typeof globalThis.fetch;
|
|
68
|
+
/**
|
|
69
|
+
* Drop-in fetch replacement with TerseJSON support
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* import { fetch } from 'tersejson/client';
|
|
74
|
+
*
|
|
75
|
+
* const users = await fetch('/api/users').then(r => r.json());
|
|
76
|
+
* console.log(users[0].firstName); // Transparent!
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
declare const fetch: typeof globalThis.fetch;
|
|
80
|
+
/**
|
|
81
|
+
* React hook for fetching with TerseJSON support (if using React)
|
|
82
|
+
* Returns a configured fetch function
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```typescript
|
|
86
|
+
* function MyComponent() {
|
|
87
|
+
* const terseFetch = useTerseFetch();
|
|
88
|
+
* // Use in useEffect, etc.
|
|
89
|
+
* }
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
declare function useTerseFetch(options?: TerseClientOptions): typeof globalThis.fetch;
|
|
93
|
+
/**
|
|
94
|
+
* Axios interceptor for TerseJSON support
|
|
95
|
+
*
|
|
96
|
+
* @example
|
|
97
|
+
* ```typescript
|
|
98
|
+
* import axios from 'axios';
|
|
99
|
+
* import { axiosInterceptor } from 'tersejson/client';
|
|
100
|
+
*
|
|
101
|
+
* axios.interceptors.request.use(axiosInterceptor.request);
|
|
102
|
+
* axios.interceptors.response.use(axiosInterceptor.response);
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
declare const axiosInterceptor: {
|
|
106
|
+
request: (config: {
|
|
107
|
+
headers?: Record<string, string>;
|
|
108
|
+
}) => {
|
|
109
|
+
headers?: Record<string, string>;
|
|
110
|
+
};
|
|
111
|
+
response: (response: {
|
|
112
|
+
headers?: Record<string, string>;
|
|
113
|
+
data?: unknown;
|
|
114
|
+
}) => {
|
|
115
|
+
headers?: Record<string, string>;
|
|
116
|
+
data?: unknown;
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
declare const _default: {
|
|
120
|
+
fetch: typeof globalThis.fetch;
|
|
121
|
+
createFetch: typeof createFetch;
|
|
122
|
+
expand: typeof expand;
|
|
123
|
+
proxy: typeof wrapWithProxy;
|
|
124
|
+
process: typeof process;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
declare const client_axiosInterceptor: typeof axiosInterceptor;
|
|
128
|
+
declare const client_createFetch: typeof createFetch;
|
|
129
|
+
declare const client_expand: typeof expand;
|
|
130
|
+
declare const client_fetch: typeof fetch;
|
|
131
|
+
declare const client_isTersePayload: typeof isTersePayload;
|
|
132
|
+
declare const client_process: typeof process;
|
|
133
|
+
declare const client_useTerseFetch: typeof useTerseFetch;
|
|
134
|
+
declare namespace client {
|
|
135
|
+
export { client_axiosInterceptor as axiosInterceptor, client_createFetch as createFetch, _default as default, client_expand as expand, client_fetch as fetch, client_isTersePayload as isTersePayload, client_process as process, wrapWithProxy as proxy, client_useTerseFetch as useTerseFetch };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export { _default as _, createTerseProxy as a, createKeyGenerator as b, compress as c, client as d, expand as e, createFetch as f, fetch as g, axiosInterceptor as h, isCompressibleArray as i, process as p, useTerseFetch as u, wrapWithProxy as w };
|
package/dist/client.d.ts
ADDED
package/dist/client.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
// src/types.ts
|
|
6
|
+
function isTersePayload(value) {
|
|
7
|
+
return typeof value === "object" && value !== null && "__terse__" in value && value.__terse__ === true && "v" in value && "k" in value && "d" in value;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// src/core.ts
|
|
11
|
+
function expandObject(obj, shortToKey, maxDepth, currentDepth = 0) {
|
|
12
|
+
if (currentDepth >= maxDepth) return obj;
|
|
13
|
+
const expanded = {};
|
|
14
|
+
for (const [shortKey, value] of Object.entries(obj)) {
|
|
15
|
+
const originalKey = shortToKey.get(shortKey) ?? shortKey;
|
|
16
|
+
if (Array.isArray(value)) {
|
|
17
|
+
expanded[originalKey] = value.map((item) => {
|
|
18
|
+
if (typeof item === "object" && item !== null && !Array.isArray(item)) {
|
|
19
|
+
return expandObject(
|
|
20
|
+
item,
|
|
21
|
+
shortToKey,
|
|
22
|
+
maxDepth,
|
|
23
|
+
currentDepth + 1
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
return item;
|
|
27
|
+
});
|
|
28
|
+
} else if (typeof value === "object" && value !== null) {
|
|
29
|
+
expanded[originalKey] = expandObject(
|
|
30
|
+
value,
|
|
31
|
+
shortToKey,
|
|
32
|
+
maxDepth,
|
|
33
|
+
currentDepth + 1
|
|
34
|
+
);
|
|
35
|
+
} else {
|
|
36
|
+
expanded[originalKey] = value;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return expanded;
|
|
40
|
+
}
|
|
41
|
+
function expand(payload) {
|
|
42
|
+
const shortToKey = new Map(
|
|
43
|
+
Object.entries(payload.k).map(([short, original]) => [short, original])
|
|
44
|
+
);
|
|
45
|
+
if (Array.isArray(payload.d)) {
|
|
46
|
+
return payload.d.map((item) => {
|
|
47
|
+
if (typeof item === "object" && item !== null && !Array.isArray(item)) {
|
|
48
|
+
return expandObject(item, shortToKey, 10);
|
|
49
|
+
}
|
|
50
|
+
return item;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
if (typeof payload.d === "object" && payload.d !== null) {
|
|
54
|
+
return expandObject(payload.d, shortToKey, 10);
|
|
55
|
+
}
|
|
56
|
+
return payload.d;
|
|
57
|
+
}
|
|
58
|
+
function createTerseProxy(compressed, keyMap) {
|
|
59
|
+
const originalToShort = new Map(
|
|
60
|
+
Object.entries(keyMap).map(([short, original]) => [original, short])
|
|
61
|
+
);
|
|
62
|
+
const handler = {
|
|
63
|
+
get(target, prop) {
|
|
64
|
+
if (typeof prop === "symbol") {
|
|
65
|
+
return Reflect.get(target, prop);
|
|
66
|
+
}
|
|
67
|
+
const shortKey = originalToShort.get(prop);
|
|
68
|
+
const actualKey = shortKey ?? prop;
|
|
69
|
+
const value = target[actualKey];
|
|
70
|
+
if (Array.isArray(value)) {
|
|
71
|
+
return value.map((item) => {
|
|
72
|
+
if (typeof item === "object" && item !== null && !Array.isArray(item)) {
|
|
73
|
+
return createTerseProxy(item, keyMap);
|
|
74
|
+
}
|
|
75
|
+
return item;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
if (typeof value === "object" && value !== null) {
|
|
79
|
+
return createTerseProxy(value, keyMap);
|
|
80
|
+
}
|
|
81
|
+
return value;
|
|
82
|
+
},
|
|
83
|
+
has(target, prop) {
|
|
84
|
+
if (typeof prop === "symbol") {
|
|
85
|
+
return Reflect.has(target, prop);
|
|
86
|
+
}
|
|
87
|
+
const shortKey = originalToShort.get(prop);
|
|
88
|
+
return (shortKey ?? prop) in target;
|
|
89
|
+
},
|
|
90
|
+
ownKeys(target) {
|
|
91
|
+
return Object.keys(target).map((shortKey) => keyMap[shortKey] ?? shortKey);
|
|
92
|
+
},
|
|
93
|
+
getOwnPropertyDescriptor(target, prop) {
|
|
94
|
+
if (typeof prop === "symbol") {
|
|
95
|
+
return Reflect.getOwnPropertyDescriptor(target, prop);
|
|
96
|
+
}
|
|
97
|
+
const shortKey = originalToShort.get(prop);
|
|
98
|
+
const actualKey = shortKey ?? prop;
|
|
99
|
+
const descriptor = Object.getOwnPropertyDescriptor(target, actualKey);
|
|
100
|
+
if (descriptor) {
|
|
101
|
+
return { ...descriptor, enumerable: true, configurable: true };
|
|
102
|
+
}
|
|
103
|
+
return void 0;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
return new Proxy(compressed, handler);
|
|
107
|
+
}
|
|
108
|
+
function wrapWithProxy(payload) {
|
|
109
|
+
if (Array.isArray(payload.d)) {
|
|
110
|
+
return payload.d.map((item) => {
|
|
111
|
+
if (typeof item === "object" && item !== null && !Array.isArray(item)) {
|
|
112
|
+
return createTerseProxy(item, payload.k);
|
|
113
|
+
}
|
|
114
|
+
return item;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
if (typeof payload.d === "object" && payload.d !== null) {
|
|
118
|
+
return createTerseProxy(payload.d, payload.k);
|
|
119
|
+
}
|
|
120
|
+
return payload.d;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/client.ts
|
|
124
|
+
var DEFAULT_OPTIONS = {
|
|
125
|
+
headerName: "x-terse-json",
|
|
126
|
+
debug: false,
|
|
127
|
+
autoExpand: true
|
|
128
|
+
};
|
|
129
|
+
function process(data, options = {}) {
|
|
130
|
+
const { useProxy = true } = options;
|
|
131
|
+
if (isTersePayload(data)) {
|
|
132
|
+
return useProxy ? wrapWithProxy(data) : expand(data);
|
|
133
|
+
}
|
|
134
|
+
return data;
|
|
135
|
+
}
|
|
136
|
+
function createFetch(options = {}) {
|
|
137
|
+
const config = { ...DEFAULT_OPTIONS, ...options };
|
|
138
|
+
return async function terseFetch(input, init = {}) {
|
|
139
|
+
const headers = new Headers(init.headers);
|
|
140
|
+
headers.set("accept-terse", "true");
|
|
141
|
+
const response = await globalThis.fetch(input, {
|
|
142
|
+
...init,
|
|
143
|
+
headers
|
|
144
|
+
});
|
|
145
|
+
const isTerse = response.headers.get(config.headerName) === "true";
|
|
146
|
+
if (!isTerse || !config.autoExpand) {
|
|
147
|
+
return response;
|
|
148
|
+
}
|
|
149
|
+
const clonedResponse = response.clone();
|
|
150
|
+
return new Proxy(response, {
|
|
151
|
+
get(target, prop) {
|
|
152
|
+
if (prop === "json") {
|
|
153
|
+
return async function() {
|
|
154
|
+
const data = await clonedResponse.json();
|
|
155
|
+
if (isTersePayload(data)) {
|
|
156
|
+
if (config.debug) {
|
|
157
|
+
console.log("[tersejson] Expanding terse response");
|
|
158
|
+
}
|
|
159
|
+
return wrapWithProxy(data);
|
|
160
|
+
}
|
|
161
|
+
return data;
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
const value = Reflect.get(target, prop);
|
|
165
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
var fetch = createFetch();
|
|
171
|
+
function useTerseFetch(options = {}) {
|
|
172
|
+
return createFetch(options);
|
|
173
|
+
}
|
|
174
|
+
var axiosInterceptor = {
|
|
175
|
+
request: (config) => {
|
|
176
|
+
config.headers = config.headers || {};
|
|
177
|
+
config.headers["accept-terse"] = "true";
|
|
178
|
+
return config;
|
|
179
|
+
},
|
|
180
|
+
response: (response) => {
|
|
181
|
+
const isTerse = response.headers?.["x-terse-json"] === "true";
|
|
182
|
+
if (isTerse && isTersePayload(response.data)) {
|
|
183
|
+
response.data = wrapWithProxy(response.data);
|
|
184
|
+
}
|
|
185
|
+
return response;
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
var client_default = { fetch, createFetch, expand, proxy: wrapWithProxy, process };
|
|
189
|
+
|
|
190
|
+
exports.axiosInterceptor = axiosInterceptor;
|
|
191
|
+
exports.createFetch = createFetch;
|
|
192
|
+
exports.default = client_default;
|
|
193
|
+
exports.expand = expand;
|
|
194
|
+
exports.fetch = fetch;
|
|
195
|
+
exports.isTersePayload = isTersePayload;
|
|
196
|
+
exports.process = process;
|
|
197
|
+
exports.proxy = wrapWithProxy;
|
|
198
|
+
exports.useTerseFetch = useTerseFetch;
|
|
199
|
+
//# sourceMappingURL=client.js.map
|
|
200
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/core.ts","../src/client.ts"],"names":[],"mappings":";;;;;AAiKO,SAAS,eAAe,KAAA,EAAuC;AACpE,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,QACV,WAAA,IAAe,KAAA,IACd,KAAA,CAAuB,SAAA,KAAc,IAAA,IACtC,GAAA,IAAO,KAAA,IACP,GAAA,IAAO,SACP,GAAA,IAAO,KAAA;AAEX;;;ACqGA,SAAS,YAAA,CACP,GAAA,EACA,UAAA,EACA,QAAA,EACA,eAAuB,CAAA,EACE;AACzB,EAAA,IAAI,YAAA,IAAgB,UAAU,OAAO,GAAA;AAErC,EAAA,MAAM,WAAoC,EAAC;AAE3C,EAAA,KAAA,MAAW,CAAC,QAAA,EAAU,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AACnD,IAAA,MAAM,WAAA,GAAc,UAAA,CAAW,GAAA,CAAI,QAAQ,CAAA,IAAK,QAAA;AAEhD,IAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxB,MAAA,QAAA,CAAS,WAAW,CAAA,GAAI,KAAA,CAAM,GAAA,CAAI,CAAA,IAAA,KAAQ;AACxC,QAAA,IAAI,OAAO,SAAS,QAAA,IAAY,IAAA,KAAS,QAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,EAAG;AACrE,UAAA,OAAO,YAAA;AAAA,YACL,IAAA;AAAA,YACA,UAAA;AAAA,YACA,QAAA;AAAA,YACA,YAAA,GAAe;AAAA,WACjB;AAAA,QACF;AACA,QAAA,OAAO,IAAA;AAAA,MACT,CAAC,CAAA;AAAA,IACH,CAAA,MAAA,IAAW,OAAO,KAAA,KAAU,QAAA,IAAY,UAAU,IAAA,EAAM;AACtD,MAAA,QA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AAA,KAAmE;AAC5E,IAAA,MAAM,OAAA,GAAU,QAAA,CAAS,OAAA,GAAU,cAAc,CAAA,KAAM,MAAA;AAEvD,IAAA,IAAI,OAAA,IAAW,cAAA,CAAe,QAAA,CAAS,IAAI,CAAA,EAAG;AAC5C,MAAA,QAAA,CAAS,IAAA,GAAO,aAAA,CAAc,QAAA,CAAS,IAAI,CAAA;AAAA,IAC7C;AAEA,IAAA,OAAO,QAAA;AAAA,EACT;AACF;AAGA,IAAO,iBAAQ,EAAE,KAAA,EAAO,aAAa,MAAA,EAAQ,KAAA,EAAO,eAAe,OAAA","file":"client.js","sourcesContent":["/**\n * TerseJSON Types\n *\n * Defines the wire format and configuration options for transparent\n * JSON key compression.\n */\n\n/**\n * The compressed format sent over the wire\n */\nexport interface TersePayload<T = unknown> {\n /** Marker to identify this as a TerseJSON payload */\n __terse__: true;\n /** Version for future compatibility */\n v: 1;\n /** Key mapping: short key -> original key */\n k: Record<string, string>;\n /** The compressed data with short keys */\n d: T;\n /** Pattern used for key generation (for debugging/info) */\n p?: string;\n}\n\n/**\n * Built-in key pattern presets\n */\nexport type KeyPatternPreset =\n | 'alpha' // a, b, c, ... z, aa, ab (default)\n | 'numeric' // 0, 1, 2, ... 9, 10, 11\n | 'alphanumeric' // a1, a2, ... a9, b1, b2\n | 'short' // _, __, ___, a, b (shortest possible)\n | 'prefixed'; // k0, k1, k2 (with 'k' prefix)\n\n/**\n * Custom key generator function\n */\nexport type KeyGenerator = (index: number) => string;\n\n/**\n * Key pattern configuration\n */\nexport type KeyPattern =\n | KeyPatternPreset\n | { prefix: string; style?: 'numeric' | 'alpha' }\n | KeyGenerator;\n\n/**\n * How to handle nested structures\n */\nexport type NestedHandling =\n | 'deep' // Compress all nested objects/arrays (default)\n | 'shallow' // Only compress top-level array\n | 'arrays' // Only compress nested arrays, not single objects\n | number; // Specific depth limit (1 = shallow, Infinity = deep)\n\n/**\n * Compression options\n */\nexport interface CompressOptions {\n /**\n * Minimum key length to consider for compression\n * Keys shorter than this won't be shortened\n * @default 3\n */\n minKeyLength?: number;\n\n /**\n * Maximum depth to traverse for nested objects\n * @default 10\n */\n maxDepth?: number;\n\n /**\n * Key pattern to use for generating short keys\n * @default 'alpha'\n */\n keyPattern?: KeyPattern;\n\n /**\n * How to handle nested objects and arrays\n * @default 'deep'\n */\n nestedHandling?: NestedHandling;\n\n /**\n * Only compress keys that appear in all objects (homogeneous)\n * @default false\n */\n homogeneousOnly?: boolean;\n\n /**\n * Keys to always exclude from compression\n */\n excludeKeys?: string[];\n\n /**\n * Keys to always include in compression (even if short)\n */\n includeKeys?: string[];\n}\n\n/**\n * Configuration options for the Express middleware\n */\nexport interface TerseMiddlewareOptions extends CompressOptions {\n /**\n * Minimum array length to trigger compression\n * @default 2\n */\n minArrayLength?: number;\n\n /**\n * Custom function to determine if a response should be compressed\n * Return false to skip compression for specific responses\n */\n shouldCompress?: (data: unknown, req: unknown) => boolean;\n\n /**\n * Custom header name for signaling terse responses\n * @default 'x-terse-json'\n */\n headerName?: string;\n\n /**\n * Enable debug logging\n * @default false\n */\n debug?: boolean;\n}\n\n/**\n * Configuration options for the client\n */\nexport interface TerseClientOptions {\n /**\n * Custom header name to check for terse responses\n * @default 'x-terse-json'\n */\n headerName?: string;\n\n /**\n * Enable debug logging\n * @default false\n */\n debug?: boolean;\n\n /**\n * Automatically expand terse responses\n * @default true\n */\n autoExpand?: boolean;\n}\n\n/**\n * Type helper to preserve original types through compression\n */\nexport type Tersed<T> = T;\n\n/**\n * Check if a value is a TersePayload\n */\nexport function isTersePayload(value: unknown): value is TersePayload {\n return (\n typeof value === 'object' &&\n value !== null &&\n '__terse__' in value &&\n (value as TersePayload).__terse__ === true &&\n 'v' in value &&\n 'k' in value &&\n 'd' in value\n );\n}\n","/**\n * TerseJSON Core\n *\n * The core compression and expansion algorithms.\n */\n\nimport {\n TersePayload,\n isTersePayload,\n KeyPattern,\n KeyGenerator,\n NestedHandling,\n CompressOptions,\n} from './types';\n\n// ============================================================================\n// KEY PATTERN GENERATORS\n// ============================================================================\n\n/**\n * Alpha pattern: a, b, c, ... z, aa, ab, ...\n */\nfunction alphaGenerator(index: number): string {\n let key = '';\n let remaining = index;\n\n do {\n key = String.fromCharCode(97 + (remaining % 26)) + key;\n remaining = Math.floor(remaining / 26) - 1;\n } while (remaining >= 0);\n\n return key;\n}\n\n/**\n * Numeric pattern: 0, 1, 2, ... 9, 10, 11, ...\n */\nfunction numericGenerator(index: number): string {\n return String(index);\n}\n\n/**\n * Alphanumeric pattern: a1, a2, ... a9, b1, b2, ...\n */\nfunction alphanumericGenerator(index: number): string {\n const letterIndex = Math.floor(index / 9);\n const numIndex = (index % 9) + 1;\n return alphaGenerator(letterIndex) + numIndex;\n}\n\n/**\n * Short pattern: uses shortest possible keys\n * _, a, b, ..., z, aa, ab, ...\n */\nfunction shortGenerator(index: number): string {\n if (index === 0) return '_';\n return alphaGenerator(index - 1);\n}\n\n/**\n * Prefixed pattern: k0, k1, k2, ...\n */\nfunction prefixedGenerator(prefix: string, style: 'numeric' | 'alpha' = 'numeric'): KeyGenerator {\n return (index: number) => {\n if (style === 'alpha') {\n return prefix + alphaGenerator(index);\n }\n return prefix + index;\n };\n}\n\n/**\n * Creates a key generator from a pattern configuration\n */\nexport function createKeyGenerator(pattern: KeyPattern): { generator: KeyGenerator; name: string } {\n // If it's already a function, use it directly\n if (typeof pattern === 'function') {\n return { generator: pattern, name: 'custom' };\n }\n\n // If it's a preset string\n if (typeof pattern === 'string') {\n switch (pattern) {\n case 'alpha':\n return { generator: alphaGenerator, name: 'alpha' };\n case 'numeric':\n return { generator: numericGenerator, name: 'numeric' };\n case 'alphanumeric':\n return { generator: alphanumericGenerator, name: 'alphanumeric' };\n case 'short':\n return { generator: shortGenerator, name: 'short' };\n case 'prefixed':\n return { generator: prefixedGenerator('k'), name: 'prefixed:k' };\n default:\n return { generator: alphaGenerator, name: 'alpha' };\n }\n }\n\n // If it's a prefix config object\n if (typeof pattern === 'object' && 'prefix' in pattern) {\n return {\n generator: prefixedGenerator(pattern.prefix, pattern.style || 'numeric'),\n name: `prefixed:${pattern.prefix}`,\n };\n }\n\n return { generator: alphaGenerator, name: 'alpha' };\n}\n\n/**\n * Resolves nested handling to a numeric depth\n */\nfunction resolveNestedDepth(handling: NestedHandling | undefined, maxDepth: number): number {\n if (handling === undefined || handling === 'deep') {\n return maxDepth;\n }\n if (handling === 'shallow') {\n return 1;\n }\n if (handling === 'arrays') {\n return maxDepth; // Special handling in collect/compress functions\n }\n if (typeof handling === 'number') {\n return handling;\n }\n return maxDepth;\n}\n\n// Legacy generateShortKey removed - use createKeyGenerator instead\n\ninterface CollectKeysOptions {\n minKeyLength: number;\n maxDepth: number;\n nestedHandling: NestedHandling;\n excludeKeys?: string[];\n includeKeys?: string[];\n homogeneousOnly?: boolean;\n}\n\n/**\n * Collects all unique keys from an array of objects\n */\nfunction collectKeys(\n data: Record<string, unknown>[],\n options: CollectKeysOptions,\n currentDepth: number = 0\n): Set<string> {\n const keys = new Set<string>();\n const { minKeyLength, maxDepth, nestedHandling, excludeKeys, includeKeys } = options;\n\n if (currentDepth >= maxDepth) return keys;\n\n // For homogeneous mode, track key counts\n const keyCounts = new Map<string, number>();\n\n for (const item of data) {\n if (typeof item !== 'object' || item === null) continue;\n\n for (const key of Object.keys(item)) {\n // Skip excluded keys\n if (excludeKeys?.includes(key)) continue;\n\n // Include if in includeKeys, or if meets minKeyLength\n const shouldInclude = includeKeys?.includes(key) || key.length >= minKeyLength;\n\n if (shouldInclude) {\n keys.add(key);\n keyCounts.set(key, (keyCounts.get(key) || 0) + 1);\n }\n\n // Handle nested structures based on nestedHandling option\n const value = item[key];\n\n if (nestedHandling === 'shallow') {\n // Don't process nested structures\n continue;\n }\n\n if (Array.isArray(value) && value.length > 0 && isCompressibleArray(value)) {\n // Nested array of objects - always process\n const nestedKeys = collectKeys(\n value as Record<string, unknown>[],\n options,\n currentDepth + 1\n );\n nestedKeys.forEach(k => keys.add(k));\n } else if (\n nestedHandling !== 'arrays' &&\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value)\n ) {\n // Single nested object - skip if nestedHandling is 'arrays'\n const nestedKeys = collectKeys(\n [value as Record<string, unknown>],\n options,\n currentDepth + 1\n );\n nestedKeys.forEach(k => keys.add(k));\n }\n }\n }\n\n // If homogeneous mode, only keep keys that appear in ALL objects\n if (options.homogeneousOnly && data.length > 0) {\n for (const [key, count] of keyCounts) {\n if (count < data.length) {\n keys.delete(key);\n }\n }\n }\n\n return keys;\n}\n\n/**\n * Checks if an array is compressible (array of objects with consistent structure)\n */\nexport function isCompressibleArray(data: unknown): data is Record<string, unknown>[] {\n if (!Array.isArray(data) || data.length === 0) return false;\n\n // Check if all items are objects\n return data.every(\n item => typeof item === 'object' && item !== null && !Array.isArray(item)\n );\n}\n\n/**\n * Compresses an object using the key mapping\n */\nfunction compressObject(\n obj: Record<string, unknown>,\n keyToShort: Map<string, string>,\n maxDepth: number,\n currentDepth: number = 0\n): Record<string, unknown> {\n if (currentDepth >= maxDepth) return obj;\n\n const compressed: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const shortKey = keyToShort.get(key) ?? key;\n\n if (Array.isArray(value) && isCompressibleArray(value)) {\n // Recursively compress nested arrays\n compressed[shortKey] = value.map(item =>\n compressObject(\n item as Record<string, unknown>,\n keyToShort,\n maxDepth,\n currentDepth + 1\n )\n );\n } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Compress single nested objects too\n compressed[shortKey] = compressObject(\n value as Record<string, unknown>,\n keyToShort,\n maxDepth,\n currentDepth + 1\n );\n } else {\n compressed[shortKey] = value;\n }\n }\n\n return compressed;\n}\n\n/**\n * Expands an object using the key mapping\n */\nfunction expandObject(\n obj: Record<string, unknown>,\n shortToKey: Map<string, string>,\n maxDepth: number,\n currentDepth: number = 0\n): Record<string, unknown> {\n if (currentDepth >= maxDepth) return obj;\n\n const expanded: Record<string, unknown> = {};\n\n for (const [shortKey, value] of Object.entries(obj)) {\n const originalKey = shortToKey.get(shortKey) ?? shortKey;\n\n if (Array.isArray(value)) {\n expanded[originalKey] = value.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return expandObject(\n item as Record<string, unknown>,\n shortToKey,\n maxDepth,\n currentDepth + 1\n );\n }\n return item;\n });\n } else if (typeof value === 'object' && value !== null) {\n expanded[originalKey] = expandObject(\n value as Record<string, unknown>,\n shortToKey,\n maxDepth,\n currentDepth + 1\n );\n } else {\n expanded[originalKey] = value;\n }\n }\n\n return expanded;\n}\n\n// Re-export CompressOptions from types for backwards compatibility\nexport type { CompressOptions } from './types';\n\n/**\n * Compresses an array of objects by replacing keys with short aliases\n */\nexport function compress<T extends Record<string, unknown>[]>(\n data: T,\n options: CompressOptions = {}\n): TersePayload<unknown[]> {\n const {\n minKeyLength = 3,\n maxDepth = 10,\n keyPattern = 'alpha',\n nestedHandling = 'deep',\n homogeneousOnly = false,\n excludeKeys,\n includeKeys,\n } = options;\n\n // Create key generator\n const { generator, name: patternName } = createKeyGenerator(keyPattern);\n\n // Resolve nested depth\n const effectiveDepth = resolveNestedDepth(nestedHandling, maxDepth);\n\n // Collect all unique keys\n const allKeys = collectKeys(data, {\n minKeyLength,\n maxDepth: effectiveDepth,\n nestedHandling,\n excludeKeys,\n includeKeys,\n homogeneousOnly,\n });\n\n // Sort keys by frequency of use (most used first) for optimal compression\n // For now, just sort alphabetically for deterministic output\n const sortedKeys = Array.from(allKeys).sort();\n\n // Create bidirectional mapping\n const keyToShort = new Map<string, string>();\n const keyMap: Record<string, string> = {};\n\n sortedKeys.forEach((key, index) => {\n const shortKey = generator(index);\n // Only use short key if it's actually shorter\n if (shortKey.length < key.length) {\n keyToShort.set(key, shortKey);\n keyMap[shortKey] = key;\n }\n });\n\n // Compress the data\n const compressed = data.map(item =>\n compressObject(item, keyToShort, effectiveDepth)\n );\n\n return {\n __terse__: true,\n v: 1,\n k: keyMap,\n d: compressed,\n p: patternName,\n };\n}\n\n/**\n * Expands a TersePayload back to its original form\n */\nexport function expand<T = unknown>(payload: TersePayload): T {\n const shortToKey = new Map(\n Object.entries(payload.k).map(([short, original]) => [short, original])\n );\n\n if (Array.isArray(payload.d)) {\n return payload.d.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return expandObject(item as Record<string, unknown>, shortToKey, 10);\n }\n return item;\n }) as T;\n }\n\n if (typeof payload.d === 'object' && payload.d !== null) {\n return expandObject(payload.d as Record<string, unknown>, shortToKey, 10) as T;\n }\n\n return payload.d as T;\n}\n\n/**\n * Creates a Proxy that transparently maps original keys to short keys\n * This is the magic that makes client-side access seamless\n */\nexport function createTerseProxy<T extends Record<string, unknown>>(\n compressed: Record<string, unknown>,\n keyMap: Record<string, string> // short -> original\n): T {\n // Create reverse map: original -> short\n const originalToShort = new Map(\n Object.entries(keyMap).map(([short, original]) => [original, short])\n );\n\n const handler: ProxyHandler<Record<string, unknown>> = {\n get(target, prop: string | symbol) {\n if (typeof prop === 'symbol') {\n return Reflect.get(target, prop);\n }\n\n // Check if accessing by original key name\n const shortKey = originalToShort.get(prop);\n const actualKey = shortKey ?? prop;\n const value = target[actualKey];\n\n // Recursively proxy nested objects/arrays\n if (Array.isArray(value)) {\n return value.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return createTerseProxy(item as Record<string, unknown>, keyMap);\n }\n return item;\n });\n }\n\n if (typeof value === 'object' && value !== null) {\n return createTerseProxy(value as Record<string, unknown>, keyMap);\n }\n\n return value;\n },\n\n has(target, prop: string | symbol) {\n if (typeof prop === 'symbol') {\n return Reflect.has(target, prop);\n }\n const shortKey = originalToShort.get(prop);\n return (shortKey ?? prop) in target;\n },\n\n ownKeys(target) {\n // Return original key names\n return Object.keys(target).map(shortKey => keyMap[shortKey] ?? shortKey);\n },\n\n getOwnPropertyDescriptor(target, prop: string | symbol) {\n if (typeof prop === 'symbol') {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n }\n const shortKey = originalToShort.get(prop);\n const actualKey = shortKey ?? prop;\n const descriptor = Object.getOwnPropertyDescriptor(target, actualKey);\n if (descriptor) {\n return { ...descriptor, enumerable: true, configurable: true };\n }\n return undefined;\n },\n };\n\n return new Proxy(compressed, handler) as T;\n}\n\n/**\n * Wraps TersePayload data with Proxies for transparent access\n */\nexport function wrapWithProxy<T>(payload: TersePayload): T {\n if (Array.isArray(payload.d)) {\n return payload.d.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return createTerseProxy(item as Record<string, unknown>, payload.k);\n }\n return item;\n }) as T;\n }\n\n if (typeof payload.d === 'object' && payload.d !== null) {\n return createTerseProxy(payload.d as Record<string, unknown>, payload.k) as T;\n }\n\n return payload.d as T;\n}\n\n// Re-export for convenience\nexport { isTersePayload };\n","/**\n * TerseJSON Client\n *\n * Transparent client-side handling of TerseJSON responses.\n * Use the fetch wrapper or manually expand responses.\n */\n\nimport {\n TerseClientOptions,\n isTersePayload,\n} from './types';\nimport { expand, wrapWithProxy } from './core';\n\nconst DEFAULT_OPTIONS: Required<TerseClientOptions> = {\n headerName: 'x-terse-json',\n debug: false,\n autoExpand: true,\n};\n\n/**\n * Expands a TerseJSON payload back to original format\n * Use this if you want full expansion (not proxied)\n */\nexport { expand };\n\n/**\n * Wraps a TerseJSON payload with Proxy for transparent key access\n * More memory efficient than full expansion for large datasets\n */\nexport { wrapWithProxy as proxy };\n\n/**\n * Check if a response/data is a TerseJSON payload\n */\nexport { isTersePayload };\n\n/**\n * Process a potential TerseJSON response\n * Automatically detects and expands/proxies terse payloads\n */\nexport function process<T = unknown>(\n data: unknown,\n options: { useProxy?: boolean } = {}\n): T {\n const { useProxy = true } = options;\n\n if (isTersePayload(data)) {\n return useProxy ? wrapWithProxy<T>(data) : expand<T>(data);\n }\n\n return data as T;\n}\n\n/**\n * Creates a fetch wrapper that automatically handles TerseJSON responses\n *\n * @example\n * ```typescript\n * import { createFetch } from 'tersejson/client';\n *\n * const fetch = createFetch();\n *\n * // Use exactly like regular fetch\n * const users = await fetch('/api/users').then(r => r.json());\n * console.log(users[0].firstName); // Works transparently!\n * ```\n */\nexport function createFetch(options: TerseClientOptions = {}): typeof globalThis.fetch {\n const config = { ...DEFAULT_OPTIONS, ...options };\n\n return async function terseFetch(\n input: RequestInfo | URL,\n init: RequestInit = {}\n ): Promise<Response> {\n // Add header to indicate we accept terse responses\n const headers = new Headers(init.headers);\n headers.set('accept-terse', 'true');\n\n const response = await globalThis.fetch(input, {\n ...init,\n headers,\n });\n\n // Check if response is terse\n const isTerse = response.headers.get(config.headerName) === 'true';\n\n if (!isTerse || !config.autoExpand) {\n return response;\n }\n\n // Clone response and override json() method\n const clonedResponse = response.clone();\n\n // Create a wrapper that intercepts .json()\n return new Proxy(response, {\n get(target, prop) {\n if (prop === 'json') {\n return async function (): Promise<unknown> {\n const data = await clonedResponse.json();\n\n if (isTersePayload(data)) {\n if (config.debug) {\n console.log('[tersejson] Expanding terse response');\n }\n return wrapWithProxy(data);\n }\n\n return data;\n };\n }\n\n const value = Reflect.get(target, prop);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n };\n}\n\n/**\n * Drop-in fetch replacement with TerseJSON support\n *\n * @example\n * ```typescript\n * import { fetch } from 'tersejson/client';\n *\n * const users = await fetch('/api/users').then(r => r.json());\n * console.log(users[0].firstName); // Transparent!\n * ```\n */\nexport const fetch = createFetch();\n\n/**\n * React hook for fetching with TerseJSON support (if using React)\n * Returns a configured fetch function\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const terseFetch = useTerseFetch();\n * // Use in useEffect, etc.\n * }\n * ```\n */\nexport function useTerseFetch(options: TerseClientOptions = {}): typeof globalThis.fetch {\n // This is a simple hook that just returns the configured fetch\n // Could be extended with caching, SWR integration, etc.\n return createFetch(options);\n}\n\n/**\n * Axios interceptor for TerseJSON support\n *\n * @example\n * ```typescript\n * import axios from 'axios';\n * import { axiosInterceptor } from 'tersejson/client';\n *\n * axios.interceptors.request.use(axiosInterceptor.request);\n * axios.interceptors.response.use(axiosInterceptor.response);\n * ```\n */\nexport const axiosInterceptor = {\n request: (config: { headers?: Record<string, string> }) => {\n config.headers = config.headers || {};\n config.headers['accept-terse'] = 'true';\n return config;\n },\n\n response: (response: { headers?: Record<string, string>; data?: unknown }) => {\n const isTerse = response.headers?.['x-terse-json'] === 'true';\n\n if (isTerse && isTersePayload(response.data)) {\n response.data = wrapWithProxy(response.data);\n }\n\n return response;\n },\n};\n\n// Default export for convenience\nexport default { fetch, createFetch, expand, proxy: wrapWithProxy, process };\n"]}
|