Skip to content

Fix CLI/client parsing, dependency, and runtime safety issues#4

Merged
Helal-maker merged 2 commits intomainfrom
codex/verify-findings-and-make-necessary-code-fixes
Feb 20, 2026
Merged

Fix CLI/client parsing, dependency, and runtime safety issues#4
Helal-maker merged 2 commits intomainfrom
codex/verify-findings-and-make-necessary-code-fixes

Conversation

@Helal-maker
Copy link
Copy Markdown
Owner

@Helal-maker Helal-maker commented Feb 20, 2026

Summary

This PR verifies and addresses the reported findings across CLI, client package, and base template scaffolding.

CLI updates

  • Moved typescript from runtime deps to devDependencies in packages/cli/package.json.
  • auth.ts
    • Removed SQL-style adjacent-single-quote tokenizer branch.
    • Simplified redundant createdUser guard.
  • generate.ts
    • Improved ensureZodValidatorInstalled to walk ancestor directories for hoisted installs and package declarations (dependencies/devDependencies/peerDependencies).
    • Renamed spawned install process variable to child.
    • Moved pagination constants/schema to module scope in generated route output.
    • Added generated FILTERABLE_COLUMNS and typed coercion map for safe filter handling.
    • Added _in filter parsing support in generated routes using JSON + inArray.
  • migrate.ts
    • Improved SQL splitter with -- line comment and /* */ block comment handling.
    • Removed backslash escape handling for SQLite string splitting.
    • Updated push log wording and added explicit post-push success log.
  • index.ts
    • Hardened dev cleanup path with once-guard and cleanup error catch so listeners are always removed.
  • context-generator.ts
    • Removed duplicate inline success emoji in logger message.
  • scanner.ts
    • Changed table-name fallback from ?? to || so empty names fall back to declaration identifier.
  • init.ts
    • parseNonNegativeInt now treats empty/whitespace as missing and returns fallback.
    • Implemented persistence for generated POST /api/users route template.
    • Added drizzle config inline comment to keep local fallback aligned with src/lib/env.ts.

Client updates

  • packages/client/package.json
    • Updated repository URL to weroperking/Betterbase.
    • Added Bun engine requirement.
    • Ensured typecheck and typecheck:test are both --noEmit.
    • Switched lint script to Biome and added @biomejs/biome devDependency.
  • errors.ts
    • BetterBaseError now sets name from this.constructor.name.
  • auth.ts
    • Added optional storage adapter support.
    • Added Zod credential validation for signUp and signIn.
  • client.ts
    • Added runtime Zod validation for config.
    • Added storage support to config handling.
    • Realtime now initialized with auth token and updated on auth changes.
    • from() now accepts optional QueryBuilderOptions.
  • query-builder.ts
    • Added single-use guard (executed) for mutation/execute lifecycle.
    • Added Zod validation on public inputs (select, eq, in, limit, offset, order).
    • in() now serializes arrays with JSON.stringify.
    • Added singularKey override option path via QueryBuilderOptions.
  • realtime.ts
    • Added token support (constructor + setToken) and tokenized WS URL.
    • connect() no longer throws when WebSocket is unavailable; enters disabled mode with warning.
    • Added inert/no-throw behavior for subscribe path in disabled environments.
    • On WS error, now explicitly closes socket before clearing/reconnect scheduling.
  • build.ts
    • Improved ESM/CJS build log formatting to emit readable joined diagnostics.
  • test/client.test.ts
    • Added behavior tests for chained query building and outgoing fetch request shape.
  • tsconfig.test.json
    • Removed redundant declarationMap.
  • tsconfig.json
    • Removed declarationMap to avoid conflict when test config disables declarations.

Base template updates

  • templates/base/.gitignore
    • Added .env.* and !.env.example.
  • templates/base/README.md
    • Added src/lib/realtime.ts to project structure tree.
  • templates/base/src/index.ts
    • Added header-preferred token comment and warning on query-token fallback (without logging token value).
  • templates/base/src/lib/realtime.ts
    • Replaced local deepEqual with fast-deep-equal.
    • Restricted placeholder token auth parsing to development/feature-flag path.
    • Added startup warning when no real verifier is configured outside dev path.
  • templates/base/package.json
    • Added fast-deep-equal dependency.

