@usebetterdev/audit-cli 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/check.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CheckOutput, CheckResult } from '@usebetterdev/cli-utils';
1
+ import { CliSilentExitError, CheckOutput, CheckResult } from '@usebetterdev/cli-utils';
2
2
  export { CheckOutput, CheckResult } from '@usebetterdev/cli-utils';
3
3
  import { ColumnType } from '@usebetterdev/audit-core';
4
4
  import { D as DatabaseDialect } from './detect-adapter-WIB0ARFR.js';
@@ -23,7 +23,7 @@ interface CheckOptions {
23
23
  verbose?: boolean | undefined;
24
24
  }
25
25
  /** Thrown when one or more checks fail. Carries the full output for CLI rendering. */
26
- declare class CheckFailedError extends Error {
26
+ declare class CheckFailedError extends CliSilentExitError {
27
27
  readonly output: CheckOutput;
28
28
  constructor(output: CheckOutput);
29
29
  }
package/dist/check.js CHANGED
@@ -5,10 +5,10 @@ import {
5
5
  checkColumns,
6
6
  checkIndexes,
7
7
  runCheck
8
- } from "./chunk-AURUOQDN.js";
9
- import "./chunk-O5LHE2AC.js";
8
+ } from "./chunk-PGOZIYS5.js";
9
+ import "./chunk-Q23AEDWF.js";
10
10
  import "./chunk-7GSN73TA.js";
11
- import "./chunk-IJDJMOCO.js";
11
+ import "./chunk-GHOKL227.js";
12
12
  export {
13
13
  CheckFailedError,
14
14
  DIALECT_TYPE_MAP,
@@ -1,17 +1,23 @@
1
1
  import {
2
- generateMigrationSql
3
- } from "./chunk-O5LHE2AC.js";
2
+ generateMigrationSql,
3
+ generatePluginMigrationSql
4
+ } from "./chunk-Q23AEDWF.js";
4
5
  import {
5
6
  detectDialect,
6
7
  detectOrmAdapter,
7
8
  findMigrationDirectory,
8
9
  formatTimestamp
9
- } from "./chunk-IJDJMOCO.js";
10
+ } from "./chunk-GHOKL227.js";
10
11
 
11
12
  // src/migrate.ts
12
13
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "fs";
13
14
  import { dirname, join } from "path";
14
15
  import pc from "picocolors";
16
+ import {
17
+ loadBetterConfig,
18
+ BetterConfigNotFoundError
19
+ } from "@usebetterdev/plugin/config";
20
+ import { mergeSchemas } from "@usebetterdev/plugin";
15
21
  var AUDIT_TABLE_REGEX = /create\s+table\b[^;]*\baudit_logs\b/i;
16
22
  var MAX_SCAN_DEPTH = 3;
