Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added additional context to workflow core and extended browser-sdk #2850

Merged
merged 4 commits into from
Nov 27, 2024

Conversation

chesterkmr
Copy link
Collaborator

@chesterkmr chesterkmr commented Nov 18, 2024

Summary by CodeRabbit

  • New Features
    • Introduced additionalContext support in the StateManager, enhancing state management capabilities.
    • Added a new hook, useAdditionalWorkflowContext, for improved workflow context retrieval.
  • Bug Fixes
    • Updated methods to ensure proper context handling during plugin invocation.
  • Documentation
    • Changelog updated to reflect new features and dependency updates across various packages.

Copy link

changeset-bot bot commented Nov 18, 2024

⚠️ No Changeset found

Latest commit: 990e6ba

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

Walkthrough

The changes in this pull request enhance the StateManager and related components by introducing an additionalContext prop, which allows for more dynamic state management. This prop is integrated into various hooks and methods, including useMachineLogic, invokePlugin, and sendEvent, across several files. The modifications ensure that the state machine and plugins can utilize this additional context, improving the overall flexibility and capability of the state management system.

Changes

File Change Summary
apps/kyb-app/src/components/organisms/DynamicUI/StateManager/StateManager.tsx Added additionalContext prop to StateManagerProps and updated useMemo hooks accordingly.
apps/kyb-app/src/components/organisms/DynamicUI/StateManager/components/ActionsHandler/action-handlers/plugin-runner.handler.ts Updated run method to return context from StateMachineAPI after invoking the plugin.
apps/kyb-app/src/components/organisms/DynamicUI/StateManager/hooks/useMachineLogic/useMachineLogic.ts Modified invokePlugin to accept additionalContext and updated useMachineLogic signature.
apps/kyb-app/src/components/organisms/DynamicUI/StateManager/state-machine.factory.ts Added additionalContext parameter to createStateMachine function.
apps/kyb-app/src/components/organisms/DynamicUI/StateManager/types.ts Added additionalContext property to StateManagerProps interface.
apps/kyb-app/src/pages/CollectionFlow/CollectionFlow.tsx Integrated useAdditionalWorkflowContext to pass additional context to StateManager.
apps/kyb-app/src/pages/CollectionFlow/hooks/useAdditionalWorkflowContext/index.ts Exported all entities from useAdditionalWorkflowContext module.
apps/kyb-app/src/pages/CollectionFlow/hooks/useAdditionalWorkflowContext/useAdditionalWorkflowContext.ts Introduced useAdditionalWorkflowContext hook to access URL search parameters.
packages/workflow-core/CHANGELOG.md Updated changelog with new version entries and dependency updates.
packages/workflow-core/src/lib/plugins/external-plugin/api-plugin.ts Updated invoke method to include additionalContext parameter.
packages/workflow-core/src/lib/types.ts Updated sendEvent and invokePlugin methods to include additionalContext.
packages/workflow-core/src/lib/workflow-runner.ts Modified methods in WorkflowRunner to handle additionalContext for plugin invocations.
sdks/workflow-browser-sdk/CHANGELOG.md Updated changelog for version updates and dependency changes.
sdks/workflow-browser-sdk/src/lib/types.ts Added additionalContext to WorkflowOptionsBrowser interface.
sdks/workflow-browser-sdk/src/lib/workflow-browser-sdk.ts Updated constructor and methods in WorkflowBrowserSDK to accept additionalContext.

Possibly related PRs

Suggested reviewers

  • MatanYadaev
  • Omri-Levy

Poem

🐇 In the meadow where bunnies play,
A new context blooms today.
With additionalContext, oh what a sight,
State management's now a delight!
Hop along, let the plugins run,
In our dynamic world, we have so much fun! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 982c3a1 and 990e6ba.

📒 Files selected for processing (2)
  • packages/workflow-core/CHANGELOG.md (1 hunks)
  • sdks/workflow-browser-sdk/CHANGELOG.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/workflow-core/CHANGELOG.md
  • sdks/workflow-browser-sdk/CHANGELOG.md

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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: 5

🧹 Outside diff range and nitpick comments (13)
apps/kyb-app/src/pages/CollectionFlow/hooks/useAdditionalWorkflowContext/useAdditionalWorkflowContext.ts (1)

4-16: Add TypeScript types for better type safety and documentation

Consider adding TypeScript interfaces to clearly define the shape of the context object.

