Skip to content

Conversation

Copy link

Copilot AI commented May 23, 2025

Problem

When multiple bundles of the keyborg package are loaded on the same site, each bundle maintains its own file-scoped _lastId variable. This leads to ID conflicts and incorrect behavior as different bundles can generate overlapping IDs for KeyborgCore and Keyborg instances.

// Before: Each bundle has its own _lastId counter
let _lastId = 0; // Bundle A starts at 0
let _lastId = 0; // Bundle B also starts at 0
// This causes ID collisions!

Solution

Move the _lastId counter to the shared window.__keyborg object so all bundles use the same ID sequence, ensuring unique IDs across all instances regardless of which bundle created them.

Changes Made

  • Extended WindowWithKeyborg interface to include _lastId: number
  • Created getNextId() helper function that manages the shared ID counter on window.__keyborg._lastId
  • Replaced all ++_lastId usages with calls to getNextId(win)
  • Removed the file-scoped _lastId variable
  • Added backward compatibility for older bundles that don't have the _lastId property

Compatibility Features

The fix ensures compatibility between fixed and unfixed bundles:

  • If window.__keyborg doesn't exist, initializes it with _lastId: 0
  • If window.__keyborg exists but lacks _lastId, adds it starting from 0
  • Preserves existing _lastId value when creating new __keyborg objects
  • Works seamlessly with both old and new bundle versions on the same page

Testing

  • ✅ Build passes with no TypeScript errors
  • ✅ Linting passes with no issues
  • ✅ ID generation works correctly across multiple instances
  • ✅ Backward compatibility verified with simulated older bundle scenarios
  • ✅ Shared counter properly increments and avoids collisions

This change resolves the multiple bundle issue while maintaining full backward compatibility.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

…le bundle compatibility

Co-authored-by: mathis-m <11584315+mathis-m@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix _lastId variable to ensure ID uniqueness across bundles Fix _lastId variable collision when multiple keyborg bundles are loaded May 23, 2025
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.

1 participant