Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
⚡️ Load the slim PostHog build in the browser (#3464)
Luke Velladbb3fc72ed11
diff --git a/packages/posthog/package.json b/packages/posthog/package.jsonindex ae8870e2a..13b3df62b 100644--- a/packages/posthog/package.json+++ b/packages/posthog/package.json@@ -4,8 +4,7 @@"private": true,"exports": {"./server": "./src/server.ts",- "./client": "./src/client.ts",- "./utils": "./src/utils.ts"+ "./client": "./src/client.ts"},"scripts": {"backfill-space-group-properties": "dotenv -e .env -- pnpx tsx ./src/scripts/backfill-space-group-properties.ts",diff --git a/packages/posthog/src/client-config.ts b/packages/posthog/src/client-config.tsindex e2bce68c5..8699e4e97 100644--- a/packages/posthog/src/client-config.ts+++ b/packages/posthog/src/client-config.ts@@ -1,4 +1,4 @@-import type { PostHogConfig } from "posthog-js";+import type { PostHogConfig } from "posthog-js/dist/module.slim";/*** Persistence options for the browser client. The anonymous id lives in adiff --git a/packages/posthog/src/client.ts b/packages/posthog/src/client.tsindex 77dba9557..8366f25a4 100644--- a/packages/posthog/src/client.ts+++ b/packages/posthog/src/client.ts@@ -1,17 +1,45 @@"use client";-import posthog from "posthog-js";+// The slim build leaves out every extension (replay, surveys, flags,+// exception capture, history autocapture), roughly halving the SDK. Browser+// errors go to Sentry, and trackHistoryPageviews below replaces the one+// extension we used.+import posthog from "posthog-js/dist/module.slim";import type React from "react";import { getPostHogInitOptions } from "./client-config";-import {- isAbortError,- isInjectedExtensionException,- isResizeObserverLoopError,- isUnsymbolicatedMinifiedException,-} from "./utils";let initialized = false;let syncedDistinctId: string | null | undefined;+let lastPathname: string | undefined;++/**+ * Captures a $pageview when a client-side navigation changes the path, which+ * is what capture_pageview: "history_change" does through the history+ * autocapture extension in the full build.+ */+function trackHistoryPageviews() {+ lastPathname = window.location.pathname;++ const capture = (navigationType: string) => {+ const { pathname } = window.location;+ if (pathname === lastPathname) return;+ lastPathname = pathname;+ // Runs inside the router's own history call, so analytics must never+ // throw back into navigation+ try {+ posthog.capture("$pageview", { navigation_type: navigationType });+ } catch {}+ };++ for (const method of ["pushState", "replaceState"] as const) {+ const original = window.history[method];+ window.history[method] = function (...args) {+ original.apply(this, args);+ capture(method);+ };+ }+ window.addEventListener("popstate", () => capture("popstate"));+}function syncIdentity(distinctId: string | null | undefined) {syncedDistinctId = distinctId;@@ -66,28 +94,17 @@ export function initPostHog({debug: false,api_host: process.env.NEXT_PUBLIC_POSTHOG_API_HOST,ui_host: process.env.NEXT_PUBLIC_POSTHOG_UI_HOST,- capture_pageview: "history_change",+ capture_pageview: true,capture_pageleave: true,enable_heatmaps: false,autocapture: false,capture_performance: {web_vitals: false,},- before_send: (event) => {- if (- event?.event === "$exception" &&- (isInjectedExtensionException(event) ||- isAbortError(event) ||- isResizeObserverLoopError(event) ||- isUnsymbolicatedMinifiedException(event))- ) {- return null;- }- return event;- },...getPostHogInitOptions(),});+ trackHistoryPageviews();syncIdentity(distinctId);}diff --git a/packages/posthog/src/utils.test.ts b/packages/posthog/src/utils.test.tsdeleted file mode 100644index 0035c95b4..000000000--- a/packages/posthog/src/utils.test.ts+++ /dev/null@@ -1,178 +0,0 @@-import type { CaptureResult } from "posthog-js";-import { describe, expect, it } from "vitest";-import {- isAbortError,- isResizeObserverLoopError,- isUnsymbolicatedMinifiedException,-} from "./utils";--describe("isAbortError", () => {- const event = (exceptionList: unknown) =>- ({- properties: { $exception_list: exceptionList },- }) as unknown as CaptureResult;-- it("matches an aborted tRPC request", () => {- expect(- isAbortError(- event([- { type: "TRPCClientError", value: "The operation was aborted. " },- {- type: "DOMException",- value: "AbortError: The operation was aborted. ",- },- ]),- ),- ).toBe(true);- });-- it("matches a bare AbortError DOMException", () => {- expect(- isAbortError(- event([- {- type: "DOMException",- value: "AbortError: The user aborted a request.",- },- ]),- ),- ).toBe(true);- });-- it("does not match an unrelated exception", () => {- expect(- isAbortError(- event([{ type: "TypeError", value: "x is not a function" }]),- ),- ).toBe(false);- });-- it("does not match when the exception list is missing", () => {- expect(isAbortError({ properties: {} } as unknown as CaptureResult)).toBe(- false,- );- });-});--describe("isResizeObserverLoopError", () => {- const event = (exceptionList: unknown) =>- ({- properties: { $exception_list: exceptionList },- }) as unknown as CaptureResult;-- it("matches the undelivered notifications notice", () => {- expect(- isResizeObserverLoopError(- event([- {- type: "Error",- value:- "ResizeObserver loop completed with undelivered notifications.",- },- ]),- ),- ).toBe(true);- });-- it("matches the loop limit exceeded notice", () => {- expect(- isResizeObserverLoopError(- event([{ type: "Error", value: "ResizeObserver loop limit exceeded" }]),- ),- ).toBe(true);- });-- it("does not match an unrelated exception", () => {- expect(- isResizeObserverLoopError(- event([{ type: "TypeError", value: "x is not a function" }]),- ),- ).toBe(false);- });-- it("does not match when the exception list is missing", () => {- expect(- isResizeObserverLoopError({- properties: {},- } as unknown as CaptureResult),- ).toBe(false);- });-});--describe("isUnsymbolicatedMinifiedException", () => {- const event = (exceptionList: unknown) =>- ({- properties: { $exception_list: exceptionList },- }) as unknown as CaptureResult;-- const documentFrames = [- { filename: "https://app.rallly.co/", function: "?" },- { filename: "https://app.rallly.co/", function: "?" },- ];-- it("matches a minified identifier with no /_next/static frame", () => {- for (const value of ["fa", "ga", "Ba", "Ca"]) {- expect(- isUnsymbolicatedMinifiedException(- event([- { type: "Error", value, stacktrace: { frames: documentFrames } },- ]),- ),- ).toBe(true);- }- });-- it("does not match when a frame resolves to a /_next/static chunk", () => {- expect(- isUnsymbolicatedMinifiedException(- event([- {- type: "Error",- value: "Ca",- stacktrace: {- frames: [- ...documentFrames,- { filename: "https://app.rallly.co/_next/static/chunk.js" },- ],- },- },- ]),- ),- ).toBe(false);- });-- it("does not match a readable error message", () => {- expect(- isUnsymbolicatedMinifiedException(- event([- {- type: "TypeError",- value: "x is not a function",- stacktrace: { frames: documentFrames },- },- ]),- ),- ).toBe(false);- });-- it("does not match a minified value without a stack", () => {- expect(- isUnsymbolicatedMinifiedException(- event([{ type: "Error", value: "Ca", stacktrace: { frames: [] } }]),- ),- ).toBe(false);- expect(- isUnsymbolicatedMinifiedException(- event([{ type: "Error", value: "Ca" }]),- ),- ).toBe(false);- });-- it("does not match when the exception list is missing", () => {- expect(- isUnsymbolicatedMinifiedException({- properties: {},- } as unknown as CaptureResult),- ).toBe(false);- });-});diff --git a/packages/posthog/src/utils.ts b/packages/posthog/src/utils.tsdeleted file mode 100644index c7598de28..000000000--- a/packages/posthog/src/utils.ts+++ /dev/null@@ -1,131 +0,0 @@-import type { CaptureResult } from "posthog-js";--/**- * Stack-frame function names that only ever appear in password-manager browser- * extension content scripts (1Password/Dashlane-style form scanners), never in- * our own code. Such extensions scan the page for login forms, misread our- * invite voting form (`voting-form.tsx`) as a login form, and throw a- * `DOMException: InvalidAccessError` from inside their own `MutationObserver`- * callback. PostHog's exception autocapture then attributes the error to our- * page URL, so this third-party noise ends up in error tracking.- *- * Matching any of these frames lets us drop the whole noise class — including- * future variants such as other `logLogin*Detected` probes — before it is sent.- */-const EXTENSION_NOISE_FRAME_PATTERN =- /^(dispatchToBridge|logLogin\w*Detected)$/;--export function isInjectedExtensionException(event: CaptureResult) {- const exceptionList = event.properties?.$exception_list as- | Array<{ stacktrace?: { frames?: Array<{ function?: string }> } }>- | undefined;-- if (!Array.isArray(exceptionList)) {- return false;- }-- return exceptionList.some((exception) =>- exception?.stacktrace?.frames?.some(- (frame) =>- typeof frame?.function === "string" &&- EXTENSION_NOISE_FRAME_PATTERN.test(frame.function),- ),- );-}--/**- * A request that is aborted (React Query cancels an in-flight query on unmount- * or navigation) surfaces as an `AbortError`. When it wraps a tRPC request, the- * `$exception_list` holds a `TRPCClientError` ("The operation was aborted.")- * chained to a `DOMException` whose value starts with "AbortError:". Nothing- * broke for the user, so this is autocapture noise, not a real error.- */-const ABORT_NOISE_VALUE_PATTERN =- /^AbortError\b|operation was aborted|user aborted a request/i;--export function isAbortError(event: CaptureResult) {- const exceptionList = event.properties?.$exception_list as- | Array<{ type?: string; value?: string }>- | undefined;-- if (!Array.isArray(exceptionList)) {- return false;- }-- return exceptionList.some(- (exception) =>- exception?.type === "AbortError" ||- (typeof exception?.value === "string" &&- ABORT_NOISE_VALUE_PATTERN.test(exception.value)),- );-}--/**- * The browser fires `ResizeObserver loop completed with undelivered- * notifications.` on `window.onerror` when a ResizeObserver callback changes- * layout and the browser cannot deliver every notification inside one animation- * frame. Nothing breaks — it is a notice, not a crash — so autocapture must not- * report it as a real error.- */-const RESIZE_OBSERVER_LOOP_VALUE_PATTERN =- /^ResizeObserver loop (limit exceeded|completed with undelivered notifications)/i;--export function isResizeObserverLoopError(event: CaptureResult) {- const exceptionList = event.properties?.$exception_list as- | Array<{ value?: string }>- | undefined;-- if (!Array.isArray(exceptionList)) {- return false;- }-- return exceptionList.some(- (exception) =>- typeof exception?.value === "string" &&- RESIZE_OBSERVER_LOOP_VALUE_PATTERN.test(exception.value),- );-}--/**- * An iOS-only throw reaches error tracking with a bare minified identifier as- * its message (`fa`, `ga`, `Ba`, `Ca`, ...) and a stack whose every frame- * resolves to the HTML document (`filename: https://app.rallly.co/`,- * `function: "?"`) instead of a `/_next/static` chunk. Only chunk files ship- * source maps (`productionBrowserSourceMaps` in next.config.ts), so an inline- * document script can never be symbolicated and the stack stays useless. The- * minifier renames the symbol on each release, so the message is part of the- * fingerprint and every deploy opens a fresh, uninvestigable issue.- *- * Match a short minified identifier value together with a stack that carries no- * `/_next/static` frame. This drops the whole class and covers the next rename.- */-const MINIFIED_IDENTIFIER_VALUE_PATTERN = /^[A-Za-z$_][\w$]{0,2}$/;--export function isUnsymbolicatedMinifiedException(event: CaptureResult) {- const exceptionList = event.properties?.$exception_list as- | Array<{- value?: string;- stacktrace?: { frames?: Array<{ filename?: string }> };- }>- | undefined;-- if (!Array.isArray(exceptionList)) {- return false;- }-- return exceptionList.some((exception) => {- if (- typeof exception?.value !== "string" ||- !MINIFIED_IDENTIFIER_VALUE_PATTERN.test(exception.value)- ) {- return false;- }-- const frames = exception.stacktrace?.frames;- if (!Array.isArray(frames) || frames.length === 0) {- return false;- }-- return !frames.some((frame) => frame?.filename?.includes("/_next/static"));- });-}