+interface WorkflowContext {
+  query: {
+    token: string | null;
+  };
+}

-export const useAdditionalWorkflowContext = () => {
+export const useAdditionalWorkflowContext = (): WorkflowContext => {
apps/kyb-app/src/components/organisms/DynamicUI/StateManager/components/ActionsHandler/action-handlers/plugin-runner.handler.ts (1)

14-16: Consider adding error handling around plugin execution

While the implementation is functionally correct, consider adding error handling to gracefully handle plugin execution failures and context retrieval issues.

 async run(_: CollectionFlowContext, action: Action<PluginRunnerParams>, api: StateMachineAPI) {
-    await api.invokePlugin(action.params.pluginName);
+    try {
+      await api.invokePlugin(action.params.pluginName);
+      const context = api.getContext();
+      if (!context) {
+        throw new Error('Context not available after plugin execution');
+      }
+      return context;
+    } catch (error) {
+      console.error(`Plugin execution failed: ${action.params.pluginName}`, error);
+      throw error;
+    }
-    return api.getContext();
 }
apps/kyb-app/src/components/organisms/DynamicUI/StateManager/StateManager.tsx (1)

Line range hint 53-53: Remove @ts-ignore comment

There's a @ts-ignore comment that bypasses TypeScript type checking. This could hide potential type-related issues.

Consider fixing the underlying type issue instead of suppressing it. If you need help resolving the type error, I can assist you.

apps/kyb-app/src/components/organisms/DynamicUI/StateManager/hooks/useMachineLogic/useMachineLogic.ts (3)

17-17: Consider adding type validation for additionalContext

While the typing is correct, consider adding runtime validation to ensure the additionalContext meets expected shape/constraints before passing it to plugins.

export const useMachineLogic = (
  machine: WorkflowBrowserSDK,
-  additionalContext?: AnyRecord,
+  additionalContext?: AnyRecord,
+  validate = true,
): { isInvokingPlugin: boolean; machineApi: StateMachineAPI } => {
+  useEffect(() => {
+    if (validate && additionalContext) {
+      // Add validation logic here
+      // Throw or log warning if validation fails
+    }
+  }, [additionalContext, validate]);

25-25: Document the impact of additionalContext on plugins

Please add JSDoc comments explaining:

  • The expected structure of additionalContext
  • How plugins utilize this additional context
  • Any side effects or behavioral changes when context is provided
+/**
+ * Invokes a plugin with additional context
+ * @param pluginName - The name of the plugin to invoke
+ * @param additionalContext - Optional context that affects plugin behavior:
+ *   - Expected properties and their purpose
+ *   - How plugins consume this context
+ *   - Any side effects when context is provided
+ */
async (pluginName: string) => {

32-32: Consider memoizing additionalContext if it changes frequently

The addition of additionalContext to the dependency array is correct. However, if it changes frequently, consider memoizing it at a higher level to prevent unnecessary callback recreations and potential re-renders.

// In parent component:
const memoizedContext = useMemo(
  () => additionalContext,
  [/* dependencies that should trigger context updates */]
);
sdks/workflow-browser-sdk/src/lib/types.ts (2)

65-65: Add JSDoc documentation for the new property.

The addition of additionalContext aligns well with the PR objectives. However, please add JSDoc documentation to describe:

  • The purpose of this property
  • Expected structure of the context
  • Any constraints or requirements
  • Usage examples

Example documentation:

+  /**
+   * Additional context to be passed to the workflow.
+   * This can be used to provide extra data that might be needed during workflow execution.
+   * @example
+   * {
+   *   userId: '123',
+   *   metadata: { source: 'external' }
+   * }
+   */
   additionalContext?: AnyRecord;

65-65: Consider using a more specific type for better type safety.

While AnyRecord provides flexibility, it might be too permissive and could lead to runtime issues. Consider:

  1. Creating a specific interface for the context
  2. Using generics to allow consumers to define their context type
  3. Adding runtime validation using a schema validation library

Example using generics:

-export interface WorkflowOptionsBrowser extends Omit<WorkflowOptions, 'workflowActions'> {
+export interface WorkflowOptionsBrowser<TContext extends Record<string, unknown> = AnyRecord> extends Omit<WorkflowOptions, 'workflowActions'> {
   backend?: DeepPartial<BackendOptions>;
   persistStates?: IPersistState[];
   submitStates?: Array<Omit<IPersistState, 'persistence'>>;
-  additionalContext?: AnyRecord;
+  additionalContext?: TContext;
}
sdks/workflow-browser-sdk/src/lib/workflow-browser-sdk.ts (2)

34-34: Consider simplifying the type definition.

The property type definition can be simplified as the | undefined is redundant when using the optional modifier ?.

-  #__additionalContext?: AnyRecord | undefined;
+  #__additionalContext?: AnyRecord;

34-34: Consider documenting the additionalContext contract.

The introduction of additionalContext adds flexibility but also introduces potential complexity. Consider:

  1. Documenting the expected shape and usage of the additional context.
  2. Adding runtime validation for critical context properties.
  3. Providing examples in the SDK documentation.

This will help maintain consistency across different implementations and make the feature more maintainable.

Also applies to: 221-232

packages/workflow-core/src/lib/plugins/external-plugin/api-plugin.ts (1)

Line range hint 44-79: Document the additionalContext feature

Consider adding documentation to describe:

  1. The purpose and intended use cases of additionalContext
  2. The context merging behavior and precedence rules
  3. Best practices for plugin authors regarding context usage

This will help plugin authors understand how to safely use this feature without introducing bugs or security issues.

packages/workflow-core/CHANGELOG.md (1)

3-7: Enhance the changelog entry with more details

The current changelog entry could be more helpful to users by including:

  • A description of what additionalContext is and its purpose
  • Example usage or code snippets
  • Any migration steps if needed
  • Impact on existing implementations

Consider expanding the entry like this:

 ## 0.6.65

 ### Patch Changes

-Added additionalContext
+- Added `additionalContext` parameter to enhance contextual data handling
+  - Purpose: Allows passing additional context data through workflow components
+  - Usage: `someWorkflowComponent({ additionalContext: { key: 'value' } })`
+  - Note: This is a backward-compatible change and existing implementations will continue to work
sdks/workflow-browser-sdk/CHANGELOG.md (1)

3-10: Enhance the changelog entry with more details.

The changelog entry could be more descriptive to help users understand the changes better. Consider following the conventional changelog format more strictly.

Apply this diff to improve the changelog entry:

 ## 0.6.65
 
 ### Patch Changes
 
-- Added additionalContext
+- feat: Added `additionalContext` parameter to enhance contextual data handling
+  - Allows passing additional context to workflow components
+  - Improves flexibility in data management
+  - See documentation for usage examples
 - Updated dependencies
   - @ballerine/workflow-core@0.6.65
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d25cf30 and bfc30d5.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (28)
  • apps/backoffice-v2/CHANGELOG.md (1 hunks)
  • apps/backoffice-v2/package.json (2 hunks)
  • apps/kyb-app/CHANGELOG.md (1 hunks)
  • apps/kyb-app/package.json (2 hunks)
  • apps/kyb-app/src/components/organisms/DynamicUI/StateManager/StateManager.tsx (2 hunks)
  • apps/kyb-app/src/components/organisms/DynamicUI/StateManager/components/ActionsHandler/action-handlers/plugin-runner.handler.ts (1 hunks)
  • apps/kyb-app/src/components/organisms/DynamicUI/StateManager/hooks/useMachineLogic/useMachineLogic.ts (2 hunks)
  • apps/kyb-app/src/components/organisms/DynamicUI/StateManager/state-machine.factory.ts (3 hunks)
  • apps/kyb-app/src/components/organisms/DynamicUI/StateManager/types.ts (2 hunks)
  • apps/kyb-app/src/pages/CollectionFlow/CollectionFlow.tsx (4 hunks)
  • apps/kyb-app/src/pages/CollectionFlow/hooks/useAdditionalWorkflowContext/index.ts (1 hunks)
  • apps/kyb-app/src/pages/CollectionFlow/hooks/useAdditionalWorkflowContext/useAdditionalWorkflowContext.ts (1 hunks)
  • examples/headless-example/CHANGELOG.md (1 hunks)
  • examples/headless-example/package.json (2 hunks)
  • packages/workflow-core/CHANGELOG.md (1 hunks)
  • packages/workflow-core/package.json (1 hunks)
  • packages/workflow-core/src/lib/plugins/external-plugin/api-plugin.ts (3 hunks)
  • packages/workflow-core/src/lib/types.ts (2 hunks)
  • packages/workflow-core/src/lib/workflow-runner.ts (7 hunks)
  • sdks/workflow-browser-sdk/CHANGELOG.md (1 hunks)
  • sdks/workflow-browser-sdk/package.json (3 hunks)
  • sdks/workflow-browser-sdk/src/lib/types.ts (1 hunks)
  • sdks/workflow-browser-sdk/src/lib/workflow-browser-sdk.ts (4 hunks)
  • sdks/workflow-node-sdk/CHANGELOG.md (1 hunks)
  • sdks/workflow-node-sdk/package.json (2 hunks)
  • services/workflows-service/CHANGELOG.md (1 hunks)
  • services/workflows-service/package.json (2 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
✅ Files skipped from review due to trivial changes (12)
  • apps/backoffice-v2/CHANGELOG.md
  • apps/backoffice-v2/package.json
  • apps/kyb-app/CHANGELOG.md
  • apps/kyb-app/package.json
  • apps/kyb-app/src/pages/CollectionFlow/hooks/useAdditionalWorkflowContext/index.ts
  • examples/headless-example/CHANGELOG.md
  • examples/headless-example/package.json
  • packages/workflow-core/package.json
  • sdks/workflow-node-sdk/CHANGELOG.md
  • sdks/workflow-node-sdk/package.json
  • services/workflows-service/package.json
  • services/workflows-service/prisma/data-migrations
🧰 Additional context used
🪛 Biome
packages/workflow-core/src/lib/workflow-runner.ts

[error] 765-765: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)

🔇 Additional comments (31)
apps/kyb-app/src/pages/CollectionFlow/hooks/useAdditionalWorkflowContext/useAdditionalWorkflowContext.ts (2)

1-2: LGTM!

The imports are clean, specific, and all are being used in the implementation.


4-16: Review security implications of exposing tokens in URL

Tokens in URL parameters can be:

  1. Logged in server logs
  2. Visible in browser history
  3. Leaked through Referer headers
  4. Cached by browsers

Consider using more secure methods for token transmission, such as HTTP-only cookies or request headers.

Let's verify the token usage across the codebase:

✅ Verification successful

Let me gather more specific information about how this token is being used in the codebase.

The previous results show the token is used in multiple places, but we need to understand its specific usage in the collection flow and any validation mechanisms in place.


Let me check one more aspect to understand the token's lifecycle and validation:

The previous results show this is a workflow-specific token created through a secure endpoint and validated through error handling, but let's confirm the validation mechanisms.


Token usage in URL is acceptable for this specific workflow implementation

The token implementation appears to be secure based on the following findings:

  1. This is a single-use workflow token created through a secure endpoint (/create-token) with proper authentication
  2. The token has built-in expiration (expiresAt) and is scoped to specific workflow data and end user
  3. Proper validation and error handling is implemented:
    • AccessTokenIsMissingError for missing tokens
    • InvalidAccessTokenError for invalid tokens
    • Dedicated error screens for both cases
  4. The token is managed by a dedicated WorkflowTokenService and repository

While URL parameters have known security considerations, this implementation appears to be a deliberate architectural choice for workflow-specific, temporary tokens with appropriate security controls in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how the token is being used and transmitted

# Check for token references in URLs
rg -l "token=" 

# Check for security-related comments or documentation
rg -i "security|token|auth" "*.md"

# Look for cookie or header-based auth patterns
ast-grep --pattern 'cookie' 

Length of output: 2378


Script:

#!/bin/bash
# Check the token usage in the collection flow and related files
rg -A 5 -B 5 "token.*searchParams" apps/kyb-app/

# Check how MissingTokenErrorScreen is used
rg -A 5 "MissingTokenErrorScreen" apps/kyb-app/

# Look for token validation or processing
ast-grep --pattern 'searchParams.get("token")'

# Check the workflow controller for token handling
rg -A 10 "token" services/workflows-service/src/workflow/workflow.controller.external.ts

Length of output: 5794


Script:

#!/bin/bash
# Check token validation and authentication flow
rg -A 10 "class WorkflowTokenService" services/workflows-service/src/auth/workflow-token/

# Look for token validation middleware or guards
rg -A 10 "validateToken|verifyToken" services/workflows-service/

# Check for token-related errors and handling
rg -A 5 "InvalidAccessTokenError|AccessTokenIsMissingError" apps/kyb-app/

Length of output: 8028

apps/kyb-app/src/components/organisms/DynamicUI/StateManager/state-machine.factory.ts (2)

12-12: LGTM: Additional context parameter properly integrated

The addition of the optional additionalContext parameter is well-implemented:

  • Properly typed using AnyRecord
  • Maintains backward compatibility by being optional
  • Correctly passed through to the underlying createWorkflow function

Let's verify the integration with the workflow SDK:

#!/bin/bash
# Check if the workflow SDK expects this parameter
rg -A 5 "createWorkflow.*interface|type" --type typescript

Also applies to: 21-21


Line range hint 15-17: Address type safety concerns

The @ts-nocheck comment and as any type assertion suggest potential type safety issues that should be addressed:

  1. The definition parameter is being cast to any
  2. The entire TypeScript checking is disabled for this section

Consider properly typing the definition parameter instead of using type assertions. This will provide better type safety and IDE support.

- //@ts-nocheck
- definition: definition as any,
+ definition: definition,

Let's check how the definition type is used across the codebase:

apps/kyb-app/src/components/organisms/DynamicUI/StateManager/components/ActionsHandler/action-handlers/plugin-runner.handler.ts (1)

15-15: Verify the context retrieval usage across consumers

The addition of context retrieval aligns well with the PR's objective of enhancing context handling. However, let's verify that all consumers of this handler are prepared to handle the returned context.

✅ Verification successful

Context retrieval change appears safe to implement

Based on the code analysis:

  • The PluginRunnerHandler is part of a collection of action handlers used in the state management system
  • It's instantiated and used alongside other handlers (ApiActionHandler, EventDispatcherHandler, etc.)
  • The handler implements the ActionHandler interface and is used in a standardized way
  • The change to return context aligns with the state management pattern

Since this is a contained change within the handler implementation and the consuming code in useActionsHandlerLogic uses a standard interface pattern, the context retrieval addition should be safe to implement.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of PluginRunnerHandler to verify context handling
# Expected: Locations where the handler is instantiated and its run method is called

# Search for direct usage of the handler
ast-grep --pattern 'new PluginRunnerHandler()' 

# Search for places where the run method result is used
rg -l "pluginRunner.*run\(" 

Length of output: 252


Script:

#!/bin/bash
# Let's examine the usage context in useActionsHandlerLogic.ts and look for run method calls
rg -A 5 "pluginRunner.*run" apps/kyb-app/src/components/organisms/DynamicUI/StateManager/components/ActionsHandler/hooks/useActionsHandlerLogic/useActionsHandlerLogic.ts

# Also search for any await patterns since this might be an async operation
ast-grep --pattern 'await pluginRunner.run($_)'

# Let's also check the interface/type definition of the handler
ast-grep --pattern 'interface $_Handler {
  run($_): $_
}'

Length of output: 282


Script:

#!/bin/bash
# Let's try a broader search for the handler interface and its implementations
ast-grep --pattern 'interface ActionHandler {
  $$$
}'

# Search for the plugin runner handler class definition
ast-grep --pattern 'class PluginRunnerHandler {
  $$$
}'

# Look for any usage of the handler with more context
rg -B 3 -A 3 "PluginRunnerHandler"

Length of output: 4459


Script:

#!/bin/bash
# Let's check how the handlers are used in the processing logic
rg -B 3 -A 10 "useActionsProcessingLogic" apps/kyb-app/src/components/organisms/DynamicUI/StateManager/components/ActionsHandler/hooks/useActionsHandlerLogic/hooks/useActionsProcessingLogic.ts

# Let's also check the ActionHandler interface definition
rg -B 2 -A 5 "interface ActionHandler" apps/kyb-app/src/components/organisms/DynamicUI/StateManager/components/ActionsHandler/action-handlers/action-handler.abstract.ts

# And check how the StateMachineAPI is handling context
ast-grep --pattern 'class StateMachineAPI {
  $$$
}'

Length of output: 609

apps/kyb-app/src/components/organisms/DynamicUI/StateManager/types.ts (2)

6-6: LGTM!

Clean import of the required type from the common package.


30-30: Consider adding JSDoc documentation for the new property.

The addition of additionalContext is clean and maintains backward compatibility. However, adding documentation would help other developers understand its purpose and expected usage.

Let's verify the consistent usage of this property across related files:

apps/kyb-app/src/components/organisms/DynamicUI/StateManager/StateManager.tsx (3)

19-19: LGTM: additionalContext prop addition

The new prop is properly typed and aligns with the PR's objective to extend context handling capabilities.


41-41: LGTM: Proper hook usage

The useMachineLogic hook is correctly updated to receive the additionalContext parameter.


33-33: Consider optimizing machine recreation

While passing additionalContext to createStateMachine is correct, be aware that the machine will be recreated whenever additionalContext changes. If additionalContext changes frequently, this could impact performance.

Let's check the implementation of createStateMachine to understand the impact:

Consider implementing a deep comparison in the useMemo dependency array or memoizing additionalContext at a higher level if it changes frequently.

apps/kyb-app/src/components/organisms/DynamicUI/StateManager/hooks/useMachineLogic/useMachineLogic.ts (3)

2-2: LGTM: Import added correctly

The AnyRecord type import is appropriately added for the new additionalContext parameter.


8-8: LGTM: Interface updated correctly

The invokePlugin method signature is properly updated to include the optional additionalContext parameter.


8-8: Verify plugin compatibility with additionalContext

The introduction of additionalContext affects the plugin system. Let's verify that all existing plugins can handle this parameter gracefully.

Also applies to: 17-17, 25-25

✅ Verification successful

Let me gather more information about the plugin implementations to verify their compatibility with the additional context parameter.


Based on the analysis of the code, I can now generate the final response as we have sufficient information about the plugin system and its handling of additional context.

Additional context parameter is safely handled across the plugin system

The codebase shows that:

  1. The WorkflowRunner.invokePlugin() method properly passes the additionalContext parameter to plugins
  2. The plugin system, particularly __invokeApiPlugin(), is designed to handle the optional additionalContext parameter
  3. All plugin implementations (NodePlugin, TransformerPlugin, etc.) are compatible with receiving additional context through their invoke methods

The introduction of the optional additionalContext parameter in invokePlugin is a safe enhancement that maintains backward compatibility while adding new functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for plugin implementations to verify compatibility
echo "Searching for plugin implementations..."
rg -l "class.*implements.*Plugin" || rg -l "export.*class.*Plugin"

# Search for plugin invocations to ensure consistent usage
echo -e "\nSearching for plugin invocations..."
rg "invokePlugin\(" -A 2

Length of output: 2874


Script:

#!/bin/bash
# Check the implementation of plugins to verify if they can handle additional context
echo "Checking NodePlugin implementation..."
cat sdks/workflow-node-sdk/src/lib/plugins/node-plugin.ts

echo -e "\nChecking TransformerPlugin implementation..."
cat packages/workflow-core/src/lib/plugins/common-plugin/transformer-plugin.ts

echo -e "\nChecking plugin registration and handling in WorkflowRunner..."
cat packages/workflow-core/src/lib/workflow-runner.ts

Length of output: 32172

sdks/workflow-browser-sdk/package.json (1)

4-4: LGTM: Version updates are consistent

The version bump and corresponding workflow-core dependency update are aligned, maintaining consistency across the package ecosystem.

Also applies to: 37-37

packages/workflow-core/src/lib/types.ts (3)

Line range hint 1-17: LGTM! Import statements are well-organized

The new imports are properly structured and necessary for the interface changes.


Line range hint 39-45: LGTM! Consistent plugin configuration pattern

The dispatchEventPlugins property follows the established pattern of supporting both plugin instances and plugin parameters, maintaining consistency with other plugin configurations in the interface.


25-25: Consider strengthening type safety for additionalContext

While the implementation is consistent, using AnyRecord for additionalContext might be too permissive. Consider creating a more specific interface to better document and enforce the expected structure of the additional context.

+interface WorkflowAdditionalContext {
+  // Add expected properties here
+  [key: string]: unknown;
+}

 export interface Workflow {
   subscribe: (eventName: string, callback: (event: WorkflowEvent) => Promise<void>) => void;
-  sendEvent: (event: WorkflowEventWithoutState, additionalContext?: AnyRecord) => Promise<void>;
+  sendEvent: (event: WorkflowEventWithoutState, additionalContext?: WorkflowAdditionalContext) => Promise<void>;
   getSnapshot: () => Record<PropertyKey, any>;
-  invokePlugin: (pluginName: string, additionalContext?: AnyRecord) => Promise<void>;
+  invokePlugin: (pluginName: string, additionalContext?: WorkflowAdditionalContext) => Promise<void>;
   overrideContext: (context: any) => any;
 }

Let's verify that all implementations handle the new parameter:

Also applies to: 27-27

✅ Verification successful

Type safety suggestion can be implemented without breaking changes

The search results confirm that all implementations properly handle the additionalContext parameter with the AnyRecord type. The implementations are found in:

  • workflow-browser-sdk.ts
  • workflow-runner.ts
  • useMachineLogic.ts

Creating a more specific WorkflowAdditionalContext interface as suggested would be a good improvement for type safety while maintaining backward compatibility since the interface would still allow string indexing.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for implementations of sendEvent and invokePlugin
ast-grep --pattern 'class $_ implements Workflow {
  $$$
  sendEvent($$$) {
    $$$
  }
  $$$
}'

