Skip to content

Conversation

@miguelccodev
Copy link
Contributor

@miguelccodev miguelccodev commented Jan 13, 2026

Changes

  • Added zod dependency for validation
  • Removed unnecessary code for now
  • Updated options to accommodate minimum required data for payload.
  • Updated unit tests

How to test

  • npm run test android-interface

Note: Next part is to integrate into assessment code

Ref: MR-18

Summary by CodeRabbit

  • New Features

    • Added summary-data logging with schema-based payload validation, consistent ISO timestamping, and propagation of processing options.
  • Refactor

    • Require explicit identifiers (app_id, cr_user_id) and tightened payload shape.
    • Consolidated legacy event/interaction paths into a single validated summary-data flow.
  • Tests

    • Updated tests to cover the new summary-data pathway, option propagation, and payload validation.

✏️ Tip: You can customize this high-level summary in your review settings.

@miguelccodev miguelccodev self-assigned this Jan 13, 2026
@coderabbitai
Copy link

coderabbitai bot commented Jan 13, 2026

📝 Walkthrough

Walkthrough

Refactors AndroidInterface to emit validated "summary_data" payloads including explicit app_id and cr_user_id, adds Zod-based schema and new types, renames logEventlogSummaryData, removes logInteraction and singleton export, updates tests, and adds zod dependency.

Changes

Cohort / File(s) Summary
Dependency Management
package.json
Added runtime dependency zod (^4.3.5).
Type Definitions
src/android-interface/types.d.ts
Added AppEventPayload, AppEventPayloadVersion ('v1'), AppEventPayloadCollection ('summary_data'), PayloadProcessingInstruction ('add' | 'replace'), and AppEventPayloadOptions.
Validation Schema
src/android-interface/schema-validators.ts
New Zod schema ValidateV1Schema validating required cr_user_id, app_id, collection, timestamp, and data/options shapes with custom error messages.
Core Implementation
src/android-interface/android-interface.ts
Introduced logSummaryData(data, options?), added getBaseParams(), createTimestamp(), validatePayload(); payload now includes baseParams, collection: 'summary_data', options, and timestamp; removed logInteraction() and ANDROID_INTERFACE singleton; added schema validation and updated constructor signature.
Tests
src/android-interface/android-interface.spec.ts
Tests updated to use logSummaryData, assert payload structure (collection: 'summary_data', data, options, timestamp) and verify propagation of provided options/identifiers.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant AndroidInterface
    participant ValidateV1Schema
    participant Logger

    Caller->>AndroidInterface: logSummaryData(data, options?)
    AndroidInterface->>AndroidInterface: getBaseParams()
    AndroidInterface->>AndroidInterface: createTimestamp()
    AndroidInterface->>AndroidInterface: build payload (baseParams + data + options + timestamp + collection)
    AndroidInterface->>ValidateV1Schema: validatePayload(payload)
    ValidateV1Schema-->>AndroidInterface: validated payload
    AndroidInterface->>Logger: emit log event
    Logger-->>Caller: confirmation/ack
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hop and I check each field with delight,

Zod censors wrong shapes and keeps things tight.
app_id and cr_user_id snug and right,
summary_data launched into the night,
A tiny carrot for tests passing bright.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: Option driven data payload with schema validation' directly and clearly summarizes the main changes: introducing option-driven payload handling and adding schema validation (via Zod). It aligns with the core objectives of updating options structure, adding validation, and refactoring the interface.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing touches
  • 📝 Generate docstrings

🧹 Recent nitpick comments
src/android-interface/android-interface.spec.ts (2)

1-1: Unused import: DEFAULT_OPTIONS.

DEFAULT_OPTIONS is imported but never used in the test file. Consider removing it or adding a test that verifies default behavior.

Suggested fix
-import { AndroidInterface, DEFAULT_OPTIONS } from './android-interface';
+import { AndroidInterface } from './android-interface';

Alternatively, add a test to verify default options are applied correctly when no options are provided.


40-87: Consider adding error scenario tests.