Monorepo config

  • Removed base jsx from tsconfig.base.json to keep base config React-agnostic.

Validation

  • git diff --check passes.
  • bun run typecheck:test (client package) currently fails in this environment due missing Bun type definitions (TS2688: Cannot find type definition file for 'bun').

Codex Task

Summary by CodeRabbit

  • New Features

    • Token-based realtime authentication and reconnect behavior
    • Configurable storage adapters for auth state
    • Enhanced query filtering supporting array/in-list values
    • Client-side credential validation for sign-up/sign-in
  • Bug Fixes

    • More robust SQL migration parsing and improved realtime error/reconnect handling
    • Clearer error names and improved build logging
  • Documentation

    • Updated project structure and examples
  • Chores

    • Dependency and config cleanups; template updates and .gitignore adjustments

@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 20, 2026

📝 Walkthrough

Walkthrough

Moves TypeScript to devDependencies, adds storage abstraction and runtime config validation in the client, enables token-aware realtime and query validation, enhances CLI route generation and SQL parsing, tightens dev cleanup and logging, and updates templates and dependencies (fast-deep-equal, .env patterns).

Changes

Cohort / File(s) Summary
CLI package manifest
betterbase/packages/cli/package.json
Removed typescript from dependencies and added to devDependencies.
Client package manifest
betterbase/packages/client/package.json
Repository URL updated, added bun engine, changed lint to biome, adjusted devDeps (biome, @types/bun).
CLI command & utilities
betterbase/packages/cli/src/commands/auth.ts, betterbase/packages/cli/src/commands/init.ts, betterbase/packages/cli/src/commands/migrate.ts, betterbase/packages/cli/src/index.ts, betterbase/packages/cli/src/utils/context-generator.ts, betterbase/packages/cli/src/utils/scanner.ts
Simplified auth signup checks; persisted created users on POST; improved SQL splitter to handle line/block comments; guarded dev cleanup to run once; removed emoji from generator logs; changed table name fallback from ?? to `
CLI route generation
betterbase/packages/cli/src/commands/generate.ts
Added helpers to derive FILTERABLE_COLUMNS and FILTER_COERCE; generate route files now support _in filters with JSON parsing and per-field coercion; improved zod-validator detection (walks up tree) and installation handling.
Client auth & storage
betterbase/packages/client/src/auth.ts, betterbase/packages/client/src/types.ts
Introduced StorageAdapter abstraction; AuthClient now accepts optional storage; client-side credential validation via zod; replaced direct localStorage access with adapter.
Client core & factory
betterbase/packages/client/src/client.ts
Added runtime config validation (zod), createClient factory, pass parsed storage to AuthClient, propagate token to realtime client; from() now accepts QueryBuilderOptions.
Query builder & errors
betterbase/packages/client/src/query-builder.ts, betterbase/packages/client/src/errors.ts
Added QueryBuilderOptions and single-use enforcement; zod input validation for query methods; improved error naming (dynamic constructor name) and enriched error flows.
Realtime client
betterbase/packages/client/src/realtime.ts, betterbase/templates/base/src/lib/realtime.ts, betterbase/templates/base/src/index.ts
Realtime client gains token parameter and setToken; supports token-in-query auth, disabled flag, token-aware reconnect/resubscribe; template realtime server now uses fast-deep-equal, warns on dev-auth absence, and restricts dev-auth parsing unless enabled.
Build & tests
betterbase/packages/client/src/build.ts, betterbase/packages/client/test/client.test.ts
Improved Bun.build error logging (join logs); added tests and test cleanup verifying API key header and request formation.
Configuration & templates
betterbase/packages/client/tsconfig.json, betterbase/packages/client/tsconfig.test.json, betterbase/templates/base/.gitignore, betterbase/templates/base/README.md, betterbase/templates/base/package.json, betterbase/tsconfig.base.json, betterbase/templates/base/src/index.ts
Removed some TS declarationMap/jsx compiler options; updated tsconfig formatting; .gitignore now ignores .env.* but not .env.example; added fast-deep-equal dependency; README updated to include realtime file; removed JSX option from base tsconfig.
Scanner & context generator
betterbase/packages/cli/src/utils/scanner.ts, betterbase/packages/cli/src/utils/context-generator.ts
Minor behavior/logging tweaks: table name fallback uses `