ast-grep --pattern 'class $_ implements Workflow {
  $$$
  invokePlugin($$$) {
    $$$
  }
  $$$
}'

Length of output: 200


Script:

#!/bin/bash
# Let's try a different approach to find implementations
# First, find all TypeScript files
rg -t typescript "implements\s+Workflow" -l | while read -r file; do
    echo "=== $file ==="
    # Show the class implementation with context
    rg "implements\s+Workflow" "$file" -A 20 -B 5
done

# Also search for direct implementations of these methods
rg "sendEvent.*additionalContext" -t typescript
rg "invokePlugin.*additionalContext" -t typescript

Length of output: 268


Script:

#!/bin/bash
# Search for implementations without file type flag
rg "implements\s+Workflow" | while read -r line; do
    echo "=== Implementation ==="
    echo "$line"
done

# Search for method implementations
echo -e "\n=== sendEvent implementations ==="
rg "sendEvent.*\(.*additionalContext.*\)"

echo -e "\n=== invokePlugin implementations ==="
rg "invokePlugin.*\(.*additionalContext.*\)"

Length of output: 1443

sdks/workflow-browser-sdk/src/lib/workflow-browser-sdk.ts (3)

2-2: LGTM: Import addition is appropriate.

The addition of AnyRecord type import is well-placed and properly utilized for typing the new context parameter.


