The Open Standard for Generative UI
feat(lang-core): add opt-out postinstall telemetry (#931)
Zahle Khan6facbd6aaf40
diff --git a/packages/lang-core/README.md b/packages/lang-core/README.mdindex a62851d77..cf27acd88 100644--- a/packages/lang-core/README.md+++ b/packages/lang-core/README.md@@ -107,12 +107,16 @@ const merged = mergeStatements(original, patch);## Telemetry-Lang Core collects limited usage telemetry from 10% of successful server-side-`generateSystemPrompt()` calls to help improve OpenUI. It does not collect-application-user data, prompts, messages, generated output, credentials, or raw-component and tool definitions. Project and prompt-configuration identifiers-are hashed locally before being sent, and browsers do not send telemetry. Set-`OPENUI_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1` to disable it.+Lang Core sends pseudonymous installation telemetry during `postinstall` and+collects limited usage telemetry from 10% of successful server-side+`generateSystemPrompt()` calls. It does not collect application-user data,+prompts, messages, generated output, credentials, or raw component and tool+definitions. Project identifiers are hashed locally before being sent, and+browsers do not send telemetry.++Set `OPENUI_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1` to disable telemetry. Set+`OPENUI_TELEMETRY_DEBUG=1` to print the installation payload to stdout without+sending it.### Runtimediff --git a/packages/lang-core/package.json b/packages/lang-core/package.jsonindex 83d0edb27..81e269cd6 100644--- a/packages/lang-core/package.json+++ b/packages/lang-core/package.json@@ -1,6 +1,6 @@{"name": "@openuidev/lang-core",- "version": "0.2.10",+ "version": "0.2.11","description": "Framework-agnostic core for OpenUI Lang: parser, prompt generation, validation, and type definitions","license": "MIT","type": "module",@@ -10,6 +10,7 @@"sideEffects": false,"files": ["dist",+ "postinstall.cjs","README.md"],"exports": {@@ -35,6 +36,7 @@"format:check": "prettier --check ./src","check:publint": "publint","check:attw": "attw --pack .",+ "postinstall": "node ./postinstall.cjs","prepare": "pnpm run build","prepublishOnly": "pnpm run check:publint && pnpm run check:attw","ci": "pnpm run lint:check && pnpm run format:check"@@ -71,6 +73,7 @@"author": "[email protected]","devDependencies": {"@modelcontextprotocol/sdk": "^1.27.1",+ "@types/node": "^20","vitest": "^4.0.18"}}diff --git a/packages/lang-core/postinstall.cjs b/packages/lang-core/postinstall.cjsnew file mode 100644index 000000000..2f17810f3--- /dev/null+++ b/packages/lang-core/postinstall.cjs@@ -0,0 +1,9 @@+"use strict";++try {+ process.env.OPENUI_LANG_CORE_PACKAGE_VERSION = require("./package.json").version;+ require("./dist/postinstall.cjs");+} catch {+ // Telemetry must never fail installation, including a clean source checkout+ // where the compiled postinstall entry does not exist yet.+}diff --git a/packages/lang-core/src/parser/prompt.ts b/packages/lang-core/src/parser/prompt.tsindex 5c3e5da2e..069eddadb 100644--- a/packages/lang-core/src/parser/prompt.ts+++ b/packages/lang-core/src/parser/prompt.ts@@ -1,4 +1,4 @@-import { recordSystemPromptGeneration } from "../telemetry";+import { recordSystemPromptGeneration } from "../telemetry/runtime";import { BUILTINS, LAZY_BUILTIN_DEFS } from "./builtins";import type { LibraryJSONSchema } from "./types";diff --git a/packages/lang-core/src/postinstall.ts b/packages/lang-core/src/postinstall.tsnew file mode 100644index 000000000..7a9099fa2--- /dev/null+++ b/packages/lang-core/src/postinstall.ts@@ -0,0 +1,5 @@+import { runInstallTelemetry } from "./telemetry/install";++void runInstallTelemetry().catch(() => {+ // The lifecycle entry must always resolve successfully.+});diff --git a/packages/lang-core/src/telemetry/install.ts b/packages/lang-core/src/telemetry/install.tsnew file mode 100644index 000000000..d272469c8--- /dev/null+++ b/packages/lang-core/src/telemetry/install.ts@@ -0,0 +1,312 @@+/**+ * Installation telemetry disclosure+ *+ * Sent during package postinstall unless telemetry is disabled:+ * - A random installation ID and a salted SHA-256 project ID+ * - Lang Core, Node.js, OS, architecture, and package-manager versions+ * - CI provider category, Docker status, project-ID source category, and schema version+ *+ * The JSON payload contains no direct PII or application-user data. It never includes+ * names, email addresses, usernames, raw Git origins, repository or project names,+ * filesystem paths, branches, commits, credentials, environment values, source code,+ * prompts, messages, generated output, component or tool definitions, errors, logs,+ * stack traces, routes, or UI interactions. As with any HTTP request, the telemetry+ * proxy and PostHog can observe the source IP as transport metadata; the script does+ * not read it or add it to the payload.+ */+import { execFileSync } from "node:child_process";+import { createHash, randomBytes, randomUUID } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, writeFileSync, type WriteFileOptions } from "node:fs";+import { homedir, release } from "node:os";+import path from "node:path";+import {+ detectCI,+ getPostHogConfig,+ isTelemetryDisabled,+ isTruthyEnv,+ normalizeProjectIdentity,+ TELEMETRY_REQUEST_TIMEOUT_MS,+ TELEMETRY_SCHEMA_VERSION,+ type CiName,+} from "./shared";++export { detectCI, isTelemetryDisabled, isTruthyEnv, normalizeProjectIdentity };+export type { CiName };++export const INSTALL_EVENT = "openui_lang_core_installed";++export type ProjectIdSource = "git_origin" | "repository_url" | "install_root";+export type PackageManagerName = "npm" | "pnpm" | "yarn" | "bun" | "unknown";+export interface InstallTelemetryProperties extends Record<string, unknown> {+ telemetry_schema_version: number;+ project_id: string;+ project_id_source: ProjectIdSource;+ lang_core_version: string;+ node_version: string;+ system_platform: string;+ system_release: string;+ system_architecture: string;+ package_manager: PackageManagerName;+ package_manager_version?: string;+ ci: boolean;+ ci_name?: CiName;+ is_docker: boolean;+}++export interface InstallTelemetryPayload {+ distinctId: string;+ event: typeof INSTALL_EVENT;+ properties: InstallTelemetryProperties;+}++export interface InstallTelemetryIO {+ cwd(): string;+ homedir(): string;+ readFile(file: string): string;+ writeFile(file: string, contents: string, options?: WriteFileOptions): void;+ mkdir(directory: string): void;+ getGitOrigin(projectRoot: string): string | undefined;+ platform: string;+ architecture: string;+ release(): string;+ randomUUID(): string;+ randomHex(bytes: number): string;+ isDocker(): boolean;+ stdout(message: string): void;+ stderr(message: string): void;+}++export type InstallTelemetrySender = (+ payload: InstallTelemetryPayload,+ env: NodeJS.ProcessEnv,+) => Promise<void>;++export interface RunInstallTelemetryOptions {+ env?: NodeJS.ProcessEnv;+ io?: Partial<InstallTelemetryIO>;+ send?: InstallTelemetrySender;+}++export type RunInstallTelemetryResult =+ | { status: "disabled" }+ | { status: "debug"; payload: InstallTelemetryPayload }+ | { status: "sent"; payload: InstallTelemetryPayload }+ | { status: "failed"; payload?: InstallTelemetryPayload };++interface StoredTelemetryState extends Record<string, unknown> {+ distinctId: string;+ projectSalt: string;+ langCorePostinstallNoticeShown?: boolean;+}++interface ProjectIdentity {+ value: string;+ source: ProjectIdSource;+}++const INSTALL_NOTICE =+ "\n◆ OpenUI Lang Core sends pseudonymous installation telemetry to PostHog.\n" ++ " It includes a salted project ID, OpenUI/Node/OS/package-manager metadata, and the network IP observed by PostHog.\n" ++ " It does not send repository URLs, paths, source code, prompts, errors, or application data.\n" ++ " Disable it with OPENUI_TELEMETRY_DISABLED=1 or DO_NOT_TRACK=1.\n\n";++export function hashProjectIdentity(salt: string, projectIdentity: string): string {+ return createHash("sha256").update(salt).update("\0").update(projectIdentity).digest("hex");+}++export function detectPackageManager(env: NodeJS.ProcessEnv): {+ name: PackageManagerName;+ version?: string;+} {+ const userAgent = env["npm_config_user_agent"]?.trim() ?? "";+ const match = userAgent.match(/^(npm|pnpm|yarn|bun)\/([^\s]+)/i);+ if (!match) return { name: "unknown" };++ const name = match[1]!.toLowerCase() as Exclude<PackageManagerName, "unknown">;+ const version = match[2]!.slice(0, 64);+ return version ? { name, version } : { name };+}++export async function runInstallTelemetry(+ options: RunInstallTelemetryOptions = {},+): Promise<RunInstallTelemetryResult> {+ const env = options.env ?? process.env;+ if (isTelemetryDisabled(env)) return { status: "disabled" };++ let payload: InstallTelemetryPayload | undefined;+ try {+ const io = createInstallTelemetryIO(options.io);+ const stateFile = getTelemetryStateFile(env, io);+ const state = loadOrCreateState(stateFile, io);+ const projectRoot = path.resolve(env["INIT_CWD"] || io.cwd());+ const projectIdentity = resolveProjectIdentity(projectRoot, env, io);+ const packageManager = detectPackageManager(env);+ const ci = detectCI(env);++ payload = {+ distinctId: state.distinctId,+ event: INSTALL_EVENT,+ properties: {+ telemetry_schema_version: TELEMETRY_SCHEMA_VERSION,+ project_id: hashProjectIdentity(state.projectSalt, projectIdentity.value),+ project_id_source: projectIdentity.source,+ lang_core_version:+ env["OPENUI_LANG_CORE_PACKAGE_VERSION"] || env["npm_package_version"] || "unknown",+ node_version: process.version,+ system_platform: io.platform,+ system_release: io.release(),+ system_architecture: io.architecture,+ package_manager: packageManager.name,+ ...(packageManager.version ? { package_manager_version: packageManager.version } : {}),+ ci: ci.ci,+ ...(ci.name ? { ci_name: ci.name } : {}),+ is_docker: io.isDocker(),+ },+ };++ if (!state.langCorePostinstallNoticeShown) {+ io.stderr(INSTALL_NOTICE);+ state.langCorePostinstallNoticeShown = true;+ }+ persistState(stateFile, state, io);++ if (isTruthyEnv(env["OPENUI_TELEMETRY_DEBUG"])) {+ io.stdout(`[OpenUI telemetry debug]\n${JSON.stringify(payload, null, 2)}\n`);+ return { status: "debug", payload };+ }++ await (options.send ?? sendToPostHog)(payload, env);+ return { status: "sent", payload };+ } catch {+ return { status: "failed", ...(payload ? { payload } : {}) };+ }+}++function createInstallTelemetryIO(overrides: Partial<InstallTelemetryIO> = {}): InstallTelemetryIO {+ return {+ cwd: () => process.cwd(),+ homedir,+ readFile: (file) => readFileSync(file, "utf8"),+ writeFile: (file, contents, options) => writeFileSync(file, contents, options),+ mkdir: (directory) => mkdirSync(directory, { recursive: true, mode: 0o700 }),+ getGitOrigin: defaultGetGitOrigin,+ platform: process.platform,+ architecture: process.arch,+ release,+ randomUUID,+ randomHex: (bytes) => randomBytes(bytes).toString("hex"),+ isDocker: defaultIsDocker,+ stdout: (message) => process.stdout.write(message),+ stderr: (message) => process.stderr.write(message),+ ...overrides,+ };+}++function getTelemetryStateFile(env: NodeJS.ProcessEnv, io: InstallTelemetryIO): string {+ const configRoot = env["XDG_CONFIG_HOME"] || path.join(io.homedir(), ".config");+ return path.join(configRoot, "openui", "telemetry.json");+}++function loadOrCreateState(stateFile: string, io: InstallTelemetryIO): StoredTelemetryState {+ let stored: Record<string, unknown> = {};+ try {+ const parsed = JSON.parse(io.readFile(stateFile)) as unknown;+ if (isRecord(parsed)) stored = parsed;+ } catch {+ // Missing or corrupt state is replaced with a new best-effort state.+ }++ return {+ ...stored,+ distinctId:+ typeof stored["distinctId"] === "string" && stored["distinctId"]+ ? stored["distinctId"]+ : io.randomUUID(),+ projectSalt:+ typeof stored["projectSalt"] === "string" && stored["projectSalt"]+ ? stored["projectSalt"]+ : io.randomHex(16),+ langCorePostinstallNoticeShown: stored["langCorePostinstallNoticeShown"] === true,+ };+}++function persistState(+ stateFile: string,+ state: StoredTelemetryState,+ io: InstallTelemetryIO,+): void {+ try {+ io.mkdir(path.dirname(stateFile));+ io.writeFile(stateFile, JSON.stringify(state), { mode: 0o600 });+ } catch {+ // Read-only or ephemeral environments use the in-memory state for this run.+ }+}++function resolveProjectIdentity(+ projectRoot: string,+ env: NodeJS.ProcessEnv,+ io: InstallTelemetryIO,+): ProjectIdentity {+ const gitOrigin = io.getGitOrigin(projectRoot)?.trim();+ if (gitOrigin) {+ return { value: normalizeProjectIdentity(gitOrigin), source: "git_origin" };+ }++ const repositoryUrl = env["REPOSITORY_URL"]?.trim();+ if (repositoryUrl) {+ return {+ value: normalizeProjectIdentity(repositoryUrl),+ source: "repository_url",+ };+ }++ return { value: projectRoot, source: "install_root" };+}++function defaultGetGitOrigin(projectRoot: string): string | undefined {+ try {+ return execFileSync("git", ["-C", projectRoot, "config", "--get", "remote.origin.url"], {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ timeout: 1000,+ }).trim();+ } catch {+ return undefined;+ }+}++function defaultIsDocker(): boolean {+ if (existsSync("/.dockerenv")) return true;+ try {+ return /docker|containerd|kubepods/i.test(readFileSync("/proc/self/cgroup", "utf8"));+ } catch {+ return false;+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++async function sendToPostHog(+ payload: InstallTelemetryPayload,+ env: NodeJS.ProcessEnv,+): Promise<void> {+ const postHog = getPostHogConfig(env);+ const response = await fetch(postHog.captureUrl, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ api_key: postHog.apiKey,+ event: payload.event,+ properties: {+ distinct_id: payload.distinctId,+ ...payload.properties,+ },+ }),+ signal: AbortSignal.timeout(TELEMETRY_REQUEST_TIMEOUT_MS),+ });++ if (!response.ok) throw new Error(`PostHog capture failed: ${response.status}`);+}diff --git a/packages/lang-core/src/telemetry.ts b/packages/lang-core/src/telemetry/runtime.tssimilarity index 82%rename from packages/lang-core/src/telemetry.tsrename to packages/lang-core/src/telemetry/runtime.tsindex b27be1982..c4bc60a64 100644--- a/packages/lang-core/src/telemetry.ts+++ b/packages/lang-core/src/telemetry/runtime.ts@@ -1,4 +1,12 @@-import type { PromptSpec } from "./parser/prompt";+import type { PromptSpec } from "../parser/prompt";+import {+ detectCI,+ getPostHogConfig,+ isTelemetryDisabled,+ normalizeProjectIdentity,+ TELEMETRY_REQUEST_TIMEOUT_MS,+ TELEMETRY_SCHEMA_VERSION,+} from "./shared";/*** Telemetry disclosure@@ -26,13 +34,10 @@ declare const __OPENUI_LANG_CORE_VERSION__: string;const EVENT_NAME = "lang_core_system_prompt_generation_used";const SAMPLE_RATE = 0.1;-const REQUEST_TIMEOUT_MS = 2_000;const SDK_VERSION =typeof __OPENUI_LANG_CORE_VERSION__ === "string"? __OPENUI_LANG_CORE_VERSION__: "0.0.0-development";-const CAPTURE_URL = "https://dgoeivjus9jfp.cloudfront.net/capture/";-const POSTHOG_KEY = "phc_3OLW53x09ZTVZSV6BEpj5uycj3ooqR6KOemOjx04e3D";type Json = null | boolean | number | string | Json[] | { [key: string]: Json };type InputShape = "library_spec" | "legacy_prompt_spec";@@ -63,7 +68,7 @@ interface CaptureProperties {distinct_id: string;$process_person_profile: false;event_id: string;- telemetry_schema_version: 1;+ telemetry_schema_version: typeof TELEMETRY_SCHEMA_VERSION;system_prompt_config_hash_version: 1;system_prompt_config_hash: string;project_hash_version?: 1;@@ -212,28 +217,6 @@ function getEnvironment(env: Record<string, string | undefined> | undefined): Enreturn "unknown";}-function isTruthyOptOut(value: string | undefined): boolean {- return value === "1" || value?.toLowerCase() === "true";-}--function isCi(env: Record<string, string | undefined> | undefined): boolean {- if (!env) return false;- return [- "CI",- "CONTINUOUS_INTEGRATION",- "BUILD_NUMBER",- "GITHUB_ACTIONS",- "GITLAB_CI",- "BUILDKITE",- "CIRCLECI",- "VERCEL",- "NETLIFY",- ].some((name) => {- const value = env[name];- return Boolean(value && value !== "0" && value.toLowerCase() !== "false");- });-}-function getState(): TelemetryState {const registry = globalThis as typeof globalThis & { [STATE_KEY]?: TelemetryState };registry[STATE_KEY] ??= {@@ -242,35 +225,6 @@ function getState(): TelemetryState {return registry[STATE_KEY];}-function normalizeRepositoryIdentifier(rawValue: string): string | undefined {- const value = rawValue.trim();- if (!value) return undefined;-- try {- const url = new URL(value);- const pathname = decodeURIComponent(url.pathname)- .replace(/^\/+|\/+$/g, "")- .replace(/\.git$/i, "");- if (url.hostname && pathname) return `${url.hostname.toLowerCase()}/${pathname}`;- } catch {- // SCP-style Git origins and local paths are handled below.- }-- if (/^[A-Za-z]:[\\/]/.test(value)) {- return value.replace(/\\/g, "/").replace(/\/+$/g, "");- }-- const scpMatch = /^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/.exec(value);- if (scpMatch) {- const host = scpMatch[1]?.toLowerCase();- const pathname = scpMatch[2]?.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");- if (host && pathname) return `${host}/${pathname}`;- }-- // Local paths are still useful as a last-resort, deployment-local identifier.- return value.replace(/\\/g, "/").replace(/\/+$/g, "");-}-function readGitOrigin(processLike: ProcessLike): Promise<string | undefined> {const childProcess = processLike.getBuiltinModule?.("node:child_process") as| {@@ -314,11 +268,11 @@ async function getRepositoryIdentifier(const rawValue =(await readGitOrigin(processLike)) || processLike.env?.REPOSITORY_URL || processLike.cwd?.();- return rawValue ? normalizeRepositoryIdentifier(rawValue) : undefined;+ return rawValue ? normalizeProjectIdentity(rawValue) || undefined : undefined;}export function calculateProjectHash(repositoryIdentifier: string): Promise<string> {- const normalized = normalizeRepositoryIdentifier(repositoryIdentifier);+ const normalized = normalizeProjectIdentity(repositoryIdentifier);if (!normalized) return Promise.reject(new TypeError("Repository identifier is empty"));return sha256(normalized);}@@ -346,11 +300,12 @@ async function sendCapture(getProjectHash(state, runtime),]);+ const postHog = getPostHogConfig(runtime.env);const properties: CaptureProperties = {distinct_id: state.runtimeId,$process_person_profile: false,event_id: globalThis.crypto.randomUUID(),- telemetry_schema_version: 1,+ telemetry_schema_version: TELEMETRY_SCHEMA_VERSION,system_prompt_config_hash_version: 1,system_prompt_config_hash: systemPromptConfigHash,component_count: Object.keys(spec.components).length,@@ -362,7 +317,7 @@ async function sendCapture(runtime: runtime.name,runtime_version: runtime.version,environment,- ci: isCi(runtime.env),+ ci: detectCI(runtime.env).ci,sample_rate: SAMPLE_RATE,...(projectHash? {@@ -372,17 +327,17 @@ async function sendCapture(: {}),};- await globalThis.fetch(CAPTURE_URL, {+ await globalThis.fetch(postHog.captureUrl, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({- api_key: POSTHOG_KEY,+ api_key: postHog.apiKey,event: EVENT_NAME,timestamp: new Date().toISOString(),properties,}),keepalive: true,- signal: globalThis.AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ signal: globalThis.AbortSignal.timeout(TELEMETRY_REQUEST_TIMEOUT_MS),});}@@ -401,9 +356,7 @@ export function recordSystemPromptGeneration(spec: PromptSpec, inputShape: Inputconst env = runtime.env;const environment = getEnvironment(env);- if (isTruthyOptOut(env?.DO_NOT_TRACK) || isTruthyOptOut(env?.OPENUI_TELEMETRY_DISABLED)) {- return;- }+ if (isTelemetryDisabled(env)) return;// Reject 90% of calls before projection, hashing, repository lookup, or payload allocation.if (Math.random() >= SAMPLE_RATE) return;diff --git a/packages/lang-core/src/telemetry/shared.ts b/packages/lang-core/src/telemetry/shared.tsnew file mode 100644index 000000000..25a24fcb4--- /dev/null+++ b/packages/lang-core/src/telemetry/shared.ts@@ -0,0 +1,100 @@+// Browser-safe primitives shared by runtime and installation telemetry.+export const POSTHOG_KEY = "phc_3OLW53x09ZTVZSV6BEpj5uycj3ooqR6KOemOjx04e3D";+export const POSTHOG_HOST = "https://dgoeivjus9jfp.cloudfront.net";+export const TELEMETRY_REQUEST_TIMEOUT_MS = 2_000;+export const TELEMETRY_SCHEMA_VERSION = 1;++export type TelemetryEnvironment = Readonly<Record<string, string | undefined>>;++export type CiName =+ | "github_actions"+ | "gitlab_ci"+ | "buildkite"+ | "circleci"+ | "vercel"+ | "netlify"+ | "jenkins"+ | "travis";++const CI_PROVIDERS: ReadonlyArray<readonly [string, CiName]> = [+ ["GITHUB_ACTIONS", "github_actions"],+ ["GITLAB_CI", "gitlab_ci"],+ ["BUILDKITE", "buildkite"],+ ["CIRCLECI", "circleci"],+ ["VERCEL", "vercel"],+ ["NETLIFY", "netlify"],+ ["JENKINS_URL", "jenkins"],+ ["TRAVIS", "travis"],+];++const GENERIC_CI_ENV_VARS = ["CI", "CONTINUOUS_INTEGRATION", "BUILD_NUMBER"] as const;++export function getPostHogConfig(env?: TelemetryEnvironment): {+ apiKey: string;+ captureUrl: string;+} {+ const host = env?.["OPENUI_POSTHOG_HOST"] ?? POSTHOG_HOST;+ return {+ apiKey: env?.["OPENUI_POSTHOG_KEY"] ?? POSTHOG_KEY,+ captureUrl: new URL("/capture/", host).toString(),+ };+}++export function isTruthyEnv(value?: string): boolean {+ return value === "1" || value?.toLowerCase() === "true";+}++export function isTelemetryDisabled(env?: TelemetryEnvironment): boolean {+ return isTruthyEnv(env?.["OPENUI_TELEMETRY_DISABLED"]) || isTruthyEnv(env?.["DO_NOT_TRACK"]);+}++export function detectCI(env?: TelemetryEnvironment): { ci: boolean; name?: CiName } {+ if (!env) return { ci: false };++ const provider = CI_PROVIDERS.find(([key]) => isEnabledEnvValue(env[key]));+ return {+ ci: Boolean(provider) || GENERIC_CI_ENV_VARS.some((key) => isEnabledEnvValue(env[key])),+ ...(provider ? { name: provider[1] } : {}),+ };+}++export function normalizeProjectIdentity(rawValue: string): string {+ const value = rawValue.trim();+ if (!value) return "";++ try {+ const url = new URL(value);+ const repositoryPath = normalizeRepositoryPath(decodeURIComponent(url.pathname));+ if (url.protocol === "file:") return `file:${repositoryPath}`;+ if (url.host) return joinHostAndPath(url.host, repositoryPath);+ } catch {+ // SCP-style Git origins and local paths are handled below.+ }++ if (/^[A-Za-z]:[\\/]/.test(value)) return normalizeRepositoryPath(value);++ const scpMatch = /^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/.exec(value);+ if (scpMatch) return joinHostAndPath(scpMatch[1]!, scpMatch[2]!);++ return normalizeRepositoryPath(value);+}++function isEnabledEnvValue(value: string | undefined): boolean {+ if (!value) return false;+ const normalized = value.toLowerCase();+ return normalized !== "0" && normalized !== "false";+}++function joinHostAndPath(host: string, repositoryPath: string): string {+ const normalizedHost = host.trim().toLowerCase();+ const normalizedPath = normalizeRepositoryPath(repositoryPath);+ return normalizedPath ? `${normalizedHost}/${normalizedPath}` : normalizedHost;+}++function normalizeRepositoryPath(repositoryPath: string): string {+ return repositoryPath+ .trim()+ .replace(/\\/g, "/")+ .replace(/^\/+|\/+$/g, "")+ .replace(/\.git$/i, "");+}diff --git a/packages/lang-core/tsdown.config.ts b/packages/lang-core/tsdown.config.tsindex 74c52dbb9..b805735df 100644--- a/packages/lang-core/tsdown.config.ts+++ b/packages/lang-core/tsdown.config.ts@@ -2,7 +2,7 @@ import { defineConfig } from "tsdown";import packageJson from "./package.json" with { type: "json" };export default defineConfig({- entry: ["src/index.ts"],+ entry: ["src/index.ts", "src/postinstall.ts"],format: ["esm", "cjs"],dts: true,sourcemap: true,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1c66a635f..9c1404a3a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1773,6 +1773,9 @@ importers:'@modelcontextprotocol/sdk':specifier: ^1.27.1version: 1.30.0(@cfworker/[email protected])([email protected])+ '@types/node':+ specifier: ^20+ version: 20.19.43vitest:specifier: ^4.0.18version: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))