@sanity-labs/groq-wasm 0.1.0 → 0.3.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.
@@ -0,0 +1,307 @@
1
+ /* @ts-self-types="./groq_wasm.d.ts" */
2
+
3
+ /**
4
+ * Format a GROQ query.
5
+ *
6
+ * # Arguments
7
+ * * `query` - The GROQ query string to format
8
+ * * `width` - Maximum line width (default: 80)
9
+ *
10
+ * # Returns
11
+ * The formatted query string
12
+ * @param {string} query
13
+ * @param {number | null} [width]
14
+ * @returns {string}
15
+ */
16
+ export function format(query, width) {
17
+ let deferred3_0;
18
+ let deferred3_1;
19
+ try {
20
+ const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
21
+ const len0 = WASM_VECTOR_LEN;
22
+ const ret = wasm.format(ptr0, len0, isLikeNone(width) ? 0x100000001 : (width) >>> 0);
23
+ var ptr2 = ret[0];
24
+ var len2 = ret[1];
25
+ if (ret[3]) {
26
+ ptr2 = 0; len2 = 0;
27
+ throw takeFromExternrefTable0(ret[2]);
28
+ }
29
+ deferred3_0 = ptr2;
30
+ deferred3_1 = len2;
31
+ return getStringFromWasm0(ptr2, len2);
32
+ } finally {
33
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
34
+ }
35
+ }
36
+
37
+ export function init() {
38
+ wasm.init();
39
+ }
40
+
41
+ /**
42
+ * Lint a GROQ query and return findings as JSON.
43
+ *
44
+ * # Arguments
45
+ * * `query` - The GROQ query string to lint
46
+ *
47
+ * # Returns
48
+ * A JSON string containing an array of findings
49
+ * @param {string} query
50
+ * @returns {string}
51
+ */
52
+ export function lint(query) {
53
+ let deferred3_0;
54
+ let deferred3_1;
55
+ try {
56
+ const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
57
+ const len0 = WASM_VECTOR_LEN;
58
+ const ret = wasm.lint(ptr0, len0);
59
+ var ptr2 = ret[0];
60
+ var len2 = ret[1];
61
+ if (ret[3]) {
62
+ ptr2 = 0; len2 = 0;
63
+ throw takeFromExternrefTable0(ret[2]);
64
+ }
65
+ deferred3_0 = ptr2;
66
+ deferred3_1 = len2;
67
+ return getStringFromWasm0(ptr2, len2);
68
+ } finally {
69
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
70
+ }
71
+ }
72
+
73
+ function __wbg_get_imports() {
74
+ const import0 = {
75
+ __proto__: null,
76
+ __wbg_error_a6fa202b58aa1cd3: function(arg0, arg1) {
77
+ let deferred0_0;
78
+ let deferred0_1;
79
+ try {
80
+ deferred0_0 = arg0;
81
+ deferred0_1 = arg1;
82
+ console.error(getStringFromWasm0(arg0, arg1));
83
+ } finally {
84
+ wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
85
+ }
86
+ },
87
+ __wbg_new_227d7c05414eb861: function() {
88
+ const ret = new Error();
89
+ return ret;
90
+ },
91
+ __wbg_stack_3b0d974bbf31e44f: function(arg0, arg1) {
92
+ const ret = arg1.stack;
93
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
94
+ const len1 = WASM_VECTOR_LEN;
95
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
96
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
97
+ },
98
+ __wbindgen_cast_0000000000000001: function(arg0, arg1) {
99
+ // Cast intrinsic for `Ref(String) -> Externref`.
100
+ const ret = getStringFromWasm0(arg0, arg1);
101
+ return ret;
102
+ },
103
+ __wbindgen_init_externref_table: function() {
104
+ const table = wasm.__wbindgen_externrefs;
105
+ const offset = table.grow(4);
106
+ table.set(0, undefined);
107
+ table.set(offset + 0, undefined);
108
+ table.set(offset + 1, null);
109
+ table.set(offset + 2, true);
110
+ table.set(offset + 3, false);
111
+ },
112
+ };
113
+ return {
114
+ __proto__: null,
115
+ "./groq_wasm_bg.js": import0,
116
+ };
117
+ }
118
+
119
+ let cachedDataViewMemory0 = null;
120
+ function getDataViewMemory0() {
121
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
122
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
123
+ }
124
+ return cachedDataViewMemory0;
125
+ }
126
+
127
+ function getStringFromWasm0(ptr, len) {
128
+ ptr = ptr >>> 0;
129
+ return decodeText(ptr, len);
130
+ }
131
+
132
+ let cachedUint8ArrayMemory0 = null;
133
+ function getUint8ArrayMemory0() {
134
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
135
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
136
+ }
137
+ return cachedUint8ArrayMemory0;
138
+ }
139
+
140
+ function isLikeNone(x) {
141
+ return x === undefined || x === null;
142
+ }
143
+
144
+ function passStringToWasm0(arg, malloc, realloc) {
145
+ if (realloc === undefined) {
146
+ const buf = cachedTextEncoder.encode(arg);
147
+ const ptr = malloc(buf.length, 1) >>> 0;
148
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
149
+ WASM_VECTOR_LEN = buf.length;
150
+ return ptr;
151
+ }
152
+
153
+ let len = arg.length;
154
+ let ptr = malloc(len, 1) >>> 0;
155
+
156
+ const mem = getUint8ArrayMemory0();
157
+
158
+ let offset = 0;
159
+
160
+ for (; offset < len; offset++) {
161
+ const code = arg.charCodeAt(offset);
162
+ if (code > 0x7F) break;
163
+ mem[ptr + offset] = code;
164
+ }
165
+ if (offset !== len) {
166
+ if (offset !== 0) {
167
+ arg = arg.slice(offset);
168
+ }
169
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
170
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
171
+ const ret = cachedTextEncoder.encodeInto(arg, view);
172
+
173
+ offset += ret.written;
174
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
175
+ }
176
+
177
+ WASM_VECTOR_LEN = offset;
178
+ return ptr;
179
+ }
180
+
181
+ function takeFromExternrefTable0(idx) {
182
+ const value = wasm.__wbindgen_externrefs.get(idx);
183
+ wasm.__externref_table_dealloc(idx);
184
+ return value;
185
+ }
186
+
187
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
188
+ cachedTextDecoder.decode();
189
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
190
+ let numBytesDecoded = 0;
191
+ function decodeText(ptr, len) {
192
+ numBytesDecoded += len;
193
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
194
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
195
+ cachedTextDecoder.decode();
196
+ numBytesDecoded = len;
197
+ }
198
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
199
+ }
200
+
201
+ const cachedTextEncoder = new TextEncoder();
202
+
203
+ if (!('encodeInto' in cachedTextEncoder)) {
204
+ cachedTextEncoder.encodeInto = function (arg, view) {
205
+ const buf = cachedTextEncoder.encode(arg);
206
+ view.set(buf);
207
+ return {
208
+ read: arg.length,
209
+ written: buf.length
210
+ };
211
+ };
212
+ }
213
+
214
+ let WASM_VECTOR_LEN = 0;
215
+
216
+ let wasmModule, wasm;
217
+ function __wbg_finalize_init(instance, module) {
218
+ wasm = instance.exports;
219
+ wasmModule = module;
220
+ cachedDataViewMemory0 = null;
221
+ cachedUint8ArrayMemory0 = null;
222
+ wasm.__wbindgen_start();
223
+ return wasm;
224
+ }
225
+
226
+ async function __wbg_load(module, imports) {
227
+ if (typeof Response === 'function' && module instanceof Response) {
228
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
229
+ try {
230
+ return await WebAssembly.instantiateStreaming(module, imports);
231
+ } catch (e) {
232
+ const validResponse = module.ok && expectedResponseType(module.type);
233
+
234
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
235
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
236
+
237
+ } else { throw e; }
238
+ }
239
+ }
240
+
241
+ const bytes = await module.arrayBuffer();
242
+ return await WebAssembly.instantiate(bytes, imports);
243
+ } else {
244
+ const instance = await WebAssembly.instantiate(module, imports);
245
+
246
+ if (instance instanceof WebAssembly.Instance) {
247
+ return { instance, module };
248
+ } else {
249
+ return instance;
250
+ }
251
+ }
252
+
253
+ function expectedResponseType(type) {
254
+ switch (type) {
255
+ case 'basic': case 'cors': case 'default': return true;
256
+ }
257
+ return false;
258
+ }
259
+ }
260
+
261
+ function initSync(module) {
262
+ if (wasm !== undefined) return wasm;
263
+
264
+
265
+ if (module !== undefined) {
266
+ if (Object.getPrototypeOf(module) === Object.prototype) {
267
+ ({module} = module)
268
+ } else {
269
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
270
+ }
271
+ }
272
+
273
+ const imports = __wbg_get_imports();
274
+ if (!(module instanceof WebAssembly.Module)) {
275
+ module = new WebAssembly.Module(module);
276
+ }
277
+ const instance = new WebAssembly.Instance(module, imports);
278
+ return __wbg_finalize_init(instance, module);
279
+ }
280
+
281
+ async function __wbg_init(module_or_path) {
282
+ if (wasm !== undefined) return wasm;
283
+
284
+
285
+ if (module_or_path !== undefined) {
286
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
287
+ ({module_or_path} = module_or_path)
288
+ } else {
289
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
290
+ }
291
+ }
292
+
293
+ if (module_or_path === undefined) {
294
+ module_or_path = new URL('groq_wasm_bg.wasm', import.meta.url);
295
+ }
296
+ const imports = __wbg_get_imports();
297
+
298
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
299
+ module_or_path = fetch(module_or_path);
300
+ }
301
+
302
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
303
+
304
+ return __wbg_finalize_init(instance, module);
305
+ }
306
+
307
+ export { initSync, __wbg_init as default };
Binary file
package/dist/index.cjs DELETED
@@ -1,253 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- DEFAULT_WIDTH: () => DEFAULT_WIDTH,
34
- RULE_ID_MAP: () => RULE_ID_MAP,
35
- WasmError: () => WasmError,
36
- format: () => format,
37
- formatAsync: () => formatAsync,
38
- initWasm: () => initWasm,
39
- isInitialized: () => isInitialized,
40
- isValidSyntax: () => isValidSyntax,
41
- lint: () => lint,
42
- lintAsync: () => lintAsync,
43
- mapRuleId: () => mapRuleId,
44
- mapSeverity: () => mapSeverity
45
- });
46
- module.exports = __toCommonJS(index_exports);
47
-
48
- // src/types.ts
49
- function mapSeverity(wasmSeverity) {
50
- switch (wasmSeverity) {
51
- case "high":
52
- return "error";
53
- case "medium":
54
- return "warning";
55
- case "low":
56
- return "info";
57
- }
58
- }
59
- var WasmError = class extends Error {
60
- constructor(message, code) {
61
- super(message);
62
- this.code = code;
63
- this.name = "WasmError";
64
- }
65
- };
66
- var RULE_ID_MAP = {
67
- join_in_filter: "join-in-filter",
68
- join_to_get_id: "join-to-get-id",
69
- computed_value_in_filter: "computed-value-in-filter",
70
- match_on_id: "match-on-id",
71
- order_on_expr: "order-on-expr",
72
- deep_pagination: "deep-pagination",
73
- large_pages: "large-pages",
74
- non_literal_comparison: "non-literal-comparison",
75
- repeated_dereference: "repeated-dereference",
76
- count_in_correlated_subquery: "count-in-correlated-subquery",
77
- very_large_query: "very-large-query",
78
- extremely_large_query: "extremely-large-query",
79
- many_joins: "many-joins"
80
- };
81
- function mapRuleId(rustRuleId) {
82
- return RULE_ID_MAP[rustRuleId] ?? rustRuleId.replace(/_/g, "-");
83
- }
84
-
85
- // src/wasm-loader.ts
86
- var import_meta = {};
87
- var initialized = false;
88
- var initPromise = null;
89
- var wasmLint = null;
90
- var wasmFormat = null;
91
- function isInitialized() {
92
- return initialized;
93
- }
94
- async function initWasm() {
95
- if (initialized) {
96
- return;
97
- }
98
- if (initPromise) {
99
- return initPromise;
100
- }
101
- initPromise = doInit();
102
- await initPromise;
103
- }
104
- async function doInit() {
105
- try {
106
- const { createRequire } = await import("module");
107
- const { fileURLToPath } = await import("url");
108
- const { dirname, join } = await import("path");
109
- const currentDir = dirname(fileURLToPath(import_meta.url));
110
- const require2 = createRequire(import_meta.url);
111
- const wasmPath = join(currentDir, "..", "wasm", "groq_wasm.cjs");
112
- const wasm = require2(wasmPath);
113
- wasmLint = wasm.lint;
114
- wasmFormat = wasm.format;
115
- initialized = true;
116
- } catch (error) {
117
- initPromise = null;
118
- throw new WasmError(
119
- `Failed to initialize WASM: ${error instanceof Error ? error.message : String(error)}`,
120
- "WASM_ERROR"
121
- );
122
- }
123
- }
124
- function callLint(query) {
125
- if (!initialized || !wasmLint) {
126
- throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
127
- }
128
- return wasmLint(query);
129
- }
130
- function callFormat(query, width) {
131
- if (!initialized || !wasmFormat) {
132
- throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
133
- }
134
- return wasmFormat(query, width ?? null);
135
- }
136
-
137
- // src/lint.ts
138
- function lint(query, config) {
139
- if (!isInitialized()) {
140
- throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
141
- }
142
- if (!query.trim()) {
143
- return [];
144
- }
145
- try {
146
- const resultJson = callLint(query);
147
- const wasmFindings = JSON.parse(resultJson);
148
- let findings = wasmFindings;
149
- if (config?.rules) {
150
- const rules = config.rules;
151
- findings = findings.filter((f) => {
152
- const enabled = rules[f.ruleId];
153
- return enabled !== false;
154
- });
155
- }
156
- return findings.map((wf) => convertFinding(wf, query));
157
- } catch (error) {
158
- if (error instanceof WasmError) {
159
- throw error;
160
- }
161
- const message = error instanceof Error ? error.message : String(error);
162
- if (message.includes("parse") || message.includes("Parse")) {
163
- throw new WasmError(`Failed to parse query: ${message}`, "PARSE_ERROR");
164
- }
165
- throw new WasmError(`Lint failed: ${message}`, "WASM_ERROR");
166
- }
167
- }
168
- async function lintAsync(query, config) {
169
- return lint(query, config);
170
- }
171
- function convertFinding(wf, query) {
172
- return {
173
- ruleId: mapRuleId(wf.ruleId),
174
- message: wf.message,
175
- severity: mapSeverity(wf.severity),
176
- span: byteSpanToSourceSpan(wf.start, wf.end, query)
177
- };
178
- }
179
- function byteSpanToSourceSpan(startByte, endByte, query) {
180
- return {
181
- start: byteOffsetToLocation(startByte, query),
182
- end: byteOffsetToLocation(endByte, query)
183
- };
184
- }
185
- function byteOffsetToLocation(offset, query) {
186
- let line = 1;
187
- let column = 1;
188
- let currentOffset = 0;
189
- for (const char of query) {
190
- if (currentOffset >= offset) {
191
- break;
192
- }
193
- if (char === "\n") {
194
- line++;
195
- column = 1;
196
- } else {
197
- column++;
198
- }
199
- currentOffset++;
200
- }
201
- return { line, column, offset };
202
- }
203
-
204
- // src/format.ts
205
- var DEFAULT_WIDTH = 80;
206
- function format(query, config) {
207
- if (!isInitialized()) {
208
- throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
209
- }
210
- const width = config?.width ?? DEFAULT_WIDTH;
211
- if (!query.trim()) {
212
- return query;
213
- }
214
- try {
215
- return callFormat(query, width);
216
- } catch (error) {
217
- const message = error instanceof Error ? error.message : String(error);
218
- if (message.includes("parse") || message.includes("Parse")) {
219
- throw new WasmError(`Failed to parse query: ${message}`, "PARSE_ERROR");
220
- }
221
- throw new WasmError(`Format failed: ${message}`, "WASM_ERROR");
222
- }
223
- }
224
- async function formatAsync(query, config) {
225
- return format(query, config);
226
- }
227
- function isValidSyntax(query) {
228
- try {
229
- format(query);
230
- return true;
231
- } catch (error) {
232
- if (error instanceof WasmError && error.code === "PARSE_ERROR") {
233
- return false;
234
- }
235
- throw error;
236
- }
237
- }
238
- // Annotate the CommonJS export names for ESM import in node:
239
- 0 && (module.exports = {
240
- DEFAULT_WIDTH,
241
- RULE_ID_MAP,
242
- WasmError,
243
- format,
244
- formatAsync,
245
- initWasm,
246
- isInitialized,
247
- isValidSyntax,
248
- lint,
249
- lintAsync,
250
- mapRuleId,
251
- mapSeverity
252
- });
253
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/wasm-loader.ts","../src/lint.ts","../src/format.ts"],"sourcesContent":["/**\n * @sanity-labs/groq-wasm\n *\n * WASM bindings for GROQ linting and formatting.\n *\n * This package provides TypeScript wrappers around:\n * - groq-lint (Rust) - GROQ query linting\n * - groq-format (Rust) - GROQ query formatting\n *\n * Both are compiled to WebAssembly for use in Node.js and browsers\n * without requiring the Rust toolchain.\n *\n * @example\n * ```typescript\n * import { initWasm, lint, format } from '@sanity-labs/groq-wasm'\n *\n * // Initialize WASM (call once at startup)\n * await initWasm()\n *\n * // Lint a query\n * const findings = lint('*[_type == \"post\"]{ author-> }')\n * console.log(findings)\n * // [{ ruleId: 'join-in-filter', message: '...', severity: 'error' }]\n *\n * // Format a query\n * const formatted = format('*[_type==\"post\"]{title,body}')\n * console.log(formatted)\n * // '*[_type == \"post\"]{ title, body }'\n * ```\n *\n * @packageDocumentation\n */\n\n// Re-export from lint module\nexport { lint, lintAsync } from './lint.js'\n\n// Re-export from format module\nexport { DEFAULT_WIDTH, format, formatAsync, isValidSyntax } from './format.js'\n\n// Re-export from wasm-loader\nexport { initWasm, isInitialized } from './wasm-loader.js'\n\n// Re-export types\nexport {\n mapRuleId,\n mapSeverity,\n RULE_ID_MAP,\n WasmError,\n type WasmFinding,\n type WasmFormatConfig,\n type WasmLintConfig,\n type WasmSeverity,\n} from './types.js'\n","/**\n * Types for @sanity-labs/groq-wasm\n *\n * These types match the Rust API from groq-lint and groq-format,\n * converted to TypeScript conventions (snake_case → camelCase).\n */\n\n/**\n * Severity levels matching Rust groq-lint\n * Rust: High, Medium, Low → TS: error, warning, info\n */\nexport type WasmSeverity = 'high' | 'medium' | 'low'\n\n/**\n * Map WASM severity to our standard severity\n */\nexport function mapSeverity(wasmSeverity: WasmSeverity): 'error' | 'warning' | 'info' {\n switch (wasmSeverity) {\n case 'high':\n return 'error'\n case 'medium':\n return 'warning'\n case 'low':\n return 'info'\n }\n}\n\n/**\n * A finding from the Rust linter (JSON format from WASM)\n */\nexport interface WasmFinding {\n /** Rule ID (snake_case from Rust) */\n ruleId: string\n /** Human-readable message */\n message: string\n /** Severity level */\n severity: WasmSeverity\n /** Start byte offset (0-based) */\n start: number\n /** End byte offset (0-based) */\n end: number\n}\n\n/**\n * Configuration for linting\n */\nexport interface WasmLintConfig {\n /** Rules to enable/disable (rule_id → enabled) */\n rules?: Record<string, boolean>\n}\n\n/**\n * Configuration for formatting\n */\nexport interface WasmFormatConfig {\n /** Maximum line width (default: 80) */\n width?: number\n}\n\n/**\n * Error from WASM operations\n */\nexport class WasmError extends Error {\n constructor(\n message: string,\n public readonly code: 'NOT_INITIALIZED' | 'PARSE_ERROR' | 'WASM_ERROR'\n ) {\n super(message)\n this.name = 'WasmError'\n }\n}\n\n/**\n * Rule ID mapping from Rust (snake_case) to TS (kebab-case)\n */\nexport const RULE_ID_MAP: Record<string, string> = {\n join_in_filter: 'join-in-filter',\n join_to_get_id: 'join-to-get-id',\n computed_value_in_filter: 'computed-value-in-filter',\n match_on_id: 'match-on-id',\n order_on_expr: 'order-on-expr',\n deep_pagination: 'deep-pagination',\n large_pages: 'large-pages',\n non_literal_comparison: 'non-literal-comparison',\n repeated_dereference: 'repeated-dereference',\n count_in_correlated_subquery: 'count-in-correlated-subquery',\n very_large_query: 'very-large-query',\n extremely_large_query: 'extremely-large-query',\n many_joins: 'many-joins',\n}\n\n/**\n * Convert Rust rule ID to TS convention\n */\nexport function mapRuleId(rustRuleId: string): string {\n return RULE_ID_MAP[rustRuleId] ?? rustRuleId.replace(/_/g, '-')\n}\n","/**\n * WASM Module Loader\n *\n * Handles loading and initializing the WASM modules for groq-lint and groq-format.\n * Currently supports Node.js environments.\n */\n\nimport { WasmError } from './types.js'\n\n// WASM module state\nlet initialized = false\nlet initPromise: Promise<void> | null = null\n\n// WASM module functions (set after initialization)\nlet wasmLint: ((query: string) => string) | null = null\nlet wasmFormat: ((query: string, width?: number | null) => string) | null = null\n\n/**\n * Check if WASM modules are initialized\n */\nexport function isInitialized(): boolean {\n return initialized\n}\n\n/**\n * Initialize WASM modules\n *\n * Call this once at application startup. Safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { initWasm } from '@sanity-labs/groq-wasm'\n *\n * await initWasm()\n * // Now lint() and format() are ready to use\n * ```\n */\nexport async function initWasm(): Promise<void> {\n if (initialized) {\n return\n }\n\n if (initPromise) {\n return initPromise\n }\n\n initPromise = doInit()\n await initPromise\n}\n\nasync function doInit(): Promise<void> {\n try {\n // Dynamic import for the CommonJS WASM module\n // The wasm-pack nodejs target generates CJS with synchronous WASM loading\n const { createRequire } = await import('node:module')\n const { fileURLToPath } = await import('node:url')\n const { dirname, join } = await import('node:path')\n\n // Create a require function that can load CJS modules\n const currentDir = dirname(fileURLToPath(import.meta.url))\n const require = createRequire(import.meta.url)\n\n // Load the WASM module - it will synchronously initialize\n // Use .cjs extension since wasm-pack generates CJS and our package uses \"type\": \"module\"\n const wasmPath = join(currentDir, '..', 'wasm', 'groq_wasm.cjs')\n const wasm = require(wasmPath)\n\n // Store the functions\n wasmLint = wasm.lint\n wasmFormat = wasm.format\n\n initialized = true\n } catch (error) {\n initPromise = null\n throw new WasmError(\n `Failed to initialize WASM: ${error instanceof Error ? error.message : String(error)}`,\n 'WASM_ERROR'\n )\n }\n}\n\n/**\n * Call the WASM lint function\n * @throws {WasmError} If not initialized\n */\nexport function callLint(query: string): string {\n if (!initialized || !wasmLint) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n return wasmLint(query)\n}\n\n/**\n * Call the WASM format function\n * @throws {WasmError} If not initialized\n */\nexport function callFormat(query: string, width?: number): string {\n if (!initialized || !wasmFormat) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n return wasmFormat(query, width ?? null)\n}\n","/**\n * GROQ Linting via WASM\n *\n * Wraps the Rust groq-lint library compiled to WASM.\n */\n\nimport type { Finding, SourceLocation, SourceSpan } from '@sanity-labs/lint-core'\nimport {\n mapRuleId,\n mapSeverity,\n WasmError,\n type WasmFinding,\n type WasmLintConfig,\n} from './types.js'\nimport { callLint, isInitialized } from './wasm-loader.js'\n\n/**\n * Lint a GROQ query using the WASM-based linter\n *\n * @param query - The GROQ query string to lint\n * @param config - Optional configuration\n * @returns Array of findings\n * @throws {WasmError} If WASM is not initialized or query parsing fails\n *\n * @example\n * ```typescript\n * import { initWasm, lint } from '@sanity-labs/groq-wasm'\n *\n * await initWasm()\n *\n * const findings = lint('*[_type == \"post\"]{ author-> }')\n * // [{ ruleId: 'join-in-filter', message: '...', severity: 'error' }]\n * ```\n */\nexport function lint(query: string, config?: WasmLintConfig): Finding[] {\n if (!isInitialized()) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n\n // Handle empty query - nothing to lint\n if (!query.trim()) {\n return []\n }\n\n try {\n // Call WASM function - returns JSON string\n const resultJson = callLint(query)\n const wasmFindings: WasmFinding[] = JSON.parse(resultJson)\n\n // Filter by config if provided\n let findings = wasmFindings\n if (config?.rules) {\n const rules = config.rules\n findings = findings.filter((f) => {\n const enabled = rules[f.ruleId]\n return enabled !== false\n })\n }\n\n // Convert to our Finding type\n return findings.map((wf) => convertFinding(wf, query))\n } catch (error) {\n if (error instanceof WasmError) {\n throw error\n }\n\n // Parse errors from WASM come as thrown strings/errors\n const message = error instanceof Error ? error.message : String(error)\n\n if (message.includes('parse') || message.includes('Parse')) {\n throw new WasmError(`Failed to parse query: ${message}`, 'PARSE_ERROR')\n }\n\n throw new WasmError(`Lint failed: ${message}`, 'WASM_ERROR')\n }\n}\n\n/**\n * Async version of lint for environments that prefer promises\n */\nexport async function lintAsync(query: string, config?: WasmLintConfig): Promise<Finding[]> {\n // WASM operations are synchronous, but we provide async API\n // for consistency and future-proofing (e.g., if we add worker support)\n return lint(query, config)\n}\n\n/**\n * Convert WASM finding to our Finding type\n */\nfunction convertFinding(wf: WasmFinding, query: string): Finding {\n return {\n ruleId: mapRuleId(wf.ruleId),\n message: wf.message,\n severity: mapSeverity(wf.severity),\n span: byteSpanToSourceSpan(wf.start, wf.end, query),\n }\n}\n\n/**\n * Convert byte offsets to line/column source span\n */\nfunction byteSpanToSourceSpan(startByte: number, endByte: number, query: string): SourceSpan {\n return {\n start: byteOffsetToLocation(startByte, query),\n end: byteOffsetToLocation(endByte, query),\n }\n}\n\n/**\n * Convert byte offset to line/column location\n */\nfunction byteOffsetToLocation(offset: number, query: string): SourceLocation {\n let line = 1\n let column = 1\n let currentOffset = 0\n\n for (const char of query) {\n if (currentOffset >= offset) {\n break\n }\n\n if (char === '\\n') {\n line++\n column = 1\n } else {\n column++\n }\n\n currentOffset++\n }\n\n return { line, column, offset }\n}\n","/**\n * GROQ Formatting via WASM\n *\n * Wraps the Rust groq-format library compiled to WASM.\n */\n\nimport { WasmError, type WasmFormatConfig } from './types.js'\nimport { callFormat, isInitialized } from './wasm-loader.js'\n\n/**\n * Default line width for formatting\n * Matches Rust groq-format DEFAULT_WIDTH\n */\nexport const DEFAULT_WIDTH = 80\n\n/**\n * Format a GROQ query using the WASM-based formatter\n *\n * @param query - The GROQ query string to format\n * @param config - Optional configuration (width defaults to 80)\n * @returns Formatted query string\n * @throws {WasmError} If WASM is not initialized or query parsing fails\n *\n * @example\n * ```typescript\n * import { initWasm, format } from '@sanity-labs/groq-wasm'\n *\n * await initWasm()\n *\n * const formatted = format('*[_type==\"post\"]{title,body}')\n * // '*[_type == \"post\"]{ title, body }'\n * ```\n */\nexport function format(query: string, config?: WasmFormatConfig): string {\n if (!isInitialized()) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n\n const width = config?.width ?? DEFAULT_WIDTH\n\n // Handle empty query\n if (!query.trim()) {\n return query\n }\n\n try {\n return callFormat(query, width)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n\n if (message.includes('parse') || message.includes('Parse')) {\n throw new WasmError(`Failed to parse query: ${message}`, 'PARSE_ERROR')\n }\n\n throw new WasmError(`Format failed: ${message}`, 'WASM_ERROR')\n }\n}\n\n/**\n * Async version of format for environments that prefer promises\n */\nexport async function formatAsync(query: string, config?: WasmFormatConfig): Promise<string> {\n // WASM operations are synchronous, but we provide async API\n // for consistency and future-proofing\n return format(query, config)\n}\n\n/**\n * Check if a query can be parsed (without full formatting)\n *\n * @param query - The GROQ query to validate\n * @returns true if the query is valid GROQ syntax\n */\nexport function isValidSyntax(query: string): boolean {\n try {\n format(query)\n return true\n } catch (error) {\n if (error instanceof WasmError && error.code === 'PARSE_ERROR') {\n return false\n }\n // Re-throw other errors\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACgBO,SAAS,YAAY,cAA0D;AACpF,UAAQ,cAAc;AAAA,IACpB,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,EACX;AACF;AAqCO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,cAAsC;AAAA,EACjD,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,0BAA0B;AAAA,EAC1B,aAAa;AAAA,EACb,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb,wBAAwB;AAAA,EACxB,sBAAsB;AAAA,EACtB,8BAA8B;AAAA,EAC9B,kBAAkB;AAAA,EAClB,uBAAuB;AAAA,EACvB,YAAY;AACd;AAKO,SAAS,UAAU,YAA4B;AACpD,SAAO,YAAY,UAAU,KAAK,WAAW,QAAQ,MAAM,GAAG;AAChE;;;AChGA;AAUA,IAAI,cAAc;AAClB,IAAI,cAAoC;AAGxC,IAAI,WAA+C;AACnD,IAAI,aAAwE;AAKrE,SAAS,gBAAyB;AACvC,SAAO;AACT;AAeA,eAAsB,WAA0B;AAC9C,MAAI,aAAa;AACf;AAAA,EACF;AAEA,MAAI,aAAa;AACf,WAAO;AAAA,EACT;AAEA,gBAAc,OAAO;AACrB,QAAM;AACR;AAEA,eAAe,SAAwB;AACrC,MAAI;AAGF,UAAM,EAAE,cAAc,IAAI,MAAM,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