36-36: LGTM: Constructor changes are well-structured.

The additionalContext parameter is properly integrated into the constructor, and its assignment is correctly placed after service initialization.

Also applies to: 72-73


221-225: Verify the service method signatures.

The method signature updates look good and maintain backward compatibility. Let's verify that the underlying service methods in workflow-core package properly handle the additionalContext parameter.

Also applies to: 228-232

✅ Verification successful

Method signatures in workflow-core package are correctly aligned

The verification confirms that the underlying service methods in the workflow-core package properly handle the additionalContext parameter:

  • WorkflowRunner.sendEvent(event: WorkflowEventWithoutState, additionalContext?: AnyRecord)
  • WorkflowRunner.invokePlugin(pluginName: string, additionalContext?: AnyRecord)

The method signature updates in the browser SDK maintain backward compatibility and correctly forward the context parameter to these core implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the service method signatures in workflow-core package.

# Search for the service method definitions
ast-grep --pattern 'class $_ {
  $$$
  invokePlugin($_, additionalContext$_) {
    $$$
  }
  $$$
  sendEvent($_, additionalContext$_) {
    $$$
  }
  $$$
}'

Length of output: 158


Script:

#!/bin/bash
# Let's try a broader search for service methods using ripgrep
rg -A 5 "invokePlugin|sendEvent" --type ts

