@moyodb/sdk 1.0.0 → 1.0.1
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/README.md +2 -2
- package/dist/LICENSE +202 -0
- package/dist/assets/worker-KDc8Khl_.js +4 -0
- package/dist/assets/worker-KDc8Khl_.js.map +1 -0
- package/dist/codec.d.ts.map +1 -1
- package/dist/compression.d.ts.map +1 -1
- package/dist/engine/README.md +11 -10
- package/dist/engine/moyodb_engine.d.ts +29 -19
- package/dist/engine/moyodb_engine.js +78 -28
- package/dist/engine/moyodb_engine_bg.wasm +0 -0
- package/dist/engine/moyodb_engine_bg.wasm.d.ts +4 -2
- package/dist/engine/snippets/moyodb-engine-8ebe6af0cc2e81b7/js/opfs_shim.js +151 -62
- package/dist/errors.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/indexing.d.ts +8 -0
- package/dist/indexing.d.ts.map +1 -1
- package/dist/moyodb-sdk.js +764 -583
- package/dist/moyodb-sdk.js.map +1 -1
- package/dist/registry.d.ts +1 -0
- package/dist/registry.d.ts.map +1 -1
- package/dist/subscriptions.d.ts.map +1 -1
- package/dist/types.d.ts +6 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/worker-api.d.ts +3 -4
- package/dist/worker-api.d.ts.map +1 -1
- package/dist/worker-client.d.ts +8 -0
- package/dist/worker-client.d.ts.map +1 -1
- package/dist/worker-protocol.d.ts +28 -0
- package/dist/worker-protocol.d.ts.map +1 -1
- package/dist/worker-server.d.ts.map +1 -1
- package/package.json +4 -2
- package/dist/assets/worker-R2dy1Ju5.js +0 -4
- package/dist/assets/worker-R2dy1Ju5.js.map +0 -1
package/README.md
CHANGED
|
@@ -7,10 +7,10 @@ The package name is lowercase/scoped for npm compatibility. The public brand is
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
npm install @moyodb/sdk@1.0.
|
|
10
|
+
npm install @moyodb/sdk@1.0.1
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
Current release: `@moyodb/sdk@1.0.
|
|
13
|
+
Current release: `@moyodb/sdk@1.0.1`.
|
|
14
14
|
|
|
15
15
|
## Usage
|
|
16
16
|
|
package/dist/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Mother of Licenses 1.0
|
|
2
|
+
|
|
3
|
+
Version: 1.0
|
|
4
|
+
Short name: MoL-1.0
|
|
5
|
+
SPDX license reference: LicenseRef-MoL-1.0
|
|
6
|
+
|
|
7
|
+
Copyright © 2026 Eluvane
|
|
8
|
+
Licensor: Eluvane
|
|
9
|
+
Licensing contact: keiko1337@proton.me
|
|
10
|
+
Official repository: https://github.com/eluvane/MoyoDB
|
|
11
|
+
|
|
12
|
+
MoyoDB is offered under this License starting with release 1.0.0. Earlier published releases remain governed by their original licenses.
|
|
13
|
+
|
|
14
|
+
1. Scope and Acceptance
|
|
15
|
+
|
|
16
|
+
This License applies only to material expressly released under the Mother of Licenses 1.0 by a party authorized to do so. Public availability does not grant additional permissions.
|
|
17
|
+
|
|
18
|
+
By exercising permissions under this License that require the Licensor's authorization, You accept its conditions. Activities independently permitted under Section 14 do not require acceptance. Merely viewing the Work does not make You a Contributor.
|
|
19
|
+
|
|
20
|
+
The grants are non-exclusive, worldwide, and royalty-free for the duration of the applicable intellectual property rights, subject to this License and its termination provisions. No subscription, registration, revenue threshold, or organization-size limit applies. Rights not expressly granted are reserved.
|
|
21
|
+
|
|
22
|
+
2. Definitions
|
|
23
|
+
|
|
24
|
+
Work means the software, source and executable code, documentation, and accompanying copyrightable material expressly covered by this License, including covered portions of that material. It excludes third-party material except to the extent the Licensor has authority to offer that material under this License.
|
|
25
|
+
|
|
26
|
+
Licensor means the copyright holder or authorized licensing party offering the Work under this License and identified in the applicable licensing notice. Where multiple copyright holders are named, the notice must identify the party receiving Contributions and administering exceptions. A Contributor does not become that party merely by contributing.
|
|
27
|
+
|
|
28
|
+
You means the individual or legal entity exercising rights under this License. Personnel and contractors may act on Your behalf within Your authorized activities; this does not give them broader independent rights.
|
|
29
|
+
|
|
30
|
+
Official Distribution means a version, source snapshot, or package expressly published under this License by, or with authorization from, the Licensor through its designated repository or release channel. An identical copy retains its provenance but its distributor does not thereby become an official publisher. Later withdrawal does not retrospectively change a distribution's authorized status.
|
|
31
|
+
|
|
32
|
+
Authorized Build means the mechanical preparation of unmodified Official Distribution source through compilation, transpilation, linking, bundling, optimization, minification, or removal of unused code, using ordinary build tools and the Work's supported configuration mechanisms. This includes necessary runtime portions incorporated into generated applications. It does not include source patches, replacement implementations, or changes to the Work's authored functionality. An Authorized Build must not be represented as an official binary unless authorized.
|
|
33
|
+
|
|
34
|
+
Derivative Work means an adaptation or modification incorporating copyright-protected expression from the Work that requires the relevant rights holder's permission under applicable law. Independently written software does not become a Derivative Work merely by interoperating with the Work. Authorized Builds and permitted component combinations are governed by their express permissions below, regardless of their legal classification.
|
|
35
|
+
|
|
36
|
+
Component Product means an application, product, or service that uses the Work as a supporting dependency or development tool and supplies substantial, independently developed, application-specific functionality beyond providing the Work's principal capabilities themselves. Its customer-facing purpose must not primarily be obtaining, operating, or replacing the Work. Merely adding packaging, branding, billing, authentication, deployment, monitoring, or an interface around those capabilities is insufficient. The Work's technical necessity, code volume, or contribution to performance does not alone disqualify a Component Product.
|
|
37
|
+
|
|
38
|
+
Commercial Use means use in business, professional, or revenue-generating activities, including internal operations and developing, distributing, or operating Component Products. Commercial Use is permitted only within the specific grants below; the term does not itself authorize Commercialization.
|
|
39
|
+
|
|
40
|
+
Hosted Service means providing others with remote access to software functionality. Access solely by Your personnel or contractors acting for Your internal operations is not a Hosted Service for this purpose.
|
|
41
|
+
|
|
42
|
+
Project-as-a-Service means a Hosted Service whose primary offering is the Work's principal capabilities themselves, supplied through the Work or a Derivative Work. A separately offered feature is evaluated separately even when bundled into a broader service. A service remains Project-as-a-Service despite added interfaces or management features described in the Component Product definition.
|
|
43
|
+
|
|
44
|
+
Commercialization means offering the Work or a Derivative Work itself for payment or other commercial consideration, including selling copies, charging for its license or access, reselling a substantially unchanged package, or supplying it as the primary inducement to purchase another offering. Charging for a qualifying Component Product or services expressly permitted below is not Commercialization.
|
|
45
|
+
|
|
46
|
+
Competing Product means software or a service that incorporates or adapts a substantial amount of the Work's protected implementation or other copyrightable expression and whose primary purpose is to offer the Work's core capabilities as a substitute, alternative distribution, or independent successor. Substantiality concerns quantity or qualitative importance to that implementation. Similar functionality, unprotected ideas, interfaces, algorithms, or general architectural concepts alone do not establish a Competing Product.
|
|
47
|
+
|
|
48
|
+
Contribution means copyrightable material intentionally submitted to the Licensor for inclusion in the official Work, through an official contribution channel, by its rights holder or authorized representative with notice and acceptance of Section 9. A Contributor is that submitting party. Material merely quoted for discussion, or clearly designated as not offered for incorporation, is not a Contribution.
|
|
49
|
+
|
|
50
|
+
Written Permission means express authorization from the Licensor or its authorized licensing representative identifying the otherwise restricted activity. Verifiable electronic communications qualify. Silence, an unanswered request, or technical access does not qualify.
|
|
51
|
+
|
|
52
|
+
3. Permitted Use and Component Products
|
|
53
|
+
|
|
54
|
+
You may obtain, copy, inspect, study, audit, and run Official Distributions and Authorized Builds for personal, educational, research, governmental, or commercial purposes. You may make backups and internal copies reasonably necessary for those activities.
|
|
55
|
+
|
|
56
|
+
You may use the Work to create commercial software and may incorporate unmodified Official Distribution code or Authorized Builds as dependencies in Component Products. This includes static or dynamic linking, embedded libraries, browser bundles, applications, containers, and ordinary infrastructure dependencies.
|
|
57
|
+
|
|
58
|
+
You may sell, license, distribute, and operate Component Products, including proprietary and closed-source products, and charge for their independently developed functionality. You may provide software-as-a-service that uses the Work internally as a component rather than providing Project-as-a-Service.
|
|
59
|
+
|
|
60
|
+
You may charge for independently supplied consulting, training, integration, audits, or support, provided the charge does not purchase restricted distribution rights, access to the Work itself, or Project-as-a-Service. General-purpose computing, storage, networking, and CI services are permitted where customers choose and operate their own instances and the provider does not supply a Work-specific managed service.
|
|
61
|
+
|
|
62
|
+
Employees, contractors, and infrastructure providers may make necessary operational copies solely on Your behalf and within these permissions. You must not authorize them to exceed those permissions.
|
|
63
|
+
|
|
64
|
+
No source-disclosure obligation attaches to Your independently developed application, integrations, data, or output merely because You use the Work. Output containing portions of the Work remains subject to this License for those portions; other output is not covered merely because the Work produced it.
|
|
65
|
+
|
|
66
|
+
You may create, maintain, build, test, and run private modifications of the Work solely for Your own internal use, including use of Your own patches in production. Under this permission, neither the modifications nor the modified Work may be distributed, published, or otherwise provided or made available to third parties. The permissions for persons acting on Your behalf do not override this restriction.
|
|
67
|
+
|
|
68
|
+
Private modifications must not be used to create a standalone or Competing Product or to provide Project-as-a-Service. This permission does not authorize distributing a Component Product containing modified portions of the Work.
|
|
69
|
+
|
|
70
|
+
Except for the limited upstream contribution workflow expressly permitted by Section 6, distributing, publishing, or otherwise making modified versions or patches available to third parties requires Written Permission. Other modifications require another express permission under this License or Written Permission.
|
|
71
|
+
|
|
72
|
+
4. Permitted Redistribution and Infrastructure Copies
|
|
73
|
+
|
|
74
|
+
You may distribute the Work as an included component of a Component Product under Section 3, in source form taken unchanged from an Official Distribution or as an Authorized Build. You may charge for the Component Product, but not separately for rights to the Work itself.
|
|
75
|
+
|
|
76
|
+
You may also reproduce and redistribute exact, unmodified Official Distributions where reasonably necessary for package managers, dependency registries, operating-system repositories, CI caches, archival preservation, security scanning, or research indexing.
|
|
77
|
+
|
|
78
|
+
For this infrastructure exception, compression, transport containers, signatures, and external package metadata may be added without changing the enclosed distribution files. A separately rebuilt binary, patched package, or substituted implementation is not an exact Official Distribution and requires another applicable permission. Mere verification, caching, and retention of historical versions do not create an independent development line.
|
|
79
|
+
|
|
80
|
+
Infrastructure redistribution must preserve this License and applicable notices, identify the original project and version, distinguish the infrastructure operator from the official publisher, and not charge primarily for access to the Work. Ordinary fees for shared infrastructure, storage, bandwidth, repository operation, or indexing are permitted. Calling a Work-specific paywall an infrastructure fee does not qualify.
|
|
81
|
+
|
|
82
|
+
These exceptions do not permit publishing an independently branded edition, issuing unofficial project releases, or operating a mirror as an independent successor project. A neutral mirror or archive faithfully presenting official versions remains permitted.
|
|
83
|
+
|
|
84
|
+
Each recipient obtains rights to the included Work directly under this License. Your product terms may govern Your own material but must exclude the Work from conflicting restrictions and must not purport to relicense it. No obligation requires disclosure of Your surrounding source code.
|
|
85
|
+
|
|
86
|
+
5. Reserved Activities
|
|
87
|
+
|
|
88
|
+
Except as expressly permitted elsewhere in this License, by Written Permission, or under Section 14, You may not create, maintain, publish, or distribute an independent fork or development line based on the Work; distribute modified versions or patches as an alternative implementation; or make the Work or a Derivative Work available as a standalone unofficial distribution.
|
|
89
|
+
|
|
90
|
+
You may not engage in Commercialization, including resale, paid repackaging, license-fee collection, or payment-gated access to the Work itself. You may not rebrand the Work or a Derivative Work as software independently created by You.
|
|
91
|
+
|
|
92
|
+
You may not develop or offer a Competing Product based on the Work, or provide Project-as-a-Service without Written Permission. The fork, Competing Product, and Project-as-a-Service restrictions apply whether the offering is paid, free, donation-supported, or promotional. Private modifications under Section 3 and genuine upstream development under Section 6 remain permitted within their respective conditions.
|
|
93
|
+
|
|
94
|
+
Changing names, adding superficial features, dividing an offering across related entities, or providing source code does not create an exception. Offering to disclose modified source does not authorize distribution.
|
|
95
|
+
|
|
96
|
+
This Section does not restrict independently written competing software merely because it addresses the same problem, nor does it restrict the ordinary component uses expressly permitted by Section 3.
|
|
97
|
+
|
|
98
|
+
6. Upstream Contribution Workflow
|
|
99
|
+
|
|
100
|
+
You may clone the official repository, create local branches, modify the Work, and build and test those modifications solely to prepare, submit, revise, or review a bona fide upstream Contribution. Reviewers and automated CI systems may make the copies necessary for that process.
|
|
101
|
+
|
|
102
|
+
Where the official contribution workflow reasonably requires it, You may create a technical fork on a hosting platform and expose the relevant branches, patches, and temporary test artifacts for upstream review. Clearly identify its contribution-only purpose and the official upstream project. Do not publish general-use releases, solicit users for an alternative project, or use that fork as a production distribution.
|
|
103
|
+
|
|
104
|
+
Once the contribution process concludes or is abandoned, stop distribution of the modified copy except for inactive review records. Further development and use must be limited to the private modifications permitted by Section 3, further bona fide upstream work under this Section, or Written Permission. You may retain private archival copies and need not delete records the platform retains independently. Retention does not authorize an independent development line.
|
|
105
|
+
|
|
106
|
+
Acceptance of a patch authorizes its incorporation into an Official Distribution, not independent distribution of Your modified version. Until officially published, modified builds may be used only under the private-modification permission in Section 3, this contribution workflow, or Written Permission.
|
|
107
|
+
|
|
108
|
+
7. Indexing, Analysis, and Artificial Intelligence
|
|
109
|
+
|
|
110
|
+
You may perform ordinary search-engine and repository indexing, code search, academic indexing, security scanning, automated review, and archival preservation. You may publish findings and reasonably necessary attributed excerpts for analysis, teaching, criticism, or security reporting, but not a substitute implementation or modified software distribution. Distribution of complete copies remains governed by Sections 4 and 6.
|
|
111
|
+
|
|
112
|
+
You may use commercial or noncommercial AI development tools to process the Work for otherwise authorized development, debugging, review, documentation, research, or contribution preparation.
|
|
113
|
+
|
|
114
|
+
This permission includes task-related transmission, temporary storage, tokenization, embeddings, retrieval, and inference. Providers acting for an authorized user may perform those operations for the requested task. Retrieval indexes and ordinary prompt processing are not model training merely because a commercial tool performs them.
|
|
115
|
+
|
|
116
|
+
Without Written Permission, You may not use a substantial portion of the Work to train, pretrain, fine-tune, or distill a model intended for commercial deployment, commercial code generation, or sale; prepare training examples for those purposes; or sell or commercially license a dataset substantially reproducing or adapting the Work.
|
|
117
|
+
|
|
118
|
+
For this restriction, training means fitting or updating learned model parameters. Commercial purposes include proprietary business deployment and research specifically undertaken to develop a commercial model. Substantiality is assessed against the Work, including a qualitatively important protected implementation, not diluted by the size of a larger corpus. Related collections are assessed together; incidental, isolated snippets are not automatically substantial.
|
|
119
|
+
|
|
120
|
+
Ordinary task processing does not authorize a provider's separate restricted training. You must not direct or knowingly authorize that training without sufficient rights, but You need not investigate undisclosed provider conduct merely to use an assistant. Genuinely noncommercial research remains permitted within the other applicable conditions.
|
|
121
|
+
|
|
122
|
+
The Licensor expressly reserves rights for the restricted reproductions and extractions described here wherever applicable law recognizes such reservations. This reservation does not narrow the permitted indexing, inference, or contribution workflows, and remains subject to Section 14.
|
|
123
|
+
|
|
124
|
+
8. Notices, Authorship, and Trademarks
|
|
125
|
+
|
|
126
|
+
Preserve the full License text and applicable copyright, authorship, patent, and attribution notices when distributing the Work. For executable or bundled distributions, include a readable copy in accompanying license files, documentation, or an accessible third-party-notices location. Mechanical removal of source comments from a build is permitted only where the relevant notices remain in those accompanying materials. For limited excerpts under Section 7, identifying the source, the copyright holder where known, and this License is sufficient.
|
|
127
|
+
|
|
128
|
+
Do not falsely remove or reassign authorship. You may accurately identify Your separate contributions and Your Component Product. No advertising, splash screen, or prominent user-interface attribution is required.
|
|
129
|
+
|
|
130
|
+
No trademark, service-mark, trade-name, logo, or endorsement rights are granted. Do not impersonate the official project, suggest unauthorized affiliation, or describe an unofficial build as an official release. Truthful, legally permitted nominative descriptions are not prohibited by this License.
|
|
131
|
+
|
|
132
|
+
9. Contributions and Relicensing Authority
|
|
133
|
+
|
|
134
|
+
By knowingly submitting a Contribution with notice of this Section, You accept this Section and make the following grants. The Licensor may require a recorded electronic acknowledgment or separate contributor agreement before incorporation. Mere public availability of someone else's material does not constitute its submission or consent.
|
|
135
|
+
|
|
136
|
+
You grant the Licensor a perpetual, worldwide, non-exclusive, irrevocable, royalty-free, fully paid-up, transferable, and sublicensable copyright license to Your Contribution. It includes authority to use, reproduce, modify, adapt, translate, combine, incorporate, distribute, publicly display, publicly perform, commercialize, and otherwise exploit the Contribution in any medium.
|
|
137
|
+
|
|
138
|
+
The Licensor may sublicense through multiple levels, sell licenses, include the Contribution in proprietary products, and offer it under different, additional, or replacement licensing terms, including commercial terms. The Licensor may transfer these granted rights without further consent from You. The grant takes effect upon submission and does not depend on acceptance, merger, attribution in advertising, or continued distribution of the Contribution.
|
|
139
|
+
|
|
140
|
+
You retain ownership and authorship of Your original Contribution unless separately assigned. No partnership, employment, equity interest, or ownership interest in the remainder of the Work arises. You may separately license material You own, but not portions of the Work belonging to others without authorization.
|
|
141
|
+
|
|
142
|
+
To the extent legally waivable, You have no entitlement to royalties, revenue share, license fees, payment, ownership percentages, or other compensation merely because the Licensor or its licensees use, relicense, or commercially exploit Your Contribution. This does not cancel compensation expressly agreed in writing or rights that applicable law makes non-waivable.
|
|
143
|
+
|
|
144
|
+
You represent that You have authority to submit the Contribution and grant these rights; that it is Your original work or You have sufficient permissions; and that any necessary employer or other rights-holder authorization has been obtained. You must identify known third-party material and its applicable terms. You must not knowingly submit material subject to obligations incompatible with these grants.
|
|
145
|
+
|
|
146
|
+
No patent search, absolute guarantee of originality, or investigation beyond reasonable knowledge is required. If You discover a material rights problem, notify the Licensor promptly. Material You cannot license on these terms must be identified before submission and may be incorporated only under a separate arrangement preserving the relevant third-party rights.
|
|
147
|
+
|
|
148
|
+
To the extent lawful, You consent to modifications and exploitation authorized here and agree not to assert moral rights solely to prevent those authorized acts. This does not authorize false attribution or waive rights that cannot lawfully be waived.
|
|
149
|
+
|
|
150
|
+
The Licensor need not accept, maintain, support, or publicly release a Contribution. These grants survive withdrawal of a submission and termination of Your permissions, subject to mandatory law and the patent-specific provisions below. A separate contribution agreement expressly accepted by the Licensor controls any stated differences.
|
|
151
|
+
|
|
152
|
+
10. Patents
|
|
153
|
+
|
|
154
|
+
Each Contributor grants the Licensor and recipients of the Work a worldwide, non-exclusive, royalty-free patent license under claims the Contributor owns or is authorized to license that are necessarily infringed by its Contribution alone or by that Contribution combined with the Work to which it was submitted. The Licensor makes the equivalent grant for its own contributed material.
|
|
155
|
+
|
|
156
|
+
The license permits making, having made, using, offering, selling, importing, and transferring the covered implementation, but only within activities authorized by this License or a separate license from the Licensor. It does not authorize otherwise prohibited Commercialization or distribution.
|
|
157
|
+
|
|
158
|
+
For Contributions, the Licensor may transfer and sublicense this patent license through multiple levels to support the exploitation and relicensing authorized by Section 9. Coverage does not extend to claims infringed only because of later additions or combinations beyond the contributed implementation and its combination with the Work as submitted. These grants continue for the relevant patents' duration and are irrevocable except for termination expressly provided by this License or required by law.
|
|
159
|
+
|
|
160
|
+
If a beneficiary of a patent grant under this Section initiates or directs patent litigation, including an infringement counterclaim or cross-claim, alleging that the Work or an incorporated Contribution infringes a patent it owns or controls, all patent permissions granted to that claimant under this License for that Work terminate when the claim is filed. Defending a claim without asserting such infringement does not trigger termination.
|
|
161
|
+
|
|
162
|
+
Patent retaliation does not terminate unrelated parties' rights. Restoration requires written consent from the relevant patent grantor and is not guaranteed by Section 13. No additional patent rights are implied, and copyright permissions do not supply missing patent rights.
|
|
163
|
+
|
|
164
|
+
11. Separate Licenses and Exceptions
|
|
165
|
+
|
|
166
|
+
The Licensor may offer separate or additional licenses on different terms, for payment or otherwise, including commercial, OEM, redistribution, fork, hosted-service, and proprietary-derivative rights, to the extent it controls the necessary rights.
|
|
167
|
+
|
|
168
|
+
A separate agreement may require source disclosure, royalties, attribution, or other conditions for authorized modifications or distributions. Those conditions neither arise automatically under this License nor create rights for anyone outside that agreement.
|
|
169
|
+
|
|
170
|
+
Written Permission controls only its stated scope. No exception is inferred from cooperation, contribution acceptance, delayed enforcement, or permission granted to another person.
|
|
171
|
+
|
|
172
|
+
12. Disclaimer of Warranty and Limitation of Liability
|
|
173
|
+
|
|
174
|
+
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WORK IS PROVIDED “AS IS” AND AS AVAILABLE, WITHOUT EXPRESS, IMPLIED, OR STATUTORY WARRANTIES OR CONDITIONS, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, CORRECTNESS, SECURITY, AVAILABILITY, OR RELIABILITY.
|
|
175
|
+
|
|
176
|
+
NO WARRANTY IS MADE OF PRODUCTION SUITABILITY, UNINTERRUPTED OPERATION, DURABILITY, CRASH CONSISTENCY, SUCCESSFUL RECOVERY, OR THE PRESERVATION, ACCURACY, OR INTEGRITY OF STORED OR PROCESSED DATA. YOU ARE RESPONSIBLE FOR EVALUATION, TESTING, BACKUPS, AND OPERATIONAL SAFEGUARDS.
|
|
177
|
+
|
|
178
|
+
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSOR AND CONTRIBUTORS SHALL NOT BE LIABLE FOR DAMAGES ARISING FROM THIS LICENSE OR THE WORK, UNDER CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY, OR OTHER THEORY, INCLUDING DIRECT, INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES; LOST OR CORRUPTED DATA; LOST REVENUE, PROFITS, BUSINESS, OR GOODWILL; DOWNTIME; SECURITY INCIDENTS; OR SYSTEM FAILURES, EVEN IF ADVISED OF THE POSSIBILITY.
|
|
179
|
+
|
|
180
|
+
These provisions do not exclude liability or rights that cannot lawfully be excluded, including any applicable mandatory protections concerning fraud, intentional misconduct, gross negligence, or death or personal injury. They do not cancel the express contributor representations in Section 9 or obligations expressly assumed in a separate written agreement.
|
|
181
|
+
|
|
182
|
+
13. Termination and Cure
|
|
183
|
+
|
|
184
|
+
Your permissions terminate automatically upon a material breach of this License, subject to mandatory law.
|
|
185
|
+
|
|
186
|
+
For a first, unintentional, curable material breach, permissions are automatically reinstated when You stop the breach and complete reasonably practicable corrective measures for consequences within Your control, provided this occurs before notice or within 30 days after receiving written notice describing the breach with reasonable specificity.
|
|
187
|
+
|
|
188
|
+
Intentional unauthorized Commercialization, deliberate operation of an unauthorized fork or Project-as-a-Service, and repeated material breaches after prior notice do not receive automatic reinstatement. The Licensor may nevertheless reinstate permissions by Written Permission. Obtaining another copy does not itself reinstate terminated permissions. Patent retaliation is governed separately by Section 10.
|
|
189
|
+
|
|
190
|
+
Upon termination, stop exercising the terminated permissions and cease unauthorized distribution and services. You may retain non-operational copies required for legal compliance or evidence, and inaccessible routine backups until ordinarily overwritten, but may not use that retention to continue prohibited activity.
|
|
191
|
+
|
|
192
|
+
Reinstatement does not automatically waive claims arising before cure. Termination does not terminate compliant recipients' direct licenses or grants You have made under Sections 9 and 10, except as expressly stated there. Ownership provisions, accrued claims, disclaimers, liability limitations, and provisions necessary to interpret surviving rights remain effective.
|
|
193
|
+
|
|
194
|
+
14. Existing Rights, Versioning, and General Terms
|
|
195
|
+
|
|
196
|
+
Historical releases and third-party material. This License does not revoke, replace, or restrict rights validly granted under another license. Those rights and obligations remain governed by their own terms. Publishing this file does not relicense third-party code or earlier Contributions. The Licensor's grants extend only to rights it controls; applicable third-party licenses and notices remain effective.
|
|
197
|
+
|
|
198
|
+
Independent legal and platform rights. Nothing here restricts fair use, fair dealing, mandatory interoperability or research exceptions, non-waivable rights, or acts not requiring permission under applicable law. Nothing here revokes rights separately granted by the Licensor through repository-hosting terms, including applicable on-platform viewing, copying, forking, or processing permissions. Such rights remain limited to their own valid scope; this License does not enlarge them or independently grant unrestricted off-platform exploitation.
|
|
199
|
+
|
|
200
|
+
Fixed version. This document is Mother of Licenses 1.0. Future license versions may be published but do not automatically apply to material released under this version. A valid existing MoL-1.0 grant is not withdrawn merely by publication of different terms. You may elect another license only where the relevant rights holder validly offers it.
|
|
201
|
+
|
|
202
|
+
Interpretation. No governing law, forum, or arbitration agreement is selected here; applicable conflict-of-laws and jurisdiction rules determine those matters. If a provision is unenforceable, it is limited or severed only as required by applicable law, without expanding the remaining grants. Failure to enforce a provision is not a continuing waiver. Notices may be delivered through a designated licensing contact or another written channel providing reasonable evidence of receipt.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
function e(e){return typeof e==`object`&&!!e}function t(e,t){return e<t?-1:+(e>t)}const n=`moyodb:worker-protocol:response`,r=/* @__PURE__ */ `open.close.destroy.deleteDB.begin.commit.rollback.autocommit.createStore.dropStore.clearStore.get.getMany.has.put.putMany.delete.deleteMany.applyBatch.scan.getByIndex.scanByIndex.scanByIndexPage.getIndexes.reconcileIndexes.listStores.getVersion.changesSince.setSchemaVersion.exportSnapshot.importSnapshot.reset.compact.rebuild.stats.storageInfo.requestPersistence.setFailpoint`.split(`.`),i=/* @__PURE__ */ new Set([`get`,`getMany`,`has`,`put`,`putMany`,`delete`,`deleteMany`,`applyBatch`,`scan`,`getByIndex`,`scanByIndex`,`createStore`,`dropStore`,`clearStore`]);function a(e){return typeof e==`string`&&i.has(e)}const o=`moyodb:packed-binary-list:v1`,s=`moyodb:packed-batch-ops:v1`,c=`moyodb:packed-optional-values:v1`,l=4294967295,u=16777216,d=[],f=new Set(r);function p(e){return typeof e==`string`&&f.has(e)}function m(t){return e(t)&&t.type===`moyodb:worker-protocol:request`&&t.version===1&&typeof t.id==`number`&&Number.isSafeInteger(t.id)&&typeof t.command==`string`&&Array.isArray(t.args)}function ee(e){return te(e,`moyodb:worker-protocol:request-batch`,`requests`)}function te(t,n,r){return e(t)&&t.type===n&&t.version===1&&Array.isArray(t[r])&&t[r].length>0&&t[r].length<=128}function ne(t){return e(t)&&(t.type===`moyodb:worker-protocol:request`||t.type===`moyodb:worker-protocol:response`||t.type===`moyodb:worker-protocol:request-batch`||t.type===`moyodb:worker-protocol:response-batch`||t.type===`moyodb:worker-protocol:ready`)}function re(t){if(e(t)){let e=x(t.code);return{name:x(t.name)??e??`Error`,code:e,message:x(t.message)??`Unknown error`,stack:x(t.stack)}}return{name:`Error`,message:String(t)}}function h(e,t,n=e){let r=Error(t);return r.name=e,Object.defineProperty(r,"code",{value:n,enumerable:!0,configurable:!0}),r}function ie(e,t){if(e===`autocommit`){let[e,n,r]=t;if(a(n)&&Array.isArray(r))return[e,n,ie(n,[0,...r]).slice(1)]}if(e===`getMany`||e===`deleteMany`){let[e,n,r]=t;if(!Array.isArray(r)){if(!Ee(r))throw h(`WorkerProtocolError`,`invalid packed binary-list argument`);return[e,n,ye(r)]}}if(e===`putMany`){let[e,n,r,i]=t;if(!Array.isArray(r)){if(!Ee(r))throw h(`WorkerProtocolError`,`invalid packed putMany argument`);return[e,n,be(r),i]}}if(e===`applyBatch`){let[e,n,r]=t;if(!Array.isArray(r)){if(!De(r))throw h(`WorkerProtocolError`,`invalid packed batch argument`);return[e,n,we(r)]}}return t}function ae(e){return Ee(e)?e.bytes:null}function oe(e){return De(e)?e.bytes:null}function se(e){return ye({__moyodbPacked:o,bytes:e})}function ce(e){return be({__moyodbPacked:o,bytes:e})}function le(e){return xe({__moyodbPacked:o,bytes:e})}function ue(e){return we({__moyodbPacked:s,bytes:e})}function de(e){return Te({__moyodbPacked:s,bytes:e})}function fe(e){return{__moyodbPacked:c,bytes:e}}function pe(e){if(!(e instanceof Uint8Array)||e.byteLength<4)throw h(`WorkerProtocolError`,`invalid packed optional-values payload`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=y(4,v(n,4,`packed optional-values metadata`),`packed optional-values header`);if(r>e.byteLength)throw h(`WorkerProtocolError`,`packed optional-values metadata exceeds payload length`);let i=Array(n),a=r;for(let r=0;r<n;r+=1){let n=t.getUint32(4+r*4,!0);if(n===l){i[r]=null;continue}let o=a+n;if(o>e.byteLength)throw h(`WorkerProtocolError`,`packed optional-values item exceeds payload length`);i[r]=e.subarray(a,o),a=o}if(a!==e.byteLength)throw h(`WorkerProtocolError`,`packed optional-values payload has trailing bytes`);return i}function me(t,n){if(t===`getMany`&&Oe(n))return{result:n,transfer:_e(n.bytes)};if(t===`scanByIndexPage`){let t=n;if(e(t)&&Array.isArray(t.rows)){let e=t.rows.length>0?Ce(t.rows):null,n={rows:e??t.rows,cursor:t.cursor},r=e?[e.bytes.buffer]:he(t.rows),i=g(t.cursor);return{result:n,transfer:i===null?r:[...r,i]}}}if(t===`getMany`){let e=n;if(Array.isArray(e)&&e.length>0){let t=Se(e);if(t)return{result:t,transfer:[t.bytes.buffer]}}return{result:n,transfer:he(n)}}if(t===`scan`||t===`scanByIndex`){let e=n;if(Array.isArray(e)&&e.length>0){let t=Ce(e);if(t)return{result:t,transfer:[t.bytes.buffer]}}return{result:n,transfer:he(n)}}return t===`get`||t===`getByIndex`||t===`exportSnapshot`?{result:n,transfer:_e(n)}:t===`changesSince`?{result:n,transfer:ve(n)}:{result:n,transfer:[]}}function he(e){let t=g(e);if(t!==null)return[t];if(typeof e!=`object`||!e)return d;let n=/* @__PURE__ */ new Set;return _(e,n,/* @__PURE__ */ new WeakSet),n.size===0?d:Array.from(n)}function ge(e,t){let n=t.length>0?structuredClone(e,{transfer:t.length===1?t:Array.from(new Set(t))}):structuredClone(e),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new WeakSet,a=0,o=e=>{if(typeof e==`string`){a+=8+e.length*2;return}if(typeof e!=`object`||!e){a+=8;return}if(!i.has(e)){if(i.add(e),a+=8,e instanceof ArrayBuffer)r.add(e),a+=e.byteLength;else if(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)a+=e.byteLength;else if(ArrayBuffer.isView(e))o(e.buffer);else if(Array.isArray(e))for(let t of e)o(t);else if(e instanceof Map)for(let[t,n]of e)o(t),o(n);else if(e instanceof Set)for(let t of e)o(t);else{let t=e;for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(a+=8+e.length*2,o(t[e]))}}};return o(n),{value:n,transfer:r.size===0?d:Array.from(r),byteLength:a}}function _e(e){let t=g(e);return t===null?d:[t]}function g(e){if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e)){let t=e.buffer;if(t instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===t.byteLength)return t}return null}function ve(t){if(!e(t)||!Array.isArray(t.changes)||t.changes.length===0)return d;let n=null;for(let r of t.changes){if(!e(r))continue;let t=g(r.key);t!==null&&(n??=/* @__PURE__ */ new Set,n.add(t));let i=g(r.value);i!==null&&(n??=/* @__PURE__ */ new Set,n.add(i))}return n===null||n.size===0?d:Array.from(n)}function _(e,t,n){if(e==null)return;if(e instanceof ArrayBuffer){t.add(e);return}if(ArrayBuffer.isView(e)){let n=e.buffer;n instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===n.byteLength&&t.add(n);return}if(typeof e!=`object`)return;let r=e;if(n.has(r))return;if(n.add(r),Array.isArray(e)){for(let r of e)_(r,t,n);return}let i=e;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&_(i[e],t,n)}function ye(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw h(`WorkerProtocolError`,`invalid packed binary-list payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0),i=y(4,v(r,4,`packed binary-list metadata`),`packed binary-list header`);if(i>t.byteLength)throw h(`WorkerProtocolError`,`packed binary-list metadata exceeds payload length`);let a=Array(r),o=4,s=i;for(let e=0;e<r;e+=1){let r=n.getUint32(o,!0);o+=4;let i=s+r;if(i>l||i>t.byteLength)throw h(`WorkerProtocolError`,`packed binary-list item exceeds payload length`);a[e]=t.subarray(s,i),s=i}if(s!==t.byteLength)throw h(`WorkerProtocolError`,`packed binary-list payload has trailing bytes`);return a}function be(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw h(`WorkerProtocolError`,`invalid packed putMany payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0);if(r%2!=0)throw h(`WorkerProtocolError`,`packed putMany payload has an odd item count`);let i=y(4,v(r,4,`packed putMany metadata`),`packed putMany header`);if(i>t.byteLength)throw h(`WorkerProtocolError`,`packed putMany metadata exceeds payload length`);let a=r/2,o=Array(a),s=4,c=i;for(let e=0;e<a;e+=1){let r=n.getUint32(s,!0),i=n.getUint32(s+4,!0);s+=8;let a=c+r;if(a>l||a>t.byteLength)throw h(`WorkerProtocolError`,`packed putMany key exceeds payload length`);let u=a+i;if(u>l||u>t.byteLength)throw h(`WorkerProtocolError`,`packed putMany value exceeds payload length`);o[e]=[t.subarray(c,a),t.subarray(a,u)],c=u}if(c!==t.byteLength)throw h(`WorkerProtocolError`,`packed putMany payload has trailing bytes`);return o}function xe(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw h(`WorkerProtocolError`,`invalid packed putMany payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0);if(r%2!=0)throw h(`WorkerProtocolError`,`packed putMany payload has an odd item count`);let i=y(4,v(r,4,`packed putMany metadata`),`packed putMany header`);if(i>t.byteLength)throw h(`WorkerProtocolError`,`packed putMany metadata exceeds payload length`);let a=r/2,o=Array(a),s=4,c=i;for(let e=0;e<a;e+=1){let r=n.getUint32(s,!0),i=n.getUint32(s+4,!0);s+=8;let a=c+r;if(a>l||a>t.byteLength)throw h(`WorkerProtocolError`,`packed putMany key exceeds payload length`);let u=a+i;if(u>l||u>t.byteLength)throw h(`WorkerProtocolError`,`packed putMany value exceeds payload length`);o[e]=t.subarray(c,a),c=u}if(c!==t.byteLength)throw h(`WorkerProtocolError`,`packed putMany payload has trailing bytes`);return o}function Se(e){let t=e.length,n=v(t,5,`packed nullable binary-list metadata`),r=0;for(let n=0;n<t;n+=1){let t=e[n];if(t===null)continue;if(!(t instanceof Uint8Array))throw h(`WorkerProtocolError`,`nullable binary-list payload item is not a Uint8Array or null`);let i=b(t.byteLength,`nullable binary-list item length`);if(r+=i,r>l)throw h(`WorkerProtocolError`,`packed nullable binary-list payload exceeds 32-bit payload limit`)}let i=y(4,n,`packed nullable binary-list header`),a=y(i,r,`packed nullable binary-list total`);if(a>u)return null;let o=new Uint8Array(a),s=new DataView(o.buffer);s.setUint32(0,t,!0);let c=4,d=i;for(let n=0;n<t;n+=1){let t=e[n];if(t===null){s.setUint8(c,0),s.setUint32(c+1,0,!0),c+=5;continue}let r=t.byteLength;s.setUint8(c,1),s.setUint32(c+1,r,!0),c+=5,o.set(t,d),d+=r}return{__moyodbPacked:`moyodb:packed-nullable-binary-list:v1`,bytes:o}}function Ce(t){let n=t.length,r=v(n,8,`packed scan row metadata`),i=0;for(let r=0;r<n;r+=1){let n=t[r];if(!e(n)||!(n.key instanceof Uint8Array)||!(n.value instanceof Uint8Array))throw h(`WorkerProtocolError`,`scan row payload key/value is not a Uint8Array`);let a=b(n.key.byteLength,`scan row key length`),o=b(n.value.byteLength,`scan row value length`);if(i+=a+o,i>l)throw h(`WorkerProtocolError`,`packed scan row payload exceeds 32-bit payload limit`)}let a=y(4,r,`packed scan row header`),o=y(a,i,`packed scan row total`);if(o>u)return null;let s=new Uint8Array(o),c=new DataView(s.buffer);c.setUint32(0,n,!0);let d=4,f=a;for(let e=0;e<n;e+=1){let n=t[e],r=n.key,i=n.value,a=r.byteLength,o=i.byteLength;c.setUint32(d,a,!0),c.setUint32(d+4,o,!0),d+=8,s.set(r,f),f+=a,s.set(i,f),f+=o}return{__moyodbPacked:`moyodb:packed-scan-rows:v1`,bytes:s}}function we(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw h(`WorkerProtocolError`,`invalid packed batch payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0),i=y(4,v(r,9,`packed batch metadata`),`packed batch header`);if(i>t.byteLength)throw h(`WorkerProtocolError`,`packed batch metadata exceeds payload length`);let a=Array(r),o=4,s=i;for(let e=0;e<r;e+=1){let r=n.getUint8(o),i=n.getUint32(o+1,!0),c=n.getUint32(o+5,!0);o+=9;let u=s+i;if(u>l||u>t.byteLength)throw h(`WorkerProtocolError`,`packed batch key exceeds payload length`);let d=t.subarray(s,u);if(s=u,r===0){if(c!==0)throw h(`WorkerProtocolError`,`packed delete operation has a value payload`);a[e]={kind:`delete`,key:d};continue}if(r!==1)throw h(`WorkerProtocolError`,`packed batch operation has invalid kind byte: ${r}`);let f=s+c;if(f>l||f>t.byteLength)throw h(`WorkerProtocolError`,`packed batch value exceeds payload length`);a[e]={kind:`put`,key:d,value:t.subarray(s,f)},s=f}if(s!==t.byteLength)throw h(`WorkerProtocolError`,`packed batch payload has trailing bytes`);return a}function Te(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw h(`WorkerProtocolError`,`invalid packed batch payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0),i=y(4,v(r,9,`packed batch metadata`),`packed batch header`);if(i>t.byteLength)throw h(`WorkerProtocolError`,`packed batch metadata exceeds payload length`);let a=Array(r),o=4,s=i;for(let e=0;e<r;e+=1){let r=n.getUint8(o),i=n.getUint32(o+1,!0),c=n.getUint32(o+5,!0);o+=9;let u=s+i;if(u>l||u>t.byteLength)throw h(`WorkerProtocolError`,`packed batch key exceeds payload length`);let d=t.subarray(s,u);if(s=u,r===0){if(c!==0)throw h(`WorkerProtocolError`,`packed delete operation has a value payload`);a[e]={kind:`delete`,key:d};continue}if(r!==1)throw h(`WorkerProtocolError`,`packed batch operation has invalid kind byte: ${r}`);let f=s+c;if(f>l||f>t.byteLength)throw h(`WorkerProtocolError`,`packed batch value exceeds payload length`);a[e]={kind:`put`,key:d},s=f}if(s!==t.byteLength)throw h(`WorkerProtocolError`,`packed batch payload has trailing bytes`);return a}function Ee(t){return e(t)&&t.__moyodbPacked===o&&t.bytes instanceof Uint8Array}function De(t){return e(t)&&t.__moyodbPacked===s&&t.bytes instanceof Uint8Array}function Oe(t){return e(t)&&t.__moyodbPacked===c&&t.bytes instanceof Uint8Array}function v(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw h(`WorkerProtocolError`,`${n} count is invalid: ${e}`);return b(e*t,n)}function y(e,t,n){return b(e+t,n)}function b(e,t){if(!Number.isSafeInteger(e)||e<0||e>l)throw h(`WorkerProtocolError`,`${t} exceeds 32-bit payload limit`);return e}function x(e){return typeof e==`string`?e:void 0}const ke=/* @__PURE__ */ new Set([`commit`,`rollback`,`createStore`,`dropStore`,`clearStore`,`get`,`getMany`,`has`,`put`,`putMany`,`delete`,`deleteMany`,`applyBatch`,`scan`,`getByIndex`,`scanByIndex`,`scanByIndexPage`,`reconcileIndexes`,`setSchemaVersion`]),Ae=/* @__PURE__ */ new Set([`open`,`close`,`destroy`,`importSnapshot`,`reset`,`compact`,`rebuild`]),je=/* @__PURE__ */ new Set([`deleteDB`,`storageInfo`,`requestPersistence`]),S=()=>{};var Me=class{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Set;#n=Promise.resolve();schedule(e,t,n){return je.has(e)?n():Ae.has(e)?this.#i(n):this.#r(Ne(e,t),n)}#r(e,t){let n=this.#n,r=e===null?void 0:this.#e.get(e),i=(async()=>(await n,r&&await r,t()))(),a=i.then(S,S);return this.#t.add(a),e!==null&&this.#e.set(e,a),a.then(()=>{this.#t.delete(a),e!==null&&this.#e.get(e)===a&&this.#e.delete(e)}),i}#i(e){let t=this.#n,n=Array.from(this.#t),r=(async()=>(await t,await Promise.all(n),e()))();return this.#n=r.then(S,S),r}};function Ne(e,t){return ke.has(e)&&typeof t[0]==`number`?t[0]:e===`autocommit`&&t[0]===`readwrite`?`autocommit:readwrite`:null}var Pe=class{scope;queued=[];queuedBytes=0;flushScheduled=!1;flushChannel=null;closed=!1;constructor(e){this.scope=e}enqueue=(e,t=[])=>{if(this.closed)return;let n=ge(e,t);this.queued.length>0&&this.queuedBytes+n.byteLength>1048576&&this.flush(),this.queued.push({response:n.value,transfer:n.transfer}),this.queuedBytes+=n.byteLength,this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>{if(this.closed||this.queued.length===0){this.flushScheduled=!1;return}this.flushChannel??=this.createFlushChannel(),this.flushChannel.port2.postMessage(null)})),(this.queued.length>=128||this.queuedBytes>=1048576)&&this.flush()};close(){this.closed=!0,this.queued=[],this.queuedBytes=0,this.flushChannel?.port1.close(),this.flushChannel?.port2.close(),this.flushChannel=null}createFlushChannel(){let e=new MessageChannel;return e.port1.addEventListener(`message`,()=>{this.flushScheduled=!1,this.flush()}),e.port1.start(),e}flush(){let e=this.queued;if(this.queued=[],this.queuedBytes=0,this.closed||e.length===0)return;let t=e.length===1?e[0].response:{type:`moyodb:worker-protocol:response-batch`,version:1,responses:e.map(e=>e.response)},n=[];for(let t of e)for(let e of t.transfer)n.push(e);He(this.scope,t,n)}};function Fe(e,t=self){let n=new Me,r=new Pe(t),i=i=>{if(i.origin===``||i.origin===t.location.origin){if(ee(i.data)){let a=i.data.requests.length,o=(e,t)=>{r.enqueue(e,t),--a,a===0&&r.flush()};for(let r of i.data.requests)Ie(t,e,n,r,o);return}Ie(t,e,n,i.data)}};return t.addEventListener(`message`,i),t.postMessage({type:`moyodb:worker-protocol:ready`,version:1,batching:1}),{close(){t.removeEventListener(`message`,i),r.close()}}}async function Ie(e,t,n,r,i=(t,n)=>He(e,t,n)){if(!ne(r))return;let o=typeof r.id==`number`&&Number.isSafeInteger(r.id)?r.id:0;if(!m(r)){i(C(o,h(`WorkerProtocolError`,`invalid worker protocol request`)));return}if(!p(r.command)){i(C(r.id,h(`WorkerProtocolError`,`unsupported worker command: ${String(r.command)}`)));return}let s=r.command,c=r.args;try{let e=s,o;if(s===`autocommit`){let[n,r,i]=c;if(n!==`readonly`&&n!==`readwrite`||!a(r)||!Array.isArray(i))throw h(`WorkerProtocolError`,`invalid autocommit request`);Le(t,r),e=r,o=()=>ze(t,n,r,i)}else Le(t,s),o=()=>Re(t,s,c);let l=await n.schedule(s,c,o),u=me(e,l);i(Ve(r.id,u.result),u.transfer)}catch(e){i(C(r.id,e))}}function Le(e,t){if(typeof e[t]!=`function`)throw h(`WorkerProtocolError`,`worker command is not implemented: ${t}`)}function Re(e,t,n){let r=Be(e,t,n);return r===null?e[t].apply(e,ie(t,n)):r}async function ze(e,t,n,r){let i=await e.begin(t),a;try{a=await Re(e,n,[i,...r])}catch(t){try{await e.rollback(i)}catch{}throw t}return t===`readwrite`?await e.commit(i):await e.rollback(i),a}function Be(e,t,n){let r=e;if(t===`getMany`||t===`deleteMany`){let[e,i,a]=n;if(typeof e!=`number`||typeof i!=`string`)return null;let o=ae(a);return o===null?null:t===`getMany`&&typeof r.getManyPacked==`function`?r.getManyPacked(e,i,o):t===`deleteMany`&&typeof r.deleteManyPacked==`function`?r.deleteManyPacked(e,i,o):null}if(t===`putMany`){let[e,t,i,a]=n;if(typeof e!=`number`||typeof t!=`string`||typeof r.putManyPacked!=`function`)return null;let o=ae(i);return o===null?null:r.putManyPacked(e,t,o,a)}if(t===`applyBatch`){let[e,t,i]=n;if(typeof e!=`number`||typeof t!=`string`||typeof r.applyBatchPacked!=`function`)return null;let a=oe(i);return a===null?null:r.applyBatchPacked(e,t,a)}return null}function Ve(e,t){return{type:n,version:1,id:e,ok:!0,result:t}}function C(e,t){return{type:n,version:1,id:e,ok:!1,error:re(t)}}function He(e,t,n=[]){if(n.length>0)try{e.postMessage(t,n);return}catch{}e.postMessage(t)}const Ue=new TextEncoder;new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});const We=BigInt(`0xffffffffffffffff`);function w(e){return Ue.encode(e)}function Ge(e){return Je(e)}function T(e){return Ye(e)}function Ke(e){let t=[],n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==0){n.push(i);continue}let a=e[r+1];if(a===255){n.push(0),r+=1;continue}if(a===0){t.push(Uint8Array.from(n)),n.length=0,r+=1;continue}throw TypeError(`invalid compound key encoding`)}if(n.length!==0)throw TypeError(`compound key terminated unexpectedly`);return t}function E(e){let t=e.slice();for(let e=t.length-1;e>=0;--e)if(t[e]!==255)return t[e]+=1,t.subarray(0,e+1);return null}function qe(e){let t=E(e);return t?{gte:e,lt:t}:{gte:e}}function Je(e){if(e===null)return Uint8Array.of(16);if(typeof e==`boolean`)return Uint8Array.of(e?33:32);if(typeof e==`number`)return Xe(e);if(typeof e==`string`){for(let t of e){let e=t.codePointAt(0);if(e>=55296&&e<=57343)throw TypeError(`compound key string parts must contain valid Unicode scalar values`)}let t=w(e),n=new Uint8Array(1+t.length);return n[0]=64,n.set(t,1),n}if(e instanceof Uint8Array){let t=new Uint8Array(1+e.length);return t[0]=80,t.set(e,1),t}throw TypeError(`compound key parts must be string, number, boolean, null, or Uint8Array`)}function Ye(e){let t=0;for(let n of e){for(let e of n)t+=e===0?2:1;t+=2}let n=new Uint8Array(t),r=0;for(let t of e){for(let e of t)e===0?(n[r]=0,n[r+1]=255,r+=2):(n[r]=e,r+=1);n[r]=0,n[r+1]=0,r+=2}return n}function Xe(e){if(!Number.isFinite(e))throw TypeError(`compound key number parts must be finite`);let t=Object.is(e,-0)?0:e,n=/* @__PURE__ */ new ArrayBuffer(9),r=new DataView(n);r.setUint8(0,48),r.setFloat64(1,t,!1);let i=r.getBigUint64(1,!1);return i=(i&1n<<63n)==0n?i^1n<<63n:~i&We,r.setBigUint64(1,i,!1),new Uint8Array(n)}const D=w(`BDBZVAL1`),Ze=w(`BDBZSNP1`),O=8388608,Qe=268435456,$e=(()=>{let e=/* @__PURE__ */ new Uint32Array(256);for(let t=0;t<256;t+=1){let n=t;for(let e=0;e<8;e+=1)n&1?n=n>>>1^3988292384:n>>>=1;e[t]=n>>>0}return e})();function k(e,t){let n=Error(t);return n.name=e,n}function et(e){switch(e){case!1:return 0;case`gzip`:return 1;case`deflate`:return 2;default:throw k(`InternalError`,`unsupported compression kind: ${String(e)}`)}}function tt(e){switch(e){case 0:return!1;case 1:return`gzip`;case 2:return`deflate`;default:throw k(`CorruptionError`,`invalid compression tag: ${e}`)}}function nt(){return k(`UnsupportedPlatformError`,`CompressionStream and DecompressionStream are required for moyodb compression`)}function rt(){if(typeof CompressionStream!=`function`||typeof DecompressionStream!=`function`)throw nt()}function it(e){let t=4294967295;for(let n of e)t=t>>>8^$e[(t^n)&255];return(t^4294967295)>>>0}function A(e,t,n,r){let i=new Uint8Array(18+r.byteLength);i.set(e,0),i[8]=1,i[9]=t;let a=new DataView(i.buffer,i.byteOffset,18);return a.setUint32(10,n,!0),a.setUint32(14,it(r),!0),i.set(r,18),i}function at(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function ot(e){let t=0;return new ReadableStream({pull(n){if(t<e.byteLength){let r=Math.min(t+65536,e.byteLength);n.enqueue(e.subarray(t,r)),t=r}t===e.byteLength&&n.close()}})}function st(e,t,n=!0){if(t.byteLength<e.byteLength)return null;for(let n=0;n<e.byteLength;n+=1)if(t[n]!==e[n])return null;if(t.byteLength<18){if(n)throw k(`CorruptionError`,`truncated compression envelope: expected at least 18 bytes, got ${t.byteLength}`);return null}let r=new DataView(t.buffer,t.byteOffset,18);return{version:t[8],kindTag:t[9],rawLength:r.getUint32(10,!0),payloadChecksum:r.getUint32(14,!0)}}async function ct(e,t){rt();let n;try{n=ot(e).pipeThrough(new CompressionStream(t))}catch{throw nt()}try{return new Uint8Array(await new Response(n).arrayBuffer())}catch(e){throw k(`InternalError`,`failed to compress bytes with ${t}: ${String(e)}`)}}async function lt(e,t,n,r){rt();let i;try{i=ot(at(e)).pipeThrough(new DecompressionStream(t))}catch{throw nt()}try{return await ut(i,n,r)}catch(e){throw k(`CorruptionError`,`failed to decompress ${n}: ${String(e)}`)}}async function ut(e,t,n){let r=e.getReader(),i=[],a=0;try{for(let e=await r.read();!e.done;e=await r.read()){let o=e.value;if(a+=o.byteLength,n!==void 0&&a>n)throw await r.cancel(`decompressed ${t} exceeded ${n} bytes`),k(`CorruptionError`,`decompressed ${t} exceeds ${n} byte limit`);i.push(o)}}finally{r.releaseLock()}if(i.length===1)return i[0];let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function dt(e){let t=(e&12)>>>2;switch(t){case 0:return!1;case 1:return`gzip`;case 2:return`deflate`;default:throw k(`CorruptionError`,`invalid store compression flags: ${t}`)}}async function ft(e,t){if(t===!1)return e;if(e.byteLength>O)throw k(`ValueTooLargeError`,`value has ${e.byteLength} bytes, exceeding the ${O} byte limit`);if(e.byteLength<1024)return A(D,0,e.byteLength,e);let n=at(e),r=await ct(n,t);return r.byteLength>=n.byteLength?A(D,0,n.byteLength,n):A(D,et(t),n.byteLength,r)}async function pt(e,t){let n=st(D,e,t.strict);if(!n)return e;if(n.version!==1){if(t.strict)throw k(`CorruptionError`,`unsupported value record version: ${n.version}`);return e}let r;try{r=tt(n.kindTag)}catch(n){if(t.strict)throw n;return e}let i=e.subarray(18);if(it(i)!==n.payloadChecksum){if(t.strict)throw k(`CorruptionError`,`value record checksum mismatch`);return e}if(r===!1){if(i.byteLength!==n.rawLength){if(t.strict)throw k(`CorruptionError`,`value record length mismatch: expected ${n.rawLength} bytes, got ${i.byteLength}`);return e}return i.slice()}if(n.rawLength>O)throw k(`CorruptionError`,`compressed value advertises ${n.rawLength} decompressed bytes, exceeding the ${O} byte limit`);let a=await lt(i,r,`value record (${r})`,n.rawLength);if(a.byteLength!==n.rawLength)throw k(`CorruptionError`,`decompressed value length mismatch: expected ${n.rawLength} bytes, got ${a.byteLength}`);return a}async function mt(e,t){if(t===!1)return e;let n=at(e),r=await ct(n,t);return A(Ze,et(t),n.byteLength,r)}async function ht(e){let t=st(Ze,e);if(!t)return e;if(t.version!==1)throw k(`CorruptionError`,`unsupported snapshot compression version: ${t.version}`);let n=tt(t.kindTag);if(n===!1)throw k(`CorruptionError`,`snapshot compression envelope cannot store kind "none"`);let r=e.subarray(18);if(it(r)!==t.payloadChecksum)throw k(`CorruptionError`,`snapshot compression checksum mismatch`);if(t.rawLength>Qe)throw k(`CorruptionError`,`compressed snapshot advertises ${t.rawLength} decompressed bytes, exceeding the ${Qe} byte limit`);let i=await lt(r,n,`snapshot export (${n})`,t.rawLength);if(i.byteLength!==t.rawLength)throw k(`CorruptionError`,`decompressed snapshot length mismatch: expected ${t.rawLength} bytes, got ${i.byteLength}`);return i}var gt=class extends Error{constructor(e,t){super(t),this.name=e,Object.setPrototypeOf(this,new.target.prototype)}},_t=class extends gt{constructor(e){super(`ReservedStoreNameError`,e)}},j=class extends gt{constructor(e){super(`SerializationError`,e)}},M=class extends gt{constructor(e){super(`InvalidOpenOptionsError`,e)}};const vt=new TextEncoder,yt=new TextDecoder(`utf-8`,{fatal:!0}),N=Symbol(`moyodb.indexing.missing`),bt=BigInt(`0xcbf29ce484222325`),xt=BigInt(`0x100000001b3`),St=BigInt(`0xffffffffffffffff`),Ct=`__browserdb:index:`,P=`__browserdb:indexes`;function F(e){return e.startsWith(`__browserdb:`)}function wt(e){if(F(e))throw new _t(`reserved store name: ${e}`)}function I(e){if(e===void 0)return[];if(!Array.isArray(e))throw new M(`indexes must be an array`);let t=[],n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map;for(let i of e){if(typeof i!=`object`||!i||Array.isArray(i))throw new M(`each index definition must be an object`);let{store:e,name:a,keyPath:o,unique:s}=i;if(typeof e!=`string`||e.length===0)throw new M(`index store must be a non-empty string`);if(typeof a!=`string`||a.length===0)throw new M(`index name must be a non-empty string`);wt(e);let c=It(o);if(s!==void 0&&typeof s!=`boolean`)throw new M(`index unique must be a boolean`);let l={store:e,name:a,keyPath:c.paths,compound:c.compound,unique:s??!1,internalStore:zt(e,a)},u=Et(l.store,l.name);if(n.has(u))throw new M(`duplicate index definition ${l.store}.${l.name}`);n.add(u);let d=r.get(l.internalStore);if(d&&d!==u)throw new M(`index definitions ${d} and ${u} map to the same internal store ${l.internalStore}`);r.set(l.internalStore,u),t.push(l)}return t.sort(Tt),t}function Tt(e,n){let r=t(e.store,n.store);if(r!==0)return r;let i=t(e.name,n.name);if(i!==0)return i;let a=Number(e.unique)-Number(n.unique);return a===0?t(Rt(e),Rt(n)):a}function Et(e,t){return JSON.stringify([e,t])}function Dt(e,t,n){return e.find(e=>e.store===t&&e.name===n)??null}function Ot(e,t){return T([w(e),w(t)])}function kt(e){return w(JSON.stringify(Ft(e)))}function At(e){let t;try{t=JSON.parse(yt.decode(e));let[n]=I([t]);return n}catch(e){throw new j(`invalid persisted index metadata: ${String(e)}`)}}function jt(e,t){return T([e,t])}function L(e){let t;try{t=Ke(e)}catch(e){throw new j(`invalid index entry key encoding: ${String(e)}`)}if(t.length!==2)throw new j(`invalid index entry key encoding`);return{logicalKey:t[0],primaryKey:t[1]}}function Mt(e){return qe(T([e]))}function Nt(e={}){Gt(e);let t={};if(e.reverse!==void 0&&(t.reverse=e.reverse),e.limit!==void 0&&(t.limit=e.limit),e.gte&&(t.gte=T([e.gte])),e.gt){let n=E(T([e.gt]));n&&(t.gte=n)}if(e.lt&&(t.lt=T([e.lt])),e.lte){let n=E(T([e.lte]));n&&(t.lt=n)}return t}function Pt(e,t){return z(e,H(t))}function R(e){let t=!1,n;return r=>(t||=(n=H(e),!0),z(r,n))}function z(e,t){if(e.compound){let n=[];for(let r of e.keyPath){let e=Ht(t,r);if(e===N)return null;n.push(Ut(e))}return T(n)}let n=Ht(t,e.keyPath[0]);return n===N?null:Ut(n)}function B(e){return e.map(e=>({store:e.store,name:e.name,keyPath:[...e.keyPath],compound:e.compound,unique:e.unique,internalStore:e.internalStore}))}function V(e){return e.map(Ft)}function Ft(e){return{store:e.store,name:e.name,keyPath:e.compound?[...e.keyPath]:e.keyPath[0],unique:e.unique}}function It(e){if(typeof e==`string`)return Lt(e),{paths:[e],compound:!1};if(!Array.isArray(e)||e.length===0||!e.every(e=>typeof e==`string`))throw new M(`index keyPath must be a non-empty string or non-empty string[]`);for(let t of e)Lt(t);return{paths:[...e],compound:!0}}function Lt(e){if(e.length===0)throw new M(`index keyPath strings must be non-empty`);if(e.startsWith(`.`)||e.endsWith(`.`)||e.includes(`..`))throw new M(`invalid index keyPath: ${e}`)}function Rt(e){return e.compound?`[${e.keyPath.join(`,`)}]`:e.keyPath[0]}function zt(e,t){let n=Bt(w(e)),r=Bt(w(t)),i=`${Ct}${n}:${r}`;if(vt.encode(i).length<=255)return i;let a=w(`${e}\u0000${t}`);return`${Ct}h:${Vt(a)}`}function Bt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/u,``)}function Vt(e){let t=bt;for(let n of e)t^=BigInt(n),t=t*xt&St;return t.toString(16).padStart(16,`0`)}function H(e){try{return JSON.parse(yt.decode(e))}catch(e){throw new j(`indexed values must be valid UTF-8 JSON: ${String(e)}`)}}function Ht(e,t){let n=e;for(let e of t.split(`.`)){if(n==null)return N;let t=Object(n);if(!Object.hasOwn(t,e))return N;n=Reflect.get(t,e)}return n}function Ut(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Uint8Array)try{return Ge(e)}catch(e){throw e instanceof TypeError?new j(`invalid indexed keyPath value: ${e.message}`):e}throw new j(`indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${Wt(e)}`)}function Wt(e){return Array.isArray(e)?`array`:typeof e}function Gt(e){if(e.gt!==void 0&&e.gte!==void 0)throw TypeError(`index range cannot specify both gt and gte`);if(e.lt!==void 0&&e.lte!==void 0)throw TypeError(`index range cannot specify both lt and lte`)}function U(e){return BigInt(e)}function W(e){return typeof e==`bigint`?Number(e):e}function Kt(e){return e==null?null:W(e)}function G(e){return e.ttl===void 0?e:{...e,ttl:U(e.ttl)}}function qt(e){let t={};return e.gt!==void 0&&(t.gt=e.gt),e.gte!==void 0&&(t.gte=e.gte),e.lt!==void 0&&(t.lt=e.lt),e.lte!==void 0&&(t.lte=e.lte),e.reverse!==void 0&&(t.reverse=e.reverse),e.limit!==void 0&&(t.limit=e.limit),t}const Jt={},Yt=/* @__PURE__ */ new Uint8Array,Xt=4194304,Zt=4096,Qt=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function $t(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}function en(t){return e(t)&&t.type===`moyodb:persistence-bridge:response`&&typeof t.id==`number`&&typeof t.granted==`boolean`}var tn=class{port=null;nextRequestId=1;pending=/* @__PURE__ */ new Map;readyResolve=null;ready;constructor(){this.ready=new Promise(e=>{this.readyResolve=e}),self.addEventListener(`message`,this.handleInitMessage)}async persisted(){return this.request(`persisted`)}async persist(){return this.request(`persist`)}close(){self.removeEventListener(`message`,this.handleInitMessage),this.readyResolve&&=(this.readyResolve(null),null),this.port&&=(this.port.onmessage=null,this.port.close(),null);for(let e of this.pending.values())e.resolve(!1);this.pending.clear()}async request(e){let t=await this.ready;return!t||this.port!==t?!1:new Promise(n=>{let r=this.nextRequestId;this.nextRequestId+=1,this.pending.set(r,{resolve:n});let i={type:`moyodb:persistence-bridge:request`,id:r,op:e};try{t.postMessage(i)}catch{this.pending.delete(r),n(!1)}})}handleInitMessage=e=>{if(e.origin!==``&&e.origin!==self.location.origin||e.data?.type!==`moyodb:persistence-bridge:init`||e.ports.length===0)return;let t=e.ports[0];if(this.port){t.close();return}this.port=t,this.port.onmessage=this.handleResponse,this.port.start(),self.removeEventListener(`message`,this.handleInitMessage),this.readyResolve?.(t),this.readyResolve=null};handleResponse=e=>{let t=e.data;if(!en(t))return;let n=this.pending.get(t.id);n&&(this.pending.delete(t.id),n.resolve(!!t.granted))}};async function nn(){let e=navigator.storage;if(typeof e.estimate!=`function`)return{usage:0,quota:0};let t=await e.estimate();return{usage:t.usage??0,quota:t.quota??0}}function rn(e){let t=``;for(let n=0;n<e.byteLength;n+=1)t+=Qt[e[n]];return t}function K(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}function q(e){return e instanceof Uint8Array?e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e:e.slice():new Uint8Array(e)}function an(t){if(!e(t))return null;let n=t.name??t.code;return typeof n==`string`?n:null}function J(e,t){return an(e)===t}const Y=w(`BDBIDX1`),on=new TextDecoder(`utf-8`,{fatal:!0});function sn(e,t){if(t.length===0)return e;let n=w(JSON.stringify(V(t))),r=/* @__PURE__ */ new ArrayBuffer(4);new DataView(r).setUint32(0,n.byteLength,!0);let i=new Uint8Array(e.byteLength+n.byteLength+4+Y.byteLength),a=0;return i.set(e,a),a+=e.byteLength,i.set(n,a),a+=n.byteLength,i.set(new Uint8Array(r),a),a+=4,i.set(Y,a),i}function cn(e){let t=Y.byteLength;if(e.byteLength<t+4)return{snapshot:e,indexes:[]};let n=e.byteLength-t;if(!K(e.subarray(n),Y))return{snapshot:e,indexes:[]};let r=n-4;if(r<0)return{snapshot:e,indexes:[]};let i=r-new DataView(e.buffer,e.byteOffset+r,4).getUint32(0,!0);if(i<0)throw Z(`CorruptionError`,`invalid snapshot index trailer length`);let a;try{a=JSON.parse(on.decode(e.subarray(i,r)))}catch(e){throw Z(`CorruptionError`,`invalid snapshot index trailer: ${String(e)}`)}return{snapshot:e.subarray(0,i),indexes:I(a)}}function ln(e){return new BroadcastChannel(`db:${e}:events`)}function X(e,t){let n=ln(e);try{n.postMessage({type:t,dbName:e,txid:null})}finally{n.close()}}var un=class{releaseResolver=null;requestPromise=null;held=!1;async acquire(e,t){let n=new Promise(e=>{this.releaseResolver=e}),r=`db:${e}:owner`;if(t===0){let t=null,i=new Promise(e=>{t=e}),a=navigator.locks.request(r,{mode:`exclusive`,ifAvailable:!0},async e=>e?(this.held=!0,t?.(!0),await n,!0):(t?.(!1),!1));if(!await i)throw Z(`DatabaseBusyError`,`database ${e} is already owned by another tab`);this.requestPromise=a;return}let i=new AbortController,a=setTimeout(()=>i.abort(),t),o=null,s=new Promise(e=>{o=e});this.requestPromise=navigator.locks.request(r,{mode:`exclusive`,signal:i.signal},async e=>(clearTimeout(a),this.held=!0,o?.(),await n,!0));try{await Promise.race([s,this.requestPromise])}catch{if(!this.held)throw Z(`DatabaseBusyError`,`timed out waiting for ownership of ${e}`)}}async release(){if(this.held){this.releaseResolver?.();try{await this.requestPromise}finally{this.releaseResolver=null,this.requestPromise=null,this.held=!1}}}},dn=class{dbName=null;engine=null;events=null;lease=null;wasmReady=null;persistenceBridge=new tn;txChanges=/* @__PURE__ */ new Map;txModes=/* @__PURE__ */ new Map;txIndexSchemas=/* @__PURE__ */ new Map;indexesBySchema=/* @__PURE__ */ new WeakMap;txEnsuredRawStores=/* @__PURE__ */ new Map;txIndexSchemaChanged=/* @__PURE__ */ new Set;txStoreCompression=/* @__PURE__ */ new Map;committedIndexes=null;committedStoreCompression=null;openOptions=null;maintenanceOperation=null;async open(e){if(this.engine)return;pn(),fn(),this.dbName=e.dbName,this.events=new BroadcastChannel(`db:${e.dbName}:events`),this.lease=new un;let t=null;try{await this.lease.acquire(e.dbName,e.options.ownerWaitMs),t=new(await(this.loadWasm())).WasmEngine,await t.open(e.dbName,{create_if_missing:e.options.createIfMissing,cache_pages:e.options.cachePages}),e.options.changeFeed&&mn(t,e.options.changeFeed),e.options.debugFailpoint&&t.set_failpoint(e.options.debugFailpoint),this.engine=t,this.openOptions=e.options,this.clearRuntimeCaches(),this.maintenanceOperation=null,this.events.postMessage({type:`owner_changed`,dbName:e.dbName,txid:null})}catch(e){throw await this.cleanupAfterFailedOpen(t),$(e)}}async close(){this.ensureNotInMaintenance();let e=this.dbName;this.clearRuntimeCaches();try{this.engine?.close()}catch(e){throw $(e)}finally{this.engine=null,e&&this.events&&this.events.postMessage({type:`db_closed`,dbName:e,txid:null}),this.events?.close(),this.events=null,e&&this.lease&&await this.lease.release(),e&&X(e,`owner_changed`),this.disposePersistenceBridge(),this.lease=null,this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}}async destroy(){this.ensureNotInMaintenance();let e=this.dbName;if(!e)return;let t=null;try{this.rollbackAllTransactions(),this.engine?.abandon(),await(await this.loadWasm()).deleteDB(e),X(e,`db_deleted`)}catch(e){t=e}finally{if(this.engine=null,this.clearRuntimeCaches(),this.events?.close(),this.events=null,this.lease)try{await this.lease.release()}catch(e){t===null&&(t=e)}X(e,`owner_changed`),this.disposePersistenceBridge(),this.lease=null,this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}if(t!==null)throw $(t)}async deleteDB(e){pn(),fn();let t=new un,n=null,r=!1;try{await t.acquire(e,0),r=!0,await(await this.loadWasm()).deleteDB(e),X(e,`db_deleted`)}catch(e){n=e}finally{try{await t.release()}catch(e){n===null&&(n=e)}r&&X(e,`owner_changed`)}if(n!==null)throw $(n)}begin(e){this.recoverEngineIfNeeded();let t=this.loadCommittedIndexSchema(),n=this.loadCommittedStoreCompression(),r=W(this.withEngine(t=>t.begin_tx(e)));return this.txChanges.set(r,/* @__PURE__ */ new Map),this.txModes.set(r,e),this.txIndexSchemas.set(r,t),this.txStoreCompression.set(r,{owned:!1,values:n}),Promise.resolve(r)}commit(e){let t=this.txChanges.get(e)??/* @__PURE__ */ new Map,n=this.txIndexSchemaChanged.has(e)?this.txIndexSchemas.get(e):void 0,r=this.txStoreCompression.get(e),i=this.txModes.get(e),a;try{a=W(this.withEngine(t=>t.commit_tx(U(e))))}catch(t){try{this.engine&&!this.engine.needs_recovery()&&this.withEngine(t=>t.rollback_tx(U(e)))}catch{}this.cleanupTxState(e);let n=this.recoverEngineIfNeeded();if(!n?.pendingCommitted||n.pendingTxid===null||J(t,`RecoveryRequiredError`)||J(t,`InjectedFailureError`))throw t;a=n.pendingTxid}if(n&&(this.committedIndexes=B(n)),i===`readwrite`&&r&&(this.committedStoreCompression=r.values),this.cleanupTxState(e),this.dbName&&this.events){let e={type:`commit_applied`,dbName:this.dbName,txid:a,stores:this.finalizeTrackedChanges(t)};this.events.postMessage(e)}return Promise.resolve(a)}rollback(e){try{this.withEngine(t=>t.rollback_tx(U(e)))}finally{this.cleanupTxState(e)}return Promise.resolve()}async autocommit(e,t,n){let r=await this.begin(e),i=this[t],a;try{a=await i.apply(this,[r,...n])}catch(e){try{await this.rollback(r)}catch{}throw e}return e===`readwrite`?await this.commit(r):await this.rollback(r),a}createStore(e,t,n={}){let r=n.compression??!1;return this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.create_store(U(e),t,{compression:r})),this.recordStoreCompressionCreate(e,t,r),this.ensureInternalStoresForStore(e,t),this.markStoreTouched(e,t),Promise.resolve()}dropStore(e,t){let n=this.indexesForStoreInTx(e,t);this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.drop_store(U(e),t)),this.recordStoreCompressionDrop(e,t);for(let t of n)this.dropRawStoreIfExists(e,t.internalStore);return this.recordStoreLevelChange(e,t,`drop`),Promise.resolve()}clearStore(e,t){let n=this.indexesForStoreInTx(e,t);this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.clear_store(U(e),t));for(let t of n)this.clearRawStoreIfExists(e,t.internalStore);return this.recordStoreLevelChange(e,t,`clear`),Promise.resolve()}async get(e,t,n){return this.readStoreValue(e,t,n)}async getMany(e,t,n){let r=this.withEngine(r=>r.get_many(U(e),t,n)),i=!F(t)&&this.storeCompressionForTx(e,t)!==!1;for(let e=0;e<r.length;e+=1){let t=r[e];t!==null&&(r[e]=q(t))}return i?this.decodeStoreValues(e,t,r):r}async getManyPacked(e,t,n){let r=q(this.withEngine(r=>r.get_many_packed(U(e),t,n)));return F(t)||this.storeCompressionForTx(e,t)===!1?fe(r):this.decodeStoreValues(e,t,pe(r))}has(e,t,n){return Promise.resolve(this.withEngine(r=>r.has(U(e),t,n)))}async put(e,t,n,r,i={}){let a=this.indexesForStoreInTx(e,t);if(a.length===0){let a=await this.encodeStoreValueForWrite(e,t,r),o=this.withEngine(r=>r.put(U(e),t,n,a,G(i)));this.recordPutChange(e,t,n,o);return}let o=await this.readStoreValue(e,t,n),s=o===null?null:R(o),c=R(r),l=a.map(e=>({def:e,oldLogicalKey:s===null?null:s(e),newLogicalKey:c(e),newPhysicalKey:null}));this.ensureInternalStoresForDefinitions(e,a);for(let t of l)t.newLogicalKey!==null&&(t.newPhysicalKey=this.buildIndexEntryKey(t.def,t.newLogicalKey,n),!(t.oldLogicalKey!==null&&K(t.oldLogicalKey,t.newLogicalKey))&&await this.assertUniqueIndexAvailability(e,t.def,t.newLogicalKey,n));let u=await this.encodeStoreValueForWrite(e,t,r),d=this.withEngine(r=>r.put(U(e),t,n,u,G(i)));for(let t of l)t.oldLogicalKey!==null&&(t.newLogicalKey!==null&&K(t.oldLogicalKey,t.newLogicalKey)||this.deleteIndexEntryIfPresent(e,t.def,t.oldLogicalKey,n));for(let t of l)if(t.newLogicalKey!==null&&!(t.oldLogicalKey!==null&&K(t.oldLogicalKey,t.newLogicalKey))){if(t.newPhysicalKey===null)throw Z(`InternalError`,`missing index entry key`);this.putIndexEntry(e,t.def,t.newPhysicalKey,Yt)}this.recordPutChange(e,t,n,d)}async putMany(e,t,n,r={}){if(n.length!==0){if(this.indexesForStoreInTx(e,t).length===0){let i=await this.encodeEntriesForWrite(e,t,n),a;try{a=this.withEngine(n=>n.put_many(U(e),t,i,G(r)))}catch(r){let i=Q(r);throw this.recordPutChanges(e,t,n,i),r}if(a.length!==n.length)throw Z(`InternalError`,`put_many outcome count mismatch: ${a.length} != ${n.length}`);this.recordPutChanges(e,t,n,a);return}for(let[i,a]of n)await this.put(e,t,i,a,r)}}async putManyPacked(e,t,n,r={}){if(this.indexesForStoreInTx(e,t).length!==0||this.storeCompressionForTx(e,t)!==!1){await this.putMany(e,t,ce(n),r);return}let i=le(n);if(i.length===0)return;let a;try{a=this.withEngine(i=>i.put_many_packed(U(e),t,n,G(r)))}catch(n){let r=Q(n);throw this.recordPutKeyChanges(e,t,i,r),n}if(a.length!==i.length)throw Z(`InternalError`,`put_many_packed outcome count mismatch: ${a.length} != ${i.length}`);this.recordPutKeyChanges(e,t,i,a)}async delete(e,t,n){let r=this.indexesForStoreInTx(e,t),i=r.length===0?null:await this.readStoreValue(e,t,n),a=i===null?null:R(i),o=a===null?[]:r.map(e=>({def:e,logicalKey:a(e)}));if(!this.withEngine(r=>r.delete(U(e),t,n)))return this.recordDeleteChange(e,t,n,!1),!1;for(let t of o)t.logicalKey!==null&&this.deleteIndexEntryIfPresent(e,t.def,t.logicalKey,n);return this.recordDeleteChange(e,t,n,!0),!0}async deleteMany(e,t,n){if(n.length!==0){if(this.indexesForStoreInTx(e,t).length===0){let r;try{r=this.withEngine(r=>r.delete_many(U(e),t,n))}catch(r){let i=Q(r);for(let r=0;r<i.length&&r<n.length;r+=1)this.recordDeleteChange(e,t,n[r],i[r]);throw r}if(r.length!==n.length)throw Z(`InternalError`,`delete_many outcome count mismatch: ${r.length} != ${n.length}`);for(let i=0;i<n.length;i+=1)this.recordDeleteChange(e,t,n[i],r[i]);return}for(let r of n)await this.delete(e,t,r)}}async deleteManyPacked(e,t,n){let r=this.indexesForStoreInTx(e,t),i=se(n);if(i.length===0)return;if(r.length!==0){await this.deleteMany(e,t,i);return}let a;try{a=this.withEngine(r=>r.delete_many_packed(U(e),t,n))}catch(n){let r=Q(n);for(let n=0;n<r.length&&n<i.length;n+=1)this.recordDeleteChange(e,t,i[n],r[n]);throw n}if(a.length!==i.length)throw Z(`InternalError`,`delete_many_packed outcome count mismatch: ${a.length} != ${i.length}`);for(let n=0;n<i.length;n+=1)this.recordDeleteChange(e,t,i[n],a[n]===1)}async applyBatch(e,t,n){if(n.length!==0){if(this.indexesForStoreInTx(e,t).length===0){let r=await this.encodeBatchOpsForWrite(e,t,n),i;try{i=this.withEngine(n=>n.apply_batch(U(e),t,r))}catch(r){throw this.recordBatchOutcomes(e,t,n,_n(r)),r}if(i.length!==n.length)throw Z(`InternalError`,`apply_batch outcome count mismatch: ${i.length} != ${n.length}`);this.recordBatchOutcomes(e,t,n,i);return}for(let r of n)r.kind===`put`?await this.put(e,t,r.key,r.value):await this.delete(e,t,r.key)}}async applyBatchPacked(e,t,n){if(this.indexesForStoreInTx(e,t).length!==0||this.storeCompressionForTx(e,t)!==!1){let r=ue(n);if(r.length===0)return;await this.applyBatch(e,t,r);return}let r=de(n);if(r.length===0)return;let i;try{i=this.withEngine(r=>r.apply_batch_packed(U(e),t,n))}catch(n){throw this.recordBatchKeyOutcomes(e,t,r,_n(n)),n}if(i.length!==r.length)throw Z(`InternalError`,`apply_batch_packed outcome count mismatch: ${i.length} != ${r.length}`);for(let n=0;n<r.length;n+=1){let a=r[n];a.kind===`put`?this.recordPutChange(e,t,a.key,i[n]===1):this.recordDeleteChange(e,t,a.key,i[n]===1)}}async scan(e,t,n){return this.readStoreScan(e,t,n)}async getByIndex(e,t,n,r){let i=this.resolveIndexDefinition(e,t,n),a=await this.loadVisibleIndexPage(e,i,qe(r),null,1);return a.rows.length===0?null:a.rows[0].value}async scanByIndex(e,t,n,r={}){let i=this.resolveIndexDefinition(e,t,n),a=[],o=r.limit??1/0,s=null;for(;o>0;){let t=await this.loadVisibleIndexPage(e,i,r,s,Math.min(o,256));if(a.push(...t.rows),o-=t.rows.length,t.cursor===null)break;s=t.cursor}return a}async scanByIndexPage(e,t,n,r,i,a){if(!Number.isSafeInteger(a)||a<=0)throw Z(`InvalidRangeError`,`index scan page limit must be a positive integer`);let o=this.resolveIndexDefinition(e,t,n);return this.loadVisibleIndexPage(e,o,r,i,a)}getIndexes(){return Promise.resolve(V(this.loadCommittedIndexSchema()))}async reconcileIndexes(e,t){let n=I(t);this.ensureRawStore(e,P);let r=this.readIndexSchemaInTx(e),i=new Set(n.map(e=>e.internalStore));for(let t of r)i.has(t.internalStore)||this.dropRawStoreIfExists(e,t.internalStore);this.clearRawStoreIfExists(e,P);let a=null,o=0,s=null,c=typeof this.engine?.has_many==`function`,l=/* @__PURE__ */ new Map;for(let t of n){if(a!==t.store&&(l.clear(),o=0,s=null,a=t.store),this.ensureRawStore(e,t.internalStore),this.clearRawStoreIfExists(e,t.internalStore),this.rawStoreExistsInTx(e,t.store)){let n;if(s!==null){let r=this.withEngine(n=>n.has_many(U(e),t.store,s.map(e=>e.key)));if(r.length!==s.length)throw Z(`InternalError`,`has_many outcome count mismatch: ${r.length} != ${s.length}`);n=s.filter((e,t)=>r[t])}else if(n=await this.readStoreScan(e,t.store,Jt),c&&n.length<=Zt){let e=0;for(let t of n)if(e+=t.key.byteLength+t.value.byteLength,e>Xt)break;e<=Xt&&(s=n)}for(let r of n){let n=rn(r.key),i=l.get(n),a;if(i&&(i.bytes===r.value||K(i.bytes,r.value)))a=i.document,i.bytes=r.value;else{a=H(r.value);let e=i?.inputBytes??0,t=r.key.byteLength+r.value.byteLength;(i||l.size<Zt)&&o-e+t<=Xt?(l.set(n,{bytes:r.value,inputBytes:t,document:a}),o+=t-e):i&&(l.delete(n),o-=e)}let s=z(t,a);s!==null&&(await this.assertUniqueIndexAvailability(e,t,s,r.key),this.putIndexEntry(e,t,this.buildIndexEntryKey(t,s,r.key),Yt))}}this.putRawValue(e,P,Ot(t.store,t.name),kt(t))}this.txIndexSchemas.set(e,B(n)),this.txIndexSchemaChanged.add(e)}listStores(){return Promise.resolve(this.currentStoreNames())}getVersion(){return Promise.resolve(W(this.withEngine(e=>e.get_schema_version())))}async changesSince(e,t={}){let n=t.stores?.filter(e=>!F(e)),r={...t,stores:n?[...n]:void 0,limit:n?t.limit:void 0},i=this.withEngine(t=>t.changes_since(U(e),r)),a=n?new Set(n):null,o=[];for(let e of i.changes){if(F(e.store)||a&&!a.has(e.store))continue;let n=t.limit===void 0||o.length<t.limit?q(e.key):null,r;e.value!==void 0&&(r=await this.decodeStoreValueForFeed(e.store,q(e.value))),n!==null&&o.push({txId:W(e.txId),store:e.store,key:n,kind:e.kind,value:r})}return{latestTxId:W(i.latestTxId),changes:o}}setSchemaVersion(e,t){return this.withEngine(n=>n.set_schema_version(U(e),U(t))),Promise.resolve()}async exportSnapshot(e={}){let t=B(this.loadCommittedIndexSchema());return await mt(sn(q(this.withEngine(e=>e.export_snapshot())),t),e.compression??!1)}async importSnapshot(e){this.rollbackAllTransactions();let t=cn(await ht(e));this.withEngine(e=>e.import_snapshot(t.snapshot)),this.committedIndexes=[],this.committedStoreCompression=null,await this.applyCommittedIndexSchema(t.indexes)}async reset(){let e=this.dbName;if(!e)throw Z(`InternalError`,`engine is not open`);let t=B(this.loadCommittedIndexSchema());this.rollbackAllTransactions();let n=this.currentStoreNames().map(e=>({store:e,changes:[{key:/* @__PURE__ */ new Uint8Array,kind:`clear`}]})),r=W(this.withEngine(e=>e.reset()));if(this.committedIndexes=[],await this.applyCommittedIndexSchema(t),this.events){let t={type:`commit_applied`,dbName:e,txid:r,stores:n};this.events.postMessage(t)}}async compact(){return this.runCompactionOperation(`compact`)}async rebuild(){return this.runCompactionOperation(`rebuild`)}stats(){let e=this.withEngine(e=>e.stats());return Promise.resolve({...e,db_id:W(e.db_id),catalog_root_page_id:W(e.catalog_root_page_id),next_page_id:W(e.next_page_id),last_committed_txid:W(e.last_committed_txid),last_replayed_wal_offset:W(e.last_replayed_wal_offset),manifest_len:W(e.manifest_len),main_len:W(e.main_len),wal_len:W(e.wal_len),health:gn(e.health),store_count:this.currentStoreNames().length})}async storageInfo(){let[e,t,n]=await Promise.all([this.dbDirectorySize(),nn(),this.persistenceBridge.persisted()]);return{dbSize:e,originUsage:t.usage,originQuota:t.quota,persisted:n}}async requestPersistence(){return this.persistenceBridge.persist()}setFailpoint(e){return this.withEngine(t=>t.set_failpoint(e)),Promise.resolve()}requireDbName(){if(!this.dbName)throw Z(`InternalError`,`engine is not open`);return this.dbName}ensureNotInMaintenance(){if(this.maintenanceOperation)throw Z(`DatabaseBusyError`,`database ${this.dbName??`database`} is busy: ${this.maintenanceOperation} in progress`)}currentCachePages(){return this.openOptions?.cachePages??256}async dbDirectorySize(){return(await this.loadWasm()).dbDirectorySize(this.requireDbName())}async applyCommittedIndexSchema(e){let t=B(e);if(t.length===0){this.committedIndexes=[];return}let n=W(this.withEngine(e=>e.begin_tx(`readwrite`),{allowDuringMaintenance:!0}));this.txChanges.set(n,/* @__PURE__ */ new Map),this.txModes.set(n,`readwrite`),this.txStoreCompression.set(n,{owned:!1,values:this.loadCommittedStoreCompression()});try{await this.reconcileIndexes(n,V(t)),this.withEngine(e=>e.commit_tx(U(n)),{allowDuringMaintenance:!0}),this.committedIndexes=B(t)}catch(e){try{this.withEngine(e=>e.rollback_tx(U(n)),{allowDuringMaintenance:!0})}catch{}throw e}finally{this.cleanupTxState(n)}}async runCompactionOperation(e){let t=this.requireDbName();if(this.maintenanceOperation)throw Z(`DatabaseBusyError`,`database ${t} is busy: ${this.maintenanceOperation} in progress`);this.maintenanceOperation=e;let n=performance.now(),r=await this.loadWasm(),i=null,a=null,o=!1;try{let s=await r.dbDirectorySize(t),c=B(this.loadCommittedIndexSchema());this.rollbackAllTransactions({allowDuringMaintenance:!0});let l=await r.readActiveGeneration(t);a=(await r.prepareRebuildTarget(t)).generationName,i=new r.WasmEngine,await i.openGeneration(t,a,{create_if_missing:!0,cache_pages:this.currentCachePages()});let u=i;if(this.withEngine(t=>e===`rebuild`?t.compact_into_skipping_stores(u,[...c.map(e=>e.internalStore),P]):t.compact_into(u),{allowDuringMaintenance:!0}),e===`rebuild`&&c.length>0){let e=this.engine,t=this.maintenanceOperation;this.engine=u,this.maintenanceOperation=null;try{this.committedIndexes=[],this.committedStoreCompression=null,await this.applyCommittedIndexSchema(c)}finally{this.engine=e,this.maintenanceOperation=t,this.committedStoreCompression=null}}try{await r.swapActiveGeneration(t,a,l),o=!0}catch(e){if(o=await hn(r,t)===a,!o)throw e}let d=this.engine;this.engine=i,i=null,this.committedIndexes=c,this.committedStoreCompression=null;try{d?.abandon()}catch{}try{await r.cleanupInactiveEntries(t)}catch{}let f=await r.dbDirectorySize(t);return{sizeBefore:s,sizeAfter:f,reclaimedBytes:Math.max(0,s-f),durationMs:performance.now()-n}}catch(e){if(!o){this.committedIndexes=null,this.committedStoreCompression=null;try{i?.abandon()}catch{}if(a!==null){let e=await hn(r,t);if(e!==void 0&&e!==a)try{await r.cleanupInactiveEntries(t)}catch{}}}throw $(e)}finally{this.maintenanceOperation=null}}recoverEngineIfNeeded(){let e=this.engine;if(!e||!e.needs_recovery())return null;let t;try{t=e.recover()}catch(e){throw Z(`RecoveryRequiredError`,`database ${this.dbName??``} needs recovery and recovery failed: ${$(e).message}`)}finally{this.clearRuntimeCaches()}return{pendingTxid:Kt(t.pendingTxid),pendingCommitted:t.pendingCommitted===!0}}cleanupTxState(e){this.txChanges.delete(e),this.txModes.delete(e),this.txIndexSchemas.delete(e),this.txEnsuredRawStores.delete(e),this.txIndexSchemaChanged.delete(e),this.txStoreCompression.delete(e)}getOrCreateTrackedTxn(e){return $t(this.txChanges,e,()=>/* @__PURE__ */ new Map)}getOrCreateTrackedStore(e,t){return $t(this.getOrCreateTrackedTxn(e),t,()=>({touched:!1,storeLevel:null,keys:/* @__PURE__ */ new Map}))}recordStoreLevelChange(e,t,n){if(F(t))return;let r=this.getOrCreateTrackedStore(e,t);r.touched=!0,r.storeLevel=n,r.keys.clear()}recordPutChange(e,t,n,r){this.recordKeyChange(e,t,n,r,`put`)}recordPutChanges(e,t,n,r){if(F(t))return;let i=this.getOrCreateTrackedStore(e,t);i.touched=!0;let a=Math.min(n.length,r.length);for(let e=0;e<a;e+=1)this.setTrackedKeyChange(i,n[e][0],r[e],`put`)}recordPutKeyChanges(e,t,n,r){if(F(t))return;let i=this.getOrCreateTrackedStore(e,t);i.touched=!0;let a=Math.min(n.length,r.length);for(let e=0;e<a;e+=1)this.setTrackedKeyChange(i,n[e],r[e]===!0||r[e]===1,`put`)}recordDeleteChange(e,t,n,r){r&&this.recordKeyChange(e,t,n,!0,`delete`)}recordKeyChange(e,t,n,r,i){if(F(t))return;let a=this.getOrCreateTrackedStore(e,t);a.touched=!0,this.setTrackedKeyChange(a,n,r,i)}setTrackedKeyChange(e,t,n,r){let i=rn(t),a=e.keys.get(i);e.keys.set(i,{key:a?.key??t.slice(),baselineExists:a?.baselineExists??n,finalKind:r})}markStoreTouched(e,t){F(t)||(this.getOrCreateTrackedStore(e,t).touched=!0)}recordBatchOutcomes(e,t,n,r){for(let i=0;i<r.length&&i<n.length;i+=1){let a=n[i],o=r[i];a.kind===`put`&&o.kind===`put`?this.recordPutChange(e,t,a.key,o.baselineExists):a.kind===`delete`&&o.kind===`delete`&&this.recordDeleteChange(e,t,a.key,o.deleted)}}recordBatchKeyOutcomes(e,t,n,r){for(let i=0;i<r.length&&i<n.length;i+=1){let a=n[i],o=r[i];a.kind===`put`&&o.kind===`put`?this.recordPutChange(e,t,a.key,o.baselineExists):a.kind===`delete`&&o.kind===`delete`&&this.recordDeleteChange(e,t,a.key,o.deleted)}}finalizeTrackedChanges(e){let t=[];for(let[n,r]of e){if(!r.touched||F(n))continue;let e=[];r.storeLevel!==null&&e.push({key:/* @__PURE__ */ new Uint8Array,kind:r.storeLevel});for(let t of r.keys.values())(t.finalKind!==`delete`||t.baselineExists)&&e.push({key:t.key,kind:t.finalKind});t.push({store:n,changes:e})}return t}rollbackAllTransactions(e={}){if(!this.engine||this.txChanges.size===0){this.clearTxCaches();return}let t=Array.from(this.txChanges.keys());for(let n of t)try{this.withEngine(e=>e.rollback_tx(U(n)),e)}finally{this.cleanupTxState(n)}}currentStoreNames(){return this.allRawStoreNames().filter(e=>!F(e))}allRawStoreNames(){return this.withEngine(e=>e.list_stores())}loadCommittedStoreCompression(){if(this.committedStoreCompression)return this.committedStoreCompression;let e=this.withEngine(e=>e.list_store_configs()),t=/* @__PURE__ */ new Map;for(let n of e){if(typeof n.name!=`string`)throw Z(`CorruptionError`,`invalid store config row: missing name`);let e=typeof n.flags==`bigint`?Number(n.flags):n.flags;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Z(`CorruptionError`,`invalid store flags for ${n.name}`);t.set(n.name,dt(e))}return this.committedStoreCompression=t,t}ensureTxStoreCompression(e){let t=this.txStoreCompression.get(e);if(t?.owned)return t.values;let n=new Map(t?.values);return this.txStoreCompression.set(e,{owned:!0,values:n}),n}recordStoreCompressionCreate(e,t,n){F(t)||this.ensureTxStoreCompression(e).set(t,n)}recordStoreCompressionDrop(e,t){F(t)||this.ensureTxStoreCompression(e).delete(t)}storeCompressionForTx(e,t){if(F(t))return!1;let n=this.txStoreCompression.get(e);return n?n.values.get(t)??!1:this.loadCommittedStoreCompression().get(t)??!1}async encodeEntriesForWrite(e,t,n){if(F(t))return n;let r=this.storeCompressionForTx(e,t);if(r===!1)return n;let i=[];for(let[e,t]of n)i.push([e,await ft(t,r)]);return i}async encodeBatchOpsForWrite(e,t,n){if(F(t))return n;let r=this.storeCompressionForTx(e,t);if(r===!1)return n;let i=[];for(let e of n)i.push(e.kind===`put`?{kind:`put`,key:e.key,value:await ft(e.value,r)}:e);return i}async encodeStoreValueForWrite(e,t,n){return F(t)?n:ft(n,this.storeCompressionForTx(e,t))}async decodeStoreValue(e,t,n){return F(t)||this.storeCompressionForTx(e,t)===!1?n:pt(n,{strict:!0})}async decodeStoreValueForFeed(e,t){return F(e)?t:pt(t,{strict:(this.loadCommittedStoreCompression().get(e)??!1)!==!1})}async readStoreValue(e,t,n){let r=this.readRawValue(e,t,n);return r===null?null:this.decodeStoreValue(e,t,r)}async readStoreScan(e,t,n){let r=this.readRawScan(e,t,n);if(F(t)||this.storeCompressionForTx(e,t)===!1)return r;let i=r.map(e=>e.value);await this.decodeStoreValues(e,t,i);for(let e=0;e<r.length;e+=1)r[e].value=i[e];return r}async decodeStoreValues(e,t,n){let r={next:0,failed:!1,failure:void 0};if(await Promise.all(Array.from({length:Math.min(8,n.length)},async()=>{for(;!r.failed&&r.next<n.length;){let i=r.next++,a=n[i];if(a!==null)try{n[i]=await this.decodeStoreValue(e,t,a)}catch(e){r.failed||(r.failed=!0,r.failure=e)}}})),r.failed)throw r.failure;return n}indexesForStoreInTx(e,t){let n=this.indexSchemaForTx(e),r=this.indexesBySchema.get(n);if(!r){r=/* @__PURE__ */ new Map;for(let e of n){let t=r.get(e.store);t?t.push(e):r.set(e.store,[e])}this.indexesBySchema.set(n,r)}return r.get(t)??[]}resolveIndexDefinition(e,t,n){if(!this.rawStoreExistsInTx(e,t))throw Z(`StoreNotFoundError`,`store not found: ${t}`);let r=Dt(this.indexesForStoreInTx(e,t),t,n);if(!r)throw Z(`IndexNotFoundError`,`index not found: ${t}.${n}`);return r}indexSchemaForTx(e){let t=this.txIndexSchemas.get(e);if(t)return t;if(this.committedIndexes)return this.committedIndexes;let n=this.readIndexSchemaInTx(e);return this.committedIndexes=B(n),this.committedIndexes}loadCommittedIndexSchema(){if(this.committedIndexes)return this.committedIndexes;let e=W(this.withEngine(e=>e.begin_tx(`readonly`)));try{let t=this.readIndexSchemaInTx(e);return this.committedIndexes=B(t),this.committedIndexes}finally{this.withEngine(t=>t.rollback_tx(U(e)))}}readIndexSchemaInTx(e){if(!this.rawStoreExistsInTx(e,`__browserdb:indexes`))return[];let t=this.readRawScan(e,P,Jt).map(e=>At(e.value));return t.sort(Tt),t}rawStoreExistsInTx(e,t){try{return this.readRawScan(e,t,{limit:0}),!0}catch(e){if(J(e,`StoreNotFoundError`))return!1;throw e}}ensureRawStore(e,t){let n=this.txModes.get(e)===`readwrite`;n&&this.txEnsuredRawStores.get(e)?.has(t)||(this.ignoreNamedError(`StoreExistsError`,()=>{this.withEngine(n=>n.create_store(U(e),t))}),n&&$t(this.txEnsuredRawStores,e,()=>/* @__PURE__ */ new Set).add(t))}clearRawStoreIfExists(e,t){try{this.withEngine(n=>n.clear_store(U(e),t))}catch(n){if(!J(n,`StoreNotFoundError`))throw n;this.txEnsuredRawStores.get(e)?.delete(t)}}dropRawStoreIfExists(e,t){this.txEnsuredRawStores.get(e)?.delete(t),this.ignoreNamedError(`StoreNotFoundError`,()=>{this.withEngine(n=>n.drop_store(U(e),t))})}ensureInternalStoresForDefinitions(e,t){for(let n of t)this.ensureRawStore(e,n.internalStore)}ensureInternalStoresForStore(e,t){this.ensureInternalStoresForDefinitions(e,this.indexesForStoreInTx(e,t))}readRawValue(e,t,n){let r=this.withEngine(r=>r.get(U(e),t,n));return r===null?null:q(r)}readRawScan(e,t,n){let r=this.withEngine(r=>r.scan(U(e),t,qt(n)));for(let e of r)e.key=q(e.key),e.value=q(e.value);return r}putRawValue(e,t,n,r){this.withEngine(i=>i.put(U(e),t,n,r))}putIndexEntry(e,t,n,r){this.putRawValue(e,t.internalStore,n,r)}deleteIndexEntryIfPresent(e,t,n,r){let i=this.buildIndexEntryKey(t,n,r);this.ignoreNamedError(`StoreNotFoundError`,()=>{this.withEngine(n=>n.delete(U(e),t.internalStore,i))})}buildIndexEntryKey(e,t,n){let r=jt(t,n);if(r.byteLength>1024)throw Z(`KeyTooLargeError`,`index key too large for ${e.store}.${e.name}`);return r}async assertUniqueIndexAvailability(e,t,n,r){if(!t.unique)return;let i=Mt(n),a=null,o=1;for(;;){let s={...i,limit:o};a!==null&&(s.gt=a,delete s.gte);let c=this.readRawScan(e,t.internalStore,s);for(let i of c){a=i.key;let o=L(i.key);if(K(o.primaryKey,r))continue;let s=await this.readStoreValue(e,t.store,o.primaryKey);if(s===null){this.cleanupStaleIndexRow(e,t,i.key);continue}let c=Pt(t,s);if(c===null||!K(c,n)){this.cleanupStaleIndexRow(e,t,i.key);continue}throw Z(`UniqueIndexConstraintError`,`unique index constraint violation on ${t.store}.${t.name}`)}if(c.length<o)return;o=Math.min(512,o*2)}}async loadVisibleIndexPage(e,t,n,r,i){let{limit:a,...o}=n,s=Nt(o),c=s.reverse===!0,l=r,u=[],d=1;for(;;){let n=Math.min(512,Math.max(i-u.length,d)),r={...s,limit:n};l!==null&&(c?(delete r.lte,r.lt=l):(delete r.gte,r.gt=l));let a;try{a=this.readRawScan(e,t.internalStore,r)}catch(e){if(J(e,`StoreNotFoundError`))return{rows:[],cursor:null};throw e}let o=u.length,f=0,p=0,m=null;for(let n=0;n<a.length;n+=1){n===p&&(f=n,p=Math.min(a.length,n+i-u.length),m=this.readIndexPrimaryValues(e,t,a,f,p));let r=a[n];l=r.key;let o=m?await this.resolveVisibleIndexedValue(e,t,r.key,m.entries[n-f],m.values[n-f]):await this.resolveVisibleIndexedRow(e,t,r.key);if(o&&(u.push(o),u.length>=i))return{rows:u,cursor:r.key.slice()}}if(a.length<n)return{rows:u,cursor:null};d=u.length===o?Math.min(512,n*2):1}}readIndexPrimaryValues(e,t,n,r,i){if(this.txModes.get(e)!==`readonly`||i-r<=1)return null;let a,o;try{a=n.slice(r,i).map(e=>L(e.key)),o=this.withEngine(n=>n.get_many(U(e),t.store,a.map(e=>e.primaryKey)))}catch{return null}if(o.length!==a.length)throw Z(`InternalError`,`get_many outcome count mismatch: ${o.length} != ${a.length}`);return{entries:a,values:o}}async resolveVisibleIndexedRow(e,t,n){let r=L(n),i=this.readRawValue(e,t.store,r.primaryKey);return this.resolveVisibleIndexedValue(e,t,n,r,i)}async resolveVisibleIndexedValue(e,t,n,r,i){if(i===null)return this.cleanupStaleIndexRow(e,t,n),null;let a=await this.decodeStoreValue(e,t.store,q(i)),o=Pt(t,a);return o===null||!K(o,r.logicalKey)?(this.cleanupStaleIndexRow(e,t,n),null):{key:r.primaryKey,value:a}}cleanupStaleIndexRow(e,t,n){if(this.txModes.get(e)===`readwrite`)try{this.withEngine(r=>r.delete(U(e),t.internalStore,n))}catch{}}async loadWasm(){return this.wasmReady||=(async()=>{let e=new URL(`/engine/moyodb_engine.js`,``+import.meta.url).href,t=new URL(`/engine/moyodb_engine_bg.wasm`,``+import.meta.url).href,n=await import(
|
|
2
|
+
/* @vite-ignore */
|
|
3
|
+
e);return await n.default({module_or_path:t}),n})(),this.wasmReady}withEngine(e,t={}){if(this.maintenanceOperation&&!t.allowDuringMaintenance&&this.ensureNotInMaintenance(),!this.engine)throw Z(`InternalError`,`engine is not open`);try{return e(this.engine)}catch(e){throw $(e)}}ignoreNamedError(e,t){try{t()}catch(t){if(J(t,e))return;throw t}}clearTxCaches(){this.txChanges.clear(),this.txModes.clear(),this.txIndexSchemas.clear(),this.txEnsuredRawStores.clear(),this.txIndexSchemaChanged.clear(),this.txStoreCompression.clear()}clearRuntimeCaches(){this.clearTxCaches(),this.committedIndexes=null,this.committedStoreCompression=null}async cleanupAfterFailedOpen(e){try{e?.abandon()}catch{}if(this.engine=null,this.clearRuntimeCaches(),this.events?.close(),this.events=null,this.lease)try{await this.lease.release()}catch{}this.lease=null,this.disposePersistenceBridge(),this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}disposePersistenceBridge(){this.persistenceBridge.close()}};function fn(){if(typeof navigator.storage.getDirectory!=`function`)throw Z(`UnsupportedPlatformError`,`navigator.storage.getDirectory is unavailable`);if(typeof BroadcastChannel>`u`)throw Z(`UnsupportedPlatformError`,`BroadcastChannel is unavailable`);if(typeof FileSystemFileHandle>`u`||typeof FileSystemFileHandle.prototype.createSyncAccessHandle!=`function`)throw Z(`UnsupportedPlatformError`,`createSyncAccessHandle is unavailable`)}function pn(){if(!self.isSecureContext)throw Z(`UnsupportedPlatformError`,`moyodb requires a secure context (HTTPS)`)}function Z(e,t){let n=Error(t);return n.name=e,Object.defineProperty(n,"code",{value:e,enumerable:!0,configurable:!0}),n}function mn(e,t){let n=e.change_feed_policy(),r=Kt(n.retainTxids);if(n.enabled===t.enabled&&(!t.enabled||r===t.retainTxids))return;let i=e.begin_tx(`readwrite`);try{e.set_change_feed_policy(i,{enabled:t.enabled,retainTxids:t.retainTxids}),e.commit_tx(i)}catch(t){try{e.rollback_tx(i)}catch{}throw $(t)}}async function hn(e,t){try{return await e.readActiveGeneration(t)}catch{return}}function gn(e){return e.state===`recoveryRequired`?{state:`recoveryRequired`,reason:e.reason,pendingTxid:Kt(e.pendingTxid)}:{state:e.state}}function Q(t){return!e(t)||!Array.isArray(t.partial)?[]:t.partial.filter(e=>typeof e==`boolean`)}function _n(t){return!e(t)||!Array.isArray(t.partial)?[]:t.partial.filter(t=>!e(t)||typeof t.kind!=`string`?!1:t.kind===`put`&&typeof t.baselineExists==`boolean`||t.kind===`delete`&&typeof t.deleted==`boolean`)}function $(t){if(t instanceof Error)return t;if(e(t)){let e=Z(typeof t.code==`string`?t.code:typeof t.name==`string`?t.name:`Error`,typeof t.message==`string`?t.message:`Unknown error`);return`partial`in t&&Object.defineProperty(e,"partial",{value:t.partial,enumerable:!0,configurable:!0}),e}return Z(`Error`,String(t))}Fe(new dn);
|
|
4
|
+
//# sourceMappingURL=worker-KDc8Khl_.js.map
|