The current tests cover happy paths well, but the implementation includes a try/catch block that handles validation failures. Consider adding tests for:

  1. Validation failure scenario - verify behavior when ValidateV1Schema.parse throws (e.g., missing required fields)
  2. Console warning verification - ensure console.warn is called on errors
  3. Default options - verify default behavior when no options are provided
Example test for error handling
describe('Scenario: Handling validation errors', () => {
  test('should log a warning when validation fails', () => {
    const warnSpy = jest.spyOn(console, 'warn').mockImplementation();
    
    // Initialize without required fields to trigger validation error
    const invalidInterface = new AndroidInterface({
      namespace: 'Android'
      // missing app_id and cr_user_id
    });
    
    invalidInterface.logSummaryData({ event: 'test' });
    
    expect(warnSpy).toHaveBeenCalled();
    expect(mockLogMessage).not.toHaveBeenCalled();
    
    warnSpy.mockRestore();
  });
});

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e23ec71 and e4ae145.

📒 Files selected for processing (1)
  • src/android-interface/android-interface.spec.ts
🧰 Additional context used
🧬 Code graph analysis (1)
src/android-interface/android-interface.spec.ts (1)
src/android-interface/android-interface.ts (1)
  • AndroidInterface (17-67)
🔇 Additional comments (4)
src/android-interface/android-interface.spec.ts (4)

3-16: LGTM!

The test setup correctly mocks the Android namespace and clears mocks between tests.


18-37: LGTM!

The initialization test correctly verifies that custom options (app_id, cr_user_id) are propagated to the payload.


40-71: LGTM!

The test correctly validates the complete summary_data payload structure, including the required fields and timestamp format verification.


73-86: LGTM!

The test correctly verifies that optional processing instructions are included in the payload.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link

@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.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In @package.json:
- Around line 49-50: package.json currently pins "zod": "^4.3.5" which is a
breaking major that requires migrating Zod v3 APIs; either pin to a Zod v3
release (e.g., change the dependency to "zod": "^3.21.4") to avoid runtime
breaks, or perform the migration: update all imports from "zod" usages, search
for and adapt ZodError handling and thrown/format shapes (references to
ZodError, .errors, .format), update parse APIs and return shapes (safeParse
usage), and adjust object schema strictness/object/strict() and transform APIs;
run the official Zod v3→v4 codemods and tests to validate changes before
merging.

In @src/android-interface/android-interface.ts:
- Around line 5-17: The interface AndroidInterfaceOptions declares app_id and
cr_user_id as required but runtime/constructor accepts partial options and uses
DEFAULT_OPTIONS; update the type to match runtime by making app_id and
cr_user_id optional (app_id? and cr_user_id?) on AndroidInterfaceOptions so
callers can omit them, and ensure DEFAULT_OPTIONS still satisfies
AndroidInterfaceOptions after this change; verify any code referencing
AndroidInterfaceOptions (e.g., the constructor that consumes options) handles
possibly undefined app_id/cr_user_id appropriately.
🧹 Nitpick comments (4)
src/android-interface/schema-validators.ts (1)

9-15: Schema missing options field present in AppEventPayload type.

The ValidateV1Schema does not include the options field, but AppEventPayload in types.d.ts defines options?: AppEventPayloadOptions. By default, Zod strips unknown keys during parsing, so the validated payload returned from parse() will not include options.

However, since the validation result isn't used (the original payload object is passed to logMessage), this works correctly. If you later use the parsed result, the options field would be lost.

Consider adding the options field to the schema for completeness:

♻️ Suggested schema update
+import { AppEventPayloadOptions } from './types';
+
 export const ValidateV1Schema = z.object({
   cr_user_id: requiredString('CR User ID'),
   app_id: requiredString('App ID'),
   collection: requiredString('Collection'),
   data: z.record(z.string(), z.any()),
-  timestamp: requiredString('Event ISO-8601 timestamp')
+  timestamp: requiredString('Event ISO-8601 timestamp'),
+  options: z.record(z.string(), z.enum(['add', 'replace'])).optional()
 });
src/android-interface/types.d.ts (1)

11-18: Consider using Record<string, any> for the data field.