# Also search for class definitions containing these methods
ast-grep --pattern 'class $_ {
  $$$
  invokePlugin($_) {
    $$$
  }
  $$$
}'

ast-grep --pattern 'class $_ {
  $$$
  sendEvent($_) {
    $$$
  }
  $$$
}'

Length of output: 52220


Script:

#!/bin/bash
# Let's check the workflow-core package for the service implementation
rg -A 5 "class WorkflowRunner" --type ts

# Also search for the createWorkflow function that creates the service
rg -A 5 "createWorkflow" --type ts

Length of output: 33242


Script:

#!/bin/bash
# Let's look at the WorkflowRunner class implementation to verify the method signatures
rg -A 10 "async sendEvent|async invokePlugin" packages/workflow-core/src/lib/workflow-runner.ts

Length of output: 865

packages/workflow-core/src/lib/plugins/external-plugin/api-plugin.ts (3)

44-44: LGTM: Method signature change maintains backward compatibility

The addition of the optional additionalContext parameter is well-typed and maintains backward compatibility with existing code.


76-79: Review security implications of header context merging

The additional context can override header values derived from the base context. This requires careful consideration if headers contain sensitive information like authentication tokens.

Let's analyze header usage patterns:

#!/bin/bash
# Description: Find header patterns to understand security implications

# Search for header definitions and usage
rg -B 5 "headers.*?{.*?}"

# Search for sensitive patterns in headers
rg -i "(auth|token|key|secret|credential).*header"

62-65: Verify context merging behavior

The additional context can override base context values. Please ensure this is the intended behavior and that no critical keys from the base context should be preserved.

Let's analyze the context usage in the codebase:

✅ Verification successful

Based on the search results, I can now provide a final response:

Context merging behavior is safe and intentional

The _getPluginUrl method is used in both ApiPlugin and WebhookPlugin classes, where:

  1. In ApiPlugin, it's used with merged contexts to allow for dynamic URL generation with additional parameters
  2. In WebhookPlugin, it's used with just the base context

The method itself is protected and only processes the URL string, with no critical security or authentication context being overridden. The spread operator usage here is a valid pattern for extending the URL context with additional parameters.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of _getPluginUrl to understand what context keys are typically used

# Search for context keys used in URL patterns
rg -A 5 "url.*?{.*?}" 

# Search for _getPluginUrl method calls
ast-grep --pattern 'this._getPluginUrl($context)'

Length of output: 9477


Script:

#!/bin/bash
# Let's try a different approach to find _getPluginUrl usage and context patterns

# Search for _getPluginUrl method definition and its usage
rg "_getPluginUrl" -A 5 -B 5

# Search for context spread patterns near _getPluginUrl
rg "\.\.\.context.*_getPluginUrl" -A 5 -B 5

# Search for the class containing _getPluginUrl
ast-grep --pattern 'class $_ {
  $$$
  _getPluginUrl($_) {
    $$$
  }
  $$$
}'

Length of output: 3423

apps/kyb-app/src/pages/CollectionFlow/CollectionFlow.tsx (1)

41-41: LGTM!

The integration of additional workflow context is well-implemented. The import, hook usage, and prop passing follow React best practices.

Also applies to: 77-77, 148-148

services/workflows-service/CHANGELOG.md (1)

3-9: LGTM! Changelog updates are properly documented.

The changelog correctly documents the new version 0.7.69 with its dependency updates, maintaining consistency with the version control history.

packages/workflow-core/src/lib/workflow-runner.ts (6)

3-3: Approved

The import of search from jmespath is correctly added and used in the jmespath guard function.


561-561: Enhancement: Added additionalContext parameter to sendEvent

The inclusion of the optional additionalContext parameter in the sendEvent method improves flexibility by allowing extra data to be passed during event handling.


687-687: Propagation of additionalContext to __invokeApiPlugin

Passing the additionalContext to __invokeApiPlugin ensures that any additional context is utilized during API plugin invocation.