17
23
  function migrationAlreadyExists(directory, depth = 0) {
@@ -47,7 +53,10 @@ function migrationAlreadyExists(directory, depth = 0) {
47
53
  async function migrate(options = {}) {
48
54
  const cwd = options.cwd ?? process.cwd();
49
55
  const dialect = options.dialect ?? detectDialect(options.databaseUrl ?? process.env["DATABASE_URL"]);
50
- const sql = generateMigrationSql(dialect);
56
+ let sql = generateMigrationSql(dialect);
57
+ if (options.noPlugins !== true) {
58
+ sql += await loadPluginSql(cwd, dialect);
59
+ }
51
60
  if (options.dryRun === true) {
52
61
  process.stdout.write(sql);
53
62
  return;
@@ -94,8 +103,24 @@ async function migrate(options = {}) {
94
103
  console.log(` ${pc.yellow("$")} npx prisma migrate dev`);
95
104
  }
96
105
  }
106
+ async function loadPluginSql(cwd, dialect) {
107
+ try {
108
+ const config = await loadBetterConfig({ cwd });
109
+ const plugins = config.audit?.plugins;
110
+ if (!plugins || plugins.length === 0) {
111
+ return "";
112
+ }
113
+ const schema = mergeSchemas(plugins);
114
+ return generatePluginMigrationSql(schema, dialect);
115
+ } catch (error) {
116
+ if (error instanceof BetterConfigNotFoundError) {
117
+ return "";
118
+ }
119
+ throw error;
120
+ }
121
+ }
97
122
 
98
123
  export {
99
124
  migrate
100
125
  };
101
- //# sourceMappingURL=chunk-6HCQ22YY.js.map
126
+ //# sourceMappingURL=chunk-AWFOUH4H.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/migrate.ts"],"sourcesContent":["/**\n * `better-audit migrate` — Generate the audit_logs table migration.\n *\n * Generates appropriate DDL for the configured database:\n * - Postgres: JSONB columns, TIMESTAMPTZ, gen_random_uuid()\n * - MySQL: JSON columns, DATETIME(6), UUID() default\n * - SQLite: TEXT columns for JSON, no UUID default\n *\n * Writes the migration file into the appropriate ORM directory,\n * or prints to stdout with --dry-run.\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport pc from \"picocolors\";\nimport { generateMigrationSql, generatePluginMigrationSql, type DatabaseDialect } from \"./generate-sql.js\";\nimport { formatTimestamp } from \"@usebetterdev/cli-utils\";\nimport {\n detectAdapter,\n detectDialect,\n findMigrationDirectory,\n type AdapterType,\n} from \"./detect-adapter.js\";\nimport {\n loadBetterConfig,\n BetterConfigNotFoundError,\n} from \"@usebetterdev/plugin/config\";\nimport { mergeSchemas } from \"@usebetterdev/plugin\";\n\nexport interface MigrateOptions {\n /** Output SQL to stdout instead of writing a file */\n dryRun?: boolean | undefined;\n /** Override ORM auto-detection */\n adapter?: AdapterType | undefined;\n /** Override database dialect detection */\n dialect?: DatabaseDialect | undefined;\n /** Override output directory/file */\n output?: string | undefined;\n /** Working directory (defaults to process.cwd()) */\n cwd?: string | undefined;\n /** Database connection URL for dialect detection (defaults to DATABASE_URL env) */\n databaseUrl?: string | undefined;\n /** Skip plugin table generation even if plugins are configured */\n noPlugins?: boolean | undefined;\n}\n\n/** Regex to detect an existing audit_logs CREATE TABLE statement (case-insensitive). */\nconst AUDIT_TABLE_REGEX = /create\\s+table\\b[^;]*\\baudit_logs\\b/i;\n\n/** Maximum directory depth for the idempotency scan. */\nconst MAX_SCAN_DEPTH = 3;\n\n/**\n * Check if a migration for `audit_logs` already exists in the given directory.\n * Scans `.sql` files up to `MAX_SCAN_DEPTH` levels deep, skipping symlinks.\n */\nfunction migrationAlreadyExists(directory: string, depth: number = 0): boolean {\n if (depth > MAX_SCAN_DEPTH) {\n return false;\n }\n if (!existsSync(directory)) {\n return false;\n }\n\n try {\n const entries = readdirSync(directory, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n continue;\n }\n const fullPath = join(directory, entry.name);\n if (entry.isFile() && entry.name.endsWith(\".sql\")) {\n const content = readFileSync(fullPath, \"utf-8\");\n if (AUDIT_TABLE_REGEX.test(content)) {\n return true;\n }\n }\n if (entry.isDirectory()) {\n if (migrationAlreadyExists(fullPath, depth + 1)) {\n return true;\n }\n }\n }\n } catch {\n // Read error — treat as no existing migration\n }\n\n return false;\n}\n\nexport async function migrate(options: MigrateOptions = {}): Promise<void> {\n const cwd = options.cwd ?? process.cwd();\n\n // 1. Resolve dialect\n const dialect: DatabaseDialect =\n options.dialect ?? detectDialect(options.databaseUrl ?? process.env[\"DATABASE_URL\"]);\n\n // 2. Generate SQL\n let sql = generateMigrationSql(dialect);\n\n // 2b. Load plugin schemas from better.config.ts (unless --no-plugins)\n if (options.noPlugins !== true) {\n sql += await loadPluginSql(cwd, dialect);\n }\n\n // 3. Dry-run: print to stdout and return\n if (options.dryRun === true) {\n process.stdout.write(sql);\n return;\n }\n\n // 4. Resolve adapter\n const adapter: AdapterType | undefined =\n options.adapter ?? detectAdapter(cwd);\n\n if (adapter === undefined) {\n throw new Error(\n \"Could not detect ORM adapter. Install drizzle-orm or @prisma/client, \" +\n \"or pass --adapter drizzle|prisma.\",\n );\n }\n\n // 5. Resolve output directory\n let outputPath: string;\n let filePath: string;\n\n if (options.output !== undefined) {\n if (options.output.endsWith(\".sql\")) {\n filePath = options.output;\n outputPath = dirname(filePath);\n } else {\n outputPath = options.output;\n filePath =\n adapter === \"prisma\"\n ? join(outputPath, \"migration.sql\")\n : join(outputPath, `${formatTimestamp(new Date(), \"\")}_audit_logs.sql`);\n }\n } else {\n const migrationDir = findMigrationDirectory(cwd, adapter);\n outputPath = migrationDir;\n filePath =\n adapter === \"prisma\"\n ? join(migrationDir, \"migration.sql\")\n : join(migrationDir, `${formatTimestamp(new Date(), \"\")}_audit_logs.sql`);\n }\n\n // 6. Check idempotency — scan parent migration directory\n const scanDir =\n adapter === \"prisma\"\n ? join(cwd, \"prisma\", \"migrations\")\n : outputPath;\n\n if (migrationAlreadyExists(scanDir)) {\n console.log(\n pc.green(\"✓\") + \" audit_logs migration already exists — up to date.\",\n );\n return;\n }\n\n // 7. Warn if output file already exists (explicit --output path)\n if (options.output !== undefined && existsSync(filePath)) {\n console.warn(pc.yellow(`Warning: overwriting existing file ${filePath}`));\n }\n\n // 8. Write migration file\n mkdirSync(outputPath, { recursive: true });\n writeFileSync(filePath, sql, \"utf-8\");\n\n console.log(`${pc.green(\"✓\")} Wrote migration: ${pc.dim(filePath)}`);\n console.log(\"\");\n console.log(pc.bold(\"Next steps:\"));\n\n if (adapter === \"drizzle\") {\n console.log(` ${pc.yellow(\"$\")} npx drizzle-kit migrate`);\n } else {\n console.log(` ${pc.yellow(\"$\")} npx prisma migrate dev`);\n }\n}\n\n/**\n * Attempt to load better.config.ts and generate plugin migration SQL.\n * Returns empty string if config not found or no audit plugins defined.\n */\nasync function loadPluginSql(\n cwd: string,\n dialect: DatabaseDialect,\n): Promise<string> {\n try {\n const config = await loadBetterConfig({ cwd });\n const plugins = config.audit?.plugins;\n if (!plugins || plugins.length === 0) {\n return \"\";\n }\n const schema = mergeSchemas(plugins);\n return generatePluginMigrationSql(schema, dialect);\n } catch (error) {\n if (error instanceof BetterConfigNotFoundError) {\n return \"\";\n }\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAS,YAAY,WAAW,aAAa,cAAc,qBAAqB;AAChF,SAAS,SAAS,YAAY;AAC9B,OAAO,QAAQ;AASf;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAoB7B,IAAM,oBAAoB;AAG1B,IAAM,iBAAiB;AAMvB,SAAS,uBAAuB,WAAmB,QAAgB,GAAY;AAC7E,MAAI,QAAQ,gBAAgB;AAC1B,WAAO;AAAA,EACT;AACA,MAAI,CAAC,WAAW,SAAS,GAAG;AAC1B,WAAO;AAAA,EACT;AAEA,MAA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;AACd,QAAI,iBAAiB,2BAA2B;AAC9C,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -0,0 +1,15 @@
1
+ // src/parse-since.ts
2
+ var ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}(T[\w:.+-]+)?$/;
3
+ function parseIsoDate(value) {
4
+ const date = new Date(value);
5
+ if (Number.isNaN(date.getTime())) {
6
+ throw new Error(`Invalid date "${value}". Expected ISO-8601 format.`);
7
+ }
8
+ return date;
9
+ }
10
+
11
+ export {
12
+ ISO_DATE_REGEX,
13
+ parseIsoDate
14
+ };
15
+ //# sourceMappingURL=chunk-EEYS3G5Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parse-since.ts"],"sourcesContent":["/**\n * Shared ISO date parsing primitives for `--since` flag handling.\n *\n * Used by both `export.ts` and `purge.ts`. Each command has its own\n * `parseSinceValue()` with different return types and duration handling,\n * but they share the regex and ISO date validation logic.\n */\n\nexport const ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}(T[\\w:.+-]+)?$/;\n\n/**\n * Parse and validate an ISO-8601 date string.\n *\n * Throws if the value is not a valid date. Does **not** handle duration\n * strings — callers are responsible for duration resolution.\n */\nexport function parseIsoDate(value: string): Date {\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid date \"${value}\". Expected ISO-8601 format.`);\n }\n return date;\n}\n"],"mappings":";AAQO,IAAM,iBAAiB;AAQvB,SAAS,aAAa,OAAqB;AAChD,QAAM,OAAO,IAAI,KAAK,KAAK;AAC3B,MAAI,OAAO,MAAM,KAAK,QAAQ,CAAC,GAAG;AAChC,UAAM,IAAI,MAAM,iBAAiB,KAAK,8BAA8B;AAAA,EACtE;AACA,SAAO;AACT;","names":[]}
@@ -6,6 +6,7 @@ import { readFileSync as readFileSync2 } from "fs";
6
6
  import { dirname as dirname2, join as join3 } from "path";
7
7
  import { fileURLToPath } from "url";
8
8
  import pc2 from "picocolors";
9
+ import pc3 from "picocolors";
9
10
  function formatTimestamp(date, separator = "_") {
10
11
  const y = date.getFullYear();
11
12
  const m = String(date.getMonth() + 1).padStart(2, "0");
@@ -111,6 +112,36 @@ function printCheckResults(output, options) {
111
112
  }
112
113
  }
113
114
  }
115
+ var CliSilentExitError = class extends Error {
116
+ exitCode;
117
+ constructor(exitCode, message) {
118
+ super(message ?? `CLI exited with code ${String(exitCode)}`);
119
+ this.name = "CliSilentExitError";
120
+ this.exitCode = exitCode;
121
+ }
122
+ };
123
+ function formatErrorMessage(err) {
124
+ if (err instanceof AggregateError && err.errors.length > 0) {
125
+ const nested = err.errors.map((e) => e instanceof Error ? e.message : String(e)).join("; ");
126
+ return err.message !== "" ? `${err.message}: ${nested}` : nested;
127
+ }
128
+ if (err instanceof Error) {
129
+ return err.message;
130
+ }
131
+ return String(err);
132
+ }
133
+ async function runAction(fn) {
134
+ try {
135
+ await fn();
136
+ } catch (err) {
137
+ if (err instanceof CliSilentExitError) {
138
+ process.exit(err.exitCode);
139
+ }
140
+ const message = formatErrorMessage(err);
141
+ console.error(pc3.red(message));
142
+ process.exit(1);
143
+ }
144
+ }
114
145
 
115
146
  // src/detect-adapter.ts
116
147
  import { existsSync } from "fs";
@@ -148,7 +179,9 @@ export {
148
179
  detectOrmAdapter,
149
180
  readCliVersion,
150
181
  printCheckResults,
182
+ CliSilentExitError,
183
+ runAction,
151
184
  detectDialect,
152
185
  findMigrationDirectory
153
186
  };
154
- //# sourceMappingURL=chunk-IJDJMOCO.js.map
187
+ //# sourceMappingURL=chunk-GHOKL227.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../shared/cli-utils/src/format-timestamp.ts","../../../shared/cli-utils/src/write-sql-output.ts","../../../shared/cli-utils/src/detect-orm-adapter.ts","../../../shared/cli-utils/src/read-cli-version.ts","../../../shared/cli-utils/src/print-check-results.ts","../../../shared/cli-utils/src/cli-silent-exit-error.ts","../../../shared/cli-utils/src/format-error-message.ts","../../../shared/cli-utils/src/run-action.ts","../src/detect-adapter.ts"],"sourcesContent":["/**\n * Format a date as `YYYYMMDD<sep>HHMMSS`.\n *\n * @param date - The date to format.\n * @param separator - String inserted between date and time parts. Defaults to `\"_\"`.\n * Pass `\"\"` for a compact `YYYYMMDDHHMMSS` format (e.g. for Prisma migration directories).\n */\nexport function formatTimestamp(date: Date, separator: string = \"_\"): string {\n const y = date.getFullYear();\n const m = String(date.getMonth() + 1).padStart(2, \"0\");\n const d = String(date.getDate()).padStart(2, \"0\");\n const h = String(date.getHours()).padStart(2, \"0\");\n const min = String(date.getMinutes()).padStart(2, \"0\");\n const sec = String(date.getSeconds()).padStart(2, \"0\");\n return `${y}${m}${d}${separator}${h}${min}${sec}`;\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport pc from \"picocolors\";\n\n/**\n * Write SQL to a file. If `output` ends in `.sql`, treat it as a file path.\n * Otherwise treat it as a directory and generate a filename inside it.\n *\n * @returns `true` if the file was written, `false` if it already exists and `force` is not set.\n */\nexport function writeSqlOutput(\n sql: string,\n output: string,\n defaultFilename: string,\n force: boolean,\n): boolean {\n let filePath: string;\n if (output.endsWith(\".sql\")) {\n mkdirSync(dirname(output), { recursive: true });\n filePath = output;\n } else {\n mkdirSync(output, { recursive: true });\n filePath = join(output, defaultFilename);\n }\n const existed = existsSync(filePath);\n if (existed && !force) {\n console.error(pc.red(`File already exists: ${filePath}`));\n console.error(pc.dim(\"Use --force to overwrite.\"));\n return false;\n }\n if (existed) {\n console.warn(pc.yellow(`Warning: overwriting existing file ${filePath}`));\n }\n writeFileSync(filePath, sql, \"utf-8\");\n console.log(`${pc.green(\"✓\")} Wrote ${filePath}`);\n return true;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { OrmAdapter } from \"./types.js\";\n\n/**\n * Detect the ORM adapter from `package.json` dependencies.\n * Prefers drizzle when both are present.\n * Returns `undefined` if neither is found.\n */\nexport function detectOrmAdapter(cwd: string): OrmAdapter | undefined {\n const pkgPath = join(cwd, \"package.json\");\n if (!existsSync(pkgPath)) {\n return undefined;\n }\n\n try {\n const content = readFileSync(pkgPath, \"utf-8\");\n const parsed: unknown = JSON.parse(content);\n if (typeof parsed !== \"object\" || parsed === null) {\n return undefined;\n }\n\n const allDeps: Record<string, unknown> = {};\n if (\"dependencies\" in parsed && typeof parsed.dependencies === \"object\" && parsed.dependencies !== null) {\n Object.assign(allDeps, parsed.dependencies);\n }\n if (\"devDependencies\" in parsed && typeof parsed.devDependencies === \"object\" && parsed.devDependencies !== null) {\n Object.assign(allDeps, parsed.devDependencies);\n }\n\n if (\"drizzle-orm\" in allDeps) {\n return \"drizzle\";\n }\n if (\"@prisma/client\" in allDeps) {\n return \"prisma\";\n }\n } catch {\n // Invalid JSON or read error — skip detection\n }\n\n return undefined;\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Read the `version` field from the `package.json` located one directory above\n * the given `import.meta.url`.\n *\n * Returns `\"0.0.0\"` if the file cannot be read or does not contain a valid version.\n */\nexport function readCliVersion(metaUrl: string): string {\n const cliDir = dirname(fileURLToPath(metaUrl));\n try {\n const raw: unknown = JSON.parse(\n readFileSync(join(cliDir, \"..\", \"package.json\"), \"utf-8\"),\n );\n if (\n typeof raw === \"object\" &&\n raw !== null &&\n \"version\" in raw &&\n typeof raw.version === \"string\"\n ) {\n return raw.version;\n }\n } catch {\n // Read or parse error — fall through to default\n }\n return \"0.0.0\";\n}\n","import pc from \"picocolors\";\nimport type { CheckOutput, PrintCheckOptions } from \"./types.js\";\n\n/**\n * Print structured check results to stdout.\n *\n * When `verbose` is true, every individual check is printed.\n * Failed checks are always shown with details and optional remediation hints.\n * A summary line is always printed at the end.\n */\nexport function printCheckResults(\n output: CheckOutput,\n options?: PrintCheckOptions,\n): void {\n const verbose = options?.verbose === true;\n const failures: typeof output.results = [];\n let passedCount = 0;\n for (const r of output.results) {\n if (r.passed) {\n passedCount++;\n } else {\n failures.push(r);\n }\n }\n const failedCount = failures.length;\n\n // Verbose: show all individual checks\n if (verbose) {\n console.log(\"\");\n for (const r of output.results) {\n const icon = r.passed ? pc.green(\"✓\") : pc.red(\"✗\");\n const detail =\n r.message !== undefined ? pc.dim(` — ${r.message}`) : \"\";\n console.log(` ${icon} ${r.check}${detail}`);\n }\n }\n\n // Warnings\n if (output.warnings.length > 0) {\n console.log(\"\");\n for (const w of output.warnings) {\n console.log(` ${pc.yellow(\"⚠\")} ${w.message ?? w.check}`);\n }\n }\n\n // Summary\n console.log(\"\");\n if (output.passed) {\n console.log(pc.green(`✓ All ${passedCount} checks passed`));\n } else {\n console.log(\n pc.red(\n `✗ ${failedCount} check${failedCount === 1 ? \"\" : \"s\"} failed`,\n ) + pc.dim(`, ${passedCount} passed`),\n );\n\n // Failure details\n console.log(\"\");\n if (verbose) {\n // In verbose mode, individual results were already printed — just show remediation\n for (const f of failures) {\n if (f.remediation !== undefined) {\n console.log(` ${pc.cyan(\"→\")} ${f.check}: ${f.remediation}`);\n }\n }\n } else {\n // Default mode: show full failure details\n for (const f of failures) {\n console.log(` ${pc.red(\"✗\")} ${f.check}`);\n if (f.message !== undefined) {\n console.log(` ${f.message}`);\n }\n if (f.remediation !== undefined) {\n console.log(` ${pc.cyan(\"→\")} ${f.remediation}`);\n }\n }\n }\n }\n}\n","/**\n * Error class for CLI commands that have already rendered their output\n * or represent an intentional exit (e.g. user cancellation).\n *\n * `runAction` catches this and calls `process.exit(exitCode)` without\n * printing an additional error message.\n */\nexport class CliSilentExitError extends Error {\n readonly exitCode: number;\n\n constructor(exitCode: number, message?: string) {\n super(message ?? `CLI exited with code ${String(exitCode)}`);\n this.name = \"CliSilentExitError\";\n this.exitCode = exitCode;\n }\n}\n","/**\n * Extract a human-readable message from an error value.\n *\n * Handles `AggregateError` (common from pg connection failures where\n * `.message` is empty but nested errors contain the real details),\n * regular `Error`, and unknown/non-Error values.\n */\nexport function formatErrorMessage(err: unknown): string {\n if (err instanceof AggregateError && err.errors.length > 0) {\n const nested = err.errors\n .map((e: unknown) => (e instanceof Error ? e.message : String(e)))\n .join(\"; \");\n return err.message !== \"\" ? `${err.message}: ${nested}` : nested;\n }\n if (err instanceof Error) {\n return err.message;\n }\n return String(err);\n}\n","import pc from \"picocolors\";\nimport { CliSilentExitError } from \"./cli-silent-exit-error.js\";\nimport { formatErrorMessage } from \"./format-error-message.js\";\n\n/**\n * Wrap a CLI subcommand action with consistent error handling.\n *\n * - `CliSilentExitError` → `process.exit(exitCode)` (output already rendered)\n * - Other errors → red error message + `process.exit(1)`\n */\nexport async function runAction(fn: () => Promise<void>): Promise<void> {\n try {\n await fn();\n } catch (err) {\n if (err instanceof CliSilentExitError) {\n process.exit(err.exitCode);\n }\n const message = formatErrorMessage(err);\n console.error(pc.red(message));\n process.exit(1);\n }\n}\n","/**\n * Auto-detection utilities for ORM adapter, database dialect, and migration directories.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { detectOrmAdapter, formatTimestamp } from \"@usebetterdev/cli-utils\";\n\nexport { detectOrmAdapter as detectAdapter };\nexport type { OrmAdapter as AdapterType } from \"@usebetterdev/cli-utils\";\n\nexport type DatabaseDialect = \"postgres\" | \"mysql\" | \"sqlite\";\n\n/**\n * Detect the database dialect from a connection URL.\n * Falls back to `\"postgres\"` if the URL is missing or unrecognizable.\n */\nexport function detectDialect(databaseUrl?: string): DatabaseDialect {\n if (databaseUrl === undefined) {\n return \"postgres\";\n }\n\n const lower = databaseUrl.toLowerCase();\n\n if (lower.startsWith(\"postgres://\") || lower.startsWith(\"postgresql://\")) {\n return \"postgres\";\n }\n if (lower.startsWith(\"mysql://\")) {\n return \"mysql\";\n }\n if (lower.startsWith(\"file:\") || lower.endsWith(\".db\") || lower.endsWith(\".sqlite\") || lower.endsWith(\".sqlite3\")) {\n return \"sqlite\";\n }\n\n return \"postgres\";\n}\n\n/**\n * Determine the migration output directory based on the detected adapter.\n *\n * - **Drizzle**: `./drizzle/` (or `./supabase/migrations/` if that directory exists)\n * - **Prisma**: `./prisma/migrations/<timestamp_add_audit_logs>/migration.sql`\n */\nexport function findMigrationDirectory(\n cwd: string,\n adapter: \"drizzle\" | \"prisma\",\n): string {\n if (adapter === \"drizzle\") {\n const supabasePath = join(cwd, \"supabase\", \"migrations\");\n if (existsSync(supabasePath)) {\n return supabasePath;\n }\n return join(cwd, \"drizzle\");\n }\n\n // prisma\n const timestamp = formatTimestamp(new Date(), \"\");\n return join(cwd, \"prisma\", \"migrations\", `${timestamp}_add_audit_logs`);\n}\n"],"mappings":";ACEA,OAAO,QAAQ;ACFf,SAAS,cAAAA,aAAY,oBAAoB;AACzC,SAAS,QAAAC,aAAY;ACDrB,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,WAAAC,UAAS,QAAAF,aAAY;AAC9B,SAAS,qBAAqB;ACF9B,OAAOG,SAAQ;AGAf,OAAOA,SAAQ;APOR,SAAS,gBAAgB,MAAY,YAAoB,KAAa;AAC3E,QAAM,IAAI,KAAK,YAAY;AAC3B,QAAM,IAAI,OAAO,KAAK,SAAS,IAAI,CAAC,EAAE,SAAS,GAAG,GAAG;AACrD,QAAM,IAAI,OAAO,KAAK,QAAQ,CAAC,EAAE,SAAS,GAAG,GAAG;AAChD,QAAM,IAAI,OAAO,KAAK,SAAS,CAAC,EAAE,SAAS,GAAG,GAAG;AACjD,QAAM,MAAM,OAAO,KAAK,WAAW,CAAC,EAAE,SAAS,GAAG,GAAG;AACrD,QAAM,MAAM,OAAO,KAAK,WAAW,CAAC,EAAE,SAAS,GAAG,GAAG;AACrD,SAAO,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,CAAC,GAAG,GAAG,GAAG,GAAG;AACjD;AENO,SAAS,iBAAiB,KAAqC;AACpE,QAAM,UAAUC,MAAK,KAAK,cAAc;AACxC,MAAI,CAACC,YAAW,OAAO,GAAG;AACxB,W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AK,SAAS;AAAA,EAC5B;AAGA,QAAM,YAAY,gBAAgB,oBAAI,KAAK,GAAG,EAAE;AAChD,SAAO,KAAK,KAAK,UAAU,cAAc,GAAG,SAAS,iBAAiB;AACxE;","names":["existsSync","join","readFileSync","dirname","pc","join","existsSync","dirname","readFileSync","pc"]}
@@ -1,10 +1,14 @@
1
+ import {
2
+ ISO_DATE_REGEX,
3
+ parseIsoDate
4
+ } from "./chunk-EEYS3G5Y.js";
1
5
  import {
2
6
  createKyselyInstance,
3
7
  createSqlExecutor
4
8
  } from "./chunk-7GSN73TA.js";
5
9
  import {
6
10
  detectDialect
7
- } from "./chunk-IJDJMOCO.js";
11
+ } from "./chunk-GHOKL227.js";
8
12
 