For consistency with the Zod schema (z.record(z.string(), z.any())), consider typing data as Record<string, any> instead of any. This provides slightly better type safety while maintaining flexibility.

♻️ Suggested change
 export interface AppEventPayload {
   cr_user_id: string;
   app_id: string;
   collection: AppEventPayloadCollection;
-  data: any;
+  data: Record<string, any>;
   options?: AppEventPayloadOptions;
   timestamp: string;
 }
src/android-interface/android-interface.spec.ts (1)

86-99: Consider adding negative test cases for validation failures.

The current tests cover successful scenarios. Consider adding tests that verify validation errors are handled gracefully (e.g., missing required fields, invalid data types). This would validate the catch block behavior in logSummaryData.

🧪 Example negative test
test('should warn and not call logMessage when validation fails', () => {
  const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
  
  // Force validation failure by mocking validatePayload to throw
  // or by testing with invalid payload structure
  androidInterface.logSummaryData(null as any);
  
  expect(mockLogMessage).not.toHaveBeenCalled();
  expect(consoleSpy).toHaveBeenCalled();
  
  consoleSpy.mockRestore();
});
src/android-interface/android-interface.ts (1)

42-42: Consider adding type safety for the global namespace access.

The window[this.options.namespace] access is not type-safe. Consider declaring an interface for the expected Android bridge methods.

♻️ Suggested type declaration
// Add to types.d.ts or at the top of this file
declare global {
  interface Window {
    Android?: {
      logMessage: (message: string) => void;
    };
    [key: string]: any;
  }
}

Then add a runtime check:

+     const bridge = window[this.options.namespace!];
+     if (!bridge?.logMessage) {
+       throw new Error(`Android bridge not found at window.${this.options.namespace}`);
+     }
-     window[this.options.namespace].logMessage(JSON.stringify(payload));
+     bridge.logMessage(JSON.stringify(payload));
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c43d7b9 and c4e7b24.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • package.json
  • src/android-interface/android-interface.spec.ts
  • src/android-interface/android-interface.ts
  • src/android-interface/schema-validators.ts
  • src/android-interface/types.d.ts
🧰 Additional context used
🧬 Code graph analysis (2)
src/android-interface/android-interface.spec.ts (1)
src/android-interface/android-interface.ts (2)
  • AndroidInterface (19-69)
  • DEFAULT_OPTIONS (12-17)
src/android-interface/android-interface.ts (2)
src/android-interface/types.d.ts (3)
  • AppEventPayloadVersion (1-1)
  • AppEventPayloadOptions (7-9)
  • AppEventPayload (11-18)
src/android-interface/schema-validators.ts (1)
  • ValidateV1Schema (9-15)
🔇 Additional comments (5)
src/android-interface/schema-validators.ts (1)

3-7: LGTM — Zod v4 error customization syntax is correct.

The error callback approach aligns with Zod 4's unified error customization API. The conditional logic for distinguishing missing vs. wrong-type inputs provides clear error messages.

src/android-interface/types.d.ts (1)

1-9: LGTM — Well-structured type definitions.

The literal types ('v1', 'summary_data', 'add' | 'replace') provide good type safety, and the interface design cleanly separates concerns.

src/android-interface/android-interface.spec.ts (1)

56-84: LGTM — Good test coverage for the happy path.

The tests effectively validate payload structure, timestamp format, and the integration with the Android bridge mock.

src/android-interface/android-interface.ts (2)

29-46: LGTM — Clean payload construction and validation flow.

The logSummaryData method properly builds the payload, validates it, and handles errors gracefully with a warning log. The use of try/catch ensures validation failures don't crash the application.


48-68: LGTM — Well-organized helper methods.

The getBaseParams, validatePayload, and createTimestamp methods are cleanly separated and easy to test independently. The TODO comment appropriately signals planned expansion.

Copy link

@Rajesh1041 Rajesh1041 left a comment

Choose a reason for hiding this comment

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

Looks Good @miguelccodev

@miguelccodev miguelccodev merged commit 0a5a973 into main Jan 15, 2026
3 checks passed
@miguelccodev
Copy link
Contributor Author

🎉 This PR is included in version 1.6.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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.

4 participants