@liberation-data/drivine-cypher-compiler 0.0.0-stage → 0.32.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # Drivine's Cypher compiler
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cypher compiled to SQL for Postgres, Oracle and SQLite, built for Wasm from the Kotlin Multiplatform compiler in
4
+ [drivine-cypher-spec](https://github.com/liberation-data/drivine-cypher-spec/tree/main/compiler). It is what
5
+ [Drivine for TypeScript](https://github.com/liberation-data/drivine) compiles Cypher with on its SQL stores, and the same
6
+ compiler [drivine4j](https://github.com/liberation-data/drivine4j) runs on the JVM: given the same request, both give the
7
+ same SQL, byte for byte.
8
+
9
+ Each version is the Cypher spec's tag of that number, so the compiler and the spec it was checked against share one
10
+ number. Node 22 or later.
11
+
12
+ ```js
13
+ const { compile } = require('@liberation-data/drivine-cypher-compiler'); // or: import { compile } from '…'
14
+ const answer = JSON.parse(compile(JSON.stringify({ store: 'sqlite', graph: { name: 'g' }, cypher: 'RETURN 1' })));
15
+ ```
16
+
17
+ A request and its answer are JSON text. The request names the store, the graph and the Cypher, with its parameters; the
18
+ answer is the SQL and how to read its rows, or why the statement is refused. The module's README describes both:
19
+ [compiler/README.md](https://github.com/liberation-data/drivine-cypher-spec/blob/main/compiler/README.md).
20
+
21
+ The Wasm module is read and started on the first `compile`, not on `require`.
22
+
23
+ Apache License 2.0.
@@ -0,0 +1,3 @@
1
+ type Nullable<T> = T | null | undefined
2
+ declare function KtSingleton<T>(): T & (abstract new() => any);
3
+ export declare function compile(request: string): string;
@@ -0,0 +1,16 @@
1
+
2
+ import * as _ref_QGpzLWpvZGEvY29yZQ_ from '@js-joda/core';
3
+ import { instantiate } from './drivine-cypher-compiler.uninstantiated.mjs';
4
+
5
+
6
+ const exports = (await instantiate({
7
+ '@js-joda/core': _ref_QGpzLWpvZGEvY29yZQ_
8
+ })).exports;
9
+
10
+ export const {
11
+ compile,
12
+ memory,
13
+ _initialize
14
+ } = exports
15
+
16
+
@@ -0,0 +1,222 @@
1
+
2
+ export async function instantiate(imports={}, runInitializer=true) {
3
+ const cachedJsObjects = new WeakMap();
4
+ // ref must be non-null
5
+ function getCachedJsObject(ref, ifNotCached) {
6
+ if (typeof ref !== 'object' && typeof ref !== 'function') return ifNotCached;
7
+ const cached = cachedJsObjects.get(ref);
8
+ if (cached !== void 0) return cached;
9
+ cachedJsObjects.set(ref, ifNotCached);
10
+ return ifNotCached;
11
+ }
12
+
13
+ const _ref_QGpzLWpvZGEvY29yZQ_ = imports['@js-joda/core'];
14
+
15
+ const wasmJsTag = WebAssembly.JSTag;
16
+ const wasmTag = wasmJsTag ?? new WebAssembly.Tag({ parameters: ['externref'] });
17
+
18
+ const js_code = {
19
+ 'kotlin.createJsError' : (message, cause) => new Error(message, { cause }),
20
+ 'kotlin.wasm.internal.jsThrow' : typeof wasmJsTag === 'undefined' || wasmTag === wasmJsTag ? (e) => { throw e; } : () => {},
21
+ 'kotlin.wasm.internal.stringLength' : (x) => x.length,
22
+ 'kotlin.wasm.internal.jsExportStringToWasm' : (src, srcOffset, srcLength, dstAddr) => {
23
+ const mem16 = new Uint16Array(wasmExports.memory.buffer, dstAddr, srcLength);
24
+ let arrayIndex = 0;
25
+ let srcIndex = srcOffset;
26
+ while (arrayIndex < srcLength) {
27
+ mem16.set([src.charCodeAt(srcIndex)], arrayIndex);
28
+ srcIndex++;
29
+ arrayIndex++;
30
+ }
31
+ },
32
+ 'kotlin.wasm.internal.externrefToString' : (ref) => String(ref),
33
+ 'kotlin.wasm.internal.externrefEquals' : (lhs, rhs) => lhs === rhs,
34
+ 'kotlin.wasm.internal.externrefHashCode' :
35
+ (() => {
36
+ const dataView = new DataView(new ArrayBuffer(8));
37
+ function numberHashCode(obj) {
38
+ if ((obj | 0) === obj) {
39
+ return obj | 0;
40
+ } else {
41
+ dataView.setFloat64(0, obj, true);
42
+ return (dataView.getInt32(0, true) * 31 | 0) + dataView.getInt32(4, true) | 0;
43
+ }
44
+ }
45
+
46
+ const hashCodes = new WeakMap();
47
+ function getObjectHashCode(obj) {
48
+ const res = hashCodes.get(obj);
49
+ if (res === undefined) {
50
+ const POW_2_32 = 4294967296;
51
+ const hash = (Math.random() * POW_2_32) | 0;
52
+ hashCodes.set(obj, hash);
53
+ return hash;
54
+ }
55
+ return res;
56
+ }
57
+
58
+ function getStringHashCode(str) {
59
+ var hash = 0;
60
+ for (var i = 0; i < str.length; i++) {
61
+ var code = str.charCodeAt(i);
62
+ hash = (hash * 31 + code) | 0;
63
+ }
64
+ return hash;
65
+ }
66
+
67
+ return (obj) => {
68
+ if (obj == null) {
69
+ return 0;
70
+ }
71
+ switch (typeof obj) {
72
+ case "object":
73
+ case "function":
74
+ return getObjectHashCode(obj);
75
+ case "number":
76
+ return numberHashCode(obj);
77
+ case "boolean":
78
+ return obj ? 1231 : 1237;
79
+ default:
80
+ return getStringHashCode(String(obj));
81
+ }
82
+ }
83
+ })(),
84
+ 'kotlin.wasm.internal.importStringFromWasm' : (address, length, prefix) => {
85
+ const mem16 = new Uint16Array(wasmExports.memory.buffer, address, length);
86
+ const str = String.fromCharCode.apply(null, mem16);
87
+ return (prefix == null) ? str : prefix + str;
88
+ },
89
+ 'kotlin.wasm.internal.getJsEmptyString' : () => '',
90
+ 'kotlin.wasm.internal.isNullish' : (ref) => ref == null,
91
+ 'kotlin.wasm.internal.getCachedJsObject_$external_fun' : (p0, p1) => getCachedJsObject(p0, p1),
92
+ 'kotlin.io.printlnImpl' : (message) => console.log(message),
93
+ 'kotlin.js.jsArrayGet' : (array, index) => array[index],
94
+ 'kotlin.js.length_$external_prop_getter' : (_this) => _this.length,
95
+ 'kotlin.js.stackPlaceHolder_js_code' : () => (''),
96
+ 'kotlin.js.message_$external_prop_getter' : (_this) => _this.message,
97
+ 'kotlin.js.name_$external_prop_setter' : (_this, v) => _this.name = v,
98
+ 'kotlin.js.kotlinException_$external_prop_getter' : (_this) => _this.kotlinException,
99
+ 'kotlin.js.kotlinException_$external_prop_setter' : (_this, v) => _this.kotlinException = v,
100
+ 'kotlin.js.JsError_$external_class_instanceof' : (x) => x instanceof Error,
101
+ 'kotlin.js.JsString_$external_class_instanceof' : (x) => typeof x === 'string',
102
+ 'kotlin.js.JsString_$external_class_get' : () => JsString,
103
+ 'kotlin.random.initialSeed' : () => ((Math.random() * Math.pow(2, 32)) | 0),
104
+ 'kotlin.wasm.internal.getJsClassName' : (jsKlass) => jsKlass.name,
105
+ 'kotlin.wasm.internal.instanceOf' : (ref, jsKlass) => ref instanceof jsKlass,
106
+ 'kotlin.wasm.internal.getConstructor' : (obj) => obj.constructor,
107
+ 'kotlin.time.Date_$external_fun' : () => new Date(),
108
+ 'kotlin.time.getTime_$external_fun' : (_this, ) => _this.getTime(),
109
+ 'kotlinx.datetime.internal.Date_$external_fun' : (p0) => new Date(p0),
110
+ 'kotlinx.datetime.internal.getTimezoneOffset_$external_fun' : (_this, ) => _this.getTimezoneOffset(),
111
+ 'kotlinx.datetime.internal.JSJoda.ZoneRulesProvider_$external_object_getInstance' : () => _ref_QGpzLWpvZGEvY29yZQ_.ZoneRulesProvider,
112
+ 'kotlinx.datetime.internal.JSJoda.id_$external_fun' : (_this, ) => _this.id(),
113
+ 'kotlinx.datetime.internal.JSJoda.systemDefault_$external_fun' : (_this, ) => _this.systemDefault(),
114
+ 'kotlinx.datetime.internal.JSJoda.Companion_$external_object_getInstance' : () => _ref_QGpzLWpvZGEvY29yZQ_.ZoneId,
115
+ 'kotlinx.datetime.internal.withCaughtJsException' : (body) => {
116
+ try {
117
+ body();
118
+ return null;
119
+ } catch(e) {
120
+ return e;
121
+ }
122
+ },
123
+ 'kotlinx.datetime.internal.__convertKotlinClosureToJsClosure_(()->Unit)' : (f) => getCachedJsObject(f, () => wasmExports['__callFunction_(()->Unit)'](f, )),
124
+ 'kotlinx.datetime.internal.getExceptionMessage' : (jsException) => jsException.message,
125
+ 'kotlinx.datetime.internal.getZones' : (rulesProvider) => rulesProvider.getTzdbData().zones,
126
+ 'kotlinx.datetime.internal.getLinks' : (rulesProvider) => rulesProvider.getTzdbData().links,
127
+ 'com.strumenta.antlrkotlin.runtime.platformPrintErrLn' : (message) => console.error(message),
128
+ 'com.strumenta.antlrkotlin.runtime.processEnvJs' : (name) => process.env[name],
129
+ 'com.strumenta.antlrkotlin.runtime.isNodeJs' : () =>
130
+ (typeof process !== 'undefined'
131
+ && process.versions != null
132
+ && process.versions.node != null) ||
133
+ (typeof window !== 'undefined'
134
+ && typeof window.process !== 'undefined'
135
+ && window.process.versions != null
136
+ && window.process.versions.node != null)
137
+
138
+ }
139
+
140
+ // Placed here to give access to it from externals (js_code)
141
+ let wasmInstance;
142
+ let require;
143
+ let wasmExports;
144
+
145
+ const isNodeJs = (typeof process !== 'undefined') && (process.release.name === 'node');
146
+ const isDeno = !isNodeJs && (typeof Deno !== 'undefined')
147
+ const isStandaloneJsVM =
148
+ !isDeno && !isNodeJs && (
149
+ typeof d8 !== 'undefined' // V8
150
+ || typeof inIon !== 'undefined' // SpiderMonkey
151
+ || typeof jscOptions !== 'undefined' // JavaScriptCore
152
+ );
153
+ const isBrowser = !isNodeJs && !isDeno && !isStandaloneJsVM && (typeof window !== 'undefined' || typeof self !== 'undefined');
154
+
155
+ if (!isNodeJs && !isDeno && !isStandaloneJsVM && !isBrowser) {
156
+ throw "Supported JS engine not detected";
157
+ }
158
+
159
+ const wasmFilePath = './drivine-cypher-compiler.wasm';
160
+
161
+ const importObject = {
162
+ js_code,
163
+ intrinsics: {
164
+ tag: wasmTag
165
+ },
166
+
167
+ };
168
+
169
+ try {
170
+ if (isNodeJs) {
171
+ const module = await import(/* webpackIgnore: true */'node:module');
172
+ const importMeta = import.meta;
173
+ require = module.default.createRequire(importMeta.url);
174
+ const fs = require('fs');
175
+ const url = require('url');
176
+ const filepath = import.meta.resolve(wasmFilePath);
177
+ const wasmBuffer = fs.readFileSync(url.fileURLToPath(filepath));
178
+ const wasmModule = new WebAssembly.Module(wasmBuffer);
179
+ wasmInstance = new WebAssembly.Instance(wasmModule, importObject);
180
+ }
181
+
182
+ if (isDeno) {
183
+ const path = await import(/* webpackIgnore: true */'https://deno.land/std/path/mod.ts');
184
+ const binary = Deno.readFileSync(path.fromFileUrl(import.meta.resolve(wasmFilePath)));
185
+ const module = await WebAssembly.compile(binary);
186
+ wasmInstance = await WebAssembly.instantiate(module, importObject);
187
+ }
188
+
189
+ if (isStandaloneJsVM) {
190
+ const wasmBuffer = read(wasmFilePath, 'binary');
191
+ const wasmModule = new WebAssembly.Module(wasmBuffer);
192
+ wasmInstance = new WebAssembly.Instance(wasmModule, importObject);
193
+ }
194
+
195
+ if (isBrowser) {
196
+ wasmInstance = (await WebAssembly.instantiateStreaming(fetch(new URL('./drivine-cypher-compiler.wasm',import.meta.url).href), importObject)).instance;
197
+ }
198
+ } catch (e) {
199
+ if (e instanceof WebAssembly.CompileError) {
200
+ let text = `Please make sure that your runtime environment supports the latest version of Wasm GC and Exception-Handling proposals.
201
+ For more information, see https://kotl.in/wasm-help
202
+ `;
203
+ if (isBrowser) {
204
+ console.error(text);
205
+ } else {
206
+ const t = "\n" + text;
207
+ if (typeof console !== "undefined" && console.log !== void 0)
208
+ console.log(t);
209
+ else
210
+ print(t);
211
+ }
212
+ }
213
+ throw e;
214
+ }
215
+
216
+ wasmExports = wasmInstance.exports;
217
+ if (runInitializer) {
218
+ wasmExports._initialize();
219
+ }
220
+
221
+ return { instance: wasmInstance, exports: wasmExports };
222
+ }
Binary file
package/index.cjs ADDED
@@ -0,0 +1,60 @@
1
+ 'use strict';
2
+ /**
3
+ * The compiler's CommonJS entry point: the Kotlin/Wasm build, loaded synchronously.
4
+ *
5
+ * Kotlin/Wasm writes only an ES module loader, whose `instantiate` is async and which an ES module imports with a
6
+ * top-level await, so `require` can't load it. Its Node branch is synchronous all the same (`new WebAssembly.Module`,
7
+ * `new WebAssembly.Instance`), so this runs the loader's text as a function, with that branch given the module's bytes
8
+ * and its awaits taken out. Each edit is checked to apply, so a Kotlin release that writes the loader otherwise fails
9
+ * here at once, rather than loading something else.
10
+ *
11
+ * const { compile } = require('@liberation-data/drivine-cypher-compiler');
12
+ * JSON.parse(compile(JSON.stringify({ store: 'postgres', graph: { name: 'g' }, cypher: 'RETURN 1' })));
13
+ */
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const url = require('url');
17
+
18
+ const NAME = 'drivine-cypher-compiler';
19
+ let loaded;
20
+
21
+ function edit(text, pattern, replacement, what) {
22
+ const edited = text.replace(pattern, replacement);
23
+ if (edited === text) {
24
+ throw new Error(`${NAME}: the Kotlin/Wasm loader has no ${what} to edit: see index.cjs.`);
25
+ }
26
+ return edited;
27
+ }
28
+
29
+ function load() {
30
+ if (loaded) {
31
+ return loaded;
32
+ }
33
+ const loader = path.join(__dirname, `${NAME}.uninstantiated.mjs`);
34
+ let source = fs.readFileSync(loader, 'utf8');
35
+ source = edit(source, 'export async function instantiate', 'function instantiate', 'async instantiate');
36
+ source = edit(
37
+ source,
38
+ /if \(isNodeJs\) \{\s*const module = await import\([^)]*\);[\s\S]*?wasmInstance = new WebAssembly\.Instance\(wasmModule, importObject\);\s*\}/,
39
+ 'if (isNodeJs) { wasmInstance = new WebAssembly.Instance(new WebAssembly.Module(__wasmBytes), importObject); }',
40
+ 'Node branch'
41
+ );
42
+ // The other branches (Deno, a browser) are never taken here, but must parse in a function that isn't async.
43
+ source = source.replace(/await import\(/g, '(() => { throw new Error("not on Node"); })(');
44
+ source = source.replace(/\bawait /g, '');
45
+ source = source.replace(/import\.meta\.url/g, '__metaUrl').replace(/import\.meta/g, '({ url: __metaUrl, resolve: (p) => p })');
46
+ const instantiate = new Function('__wasmBytes', '__metaUrl', `${source}\nreturn instantiate;`)(
47
+ fs.readFileSync(path.join(__dirname, `${NAME}.wasm`)),
48
+ url.pathToFileURL(loader).href
49
+ );
50
+ // The loader's own imports: kotlinx-datetime's, on wasmJs.
51
+ loaded = instantiate({ '@js-joda/core': require('@js-joda/core') }).exports;
52
+ return loaded;
53
+ }
54
+
55
+ /** A request as JSON text, and back the answer as JSON text: see the package's README. */
56
+ function compile(request) {
57
+ return load().compile(request);
58
+ }
59
+
60
+ module.exports = { compile };
package/index.d.cts ADDED
@@ -0,0 +1,2 @@
1
+ /** A request as JSON text, and back the answer as JSON text: see the package's README. The types of `require`. */
2
+ export declare function compile(request: string): string;
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
- "name": "@liberation-data/drivine-cypher-compiler",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@liberation-data/drivine-cypher-compiler",
3
+ "version": "0.32.0",
4
+ "description": "Drivine's Cypher compiler: Cypher as SQL for Postgres, Oracle and SQLite, built for Wasm.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/liberation-data/drivine-cypher-spec.git",
9
+ "directory": "compiler"
10
+ },
11
+ "type": "commonjs",
12
+ "main": "index.cjs",
13
+ "types": "drivine-cypher-compiler.d.mts",
14
+ "exports": {
15
+ ".": {
16
+ "import": {
17
+ "types": "./drivine-cypher-compiler.d.mts",
18
+ "default": "./drivine-cypher-compiler.mjs"
19
+ },
20
+ "require": {
21
+ "types": "./index.d.cts",
22
+ "default": "./index.cjs"
23
+ }
24
+ }
25
+ },
26
+ "engines": {
27
+ "node": ">=22"
28
+ },
29
+ "dependencies": {
30
+ "@js-joda/core": "3.2.0"
31
+ }
32
+ }