9
13
  // src/export.ts
10
14
  import { createWriteStream } from "fs";
@@ -17,7 +21,6 @@ var VALID_SEVERITIES = /* @__PURE__ */ new Set([
17
21
  "high",
18
22
  "critical"
19
23
  ]);
20
- var ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}(T[\w:.+-]+)?$/;
21
24
  function parseFormat(value) {
22
25
  if (value === void 0) {
23
26
  return "csv";
@@ -29,6 +32,9 @@ function parseFormat(value) {
29
32
  }
30
33
  return value;
31
34
  }
35
+ function parseActors(value) {
36
+ return [...new Set(value.split(",").map((v) => v.trim()).filter((v) => v.length > 0))];
37
+ }
32
38
  function parseSeverity(value) {
33
39
  if (!VALID_SEVERITIES.has(value)) {
34
40
  throw new Error(
@@ -39,11 +45,7 @@ function parseSeverity(value) {
39
45
  }
40
46
  function parseSinceValue(value) {
41
47
  if (ISO_DATE_REGEX.test(value)) {
42
- const date = new Date(value);
43
- if (Number.isNaN(date.getTime())) {
44
- throw new Error(`Invalid date "${value}". Expected ISO-8601 format.`);
45
- }
46
- return date;
48
+ return parseIsoDate(value);
47
49
  }
48
50
  parseDuration(value);
49
51
  return value;
@@ -136,7 +138,8 @@ async function exportLogs(options) {
136
138
  builder = builder.compliance(...tags);
137
139
  }
138
140
  if (options.actor !== void 0) {
139
- builder = builder.actor(options.actor);
141
+ const actors = parseActors(options.actor);
142
+ builder = builder.actor(...actors);
140
143
  }
141
144
  if (options.limit !== void 0) {
142
145
  const n = Number(options.limit);
@@ -173,10 +176,11 @@ async function exportLogs(options) {
173
176
 
174
177
  export {
175
178
  parseFormat,
179
+ parseActors,
176
180
  parseSeverity,
177
181
  parseSinceValue,
178
182
  createFileWritableStream,
179
183
  createStdoutWritableStream,
180
184
  exportLogs
181
185
  };
182
- //# sourceMappingURL=chunk-TLZWAZAJ.js.map
186
+ //# sourceMappingURL=chunk-O4577NVP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/export.ts"],"sourcesContent":["/**\n * `better-audit export` — Export audit log entries as CSV or JSON.\n *\n * Connects to the database via Kysely (multi-dialect), builds query filters\n * from CLI flags, and streams results to a file or stdout.\n */\n\nimport { createWriteStream } from \"node:fs\";\nimport pc from \"picocolors\";\nimport { runExport, AuditQueryBuilder, parseDuration } from \"@usebetterdev/audit-core\";\nimport type { AuditSeverity, ExportOptions } from \"@usebetterdev/audit-core\";\nimport { createKyselyInstance, createSqlExecutor } from \"./sql-executor.js\";\nimport { detectDialect } from \"./detect-adapter.js\";\nimport { ISO_DATE_REGEX, parseIsoDate } from \"./parse-since.js\";\n\nconst VALID_FORMATS = new Set([\"csv\", \"json\"]);\nconst VALID_SEVERITIES: ReadonlySet<string> = new Set([\n \"low\",\n \"medium\",\n \"high\",\n \"critical\",\n]);\n\nexport interface ExportCommandOptions {\n format?: string;\n output?: string;\n since?: string;\n severity?: string;\n compliance?: string;\n actor?: string;\n limit?: string;\n databaseUrl?: string;\n}\n\n/** Parse `--format` flag, validate and default to \"csv\". */\nexport function parseFormat(value: string | undefined): \"csv\" | \"json\" {\n if (value === undefined) {\n return \"csv\";\n }\n if (!VALID_FORMATS.has(value)) {\n throw new Error(\n `Invalid format \"${value}\". Expected \"csv\" or \"json\".`,\n );\n }\n return value as \"csv\" | \"json\";\n}\n\n/** Parse `--actor` flag, split comma-separated values and deduplicate. */\nexport function parseActors(value: string): string[] {\n return [...new Set(value.split(\",\").map((v) => v.trim()).filter((v) => v.length > 0))];\n}\n\n/** Parse `--severity` flag, validate against known values. */\nexport function parseSeverity(value: string): AuditSeverity {\n if (!VALID_SEVERITIES.has(value)) {\n throw new Error(\n `Invalid severity \"${value}\". Expected one of: low, medium, high, critical.`,\n );\n }\n return value as AuditSeverity;\n}\n\n/**\n * Parse `--since` flag. ISO date strings (e.g. \"2025-01-01\") become Date objects.\n * Duration strings (e.g. \"90d\") are returned as-is for the query builder.\n */\nexport function parseSinceValue(value: string): Date | string {\n if (ISO_DATE_REGEX.test(value)) {\n return parseIsoDate(value);\n }\n // Validate as duration — throws if invalid\n parseDuration(value);\n return value;\n}\n\n/**\n * Bridge a single `nodeStream.write()` call into a Promise that respects\n * backpressure and settles exactly once — whichever of error/drain fires first.\n */\nfunction writeToNodeStream(\n nodeStream: NodeJS.WritableStream,\n chunk: string,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void) => {\n if (!settled) {\n settled = true;\n cleanup();\n fn();\n }\n };\n const onError = (err: Error) => { settle(() => reject(err)); };\n const onDrain = () => { settle(resolve); };\n const cleanup = () => {\n nodeStream.removeListener(\"error\", onError);\n nodeStream.removeListener(\"drain\", onDrain);\n };\n\n nodeStream.once(\"error\", onError);\n const canContinue = nodeStream.write(chunk);\n if (canContinue) {\n settle(resolve);\n } else {\n nodeStream.once(\"drain\", onDrain);\n }\n });\n}\n\n/**\n * Create a WHATWG WritableStream<string> that writes to a Node.js file.\n * Handles backpressure by awaiting the drain event.\n */\nexport function createFileWritableStream(\n path: string,\n): WritableStream<string> {\n const nodeStream = createWriteStream(path, { encoding: \"utf-8\" });\n\n return new WritableStream<string>({\n write(chunk) {\n return writeToNodeStream(nodeStream, chunk);\n },\n close() {\n return new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => { reject(err); };\n nodeStream.once(\"error\", onError);\n nodeStream.end(() => {\n nodeStream.removeListener(\"error\", onError);\n resolve();\n });\n });\n },\n abort() {\n nodeStream.destroy();\n },\n });\n}\n\n/** Create a WHATWG WritableStream<string> that writes to process.stdout. */\nexport function createStdoutWritableStream(): WritableStream<string> {\n return new WritableStream<string>({\n write(chunk) {\n return writeToNodeStream(process.stdout, chunk);\n },\n });\n}\n\nexport async function exportLogs(options: ExportCommandOptions): Promise<void> {\n // 1. Resolve DATABASE_URL\n const databaseUrl = options.databaseUrl ?? process.env[\"DATABASE_URL\"];\n if (databaseUrl === undefined || databaseUrl === \"\") {\n throw new Error(\n \"DATABASE_URL is required. Set the DATABASE_URL environment variable or pass --database-url.\",\n );\n }\n\n // 2. Parse flags\n const format = parseFormat(options.format);\n\n // 3. Detect dialect + create Kysely instance\n const dialect = detectDialect(databaseUrl);\n const db = await createKyselyInstance(databaseUrl, dialect);\n\n try {\n const executor = createSqlExecutor(db, dialect);\n\n // 4. Build query\n let query: AuditQueryBuilder | undefined;\n const hasFilters =\n options.since !== undefined ||\n options.severity !== undefined ||\n options.compliance !== undefined ||\n options.actor !== undefined ||\n options.limit !== undefined;\n\n if (hasFilters) {\n let builder = new AuditQueryBuilder(executor);\n\n if (options.since !== undefined) {\n const sinceValue = parseSinceValue(options.since);\n builder = builder.since(sinceValue);\n }\n\n if (options.severity !== undefined) {\n const severity = parseSeverity(options.severity);\n builder = builder.severity(severity);\n }\n\n if (options.compliance !== undefined) {\n const tags = options.compliance.split(\",\").map((t) => t.trim());\n builder = builder.compliance(...tags);\n }\n\n if (options.actor !== undefined) {\n const actors = parseActors(options.actor);\n builder = builder.actor(...actors);\n }\n\n if (options.limit !== undefined) {\n const n = Number(options.limit);\n if (Number.isNaN(n) || n <= 0 || !Number.isInteger(n)) {\n throw new Error(\n `Invalid limit \"${options.limit}\". Expected a positive integer.`,\n );\n }\n builder = builder.limit(n);\n }\n\n query = builder;\n }\n\n // 5. Create output sink\n const outputPath = options.output;\n const output: WritableStream<string> = outputPath !== undefined\n ? createFileWritableStream(outputPath)\n : createStdoutWritableStream();\n\n // 6. Run export\n const exportOptions: ExportOptions = {\n format,\n output,\n ...(query !== undefined && { query }),\n };\n\n const result = await runExport(executor, exportOptions);\n\n // 7. Summary message\n if (outputPath !== undefined) {\n console.error(\n `${pc.green(\"✓\")} Exported ${result.rowCount} rows to ${pc.dim(outputPath)}`,\n );\n } else {\n console.error(\n `${pc.green(\"✓\")} Exported ${result.rowCount} rows`,\n );\n }\n } finally {\n await db.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAOA,SAAS,yBAAyB;AAClC,OAAO,QAAQ;AACf,SAAS,WAAW,mBAAmB,qBAAqB;AAM5D,IAAM,gBAAgB,oBAAI,IAAI,CAAC,OAAO,MAAM,CAAC;AAC7C,IAAM,mBAAwC,oBAAI,IAAI;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAcM,SAAS,YAAY,OAA2C;AACrE,MAAI,UAAU,QAAW;AACvB,WAAO;AAAA,EACT;AACA,MAAI,CAAC,cAAc,IAAI,KAAK,GAAG;AAC7B,UAAM,IAAI;AAAA,MACR,mBAAmB,KAAK;AAAA,IAC1B;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,YAAY,OAAyB;AACnD,SAAO,CAAC,GAAG,IAAI,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AACvF;AAGO,SAAS,cAAc,OAA8B;AAC1D,MAAI,CAAC,iBAAiB,IAAI,KAAK,GAAG;AAChC,UAAM,IAAI;AAAA,MACR,qBAAqB,KAAK;AAAA,IAC5B;AAAA,EACF;AACA,SAAO;AACT;AAMO,SAAS,gBAAgB,OAA8B;AAC5D,MAAI,eAAe,KAAK,KAAK,GAAG;AAC9B,WAAO,aAAa,KAAK;AAAA,EAC3B;AAEA,gBAAc,KAAK;AACnB,SAAO;AACT;AAMA,S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gBAAM,IAAI;AAAA,YACR,kBAAkB,QAAQ,KAAK;AAAA,UACjC;AAAA,QACF;AACA,kBAAU,QAAQ,MAAM,CAAC;AAAA,MAC3B;AAEA,cAAQ;AAAA,IACV;AAGA,UAAM,aAAa,QAAQ;AAC3B,UAAM,SAAiC,eAAe,SAClD,yBAAyB,UAAU,IACnC,2BAA2B;AAG/B,UAAM,gBAA+B;AAAA,MACnC;AAAA,MACA;AAAA,MACA,GAAI,UAAU,UAAa,EAAE,MAAM;AAAA,IACrC;AAEA,UAAM,SAAS,MAAM,UAAU,UAAU,aAAa;AAGtD,QAAI,eAAe,QAAW;AAC5B,cAAQ;AAAA,QACN,GAAG,GAAG,MAAM,QAAG,CAAC,aAAa,OAAO,QAAQ,YAAY,GAAG,IAAI,UAAU,CAAC;AAAA,MAC5E;AAAA,IACF,OAAO;AACL,cAAQ;AAAA,QACN,GAAG,GAAG,MAAM,QAAG,CAAC,aAAa,OAAO,QAAQ;AAAA,MAC9C;AAAA,IACF;AAAA,EACF,UAAE;AACA,UAAM,GAAG,QAAQ;AAAA,EACnB;AACF;","names":[]}
@@ -1,22 +1,23 @@
1
1
  import {
2
2
  INDEX_DEFINITIONS
3
- } from "./chunk-O5LHE2AC.js";
3
+ } from "./chunk-Q23AEDWF.js";
4
4
  import {
5
5
  createKyselyInstance
6
6
  } from "./chunk-7GSN73TA.js";
7
7
  import {
8
+ CliSilentExitError,
8
9
  detectDialect,
9
10
  printCheckResults
10
- } from "./chunk-IJDJMOCO.js";
11
+ } from "./chunk-GHOKL227.js";
11
12
 
12
13
  // src/check.ts
13
14
  import { randomUUID } from "crypto";
14
15
  import { sql } from "kysely";
15
16
  import { AUDIT_LOG_SCHEMA } from "@usebetterdev/audit-core";
16
- var CheckFailedError = class extends Error {
17
+ var CheckFailedError = class extends CliSilentExitError {
17
18
  output;
18
19
  constructor(output) {
19
- super("One or more audit checks failed");
20
+ super(1, "One or more audit checks failed");
20
21
  this.name = "CheckFailedError";
21
22
  this.output = output;
22
23
  }
@@ -30,21 +31,24 @@ var DIALECT_TYPE_MAP = {
30
31
  timestamptz: ["timestamptz"],
31
32
  text: ["text"],
32
33
  jsonb: ["jsonb"],
33
- boolean: ["bool"]
34
+ boolean: ["bool"],
35
+ integer: ["integer"]
34
36
  },
35
37
  mysql: {
36
38
  uuid: ["char"],
37
39
  timestamptz: ["datetime"],
38
40
  text: ["text", "mediumtext", "longtext"],
39
41
  jsonb: ["json"],
40
- boolean: ["tinyint"]
42
+ boolean: ["tinyint"],
43
+ integer: ["bigint", "int"]
41
44
  },
42
45
  sqlite: {
43
46
  uuid: ["TEXT"],
44
47
  timestamptz: ["TEXT"],
45
48
  text: ["TEXT"],
46
49
  jsonb: ["TEXT"],
47
- boolean: ["INTEGER"]
50
+ boolean: ["INTEGER"],
51
+ integer: ["INTEGER"]
48
52
  }
49
53
  };
50
54
  function normalizeReportedType(raw, dialect) {
@@ -358,4 +362,4 @@ export {
358
362
  runCheck,
359
363
  check
360
364
  };
361
- //# sourceMappingURL=chunk-AURUOQDN.js.map
365
+ //# sourceMappingURL=chunk-PGOZIYS5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/check.ts"],"sourcesContent":["/**\n * `better-audit check` — Verify audit_logs table schema, indexes, and write path.\n *\n * Performs:\n * 1. Database connectivity test\n * 2. Schema validation: table exists, columns have correct types and nullability\n * 3. Index validation: all expected indexes are present\n * 4. Live integration test: sentinel INSERT → SELECT → verify actor_id → DELETE\n *\n * Supports Postgres, MySQL, and SQLite via dialect-specific introspection queries.\n *\n * Exits with code 0 on success, 1 on failure.\n * All sentinel data is cleaned up regardless of check outcome.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { sql } from \"kysely\";\nimport type { Kysely } from \"kysely\";\nimport { printCheckResults, CliSilentExitError, type CheckResult, type CheckOutput } from \"@usebetterdev/cli-utils\";\nimport { AUDIT_LOG_SCHEMA, type ColumnType } from \"@usebetterdev/audit-core\";\nimport { createKyselyInstance } from \"./sql-executor.js\";\nimport type { Database } from \"./sql-executor.js\";\nimport { detectDialect, type DatabaseDialect } from \"./detect-adapter.js\";\nimport { INDEX_DEFINITIONS } from \"./generate-sql.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type { CheckResult, CheckOutput };\n\nexport interface CheckOptions {\n databaseUrl?: string | undefined;\n verbose?: boolean | undefined;\n}\n\n/** Thrown when one or more checks fail. Carries the full output for CLI rendering. */\nexport class CheckFailedError extends CliSilentExitError {\n readonly output: CheckOutput;\n constructor(output: CheckOutput) {\n super(1, \"One or more audit checks failed\");\n this.name = \"CheckFailedError\";\n this.output = output;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst SENTINEL_TABLE_NAME = \"__audit_cli_check__\";\nconst SENTINEL_ACTOR_ID = \"__check_actor__\";\nconst SENTINEL_RECORD_ID = \"__sentinel__\";\n\n/**\n * Map from core ColumnType to the type string each dialect reports via\n * introspection. Mirrors the sqlType map in generate-sql.ts but in the\n * direction the database returns (lowercase / as-reported).\n *\n * Postgres: information_schema.columns → udt_name\n * MySQL: information_schema.columns → data_type (lowercase)\n * SQLite: PRAGMA table_info → type (uppercase, as declared)\n */\nexport const DIALECT_TYPE_MAP: Record<\n DatabaseDialect,\n Record<ColumnType, ReadonlyArray<string>>\n> = {\n postgres: {\n uuid: [\"uuid\"],\n timestamptz: [\"timestamptz\"],\n text: [\"text\"],\n jsonb: [\"jsonb\"],\n boolean: [\"bool\"],\n integer: [\"integer\"],\n },\n mysql: {\n uuid: [\"char\"],\n timestamptz: [\"datetime\"],\n text: [\"text\", \"mediumtext\", \"longtext\"],\n jsonb: [\"json\"],\n boolean: [\"tinyint\"],\n integer: [\"bigint\", \"int\"],\n },\n sqlite: {\n uuid: [\"TEXT\"],\n timestamptz: [\"TEXT\"],\n text: [\"TEXT\"],\n jsonb: [\"TEXT\"],\n boolean: [\"INTEGER\"],\n integer: [\"INTEGER\"],\n },\n};\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\n/** Normalize a reported type string for comparison against the dialect map. */\nfunction normalizeReportedType(\n raw: string,\n dialect: DatabaseDialect,\n): string {\n if (dialect === \"sqlite\") {\n return raw.toUpperCase();\n }\n // Postgres udt_name and MySQL data_type are already lowercase\n return raw.toLowerCase();\n}\n\n/** Check whether `actual` matches any of the acceptable types for a column. */\nfunction typeMatches(\n actual: string,\n definition: { type: ColumnType },\n dialect: DatabaseDialect,\n): boolean {\n const normalized = normalizeReportedType(actual, dialect);\n const acceptable = DIALECT_TYPE_MAP[dialect][definition.type];\n return acceptable.includes(normalized);\n}\n\n/** Build the \"expected\" label shown in error messages. */\nfunction expectedTypeLabel(\n definition: { type: ColumnType },\n dialect: DatabaseDialect,\n): string {\n const acceptable = DIALECT_TYPE_MAP[dialect][definition.type];\n if (acceptable.length === 1) {\n return acceptable[0] ?? definition.type;\n }\n return acceptable.join(\" | \");\n}\n\n// ---------------------------------------------------------------------------\n// Individual checks\n// ---------------------------------------------------------------------------\n\nasync function checkConnection(\n db: Kysely<Database>,\n): Promise<CheckResult> {\n try {\n await sql`SELECT 1`.execute(db);\n return { check: \"database connection\", passed: true };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n check: \"database connection\",\n passed: false,\n message: `Cannot connect to database: ${message}`,\n remediation:\n \"Verify DATABASE_URL is correct and the database server is running\",\n };\n }\n}\n\nasync function checkTableExists(\n db: Kysely<Database>,\n): Promise<CheckResult> {\n try {\n await sql`SELECT 1 FROM audit_logs WHERE 1 = 0`.execute(db);\n return { check: \"audit_logs table exists\", passed: true };\n } catch {\n return {\n check: \"audit_logs table exists\",\n passed: false,\n message: \"Table audit_logs not found\",\n remediation:\n \"Run `npx @usebetterdev/audit-cli migrate` to create the table\",\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Column checks — per-dialect introspection\n// ---------------------------------------------------------------------------\n\ninterface IntrospectedColumn {\n name: string;\n reportedType: string;\n nullable: boolean;\n}\n\nasync function introspectColumnsPostgres(\n db: Kysely<Database>,\n): Promise<IntrospectedColumn[]> {\n const result = await sql<{\n column_name: string;\n udt_name: string;\n is_nullable: string;\n }>`\n SELECT column_name, udt_name, is_nullable\n FROM information_schema.columns\n WHERE table_schema = 'public' AND table_name = ${AUDIT_LOG_SCHEMA.tableName}\n ORDER BY ordinal_position\n `.execute(db);\n\n return result.rows.map((row) => ({\n name: row.column_name,\n reportedType: row.udt_name,\n nullable: row.is_nullable === \"YES\",\n }));\n}\n\nasync function introspectColumnsMysql(\n db: Kysely<Database>,\n): Promise<IntrospectedColumn[]> {\n const result = await sql<{\n COLUMN_NAME: string;\n DATA_TYPE: string;\n IS_NULLABLE: string;\n }>`\n SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE\n FROM information_schema.columns\n WHERE table_schema = DATABASE() AND table_name = ${AUDIT_LOG_SCHEMA.tableName}\n ORDER BY ORDINAL_POSITION\n `.execute(db);\n\n return result.rows.map((row) => ({\n name: row.COLUMN_NAME,\n reportedType: row.DATA_TYPE,\n nullable: row.IS_NULLABLE === \"YES\",\n }));\n}\n\nasync function introspectColumnsSqlite(\n db: Kysely<Database>,\n): Promise<IntrospectedColumn[]> {\n const result = await sql<{\n name: string;\n type: string;\n notnull: number;\n }>`PRAGMA table_info(audit_logs)`.execute(db);\n\n return result.rows.map((row) => ({\n name: row.name,\n reportedType: row.type,\n nullable: row.notnull === 0,\n }));\n}\n\nasync function introspectColumns(\n db: Kysely<Database>,\n dialect: DatabaseDialect,\n): Promise<IntrospectedColumn[]> {\n if (dialect === \"mysql\") {\n return introspectColumnsMysql(db);\n }\n if (dialect === \"sqlite\") {\n return introspectColumnsSqlite(db);\n }\n return introspectColumnsPostgres(db);\n}\n\nfunction checkColumns(\n columns: ReadonlyArray<IntrospectedColumn>,\n dialect: DatabaseDialect,\n): CheckResult[] {\n const results: CheckResult[] = [];\n\n const actualColumns = new Map<string, IntrospectedColumn>();\n for (const col of columns) {\n actualColumns.set(col.name, col);\n }\n\n for (const [name, definition] of Object.entries(AUDIT_LOG_SCHEMA.columns)) {\n const actual = actualColumns.get(name);\n\n if (actual === undefined) {\n results.push({\n check: `column ${name}`,\n passed: false,\n message: `Missing column: ${name}`,\n remediation:\n \"Run `npx @usebetterdev/audit-cli migrate` to add missing columns\",\n });\n continue;\n }\n\n // Type check\n if (!typeMatches(actual.reportedType, definition, dialect)) {\n const expected = expectedTypeLabel(definition, dialect);\n results.push({\n check: `column ${name} type`,\n passed: false,\n message: `Column ${name} has type \"${actual.reportedType}\", expected \"${expected}\"`,\n remediation: `Alter column ${name} to type ${definition.type.toUpperCase()}`,\n });\n } else {\n results.push({ check: `column ${name} type`, passed: true });\n }\n\n // Nullability check\n // SQLite does not enforce NOT NULL for PRIMARY KEY columns the same way,\n // so skip nullability checks on the primary key in SQLite.\n if (dialect === \"sqlite\" && definition.primaryKey === true) {\n results.push({ check: `column ${name} nullability`, passed: true });\n } else if (actual.nullable !== definition.nullable) {\n const actualDesc = actual.nullable ? \"nullable\" : \"NOT NULL\";\n const expectedDesc = definition.nullable ? \"nullable\" : \"NOT NULL\";\n results.push({\n check: `column ${name} nullability`,\n passed: false,\n message: `Column ${name} is ${actualDesc}, expected ${expectedDesc}`,\n remediation: `ALTER TABLE audit_logs ALTER COLUMN ${name} ${definition.nullable ? \"DROP NOT NULL\" : \"SET NOT NULL\"}`,\n });\n } else {\n results.push({ check: `column ${name} nullability`, passed: true });\n }\n }\n\n return results;\n}\n\n// ---------------------------------------------------------------------------\n// Index checks — per-dialect introspection\n// ---------------------------------------------------------------------------\n\nasync function introspectIndexNamesPostgres(\n db: Kysely<Database>,\n): Promise<Set<string>> {\n const result = await sql<{ indexname: string }>`\n SELECT indexname\n FROM pg_indexes\n WHERE schemaname = 'public' AND tablename = ${AUDIT_LOG_SCHEMA.tableName}\n `.execute(db);\n return new Set(result.rows.map((row) => row.indexname));\n}\n\nasync function introspectIndexNamesMysql(\n db: Kysely<Database>,\n): Promise<Set<string>> {\n const result = await sql<{ INDEX_NAME: string }>`\n SELECT DISTINCT INDEX_NAME\n FROM information_schema.statistics\n WHERE table_schema = DATABASE() AND table_name = ${AUDIT_LOG_SCHEMA.tableName}\n `.execute(db);\n return new Set(result.rows.map((row) => row.INDEX_NAME));\n}\n\nasync function introspectIndexNamesSqlite(\n db: Kysely<Database>,\n): Promise<Set<string>> {\n const result = await sql<{ name: string }>`\n PRAGMA index_list(audit_logs)\n `.execute(db);\n return new Set(result.rows.map((row) => row.name));\n}\n\nasync function introspectIndexNames(\n db: Kysely<Database>,\n dialect: DatabaseDialect,\n): Promise<Set<string>> {\n if (dialect === \"mysql\") {\n return introspectIndexNamesMysql(db);\n }\n if (dialect === \"sqlite\") {\n return introspectIndexNamesSqlite(db);\n }\n return introspectIndexNamesPostgres(db);\n}\n\nfunction checkIndexes(actualIndexes: Set<string>): CheckResult[] {\n const results: CheckResult[] = [];\n\n for (const idx of INDEX_DEFINITIONS) {\n if (actualIndexes.has(idx.name)) {\n results.push({ check: `index ${idx.name}`, passed: true });\n } else {\n results.push({\n check: `index ${idx.name}`,\n passed: false,\n message: `Missing index ${idx.name} on (${idx.columns.join(\", \")})`,\n remediation:\n \"Run `npx @usebetterdev/audit-cli migrate` to create missing indexes\",\n });\n }\n }\n\n return results;\n}\n\n// ---------------------------------------------------------------------------\n// Live write test\n// ---------------------------------------------------------------------------\n\nasync function checkLiveWrite(\n db: Kysely<Database>,\n): Promise<CheckResult[]> {\n const results: CheckResult[] = [];\n const sentinelId = randomUUID();\n\n try {\n // INSERT sentinel row\n try {\n await sql`\n INSERT INTO audit_logs (id, table_name, operation, record_id, actor_id)\n VALUES (\n ${sentinelId},\n ${SENTINEL_TABLE_NAME},\n 'INSERT',\n ${SENTINEL_RECORD_ID},\n ${SENTINEL_ACTOR_ID}\n )\n `.execute(db);\n results.push({\n check: \"write test: insert sentinel row\",\n passed: true,\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n results.push({\n check: \"write test: insert sentinel row\",\n passed: false,\n message: `Failed to insert into audit_logs: ${message}`,\n remediation:\n \"Verify the database user has INSERT permission on audit_logs\",\n });\n return results;\n }\n\n // SELECT sentinel row back\n try {\n const readResult = await sql<{\n id: string;\n actor_id: string | null;\n }>`\n SELECT id, actor_id FROM audit_logs WHERE id = ${sentinelId}\n `.execute(db);\n\n const row = readResult.rows[0];\n\n if (row === undefined) {\n results.push({\n check: \"write test: read back sentinel row\",\n passed: false,\n message:\n \"Sentinel row not found after INSERT — possible trigger or RLS interference\",\n remediation:\n \"Check for DELETE triggers or restrictive RLS policies on audit_logs\",\n });\n return results;\n }\n\n results.push({\n check: \"write test: read back sentinel row\",\n passed: true,\n });\n\n // Verify actor_id round-trip (context propagation proxy)\n if (row.actor_id === SENTINEL_ACTOR_ID) {\n results.push({\n check: \"write test: actor context captured\",\n passed: true,\n });\n } else {\n results.push({\n check: \"write test: actor context captured\",\n passed: false,\n message: `actor_id is \"${row.actor_id ?? \"NULL\"}\", expected \"${SENTINEL_ACTOR_ID}\"`,\n remediation:\n \"Verify AsyncLocalStorage context propagation in your middleware setup\",\n });\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n results.push({\n check: \"write test: read back sentinel row\",\n passed: false,\n message: `Failed to read from audit_logs: ${message}`,\n remediation:\n \"Verify the database user has SELECT permission on audit_logs\",\n });\n }\n } finally {\n // Always clean up sentinel data\n try {\n await sql`\n DELETE FROM audit_logs WHERE id = ${sentinelId}\n `.execute(db);\n } catch {\n // Cleanup failure is not critical — sentinel has a distinctive table_name\n // for manual identification\n }\n }\n\n return results;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Run all audit_logs checks and return structured results.\n * Does not print to stdout — use `check()` for CLI output.\n */\nexport async function runCheck(databaseUrl: string): Promise<CheckOutput> {\n const dialect = detectDialect(databaseUrl);\n const db = await createKyselyInstance(databaseUrl, dialect);\n const results: CheckResult[] = [];\n const warnings: CheckResult[] = [];\n\n try {\n // 0. Connection test\n const connectionCheck = await checkConnection(db);\n results.push(connectionCheck);\n if (!connectionCheck.passed) {\n return { passed: false, results, warnings };\n }\n\n // 1. Table exists\n const tableCheck = await checkTableExists(db);\n results.push(tableCheck);\n if (!tableCheck.passed) {\n return { passed: false, results, warnings };\n }\n\n // 2–3. Column + index validation (independent — run in parallel)\n const [columns, indexNames] = await Promise.all([\n introspectColumns(db, dialect),\n introspectIndexNames(db, dialect),\n ]);\n results.push(...checkColumns(columns, dialect));\n results.push(...checkIndexes(indexNames));\n\n // 4. Live write + read-back + actor context + cleanup\n results.push(...(await checkLiveWrite(db)));\n } finally {\n await db.destroy();\n }\n\n const passed = results.every((r) => r.passed);\n return { passed, results, warnings };\n}\n\n// ---------------------------------------------------------------------------\n// CLI entry point\n// ---------------------------------------------------------------------------\n\n/** CLI action handler for `better-audit check`. */\nexport async function check(options: CheckOptions = {}): Promise<void> {\n const databaseUrl = options.databaseUrl ?? process.env[\"DATABASE_URL\"];\n if (databaseUrl === undefined || databaseUrl === \"\") {\n throw new Error(\n \"DATABASE_URL is required. Set the DATABASE_URL environment variable or pass --database-url.\",\n );\n }\n\n const output = await runCheck(databaseUrl);\n const verbose = options.verbose === true;\n\n printCheckResults(output, { verbose });\n\n if (!output.passed) {\n throw new CheckFailedError(output);\n }\n}\n\n// Re-export internals for unit testing\nexport {\n checkColumns as _checkColumns,\n checkIndexes as _checkIndexes,\n};\nexport type { IntrospectedColumn as _IntrospectedColumn };\n"],"mappings":";;;;;;;;;;;;;AAeA,SAAS,kBAAkB;AAC3B,SAAS,WAAW;AAGpB,SAAS,wBAAyC;AAkB3C,IAAM,mBAAN,cAA+B,mBAAmB;AAAA,EAC9C;AAAA,EACT,YAAY,QAAqB;AAC/B,UAAM,GAAG,iCAAiC;AAC1C,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAMA,IAAM,sBAAsB;AAC5B,IAAM,oBAAoB;AAC1B,IAAM,qB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