Sequence Diagram(s)

sequenceDiagram
    actor Dev
    participant CreateClient as createClient(config)
    participant Config as BetterBaseConfigSchema
    participant Storage as StorageAdapter
    participant Auth as AuthClient
    participant Realtime as RealtimeClient

    Dev->>CreateClient: call with config
    CreateClient->>Config: parse & validate config
    Config-->>CreateClient: parsed config
    CreateClient->>Storage: init storage (config.storage or getStorage)
    Storage-->>CreateClient: storage instance
    CreateClient->>Auth: new AuthClient(..., storage)
    Auth-->>CreateClient: auth instance
    CreateClient->>Realtime: new RealtimeClient(url, token from auth)
    Realtime-->>CreateClient: realtime instance
    Note over Auth,Realtime: Auth updates propagate -> Realtime.setToken(token)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰 I hopped through configs, keys, and store,

Tokens bounced and validations bore,
Filters lined up in tidy rows,
Realtime wakes when auth wind blows,
A little rabbit cheers — code ready to soar!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes across the PR: fixes to parsing logic (SQL comment handling, input validation), dependency management (TypeScript moved to devDependencies), and runtime safety improvements (single-use guards, error handling).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/verify-findings-and-make-necessary-code-fixes

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot]

This comment was marked as resolved.

@Helal-maker Helal-maker merged commit f83cdcb into main Feb 20, 2026
1 check was pending
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
betterbase/packages/cli/src/commands/generate.ts (1)

88-146: ⚠️ Potential issue | 🟠 Major

Boolean query filters will misparse "false" as true.
FILTER_COERCE uses z.coerce.boolean() (via schemaTypeToZod), which coerces values using JavaScript's truthy/falsy semantics—any non-empty string becomes true. As a result, ?active=false (and _in arrays containing "false") will be coerced to true, producing incorrect filtering.

🔧 Suggested fixes

Option 1 (Zod v4+, recommended): Use z.stringbool()

-  if (type === 'boolean') return 'z.coerce.boolean()';
+  if (type === 'boolean') return 'z.stringbool()';

Option 2: Explicit string→boolean preprocess

-  if (type === 'boolean') return 'z.coerce.boolean()';
+  if (type === 'boolean')
+    return 'z.preprocess((v) => (v === "true" ? true : v === "false" ? false : v), z.boolean())';

Option 3: Enum with transform

-  if (type === 'boolean') return 'z.coerce.boolean()';
+  if (type === 'boolean') return 'z.enum(["true", "false"]).transform(v => v === "true")';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@betterbase/packages/cli/src/commands/generate.ts` around lines 88 - 146,
FILTER_COERCE currently uses z.coerce.boolean() which treats any non-empty
string as true, causing "?active=false" to misparse; update the boolean coercion
used when building FILTER_COERCE (where schemaTypeToZod produces z schemas) to
explicitly parse string booleans (e.g., use a preprocess that returns true only
for 'true' and false only for 'false' and passes through actual booleans) so
both single-value parsing (the parsed = schema.safeParse(value) branch) and
array parsing (parsedInValues items validated in the _in branch) correctly
interpret "true"/"false"; change the boolean branch in schemaTypeToZod (and thus
FILTER_COERCE) to use that explicit string→boolean parser so eq(...) and
inArray(...) get correct boolean values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@betterbase/packages/cli/src/commands/generate.ts`:
- Around line 88-146: FILTER_COERCE currently uses z.coerce.boolean() which
treats any non-empty string as true, causing "?active=false" to misparse; update
the boolean coercion used when building FILTER_COERCE (where schemaTypeToZod
produces z schemas) to explicitly parse string booleans (e.g., use a preprocess
that returns true only for 'true' and false only for 'false' and passes through
actual booleans) so both single-value parsing (the parsed =
schema.safeParse(value) branch) and array parsing (parsedInValues items
validated in the _in branch) correctly interpret "true"/"false"; change the
boolean branch in schemaTypeToZod (and thus FILTER_COERCE) to use that explicit
string→boolean parser so eq(...) and inArray(...) get correct boolean values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant