spacetimedb 0.0.2 â 0.0.3
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/browser/react/index.mjs.map +1 -1
- package/dist/index.browser.mjs +18 -4
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.cjs +18 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +18 -16
- package/dist/index.mjs.map +1 -1
- package/dist/lib/algebraic_type.d.ts +115 -0
- package/dist/lib/algebraic_type.d.ts.map +1 -0
- package/dist/lib/algebraic_value.d.ts +6 -0
- package/dist/lib/algebraic_value.d.ts.map +1 -0
- package/dist/lib/autogen/algebraic_type_type.d.ts +64 -0
- package/dist/lib/autogen/algebraic_type_type.d.ts.map +1 -0
- package/dist/lib/autogen/algebraic_type_variants.d.ts +68 -0
- package/dist/lib/autogen/algebraic_type_variants.d.ts.map +1 -0
- package/dist/lib/autogen/index_type_type.d.ts +16 -0
- package/dist/lib/autogen/index_type_type.d.ts.map +1 -0
- package/dist/lib/autogen/index_type_variants.d.ts +7 -0
- package/dist/lib/autogen/index_type_variants.d.ts.map +1 -0
- package/dist/lib/autogen/lifecycle_type.d.ts +19 -0
- package/dist/lib/autogen/lifecycle_type.d.ts.map +1 -0
- package/dist/lib/autogen/lifecycle_variants.d.ts +10 -0
- package/dist/lib/autogen/lifecycle_variants.d.ts.map +1 -0
- package/dist/lib/autogen/misc_module_export_type.d.ts +12 -0
- package/dist/lib/autogen/misc_module_export_type.d.ts.map +1 -0
- package/dist/lib/autogen/misc_module_export_variants.d.ts +6 -0
- package/dist/lib/autogen/misc_module_export_variants.d.ts.map +1 -0
- package/dist/lib/autogen/product_type_element_type.d.ts +20 -0
- package/dist/lib/autogen/product_type_element_type.d.ts.map +1 -0
- package/dist/lib/autogen/product_type_type.d.ts +19 -0
- package/dist/lib/autogen/product_type_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_column_def_v_8_type.d.ts +20 -0
- package/dist/lib/autogen/raw_column_def_v_8_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_column_default_value_v_9_type.d.ts +20 -0
- package/dist/lib/autogen/raw_column_default_value_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_constraint_data_v_9_type.d.ts +12 -0
- package/dist/lib/autogen/raw_constraint_data_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_constraint_data_v_9_variants.d.ts +6 -0
- package/dist/lib/autogen/raw_constraint_data_v_9_variants.d.ts.map +1 -0
- package/dist/lib/autogen/raw_constraint_def_v_8_type.d.ts +20 -0
- package/dist/lib/autogen/raw_constraint_def_v_8_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_constraint_def_v_9_type.d.ts +20 -0
- package/dist/lib/autogen/raw_constraint_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_index_algorithm_type.d.ts +13 -0
- package/dist/lib/autogen/raw_index_algorithm_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_index_algorithm_variants.d.ts +13 -0
- package/dist/lib/autogen/raw_index_algorithm_variants.d.ts.map +1 -0
- package/dist/lib/autogen/raw_index_def_v_8_type.d.ts +22 -0
- package/dist/lib/autogen/raw_index_def_v_8_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_index_def_v_9_type.d.ts +21 -0
- package/dist/lib/autogen/raw_index_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_misc_module_export_v_9_type.d.ts +12 -0
- package/dist/lib/autogen/raw_misc_module_export_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_misc_module_export_v_9_variants.d.ts +6 -0
- package/dist/lib/autogen/raw_misc_module_export_v_9_variants.d.ts.map +1 -0
- package/dist/lib/autogen/raw_module_def_type.d.ts +14 -0
- package/dist/lib/autogen/raw_module_def_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_module_def_v_8_type.d.ts +25 -0
- package/dist/lib/autogen/raw_module_def_v_8_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_module_def_v_9_type.d.ts +29 -0
- package/dist/lib/autogen/raw_module_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_module_def_variants.d.ts +11 -0
- package/dist/lib/autogen/raw_module_def_variants.d.ts.map +1 -0
- package/dist/lib/autogen/raw_reducer_def_v_9_type.d.ts +22 -0
- package/dist/lib/autogen/raw_reducer_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_row_level_security_def_v_9_type.d.ts +18 -0
- package/dist/lib/autogen/raw_row_level_security_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_schedule_def_v_9_type.d.ts +20 -0
- package/dist/lib/autogen/raw_schedule_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_scoped_type_name_v_9_type.d.ts +19 -0
- package/dist/lib/autogen/raw_scoped_type_name_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_sequence_def_v_8_type.d.ts +24 -0
- package/dist/lib/autogen/raw_sequence_def_v_8_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_sequence_def_v_9_type.d.ts +23 -0
- package/dist/lib/autogen/raw_sequence_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_table_def_v_8_type.d.ts +29 -0
- package/dist/lib/autogen/raw_table_def_v_8_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_table_def_v_9_type.d.ts +32 -0
- package/dist/lib/autogen/raw_table_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_type_def_v_9_type.d.ts +21 -0
- package/dist/lib/autogen/raw_type_def_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/raw_unique_constraint_data_v_9_type.d.ts +18 -0
- package/dist/lib/autogen/raw_unique_constraint_data_v_9_type.d.ts.map +1 -0
- package/dist/lib/autogen/reducer_def_type.d.ts +20 -0
- package/dist/lib/autogen/reducer_def_type.d.ts.map +1 -0
- package/dist/lib/autogen/sum_type_type.d.ts +19 -0
- package/dist/lib/autogen/sum_type_type.d.ts.map +1 -0
- package/dist/lib/autogen/sum_type_variant_type.d.ts +20 -0
- package/dist/lib/autogen/sum_type_variant_type.d.ts.map +1 -0
- package/dist/lib/autogen/table_access_type.d.ts +16 -0
- package/dist/lib/autogen/table_access_type.d.ts.map +1 -0
- package/dist/lib/autogen/table_access_variants.d.ts +7 -0
- package/dist/lib/autogen/table_access_variants.d.ts.map +1 -0
- package/dist/lib/autogen/table_desc_type.d.ts +20 -0
- package/dist/lib/autogen/table_desc_type.d.ts.map +1 -0
- package/dist/lib/autogen/table_type_type.d.ts +16 -0
- package/dist/lib/autogen/table_type_type.d.ts.map +1 -0
- package/dist/lib/autogen/table_type_variants.d.ts +7 -0
- package/dist/lib/autogen/table_type_variants.d.ts.map +1 -0
- package/dist/lib/autogen/type_alias_type.d.ts +19 -0
- package/dist/lib/autogen/type_alias_type.d.ts.map +1 -0
- package/dist/lib/autogen/typespace_type.d.ts +19 -0
- package/dist/lib/autogen/typespace_type.d.ts.map +1 -0
- package/dist/lib/binary_reader.d.ts +25 -0
- package/dist/lib/binary_reader.d.ts.map +1 -0
- package/dist/lib/binary_writer.d.ts +25 -0
- package/dist/lib/binary_writer.d.ts.map +1 -0
- package/dist/lib/connection_id.d.ts +37 -0
- package/dist/lib/connection_id.d.ts.map +1 -0
- package/dist/lib/identity.d.ts +39 -0
- package/dist/lib/identity.d.ts.map +1 -0
- package/dist/lib/schedule_at.d.ts +23 -0
- package/dist/lib/schedule_at.d.ts.map +1 -0
- package/dist/lib/time_duration.d.ts +18 -0
- package/dist/lib/time_duration.d.ts.map +1 -0
- package/dist/lib/timestamp.d.ts +35 -0
- package/dist/lib/timestamp.d.ts.map +1 -0
- package/dist/lib/utils.d.ts +13 -0
- package/dist/lib/utils.d.ts.map +1 -0
- package/dist/min/index.browser.mjs +1 -1
- package/dist/min/index.browser.mjs.map +1 -1
- package/dist/min/react/index.mjs.map +1 -1
- package/dist/min/sdk/index.browser.mjs +1 -1
- package/dist/min/sdk/index.browser.mjs.map +1 -1
- package/dist/react/SpacetimeDBProvider.d.ts +8 -0
- package/dist/react/SpacetimeDBProvider.d.ts.map +1 -0
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.mjs.map +1 -1
- package/dist/react/useSpacetimeDB.d.ts +5 -0
- package/dist/react/useSpacetimeDB.d.ts.map +1 -0
- package/dist/react/useTable.d.ts +120 -0
- package/dist/react/useTable.d.ts.map +1 -0
- package/dist/sdk/client_api/bsatn_row_list_type.d.ts +20 -0
- package/dist/sdk/client_api/bsatn_row_list_type.d.ts.map +1 -0
- package/dist/sdk/client_api/call_reducer_type.d.ts +21 -0
- package/dist/sdk/client_api/call_reducer_type.d.ts.map +1 -0
- package/dist/sdk/client_api/client_message_type.d.ts +24 -0
- package/dist/sdk/client_api/client_message_type.d.ts.map +1 -0
- package/dist/sdk/client_api/client_message_variants.d.ts +36 -0
- package/dist/sdk/client_api/client_message_variants.d.ts.map +1 -0
- package/dist/sdk/client_api/compressable_query_update_type.d.ts +14 -0
- package/dist/sdk/client_api/compressable_query_update_type.d.ts.map +1 -0
- package/dist/sdk/client_api/compressable_query_update_variants.d.ts +14 -0
- package/dist/sdk/client_api/compressable_query_update_variants.d.ts.map +1 -0
- package/dist/sdk/client_api/database_update_type.d.ts +19 -0
- package/dist/sdk/client_api/database_update_type.d.ts.map +1 -0
- package/dist/sdk/client_api/energy_quanta_type.d.ts +18 -0
- package/dist/sdk/client_api/energy_quanta_type.d.ts.map +1 -0
- package/dist/sdk/client_api/identity_token_type.d.ts +20 -0
- package/dist/sdk/client_api/identity_token_type.d.ts.map +1 -0
- package/dist/sdk/client_api/index.d.ts +86 -0
- package/dist/sdk/client_api/index.d.ts.map +1 -0
- package/dist/sdk/client_api/initial_subscription_type.d.ts +21 -0
- package/dist/sdk/client_api/initial_subscription_type.d.ts.map +1 -0
- package/dist/sdk/client_api/one_off_query_response_type.d.ts +22 -0
- package/dist/sdk/client_api/one_off_query_response_type.d.ts.map +1 -0
- package/dist/sdk/client_api/one_off_query_type.d.ts +19 -0
- package/dist/sdk/client_api/one_off_query_type.d.ts.map +1 -0
- package/dist/sdk/client_api/one_off_table_type.d.ts +20 -0
- package/dist/sdk/client_api/one_off_table_type.d.ts.map +1 -0
- package/dist/sdk/client_api/query_id_type.d.ts +18 -0
- package/dist/sdk/client_api/query_id_type.d.ts.map +1 -0
- package/dist/sdk/client_api/query_update_type.d.ts +20 -0
- package/dist/sdk/client_api/query_update_type.d.ts.map +1 -0
- package/dist/sdk/client_api/reducer_call_info_type.d.ts +21 -0
- package/dist/sdk/client_api/reducer_call_info_type.d.ts.map +1 -0
- package/dist/sdk/client_api/row_size_hint_type.d.ts +12 -0
- package/dist/sdk/client_api/row_size_hint_type.d.ts.map +1 -0
- package/dist/sdk/client_api/row_size_hint_variants.d.ts +9 -0
- package/dist/sdk/client_api/row_size_hint_variants.d.ts.map +1 -0
- package/dist/sdk/client_api/server_message_type.d.ts +30 -0
- package/dist/sdk/client_api/server_message_type.d.ts.map +1 -0
- package/dist/sdk/client_api/server_message_variants.d.ts +51 -0
- package/dist/sdk/client_api/server_message_variants.d.ts.map +1 -0
- package/dist/sdk/client_api/subscribe_applied_type.d.ts +23 -0
- package/dist/sdk/client_api/subscribe_applied_type.d.ts.map +1 -0
- package/dist/sdk/client_api/subscribe_multi_applied_type.d.ts +23 -0
- package/dist/sdk/client_api/subscribe_multi_applied_type.d.ts.map +1 -0
- package/dist/sdk/client_api/subscribe_multi_type.d.ts +21 -0
- package/dist/sdk/client_api/subscribe_multi_type.d.ts.map +1 -0
- package/dist/sdk/client_api/subscribe_rows_type.d.ts +21 -0
- package/dist/sdk/client_api/subscribe_rows_type.d.ts.map +1 -0
- package/dist/sdk/client_api/subscribe_single_type.d.ts +21 -0
- package/dist/sdk/client_api/subscribe_single_type.d.ts.map +1 -0
- package/dist/sdk/client_api/subscribe_type.d.ts +19 -0
- package/dist/sdk/client_api/subscribe_type.d.ts.map +1 -0
- package/dist/sdk/client_api/subscription_error_type.d.ts +22 -0
- package/dist/sdk/client_api/subscription_error_type.d.ts.map +1 -0
- package/dist/sdk/client_api/table_update_type.d.ts +22 -0
- package/dist/sdk/client_api/table_update_type.d.ts.map +1 -0
- package/dist/sdk/client_api/transaction_update_light_type.d.ts +20 -0
- package/dist/sdk/client_api/transaction_update_light_type.d.ts.map +1 -0
- package/dist/sdk/client_api/transaction_update_type.d.ts +27 -0
- package/dist/sdk/client_api/transaction_update_type.d.ts.map +1 -0
- package/dist/sdk/client_api/unsubscribe_applied_type.d.ts +23 -0
- package/dist/sdk/client_api/unsubscribe_applied_type.d.ts.map +1 -0
- package/dist/sdk/client_api/unsubscribe_multi_applied_type.d.ts +23 -0
- package/dist/sdk/client_api/unsubscribe_multi_applied_type.d.ts.map +1 -0
- package/dist/sdk/client_api/unsubscribe_multi_type.d.ts +20 -0
- package/dist/sdk/client_api/unsubscribe_multi_type.d.ts.map +1 -0
- package/dist/sdk/client_api/unsubscribe_type.d.ts +20 -0
- package/dist/sdk/client_api/unsubscribe_type.d.ts.map +1 -0
- package/dist/sdk/client_api/update_status_type.d.ts +16 -0
- package/dist/sdk/client_api/update_status_type.d.ts.map +1 -0
- package/dist/sdk/client_api/update_status_variants.d.ts +13 -0
- package/dist/sdk/client_api/update_status_variants.d.ts.map +1 -0
- package/dist/sdk/client_cache.d.ts +17 -0
- package/dist/sdk/client_cache.d.ts.map +1 -0
- package/dist/sdk/db_connection_builder.d.ts +145 -0
- package/dist/sdk/db_connection_builder.d.ts.map +1 -0
- package/dist/sdk/db_connection_impl.d.ts +102 -0
- package/dist/sdk/db_connection_impl.d.ts.map +1 -0
- package/dist/sdk/db_context.d.ts +25 -0
- package/dist/sdk/db_context.d.ts.map +1 -0
- package/dist/sdk/decompress.d.ts +2 -0
- package/dist/sdk/decompress.d.ts.map +1 -0
- package/dist/sdk/event.d.ts +15 -0
- package/dist/sdk/event.d.ts.map +1 -0
- package/dist/sdk/event_context.d.ts +18 -0
- package/dist/sdk/event_context.d.ts.map +1 -0
- package/dist/sdk/event_emitter.d.ts +7 -0
- package/dist/sdk/event_emitter.d.ts.map +1 -0
- package/dist/sdk/index.browser.mjs +18 -4
- package/dist/sdk/index.browser.mjs.map +1 -1
- package/dist/sdk/index.cjs +18 -16
- package/dist/sdk/index.cjs.map +1 -1
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.d.ts.map +1 -0
- package/dist/sdk/index.mjs +18 -16
- package/dist/sdk/index.mjs.map +1 -1
- package/dist/sdk/json_api.d.ts +40 -0
- package/dist/sdk/json_api.d.ts.map +1 -0
- package/dist/sdk/logger.d.ts +4 -0
- package/dist/sdk/logger.d.ts.map +1 -0
- package/dist/sdk/message_types.d.ts +50 -0
- package/dist/sdk/message_types.d.ts.map +1 -0
- package/dist/sdk/reducer_event.d.ts +42 -0
- package/dist/sdk/reducer_event.d.ts.map +1 -0
- package/dist/sdk/spacetime_module.d.ts +31 -0
- package/dist/sdk/spacetime_module.d.ts.map +1 -0
- package/dist/sdk/subscription_builder_impl.d.ts +126 -0
- package/dist/sdk/subscription_builder_impl.d.ts.map +1 -0
- package/dist/sdk/table_cache.d.ts +111 -0
- package/dist/sdk/table_cache.d.ts.map +1 -0
- package/dist/sdk/version.d.ts +18 -0
- package/dist/sdk/version.d.ts.map +1 -0
- package/dist/sdk/websocket_decompress_adapter.d.ts +21 -0
- package/dist/sdk/websocket_decompress_adapter.d.ts.map +1 -0
- package/dist/sdk/websocket_test_adapter.d.ts +22 -0
- package/dist/sdk/websocket_test_adapter.d.ts.map +1 -0
- package/dist/sdk/ws.d.ts +2 -0
- package/dist/sdk/ws.d.ts.map +1 -0
- package/dist/server/index.d.ts +3 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/type_builders.d.ts +656 -0
- package/dist/server/type_builders.d.ts.map +1 -0
- package/dist/server/type_builders.test-d.d.ts +2 -0
- package/dist/server/type_builders.test-d.d.ts.map +1 -0
- package/dist/server/type_util.d.ts +18 -0
- package/dist/server/type_util.d.ts.map +1 -0
- package/package.json +30 -27
- package/src/react/SpacetimeDBProvider.ts +4 -1
- package/src/react/useSpacetimeDB.ts +1 -1
- package/src/react/useTable.ts +1 -1
- package/src/sdk/db_connection_builder.ts +1 -1
- package/src/sdk/db_connection_impl.ts +6 -6
- package/src/sdk/message_types.ts +3 -3
- package/src/sdk/reducer_event.ts +3 -3
- package/src/sdk/spacetime_module.ts +1 -1
- package/src/sdk/table_cache.ts +1 -1
- package/src/sdk/websocket_decompress_adapter.ts +2 -30
- package/src/sdk/websocket_test_adapter.ts +1 -1
- package/src/sdk/ws.ts +24 -0
- package/LICENSE.txt +0 -759
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/react/useSpacetimeDB.ts","../../../src/react/SpacetimeDBProvider.ts","../../../src/react/useTable.ts"],"names":["where"],"mappings":";AAGO,IAAM,kBAAA,GACX,cAA4C,MAAS,CAAA;AAIhD,SAAS,cAAA,GAEE;AAChB,EAAA,MAAM,OAAA,GAAU,WAAW,kBAAkB,CAAA;AAC7C,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;;;ACDO,SAAS,mBAAA,CAId;AAAA,EACA,iBAAA;AAAA,EACA;AACF,CAAA,EAIsB;AACpB,EAAA,OAAa,KAAA,CAAA,aAAA;AAAA,IACX,kBAAA,CAAmB,QAAA;AAAA,IACnB,EAAE,KAAA,EAAO,iBAAA,CAAkB,KAAA,EAAM,EAAE;AAAA;AAAA,IACnC;AAAA,GACF;AACF;ACXO,IAAM,EAAA,GAAK,CAChB,GAAA,EACA,KAAA,MACkB,EAAE,IAAA,EAAM,IAAA,EAAM,KAAK,KAAA,EAAM;AA4CtC,SAAS,QAAA,CACd,MACA,GAAA,EACS;AAC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A;AAC7B,QAAA,KAAA,CAAM,iBAAiB,QAAQ,CAAA;AAAA,MACjC,CAAA;AAAA,IACF,CAAA;AAAA;AAAA,IAEA;AAAA,MACE,MAAA;AAAA,MACA,SAAA;AAAA,MACA,QAAA;AAAA,MACA,SAAA,EAAW,QAAA;AAAA,MACX,SAAA,EAAW,QAAA;AAAA,MACX,SAAA,EAAW;AAAA;AACb,GACF;AAEA,EAAA,MAAM,WAAA,GAAc,YAAY,MAAyB;AACvD,IAAA,IAAI,CAAC,gBAAgB,OAAA,EAAS;AAC5B,MAAA,eAAA,CAAgB,UAAU,eAAA,EAAgB;AAAA,IAC5C;AACA,IAAA,OAAO,eAAA,CAAgB,OAAA;AAAA,EACzB,CAAA,EAAG,CAAC,eAAe,CAAC,CAAA;AAGpB,EAAA,OAAO,oBAAA,CAAqB,SAAA,EAAW,WAAA,EAAa,WAAW,CAAA;AACjE","file":"index.mjs","sourcesContent":["import { createContext, useContext, type Context } from 'react';\nimport type { DbConnectionImpl } from '../index';\n\nexport const SpacetimeDBContext: Context<DbConnectionImpl | undefined> =\n createContext<DbConnectionImpl | undefined>(undefined);\n\n// Throws an error if used outside of a SpacetimeDBProvider\n// Error is caught by other hooks like useTable so they can provide better error messages\nexport function useSpacetimeDB<\n DbConnection extends DbConnectionImpl,\n>(): DbConnection {\n const context = useContext(SpacetimeDBContext) as DbConnection | undefined;\n if (!context) {\n throw new Error(\n 'useSpacetimeDB must be used within a SpacetimeDBProvider component. Did you forget to add a `SpacetimeDBProvider` to your component tree?'\n );\n }\n return context;\n}\n","import { DbConnectionBuilder, type DbConnectionImpl } from '../index';\nimport * as React from 'react';\nimport { SpacetimeDBContext } from './useSpacetimeDB';\n\nexport interface SpacetimeDBProviderProps<\n DbConnection extends DbConnectionImpl,\n ErrorContext,\n SubscriptionEventContext,\n> {\n connectionBuilder: DbConnectionBuilder<\n DbConnection,\n ErrorContext,\n SubscriptionEventContext\n >;\n children?: React.ReactNode;\n}\n\nexport function SpacetimeDBProvider<\n DbConnection extends DbConnectionImpl,\n ErrorContext,\n SubscriptionEventContext,\n>({\n connectionBuilder,\n children,\n}: SpacetimeDBProviderProps<\n DbConnection,\n ErrorContext,\n SubscriptionEventContext\n>): React.JSX.Element {\n return React.createElement(\n SpacetimeDBContext.Provider,\n { value: connectionBuilder.build() }, // May need to modify this to do it lazily in server-side rendering\n children\n );\n}\n","import {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useSpacetimeDB } from './useSpacetimeDB';\nimport { DbConnectionImpl, TableCache } from '../sdk';\n\nexport interface UseQueryCallbacks<RowType> {\n onInsert?: (row: RowType) => void;\n onDelete?: (row: RowType) => void;\n onUpdate?: (oldRow: RowType, newRow: RowType) => void;\n}\n\nexport type Value = string | number | boolean;\n\nexport type Expr<Column extends string> =\n | { type: 'eq'; key: Column; value: Value }\n | { type: 'and'; children: Expr<Column>[] }\n | { type: 'or'; children: Expr<Column>[] };\n\nexport const eq = <Column extends string>(\n key: Column,\n value: Value\n): Expr<Column> => ({ type: 'eq', key, value });\n\nexport const and = <Column extends string>(\n ...children: Expr<Column>[]\n): Expr<Column> => {\n const flat: Expr<Column>[] = [];\n for (const c of children) {\n if (!c) continue;\n if (c.type === 'and') flat.push(...c.children);\n else flat.push(c);\n }\n const pruned = flat.filter(Boolean);\n if (pruned.length === 0) return { type: 'and', children: [] };\n if (pruned.length === 1) return pruned[0];\n return { type: 'and', children: pruned };\n};\n\nexport const or = <Column extends string>(\n ...children: Expr<Column>[]\n): Expr<Column> => {\n const flat: Expr<Column>[] = [];\n for (const c of children) {\n if (!c) continue;\n if (c.type === 'or') flat.push(...c.children);\n else flat.push(c);\n }\n const pruned = flat.filter(Boolean);\n if (pruned.length === 0) return { type: 'or', children: [] };\n if (pruned.length === 1) return pruned[0];\n return { type: 'or', children: pruned };\n};\n\nexport const isEq = <Column extends string>(\n e: Expr<Column>\n): e is Extract<Expr<Column>, { type: 'eq' }> => e.type === 'eq';\nexport const isAnd = <Column extends string>(\n e: Expr<Column>\n): e is Extract<Expr<Column>, { type: 'and' }> => e.type === 'and';\nexport const isOr = <Column extends string>(\n e: Expr<Column>\n): e is Extract<Expr<Column>, { type: 'or' }> => e.type === 'or';\n\ntype RecordLike<Column extends string> = Record<Column, unknown>;\n\nexport function evaluate<Column extends string>(\n expr: Expr<Column>,\n row: RecordLike<Column>\n): boolean {\n switch (expr.type) {\n case 'eq': {\n const v = row[expr.key];\n if (\n typeof v === 'string' ||\n typeof v === 'number' ||\n typeof v === 'boolean'\n ) {\n return v === expr.value;\n }\n return false;\n }\n case 'and':\n return (\n expr.children.length === 0 || expr.children.every(c => evaluate(c, row))\n );\n case 'or':\n return (\n expr.children.length !== 0 && expr.children.some(c => evaluate(c, row))\n );\n }\n}\n\nfunction formatValue(v: Value): string {\n switch (typeof v) {\n case 'string':\n return `'${v.replace(/'/g, \"''\")}'`;\n case 'number':\n return Number.isFinite(v) ? String(v) : `'${String(v)}'`;\n case 'boolean':\n return v ? 'TRUE' : 'FALSE';\n }\n}\n\nfunction escapeIdent(id: string): string {\n if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(id)) return id;\n return `\"${id.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction parenthesize(s: string): string {\n if (!s.includes(' AND ') && !s.includes(' OR ')) return s;\n return `(${s})`;\n}\n\nexport function toString<Column extends string>(expr: Expr<Column>): string {\n switch (expr.type) {\n case 'eq':\n return `${escapeIdent(expr.key)} = ${formatValue(expr.value)}`;\n case 'and':\n return parenthesize(expr.children.map(toString).join(' AND '));\n case 'or':\n return parenthesize(expr.children.map(toString).join(' OR '));\n }\n}\n\n/**\n * This is just the identity function to make things look like SQL.\n * @param expr\n * @returns\n */\nexport function where<Column extends string>(expr: Expr<Column>): Expr<Column> {\n return expr;\n}\n\ntype Snapshot<RowType> = {\n readonly rows: readonly RowType[];\n readonly state: 'loading' | 'ready';\n};\n\ntype MembershipChange = 'enter' | 'leave' | 'stayIn' | 'stayOut';\n\nfunction classifyMembership<\n Col extends string,\n R extends Record<string, unknown>,\n>(where: Expr<Col> | undefined, oldRow: R, newRow: R): MembershipChange {\n // No filter: everything is in, so updates are always \"stayIn\".\n if (!where) {\n return 'stayIn';\n }\n\n const oldIn = evaluate(where, oldRow);\n const newIn = evaluate(where, newRow);\n\n if (oldIn && !newIn) {\n return 'leave';\n }\n if (!oldIn && newIn) {\n return 'enter';\n }\n if (oldIn && newIn) {\n return 'stayIn';\n }\n return 'stayOut';\n}\n\n/**\n * Extracts the column names from a RowType whose values are of type Value.\n * Note that this will exclude columns that are of type object, array, etc.\n */\ntype ColumnsFromRow<R> = {\n [K in keyof R]-?: R[K] extends Value | undefined ? K : never;\n}[keyof R] &\n string;\n\n/**\n * React hook to subscribe to a table in SpacetimeDB and receive live updates as rows are inserted, updated, or deleted.\n *\n * This hook returns a snapshot of the table's rows, filtered by an optional `where` clause, and provides a loading state\n * until the initial subscription is applied. It also allows you to specify callbacks for row insertions, deletions, and updates.\n *\n * The hook must be used within a component tree wrapped by `SpacetimeDBProvider`.\n *\n * Overloads:\n * - `useTable(tableName, where, callbacks?)`: Subscribe to a table with a filter and optional callbacks.\n * - `useTable(tableName, callbacks?)`: Subscribe to a table without a filter, with optional callbacks.\n *\n * @template DbConnection The type of the SpacetimeDB connection.\n * @template RowType The type of the table row.\n * @template TableName The name of the table.\n *\n * @param tableName - The name of the table to subscribe to.\n * @param whereClauseOrCallbacks - (Optional) Either a filter expression (where clause) or the callbacks object.\n * @param callbacks - (Optional) Callbacks for row insert, delete, and update events.\n *\n * @returns A snapshot object containing the current rows and the subscription state (`'loading'` or `'ready'`).\n *\n * @throws Error if the hook is used outside of a `SpacetimeDBProvider`.\n *\n * @example\n * ```tsx\n * const { rows, state } = useTable('users', where(eq('isActive', true)), {\n * onInsert: (row) => console.log('Inserted:', row),\n * onDelete: (row) => console.log('Deleted:', row),\n * onUpdate: (oldRow, newRow) => console.log('Updated:', oldRow, newRow),\n * });\n * ```\n */\nexport function useTable<\n DbConnection extends DbConnectionImpl,\n RowType extends Record<string, any>,\n TableName extends keyof DbConnection['db'] &\n string = keyof DbConnection['db'] & string,\n>(\n tableName: TableName,\n where: Expr<ColumnsFromRow<RowType>>,\n callbacks?: UseQueryCallbacks<RowType>\n): Snapshot<RowType>;\n\n/**\n * React hook to subscribe to a table in SpacetimeDB and receive live updates as rows are inserted, updated, or deleted.\n *\n * This hook returns a snapshot of the table's rows, filtered by an optional `where` clause, and provides a loading state\n * until the initial subscription is applied. It also allows you to specify callbacks for row insertions, deletions, and updates.\n *\n * The hook must be used within a component tree wrapped by `SpacetimeDBProvider`.\n *\n * Overloads:\n * - `useTable(tableName, where, callbacks?)`: Subscribe to a table with a filter and optional callbacks.\n * - `useTable(tableName, callbacks?)`: Subscribe to a table without a filter, with optional callbacks.\n *\n * @template DbConnection The type of the SpacetimeDB connection.\n * @template RowType The type of the table row.\n * @template TableName The name of the table.\n *\n * @param tableName - The name of the table to subscribe to.\n * @param whereClauseOrCallbacks - (Optional) Either a filter expression (where clause) or the callbacks object.\n * @param callbacks - (Optional) Callbacks for row insert, delete, and update events.\n *\n * @returns A snapshot object containing the current rows and the subscription state (`'loading'` or `'ready'`).\n *\n * @throws Error if the hook is used outside of a `SpacetimeDBProvider`.\n *\n * @example\n * ```tsx\n * const { rows, state } = useTable('users', where(eq('isActive', true)), {\n * onInsert: (row) => console.log('Inserted:', row),\n * onDelete: (row) => console.log('Deleted:', row),\n * onUpdate: (oldRow, newRow) => console.log('Updated:', oldRow, newRow),\n * });\n * ```\n */\nexport function useTable<\n DbConnection extends DbConnectionImpl,\n RowType extends Record<string, any>,\n TableName extends keyof DbConnection['db'] &\n string = keyof DbConnection['db'] & string,\n>(\n tableName: TableName,\n callbacks?: UseQueryCallbacks<RowType>\n): Snapshot<RowType>;\n\nexport function useTable<\n DbConnection extends DbConnectionImpl,\n RowType extends Record<string, any>,\n TableName extends keyof DbConnection['db'] &\n string = keyof DbConnection['db'] & string,\n>(\n tableName: TableName,\n whereClauseOrCallbacks?:\n | Expr<ColumnsFromRow<RowType>>\n | UseQueryCallbacks<RowType>,\n callbacks?: UseQueryCallbacks<RowType>\n): Snapshot<RowType> {\n let whereClause: Expr<ColumnsFromRow<RowType>> | undefined;\n if (\n whereClauseOrCallbacks &&\n typeof whereClauseOrCallbacks === 'object' &&\n 'type' in whereClauseOrCallbacks\n ) {\n whereClause = whereClauseOrCallbacks as Expr<ColumnsFromRow<RowType>>;\n } else {\n callbacks = whereClauseOrCallbacks as\n | UseQueryCallbacks<RowType>\n | undefined;\n }\n const [subscribeApplied, setSubscribeApplied] = useState(false);\n const [isActive, setIsActive] = useState(false);\n let spacetime: DbConnection | undefined;\n try {\n spacetime = useSpacetimeDB<DbConnection>();\n } catch {\n throw new Error(\n 'Could not find SpacetimeDB client! Did you forget to add a ' +\n '`SpacetimeDBProvider`? `useTable` must be used in the React component tree ' +\n 'under a `SpacetimeDBProvider` component.'\n );\n }\n const client = spacetime;\n\n const query =\n `SELECT * FROM ${tableName}` +\n (whereClause ? ` WHERE ${toString(whereClause)}` : '');\n\n const latestTransactionEvent = useRef<any>(null);\n const lastSnapshotRef = useRef<Snapshot<RowType> | null>(null);\n\n const whereKey = whereClause ? toString(whereClause) : '';\n\n const computeSnapshot = useCallback((): Snapshot<RowType> => {\n const table = client.db[\n tableName as keyof typeof client.db\n ] as unknown as TableCache<RowType>;\n const result: readonly RowType[] = whereClause\n ? table.iter().filter(row => evaluate(whereClause, row))\n : table.iter();\n return {\n rows: result,\n state: subscribeApplied ? 'ready' : 'loading',\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, tableName, whereKey, subscribeApplied]);\n\n useEffect(() => {\n const onConnect = () => {\n setIsActive(client.isActive);\n };\n const onDisconnect = () => {\n setIsActive(client.isActive);\n };\n const onConnectError = () => {\n setIsActive(client.isActive);\n };\n client['on']('connect', onConnect);\n client['on']('disconnect', onDisconnect);\n client['on']('connectError', onConnectError);\n return () => {\n client['off']('connect', onConnect);\n client['off']('disconnect', onDisconnect);\n client['off']('connectError', onConnectError);\n };\n }, [client]);\n\n useEffect(() => {\n if (isActive) {\n const cancel = client\n .subscriptionBuilder()\n .onApplied(() => {\n setSubscribeApplied(true);\n })\n .subscribe(query);\n return () => {\n cancel.unsubscribe();\n };\n }\n }, [query, isActive, client]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const onInsert = (ctx: any, row: RowType) => {\n if (whereClause && !evaluate(whereClause, row)) {\n return;\n }\n if (tableName === 'message') {\n console.log('onInsert for messages table:', row);\n }\n callbacks?.onInsert?.(row);\n if (\n ctx.event !== latestTransactionEvent.current ||\n !latestTransactionEvent.current\n ) {\n latestTransactionEvent.current = ctx.event;\n lastSnapshotRef.current = computeSnapshot();\n onStoreChange();\n }\n };\n\n const onDelete = (ctx: any, row: RowType) => {\n if (whereClause && !evaluate(whereClause, row)) {\n return;\n }\n if (tableName === 'message') {\n console.log('onDelete for messages table:', row);\n }\n callbacks?.onDelete?.(row);\n if (\n ctx.event !== latestTransactionEvent.current ||\n !latestTransactionEvent.current\n ) {\n latestTransactionEvent.current = ctx.event;\n lastSnapshotRef.current = computeSnapshot();\n onStoreChange();\n }\n };\n\n const onUpdate = (ctx: any, oldRow: RowType, newRow: RowType) => {\n const change = classifyMembership(whereClause, oldRow, newRow);\n\n switch (change) {\n case 'leave':\n callbacks?.onDelete?.(oldRow);\n break;\n case 'enter':\n callbacks?.onInsert?.(newRow);\n break;\n case 'stayIn':\n callbacks?.onUpdate?.(oldRow, newRow);\n break;\n case 'stayOut':\n return; // no-op\n }\n\n if (\n ctx.event !== latestTransactionEvent.current ||\n !latestTransactionEvent.current\n ) {\n latestTransactionEvent.current = ctx.event;\n lastSnapshotRef.current = computeSnapshot();\n onStoreChange();\n }\n };\n\n const table = client.db[\n tableName as keyof typeof client.db\n ] as unknown as TableCache<RowType>;\n table.onInsert(onInsert);\n table.onDelete(onDelete);\n table.onUpdate?.(onUpdate);\n\n return () => {\n table.removeOnInsert(onInsert);\n table.removeOnDelete(onDelete);\n table.removeOnUpdate?.(onUpdate);\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n client,\n tableName,\n whereKey,\n callbacks?.onDelete,\n callbacks?.onInsert,\n callbacks?.onUpdate,\n ]\n );\n\n const getSnapshot = useCallback((): Snapshot<RowType> => {\n if (!lastSnapshotRef.current) {\n lastSnapshotRef.current = computeSnapshot();\n }\n return lastSnapshotRef.current;\n }, [computeSnapshot]);\n\n // SSR fallback can be the same getter\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/react/useSpacetimeDB.ts","../../../src/react/SpacetimeDBProvider.ts","../../../src/react/useTable.ts"],"names":["where"],"mappings":";AAGO,IAAM,kBAAA,GACX,cAA4C,MAAS,CAAA;AAIhD,SAAS,cAAA,GAEE;AAChB,EAAA,MAAM,OAAA,GAAU,WAAW,kBAAkB,CAAA;AAC7C,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;;;ACEO,SAAS,mBAAA,CAId;AAAA,EACA,iBAAA;AAAA,EACA;AACF,CAAA,EAIsB;AACpB,EAAA,OAAa,KAAA,CAAA,aAAA;AAAA,IACX,kBAAA,CAAmB,QAAA;AAAA,IACnB,EAAE,KAAA,EAAO,iBAAA,CAAkB,KAAA,EAAM,EAAE;AAAA;AAAA,IACnC;AAAA,GACF;AACF;ACdO,IAAM,EAAA,GAAK,CAChB,GAAA,EACA,KAAA,MACkB,EAAE,IAAA,EAAM,IAAA,EAAM,KAAK,KAAA,EAAM;AA4CtC,SAAS,QAAA,CACd,MACA,GAAA,EACS;AACT,EAAA,QAAQ,KAAK,IAAA;AAAM,IACjB,KAAK,IAAA,EAAM;AACT,MAAA,MAAM,CAAA,GAAI,GAAA,CAAI,IAAA,CAAK,GAAG,CAAA;AACtB,MAA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AA;AAAA,MACA,QAAA;AAAA,MACA,SAAA,EAAW,QAAA;AAAA,MACX,SAAA,EAAW,QAAA;AAAA,MACX,SAAA,EAAW;AAAA;AACb,GACF;AAEA,EAAA,MAAM,WAAA,GAAc,YAAY,MAAyB;AACvD,IAAA,IAAI,CAAC,gBAAgB,OAAA,EAAS;AAC5B,MAAA,eAAA,CAAgB,UAAU,eAAA,EAAgB;AAAA,IAC5C;AACA,IAAA,OAAO,eAAA,CAAgB,OAAA;AAAA,EACzB,CAAA,EAAG,CAAC,eAAe,CAAC,CAAA;AAGpB,EAAA,OAAO,oBAAA,CAAqB,SAAA,EAAW,WAAA,EAAa,WAAW,CAAA;AACjE","file":"index.mjs","sourcesContent":["import { createContext, useContext, type Context } from 'react';\nimport type { DbConnectionImpl } from '../sdk/db_connection_impl';\n\nexport const SpacetimeDBContext: Context<DbConnectionImpl | undefined> =\n createContext<DbConnectionImpl | undefined>(undefined);\n\n// Throws an error if used outside of a SpacetimeDBProvider\n// Error is caught by other hooks like useTable so they can provide better error messages\nexport function useSpacetimeDB<\n DbConnection extends DbConnectionImpl,\n>(): DbConnection {\n const context = useContext(SpacetimeDBContext) as DbConnection | undefined;\n if (!context) {\n throw new Error(\n 'useSpacetimeDB must be used within a SpacetimeDBProvider component. Did you forget to add a `SpacetimeDBProvider` to your component tree?'\n );\n }\n return context;\n}\n","import {\n DbConnectionBuilder,\n type DbConnectionImpl,\n} from '../sdk/db_connection_impl';\nimport * as React from 'react';\nimport { SpacetimeDBContext } from './useSpacetimeDB';\n\nexport interface SpacetimeDBProviderProps<\n DbConnection extends DbConnectionImpl,\n ErrorContext,\n SubscriptionEventContext,\n> {\n connectionBuilder: DbConnectionBuilder<\n DbConnection,\n ErrorContext,\n SubscriptionEventContext\n >;\n children?: React.ReactNode;\n}\n\nexport function SpacetimeDBProvider<\n DbConnection extends DbConnectionImpl,\n ErrorContext,\n SubscriptionEventContext,\n>({\n connectionBuilder,\n children,\n}: SpacetimeDBProviderProps<\n DbConnection,\n ErrorContext,\n SubscriptionEventContext\n>): React.JSX.Element {\n return React.createElement(\n SpacetimeDBContext.Provider,\n { value: connectionBuilder.build() }, // May need to modify this to do it lazily in server-side rendering\n children\n );\n}\n","import {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useSpacetimeDB } from './useSpacetimeDB';\nimport { DbConnectionImpl, TableCache } from '../sdk/db_connection_impl';\n\nexport interface UseQueryCallbacks<RowType> {\n onInsert?: (row: RowType) => void;\n onDelete?: (row: RowType) => void;\n onUpdate?: (oldRow: RowType, newRow: RowType) => void;\n}\n\nexport type Value = string | number | boolean;\n\nexport type Expr<Column extends string> =\n | { type: 'eq'; key: Column; value: Value }\n | { type: 'and'; children: Expr<Column>[] }\n | { type: 'or'; children: Expr<Column>[] };\n\nexport const eq = <Column extends string>(\n key: Column,\n value: Value\n): Expr<Column> => ({ type: 'eq', key, value });\n\nexport const and = <Column extends string>(\n ...children: Expr<Column>[]\n): Expr<Column> => {\n const flat: Expr<Column>[] = [];\n for (const c of children) {\n if (!c) continue;\n if (c.type === 'and') flat.push(...c.children);\n else flat.push(c);\n }\n const pruned = flat.filter(Boolean);\n if (pruned.length === 0) return { type: 'and', children: [] };\n if (pruned.length === 1) return pruned[0];\n return { type: 'and', children: pruned };\n};\n\nexport const or = <Column extends string>(\n ...children: Expr<Column>[]\n): Expr<Column> => {\n const flat: Expr<Column>[] = [];\n for (const c of children) {\n if (!c) continue;\n if (c.type === 'or') flat.push(...c.children);\n else flat.push(c);\n }\n const pruned = flat.filter(Boolean);\n if (pruned.length === 0) return { type: 'or', children: [] };\n if (pruned.length === 1) return pruned[0];\n return { type: 'or', children: pruned };\n};\n\nexport const isEq = <Column extends string>(\n e: Expr<Column>\n): e is Extract<Expr<Column>, { type: 'eq' }> => e.type === 'eq';\nexport const isAnd = <Column extends string>(\n e: Expr<Column>\n): e is Extract<Expr<Column>, { type: 'and' }> => e.type === 'and';\nexport const isOr = <Column extends string>(\n e: Expr<Column>\n): e is Extract<Expr<Column>, { type: 'or' }> => e.type === 'or';\n\ntype RecordLike<Column extends string> = Record<Column, unknown>;\n\nexport function evaluate<Column extends string>(\n expr: Expr<Column>,\n row: RecordLike<Column>\n): boolean {\n switch (expr.type) {\n case 'eq': {\n const v = row[expr.key];\n if (\n typeof v === 'string' ||\n typeof v === 'number' ||\n typeof v === 'boolean'\n ) {\n return v === expr.value;\n }\n return false;\n }\n case 'and':\n return (\n expr.children.length === 0 || expr.children.every(c => evaluate(c, row))\n );\n case 'or':\n return (\n expr.children.length !== 0 && expr.children.some(c => evaluate(c, row))\n );\n }\n}\n\nfunction formatValue(v: Value): string {\n switch (typeof v) {\n case 'string':\n return `'${v.replace(/'/g, \"''\")}'`;\n case 'number':\n return Number.isFinite(v) ? String(v) : `'${String(v)}'`;\n case 'boolean':\n return v ? 'TRUE' : 'FALSE';\n }\n}\n\nfunction escapeIdent(id: string): string {\n if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(id)) return id;\n return `\"${id.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction parenthesize(s: string): string {\n if (!s.includes(' AND ') && !s.includes(' OR ')) return s;\n return `(${s})`;\n}\n\nexport function toString<Column extends string>(expr: Expr<Column>): string {\n switch (expr.type) {\n case 'eq':\n return `${escapeIdent(expr.key)} = ${formatValue(expr.value)}`;\n case 'and':\n return parenthesize(expr.children.map(toString).join(' AND '));\n case 'or':\n return parenthesize(expr.children.map(toString).join(' OR '));\n }\n}\n\n/**\n * This is just the identity function to make things look like SQL.\n * @param expr\n * @returns\n */\nexport function where<Column extends string>(expr: Expr<Column>): Expr<Column> {\n return expr;\n}\n\ntype Snapshot<RowType> = {\n readonly rows: readonly RowType[];\n readonly state: 'loading' | 'ready';\n};\n\ntype MembershipChange = 'enter' | 'leave' | 'stayIn' | 'stayOut';\n\nfunction classifyMembership<\n Col extends string,\n R extends Record<string, unknown>,\n>(where: Expr<Col> | undefined, oldRow: R, newRow: R): MembershipChange {\n // No filter: everything is in, so updates are always \"stayIn\".\n if (!where) {\n return 'stayIn';\n }\n\n const oldIn = evaluate(where, oldRow);\n const newIn = evaluate(where, newRow);\n\n if (oldIn && !newIn) {\n return 'leave';\n }\n if (!oldIn && newIn) {\n return 'enter';\n }\n if (oldIn && newIn) {\n return 'stayIn';\n }\n return 'stayOut';\n}\n\n/**\n * Extracts the column names from a RowType whose values are of type Value.\n * Note that this will exclude columns that are of type object, array, etc.\n */\ntype ColumnsFromRow<R> = {\n [K in keyof R]-?: R[K] extends Value | undefined ? K : never;\n}[keyof R] &\n string;\n\n/**\n * React hook to subscribe to a table in SpacetimeDB and receive live updates as rows are inserted, updated, or deleted.\n *\n * This hook returns a snapshot of the table's rows, filtered by an optional `where` clause, and provides a loading state\n * until the initial subscription is applied. It also allows you to specify callbacks for row insertions, deletions, and updates.\n *\n * The hook must be used within a component tree wrapped by `SpacetimeDBProvider`.\n *\n * Overloads:\n * - `useTable(tableName, where, callbacks?)`: Subscribe to a table with a filter and optional callbacks.\n * - `useTable(tableName, callbacks?)`: Subscribe to a table without a filter, with optional callbacks.\n *\n * @template DbConnection The type of the SpacetimeDB connection.\n * @template RowType The type of the table row.\n * @template TableName The name of the table.\n *\n * @param tableName - The name of the table to subscribe to.\n * @param whereClauseOrCallbacks - (Optional) Either a filter expression (where clause) or the callbacks object.\n * @param callbacks - (Optional) Callbacks for row insert, delete, and update events.\n *\n * @returns A snapshot object containing the current rows and the subscription state (`'loading'` or `'ready'`).\n *\n * @throws Error if the hook is used outside of a `SpacetimeDBProvider`.\n *\n * @example\n * ```tsx\n * const { rows, state } = useTable('users', where(eq('isActive', true)), {\n * onInsert: (row) => console.log('Inserted:', row),\n * onDelete: (row) => console.log('Deleted:', row),\n * onUpdate: (oldRow, newRow) => console.log('Updated:', oldRow, newRow),\n * });\n * ```\n */\nexport function useTable<\n DbConnection extends DbConnectionImpl,\n RowType extends Record<string, any>,\n TableName extends keyof DbConnection['db'] &\n string = keyof DbConnection['db'] & string,\n>(\n tableName: TableName,\n where: Expr<ColumnsFromRow<RowType>>,\n callbacks?: UseQueryCallbacks<RowType>\n): Snapshot<RowType>;\n\n/**\n * React hook to subscribe to a table in SpacetimeDB and receive live updates as rows are inserted, updated, or deleted.\n *\n * This hook returns a snapshot of the table's rows, filtered by an optional `where` clause, and provides a loading state\n * until the initial subscription is applied. It also allows you to specify callbacks for row insertions, deletions, and updates.\n *\n * The hook must be used within a component tree wrapped by `SpacetimeDBProvider`.\n *\n * Overloads:\n * - `useTable(tableName, where, callbacks?)`: Subscribe to a table with a filter and optional callbacks.\n * - `useTable(tableName, callbacks?)`: Subscribe to a table without a filter, with optional callbacks.\n *\n * @template DbConnection The type of the SpacetimeDB connection.\n * @template RowType The type of the table row.\n * @template TableName The name of the table.\n *\n * @param tableName - The name of the table to subscribe to.\n * @param whereClauseOrCallbacks - (Optional) Either a filter expression (where clause) or the callbacks object.\n * @param callbacks - (Optional) Callbacks for row insert, delete, and update events.\n *\n * @returns A snapshot object containing the current rows and the subscription state (`'loading'` or `'ready'`).\n *\n * @throws Error if the hook is used outside of a `SpacetimeDBProvider`.\n *\n * @example\n * ```tsx\n * const { rows, state } = useTable('users', where(eq('isActive', true)), {\n * onInsert: (row) => console.log('Inserted:', row),\n * onDelete: (row) => console.log('Deleted:', row),\n * onUpdate: (oldRow, newRow) => console.log('Updated:', oldRow, newRow),\n * });\n * ```\n */\nexport function useTable<\n DbConnection extends DbConnectionImpl,\n RowType extends Record<string, any>,\n TableName extends keyof DbConnection['db'] &\n string = keyof DbConnection['db'] & string,\n>(\n tableName: TableName,\n callbacks?: UseQueryCallbacks<RowType>\n): Snapshot<RowType>;\n\nexport function useTable<\n DbConnection extends DbConnectionImpl,\n RowType extends Record<string, any>,\n TableName extends keyof DbConnection['db'] &\n string = keyof DbConnection['db'] & string,\n>(\n tableName: TableName,\n whereClauseOrCallbacks?:\n | Expr<ColumnsFromRow<RowType>>\n | UseQueryCallbacks<RowType>,\n callbacks?: UseQueryCallbacks<RowType>\n): Snapshot<RowType> {\n let whereClause: Expr<ColumnsFromRow<RowType>> | undefined;\n if (\n whereClauseOrCallbacks &&\n typeof whereClauseOrCallbacks === 'object' &&\n 'type' in whereClauseOrCallbacks\n ) {\n whereClause = whereClauseOrCallbacks as Expr<ColumnsFromRow<RowType>>;\n } else {\n callbacks = whereClauseOrCallbacks as\n | UseQueryCallbacks<RowType>\n | undefined;\n }\n const [subscribeApplied, setSubscribeApplied] = useState(false);\n const [isActive, setIsActive] = useState(false);\n let spacetime: DbConnection | undefined;\n try {\n spacetime = useSpacetimeDB<DbConnection>();\n } catch {\n throw new Error(\n 'Could not find SpacetimeDB client! Did you forget to add a ' +\n '`SpacetimeDBProvider`? `useTable` must be used in the React component tree ' +\n 'under a `SpacetimeDBProvider` component.'\n );\n }\n const client = spacetime;\n\n const query =\n `SELECT * FROM ${tableName}` +\n (whereClause ? ` WHERE ${toString(whereClause)}` : '');\n\n const latestTransactionEvent = useRef<any>(null);\n const lastSnapshotRef = useRef<Snapshot<RowType> | null>(null);\n\n const whereKey = whereClause ? toString(whereClause) : '';\n\n const computeSnapshot = useCallback((): Snapshot<RowType> => {\n const table = client.db[\n tableName as keyof typeof client.db\n ] as unknown as TableCache<RowType>;\n const result: readonly RowType[] = whereClause\n ? table.iter().filter(row => evaluate(whereClause, row))\n : table.iter();\n return {\n rows: result,\n state: subscribeApplied ? 'ready' : 'loading',\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, tableName, whereKey, subscribeApplied]);\n\n useEffect(() => {\n const onConnect = () => {\n setIsActive(client.isActive);\n };\n const onDisconnect = () => {\n setIsActive(client.isActive);\n };\n const onConnectError = () => {\n setIsActive(client.isActive);\n };\n client['on']('connect', onConnect);\n client['on']('disconnect', onDisconnect);\n client['on']('connectError', onConnectError);\n return () => {\n client['off']('connect', onConnect);\n client['off']('disconnect', onDisconnect);\n client['off']('connectError', onConnectError);\n };\n }, [client]);\n\n useEffect(() => {\n if (isActive) {\n const cancel = client\n .subscriptionBuilder()\n .onApplied(() => {\n setSubscribeApplied(true);\n })\n .subscribe(query);\n return () => {\n cancel.unsubscribe();\n };\n }\n }, [query, isActive, client]);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const onInsert = (ctx: any, row: RowType) => {\n if (whereClause && !evaluate(whereClause, row)) {\n return;\n }\n if (tableName === 'message') {\n console.log('onInsert for messages table:', row);\n }\n callbacks?.onInsert?.(row);\n if (\n ctx.event !== latestTransactionEvent.current ||\n !latestTransactionEvent.current\n ) {\n latestTransactionEvent.current = ctx.event;\n lastSnapshotRef.current = computeSnapshot();\n onStoreChange();\n }\n };\n\n const onDelete = (ctx: any, row: RowType) => {\n if (whereClause && !evaluate(whereClause, row)) {\n return;\n }\n if (tableName === 'message') {\n console.log('onDelete for messages table:', row);\n }\n callbacks?.onDelete?.(row);\n if (\n ctx.event !== latestTransactionEvent.current ||\n !latestTransactionEvent.current\n ) {\n latestTransactionEvent.current = ctx.event;\n lastSnapshotRef.current = computeSnapshot();\n onStoreChange();\n }\n };\n\n const onUpdate = (ctx: any, oldRow: RowType, newRow: RowType) => {\n const change = classifyMembership(whereClause, oldRow, newRow);\n\n switch (change) {\n case 'leave':\n callbacks?.onDelete?.(oldRow);\n break;\n case 'enter':\n callbacks?.onInsert?.(newRow);\n break;\n case 'stayIn':\n callbacks?.onUpdate?.(oldRow, newRow);\n break;\n case 'stayOut':\n return; // no-op\n }\n\n if (\n ctx.event !== latestTransactionEvent.current ||\n !latestTransactionEvent.current\n ) {\n latestTransactionEvent.current = ctx.event;\n lastSnapshotRef.current = computeSnapshot();\n onStoreChange();\n }\n };\n\n const table = client.db[\n tableName as keyof typeof client.db\n ] as unknown as TableCache<RowType>;\n table.onInsert(onInsert);\n table.onDelete(onDelete);\n table.onUpdate?.(onUpdate);\n\n return () => {\n table.removeOnInsert(onInsert);\n table.removeOnDelete(onDelete);\n table.removeOnUpdate?.(onUpdate);\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n client,\n tableName,\n whereKey,\n callbacks?.onDelete,\n callbacks?.onInsert,\n callbacks?.onUpdate,\n ]\n );\n\n const getSnapshot = useCallback((): Snapshot<RowType> => {\n if (!lastSnapshotRef.current) {\n lastSnapshotRef.current = computeSnapshot();\n }\n return lastSnapshotRef.current;\n }, [computeSnapshot]);\n\n // SSR fallback can be the same getter\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fromByteArray as e}from"base64-js";var t=class e{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;static getAlgebraicType(){return T.Product({elements:[{name:"__time_duration_micros__",algebraicType:T.I64}]})}get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/e.MICROS_PER_MILLIS)}constructor(e){this.__time_duration_micros__=e}static fromMillis(t){return new e(BigInt(t)*e.MICROS_PER_MILLIS)}},r=class e{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(e){this.__timestamp_micros_since_unix_epoch__=e}static getAlgebraicType(){return T.Product({elements:[{name:"__timestamp_micros_since_unix_epoch__",algebraicType:T.I64}]})}static UNIX_EPOCH=new e(0n);static now(){return e.fromDate(new Date)}static fromDate(t){const r=t.getTime(),i=BigInt(r)*e.MICROS_PER_MILLIS;return new e(i)}toDate(){const t=this.__timestamp_micros_since_unix_epoch__/e.MICROS_PER_MILLIS;if(t>BigInt(Number.MAX_SAFE_INTEGER)||t<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError("Timestamp is outside of the representable range of JS's Date");return new Date(Number(t))}},i=class{#e;#t;#r=0;constructor(e){this.#e=new Uint8Array(e),this.#t=new DataView(this.#e.buffer)}#i(e){const t=this.#r+e+1;if(t<=this.#e.length)return;let r=2*this.#e.length;r<t&&(r=t);const i=new Uint8Array(r);i.set(this.#e),this.#e=i,this.#t=new DataView(this.#e.buffer)}toBase64(){return e(this.#e.subarray(0,this.#r))}getBuffer(){return this.#e.slice(0,this.#r)}writeUInt8Array(e){const t=e.length;this.#i(4+t),this.writeU32(t),this.#e.set(e,this.#r),this.#r+=e.length}writeBool(e){this.#i(1),this.#t.setUint8(this.#r,e?1:0),this.#r+=1}writeByte(e){this.#i(1),this.#t.setUint8(this.#r,e),this.#r+=1}writeI8(e){this.#i(1),this.#t.setInt8(this.#r,e),this.#r+=1}writeU8(e){this.#i(1),this.#t.setUint8(this.#r,e),this.#r+=1}writeI16(e){this.#i(2),this.#t.setInt16(this.#r,e,!0),this.#r+=2}writeU16(e){this.#i(2),this.#t.setUint16(this.#r,e,!0),this.#r+=2}writeI32(e){this.#i(4),this.#t.setInt32(this.#r,e,!0),this.#r+=4}writeU32(e){this.#i(4),this.#t.setUint32(this.#r,e,!0),this.#r+=4}writeI64(e){this.#i(8),this.#t.setBigInt64(this.#r,e,!0),this.#r+=8}writeU64(e){this.#i(8),this.#t.setBigUint64(this.#r,e,!0),this.#r+=8}writeU128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#t.setBigUint64(this.#r,t,!0),this.#t.setBigUint64(this.#r+8,r,!0),this.#r+=16}writeI128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#t.setBigInt64(this.#r,t,!0),this.#t.setBigInt64(this.#r+8,r,!0),this.#r+=16}writeU256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,a=e>>BigInt(128)&t,s=e>>BigInt(192);this.#t.setBigUint64(this.#r+0,r,!0),this.#t.setBigUint64(this.#r+8,i,!0),this.#t.setBigUint64(this.#r+16,a,!0),this.#t.setBigUint64(this.#r+24,s,!0),this.#r+=32}writeI256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,a=e>>BigInt(128)&t,s=e>>BigInt(192);this.#t.setBigUint64(this.#r+0,r,!0),this.#t.setBigUint64(this.#r+8,i,!0),this.#t.setBigUint64(this.#r+16,a,!0),this.#t.setBigInt64(this.#r+24,s,!0),this.#r+=32}writeF32(e){this.#i(4),this.#t.setFloat32(this.#r,e,!0),this.#r+=4}writeF64(e){this.#i(8),this.#t.setFloat64(this.#r,e,!0),this.#r+=8}writeString(e){const t=(new TextEncoder).encode(e);this.writeU32(t.length),this.#i(t.length),this.#e.set(t,this.#r),this.#r+=t.length}},a=class{#e;#r=0;constructor(e){this.#e=new DataView(e.buffer),this.#r=e.byteOffset}get offset(){return this.#r}readUInt8Array(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#r,e);return this.#r+=e,t}readBool(){const e=this.#e.getUint8(this.#r);return this.#r+=1,0!==e}readByte(){const e=this.#e.getUint8(this.#r);return this.#r+=1,e}readBytes(e){const t=new DataView(this.#e.buffer,this.#r,e);return this.#r+=e,new Uint8Array(t.buffer)}readI8(){const e=this.#e.getInt8(this.#r);return this.#r+=1,e}readU8(){const e=this.#e.getUint8(this.#r);return this.#r+=1,e}readI16(){const e=this.#e.getInt16(this.#r,!0);return this.#r+=2,e}readU16(){const e=this.#e.getUint16(this.#r,!0);return this.#r+=2,e}readI32(){const e=this.#e.getInt32(this.#r,!0);return this.#r+=4,e}readU32(){const e=this.#e.getUint32(this.#r,!0);return this.#r+=4,e}readI64(){const e=this.#e.getBigInt64(this.#r,!0);return this.#r+=8,e}readU64(){const e=this.#e.getBigUint64(this.#r,!0);return this.#r+=8,e}readU128(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigUint64(this.#r+8,!0);return this.#r+=16,(t<<BigInt(64))+e}readI128(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigInt64(this.#r+8,!0);return this.#r+=16,(t<<BigInt(64))+e}readU256(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigUint64(this.#r+8,!0),r=this.#e.getBigUint64(this.#r+16,!0),i=this.#e.getBigUint64(this.#r+24,!0);return this.#r+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readI256(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigUint64(this.#r+8,!0),r=this.#e.getBigUint64(this.#r+16,!0),i=this.#e.getBigInt64(this.#r+24,!0);return this.#r+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readF32(){const e=this.#e.getFloat32(this.#r,!0);return this.#r+=4,e}readF64(){const e=this.#e.getFloat64(this.#r,!0);return this.#r+=8,e}readString(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#r,e),r=new TextDecoder("utf-8").decode(t);return this.#r+=e,r}};function s(e){return Array.prototype.map.call(e.reverse(),e=>("00"+e.toString(16)).slice(-2)).join("")}function n(e){e.startsWith("0x")&&(e=e.slice(2));const t=e.match(/.{1,2}/g)||[];return Uint8Array.from(t.map(e=>parseInt(e,16))).reverse()}function c(e){return function(e){if(16!=e.length)throw new Error(`Uint8Array is not 16 bytes long: ${e}`);return new a(e).readU128()}(n(e))}function o(e){return function(e){if(32!=e.length)throw new Error(`Uint8Array is not 32 bytes long: [${e}]`);return new a(e).readU256()}(n(e))}function l(e){const t=new i(16);return t.writeU128(e),t.getBuffer()}function p(e){const t=new i(32);return t.writeU256(e),t.getBuffer()}var u=class e{__identity__;constructor(e){this.__identity__="string"==typeof e?o(e):e}static getAlgebraicType(){return T.Product({elements:[{name:"__identity__",algebraicType:T.U256}]})}isEqual(e){return this.toHexString()===e.toHexString()}toHexString(){return s(p(this.__identity__))}toUint8Array(){return p(this.__identity__)}static fromString(t){return new e(t)}static zero(){return new e(0n)}},g={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"name",algebraicType:T.createOptionType(T.String)},{name:"algebraicType",algebraicType:h.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,g.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,g.getTypeScriptAlgebraicType())},d={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"variants",algebraicType:T.Array(g.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,d.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,d.getTypeScriptAlgebraicType())},y={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"name",algebraicType:T.createOptionType(T.String)},{name:"algebraicType",algebraicType:h.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,y.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,y.getTypeScriptAlgebraicType())},b={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"elements",algebraicType:T.Array(y.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,b.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,b.getTypeScriptAlgebraicType())},h={Ref:e=>({tag:"Ref",value:e}),Sum:e=>({tag:"Sum",value:e}),Product:e=>({tag:"Product",value:e}),Array:e=>({tag:"Array",value:e}),String:{tag:"String"},Bool:{tag:"Bool"},I8:{tag:"I8"},U8:{tag:"U8"},I16:{tag:"I16"},U16:{tag:"U16"},I32:{tag:"I32"},U32:{tag:"U32"},I64:{tag:"I64"},U64:{tag:"U64"},I128:{tag:"I128"},U128:{tag:"U128"},I256:{tag:"I256"},U256:{tag:"U256"},F32:{tag:"F32"},F64:{tag:"F64"},getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"Ref",algebraicType:T.U32},{name:"Sum",algebraicType:d.getTypeScriptAlgebraicType()},{name:"Product",algebraicType:b.getTypeScriptAlgebraicType()},{name:"Array",algebraicType:h.getTypeScriptAlgebraicType()},{name:"String",algebraicType:T.Product({elements:[]})},{name:"Bool",algebraicType:T.Product({elements:[]})},{name:"I8",algebraicType:T.Product({elements:[]})},{name:"U8",algebraicType:T.Product({elements:[]})},{name:"I16",algebraicType:T.Product({elements:[]})},{name:"U16",algebraicType:T.Product({elements:[]})},{name:"I32",algebraicType:T.Product({elements:[]})},{name:"U32",algebraicType:T.Product({elements:[]})},{name:"I64",algebraicType:T.Product({elements:[]})},{name:"U64",algebraicType:T.Product({elements:[]})},{name:"I128",algebraicType:T.Product({elements:[]})},{name:"U128",algebraicType:T.Product({elements:[]})},{name:"I256",algebraicType:T.Product({elements:[]})},{name:"U256",algebraicType:T.Product({elements:[]})},{name:"F32",algebraicType:T.Product({elements:[]})},{name:"F64",algebraicType:T.Product({elements:[]})}]}),serialize(e,t){T.serializeValue(e,h.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,h.getTypeScriptAlgebraicType())},f={getAlgebraicType:()=>T.Sum({variants:[{name:"Interval",algebraicType:T.createTimeDurationType()},{name:"Time",algebraicType:T.createTimestampType()}]})},T={...h,createOptionType:function(e){return h.Sum({variants:[{name:"some",algebraicType:e},{name:"none",algebraicType:h.Product({elements:[]})}]})},createIdentityType:function(){return u.getAlgebraicType()},createConnectionIdType:function(){return w.getAlgebraicType()},createScheduleAtType:function(){return f.getAlgebraicType()},createTimestampType:function(){return r.getAlgebraicType()},createTimeDurationType:function(){return t.getAlgebraicType()},serializeValue:function(e,t,r){switch(t.tag){case"Product":m.serializeValue(e,t.value,r);break;case"Sum":S.serializeValue(e,t.value,r);break;case"Array":if("U8"===t.value.tag)e.writeUInt8Array(r);else{const i=t.value;e.writeU32(r.length);for(const t of r)T.serializeValue(e,i,t)}break;case"Bool":e.writeBool(r);break;case"I8":e.writeI8(r);break;case"U8":e.writeU8(r);break;case"I16":e.writeI16(r);break;case"U16":e.writeU16(r);break;case"I32":e.writeI32(r);break;case"U32":e.writeU32(r);break;case"I64":e.writeI64(r);break;case"U64":e.writeU64(r);break;case"I128":e.writeI128(r);break;case"U128":e.writeU128(r);break;case"I256":e.writeI256(r);break;case"U256":e.writeU256(r);break;case"F32":e.writeF32(r);break;case"F64":e.writeF64(r);break;case"String":e.writeString(r);break;default:throw new Error(`not implemented, ${t.tag}`)}},deserializeValue:function(e,t){switch(t.tag){case"Product":return m.deserializeValue(e,t.value);case"Sum":return S.deserializeValue(e,t.value);case"Array":if("U8"===t.value.tag)return e.readUInt8Array();{const r=t.value,i=e.readU32(),a=[];for(let t=0;t<i;t++)a.push(T.deserializeValue(e,r));return a}case"Bool":return e.readBool();case"I8":return e.readI8();case"U8":return e.readU8();case"I16":return e.readI16();case"U16":return e.readU16();case"I32":return e.readI32();case"U32":return e.readU32();case"I64":return e.readI64();case"U64":return e.readU64();case"I128":return e.readI128();case"U128":return e.readU128();case"I256":return e.readI256();case"U256":return e.readU256();case"F32":return e.readF32();case"F64":return e.readF64();case"String":return e.readString();default:throw new Error(`not implemented, ${t.tag}`)}},intoMapKey:function(e,t){switch(e.tag){case"U8":case"U16":case"U32":case"U64":case"U128":case"U256":case"I8":case"I16":case"I64":case"I128":case"F32":case"F64":case"String":case"Bool":return t;case"Product":return m.intoMapKey(e.value,t);default:{const e=new i(10);return this.serialize(e,t),e.toBase64()}}}},m={...b,serializeValue(e,t,r){for(const i of t.elements)T.serializeValue(e,i.algebraicType,r[i.name])},deserializeValue(e,i){const a={};if(1===i.elements.length){if("__time_duration_micros__"===i.elements[0].name)return new t(e.readI64());if("__timestamp_micros_since_unix_epoch__"===i.elements[0].name)return new r(e.readI64());if("__identity__"===i.elements[0].name)return new u(e.readU256());if("__connection_id__"===i.elements[0].name)return new w(e.readU128())}for(const t of i.elements)a[t.name]=T.deserializeValue(e,t.algebraicType);return a},intoMapKey(e,t){if(1===e.elements.length){if("__time_duration_micros__"===e.elements[0].name)return t.__time_duration_micros__;if("__timestamp_micros_since_unix_epoch__"===e.elements[0].name)return t.__timestamp_micros_since_unix_epoch__;if("__identity__"===e.elements[0].name)return t.__identity__;if("__connection_id__"===e.elements[0].name)return t.__connection_id__}const r=new i(10);return T.serializeValue(r,T.Product(e),t),r.toBase64()}},S={...d,serializeValue:function(e,t,r){if(2==t.variants.length&&"some"===t.variants[0].name&&"none"===t.variants[1].name)null!=r?(e.writeByte(0),T.serializeValue(e,t.variants[0].algebraicType,r)):e.writeByte(1);else{const i=r.tag,a=t.variants.findIndex(e=>e.name===i);if(a<0)throw`Can't serialize a sum type, couldn't find ${r.tag} tag`;e.writeU8(a),T.serializeValue(e,t.variants[a].algebraicType,r.value)}},deserializeValue:function(e,t){const r=e.readU8();if(2==t.variants.length&&"some"===t.variants[0].name&&"none"===t.variants[1].name){if(0===r)return T.deserializeValue(e,t.variants[0].algebraicType);if(1===r)return;throw`Can't deserialize an option type, couldn't find ${r} tag`}{const i=t.variants[r],a=T.deserializeValue(e,i.algebraicType);return{tag:i.name,value:a}}}},w=class e{__connection_id__;constructor(e){this.__connection_id__=e}static getAlgebraicType(){return T.Product({elements:[{name:"__connection_id__",algebraicType:T.U128}]})}isZero(){return this.__connection_id__===BigInt(0)}static nullIfZero(e){return e.isZero()?null:e}static random(){function t(){return Math.floor(255*Math.random())}let r=BigInt(0);for(let e=0;e<16;e++)r=r<<BigInt(8)|BigInt(t());return new e(r)}isEqual(e){return this.__connection_id__==e.__connection_id__}toHexString(){return s(l(this.__connection_id__))}toUint8Array(){return l(this.__connection_id__)}static fromString(t){return new e(c(t))}static fromStringOrNull(t){const r=e.fromString(t);return r.isZero()?null:r}};var I={FixedSize:e=>({tag:"FixedSize",value:e}),RowOffsets:e=>({tag:"RowOffsets",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"FixedSize",algebraicType:T.U16},{name:"RowOffsets",algebraicType:T.Array(T.U64)}]}),serialize(e,t){T.serializeValue(e,I.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,I.getTypeScriptAlgebraicType())},A={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"sizeHint",algebraicType:I.getTypeScriptAlgebraicType()},{name:"rowsData",algebraicType:T.Array(T.U8)}]}),serialize(e,t){T.serializeValue(e,A.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,A.getTypeScriptAlgebraicType())},U={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"reducer",algebraicType:T.String},{name:"args",algebraicType:T.Array(T.U8)},{name:"requestId",algebraicType:T.U32},{name:"flags",algebraicType:T.U8}]}),serialize(e,t){T.serializeValue(e,U.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,U.getTypeScriptAlgebraicType())},_={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"queryStrings",algebraicType:T.Array(T.String)},{name:"requestId",algebraicType:T.U32}]}),serialize(e,t){T.serializeValue(e,_.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,_.getTypeScriptAlgebraicType())},z={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"messageId",algebraicType:T.Array(T.U8)},{name:"queryString",algebraicType:T.String}]}),serialize(e,t){T.serializeValue(e,z.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,z.getTypeScriptAlgebraicType())},v={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"id",algebraicType:T.U32}]}),serialize(e,t){T.serializeValue(e,v.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,v.getTypeScriptAlgebraicType())},F={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"query",algebraicType:T.String},{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,F.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,F.getTypeScriptAlgebraicType())},B={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"queryStrings",algebraicType:T.Array(T.String)},{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,B.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,B.getTypeScriptAlgebraicType())},M={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,M.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,M.getTypeScriptAlgebraicType())},V={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,V.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,V.getTypeScriptAlgebraicType())},P={CallReducer:e=>({tag:"CallReducer",value:e}),Subscribe:e=>({tag:"Subscribe",value:e}),OneOffQuery:e=>({tag:"OneOffQuery",value:e}),SubscribeSingle:e=>({tag:"SubscribeSingle",value:e}),SubscribeMulti:e=>({tag:"SubscribeMulti",value:e}),Unsubscribe:e=>({tag:"Unsubscribe",value:e}),UnsubscribeMulti:e=>({tag:"UnsubscribeMulti",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"CallReducer",algebraicType:U.getTypeScriptAlgebraicType()},{name:"Subscribe",algebraicType:_.getTypeScriptAlgebraicType()},{name:"OneOffQuery",algebraicType:z.getTypeScriptAlgebraicType()},{name:"SubscribeSingle",algebraicType:F.getTypeScriptAlgebraicType()},{name:"SubscribeMulti",algebraicType:B.getTypeScriptAlgebraicType()},{name:"Unsubscribe",algebraicType:M.getTypeScriptAlgebraicType()},{name:"UnsubscribeMulti",algebraicType:V.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,P.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,P.getTypeScriptAlgebraicType())},x={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"deletes",algebraicType:A.getTypeScriptAlgebraicType()},{name:"inserts",algebraicType:A.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,x.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,x.getTypeScriptAlgebraicType())},O={Uncompressed:e=>({tag:"Uncompressed",value:e}),Brotli:e=>({tag:"Brotli",value:e}),Gzip:e=>({tag:"Gzip",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"Uncompressed",algebraicType:x.getTypeScriptAlgebraicType()},{name:"Brotli",algebraicType:T.Array(T.U8)},{name:"Gzip",algebraicType:T.Array(T.U8)}]}),serialize(e,t){T.serializeValue(e,O.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,O.getTypeScriptAlgebraicType())},E={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tableId",algebraicType:T.U32},{name:"tableName",algebraicType:T.String},{name:"numRows",algebraicType:T.U64},{name:"updates",algebraicType:T.Array(O.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,E.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,E.getTypeScriptAlgebraicType())},C={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tables",algebraicType:T.Array(E.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,C.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,C.getTypeScriptAlgebraicType())},k={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"databaseUpdate",algebraicType:C.getTypeScriptAlgebraicType()},{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDuration",algebraicType:T.createTimeDurationType()}]}),serialize(e,t){T.serializeValue(e,k.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,k.getTypeScriptAlgebraicType())},q={Committed:e=>({tag:"Committed",value:e}),Failed:e=>({tag:"Failed",value:e}),OutOfEnergy:{tag:"OutOfEnergy"},getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"Committed",algebraicType:C.getTypeScriptAlgebraicType()},{name:"Failed",algebraicType:T.String},{name:"OutOfEnergy",algebraicType:T.Product({elements:[]})}]}),serialize(e,t){T.serializeValue(e,q.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,q.getTypeScriptAlgebraicType())},R={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"reducerName",algebraicType:T.String},{name:"reducerId",algebraicType:T.U32},{name:"args",algebraicType:T.Array(T.U8)},{name:"requestId",algebraicType:T.U32}]}),serialize(e,t){T.serializeValue(e,R.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,R.getTypeScriptAlgebraicType())},D={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"quanta",algebraicType:T.U128}]}),serialize(e,t){T.serializeValue(e,D.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,D.getTypeScriptAlgebraicType())},N={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"status",algebraicType:q.getTypeScriptAlgebraicType()},{name:"timestamp",algebraicType:T.createTimestampType()},{name:"callerIdentity",algebraicType:T.createIdentityType()},{name:"callerConnectionId",algebraicType:T.createConnectionIdType()},{name:"reducerCall",algebraicType:R.getTypeScriptAlgebraicType()},{name:"energyQuantaUsed",algebraicType:D.getTypeScriptAlgebraicType()},{name:"totalHostExecutionDuration",algebraicType:T.createTimeDurationType()}]}),serialize(e,t){T.serializeValue(e,N.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,N.getTypeScriptAlgebraicType())},$={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"update",algebraicType:C.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,$.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,$.getTypeScriptAlgebraicType())},L={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"identity",algebraicType:T.createIdentityType()},{name:"token",algebraicType:T.String},{name:"connectionId",algebraicType:T.createConnectionIdType()}]}),serialize(e,t){T.serializeValue(e,L.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,L.getTypeScriptAlgebraicType())},H={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tableName",algebraicType:T.String},{name:"rows",algebraicType:A.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,H.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,H.getTypeScriptAlgebraicType())},Q={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"messageId",algebraicType:T.Array(T.U8)},{name:"error",algebraicType:T.createOptionType(T.String)},{name:"tables",algebraicType:T.Array(H.getTypeScriptAlgebraicType())},{name:"totalHostExecutionDuration",algebraicType:T.createTimeDurationType()}]}),serialize(e,t){T.serializeValue(e,Q.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,Q.getTypeScriptAlgebraicType())},j={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tableId",algebraicType:T.U32},{name:"tableName",algebraicType:T.String},{name:"tableRows",algebraicType:E.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,j.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,j.getTypeScriptAlgebraicType())},W={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"rows",algebraicType:j.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,W.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,W.getTypeScriptAlgebraicType())},Z={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"rows",algebraicType:j.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,Z.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,Z.getTypeScriptAlgebraicType())},G={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"requestId",algebraicType:T.createOptionType(T.U32)},{name:"queryId",algebraicType:T.createOptionType(T.U32)},{name:"tableId",algebraicType:T.createOptionType(T.U32)},{name:"error",algebraicType:T.String}]}),serialize(e,t){T.serializeValue(e,G.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,G.getTypeScriptAlgebraicType())},K={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"update",algebraicType:C.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,K.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,K.getTypeScriptAlgebraicType())},X={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"update",algebraicType:C.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,X.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,X.getTypeScriptAlgebraicType())},J={InitialSubscription:e=>({tag:"InitialSubscription",value:e}),TransactionUpdate:e=>({tag:"TransactionUpdate",value:e}),TransactionUpdateLight:e=>({tag:"TransactionUpdateLight",value:e}),IdentityToken:e=>({tag:"IdentityToken",value:e}),OneOffQueryResponse:e=>({tag:"OneOffQueryResponse",value:e}),SubscribeApplied:e=>({tag:"SubscribeApplied",value:e}),UnsubscribeApplied:e=>({tag:"UnsubscribeApplied",value:e}),SubscriptionError:e=>({tag:"SubscriptionError",value:e}),SubscribeMultiApplied:e=>({tag:"SubscribeMultiApplied",value:e}),UnsubscribeMultiApplied:e=>({tag:"UnsubscribeMultiApplied",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"InitialSubscription",algebraicType:k.getTypeScriptAlgebraicType()},{name:"TransactionUpdate",algebraicType:N.getTypeScriptAlgebraicType()},{name:"TransactionUpdateLight",algebraicType:$.getTypeScriptAlgebraicType()},{name:"IdentityToken",algebraicType:L.getTypeScriptAlgebraicType()},{name:"OneOffQueryResponse",algebraicType:Q.getTypeScriptAlgebraicType()},{name:"SubscribeApplied",algebraicType:W.getTypeScriptAlgebraicType()},{name:"UnsubscribeApplied",algebraicType:Z.getTypeScriptAlgebraicType()},{name:"SubscriptionError",algebraicType:G.getTypeScriptAlgebraicType()},{name:"SubscribeMultiApplied",algebraicType:K.getTypeScriptAlgebraicType()},{name:"UnsubscribeMultiApplied",algebraicType:X.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,J.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,J.getTypeScriptAlgebraicType())},Y=class{#a=new Map;on(e,t){let r=this.#a.get(e);r||(r=new Set,this.#a.set(e,r)),r.add(t)}off(e,t){const r=this.#a.get(e);r&&r.delete(t)}emit(e,...t){const r=this.#a.get(e);if(r)for(const e of r)e(...t)}},ee={component:"đĻ",info:"âšī¸",warn:"â ī¸",error:"â",debug:"đ"},te={component:"color: #fff; background-color: #8D6FDD; padding: 2px 5px; border-radius: 3px;",info:"color: #fff; background-color: #007bff; padding: 2px 5px; border-radius: 3px;",warn:"color: #fff; background-color: #ffc107; padding: 2px 5px; border-radius: 3px;",error:"color: #fff; background-color: #dc3545; padding: 2px 5px; border-radius: 3px;",debug:"color: #fff; background-color: #28a745; padding: 2px 5px; border-radius: 3px;"},re={component:"color: #8D6FDD;",info:"color: #007bff;",warn:"color: #ffc107;",error:"color: #dc3545;",debug:"color: #28a745;"},ie=(e,t)=>{console.log(`%c${ee[e]} ${e.toUpperCase()}%c ${t}`,te[e],re[e])},ae=class{rows;tableTypeInfo;emitter;constructor(e){this.tableTypeInfo=e,this.rows=new Map,this.emitter=new Y}count(){return this.rows.size}iter(){return Array.from(this.rows.values()).map(([e])=>e)}applyOperations=(e,t)=>{const r=[];if(void 0!==this.tableTypeInfo.primaryKeyInfo){const i=new Map,a=new Map;for(const t of e)if("insert"===t.type){const[e,r]=i.get(t.rowId)||[t,0];i.set(t.rowId,[t,r+1])}else{const[e,r]=a.get(t.rowId)||[t,0];a.set(t.rowId,[t,r+1])}for(const[e,[s,n]]of i){const i=a.get(e);if(i){const[c,o]=i,l=n-o,p=this.update(t,e,s.row,l);p&&r.push(p),a.delete(e)}else{const e=this.insert(t,s,n);e&&r.push(e)}}for(const[e,i]of a.values()){const a=this.delete(t,e,i);a&&r.push(a)}}else for(const i of e)if("insert"===i.type){const e=this.insert(t,i);e&&r.push(e)}else{const e=this.delete(t,i);e&&r.push(e)}return r};update=(e,t,r,i=0)=>{const a=this.rows.get(t);if(!a)return void ie("error",`Updating a row that was not present in the cache. Table: ${this.tableTypeInfo.tableName}, RowId: ${t}`);const[s,n]=a,c=Math.max(1,n+i);if(!(n+i<=0))return this.rows.set(t,[r,c]),0===n?(ie("error",`Updating a row id in table ${this.tableTypeInfo.tableName} which was not present in the cache (rowId: ${t})`),{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,r)}}):{type:"update",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("update",e,s,r)}};ie("error",`Negative reference count for in table ${this.tableTypeInfo.tableName} row ${t} (${n} + ${i})`)};insert=(e,t,r=1)=>{const[i,a]=this.rows.get(t.rowId)||[t.row,0];if(this.rows.set(t.rowId,[t.row,a+r]),0===a)return{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}};delete=(e,t,r=1)=>{const[i,a]=this.rows.get(t.rowId)||[t.row,0];if(0!==a)return a<=r?(this.rows.delete(t.rowId),{type:"delete",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("delete",e,t.row)}}):void this.rows.set(t.rowId,[t.row,a-r]);ie("warn","Deleting a row that was not present in the cache")};onInsert=e=>{this.emitter.on("insert",e)};onDelete=e=>{this.emitter.on("delete",e)};onUpdate=e=>{this.emitter.on("update",e)};removeOnInsert=e=>{this.emitter.off("insert",e)};removeOnDelete=e=>{this.emitter.off("delete",e)};removeOnUpdate=e=>{this.emitter.off("update",e)}},se=class{tables;constructor(){this.tables=new Map}getTable(e){const t=this.tables.get(e);if(!t)throw console.error("The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!"),new Error(`Table ${e} does not exist`);return t}getOrCreateTable(e){let t;return this.tables.has(e.tableName)?t=this.tables.get(e.tableName):(t=new ae(e),this.tables.set(e.tableName,t)),t}};var ne=class e{major;minor;patch;preRelease;buildInfo;constructor(e,t,r,i=null,a=null){this.major=e,this.minor=t,this.patch=r,this.preRelease=i,this.buildInfo=a}toString(){let e=`${this.major}.${this.minor}.${this.patch}`;return this.preRelease&&(e+=`-${this.preRelease.join(".")}`),this.buildInfo&&(e+=`+${this.buildInfo}`),e}compare(e){return this.major!==e.major?this.major-e.major:this.minor!==e.minor?this.minor-e.minor:this.patch!==e.patch?this.patch-e.patch:this.preRelease&&e.preRelease?function(e,t){const r=Math.min(e.length,t.length);for(let i=0;i<r;i++){const r=e[i],a=t[i];if(r!==a)return"number"==typeof r&&"number"==typeof a?r-a:"string"==typeof r&&"string"==typeof a?r.localeCompare(a):"string"==typeof r?1:-1}return e.length-t.length}(this.preRelease,e.preRelease):this.preRelease||e.preRelease?-1:0}clone(){return new e(this.major,this.minor,this.patch,this.preRelease?[...this.preRelease]:null,this.buildInfo)}static parseVersionString(t){const r=t.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/);if(!r)throw new Error(`Invalid version string: ${t}`);const i=parseInt(r[1],10),a=parseInt(r[2],10),s=parseInt(r[3],10),n=r[4]?r[4].split(".").map(e=>isNaN(Number(e))?e:Number(e)):null,c=r[5]||null;return new e(i,a,s,n,c)}},ce=new ne(1,4,0);function oe(e){return`Module code was generated with an incompatible version of the spacetimedb cli (${e}). Update the cli version to at least ${ce.toString()} and regenerate the bindings. You can upgrade to the latest cli version by running: spacetime version upgrade`}async function le(e,t,r=131072){let i=0;const a=new ReadableStream({pull(t){if(i<e.length){const a=e.subarray(i,Math.min(i+r,e.length));t.enqueue(a),i+=r}else t.close()}}),s=new DecompressionStream(t),n=a.pipeThrough(s).getReader(),c=[];let o,l=0;for(;!(o=await n.read()).done;)c.push(o.value),l+=o.value.length;const p=new Uint8Array(l);let u=0;for(const e of c)p.set(e,u),u+=e.length;return p}var pe=class e{onclose;onopen;onmessage;onerror;#s;async#n(e){const t=new Uint8Array(e.data);let r;if(0===t[0])r=t.slice(1);else{if(1===t[0])throw new Error("Brotli Compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");if(2!==t[0])throw new Error("Unexpected Compression Algorithm. Please use `gzip` or `none`");r=await le(t.slice(1),"gzip")}this.onmessage?.({data:r})}#c(e){this.onopen?.(e)}#o(e){this.onerror?.(e)}#l(e){this.onclose?.(e)}send(e){this.#s.send(e)}close(){this.#s.close()}constructor(e){this.onmessage=void 0,this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,e.onmessage=this.#n.bind(this),e.onerror=this.#o.bind(this),e.onclose=this.#l.bind(this),e.onopen=this.#c.bind(this),e.binaryType="arraybuffer",this.#s=e}static async createWebSocketFn({url:t,nameOrAddress:r,wsProtocol:i,authToken:a,compression:s,lightMode:n}){const c=new Headers;let o,l;if(o=WebSocket,a){c.set("Authorization",`Bearer ${a}`);const e=new URL("v1/identity/websocket-token",t);e.protocol="wss:"===t.protocol?"https:":"http:";const r=await fetch(e,{method:"POST",headers:c});if(!r.ok)return Promise.reject(new Error(`Failed to verify token: ${r.statusText}`));{const{token:e}=await r.json();l=e}}const p=new URL(`v1/database/${r}/subscribe`,t);l&&p.searchParams.set("token",l),p.searchParams.set("compression","gzip"===s?"Gzip":"None"),n&&p.searchParams.set("light","true");const u=new o(p.toString(),i);return new e(u)}},ue=class{constructor(e,t){this.remoteModule=e,this.dbConnectionConstructor=t,this.#p=pe.createWebSocketFn}#u;#g;#d;#y;#b=new Y;#h="gzip";#f=!1;#p;withUri(e){return this.#u=new URL(e),this}withModuleName(e){return this.#g=e,this}withToken(e){return this.#y=e,this}withWSFn(e){return this.#p=e,this}withCompression(e){return this.#h=e,this}withLightMode(e){return this.#f=e,this}onConnect(e){return this.#b.on("connect",e),this}onConnectError(e){return this.#b.on("connectError",e),this}onDisconnect(e){return this.#b.on("disconnect",e),this}build(){if(!this.#u)throw new Error("URI is required to connect to SpacetimeDB");if(!this.#g)throw new Error("Database name or address is required to connect to SpacetimeDB");return function(e){if(void 0===e)throw new Error(oe(e));if(ne.parseVersionString(e).compare(ce)<0)throw new Error(oe(e))}(this.remoteModule.versionInfo?.cliVersion),this.dbConnectionConstructor(new he({uri:this.#u,nameOrAddress:this.#g,identity:this.#d,token:this.#y,emitter:this.#b,compression:this.#h,lightMode:this.#f,createWSFn:this.#p,remoteModule:this.remoteModule}))}},ge=class{constructor(e){this.db=e}#T=void 0;#m=void 0;onApplied(e){return this.#T=e,this}onError(e){return this.#m=e,this}subscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("Subscriptions must have at least one query");return new ye(this.db,t,this.#T,this.#m)}subscribeToAllTables(){this.subscribe("SELECT * FROM *")}},de=class{subscriptions=new Map},ye=class{constructor(e,t,r,i){this.db=e,this.#b.on("applied",e=>{this.#S=!0,r&&r(e)}),this.#b.on("error",(e,t)=>{this.#S=!1,this.#w=!0,i&&i(e,t)}),this.#I=this.db.registerSubscription(this,this.#b,t)}#I;#A=!1;#w=!1;#S=!1;#b=new Y;unsubscribe(){if(this.#A)throw new Error("Unsubscribe has already been called");this.#A=!0,this.db.unregisterSubscription(this.#I),this.#b.on("end",e=>{this.#w=!0,this.#S=!1})}unsubscribeThen(e){if(this.#w)throw new Error("Subscription has already ended");if(this.#A)throw new Error("Unsubscribe has already been called");this.#A=!0,this.db.unregisterSubscription(this.#I),this.#b.on("end",t=>{this.#w=!0,this.#S=!1,e(t)})}isEnded(){return this.#w}isActive(){return this.#S}};function be(e){switch(e){case"FullUpdate":return 0;case"NoSuccessNotify":return 1}}var he=class{isActive=!1;identity=void 0;token=void 0;db;reducers;setReducerFlags;connectionId=w.random();#I=0;#b;#U=new Y;#T;#_;#z=Promise.resolve();#v=new de;clientCache;ws;wsPromise;constructor({uri:e,nameOrAddress:t,identity:r,token:i,emitter:a,remoteModule:s,createWSFn:n,compression:c,lightMode:o}){ie("info","Connecting to SpacetimeDB WS...");const l=new URL(e.toString());/^wss?:/.test(e.protocol)||(l.protocol="https:"===l.protocol?"wss:":"ws:"),this.identity=r,this.token=i,this.#_=s,this.#b=a;const p=this.connectionId.toHexString();l.searchParams.set("connection_id",p),this.clientCache=new se,this.db=this.#_.dbViewConstructor(this),this.setReducerFlags=this.#_.setReducerFlagsConstructor(),this.reducers=this.#_.reducersConstructor(this,this.setReducerFlags),this.wsPromise=n({url:l,nameOrAddress:t,wsProtocol:"v1.bsatn.spacetimedb",authToken:i,compression:c,lightMode:o}).then(e=>(this.ws=e,this.ws.onclose=()=>{this.#b.emit("disconnect",this)},this.ws.onerror=e=>{this.#b.emit("connectError",this,e)},this.ws.onopen=this.#c.bind(this),this.ws.onmessage=this.#n.bind(this),e)).catch(e=>{ie("error","Error connecting to SpacetimeDB WS"),this.#b.emit("connectError",this,e)})}#F=()=>{const e=this.#I;return this.#I+=1,e};subscriptionBuilder=()=>new ge(this);registerSubscription(e,t,r){const i=this.#F();return this.#v.subscriptions.set(i,{handle:e,emitter:t}),this.#B(P.SubscribeMulti({queryStrings:r,queryId:{id:i},requestId:0})),i}unregisterSubscription(e){this.#B(P.UnsubscribeMulti({queryId:{id:e},requestId:0}))}async#M(t){const r=(t,r,i)=>{const s=i.rowsData,n=new a(s),c=[],o=this.#_.tables[r].rowType,l=this.#_.tables[r].primaryKeyInfo;for(;n.offset<s.length+s.byteOffset;){const r=n.offset,i=T.deserializeValue(n,o);let a;if(void 0!==l)a=T.intoMapKey(l.colType,i[l.colName]);else{const t=s.subarray(r-s.byteOffset,n.offset-s.byteOffset);a=e(t)}c.push({type:t,rowId:a,row:i})}return c},i=async e=>{const t=e.tableName;let i=[];for(const s of e.updates){let e;if("Gzip"===s.tag){const t=await le(s.value,"gzip");e=x.deserialize(new a(t))}else{if("Brotli"===s.tag)throw new Error("Brotli compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");e=s.value}i=i.concat(r("insert",t,e.inserts)),i=i.concat(r("delete",t,e.deletes))}return{tableName:t,operations:i}},s=async e=>{const t=[];for(const r of e.tables)t.push(await i(r));return t};switch(t.tag){case"InitialSubscription":{const e=t.value.databaseUpdate;return{tag:"InitialSubscription",tableUpdates:await s(e)}}case"TransactionUpdateLight":{const e=t.value.update;return{tag:"TransactionUpdateLight",tableUpdates:await s(e)}}case"TransactionUpdate":{const e=t.value,r=e.callerIdentity,i=w.nullIfZero(e.callerConnectionId),a=e.reducerCall.reducerName,n=e.reducerCall.args,c=e.energyQuantaUsed;let o,l=[],p="";switch(e.status.tag){case"Committed":l=await s(e.status.value);break;case"Failed":l=[],p=e.status.value;break;case"OutOfEnergy":l=[]}if("<none>"===a){const e=p;return void console.error(`Received an error from the database: ${e}`)}""!==a&&(o={reducerName:a,args:n});return{tag:"TransactionUpdate",tableUpdates:l,identity:r,connectionId:i,reducerInfo:o,status:e.status,energyConsumed:c.quanta,message:p,timestamp:e.timestamp}}case"IdentityToken":return{tag:"IdentityToken",identity:t.value.identity,token:t.value.token,connectionId:t.value.connectionId};case"OneOffQueryResponse":throw new Error(`TypeScript SDK never sends one-off queries, but got OneOffQueryResponse ${t}`);case"SubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"SubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"UnsubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"UnsubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"SubscriptionError":return{tag:"SubscriptionError",queryId:t.value.queryId,error:t.value.error}}}#B(e){this.wsPromise.then(t=>{if(t){const r=new i(1024);P.serialize(r,e);const a=r.getBuffer();t.send(a)}})}#c(){this.isActive=!0}#V(e,t){const r=[];for(const i of e){const e=i.tableName,a=this.#_.tables[e],s=this.clientCache.getOrCreateTable(a).applyOperations(i.operations,t);for(const e of s)r.push(e)}return r}async#P(e){const t=function(e,t){const r=new a(t);return e.deserialize(r)}(J,e),r=await this.#M(t);if(r)switch(r.tag){case"InitialSubscription":{const e={tag:"SubscribeApplied"},t=this.#_.eventContextConstructor(this,e),{event:i,...a}=t,s=this.#V(r.tableUpdates,t);this.#b&&this.#T?.(a);for(const e of s)e.cb();break}case"TransactionUpdateLight":{const e={tag:"UnknownTransaction"},t=this.#_.eventContextConstructor(this,e),i=this.#V(r.tableUpdates,t);for(const e of i)e.cb();break}case"TransactionUpdate":{let e,t,i=r.reducerInfo,s=!1;if(i){t=this.#_.reducers[i.reducerName];try{const r=new a(i.args);e=T.deserializeValue(r,t.argsType)}catch{console.debug("Failed to deserialize reducer arguments"),s=!0}}else s=!0;if(s){const e={tag:"UnknownTransaction"},t=this.#_.eventContextConstructor(this,e),i=this.#V(r.tableUpdates,t);for(const e of i)e.cb();return}const n={callerIdentity:r.identity,status:r.status,callerConnectionId:r.connectionId,timestamp:r.timestamp,energyConsumed:r.energyConsumed,reducer:{name:i.reducerName,args:e}},c={tag:"Reducer",value:n},o=this.#_.eventContextConstructor(this,c),l={...o,event:n},p=this.#V(r.tableUpdates,o),u=[];t.argsType.value.elements.forEach(t=>{u.push(e[t.name])}),this.#U.emit(i.reducerName,l,...u);for(const e of p)e.cb();break}case"IdentityToken":this.identity=r.identity,!this.token&&r.token&&(this.token=r.token),this.connectionId=r.connectionId,this.#b.emit("connect",this,this.identity,this.token);break;case"SubscribeApplied":{const e=this.#v.subscriptions.get(r.queryId);if(void 0===e){ie("error",`Received SubscribeApplied for unknown queryId ${r.queryId}.`);break}const t={tag:"SubscribeApplied"},i=this.#_.eventContextConstructor(this,t),{event:a,...s}=i,n=this.#V(r.tableUpdates,i);e?.emitter.emit("applied",s);for(const e of n)e.cb();break}case"UnsubscribeApplied":{const e=this.#v.subscriptions.get(r.queryId);if(void 0===e){ie("error",`Received UnsubscribeApplied for unknown queryId ${r.queryId}.`);break}const t={tag:"UnsubscribeApplied"},i=this.#_.eventContextConstructor(this,t),{event:a,...s}=i,n=this.#V(r.tableUpdates,i);e?.emitter.emit("end",s),this.#v.subscriptions.delete(r.queryId);for(const e of n)e.cb();break}case"SubscriptionError":{const e=Error(r.error),t={tag:"Error",value:e},i={...this.#_.eventContextConstructor(this,t),event:e};void 0!==r.queryId?(this.#v.subscriptions.get(r.queryId)?.emitter.emit("error",i,e),this.#v.subscriptions.delete(r.queryId)):(console.error("Received an error message without a queryId: ",e),this.#v.subscriptions.forEach(({emitter:t})=>{t.emit("error",i,e)}))}}}#n(e){this.#z=this.#z.then(()=>this.#P(e.data))}callReducer(e,t,r){const i=P.CallReducer({reducer:e,args:t,requestId:0,flags:be(r)});this.#B(i)}disconnect(){this.wsPromise.then(e=>{e&&e.close()})}on(e,t){this.#b.on(e,t)}off(e,t){this.#b.off(e,t)}onConnect(e){this.#b.on("connect",e)}onDisconnect(e){this.#b.on("disconnect",e)}onConnectError(e){this.#b.on("connectError",e)}removeOnConnect(e){this.#b.off("connect",e)}removeOnDisconnect(e){this.#b.off("disconnect",e)}removeOnConnectError(e){this.#b.off("connectError",e)}onReducer(e,t){this.#U.on(e,t)}offReducer(e,t){this.#U.off(e,t)}};export{a as BinaryReader,i as BinaryWriter,se as ClientCache,ue as DbConnectionBuilder,he as DbConnectionImpl,ge as SubscriptionBuilderImpl,ae as TableCache};//# sourceMappingURL=index.browser.mjs.map
|
|
1
|
+
import{fromByteArray as e}from"base64-js";var t=class e{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;static getAlgebraicType(){return T.Product({elements:[{name:"__time_duration_micros__",algebraicType:T.I64}]})}get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/e.MICROS_PER_MILLIS)}constructor(e){this.__time_duration_micros__=e}static fromMillis(t){return new e(BigInt(t)*e.MICROS_PER_MILLIS)}},r=class e{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(e){this.__timestamp_micros_since_unix_epoch__=e}static getAlgebraicType(){return T.Product({elements:[{name:"__timestamp_micros_since_unix_epoch__",algebraicType:T.I64}]})}static UNIX_EPOCH=new e(0n);static now(){return e.fromDate(new Date)}static fromDate(t){const r=t.getTime(),i=BigInt(r)*e.MICROS_PER_MILLIS;return new e(i)}toDate(){const t=this.__timestamp_micros_since_unix_epoch__/e.MICROS_PER_MILLIS;if(t>BigInt(Number.MAX_SAFE_INTEGER)||t<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError("Timestamp is outside of the representable range of JS's Date");return new Date(Number(t))}},i=class{#e;#t;#r=0;constructor(e){this.#e=new Uint8Array(e),this.#t=new DataView(this.#e.buffer)}#i(e){const t=this.#r+e+1;if(t<=this.#e.length)return;let r=2*this.#e.length;r<t&&(r=t);const i=new Uint8Array(r);i.set(this.#e),this.#e=i,this.#t=new DataView(this.#e.buffer)}toBase64(){return e(this.#e.subarray(0,this.#r))}getBuffer(){return this.#e.slice(0,this.#r)}writeUInt8Array(e){const t=e.length;this.#i(4+t),this.writeU32(t),this.#e.set(e,this.#r),this.#r+=e.length}writeBool(e){this.#i(1),this.#t.setUint8(this.#r,e?1:0),this.#r+=1}writeByte(e){this.#i(1),this.#t.setUint8(this.#r,e),this.#r+=1}writeI8(e){this.#i(1),this.#t.setInt8(this.#r,e),this.#r+=1}writeU8(e){this.#i(1),this.#t.setUint8(this.#r,e),this.#r+=1}writeI16(e){this.#i(2),this.#t.setInt16(this.#r,e,!0),this.#r+=2}writeU16(e){this.#i(2),this.#t.setUint16(this.#r,e,!0),this.#r+=2}writeI32(e){this.#i(4),this.#t.setInt32(this.#r,e,!0),this.#r+=4}writeU32(e){this.#i(4),this.#t.setUint32(this.#r,e,!0),this.#r+=4}writeI64(e){this.#i(8),this.#t.setBigInt64(this.#r,e,!0),this.#r+=8}writeU64(e){this.#i(8),this.#t.setBigUint64(this.#r,e,!0),this.#r+=8}writeU128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#t.setBigUint64(this.#r,t,!0),this.#t.setBigUint64(this.#r+8,r,!0),this.#r+=16}writeI128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#t.setBigInt64(this.#r,t,!0),this.#t.setBigInt64(this.#r+8,r,!0),this.#r+=16}writeU256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,a=e>>BigInt(128)&t,s=e>>BigInt(192);this.#t.setBigUint64(this.#r+0,r,!0),this.#t.setBigUint64(this.#r+8,i,!0),this.#t.setBigUint64(this.#r+16,a,!0),this.#t.setBigUint64(this.#r+24,s,!0),this.#r+=32}writeI256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,a=e>>BigInt(128)&t,s=e>>BigInt(192);this.#t.setBigUint64(this.#r+0,r,!0),this.#t.setBigUint64(this.#r+8,i,!0),this.#t.setBigUint64(this.#r+16,a,!0),this.#t.setBigInt64(this.#r+24,s,!0),this.#r+=32}writeF32(e){this.#i(4),this.#t.setFloat32(this.#r,e,!0),this.#r+=4}writeF64(e){this.#i(8),this.#t.setFloat64(this.#r,e,!0),this.#r+=8}writeString(e){const t=(new TextEncoder).encode(e);this.writeU32(t.length),this.#i(t.length),this.#e.set(t,this.#r),this.#r+=t.length}},a=class{#e;#r=0;constructor(e){this.#e=new DataView(e.buffer),this.#r=e.byteOffset}get offset(){return this.#r}readUInt8Array(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#r,e);return this.#r+=e,t}readBool(){const e=this.#e.getUint8(this.#r);return this.#r+=1,0!==e}readByte(){const e=this.#e.getUint8(this.#r);return this.#r+=1,e}readBytes(e){const t=new DataView(this.#e.buffer,this.#r,e);return this.#r+=e,new Uint8Array(t.buffer)}readI8(){const e=this.#e.getInt8(this.#r);return this.#r+=1,e}readU8(){const e=this.#e.getUint8(this.#r);return this.#r+=1,e}readI16(){const e=this.#e.getInt16(this.#r,!0);return this.#r+=2,e}readU16(){const e=this.#e.getUint16(this.#r,!0);return this.#r+=2,e}readI32(){const e=this.#e.getInt32(this.#r,!0);return this.#r+=4,e}readU32(){const e=this.#e.getUint32(this.#r,!0);return this.#r+=4,e}readI64(){const e=this.#e.getBigInt64(this.#r,!0);return this.#r+=8,e}readU64(){const e=this.#e.getBigUint64(this.#r,!0);return this.#r+=8,e}readU128(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigUint64(this.#r+8,!0);return this.#r+=16,(t<<BigInt(64))+e}readI128(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigInt64(this.#r+8,!0);return this.#r+=16,(t<<BigInt(64))+e}readU256(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigUint64(this.#r+8,!0),r=this.#e.getBigUint64(this.#r+16,!0),i=this.#e.getBigUint64(this.#r+24,!0);return this.#r+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readI256(){const e=this.#e.getBigUint64(this.#r,!0),t=this.#e.getBigUint64(this.#r+8,!0),r=this.#e.getBigUint64(this.#r+16,!0),i=this.#e.getBigInt64(this.#r+24,!0);return this.#r+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readF32(){const e=this.#e.getFloat32(this.#r,!0);return this.#r+=4,e}readF64(){const e=this.#e.getFloat64(this.#r,!0);return this.#r+=8,e}readString(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#r,e),r=new TextDecoder("utf-8").decode(t);return this.#r+=e,r}};function s(e){return Array.prototype.map.call(e.reverse(),e=>("00"+e.toString(16)).slice(-2)).join("")}function n(e){e.startsWith("0x")&&(e=e.slice(2));const t=e.match(/.{1,2}/g)||[];return Uint8Array.from(t.map(e=>parseInt(e,16))).reverse()}function o(e){return function(e){if(16!=e.length)throw new Error(`Uint8Array is not 16 bytes long: ${e}`);return new a(e).readU128()}(n(e))}function c(e){return function(e){if(32!=e.length)throw new Error(`Uint8Array is not 32 bytes long: [${e}]`);return new a(e).readU256()}(n(e))}function l(e){const t=new i(16);return t.writeU128(e),t.getBuffer()}function p(e){const t=new i(32);return t.writeU256(e),t.getBuffer()}var u=class e{__identity__;constructor(e){this.__identity__="string"==typeof e?c(e):e}static getAlgebraicType(){return T.Product({elements:[{name:"__identity__",algebraicType:T.U256}]})}isEqual(e){return this.toHexString()===e.toHexString()}toHexString(){return s(p(this.__identity__))}toUint8Array(){return p(this.__identity__)}static fromString(t){return new e(t)}static zero(){return new e(0n)}},g={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"name",algebraicType:T.createOptionType(T.String)},{name:"algebraicType",algebraicType:h.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,g.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,g.getTypeScriptAlgebraicType())},d={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"variants",algebraicType:T.Array(g.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,d.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,d.getTypeScriptAlgebraicType())},b={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"name",algebraicType:T.createOptionType(T.String)},{name:"algebraicType",algebraicType:h.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,b.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,b.getTypeScriptAlgebraicType())},y={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"elements",algebraicType:T.Array(b.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,y.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,y.getTypeScriptAlgebraicType())},h={Ref:e=>({tag:"Ref",value:e}),Sum:e=>({tag:"Sum",value:e}),Product:e=>({tag:"Product",value:e}),Array:e=>({tag:"Array",value:e}),String:{tag:"String"},Bool:{tag:"Bool"},I8:{tag:"I8"},U8:{tag:"U8"},I16:{tag:"I16"},U16:{tag:"U16"},I32:{tag:"I32"},U32:{tag:"U32"},I64:{tag:"I64"},U64:{tag:"U64"},I128:{tag:"I128"},U128:{tag:"U128"},I256:{tag:"I256"},U256:{tag:"U256"},F32:{tag:"F32"},F64:{tag:"F64"},getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"Ref",algebraicType:T.U32},{name:"Sum",algebraicType:d.getTypeScriptAlgebraicType()},{name:"Product",algebraicType:y.getTypeScriptAlgebraicType()},{name:"Array",algebraicType:h.getTypeScriptAlgebraicType()},{name:"String",algebraicType:T.Product({elements:[]})},{name:"Bool",algebraicType:T.Product({elements:[]})},{name:"I8",algebraicType:T.Product({elements:[]})},{name:"U8",algebraicType:T.Product({elements:[]})},{name:"I16",algebraicType:T.Product({elements:[]})},{name:"U16",algebraicType:T.Product({elements:[]})},{name:"I32",algebraicType:T.Product({elements:[]})},{name:"U32",algebraicType:T.Product({elements:[]})},{name:"I64",algebraicType:T.Product({elements:[]})},{name:"U64",algebraicType:T.Product({elements:[]})},{name:"I128",algebraicType:T.Product({elements:[]})},{name:"U128",algebraicType:T.Product({elements:[]})},{name:"I256",algebraicType:T.Product({elements:[]})},{name:"U256",algebraicType:T.Product({elements:[]})},{name:"F32",algebraicType:T.Product({elements:[]})},{name:"F64",algebraicType:T.Product({elements:[]})}]}),serialize(e,t){T.serializeValue(e,h.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,h.getTypeScriptAlgebraicType())},f={getAlgebraicType:()=>T.Sum({variants:[{name:"Interval",algebraicType:T.createTimeDurationType()},{name:"Time",algebraicType:T.createTimestampType()}]})},T={...h,createOptionType:function(e){return h.Sum({variants:[{name:"some",algebraicType:e},{name:"none",algebraicType:h.Product({elements:[]})}]})},createIdentityType:function(){return u.getAlgebraicType()},createConnectionIdType:function(){return w.getAlgebraicType()},createScheduleAtType:function(){return f.getAlgebraicType()},createTimestampType:function(){return r.getAlgebraicType()},createTimeDurationType:function(){return t.getAlgebraicType()},serializeValue:function(e,t,r){switch(t.tag){case"Product":m.serializeValue(e,t.value,r);break;case"Sum":S.serializeValue(e,t.value,r);break;case"Array":if("U8"===t.value.tag)e.writeUInt8Array(r);else{const i=t.value;e.writeU32(r.length);for(const t of r)T.serializeValue(e,i,t)}break;case"Bool":e.writeBool(r);break;case"I8":e.writeI8(r);break;case"U8":e.writeU8(r);break;case"I16":e.writeI16(r);break;case"U16":e.writeU16(r);break;case"I32":e.writeI32(r);break;case"U32":e.writeU32(r);break;case"I64":e.writeI64(r);break;case"U64":e.writeU64(r);break;case"I128":e.writeI128(r);break;case"U128":e.writeU128(r);break;case"I256":e.writeI256(r);break;case"U256":e.writeU256(r);break;case"F32":e.writeF32(r);break;case"F64":e.writeF64(r);break;case"String":e.writeString(r);break;default:throw new Error(`not implemented, ${t.tag}`)}},deserializeValue:function(e,t){switch(t.tag){case"Product":return m.deserializeValue(e,t.value);case"Sum":return S.deserializeValue(e,t.value);case"Array":if("U8"===t.value.tag)return e.readUInt8Array();{const r=t.value,i=e.readU32(),a=[];for(let t=0;t<i;t++)a.push(T.deserializeValue(e,r));return a}case"Bool":return e.readBool();case"I8":return e.readI8();case"U8":return e.readU8();case"I16":return e.readI16();case"U16":return e.readU16();case"I32":return e.readI32();case"U32":return e.readU32();case"I64":return e.readI64();case"U64":return e.readU64();case"I128":return e.readI128();case"U128":return e.readU128();case"I256":return e.readI256();case"U256":return e.readU256();case"F32":return e.readF32();case"F64":return e.readF64();case"String":return e.readString();default:throw new Error(`not implemented, ${t.tag}`)}},intoMapKey:function(e,t){switch(e.tag){case"U8":case"U16":case"U32":case"U64":case"U128":case"U256":case"I8":case"I16":case"I64":case"I128":case"F32":case"F64":case"String":case"Bool":return t;case"Product":return m.intoMapKey(e.value,t);default:{const e=new i(10);return this.serialize(e,t),e.toBase64()}}}},m={...y,serializeValue(e,t,r){for(const i of t.elements)T.serializeValue(e,i.algebraicType,r[i.name])},deserializeValue(e,i){const a={};if(1===i.elements.length){if("__time_duration_micros__"===i.elements[0].name)return new t(e.readI64());if("__timestamp_micros_since_unix_epoch__"===i.elements[0].name)return new r(e.readI64());if("__identity__"===i.elements[0].name)return new u(e.readU256());if("__connection_id__"===i.elements[0].name)return new w(e.readU128())}for(const t of i.elements)a[t.name]=T.deserializeValue(e,t.algebraicType);return a},intoMapKey(e,t){if(1===e.elements.length){if("__time_duration_micros__"===e.elements[0].name)return t.__time_duration_micros__;if("__timestamp_micros_since_unix_epoch__"===e.elements[0].name)return t.__timestamp_micros_since_unix_epoch__;if("__identity__"===e.elements[0].name)return t.__identity__;if("__connection_id__"===e.elements[0].name)return t.__connection_id__}const r=new i(10);return T.serializeValue(r,T.Product(e),t),r.toBase64()}},S={...d,serializeValue:function(e,t,r){if(2==t.variants.length&&"some"===t.variants[0].name&&"none"===t.variants[1].name)null!=r?(e.writeByte(0),T.serializeValue(e,t.variants[0].algebraicType,r)):e.writeByte(1);else{const i=r.tag,a=t.variants.findIndex(e=>e.name===i);if(a<0)throw`Can't serialize a sum type, couldn't find ${r.tag} tag`;e.writeU8(a),T.serializeValue(e,t.variants[a].algebraicType,r.value)}},deserializeValue:function(e,t){const r=e.readU8();if(2==t.variants.length&&"some"===t.variants[0].name&&"none"===t.variants[1].name){if(0===r)return T.deserializeValue(e,t.variants[0].algebraicType);if(1===r)return;throw`Can't deserialize an option type, couldn't find ${r} tag`}{const i=t.variants[r],a=T.deserializeValue(e,i.algebraicType);return{tag:i.name,value:a}}}},w=class e{__connection_id__;constructor(e){this.__connection_id__=e}static getAlgebraicType(){return T.Product({elements:[{name:"__connection_id__",algebraicType:T.U128}]})}isZero(){return this.__connection_id__===BigInt(0)}static nullIfZero(e){return e.isZero()?null:e}static random(){function t(){return Math.floor(255*Math.random())}let r=BigInt(0);for(let e=0;e<16;e++)r=r<<BigInt(8)|BigInt(t());return new e(r)}isEqual(e){return this.__connection_id__==e.__connection_id__}toHexString(){return s(l(this.__connection_id__))}toUint8Array(){return l(this.__connection_id__)}static fromString(t){return new e(o(t))}static fromStringOrNull(t){const r=e.fromString(t);return r.isZero()?null:r}};var I={FixedSize:e=>({tag:"FixedSize",value:e}),RowOffsets:e=>({tag:"RowOffsets",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"FixedSize",algebraicType:T.U16},{name:"RowOffsets",algebraicType:T.Array(T.U64)}]}),serialize(e,t){T.serializeValue(e,I.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,I.getTypeScriptAlgebraicType())},A={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"sizeHint",algebraicType:I.getTypeScriptAlgebraicType()},{name:"rowsData",algebraicType:T.Array(T.U8)}]}),serialize(e,t){T.serializeValue(e,A.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,A.getTypeScriptAlgebraicType())},U={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"reducer",algebraicType:T.String},{name:"args",algebraicType:T.Array(T.U8)},{name:"requestId",algebraicType:T.U32},{name:"flags",algebraicType:T.U8}]}),serialize(e,t){T.serializeValue(e,U.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,U.getTypeScriptAlgebraicType())},_={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"queryStrings",algebraicType:T.Array(T.String)},{name:"requestId",algebraicType:T.U32}]}),serialize(e,t){T.serializeValue(e,_.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,_.getTypeScriptAlgebraicType())},z={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"messageId",algebraicType:T.Array(T.U8)},{name:"queryString",algebraicType:T.String}]}),serialize(e,t){T.serializeValue(e,z.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,z.getTypeScriptAlgebraicType())},v={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"id",algebraicType:T.U32}]}),serialize(e,t){T.serializeValue(e,v.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,v.getTypeScriptAlgebraicType())},F={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"query",algebraicType:T.String},{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,F.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,F.getTypeScriptAlgebraicType())},B={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"queryStrings",algebraicType:T.Array(T.String)},{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,B.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,B.getTypeScriptAlgebraicType())},M={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,M.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,M.getTypeScriptAlgebraicType())},V={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,V.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,V.getTypeScriptAlgebraicType())},P={CallReducer:e=>({tag:"CallReducer",value:e}),Subscribe:e=>({tag:"Subscribe",value:e}),OneOffQuery:e=>({tag:"OneOffQuery",value:e}),SubscribeSingle:e=>({tag:"SubscribeSingle",value:e}),SubscribeMulti:e=>({tag:"SubscribeMulti",value:e}),Unsubscribe:e=>({tag:"Unsubscribe",value:e}),UnsubscribeMulti:e=>({tag:"UnsubscribeMulti",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"CallReducer",algebraicType:U.getTypeScriptAlgebraicType()},{name:"Subscribe",algebraicType:_.getTypeScriptAlgebraicType()},{name:"OneOffQuery",algebraicType:z.getTypeScriptAlgebraicType()},{name:"SubscribeSingle",algebraicType:F.getTypeScriptAlgebraicType()},{name:"SubscribeMulti",algebraicType:B.getTypeScriptAlgebraicType()},{name:"Unsubscribe",algebraicType:M.getTypeScriptAlgebraicType()},{name:"UnsubscribeMulti",algebraicType:V.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,P.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,P.getTypeScriptAlgebraicType())},O={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"deletes",algebraicType:A.getTypeScriptAlgebraicType()},{name:"inserts",algebraicType:A.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,O.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,O.getTypeScriptAlgebraicType())},x={Uncompressed:e=>({tag:"Uncompressed",value:e}),Brotli:e=>({tag:"Brotli",value:e}),Gzip:e=>({tag:"Gzip",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"Uncompressed",algebraicType:O.getTypeScriptAlgebraicType()},{name:"Brotli",algebraicType:T.Array(T.U8)},{name:"Gzip",algebraicType:T.Array(T.U8)}]}),serialize(e,t){T.serializeValue(e,x.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,x.getTypeScriptAlgebraicType())},E={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tableId",algebraicType:T.U32},{name:"tableName",algebraicType:T.String},{name:"numRows",algebraicType:T.U64},{name:"updates",algebraicType:T.Array(x.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,E.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,E.getTypeScriptAlgebraicType())},C={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tables",algebraicType:T.Array(E.getTypeScriptAlgebraicType())}]}),serialize(e,t){T.serializeValue(e,C.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,C.getTypeScriptAlgebraicType())},k={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"databaseUpdate",algebraicType:C.getTypeScriptAlgebraicType()},{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDuration",algebraicType:T.createTimeDurationType()}]}),serialize(e,t){T.serializeValue(e,k.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,k.getTypeScriptAlgebraicType())},q={Committed:e=>({tag:"Committed",value:e}),Failed:e=>({tag:"Failed",value:e}),OutOfEnergy:{tag:"OutOfEnergy"},getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"Committed",algebraicType:C.getTypeScriptAlgebraicType()},{name:"Failed",algebraicType:T.String},{name:"OutOfEnergy",algebraicType:T.Product({elements:[]})}]}),serialize(e,t){T.serializeValue(e,q.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,q.getTypeScriptAlgebraicType())},R={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"reducerName",algebraicType:T.String},{name:"reducerId",algebraicType:T.U32},{name:"args",algebraicType:T.Array(T.U8)},{name:"requestId",algebraicType:T.U32}]}),serialize(e,t){T.serializeValue(e,R.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,R.getTypeScriptAlgebraicType())},D={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"quanta",algebraicType:T.U128}]}),serialize(e,t){T.serializeValue(e,D.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,D.getTypeScriptAlgebraicType())},N={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"status",algebraicType:q.getTypeScriptAlgebraicType()},{name:"timestamp",algebraicType:T.createTimestampType()},{name:"callerIdentity",algebraicType:T.createIdentityType()},{name:"callerConnectionId",algebraicType:T.createConnectionIdType()},{name:"reducerCall",algebraicType:R.getTypeScriptAlgebraicType()},{name:"energyQuantaUsed",algebraicType:D.getTypeScriptAlgebraicType()},{name:"totalHostExecutionDuration",algebraicType:T.createTimeDurationType()}]}),serialize(e,t){T.serializeValue(e,N.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,N.getTypeScriptAlgebraicType())},$={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"update",algebraicType:C.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,$.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,$.getTypeScriptAlgebraicType())},L={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"identity",algebraicType:T.createIdentityType()},{name:"token",algebraicType:T.String},{name:"connectionId",algebraicType:T.createConnectionIdType()}]}),serialize(e,t){T.serializeValue(e,L.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,L.getTypeScriptAlgebraicType())},W={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tableName",algebraicType:T.String},{name:"rows",algebraicType:A.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,W.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,W.getTypeScriptAlgebraicType())},H={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"messageId",algebraicType:T.Array(T.U8)},{name:"error",algebraicType:T.createOptionType(T.String)},{name:"tables",algebraicType:T.Array(W.getTypeScriptAlgebraicType())},{name:"totalHostExecutionDuration",algebraicType:T.createTimeDurationType()}]}),serialize(e,t){T.serializeValue(e,H.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,H.getTypeScriptAlgebraicType())},Q={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"tableId",algebraicType:T.U32},{name:"tableName",algebraicType:T.String},{name:"tableRows",algebraicType:E.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,Q.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,Q.getTypeScriptAlgebraicType())},j={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"rows",algebraicType:Q.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,j.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,j.getTypeScriptAlgebraicType())},Z={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"rows",algebraicType:Q.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,Z.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,Z.getTypeScriptAlgebraicType())},G={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"requestId",algebraicType:T.createOptionType(T.U32)},{name:"queryId",algebraicType:T.createOptionType(T.U32)},{name:"tableId",algebraicType:T.createOptionType(T.U32)},{name:"error",algebraicType:T.String}]}),serialize(e,t){T.serializeValue(e,G.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,G.getTypeScriptAlgebraicType())},K={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"update",algebraicType:C.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,K.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,K.getTypeScriptAlgebraicType())},X={getTypeScriptAlgebraicType:()=>T.Product({elements:[{name:"requestId",algebraicType:T.U32},{name:"totalHostExecutionDurationMicros",algebraicType:T.U64},{name:"queryId",algebraicType:v.getTypeScriptAlgebraicType()},{name:"update",algebraicType:C.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,X.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,X.getTypeScriptAlgebraicType())},J={InitialSubscription:e=>({tag:"InitialSubscription",value:e}),TransactionUpdate:e=>({tag:"TransactionUpdate",value:e}),TransactionUpdateLight:e=>({tag:"TransactionUpdateLight",value:e}),IdentityToken:e=>({tag:"IdentityToken",value:e}),OneOffQueryResponse:e=>({tag:"OneOffQueryResponse",value:e}),SubscribeApplied:e=>({tag:"SubscribeApplied",value:e}),UnsubscribeApplied:e=>({tag:"UnsubscribeApplied",value:e}),SubscriptionError:e=>({tag:"SubscriptionError",value:e}),SubscribeMultiApplied:e=>({tag:"SubscribeMultiApplied",value:e}),UnsubscribeMultiApplied:e=>({tag:"UnsubscribeMultiApplied",value:e}),getTypeScriptAlgebraicType:()=>T.Sum({variants:[{name:"InitialSubscription",algebraicType:k.getTypeScriptAlgebraicType()},{name:"TransactionUpdate",algebraicType:N.getTypeScriptAlgebraicType()},{name:"TransactionUpdateLight",algebraicType:$.getTypeScriptAlgebraicType()},{name:"IdentityToken",algebraicType:L.getTypeScriptAlgebraicType()},{name:"OneOffQueryResponse",algebraicType:H.getTypeScriptAlgebraicType()},{name:"SubscribeApplied",algebraicType:j.getTypeScriptAlgebraicType()},{name:"UnsubscribeApplied",algebraicType:Z.getTypeScriptAlgebraicType()},{name:"SubscriptionError",algebraicType:G.getTypeScriptAlgebraicType()},{name:"SubscribeMultiApplied",algebraicType:K.getTypeScriptAlgebraicType()},{name:"UnsubscribeMultiApplied",algebraicType:X.getTypeScriptAlgebraicType()}]}),serialize(e,t){T.serializeValue(e,J.getTypeScriptAlgebraicType(),t)},deserialize:e=>T.deserializeValue(e,J.getTypeScriptAlgebraicType())},Y=class{#a=new Map;on(e,t){let r=this.#a.get(e);r||(r=new Set,this.#a.set(e,r)),r.add(t)}off(e,t){const r=this.#a.get(e);r&&r.delete(t)}emit(e,...t){const r=this.#a.get(e);if(r)for(const e of r)e(...t)}},ee={component:"đĻ",info:"âšī¸",warn:"â ī¸",error:"â",debug:"đ"},te={component:"color: #fff; background-color: #8D6FDD; padding: 2px 5px; border-radius: 3px;",info:"color: #fff; background-color: #007bff; padding: 2px 5px; border-radius: 3px;",warn:"color: #fff; background-color: #ffc107; padding: 2px 5px; border-radius: 3px;",error:"color: #fff; background-color: #dc3545; padding: 2px 5px; border-radius: 3px;",debug:"color: #fff; background-color: #28a745; padding: 2px 5px; border-radius: 3px;"},re={component:"color: #8D6FDD;",info:"color: #007bff;",warn:"color: #ffc107;",error:"color: #dc3545;",debug:"color: #28a745;"},ie=(e,t)=>{console.log(`%c${ee[e]} ${e.toUpperCase()}%c ${t}`,te[e],re[e])},ae=class{rows;tableTypeInfo;emitter;constructor(e){this.tableTypeInfo=e,this.rows=new Map,this.emitter=new Y}count(){return this.rows.size}iter(){return Array.from(this.rows.values()).map(([e])=>e)}applyOperations=(e,t)=>{const r=[];if(void 0!==this.tableTypeInfo.primaryKeyInfo){const i=new Map,a=new Map;for(const t of e)if("insert"===t.type){const[e,r]=i.get(t.rowId)||[t,0];i.set(t.rowId,[t,r+1])}else{const[e,r]=a.get(t.rowId)||[t,0];a.set(t.rowId,[t,r+1])}for(const[e,[s,n]]of i){const i=a.get(e);if(i){const[o,c]=i,l=n-c,p=this.update(t,e,s.row,l);p&&r.push(p),a.delete(e)}else{const e=this.insert(t,s,n);e&&r.push(e)}}for(const[e,i]of a.values()){const a=this.delete(t,e,i);a&&r.push(a)}}else for(const i of e)if("insert"===i.type){const e=this.insert(t,i);e&&r.push(e)}else{const e=this.delete(t,i);e&&r.push(e)}return r};update=(e,t,r,i=0)=>{const a=this.rows.get(t);if(!a)return void ie("error",`Updating a row that was not present in the cache. Table: ${this.tableTypeInfo.tableName}, RowId: ${t}`);const[s,n]=a,o=Math.max(1,n+i);if(!(n+i<=0))return this.rows.set(t,[r,o]),0===n?(ie("error",`Updating a row id in table ${this.tableTypeInfo.tableName} which was not present in the cache (rowId: ${t})`),{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,r)}}):{type:"update",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("update",e,s,r)}};ie("error",`Negative reference count for in table ${this.tableTypeInfo.tableName} row ${t} (${n} + ${i})`)};insert=(e,t,r=1)=>{const[i,a]=this.rows.get(t.rowId)||[t.row,0];if(this.rows.set(t.rowId,[t.row,a+r]),0===a)return{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}};delete=(e,t,r=1)=>{const[i,a]=this.rows.get(t.rowId)||[t.row,0];if(0!==a)return a<=r?(this.rows.delete(t.rowId),{type:"delete",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("delete",e,t.row)}}):void this.rows.set(t.rowId,[t.row,a-r]);ie("warn","Deleting a row that was not present in the cache")};onInsert=e=>{this.emitter.on("insert",e)};onDelete=e=>{this.emitter.on("delete",e)};onUpdate=e=>{this.emitter.on("update",e)};removeOnInsert=e=>{this.emitter.off("insert",e)};removeOnDelete=e=>{this.emitter.off("delete",e)};removeOnUpdate=e=>{this.emitter.off("update",e)}},se=class{tables;constructor(){this.tables=new Map}getTable(e){const t=this.tables.get(e);if(!t)throw console.error("The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!"),new Error(`Table ${e} does not exist`);return t}getOrCreateTable(e){let t;return this.tables.has(e.tableName)?t=this.tables.get(e.tableName):(t=new ae(e),this.tables.set(e.tableName,t)),t}};var ne=class e{major;minor;patch;preRelease;buildInfo;constructor(e,t,r,i=null,a=null){this.major=e,this.minor=t,this.patch=r,this.preRelease=i,this.buildInfo=a}toString(){let e=`${this.major}.${this.minor}.${this.patch}`;return this.preRelease&&(e+=`-${this.preRelease.join(".")}`),this.buildInfo&&(e+=`+${this.buildInfo}`),e}compare(e){return this.major!==e.major?this.major-e.major:this.minor!==e.minor?this.minor-e.minor:this.patch!==e.patch?this.patch-e.patch:this.preRelease&&e.preRelease?function(e,t){const r=Math.min(e.length,t.length);for(let i=0;i<r;i++){const r=e[i],a=t[i];if(r!==a)return"number"==typeof r&&"number"==typeof a?r-a:"string"==typeof r&&"string"==typeof a?r.localeCompare(a):"string"==typeof r?1:-1}return e.length-t.length}(this.preRelease,e.preRelease):this.preRelease||e.preRelease?-1:0}clone(){return new e(this.major,this.minor,this.patch,this.preRelease?[...this.preRelease]:null,this.buildInfo)}static parseVersionString(t){const r=t.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$/);if(!r)throw new Error(`Invalid version string: ${t}`);const i=parseInt(r[1],10),a=parseInt(r[2],10),s=parseInt(r[3],10),n=r[4]?r[4].split(".").map(e=>isNaN(Number(e))?e:Number(e)):null,o=r[5]||null;return new e(i,a,s,n,o)}},oe=new ne(1,4,0);function ce(e){return`Module code was generated with an incompatible version of the spacetimedb cli (${e}). Update the cli version to at least ${oe.toString()} and regenerate the bindings. You can upgrade to the latest cli version by running: spacetime version upgrade`}async function le(e,t,r=131072){let i=0;const a=new ReadableStream({pull(t){if(i<e.length){const a=e.subarray(i,Math.min(i+r,e.length));t.enqueue(a),i+=r}else t.close()}}),s=new DecompressionStream(t),n=a.pipeThrough(s).getReader(),o=[];let c,l=0;for(;!(c=await n.read()).done;)o.push(c.value),l+=c.value.length;const p=new Uint8Array(l);let u=0;for(const e of o)p.set(e,u),u+=e.length;return p}var pe=class e{onclose;onopen;onmessage;onerror;#s;async#n(e){const t=new Uint8Array(e.data);let r;if(0===t[0])r=t.slice(1);else{if(1===t[0])throw new Error("Brotli Compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");if(2!==t[0])throw new Error("Unexpected Compression Algorithm. Please use `gzip` or `none`");r=await le(t.slice(1),"gzip")}this.onmessage?.({data:r})}#o(e){this.onopen?.(e)}#c(e){this.onerror?.(e)}#l(e){this.onclose?.(e)}send(e){this.#s.send(e)}close(){this.#s.close()}constructor(e){this.onmessage=void 0,this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,e.onmessage=this.#n.bind(this),e.onerror=this.#c.bind(this),e.onclose=this.#l.bind(this),e.onopen=this.#o.bind(this),e.binaryType="arraybuffer",this.#s=e}static async createWebSocketFn({url:t,nameOrAddress:r,wsProtocol:i,authToken:a,compression:s,lightMode:n}){const o=new Headers,c=await async function(){if(void 0!==globalThis.WebSocket)return globalThis.WebSocket;const e=new Function("m","return import(m)");try{const{WebSocket:t}=await e("undici");return t}catch(e){throw console.warn("[spacetimedb-sdk] No global WebSocket found. On Node 18â21, please install `undici` (npm install undici) to enable WebSocket support."),e}}();let l;if(a){o.set("Authorization",`Bearer ${a}`);const e=new URL("v1/identity/websocket-token",t);e.protocol="wss:"===t.protocol?"https:":"http:";const r=await fetch(e,{method:"POST",headers:o});if(!r.ok)return Promise.reject(new Error(`Failed to verify token: ${r.statusText}`));{const{token:e}=await r.json();l=e}}const p=new URL(`v1/database/${r}/subscribe`,t);l&&p.searchParams.set("token",l),p.searchParams.set("compression","gzip"===s?"Gzip":"None"),n&&p.searchParams.set("light","true");const u=new c(p.toString(),i);return new e(u)}},ue=class{constructor(e,t){this.remoteModule=e,this.dbConnectionConstructor=t,this.#p=pe.createWebSocketFn}#u;#g;#d;#b;#y=new Y;#h="gzip";#f=!1;#p;withUri(e){return this.#u=new URL(e),this}withModuleName(e){return this.#g=e,this}withToken(e){return this.#b=e,this}withWSFn(e){return this.#p=e,this}withCompression(e){return this.#h=e,this}withLightMode(e){return this.#f=e,this}onConnect(e){return this.#y.on("connect",e),this}onConnectError(e){return this.#y.on("connectError",e),this}onDisconnect(e){return this.#y.on("disconnect",e),this}build(){if(!this.#u)throw new Error("URI is required to connect to SpacetimeDB");if(!this.#g)throw new Error("Database name or address is required to connect to SpacetimeDB");return function(e){if(void 0===e)throw new Error(ce(e));if(ne.parseVersionString(e).compare(oe)<0)throw new Error(ce(e))}(this.remoteModule.versionInfo?.cliVersion),this.dbConnectionConstructor(new he({uri:this.#u,nameOrAddress:this.#g,identity:this.#d,token:this.#b,emitter:this.#y,compression:this.#h,lightMode:this.#f,createWSFn:this.#p,remoteModule:this.remoteModule}))}},ge=class{constructor(e){this.db=e}#T=void 0;#m=void 0;onApplied(e){return this.#T=e,this}onError(e){return this.#m=e,this}subscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("Subscriptions must have at least one query");return new be(this.db,t,this.#T,this.#m)}subscribeToAllTables(){this.subscribe("SELECT * FROM *")}},de=class{subscriptions=new Map},be=class{constructor(e,t,r,i){this.db=e,this.#y.on("applied",e=>{this.#S=!0,r&&r(e)}),this.#y.on("error",(e,t)=>{this.#S=!1,this.#w=!0,i&&i(e,t)}),this.#I=this.db.registerSubscription(this,this.#y,t)}#I;#A=!1;#w=!1;#S=!1;#y=new Y;unsubscribe(){if(this.#A)throw new Error("Unsubscribe has already been called");this.#A=!0,this.db.unregisterSubscription(this.#I),this.#y.on("end",e=>{this.#w=!0,this.#S=!1})}unsubscribeThen(e){if(this.#w)throw new Error("Subscription has already ended");if(this.#A)throw new Error("Unsubscribe has already been called");this.#A=!0,this.db.unregisterSubscription(this.#I),this.#y.on("end",t=>{this.#w=!0,this.#S=!1,e(t)})}isEnded(){return this.#w}isActive(){return this.#S}};function ye(e){switch(e){case"FullUpdate":return 0;case"NoSuccessNotify":return 1}}var he=class{isActive=!1;identity=void 0;token=void 0;db;reducers;setReducerFlags;connectionId=w.random();#I=0;#y;#U=new Y;#T;#_;#z=Promise.resolve();#v=new de;clientCache;ws;wsPromise;constructor({uri:e,nameOrAddress:t,identity:r,token:i,emitter:a,remoteModule:s,createWSFn:n,compression:o,lightMode:c}){ie("info","Connecting to SpacetimeDB WS...");const l=new URL(e.toString());/^wss?:/.test(e.protocol)||(l.protocol="https:"===l.protocol?"wss:":"ws:"),this.identity=r,this.token=i,this.#_=s,this.#y=a;const p=this.connectionId.toHexString();l.searchParams.set("connection_id",p),this.clientCache=new se,this.db=this.#_.dbViewConstructor(this),this.setReducerFlags=this.#_.setReducerFlagsConstructor(),this.reducers=this.#_.reducersConstructor(this,this.setReducerFlags),this.wsPromise=n({url:l,nameOrAddress:t,wsProtocol:"v1.bsatn.spacetimedb",authToken:i,compression:o,lightMode:c}).then(e=>(this.ws=e,this.ws.onclose=()=>{this.#y.emit("disconnect",this)},this.ws.onerror=e=>{this.#y.emit("connectError",this,e)},this.ws.onopen=this.#o.bind(this),this.ws.onmessage=this.#n.bind(this),e)).catch(e=>{ie("error","Error connecting to SpacetimeDB WS"),this.#y.emit("connectError",this,e)})}#F=()=>{const e=this.#I;return this.#I+=1,e};subscriptionBuilder=()=>new ge(this);registerSubscription(e,t,r){const i=this.#F();return this.#v.subscriptions.set(i,{handle:e,emitter:t}),this.#B(P.SubscribeMulti({queryStrings:r,queryId:{id:i},requestId:0})),i}unregisterSubscription(e){this.#B(P.UnsubscribeMulti({queryId:{id:e},requestId:0}))}async#M(t){const r=(t,r,i)=>{const s=i.rowsData,n=new a(s),o=[],c=this.#_.tables[r].rowType,l=this.#_.tables[r].primaryKeyInfo;for(;n.offset<s.length+s.byteOffset;){const r=n.offset,i=T.deserializeValue(n,c);let a;if(void 0!==l)a=T.intoMapKey(l.colType,i[l.colName]);else{const t=s.subarray(r-s.byteOffset,n.offset-s.byteOffset);a=e(t)}o.push({type:t,rowId:a,row:i})}return o},i=async e=>{const t=e.tableName;let i=[];for(const s of e.updates){let e;if("Gzip"===s.tag){const t=await le(s.value,"gzip");e=O.deserialize(new a(t))}else{if("Brotli"===s.tag)throw new Error("Brotli compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");e=s.value}i=i.concat(r("insert",t,e.inserts)),i=i.concat(r("delete",t,e.deletes))}return{tableName:t,operations:i}},s=async e=>{const t=[];for(const r of e.tables)t.push(await i(r));return t};switch(t.tag){case"InitialSubscription":{const e=t.value.databaseUpdate;return{tag:"InitialSubscription",tableUpdates:await s(e)}}case"TransactionUpdateLight":{const e=t.value.update;return{tag:"TransactionUpdateLight",tableUpdates:await s(e)}}case"TransactionUpdate":{const e=t.value,r=e.callerIdentity,i=w.nullIfZero(e.callerConnectionId),a=e.reducerCall.reducerName,n=e.reducerCall.args,o=e.energyQuantaUsed;let c,l=[],p="";switch(e.status.tag){case"Committed":l=await s(e.status.value);break;case"Failed":l=[],p=e.status.value;break;case"OutOfEnergy":l=[]}if("<none>"===a){const e=p;return void console.error(`Received an error from the database: ${e}`)}""!==a&&(c={reducerName:a,args:n});return{tag:"TransactionUpdate",tableUpdates:l,identity:r,connectionId:i,reducerInfo:c,status:e.status,energyConsumed:o.quanta,message:p,timestamp:e.timestamp}}case"IdentityToken":return{tag:"IdentityToken",identity:t.value.identity,token:t.value.token,connectionId:t.value.connectionId};case"OneOffQueryResponse":throw new Error(`TypeScript SDK never sends one-off queries, but got OneOffQueryResponse ${t}`);case"SubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"SubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"UnsubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"UnsubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"SubscriptionError":return{tag:"SubscriptionError",queryId:t.value.queryId,error:t.value.error}}}#B(e){this.wsPromise.then(t=>{if(t){const r=new i(1024);P.serialize(r,e);const a=r.getBuffer();t.send(a)}})}#o(){this.isActive=!0}#V(e,t){const r=[];for(const i of e){const e=i.tableName,a=this.#_.tables[e],s=this.clientCache.getOrCreateTable(a).applyOperations(i.operations,t);for(const e of s)r.push(e)}return r}async#P(e){const t=function(e,t){const r=new a(t);return e.deserialize(r)}(J,e),r=await this.#M(t);if(r)switch(r.tag){case"InitialSubscription":{const e={tag:"SubscribeApplied"},t=this.#_.eventContextConstructor(this,e),{event:i,...a}=t,s=this.#V(r.tableUpdates,t);this.#y&&this.#T?.(a);for(const e of s)e.cb();break}case"TransactionUpdateLight":{const e={tag:"UnknownTransaction"},t=this.#_.eventContextConstructor(this,e),i=this.#V(r.tableUpdates,t);for(const e of i)e.cb();break}case"TransactionUpdate":{let e,t,i=r.reducerInfo,s=!1;if(i){t=this.#_.reducers[i.reducerName];try{const r=new a(i.args);e=T.deserializeValue(r,t.argsType)}catch{console.debug("Failed to deserialize reducer arguments"),s=!0}}else s=!0;if(s){const e={tag:"UnknownTransaction"},t=this.#_.eventContextConstructor(this,e),i=this.#V(r.tableUpdates,t);for(const e of i)e.cb();return}const n={callerIdentity:r.identity,status:r.status,callerConnectionId:r.connectionId,timestamp:r.timestamp,energyConsumed:r.energyConsumed,reducer:{name:i.reducerName,args:e}},o={tag:"Reducer",value:n},c=this.#_.eventContextConstructor(this,o),l={...c,event:n},p=this.#V(r.tableUpdates,c),u=[];t.argsType.value.elements.forEach(t=>{u.push(e[t.name])}),this.#U.emit(i.reducerName,l,...u);for(const e of p)e.cb();break}case"IdentityToken":this.identity=r.identity,!this.token&&r.token&&(this.token=r.token),this.connectionId=r.connectionId,this.#y.emit("connect",this,this.identity,this.token);break;case"SubscribeApplied":{const e=this.#v.subscriptions.get(r.queryId);if(void 0===e){ie("error",`Received SubscribeApplied for unknown queryId ${r.queryId}.`);break}const t={tag:"SubscribeApplied"},i=this.#_.eventContextConstructor(this,t),{event:a,...s}=i,n=this.#V(r.tableUpdates,i);e?.emitter.emit("applied",s);for(const e of n)e.cb();break}case"UnsubscribeApplied":{const e=this.#v.subscriptions.get(r.queryId);if(void 0===e){ie("error",`Received UnsubscribeApplied for unknown queryId ${r.queryId}.`);break}const t={tag:"UnsubscribeApplied"},i=this.#_.eventContextConstructor(this,t),{event:a,...s}=i,n=this.#V(r.tableUpdates,i);e?.emitter.emit("end",s),this.#v.subscriptions.delete(r.queryId);for(const e of n)e.cb();break}case"SubscriptionError":{const e=Error(r.error),t={tag:"Error",value:e},i={...this.#_.eventContextConstructor(this,t),event:e};void 0!==r.queryId?(this.#v.subscriptions.get(r.queryId)?.emitter.emit("error",i,e),this.#v.subscriptions.delete(r.queryId)):(console.error("Received an error message without a queryId: ",e),this.#v.subscriptions.forEach(({emitter:t})=>{t.emit("error",i,e)}))}}}#n(e){this.#z=this.#z.then(()=>this.#P(e.data))}callReducer(e,t,r){const i=P.CallReducer({reducer:e,args:t,requestId:0,flags:ye(r)});this.#B(i)}disconnect(){this.wsPromise.then(e=>{e&&e.close()})}on(e,t){this.#y.on(e,t)}off(e,t){this.#y.off(e,t)}onConnect(e){this.#y.on("connect",e)}onDisconnect(e){this.#y.on("disconnect",e)}onConnectError(e){this.#y.on("connectError",e)}removeOnConnect(e){this.#y.off("connect",e)}removeOnDisconnect(e){this.#y.off("disconnect",e)}removeOnConnectError(e){this.#y.off("connectError",e)}onReducer(e,t){this.#U.on(e,t)}offReducer(e,t){this.#U.off(e,t)}};export{a as BinaryReader,i as BinaryWriter,se as ClientCache,ue as DbConnectionBuilder,he as DbConnectionImpl,ge as SubscriptionBuilderImpl,ae as TableCache};//# sourceMappingURL=index.browser.mjs.map
|