### Run TypeSlayer Quickstart Source: https://github.com/dimitropoulos/typeslayer/blob/main/npm/typeslayer/README.md Execute this command in the root of your package to start TypeSlayer. It will launch a local web UI and generate performance traces. ```bash npx typeslayer ``` -------------------------------- ### Example Migration Output Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md An example output indicating that one migration was successfully executed on the remote database. ```bash 🌀 Executing on remote database typeslayer (12345678-abcd-1234-abcd-123456789abc): 🌀 To execute on your local development database, remove the --remote flag from your wrangler command. 🚣 Executed 1 migration(s) in 0.42 seconds ┌────────┬───────────────────┬──────┐ │ Status │ Name │ │ ├────────┼───────────────────┼──────┤ │ ✅ │ 0001_init.sql │ │ └────────┴───────────────────┴──────┘ ``` -------------------------------- ### Install TypeSlayer Main Package Source: https://github.com/dimitropoulos/typeslayer/blob/main/npm/darwin-arm64/README.md Install the main 'typeslayer' package to automatically download the correct binary for your platform. Do not install this package directly. ```bash npm install --save typeslayer ``` -------------------------------- ### Example D1 Database List Output Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md An example output from the 'wrangler d1 list' command, showing database names, UUIDs, and creation dates. ```bash ┌─────────────┬──────────────────────────────────────┬─────────────────────┐ │ Name │ UUID │ Created At │ ├─────────────┼──────────────────────────────────────┼─────────────────────┤ │ typeslayer │ 12345678-abcd-1234-abcd-123456789abc │ 2025-12-27 12:00:00 │ └─────────────┴──────────────────────────────────────┴─────────────────────┘ ``` -------------------------------- ### Install and Use TypeSlayer Globally Source: https://github.com/dimitropoulos/typeslayer/blob/main/npm/darwin-arm64/README.md Install the 'typeslayer' package globally to use the command-line interface directly. This allows you to run 'typeslayer --help' without npx. ```bash npm install -g typeslayer typeslayer --help ``` -------------------------------- ### Verify PipeWire Installation with pkg-config Source: https://github.com/dimitropoulos/typeslayer/blob/main/CONTRIBUTING.md Checks if the PipeWire library is correctly installed and discoverable by pkg-config, which is relevant for screen capture on Wayland sessions. ```bash pkg-config --modversion libpipewire-0.3 ``` -------------------------------- ### Install Build Dependencies for xcap on Ubuntu/Debian Source: https://github.com/dimitropoulos/typeslayer/blob/main/CONTRIBUTING.md Installs essential build-time packages required for the xcap screenshot dependency. These are not needed for end-users of the final binary. ```bash sudo apt-get update sudo apt-get install -y \ pkg-config libclang-dev \ libxcb1-dev libxrandr-dev libdbus-1-dev \ libpipewire-0.3-dev libwayland-dev \ libegl1-mesa-dev ``` -------------------------------- ### Get D1 Database ID Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Lists available D1 databases to find the UUID for your 'typeslayer' database. This is a one-time setup step. ```bash cd packages/analytics pnpm wrangler d1 list ``` -------------------------------- ### View TypeSlayer Help via npx Source: https://github.com/dimitropoulos/typeslayer/blob/main/npm/darwin-arm64/README.md After installing the main 'typeslayer' package, you can access its functionality and help information using npx. ```bash npx typeslayer --help ``` -------------------------------- ### Start Local Worker Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Starts the analytics worker locally with persistence enabled. The default endpoint is http://localhost:8787. ```bash pnpm dev ``` -------------------------------- ### GET /leaderboard Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Returns aggregated leaderboard statistics across all collected events. Results are cached at the Cloudflare edge for 1 hour. ```APIDOC ## GET /leaderboard ### Description Returns aggregated leaderboard statistics across all collected events. The results are cached at the Cloudflare edge for 1 hour, with subsequent requests served from the cache for faster retrieval. The cache can be manually invalidated via the `/invalidate` endpoint. ### Method GET ### Endpoint /leaderboard ### Response #### Success Response (200) - **X-Cache** (string) - `hit` if data served from Cloudflare cache, `miss` if fresh data computed from database. - **Cache-Control** (string) - `public, max-age=3600` indicating cache duration. ### Response Example (Response body content not specified in source) ``` -------------------------------- ### GET /health Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Health check endpoint that returns 'ok' to indicate the service is operational. ```APIDOC ## GET /health ### Description Health check endpoint. Returns 'ok' to indicate that the service is operational. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **Body** (string) - 'ok' ``` -------------------------------- ### Invalidate Leaderboard Cache Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Manually invalidates the leaderboard cache by making a GET request to the /invalidate endpoint. No authentication is required. ```bash curl https://analytics.typeslayer.dev/invalidate ``` -------------------------------- ### Defining Explicitly Named Literal Types Source: https://github.com/dimitropoulos/typeslayer/blob/main/FAQ.md This example demonstrates how to assign names to individual literal types within a tuple definition. This approach avoids anonymous types. ```typescript type Red = "red"; type Green = "green"; type Blue = "blue"; type Colors = [Red, Green, Blue]; ``` -------------------------------- ### GET /invalidate Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Manually invalidates the leaderboard cache by deleting it from Cloudflare's Cache API. This endpoint is publicly accessible and requires no authentication. ```APIDOC ## GET /invalidate ### Description Manually invalidates the leaderboard cache by deleting it from Cloudflare's Cache API. This endpoint is publicly accessible for easy cache busting and does not require any authentication. ### Method GET ### Endpoint /invalidate ### Request Example ```bash curl https://analytics.typeslayer.dev/invalidate ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the cache invalidation was successful. - **message** (string) - A message confirming the cache invalidation. ### Response Example ```json { "success": true, "message": "Cache invalidated" } ``` ``` -------------------------------- ### Run TypeSlayer Windows Binary Source: https://github.com/dimitropoulos/typeslayer/blob/main/FAQ.md Execute the TypeSlayer binary directly on Windows if you prefer not to run postinstall scripts. ```bash npx @typeslayer/win32-x64 ``` -------------------------------- ### Loading Frontend Bundle Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/v53.0-867ef5020/index.html Dynamically creates and appends a script tag to load the main frontend bundle. Includes an onerror handler for the script load. ```javascript const script = document.createElement('script'); script.async = true; script.src = version + '/frontend_bundle.js'; script.onerror = () => errHandler(`Failed to load ${script.src}`); document.head.append(script); ``` -------------------------------- ### Backup D1 Database to SQL Dump Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Create a backup of your D1 database by exporting it to a SQL dump file. Specify the database name and output file. ```bash pnpm wrangler d1 export typeslayer --remote --output=backup.sql ``` -------------------------------- ### List All D1 Databases Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Lists all available D1 databases associated with your account. This is useful for managing your databases. ```bash pnpm wrangler d1 list ``` -------------------------------- ### Run TypeSlayer Linux Binary Source: https://github.com/dimitropoulos/typeslayer/blob/main/FAQ.md Execute the TypeSlayer binary directly on Linux if you prefer not to run postinstall scripts. ```bash npx @typeslayer/linux-x64 ``` -------------------------------- ### Analyze Trace File with @typeslayer/analyze-trace CLI Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analyze-trace/README.md Run the @typeslayer/analyze-trace CLI tool, providing the path to the generated trace JSON file as an argument. This will perform the analysis. ```bash npx @typeslayer/analyze-trace trace-json-path ``` -------------------------------- ### List Deployment Information Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Retrieves and lists information about your deployments. This is useful for tracking deployment history and status. ```bash pnpm wrangler deployments list ``` -------------------------------- ### Apply Database Migrations Locally Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Applies database migrations to your local D1 development database. This command should be run from the 'packages/analytics' directory. ```bash pnpm migrate:local ``` -------------------------------- ### Verify Table Creation in D1 Database Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Queries the D1 database to confirm that the 'events' table has been created. This command is run remotely against your production database. ```bash pnpm wrangler d1 execute typeslayer --remote --command="SELECT name FROM sqlite_master WHERE type='table'" ``` -------------------------------- ### Deploy to Production Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Deploys the Typeslayer Analytics service to production. This command uploads and publishes the worker. ```bash pnpm deploy ``` -------------------------------- ### Generate New Migration File Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Creates a new migration file with the specified name. This is part of the migration workflow for database schema changes. ```bash pnpm migrate:gen new_migration_name ``` -------------------------------- ### Execute Arbitrary SQL on D1 Database Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Execute any SQL command directly against your D1 database. Replace 'YOUR SQL HERE' with your desired SQL query. ```bash pnpm wrangler d1 execute typeslayer --remote --command="YOUR SQL HERE" ``` -------------------------------- ### Perfetto UI Error Handling and Initialization Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/index.html Handles UI load errors, timeouts, and unhandled rejections. Also initiates asset preloading and script loading for the Perfetto UI. ```javascript "use strict"; (() => { const TIMEOUT_MS = 120000; let errTimerId ; function errHandler(err) { // Note: we deliberately don't clearTimeout(), which means that this // handler is called also in the happy case when the UI loads. In that // case, though, the onCssLoaded() in frontend/index.ts will empty the // , so |div| below will be null and this function becomes a // no-op. const div = document.getElementById('app_load_failure'); if (!div) return; div.style.opacity ='1'; const errDom = document.getElementById('app_load_failure_err'); if (!errDom) return; console.error(err); errDom.innerText += `${err}\n`; const storageJson = JSON.stringify(window.localStorage); const dbg = document.getElementById('app_load_failure_dbg'); if (!dbg) return; dbg.innerText = `LocalStorage: ${storageJson}\n`; if (errTimerId !== undefined) clearTimeout(errTimerId); } // For the 'Click here to clear all caches'. window.clearAllCaches = async () => { if (window.localStorage) window.localStorage.clear(); if (window.sessionStorage) window.sessionStorage.clear(); const promises = []; if (window.caches) { try { const keys = await window.caches.keys(); keys.forEach(k => promises.push(window.caches.delete(k))); } catch (_) { // TODO(288483453) } } if (navigator.serviceWorker) { const regs = await navigator.serviceWorker.getRegistrations(); regs.forEach(reg => promises.push(reg.unregister())); } try { await Promise.all(promises); } catch (_) { // TODO(288483453) } window.location.reload(); } // If the frontend doesn't come up, make the error page above visible. errTimerId = setTimeout(() => errHandler('Timed out'), TIMEOUT_MS); window.onerror = errHandler; window.onunhandledrejection = errHandler; const versionStr = document.body.dataset['perfetto_version'] || '{}'; const versionMap = JSON.parse(versionStr); const channel = localStorage.getItem('perfettoUiChannel') || 'stable'; // The '.' below is a fallback for the case of opening a pinned version // (e.g., ui.perfetto.dev/v1.2.3./). In that case, the index.html has no // valid version map; we want to load the frontend from the same // sub-directory directory, hence ./frontend_bundle.js. const version = versionMap[channel] || versionMap['stable'] || '.'; // Preloading reduce latency of key assets requires for drawing the app. // We need to strike a balance here to avoid kicking off too many // concurrent requests and slowing down everything. // Note: Fonts (and only fonts) require "crossorigin" as per // https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/preload. const fontAttrs = {crossOrigin: '', as: 'font', type: 'font/woff2'} const assetsPreload = { '/perfetto.css': {as: 'style'}, '/assets/MaterialSymbolsOutlined.woff2': fontAttrs, '/assets/RobotoCondensed-Regular.woff2': fontAttrs, '/assets/Roboto-400.woff2': fontAttrs, }; for (const [preloadPath, preloadAttrs] of Object.entries(assetsPreload)) { const preloadLink = document.createElement('link'); preloadLink.rel = 'preload'; preloadLink.href = version + preloadPath; Object.assign(preloadLink, preloadAttrs); document.head.append(preloadLink); } const script = document.createElement('script'); script.async = true; script.src = version + '/frontend_bundle.js'; script.onerror = () => errHandler(`Failed to load ${script.src}`); document.head.append(script); })(); ``` -------------------------------- ### Stream Live Worker Logs Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Use this command to stream live logs from your deployed worker. Leave it running and make requests to see real-time logging. ```bash pnpm wrangler tail ``` -------------------------------- ### POST / Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Ingests analytics events, supporting both single events and batches of events. ```APIDOC ## POST / ### Description Ingests analytics events. This endpoint can accept single events or batches of events for processing. ### Method POST ### Endpoint / ### Parameters #### Request Body (Request body structure and fields not specified in source) ``` -------------------------------- ### Verify Production Events Data Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Executes a SQL query against the production D1 database to retrieve the latest events. Use this to confirm data is being ingested correctly in production. ```bash pnpm wrangler d1 execute typeslayer --remote --command="SELECT * FROM events ORDER BY timestamp DESC LIMIT 10" ``` -------------------------------- ### Perfetto UI Loading Spinner Styles Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/v53.0-867ef5020/index.html CSS styles for the application loading spinner, including positioning, dimensions, and animation. ```css #app_load { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #000000; } #app_load_spinner { margin: 30vh auto; width: 150px; height: 150px; border: 3px solid rgba(255, 255, 255, .3); border-radius: 50%; border-top-color: #fff; animation: app_load_spin 1s ease-in-out infinite; } @keyframes app_load_spin { to { transform: rotate(360deg); } } ``` -------------------------------- ### Run TypeSlayer macOS Binary Source: https://github.com/dimitropoulos/typeslayer/blob/main/FAQ.md Execute the TypeSlayer binary directly on macOS (Apple Silicon) if you prefer not to run postinstall scripts. ```bash npx @typeslayer/darwin-x64 ``` -------------------------------- ### Analyze Trace File and Redirect Output Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analyze-trace/README.md Analyze a trace file and redirect the JSON output to a file for further processing or inspection. This is useful for programmatic analysis. ```bash typeslayer-analyze-trace ./dist/trace.json > analysis.json ``` -------------------------------- ### Test Production Collect Endpoint Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Sends a test event to the production /collect endpoint to verify deployment and functionality. Uses the configured production domain. ```bash curl -X POST https://analytics.typeslayer.dev/collect \ -H "Content-Type: application/json" \ -d '{ "name": "production_test", "sessionId": "prod-123", "timestamp": 1735318800000, "version": "0.1.0", "platform": "Ubuntu", "mode": "GUI", "data": {"test": true} }' ``` -------------------------------- ### Analyze Trace Data Programmatically Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analyze-trace/README.md Import the analyzeTrace function and fs module. Read trace data from a JSON file, parse it, and then analyze it using analyzeTrace. The results include hot spots, depth limits, and duplicate packages. ```typescript import { analyzeTrace } from "@typeslayer/analyze-trace"; import { readFileSync } from "fs"; // Read and parse trace const traceJson = JSON.parse(readFileSync("trace.json", "utf-8")); // Analyze const result = analyzeTrace(traceJson); console.log("Hot spots:", result.hotSpots); console.log("Depth limits:", result.depthLimits); console.log("Duplicate packages:", result.duplicatePackages); ``` -------------------------------- ### Apply Database Migrations Remotely Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Applies database migrations to your production D1 database. This command should be run from the 'packages/analytics' directory. ```bash pnpm migrate:apply ``` -------------------------------- ### Configure wrangler.jsonc with D1 Database ID Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Configures the wrangler.jsonc file to link the worker to your D1 database. Replace 'REPLACE_WITH_D1_DATABASE_ID' with your actual database UUID. ```json { "name": "typeslayer-analytics", "main": "src/index.ts", "compatibility_date": "2024-12-01", "routes": ["https://analytics.typeslayer.dev/collect"], "d1_databases": [ { "binding": "DB", "database_name": "typeslayer", "database_id": "12345678-abcd-1234-abcd-123456789abc", // <- Your UUID here }, ], "vars": { "REQUIRE_INGESTION_SECRET": "0", // Set to "1" if you want to require auth }, } ``` -------------------------------- ### Asset Preloading for Performance Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/v53.0-867ef5020/index.html Preloads critical assets like CSS and fonts to reduce latency. Configures preload attributes, including 'crossorigin' for fonts. ```javascript const versionStr = document.body.dataset['perfetto_version'] || '{}'; const versionMap = JSON.parse(versionStr); const channel = localStorage.getItem('perfettoUiChannel') || 'stable'; // The '.' below is a fallback for the case of opening a pinned version // (e.g., ui.perfetto.dev/v1.2.3./). In that case, the index.html has no // valid version map; we want to load the frontend from the same // sub-directory directory, hence ./frontend_bundle.js. const version = versionMap[channel] || versionMap['stable'] || '.'; // Preloading reduce latency of key assets requires for drawing the app. // We need to strike a balance here to avoid kicking off too many // concurrent requests and slowing down everything. // Note: Fonts (and only fonts) require "crossorigin" as per // https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/preload. const fontAttrs = {crossOrigin: '', as: 'font', type: 'font/woff2'} const assetsPreload = { '/perfetto.css': {as: 'style'}, '/assets/MaterialSymbolsOutlined.woff2': fontAttrs, '/assets/RobotoCondensed-Regular.woff2': fontAttrs, '/assets/Roboto-400.woff2': fontAttrs, }; for (const [preloadPath, preloadAttrs] of Object.entries(assetsPreload)) { const preloadLink = document.createElement('link'); preloadLink.rel = 'preload'; preloadLink.href = version + preloadPath; Object.assign(preloadLink, preloadAttrs); document.head.append(preloadLink); } ``` -------------------------------- ### Perfetto UI Loading and Error Styling Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/index.html CSS styles for the application loading spinner and the error message display, including layout and appearance. ```css #app_load_failure {opacity:0;transition:opacity 1s ease;position:absolute;overflow:auto;background:#080082;top:0;left:0;width:100%;height:100%;bottom:0;right:0;margin:0;opacity:0;user-select:text} #app_load_failure > pre {color:#fff;position:absolute;margin:auto;white-space:pre-wrap;top:10vh;max-width:90vw;width:880px;left:0;right:0;font-size:16px;line-height:30px;font-weight:700} #app_load_failure > pre span {background:#fff;color:#080082;padding:2px} #app_load_failure_dbg { overflow-wrap: break-word; font-size: 12px; line-height: 1; font-weight: initial;} #app_load_failure a {color:#fff} #app_load { position: absolute; top: 0; left: 0; right:0; bottom: 0; background-color: #000000;} #app_load_spinner { margin: 30vh auto; width: 150px; height: 150px; border: 3px solid rgba(255,255,255,.3); border-radius: 50%; border-top-color: #fff; animation: app_load_spin 1s ease-in-out infinite; } @keyframes app_load_spin { to { transform: rotate(360deg); } } ``` -------------------------------- ### Query D1 Database Events by Name Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Count the occurrences of different event names in the D1 database. This helps in understanding the frequency of various events. ```bash pnpm wrangler d1 execute typeslayer --remote --command="SELECT name, COUNT(*) as count FROM events GROUP BY name" ``` -------------------------------- ### Test Local Collect Endpoint Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Sends a test event to the local /collect endpoint to verify its functionality. Requires the worker to be running locally. ```bash curl -X POST http://localhost:8787/collect \ -H "Content-Type: application/json" \ -d '{ "name": "test_event", "sessionId": "test-123", "timestamp": 1735318800000, "version": "0.1.0", "platform": "test", "mode": "CLI", "data": {"foo": "bar"} }' ``` -------------------------------- ### Create Ingestion Secret Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Creates a secret key for authenticating ingestion requests. This command will prompt for the secret value. ```bash pnpm wrangler secret put INGESTION_SECRET ``` -------------------------------- ### Perfetto UI Load Failure Styles Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/v53.0-867ef5020/index.html CSS styles for the application load failure screen, including positioning, colors, and transitions. ```css #app_load_failure { opacity: 0; transition: opacity 1s ease; position: absolute; overflow: auto; background: #080082; top: 0; left: 0; width: 100%; height: 100%; bottom: 0; right: 0; margin: 0; opacity: 0; user-select: text; } #app_load_failure > pre { color: #fff; position: absolute; margin: auto; white-space: pre-wrap; top: 10vh; max-width: 90vw; width: 880px; left: 0; right: 0; font-size: 16px; line-height: 30px; font-weight: 700; } #app_load_failure > pre span { background: #fff; color: #080082; padding: 2px; } #app_load_failure_dbg { overflow-wrap: break-word; font-size: 12px; line-height: 1; font-weight: initial; } #app_load_failure a { color: #fff; } ``` -------------------------------- ### CLI Validation Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/validate/README.md Validate compiler output files directly using the command-line interface. ```bash npx @typeslayer/validate --trace ./trace.json npx @typeslayer/validate --types ./types.json ``` -------------------------------- ### Query Local Events Data Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Executes a SQL query against the local D1 database to retrieve all events. Ensure the worker is running locally. ```bash pnpm wrangler d1 execute typeslayer --local --command="SELECT * FROM events" ``` -------------------------------- ### Generate Trace File with tsc Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analyze-trace/README.md Use the TypeScript compiler (tsc) with the --generateTrace flag to create a trace JSON file. This file is the input for the analyze-trace tool. ```bash tsc --generateTrace ./trace-json-path ``` -------------------------------- ### Query Recent D1 Events by Session ID Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Retrieve recent events associated with a specific session ID from the D1 database. Replace 'your-session-id' with the actual session ID. ```bash pnpm wrangler d1 execute typeslayer --remote --command="SELECT * FROM events WHERE session_id = 'your-session-id'" ``` -------------------------------- ### CPU Profile Validation Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/validate/README.md Validate TypeScript CPU profile data using the dedicated Zod schema. ```typescript import { tscCpuProfileSchema } from "@typeslayer/validate"; const profile = tscCpuProfileSchema.parse(jsonData); ``` -------------------------------- ### Include Secret in Request Header Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Demonstrates how to include the secret key in the X-Typeslayer-Analytics-Key header for POST requests to the collect endpoint when authentication is enabled. ```bash curl -X POST http://localhost:8787/collect \ -H "Content-Type: application/json" \ -H "X-Typeslayer-Analytics-Key: your-secret-here" \ -d '{"name":"test",...}' ``` -------------------------------- ### Query D1 Events from the Last Hour Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Fetch events that occurred within the last hour from the D1 database. This is useful for analyzing recent activity. ```bash pnpm wrangler d1 execute typeslayer --remote --command="SELECT * FROM events WHERE timestamp > (strftime('%s','now') - 3600) * 1000" ``` -------------------------------- ### Clear Site Storage and Caches Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/index.html JavaScript function to clear all site storage and caches. This is a remediation step for UI loading issues. ```javascript clearAllCaches(); ``` -------------------------------- ### Verify D1 Database Table Existence Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Checks if a specific table exists in your D1 database by querying the sqlite_master table. This is useful for debugging 'DB error' responses. ```bash pnpm wrangler d1 execute typeslayer --remote --command="SELECT name FROM sqlite_master" ``` -------------------------------- ### Error Handling and UI Load Failure Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/v53.0-867ef5020/index.html Handles errors during UI load, displays error messages and debug information, and manages timeouts. This handler is also invoked on successful load but becomes a no-op if the UI is already rendered. ```javascript 'use strict'; (() => { const TIMEOUT_MS = 120000; let errTimerId; function errHandler(err) { // Note: we deliberately don't clearTimeout(), which means that this // handler is called also in the happy case when the UI loads. In that // case, though, the onCssLoaded() in frontend/index.ts will empty the // , so |div| below will be null and this function becomes a // no-op. const div = document.getElementById('app_load_failure'); if (!div) return; div.style.opacity = '1'; const errDom = document.getElementById('app_load_failure_err'); if (!errDom) return; console.error(err); errDom.innerText += `${err}\n`; const storageJson = JSON.stringify(window.localStorage); const dbg = document.getElementById('app_load_failure_dbg'); if (!dbg) return; dbg.innerText = `LocalStorage: ${storageJson}\n`; if (errTimerId !== undefined) clearTimeout(errTimerId); } // If the frontend doesn't come up, make the error page above visible. errTimerId = setTimeout(() => errHandler('Timed out'), TIMEOUT_MS); window.onerror = errHandler; window.onunhandledrejection = errHandler; })(); ``` -------------------------------- ### Response for Cache Invalidation Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md The expected JSON response after successfully invalidating the cache. ```json { "success": true, "message": "Cache invalidated" } ``` -------------------------------- ### Collect Events Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Accepts POST requests to collect analytics events. Supports individual events, batch uploads, and NDJSON format. ```APIDOC ## POST /collect ### Description Collects analytics events. Supports individual events, batch uploads (array of events), and NDJSON format. ### Method POST ### Endpoint /collect ### Parameters #### Request Body - **name** (string) - Required - Event type (e.g., "app_started_success") - **sessionId** (string) - Required - Unique session identifier - **timestamp** (number) - Required - Unix timestamp in milliseconds - **version** (string) - Optional - App version - **platform** (string) - Optional - OS/platform info - **mode** (string) - Optional - "GUI" or "CLI" - **data** (object) - Required - Event-specific payload (stored as JSON string) ### Request Example ```json { "name": "app_started_success", "sessionId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "timestamp": 1678886400000, "version": "1.0.0", "platform": "iOS", "mode": "GUI", "data": { "screen": "home", "duration": 5000 } } ``` ### Response #### Success Response (200) (No specific success response schema documented) ``` -------------------------------- ### Clear All Caches Functionality Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/typeslayer/public/perfetto-ui/v53.0-867ef5020/index.html Provides a global function to clear browser caches including localStorage, sessionStorage, Cache API, and unregisters service workers. Reloads the window after clearing. ```javascript window.clearAllCaches = async () => { if (window.localStorage) window.localStorage.clear(); if (window.sessionStorage) window.sessionStorage.clear(); const promises = []; if (window.caches) { try { const keys = await window.caches.keys(); keys.forEach(k => promises.push(window.caches.delete(k))); } catch (_) { // TODO(288483453) } } if (navigator.serviceWorker) { const regs = await navigator.serviceWorker.getRegistrations(); regs.forEach(reg => promises.push(reg.unregister())); } try { await Promise.all(promises); } catch (_) { // TODO(288483453) } window.location.reload(); } ``` -------------------------------- ### Defining a Named Tuple Type Source: https://github.com/dimitropoulos/typeslayer/blob/main/FAQ.md This snippet shows how to define a tuple type with named elements in TypeScript. It illustrates the concept of inlined literal types. ```typescript type Colors = ["red", "green", "blue"]; ``` -------------------------------- ### Trace JSON Validation Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/validate/README.md Validate trace.json output from TypeScript compiler using Zod schemas. Can be used with Node.js streams for efficient processing. ```typescript import { traceJsonSchema, type TraceEvent } from "@typeslayer/validate"; // Validate trace.json output from TypeScript compiler const events: TraceEvent[] = traceJsonSchema.parse(jsonData); ``` ```typescript import { createReadStream } from "fs"; import { validateTraceJson } from "@typeslayer/validate/node"; const stream = createReadStream("trace.json"); const events = await validateTraceJson(stream); ``` -------------------------------- ### Health Check Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Checks the health status of the analytics service. ```APIDOC ## GET /health ### Description Provides a health check for the analytics service. ### Method GET ### Endpoint /health ### Response #### Success Response (200) (No specific success response schema documented) ``` -------------------------------- ### Analytics Worker Request Schema Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Defines the structure of POST requests to the /collect endpoint. Supports event type, session ID, timestamp, optional metadata, and an event-specific data payload. ```typescript { name: string; // Event type: "app_started_success", etc. sessionId: string; // Unique session identifier timestamp: number; // Unix timestamp in milliseconds version?: string; // App version platform?: string; // OS/platform info mode?: string; // "GUI" or "CLI" data: object; // Event-specific payload (stored as JSON string) } ``` -------------------------------- ### Enable Secret Requirement in Wrangler Config Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/analytics/README.md Configures the worker to require the INGESTION_SECRET for requests by setting the REQUIRE_INGESTION_SECRET variable to '1' in wrangler.jsonc. ```jsonc "vars": { "REQUIRE_INGESTION_SECRET": "1" // Changed from "0" to "1" } ``` -------------------------------- ### TypeScript Type Inference Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/validate/README.md Utilize inferred TypeScript types from validation schemas for type-safe event handling. ```typescript import type { TraceEvent } from "@typeslayer/validate"; // Type-safe event handling function processEvent(event: TraceEvent) { switch (event.name) { case "createSourceFile": console.log("Creating source file:", event.args.path); break; // ... other event types } } ``` -------------------------------- ### Types JSON Validation Source: https://github.com/dimitropoulos/typeslayer/blob/main/packages/validate/README.md Validate type information JSON using the provided Zod schema. ```typescript import { typesJsonSchema, type TypesJsonSchema } from "@typeslayer/validate"; const types: TypesJsonSchema = typesJsonSchema.parse(jsonData); ``` -------------------------------- ### Anonymous Arrow Function Source: https://github.com/dimitropoulos/typeslayer/blob/main/FAQ.md Illustrates an anonymous arrow function used in an array mapping operation. Anonymous functions do not have explicit names. ```typescript someArray.map(x => x + 1); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.