@contractspec/example.integration-posthog 1.57.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/dist/run.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/run.js ADDED
@@ -0,0 +1,12 @@
1
+ import { runPosthogExampleFromEnv } from "./posthog.js";
2
+
3
+ //#region src/run.ts
4
+ runPosthogExampleFromEnv().then((result) => {
5
+ console.log(JSON.stringify(result, null, 2));
6
+ }).catch((error) => {
7
+ console.error(error);
8
+ process.exitCode = 1;
9
+ });
10
+
11
+ //#endregion
12
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","names":[],"sources":["../src/run.ts"],"sourcesContent":["import { runPosthogExampleFromEnv } from './posthog';\n\nrunPosthogExampleFromEnv()\n .then((result) => {\n console.log(JSON.stringify(result, null, 2));\n })\n .catch((error) => {\n console.error(error);\n process.exitCode = 1;\n });\n"],"mappings":";;;AAEA,0BAA0B,CACvB,MAAM,WAAW;AAChB,SAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC;EAC5C,CACD,OAAO,UAAU;AAChB,SAAQ,MAAM,MAAM;AACpB,SAAQ,WAAW;EACnB"}
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@contractspec/example.integration-posthog",
3
+ "version": "1.57.0",
4
+ "description": "PostHog analytics integration example: capture events, run HogQL, and manage feature flags.",
5
+ "type": "module",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": "./dist/index.js",
9
+ "./docs": "./dist/docs/index.js",
10
+ "./docs/integration-posthog.docblock": "./dist/docs/integration-posthog.docblock.js",
11
+ "./example": "./dist/example.js",
12
+ "./posthog": "./dist/posthog.js",
13
+ "./run": "./dist/run.js",
14
+ "./*": "./*"
15
+ },
16
+ "scripts": {
17
+ "publish:pkg": "bun publish --tolerate-republish --ignore-scripts --verbose",
18
+ "publish:pkg:canary": "bun publish:pkg --tag canary",
19
+ "build": "bun build:types && bun build:bundle",
20
+ "build:bundle": "tsdown",
21
+ "build:types": "tsc --noEmit",
22
+ "dev": "bun build:bundle --watch",
23
+ "clean": "rimraf dist .turbo",
24
+ "lint": "bun lint:fix",
25
+ "lint:fix": "eslint src --fix",
26
+ "lint:check": "eslint src",
27
+ "test": "bun test"
28
+ },
29
+ "dependencies": {
30
+ "@contractspec/integration.providers-impls": "1.57.0",
31
+ "@contractspec/lib.contracts": "1.57.0"
32
+ },
33
+ "devDependencies": {
34
+ "@contractspec/tool.tsdown": "1.57.0",
35
+ "@contractspec/tool.typescript": "1.57.0",
36
+ "tsdown": "^0.20.3",
37
+ "typescript": "^5.9.3"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public",
41
+ "exports": {
42
+ ".": "./dist/index.js",
43
+ "./docs": "./dist/docs/index.js",
44
+ "./docs/integration-posthog.docblock": "./dist/docs/integration-posthog.docblock.js",
45
+ "./example": "./dist/example.js",
46
+ "./posthog": "./dist/posthog.js",
47
+ "./run": "./dist/run.js",
48
+ "./*": "./*"
49
+ },
50
+ "registry": "https://registry.npmjs.org/"
51
+ },
52
+ "license": "MIT",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "https://github.com/lssm-tech/contractspec.git",
56
+ "directory": "packages/examples/integration-posthog"
57
+ },
58
+ "homepage": "https://contractspec.io"
59
+ }
@@ -0,0 +1 @@
1
+ import './integration-posthog.docblock';
@@ -0,0 +1,53 @@
1
+ import type { DocBlock } from '@contractspec/lib.contracts/docs';
2
+ import { registerDocBlocks } from '@contractspec/lib.contracts/docs';
3
+
4
+ const blocks: DocBlock[] = [
5
+ {
6
+ id: 'docs.examples.integration-posthog',
7
+ title: 'Integration Example — PostHog Analytics',
8
+ summary:
9
+ 'Capture events, run HogQL, and manage feature flags using the PostHog analytics provider.',
10
+ kind: 'reference',
11
+ visibility: 'public',
12
+ route: '/docs/examples/integration-posthog',
13
+ tags: ['posthog', 'analytics', 'hogql', 'example'],
14
+ body: `## What this example shows
15
+ - Capture product events and identify users.
16
+ - Run HogQL queries through the analytics provider.
17
+ - Perform generic REST API requests (feature flag list/create/delete).
18
+ - Read events, persons, insights, and feature flags using typed reader methods.
19
+ - Optionally call a PostHog MCP tool via JSON-RPC.
20
+
21
+ ## Guardrails
22
+ - Use dry-run while validating credentials.
23
+ - Writes are gated behind CONTRACTSPEC_POSTHOG_ALLOW_WRITES.
24
+ - Keep API keys in secret storage.`,
25
+ },
26
+ {
27
+ id: 'docs.examples.integration-posthog.usage',
28
+ title: 'PostHog Integration Example — Usage',
29
+ summary: 'How to run the PostHog example with env-driven settings.',
30
+ kind: 'usage',
31
+ visibility: 'public',
32
+ route: '/docs/examples/integration-posthog/usage',
33
+ tags: ['posthog', 'usage'],
34
+ body: `## Usage
35
+ - Set CONTRACTSPEC_POSTHOG_MODE to capture | query | request | read | all.
36
+ - Set CONTRACTSPEC_POSTHOG_DRY_RUN=true for a safe preview.
37
+ - Set CONTRACTSPEC_POSTHOG_ALLOW_WRITES=true to enable capture and create/delete.
38
+
39
+ ## Required env vars
40
+ - POSTHOG_PROJECT_ID for queries and REST requests.
41
+ - POSTHOG_PROJECT_API_KEY for capture/identify.
42
+ - POSTHOG_PERSONAL_API_KEY for HogQL queries and REST requests.
43
+
44
+ ## MCP
45
+ - Set POSTHOG_MCP_URL to call tools/call.
46
+ - Optionally set POSTHOG_MCP_TOOL_NAME and POSTHOG_MCP_TOOL_ARGS (JSON).
47
+
48
+ ## Example
49
+ - Call runPosthogExampleFromEnv() from run.ts to execute the flow.`,
50
+ },
51
+ ];
52
+
53
+ registerDocBlocks(blocks);
package/src/example.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { defineExample } from '@contractspec/lib.contracts';
2
+
3
+ const example = defineExample({
4
+ meta: {
5
+ key: 'integration-posthog',
6
+ version: '1.0.0',
7
+ title: 'Integration — PostHog Analytics',
8
+ description:
9
+ 'Capture events, run HogQL, and manage PostHog assets via AnalyticsProvider.',
10
+ kind: 'integration',
11
+ visibility: 'public',
12
+ stability: 'experimental',
13
+ owners: ['@platform.integrations'],
14
+ tags: ['posthog', 'analytics', 'hogql', 'integration'],
15
+ },
16
+ docs: {
17
+ rootDocId: 'docs.examples.integration-posthog',
18
+ usageDocId: 'docs.examples.integration-posthog.usage',
19
+ },
20
+ entrypoints: {
21
+ packageName: '@contractspec/example.integration-posthog',
22
+ docs: './docs',
23
+ },
24
+ surfaces: {
25
+ templates: true,
26
+ sandbox: { enabled: true, modes: ['markdown', 'specs'] },
27
+ studio: { enabled: true, installable: true },
28
+ mcp: { enabled: true },
29
+ },
30
+ });
31
+
32
+ export default example;
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './posthog';
2
+ export { default as example } from './example';
3
+ import './docs';
package/src/posthog.ts ADDED
@@ -0,0 +1,362 @@
1
+ import { PosthogAnalyticsProvider } from '@contractspec/integration.providers-impls/impls/posthog';
2
+ import type {
3
+ AnalyticsEventInput,
4
+ AnalyticsProvider,
5
+ AnalyticsQueryResult,
6
+ AnalyticsRequest,
7
+ AnalyticsResponse,
8
+ } from '@contractspec/integration.providers-impls/analytics';
9
+
10
+ export type PosthogExampleMode =
11
+ | 'capture'
12
+ | 'query'
13
+ | 'request'
14
+ | 'read'
15
+ | 'all';
16
+
17
+ export interface PosthogExampleOutput {
18
+ mode: PosthogExampleMode;
19
+ dryRun: boolean;
20
+ allowWrites: boolean;
21
+ capture?: unknown;
22
+ query?: AnalyticsQueryResult | unknown;
23
+ request?: Record<string, unknown>;
24
+ read?: Record<string, unknown>;
25
+ mcp?: unknown;
26
+ }
27
+
28
+ export async function runPosthogExampleFromEnv(): Promise<PosthogExampleOutput> {
29
+ const mode = resolvePosthogMode();
30
+ const dryRun = resolveBooleanEnv('CONTRACTSPEC_POSTHOG_DRY_RUN', true);
31
+ const allowWrites = resolveBooleanEnv(
32
+ 'CONTRACTSPEC_POSTHOG_ALLOW_WRITES',
33
+ false
34
+ );
35
+ const output: PosthogExampleOutput = { mode, dryRun, allowWrites };
36
+
37
+ if (dryRun) {
38
+ if (mode === 'capture' || mode === 'all') {
39
+ output.capture = buildCapturePreview();
40
+ }
41
+ if (mode === 'query' || mode === 'all') {
42
+ output.query = { query: buildHogQLQuery() };
43
+ }
44
+ if (mode === 'request' || mode === 'all') {
45
+ output.request = buildRequestPreview();
46
+ }
47
+ if (mode === 'read' || mode === 'all') {
48
+ output.read = buildReadPreview();
49
+ }
50
+ if (process.env.POSTHOG_MCP_URL) {
51
+ output.mcp = buildMcpPreview();
52
+ }
53
+ return output;
54
+ }
55
+
56
+ const provider = createProviderFromEnv();
57
+
58
+ if (mode === 'capture' || mode === 'all') {
59
+ output.capture = await runCapture(provider, allowWrites);
60
+ }
61
+
62
+ if (mode === 'query' || mode === 'all') {
63
+ output.query = await runHogQLQuery(provider);
64
+ }
65
+
66
+ if (mode === 'request' || mode === 'all') {
67
+ output.request = await runApiRequests(provider, allowWrites);
68
+ }
69
+
70
+ if (mode === 'read' || mode === 'all') {
71
+ output.read = await runReadOperations(provider);
72
+ }
73
+
74
+ if (process.env.POSTHOG_MCP_URL) {
75
+ output.mcp = await runMcpToolCall(provider);
76
+ }
77
+
78
+ return output;
79
+ }
80
+
81
+ export function resolvePosthogMode(): PosthogExampleMode {
82
+ const raw = (process.env.CONTRACTSPEC_POSTHOG_MODE ?? 'all').toLowerCase();
83
+ if (
84
+ raw === 'capture' ||
85
+ raw === 'query' ||
86
+ raw === 'request' ||
87
+ raw === 'read' ||
88
+ raw === 'all'
89
+ ) {
90
+ return raw;
91
+ }
92
+ throw new Error(
93
+ `Unsupported CONTRACTSPEC_POSTHOG_MODE: ${raw}. Use capture, query, request, read, or all.`
94
+ );
95
+ }
96
+
97
+ function createProviderFromEnv(): AnalyticsProvider {
98
+ return new PosthogAnalyticsProvider({
99
+ host: process.env.POSTHOG_HOST,
100
+ projectId: process.env.POSTHOG_PROJECT_ID,
101
+ projectApiKey: process.env.POSTHOG_PROJECT_API_KEY,
102
+ personalApiKey: process.env.POSTHOG_PERSONAL_API_KEY,
103
+ mcpUrl: process.env.POSTHOG_MCP_URL,
104
+ requestTimeoutMs: 10000,
105
+ });
106
+ }
107
+
108
+ async function runCapture(
109
+ provider: AnalyticsProvider,
110
+ allowWrites: boolean
111
+ ): Promise<Record<string, unknown>> {
112
+ if (!allowWrites) {
113
+ return {
114
+ skipped: true,
115
+ reason: 'Set CONTRACTSPEC_POSTHOG_ALLOW_WRITES=true to enable capture.',
116
+ };
117
+ }
118
+
119
+ const event = buildCaptureEvent();
120
+ if (provider.identify) {
121
+ await provider.identify({
122
+ distinctId: event.distinctId,
123
+ properties: { plan: 'pro', source: 'contractspec-example' },
124
+ });
125
+ }
126
+ await provider.capture(event);
127
+ return { captured: true, event };
128
+ }
129
+
130
+ async function runHogQLQuery(
131
+ provider: AnalyticsProvider
132
+ ): Promise<AnalyticsQueryResult> {
133
+ if (!provider.queryHogQL) {
134
+ throw new Error('Analytics provider does not support HogQL queries.');
135
+ }
136
+ const query = buildHogQLQuery();
137
+ return provider.queryHogQL({ query });
138
+ }
139
+
140
+ async function runApiRequests(
141
+ provider: AnalyticsProvider,
142
+ allowWrites: boolean
143
+ ): Promise<Record<string, unknown>> {
144
+ const projectId = requireEnv('POSTHOG_PROJECT_ID');
145
+ const listRequest: AnalyticsRequest = {
146
+ method: 'GET',
147
+ path: `/api/projects/${projectId}/feature_flags/`,
148
+ query: { limit: 5 },
149
+ };
150
+ const listResponse = await provider.request(listRequest);
151
+ const output: Record<string, unknown> = {
152
+ list: listResponse.data,
153
+ };
154
+
155
+ if (!allowWrites) {
156
+ output.writeGuard =
157
+ 'Set CONTRACTSPEC_POSTHOG_ALLOW_WRITES=true to create/delete feature flags.';
158
+ return output;
159
+ }
160
+
161
+ const flagKey = `contractspec-example-${Date.now()}`;
162
+ const createResponse = await provider.request({
163
+ method: 'POST',
164
+ path: `/api/projects/${projectId}/feature_flags/`,
165
+ body: {
166
+ name: 'ContractSpec Example Flag',
167
+ key: flagKey,
168
+ active: true,
169
+ filters: {
170
+ groups: [
171
+ {
172
+ properties: [],
173
+ rollout_percentage: 100,
174
+ },
175
+ ],
176
+ },
177
+ },
178
+ });
179
+ output.created = createResponse.data;
180
+
181
+ const createdId = extractId(createResponse);
182
+ if (createdId) {
183
+ const deleteResponse = await provider.request({
184
+ method: 'DELETE',
185
+ path: `/api/projects/${projectId}/feature_flags/${createdId}`,
186
+ });
187
+ output.deleted = deleteResponse.status;
188
+ } else {
189
+ output.deleted = 'Skipped delete: response did not include an id.';
190
+ }
191
+
192
+ return output;
193
+ }
194
+
195
+ async function runReadOperations(
196
+ provider: AnalyticsProvider
197
+ ): Promise<Record<string, unknown>> {
198
+ const now = new Date();
199
+ const from = new Date(now.getTime() - 24 * 60 * 60 * 1000);
200
+ const dateRange = { from, to: now };
201
+ const output: Record<string, unknown> = {
202
+ window: { from: from.toISOString(), to: now.toISOString() },
203
+ };
204
+
205
+ if (provider.getEvents) {
206
+ output.events = await provider.getEvents({ dateRange, limit: 5 });
207
+ } else {
208
+ output.events = 'Provider does not support getEvents.';
209
+ }
210
+
211
+ if (provider.getPersons) {
212
+ output.persons = await provider.getPersons({ limit: 5 });
213
+ } else {
214
+ output.persons = 'Provider does not support getPersons.';
215
+ }
216
+
217
+ if (provider.getInsights) {
218
+ output.insights = await provider.getInsights({ limit: 5 });
219
+ } else {
220
+ output.insights = 'Provider does not support getInsights.';
221
+ }
222
+
223
+ if (provider.getFeatureFlags) {
224
+ output.featureFlags = await provider.getFeatureFlags({ limit: 5 });
225
+ } else {
226
+ output.featureFlags = 'Provider does not support getFeatureFlags.';
227
+ }
228
+
229
+ return output;
230
+ }
231
+
232
+ async function runMcpToolCall(provider: AnalyticsProvider): Promise<unknown> {
233
+ if (!provider.callMcpTool) {
234
+ throw new Error('Analytics provider does not support MCP tool calls.');
235
+ }
236
+ const name = process.env.POSTHOG_MCP_TOOL_NAME ?? 'posthog.query';
237
+ const argumentsValue = parseOptionalJsonEnv('POSTHOG_MCP_TOOL_ARGS', {
238
+ query: buildHogQLQuery(),
239
+ });
240
+ return provider.callMcpTool({ name, arguments: argumentsValue });
241
+ }
242
+
243
+ function buildCaptureEvent(): AnalyticsEventInput {
244
+ const distinctId = process.env.POSTHOG_DISTINCT_ID ?? 'contractspec-demo';
245
+ const event = process.env.POSTHOG_EVENT_NAME ?? 'contractspec.example.event';
246
+ return {
247
+ distinctId,
248
+ event,
249
+ properties: {
250
+ source: 'contractspec-example',
251
+ environment: process.env.NODE_ENV ?? 'development',
252
+ },
253
+ timestamp: new Date(),
254
+ };
255
+ }
256
+
257
+ function buildHogQLQuery(): string {
258
+ return (
259
+ 'select event, count() as count ' +
260
+ 'from events ' +
261
+ 'where timestamp >= now() - interval 1 day ' +
262
+ 'group by event ' +
263
+ 'order by count desc ' +
264
+ 'limit 5'
265
+ );
266
+ }
267
+
268
+ function buildCapturePreview(): Record<string, unknown> {
269
+ return {
270
+ event: buildCaptureEvent(),
271
+ hint: 'Dry run enabled. Set CONTRACTSPEC_POSTHOG_DRY_RUN=false.',
272
+ };
273
+ }
274
+
275
+ function buildRequestPreview(): Record<string, unknown> {
276
+ const projectId = process.env.POSTHOG_PROJECT_ID ?? 'PROJECT_ID';
277
+ return {
278
+ listRequest: {
279
+ method: 'GET',
280
+ path: `/api/projects/${projectId}/feature_flags/`,
281
+ query: { limit: 5 },
282
+ },
283
+ writeRequests: {
284
+ create: {
285
+ method: 'POST',
286
+ path: `/api/projects/${projectId}/feature_flags/`,
287
+ },
288
+ delete: {
289
+ method: 'DELETE',
290
+ path: `/api/projects/${projectId}/feature_flags/{id}`,
291
+ },
292
+ },
293
+ };
294
+ }
295
+
296
+ function buildReadPreview(): Record<string, unknown> {
297
+ return {
298
+ events: {
299
+ dateRange: 'last_24_hours',
300
+ limit: 5,
301
+ },
302
+ persons: {
303
+ limit: 5,
304
+ },
305
+ insights: {
306
+ limit: 5,
307
+ },
308
+ featureFlags: {
309
+ limit: 5,
310
+ },
311
+ };
312
+ }
313
+
314
+ function buildMcpPreview(): Record<string, unknown> {
315
+ return {
316
+ url: process.env.POSTHOG_MCP_URL,
317
+ toolName: process.env.POSTHOG_MCP_TOOL_NAME ?? 'posthog.query',
318
+ arguments: parseOptionalJsonEnv('POSTHOG_MCP_TOOL_ARGS', {
319
+ query: buildHogQLQuery(),
320
+ }),
321
+ };
322
+ }
323
+
324
+ function extractId(
325
+ response: AnalyticsResponse<unknown>
326
+ ): string | number | null {
327
+ if (!response || typeof response !== 'object') return null;
328
+ const data = response.data as { id?: string | number } | null | undefined;
329
+ if (data && (typeof data.id === 'string' || typeof data.id === 'number')) {
330
+ return data.id;
331
+ }
332
+ return null;
333
+ }
334
+
335
+ function resolveBooleanEnv(key: string, defaultValue: boolean): boolean {
336
+ const value = process.env[key];
337
+ if (value === undefined) return defaultValue;
338
+ return value.toLowerCase() === 'true';
339
+ }
340
+
341
+ function requireEnv(key: string): string {
342
+ const value = process.env[key];
343
+ if (!value) {
344
+ throw new Error(`Missing required env var: ${key}`);
345
+ }
346
+ return value;
347
+ }
348
+
349
+ function parseOptionalJsonEnv(
350
+ key: string,
351
+ fallback: Record<string, unknown>
352
+ ): Record<string, unknown> {
353
+ const raw = process.env[key];
354
+ if (!raw) return fallback;
355
+ try {
356
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
357
+ if (parsed && typeof parsed === 'object') return parsed;
358
+ } catch {
359
+ throw new Error(`Invalid JSON in ${key}`);
360
+ }
361
+ return fallback;
362
+ }
package/src/run.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { runPosthogExampleFromEnv } from './posthog';
2
+
3
+ runPosthogExampleFromEnv()
4
+ .then((result) => {
5
+ console.log(JSON.stringify(result, null, 2));
6
+ })
7
+ .catch((error) => {
8
+ console.error(error);
9
+ process.exitCode = 1;
10
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "@contractspec/tool.typescript/react-library.json",
3
+ "include": ["src"],
4
+ "exclude": ["node_modules", "dist"],
5
+ "compilerOptions": {
6
+ "rootDir": "src",
7
+ "outDir": "dist"
8
+ }
9
+ }