763-763: Enhancement: Updated __invokeApiPlugin to accept additionalContext

The method signature now accepts an optional additionalContext, enhancing the method's ability to handle additional data when invoking API plugins.


867-867: Enhancement: Added additionalContext parameter to invokePlugin

The invokePlugin method now accepts an optional additionalContext, allowing for more flexible plugin invocation with extra context data.


885-885: Propagation of additionalContext in invokePlugin

Passing additionalContext to __invokeApiPlugin within invokePlugin ensures consistency and proper handling of additional context across plugin invocations.

apps/kyb-app/src/pages/CollectionFlow/CollectionFlow.tsx Outdated Show resolved Hide resolved
sdks/workflow-browser-sdk/package.json Outdated Show resolved Hide resolved
- Update common, workflow-core and workflow-node-sdk versions
- Remove unnecessary createCollectionFlowToken flag from workflows
- Enhance context creation for workflow runtime data with new logic

(your workflows are more complicated than a Rubik's cube in a tornado)
@alonp99 alonp99 enabled auto-merge (squash) November 27, 2024 23:41
@alonp99 alonp99 merged commit e059a8a into dev Nov 27, 2024
10 checks passed
@alonp99 alonp99 deleted the illiar/feat/workflow-core-additional-context branch November 27, 2024 23:42
This was referenced Dec 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants