gateproof 0.2.4 → 0.5.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.
Files changed (122) hide show
  1. package/README.md +1447 -153
  2. package/dist/cloudflare/index.d.ts +4 -6
  3. package/dist/cloudflare/index.d.ts.map +1 -1
  4. package/dist/cloudflare/index.js +9 -43
  5. package/dist/cloudflare/index.js.map +1 -1
  6. package/dist/index.d.ts +263 -75
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1327 -212
  9. package/dist/index.js.map +1 -1
  10. package/package.json +18 -48
  11. package/dist/act.d.ts +0 -78
  12. package/dist/act.d.ts.map +0 -1
  13. package/dist/act.js +0 -47
  14. package/dist/act.js.map +0 -1
  15. package/dist/action-executors.d.ts +0 -39
  16. package/dist/action-executors.d.ts.map +0 -1
  17. package/dist/action-executors.js +0 -195
  18. package/dist/action-executors.js.map +0 -1
  19. package/dist/assert.d.ts +0 -59
  20. package/dist/assert.d.ts.map +0 -1
  21. package/dist/assert.js +0 -120
  22. package/dist/assert.js.map +0 -1
  23. package/dist/authority.d.ts +0 -34
  24. package/dist/authority.d.ts.map +0 -1
  25. package/dist/authority.js +0 -141
  26. package/dist/authority.js.map +0 -1
  27. package/dist/cli/gateproof.d.ts +0 -3
  28. package/dist/cli/gateproof.d.ts.map +0 -1
  29. package/dist/cli/gateproof.js +0 -548
  30. package/dist/cli/gateproof.js.map +0 -1
  31. package/dist/cloudflare/analytics.d.ts +0 -9
  32. package/dist/cloudflare/analytics.d.ts.map +0 -1
  33. package/dist/cloudflare/analytics.js +0 -98
  34. package/dist/cloudflare/analytics.js.map +0 -1
  35. package/dist/cloudflare/cli-stream.d.ts +0 -7
  36. package/dist/cloudflare/cli-stream.d.ts.map +0 -1
  37. package/dist/cloudflare/cli-stream.js +0 -85
  38. package/dist/cloudflare/cli-stream.js.map +0 -1
  39. package/dist/cloudflare/polling-backend.d.ts +0 -18
  40. package/dist/cloudflare/polling-backend.d.ts.map +0 -1
  41. package/dist/cloudflare/polling-backend.js +0 -53
  42. package/dist/cloudflare/polling-backend.js.map +0 -1
  43. package/dist/cloudflare/workers-logs.d.ts +0 -9
  44. package/dist/cloudflare/workers-logs.d.ts.map +0 -1
  45. package/dist/cloudflare/workers-logs.js +0 -51
  46. package/dist/cloudflare/workers-logs.js.map +0 -1
  47. package/dist/constants.d.ts +0 -11
  48. package/dist/constants.d.ts.map +0 -1
  49. package/dist/constants.js +0 -11
  50. package/dist/constants.js.map +0 -1
  51. package/dist/filepath-backend.d.ts +0 -64
  52. package/dist/filepath-backend.d.ts.map +0 -1
  53. package/dist/filepath-backend.js +0 -126
  54. package/dist/filepath-backend.js.map +0 -1
  55. package/dist/filepath-protocol.d.ts +0 -214
  56. package/dist/filepath-protocol.d.ts.map +0 -1
  57. package/dist/filepath-protocol.js +0 -239
  58. package/dist/filepath-protocol.js.map +0 -1
  59. package/dist/filepath-runtime.d.ts +0 -100
  60. package/dist/filepath-runtime.d.ts.map +0 -1
  61. package/dist/filepath-runtime.js +0 -190
  62. package/dist/filepath-runtime.js.map +0 -1
  63. package/dist/http-backend.d.ts +0 -32
  64. package/dist/http-backend.d.ts.map +0 -1
  65. package/dist/http-backend.js +0 -166
  66. package/dist/http-backend.js.map +0 -1
  67. package/dist/observe.d.ts +0 -26
  68. package/dist/observe.d.ts.map +0 -1
  69. package/dist/observe.js +0 -84
  70. package/dist/observe.js.map +0 -1
  71. package/dist/prd/define-prd.d.ts +0 -7
  72. package/dist/prd/define-prd.d.ts.map +0 -1
  73. package/dist/prd/define-prd.js +0 -8
  74. package/dist/prd/define-prd.js.map +0 -1
  75. package/dist/prd/index.d.ts +0 -7
  76. package/dist/prd/index.d.ts.map +0 -1
  77. package/dist/prd/index.js +0 -8
  78. package/dist/prd/index.js.map +0 -1
  79. package/dist/prd/loop.d.ts +0 -160
  80. package/dist/prd/loop.d.ts.map +0 -1
  81. package/dist/prd/loop.js +0 -462
  82. package/dist/prd/loop.js.map +0 -1
  83. package/dist/prd/runner.d.ts +0 -19
  84. package/dist/prd/runner.d.ts.map +0 -1
  85. package/dist/prd/runner.js +0 -253
  86. package/dist/prd/runner.js.map +0 -1
  87. package/dist/prd/scope-check.d.ts +0 -28
  88. package/dist/prd/scope-check.d.ts.map +0 -1
  89. package/dist/prd/scope-check.js +0 -135
  90. package/dist/prd/scope-check.js.map +0 -1
  91. package/dist/prd/scope-defaults.d.ts +0 -75
  92. package/dist/prd/scope-defaults.d.ts.map +0 -1
  93. package/dist/prd/scope-defaults.js +0 -235
  94. package/dist/prd/scope-defaults.js.map +0 -1
  95. package/dist/prd/types.d.ts +0 -101
  96. package/dist/prd/types.d.ts.map +0 -1
  97. package/dist/prd/types.js +0 -2
  98. package/dist/prd/types.js.map +0 -1
  99. package/dist/provider.d.ts +0 -6
  100. package/dist/provider.d.ts.map +0 -1
  101. package/dist/provider.js +0 -2
  102. package/dist/provider.js.map +0 -1
  103. package/dist/report.d.ts +0 -137
  104. package/dist/report.d.ts.map +0 -1
  105. package/dist/report.js +0 -234
  106. package/dist/report.js.map +0 -1
  107. package/dist/test-helpers.d.ts +0 -12
  108. package/dist/test-helpers.d.ts.map +0 -1
  109. package/dist/test-helpers.js +0 -33
  110. package/dist/test-helpers.js.map +0 -1
  111. package/dist/types.d.ts +0 -41
  112. package/dist/types.d.ts.map +0 -1
  113. package/dist/types.js +0 -2
  114. package/dist/types.js.map +0 -1
  115. package/dist/utils.d.ts +0 -22
  116. package/dist/utils.d.ts.map +0 -1
  117. package/dist/utils.js +0 -49
  118. package/dist/utils.js.map +0 -1
  119. package/dist/validation.d.ts +0 -6
  120. package/dist/validation.d.ts.map +0 -1
  121. package/dist/validation.js +0 -38
  122. package/dist/validation.js.map +0 -1
@@ -1,548 +0,0 @@
1
- #!/usr/bin/env node
2
- import { existsSync } from "node:fs";
3
- import { readFile, writeFile } from "node:fs/promises";
4
- import { stdin, stdout } from "node:process";
5
- function printHelp() {
6
- const text = [
7
- "gateproof",
8
- "",
9
- "Subcommands:",
10
- " prdts Generate a prd.ts from story descriptions",
11
- " smoke Run gates once without agent loop (validate setup)",
12
- "",
13
- "Usage:",
14
- " npx gateproof prdts --in stories.txt --out prd.ts",
15
- " echo \"User can sign up\" | npx gateproof prdts --stdout",
16
- " npx gateproof smoke ./prd.ts",
17
- "",
18
- "Options (prdts):",
19
- " -i, --in <path> Input file with one story per line",
20
- " -o, --out <path> Output file path (default: ./prd.ts)",
21
- " --stdout Print the generated prd.ts to stdout",
22
- " --endpoint <url> API base URL (default: https://opencode.ai/zen/v1)",
23
- " --model <id> Model id (default: big-pickle)",
24
- " --api-key <key> API key (or set OPENCODE_ZEN_API_KEY)",
25
- " --overwrite Overwrite output file if it exists",
26
- "",
27
- "Options (smoke):",
28
- " --report <path> Write JSON report to path",
29
- " --check-scope Validate scope constraints against git diff",
30
- " --base-ref <ref> Git ref for scope checking (default: HEAD)",
31
- " --json Output results as JSON",
32
- "",
33
- " -h, --help Show help",
34
- ].join("\n");
35
- stdout.write(`${text}\n`);
36
- }
37
- function parseArgs(argv) {
38
- const args = {
39
- endpoint: "https://opencode.ai/zen/v1",
40
- model: "big-pickle",
41
- stdout: false,
42
- overwrite: false,
43
- checkScope: false,
44
- json: false,
45
- };
46
- if (argv.length > 0 && !argv[0].startsWith("-")) {
47
- args.subcommand = argv.shift();
48
- }
49
- // For smoke command, first non-flag arg is prd path
50
- let foundPrdPath = false;
51
- for (let i = 0; i < argv.length; i++) {
52
- const arg = argv[i];
53
- switch (arg) {
54
- case "--in":
55
- case "-i":
56
- args.inputPath = argv[++i];
57
- break;
58
- case "--out":
59
- case "-o":
60
- args.outputPath = argv[++i];
61
- break;
62
- case "--endpoint":
63
- args.endpoint = argv[++i];
64
- break;
65
- case "--model":
66
- args.model = argv[++i];
67
- break;
68
- case "--api-key":
69
- args.apiKey = argv[++i];
70
- break;
71
- case "--stdout":
72
- args.stdout = true;
73
- break;
74
- case "--overwrite":
75
- args.overwrite = true;
76
- break;
77
- case "--report":
78
- args.reportPath = argv[++i];
79
- break;
80
- case "--check-scope":
81
- args.checkScope = true;
82
- break;
83
- case "--base-ref":
84
- args.baseRef = argv[++i];
85
- break;
86
- case "--json":
87
- args.json = true;
88
- break;
89
- case "--help":
90
- case "-h":
91
- printHelp();
92
- process.exit(0);
93
- default:
94
- if (arg && arg.startsWith("-")) {
95
- throw new Error(`Unknown flag: ${arg}`);
96
- }
97
- // Positional argument - treat as prd path for smoke command
98
- if (!foundPrdPath && args.subcommand === "smoke") {
99
- args.prdPath = arg;
100
- foundPrdPath = true;
101
- }
102
- }
103
- }
104
- return args;
105
- }
106
- async function readStdin() {
107
- return new Promise((resolve, reject) => {
108
- let data = "";
109
- stdin.setEncoding("utf8");
110
- stdin.on("data", (chunk) => {
111
- data += chunk;
112
- });
113
- stdin.on("end", () => resolve(data));
114
- stdin.on("error", reject);
115
- });
116
- }
117
- async function getDescriptions(inputPath) {
118
- if (inputPath) {
119
- return readFile(inputPath, "utf8");
120
- }
121
- if (stdin.isTTY) {
122
- process.stderr.write("Paste story descriptions, then press Ctrl-D.\n");
123
- }
124
- return readStdin();
125
- }
126
- function stripCodeFences(text) {
127
- return text.replace(/```(?:json|ts|typescript)?/g, "").replace(/```/g, "").trim();
128
- }
129
- function extractJson(text) {
130
- const cleaned = stripCodeFences(text);
131
- try {
132
- return JSON.parse(cleaned);
133
- }
134
- catch {
135
- // Try to extract the first JSON object or array.
136
- const objectStart = cleaned.indexOf("{");
137
- const objectEnd = cleaned.lastIndexOf("}");
138
- if (objectStart !== -1 && objectEnd !== -1 && objectEnd > objectStart) {
139
- try {
140
- return JSON.parse(cleaned.slice(objectStart, objectEnd + 1));
141
- }
142
- catch {
143
- // continue
144
- }
145
- }
146
- const arrayStart = cleaned.indexOf("[");
147
- const arrayEnd = cleaned.lastIndexOf("]");
148
- if (arrayStart !== -1 && arrayEnd !== -1 && arrayEnd > arrayStart) {
149
- return JSON.parse(cleaned.slice(arrayStart, arrayEnd + 1));
150
- }
151
- throw new Error("Model response did not contain valid JSON.");
152
- }
153
- }
154
- function normalizePrd(input) {
155
- if (Array.isArray(input)) {
156
- return { stories: input };
157
- }
158
- if (input && typeof input === "object" && "prd" in input) {
159
- const prdValue = input.prd;
160
- if (prdValue && typeof prdValue === "object") {
161
- return prdValue;
162
- }
163
- }
164
- if (!input || typeof input !== "object")
165
- return input;
166
- const root = input;
167
- if (!Array.isArray(root.stories))
168
- return input;
169
- const normalizedStories = root.stories.map((story) => {
170
- if (!story || typeof story !== "object")
171
- return story;
172
- const s = story;
173
- const gateImplementation = s.gateImplementation ?? s.gateImplementationCode ?? s.gateImplementation_code;
174
- const dependsOn = s.dependsOn ?? s.depends_on;
175
- return {
176
- ...s,
177
- gateImplementation,
178
- dependsOn,
179
- };
180
- });
181
- return { ...root, stories: normalizedStories };
182
- }
183
- function coercePrd(input) {
184
- const normalized = normalizePrd(input);
185
- if (!normalized || typeof normalized !== "object") {
186
- throw new Error("PRD output must be an object.");
187
- }
188
- const storiesValue = normalized.stories;
189
- if (!Array.isArray(storiesValue)) {
190
- throw new Error("PRD output must include stories[].");
191
- }
192
- const stories = storiesValue.map((story, index) => {
193
- if (!story || typeof story !== "object") {
194
- throw new Error(`stories[${index}] must be an object.`);
195
- }
196
- const s = story;
197
- const id = s.id;
198
- const title = s.title;
199
- const gateImplementation = s.gateImplementation;
200
- const dependsOn = s.dependsOn;
201
- if (typeof id !== "string" || id.length === 0) {
202
- throw new Error(`stories[${index}].id must be a non-empty string.`);
203
- }
204
- if (typeof title !== "string" || title.length === 0) {
205
- throw new Error(`stories[${index}].title must be a non-empty string.`);
206
- }
207
- let code;
208
- if (typeof gateImplementation === "string") {
209
- code = gateImplementation;
210
- }
211
- else if (gateImplementation && typeof gateImplementation === "object") {
212
- const codeValue = gateImplementation.code;
213
- if (typeof codeValue === "string")
214
- code = codeValue;
215
- }
216
- if (!code) {
217
- throw new Error(`stories[${index}].gateImplementation.code must be a string.`);
218
- }
219
- let dependsOnArray;
220
- if (dependsOn !== undefined) {
221
- if (!Array.isArray(dependsOn)) {
222
- throw new Error(`stories[${index}].dependsOn must be an array of strings.`);
223
- }
224
- for (const dep of dependsOn) {
225
- if (typeof dep !== "string" || dep.length === 0) {
226
- throw new Error(`stories[${index}].dependsOn must be an array of strings.`);
227
- }
228
- }
229
- dependsOnArray = dependsOn;
230
- }
231
- return {
232
- id,
233
- title,
234
- gateImplementation: { code },
235
- ...(dependsOnArray ? { dependsOn: dependsOnArray } : {}),
236
- };
237
- });
238
- return { stories };
239
- }
240
- function buildPrompt(promptText) {
241
- return `Transform the following product prompt into a structured PRD object with inline gate implementations.
242
-
243
- Prompt:
244
- ${promptText}
245
-
246
- Requirements:
247
- 1. Generate kebab-case IDs for each story (e.g., "user-signup", "email-verification")
248
- 2. Create clear, descriptive titles
249
- 3. For each story, generate a complete gate implementation in the gateImplementation.code field
250
- 4. Gate implementations should:
251
- - Use createHttpObserveResource or createEmptyObserveResource for observation
252
- - Include appropriate Act actions (Act.wait, Act.browser, etc.)
253
- - Include Assert.custom or Assert.noErrors assertions
254
- - Be self-contained and runnable
255
- - Match the story's intent (e.g., if story is about API health, gate should check API endpoint)
256
- 5. Infer dependencies from the prompt (e.g., if a story mentions "depends on signup", add "user-signup" to dependsOn)
257
- 6. If dependencies are mentioned in natural language, map them to the appropriate story IDs
258
-
259
- For gate implementations, use this EXACT pattern (return the gate spec directly):
260
- \`\`\`
261
- import { Gate, Act, Assert, createHttpObserveResource, createEmptyObserveResource } from "gateproof";
262
-
263
- export function run() {
264
- return {
265
- name: "story-id",
266
- observe: createHttpObserveResource({ url: API_URL + "/endpoint", pollInterval: 500 }),
267
- act: [Act.wait(500)],
268
- assert: [
269
- Assert.custom("check_name", async (logs) => {
270
- const httpLog = logs.find(l => l.stage === "http");
271
- return httpLog?.status === "success";
272
- })
273
- ],
274
- stop: { idleMs: 1000, maxMs: 10000 }
275
- };
276
- }
277
- \`\`\`
278
-
279
- IMPORTANT: The gateImplementation.code field must contain COMPLETE, runnable TypeScript code that:
280
- - Imports necessary functions from "gateproof"
281
- - Exports a function called "run" that returns a gate spec object
282
- - Uses the configuration variables (API_URL, TEST_URL) defined at the top
283
- - Includes proper assertions that match the story's intent
284
-
285
- Return ONLY JSON in this shape (no markdown):
286
- {
287
- "stories": [
288
- {
289
- "id": "story-id",
290
- "title": "Story title",
291
- "gateImplementation": { "code": "TypeScript code string" },
292
- "dependsOn": ["optional-story-id"]
293
- }
294
- ]
295
- }`;
296
- }
297
- async function requestPrd(endpoint, model, apiKey, descriptions) {
298
- const response = await fetch(`${endpoint.replace(/\/$/, "")}/chat/completions`, {
299
- method: "POST",
300
- headers: {
301
- "Content-Type": "application/json",
302
- Authorization: `Bearer ${apiKey}`,
303
- },
304
- body: JSON.stringify({
305
- model,
306
- temperature: 0.2,
307
- max_tokens: 3200,
308
- messages: [
309
- {
310
- role: "user",
311
- content: buildPrompt(descriptions),
312
- },
313
- ],
314
- }),
315
- });
316
- if (!response.ok) {
317
- const text = await response.text();
318
- throw new Error(`Opencode request failed (${response.status}): ${text}`);
319
- }
320
- const data = (await response.json());
321
- const content = data.choices?.[0]?.message?.content;
322
- if (!content) {
323
- throw new Error("Opencode response did not include content.");
324
- }
325
- const json = extractJson(content);
326
- return coercePrd(json);
327
- }
328
- function formatPrdFile(prd) {
329
- const gateMap = prd.stories.map((story) => {
330
- const functionName = story.id.replace(/-/g, "_");
331
- let gateCode = story.gateImplementation.code;
332
- gateCode = gateCode.replace(/export\s+function\s+run\s*\(\)/g, `function ${functionName}Gate()`);
333
- gateCode = gateCode.replace(/export\s+/g, "");
334
- if (!gateCode.includes("return {")) {
335
- gateCode = gateCode.replace(/function\s+\w+Gate\(\)\s*\{/, `function ${functionName}Gate() {\n return`);
336
- }
337
- return { story, functionName, gateCode };
338
- });
339
- const gateFunctions = gateMap
340
- .map(({ story, gateCode }) => {
341
- return `// Gate: ${story.title}
342
- ${gateCode}
343
- `;
344
- })
345
- .join("\n");
346
- const gateMapObject = gateMap
347
- .map(({ story, functionName }) => {
348
- return ` "${story.id}": ${functionName}Gate,`;
349
- })
350
- .join("\n");
351
- return `#!/usr/bin/env bun
352
- /**
353
- * gateproof PRD - Single File
354
- *
355
- * Complete PRD with inline gate implementations.
356
- * Add your API keys/config at the top and run: bun run prd.ts
357
- */
358
-
359
- // ============================================================================
360
- // CONFIGURATION
361
- // ============================================================================
362
- const API_URL = process.env.API_URL || "https://your-api.com";
363
- const TEST_URL = process.env.TEST_URL || "http://localhost:3000";
364
-
365
- // ============================================================================
366
- // GATE IMPLEMENTATIONS
367
- // ============================================================================
368
-
369
- import { Gate, Act, Assert, createHttpObserveResource, createEmptyObserveResource } from "gateproof";
370
-
371
- ${gateFunctions}
372
-
373
- // ============================================================================
374
- // PRD DEFINITION & EXECUTION
375
- // ============================================================================
376
-
377
- const stories = [
378
- ${prd.stories
379
- .map((story) => {
380
- return ` {
381
- id: "${story.id}",
382
- title: "${story.title}",${story.dependsOn ? `\n dependsOn: [${story.dependsOn.map((id) => `"${id}"`).join(", ")}],` : ""}
383
- }`;
384
- })
385
- .join(",\n")}
386
- ];
387
-
388
- const gates: Record<string, () => ReturnType<typeof Gate.run> extends Promise<infer T> ? T : never> = {
389
- ${gateMapObject}
390
- };
391
-
392
- async function runPrd() {
393
- const byId = new Map(stories.map((s) => [s.id, s]));
394
- const executed = new Set<string>();
395
- const visiting = new Set<string>();
396
-
397
- function visit(id: string): string[] {
398
- if (visiting.has(id)) {
399
- throw new Error(\`Dependency cycle detected: \${id}\`);
400
- }
401
- if (executed.has(id)) {
402
- return [];
403
- }
404
-
405
- visiting.add(id);
406
- const story = byId.get(id);
407
- if (!story) {
408
- throw new Error(\`Unknown story: \${id}\`);
409
- }
410
-
411
- const order: string[] = [];
412
- for (const depId of story.dependsOn || []) {
413
- order.push(...visit(depId));
414
- }
415
-
416
- visiting.delete(id);
417
- executed.add(id);
418
- order.push(id);
419
- return order;
420
- }
421
-
422
- const executionOrder = stories.flatMap((s) => visit(s.id));
423
- const uniqueOrder = Array.from(new Set(executionOrder));
424
-
425
- for (const storyId of uniqueOrder) {
426
- const story = byId.get(storyId);
427
- if (!story) continue;
428
-
429
- console.log(\`\\n--- \${story.id}: \${story.title}\`);
430
- const gateFn = gates[storyId];
431
- if (!gateFn) {
432
- throw new Error(\`No gate implementation for story: \${storyId}\`);
433
- }
434
-
435
- const gateSpec = gateFn();
436
- const result = await Gate.run(gateSpec);
437
-
438
- if (result.status !== "success") {
439
- console.error(\`\\n❌ PRD failed at: \${story.id} - \${story.title}\`);
440
- if (result.error) {
441
- console.error(\`Error: \${result.error.message}\`);
442
- }
443
- process.exit(1);
444
- }
445
- }
446
-
447
- console.log("\\n✅ All PRD stories passed!");
448
- }
449
-
450
- if (import.meta.main) {
451
- runPrd().catch((error) => {
452
- console.error("Fatal error:", error);
453
- process.exit(1);
454
- });
455
- }
456
- `;
457
- }
458
- async function runPrdts(args) {
459
- const descriptions = (await getDescriptions(args.inputPath)).trim();
460
- if (!descriptions) {
461
- throw new Error("No story descriptions found.");
462
- }
463
- const apiKey = args.apiKey ?? process.env.OPENCODE_ZEN_API_KEY;
464
- if (!apiKey) {
465
- throw new Error("Missing OPENCODE_ZEN_API_KEY. Pass --api-key or set OPENCODE_ZEN_API_KEY.");
466
- }
467
- const prd = await requestPrd(args.endpoint, args.model, apiKey, descriptions);
468
- const prdFile = formatPrdFile(prd);
469
- if (args.stdout) {
470
- stdout.write(prdFile);
471
- return;
472
- }
473
- const outputPath = args.outputPath ?? "prd.ts";
474
- if (existsSync(outputPath) && !args.overwrite) {
475
- throw new Error(`Refusing to overwrite ${outputPath}. Use --overwrite to replace it.`);
476
- }
477
- await writeFile(outputPath, prdFile, "utf8");
478
- stdout.write(`✅ Wrote ${outputPath}\n`);
479
- }
480
- async function runSmoke(args) {
481
- const prdPath = args.prdPath ?? "prd.ts";
482
- if (!existsSync(prdPath)) {
483
- throw new Error(`PRD file not found: ${prdPath}`);
484
- }
485
- // Dynamic import the prd module
486
- const { runPrd } = await import("../prd/runner");
487
- const { resolve } = await import("node:path");
488
- // Load the PRD file
489
- const absolutePath = resolve(process.cwd(), prdPath);
490
- const mod = await import(`file://${absolutePath}`);
491
- let prd;
492
- if (mod.default && typeof mod.default === "object" && "stories" in mod.default) {
493
- prd = mod.default;
494
- }
495
- else if (mod.prd && typeof mod.prd === "object" && "stories" in mod.prd) {
496
- prd = mod.prd;
497
- }
498
- else {
499
- throw new Error(`PRD file must export 'prd' or a default object with 'stories': ${prdPath}`);
500
- }
501
- stdout.write(`\n🔥 Smoke test: ${prdPath}\n`);
502
- stdout.write(` Stories: ${prd.stories.length}\n`);
503
- stdout.write(` Scope check: ${args.checkScope ? "enabled" : "disabled"}\n\n`);
504
- const result = await runPrd(prd, process.cwd(), {
505
- reportPath: args.reportPath,
506
- checkScope: args.checkScope,
507
- baseRef: args.baseRef,
508
- });
509
- if (args.json) {
510
- stdout.write(JSON.stringify(result.report ?? { success: result.success }, null, 2) + "\n");
511
- }
512
- else if (result.success) {
513
- stdout.write(`\n✅ Smoke test passed! All ${prd.stories.length} gates green.\n`);
514
- }
515
- else {
516
- stdout.write(`\n❌ Smoke test failed at: ${result.failedStory?.id ?? "unknown"}\n`);
517
- if (result.error) {
518
- stdout.write(` Error: ${result.error.message}\n`);
519
- }
520
- process.exit(1);
521
- }
522
- }
523
- async function main() {
524
- try {
525
- const args = parseArgs(process.argv.slice(2));
526
- if (!args.subcommand || args.subcommand === "help") {
527
- printHelp();
528
- process.exit(0);
529
- }
530
- switch (args.subcommand) {
531
- case "prdts":
532
- await runPrdts(args);
533
- break;
534
- case "smoke":
535
- await runSmoke(args);
536
- break;
537
- default:
538
- throw new Error(`Unknown subcommand: ${args.subcommand}`);
539
- }
540
- }
541
- catch (error) {
542
- const message = error instanceof Error ? error.message : String(error);
543
- stdout.write(`❌ ${message}\n`);
544
- process.exit(1);
545
- }
546
- }
547
- void main();
548
- //# sourceMappingURL=gateproof.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"gateproof.js","sourceRoot":"","sources":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AAU,IAAI,IAAI,CAAC,UAAU,KAAK,MAAM,EAAE,CAAC;YACnD,SAAS,EAAE,CAAC;YACZ,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC;QAED,QAAQ,IAAI,CAAC,UAAU,EAAE,CAAC;YACxB,KAAK,OAAO;gBACV,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACrB,MAAM;YACR,KAAK,OAAO;gBACV,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACrB,MAAM;YACR;gBACE,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvE,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,IAAI,CAAC,CAAC;QAC/B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,KAAK,IAAI,EAAE,CAAC"}
@@ -1,9 +0,0 @@
1
- import { type Backend } from "../observe";
2
- export interface AnalyticsConfig {
3
- accountId: string;
4
- apiToken: string;
5
- dataset: string;
6
- pollInterval?: number;
7
- }
8
- export declare function createAnalyticsBackend(config: AnalyticsConfig): Backend;
9
- //# sourceMappingURL=analytics.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../src/cloudflare/analytics.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgD,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAGxF,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAgBD,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,eAAe,GACtB,OAAO,CA+GT"}
@@ -1,98 +0,0 @@
1
- import { Effect, Schedule, Ref } from "effect";
2
- import { createObservabilityError } from "../observe";
3
- import { createPollingBackend } from "./polling-backend";
4
- export function createAnalyticsBackend(config) {
5
- const cacheRef = Ref.unsafeMake(new Map());
6
- const CACHE_TTL = 5000;
7
- const lastRequestRef = Ref.unsafeMake(0);
8
- const MIN_REQUEST_INTERVAL = 100;
9
- const fetchRows = (lastTimestamp) => {
10
- const cacheKey = `${config.dataset}:${lastTimestamp}`;
11
- return Effect.gen(function* () {
12
- const cache = yield* Ref.get(cacheRef);
13
- const cached = cache.get(cacheKey);
14
- const now = Date.now();
15
- if (cached && (now - cached.timestamp) < CACHE_TTL) {
16
- return cached.data;
17
- }
18
- const query = `SELECT blob1 AS requestId, blob2 AS stage, blob3 AS action, blob4 AS status, blob5 AS durableObjectId, blob6 AS containerId, blob7 AS errorTag, blob8 AS errorMessage, blob9 AS data, double1 AS durationMs, double2 AS timestamp FROM ${config.dataset} WHERE double2 > ${lastTimestamp} ORDER BY double2 ASC LIMIT 100`;
19
- const response = yield* Effect.tryPromise({
20
- try: async () => {
21
- return await fetch(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}/analytics_engine/sql`, {
22
- method: "POST",
23
- headers: {
24
- Authorization: `Bearer ${config.apiToken}`,
25
- "Content-Type": "text/plain"
26
- },
27
- body: query
28
- });
29
- },
30
- catch: (e) => createObservabilityError(e)
31
- }).pipe(Effect.timeout("30 seconds"), Effect.retry(Schedule.exponential("100 millis").pipe(Schedule.compose(Schedule.recurs(3)))), Effect.catchTag("TimeoutException", (e) => Effect.fail(createObservabilityError(e))));
32
- if (!response.ok) {
33
- yield* Effect.fail(createObservabilityError(new Error(`API request failed: ${response.status}`)));
34
- }
35
- const data = yield* Effect.tryPromise({
36
- try: async () => (await response.json()),
37
- catch: (e) => createObservabilityError(e)
38
- });
39
- const rows = data.result && Array.isArray(data.result) ? data.result : [];
40
- yield* Ref.update(cacheRef, (cache) => {
41
- const newCache = new Map(cache);
42
- newCache.set(cacheKey, { data: rows, timestamp: now });
43
- if (newCache.size > 100) {
44
- const entries = Array.from(newCache.entries());
45
- entries.sort((a, b) => b[1].timestamp - a[1].timestamp);
46
- return new Map(entries.slice(0, 100));
47
- }
48
- return newCache;
49
- });
50
- return rows;
51
- });
52
- };
53
- const parseRow = (row) => {
54
- if (!row.timestamp || !row.requestId)
55
- return null;
56
- return {
57
- requestId: row.requestId,
58
- timestamp: new Date(row.timestamp).toISOString(),
59
- stage: (row.stage || "worker"),
60
- action: row.action || "unknown",
61
- status: (row.status || "info"),
62
- ...(row.durableObjectId && { durableObjectId: row.durableObjectId }),
63
- ...(row.containerId && { containerId: row.containerId }),
64
- ...(row.errorTag && {
65
- error: {
66
- tag: row.errorTag,
67
- message: row.errorMessage || ""
68
- }
69
- }),
70
- ...(row.data && (() => {
71
- try {
72
- return { data: JSON.parse(row.data) };
73
- }
74
- catch {
75
- return {};
76
- }
77
- })()),
78
- ...(row.durationMs !== undefined && { durationMs: row.durationMs })
79
- };
80
- };
81
- const backend = {
82
- fetchData: fetchRows,
83
- processData(rows, lastTimestamp) {
84
- const logs = [];
85
- let newTimestamp = lastTimestamp;
86
- for (const row of rows) {
87
- const log = parseRow(row);
88
- if (log) {
89
- logs.push(log);
90
- newTimestamp = Math.max(newTimestamp, row.timestamp || newTimestamp);
91
- }
92
- }
93
- return { logs, newTimestamp };
94
- }
95
- };
96
- return createPollingBackend({ pollInterval: config.pollInterval ?? 1000 }, backend);
97
- }
98
- //# sourceMappingURL=analytics.js.map