@query-farm/vgi 0.39.0 → 0.41.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/dist/index.js CHANGED
@@ -8676,6 +8676,14 @@ function resolveMetadata(func) {
8676
8676
 
8677
8677
  // src/catalog/attach-option.ts
8678
8678
  init_arrow();
8679
+ var RESERVED_ATTACH_OPTION = "vgi_attach_ticket";
8680
+ function assertNoReservedAttachOption(specs) {
8681
+ for (const spec of specs) {
8682
+ if (spec.name.toLowerCase() === RESERVED_ATTACH_OPTION) {
8683
+ throw new Error(`Attach option '${spec.name}' uses the reserved name '${RESERVED_ATTACH_OPTION}': the framework ` + "reads it as an attach ticket before any catalog code runs. Rename the option.");
8684
+ }
8685
+ }
8686
+ }
8679
8687
  var SPEC_SCHEMA = schema2([
8680
8688
  field2("name", utf82(), false),
8681
8689
  field2("description", utf82(), false),
@@ -8685,6 +8693,7 @@ var SPEC_SCHEMA = schema2([
8685
8693
  field2("secret", bool2(), true)
8686
8694
  ]);
8687
8695
  function serializeAttachOptionSpec(spec) {
8696
+ assertNoReservedAttachOption([spec]);
8688
8697
  if (spec.required && spec.default !== undefined && spec.default !== null) {
8689
8698
  throw new Error(`Attach option '${spec.name}' is required but also declares a default ` + `(${JSON.stringify(spec.default)}); an option with a default is always ` + "satisfiable without the caller. Drop one.");
8690
8699
  }
@@ -8747,6 +8756,8 @@ class MissingAttachOptionsError extends Error {
8747
8756
  }
8748
8757
  }
8749
8758
  function validateRequiredAttachOptions(catalogName, specs, options) {
8759
+ specs = Array.from(specs);
8760
+ assertNoReservedAttachOption(specs);
8750
8761
  const supplied = new Set(Object.keys(options).map((key) => key.toLowerCase()));
8751
8762
  const missing = Array.from(specs).filter((spec) => spec.required && !supplied.has(spec.name.toLowerCase())).map((spec) => spec.name);
8752
8763
  if (missing.length > 0) {
@@ -8754,6 +8765,41 @@ function validateRequiredAttachOptions(catalogName, specs, options) {
8754
8765
  }
8755
8766
  }
8756
8767
 
8768
+ class ReservedAttachOptionError extends Error {
8769
+ constructor(message) {
8770
+ super(message);
8771
+ this.name = "ReservedAttachOptionError";
8772
+ }
8773
+ }
8774
+ async function checkReservedAttachOptions(catalog) {
8775
+ if (!catalog?.catalogsInfo)
8776
+ return;
8777
+ let infos;
8778
+ try {
8779
+ infos = await catalog.catalogsInfo();
8780
+ } catch (e) {
8781
+ if (e instanceof Error && e.message.includes(`reserved name '${RESERVED_ATTACH_OPTION}'`)) {
8782
+ throw new ReservedAttachOptionError(e.message);
8783
+ }
8784
+ return;
8785
+ }
8786
+ for (const info of infos ?? []) {
8787
+ for (const raw of info.attach_option_specs ?? []) {
8788
+ let name;
8789
+ try {
8790
+ name = deserializeAttachOptionSpec(toUint8Array(raw)).name;
8791
+ } catch {
8792
+ continue;
8793
+ }
8794
+ try {
8795
+ assertNoReservedAttachOption([{ name }]);
8796
+ } catch (e) {
8797
+ throw new ReservedAttachOptionError(e.message);
8798
+ }
8799
+ }
8800
+ }
8801
+ }
8802
+
8757
8803
  // src/catalog/item-encoding.ts
8758
8804
  var ENCODED = new WeakMap;
8759
8805
  function freezeCatalogItem(item) {
@@ -9513,1533 +9559,1536 @@ function sameSpelling(left, right) {
9513
9559
  const b = normalizeSchemaPath(right);
9514
9560
  return a.length === b.length && a.every((part, i) => part === b[i]);
9515
9561
  }
9516
- // src/catalog/composite.ts
9517
- var ROUTE_BYTE = 0;
9518
-
9519
- class CompositeCatalogInterface extends CatalogInterface {
9520
- _backends;
9521
- constructor(_backends) {
9522
- super();
9523
- this._backends = _backends;
9524
- if (_backends.length > 256) {
9525
- throw new Error("CompositeCatalog: at most 256 backends supported");
9526
- }
9562
+ // node_modules/@noble/ciphers/utils.js
9563
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
9564
+ function isBytes(a) {
9565
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
9566
+ }
9567
+ var atitle = (title) => title ? `"${title}" ` : "";
9568
+ function abool(value, title = "") {
9569
+ if (typeof value !== "boolean")
9570
+ throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
9571
+ return value;
9572
+ }
9573
+ function anumber(n, title = "") {
9574
+ if (typeof n !== "number")
9575
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
9576
+ if (!Number.isSafeInteger(n) || n < 0)
9577
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
9578
+ return n;
9579
+ }
9580
+ function abytes(value, length, title = "") {
9581
+ if (isBytes(value) && (length === undefined || value.length === length))
9582
+ return value;
9583
+ if (length !== undefined)
9584
+ anumber(length, "length");
9585
+ const bytes = isBytes(value);
9586
+ const ofLen = length !== undefined ? ` of length ${length}` : "";
9587
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
9588
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
9589
+ if (!bytes)
9590
+ throw new TypeError(message);
9591
+ throw new RangeError(message);
9592
+ }
9593
+ var aobject = (value, label) => {
9594
+ if (value === null || typeof value !== "object" || Array.isArray(value))
9595
+ throw new TypeError(label === "object" ? "expected valid options object" : `"${label}" expected object, got type=${typeof value}`);
9596
+ };
9597
+ function aexists(instance, checkFinished = true) {
9598
+ if (instance.destroyed)
9599
+ throw new Error("hash was destroyed");
9600
+ if (checkFinished && instance.finished)
9601
+ throw new Error("digest() was already called");
9602
+ }
9603
+ function aoutput(out, instance) {
9604
+ abytes(out, undefined, "output");
9605
+ const min = instance.outputLen;
9606
+ if (!(out.length >= min)) {
9607
+ throw new RangeError('"output" expected length >= ' + min);
9527
9608
  }
9528
- _route(attachOpaqueData) {
9529
- const idx = attachOpaqueData[ROUTE_BYTE];
9530
- const route = this._backends[idx];
9531
- if (!route) {
9532
- throw new Error(`CompositeCatalog: no backend at route-byte index ${idx} (have ${this._backends.length})`);
9533
- }
9534
- return route;
9609
+ }
9610
+ function u32(arr) {
9611
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
9612
+ }
9613
+ function clean(...arrays) {
9614
+ for (let i = 0;i < arrays.length; i++) {
9615
+ arrays[i].fill(0);
9535
9616
  }
9536
- catalogNameForAttach(attachOpaqueData) {
9537
- try {
9538
- return this._route(attachOpaqueData).catalogNameForAttach(attachOpaqueData);
9539
- } catch {
9540
- return null;
9541
- }
9617
+ }
9618
+ function createView(arr) {
9619
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9620
+ }
9621
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
9622
+ function byteSwap(word) {
9623
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
9624
+ }
9625
+ function byteSwap32(arr) {
9626
+ for (let i = 0;i < arr.length; i++) {
9627
+ arr[i] = byteSwap(arr[i]);
9542
9628
  }
9543
- catalogs() {
9544
- const all = [];
9545
- for (const b of this._backends)
9546
- all.push(...b.catalogs());
9547
- return all;
9629
+ return arr;
9630
+ }
9631
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
9632
+ function checkOpts(defaults, opts) {
9633
+ aobject(defaults, "defaults");
9634
+ aobject(opts, "opts");
9635
+ const merged = Object.assign(defaults, opts);
9636
+ return merged;
9637
+ }
9638
+ function equalBytes(a, b) {
9639
+ a = abytes(a);
9640
+ b = abytes(b);
9641
+ if (a.length !== b.length)
9642
+ return false;
9643
+ let diff = 0;
9644
+ for (let i = 0;i < a.length; i++)
9645
+ diff |= a[i] ^ b[i];
9646
+ return diff === 0;
9647
+ }
9648
+ function wrapMacConstructor(keyLen, macCons, fromMsg) {
9649
+ const mac = macCons;
9650
+ const getArgs = fromMsg || (() => []);
9651
+ const macC = (msg, key) => mac(key, ...getArgs(msg)).update(msg).digest();
9652
+ const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
9653
+ macC.outputLen = tmp.outputLen;
9654
+ macC.blockLen = tmp.blockLen;
9655
+ macC.create = (key, ...args) => mac(key, ...args);
9656
+ return macC;
9657
+ }
9658
+ var wrapCipher = (params, constructor) => {
9659
+ function wrappedCipher(key, ...args) {
9660
+ abytes(key, undefined, "key");
9661
+ if (params.nonceLength !== undefined) {
9662
+ const nonce = args[0];
9663
+ abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, "nonce");
9664
+ }
9665
+ const tagl = params.tagLength;
9666
+ const aadStart = params.nonceLength !== undefined ? 1 : 0;
9667
+ if (!params.withAAD) {
9668
+ for (let i = aadStart;i < args.length; i++)
9669
+ if (isBytes(args[i]))
9670
+ throw new Error("AAD not supported");
9671
+ }
9672
+ if (params.withAAD && args[aadStart] !== undefined)
9673
+ abytes(args[aadStart], undefined, "AAD");
9674
+ const cipher = constructor(key, ...args);
9675
+ const checkOutput = (fnLength, output) => {
9676
+ if (output !== undefined) {
9677
+ if (fnLength !== 2)
9678
+ throw new Error("cipher output not supported");
9679
+ abytes(output, undefined, "output");
9680
+ }
9681
+ };
9682
+ let called = false;
9683
+ const wrCipher = {
9684
+ encrypt(data, output) {
9685
+ if (called)
9686
+ throw new Error("cannot encrypt() twice with same key + nonce");
9687
+ called = true;
9688
+ abytes(data, undefined, "data");
9689
+ checkOutput(cipher.encrypt.length, output);
9690
+ return cipher.encrypt(data, output);
9691
+ },
9692
+ decrypt(data, output) {
9693
+ abytes(data, undefined, "data");
9694
+ if (tagl && data.length < tagl)
9695
+ throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
9696
+ checkOutput(cipher.decrypt.length, output);
9697
+ return cipher.decrypt(data, output);
9698
+ }
9699
+ };
9700
+ return wrCipher;
9548
9701
  }
9549
- async catalogsInfo() {
9550
- const all = [];
9551
- for (const b of this._backends) {
9552
- if (b.catalogsInfo) {
9553
- all.push(...await b.catalogsInfo());
9554
- } else {
9555
- for (const name of b.catalogs()) {
9556
- all.push({ name, implementation_version: null, data_version_spec: null, attach_option_specs: [], releases: [] });
9557
- }
9702
+ Object.assign(wrappedCipher, params);
9703
+ return wrappedCipher;
9704
+ };
9705
+ function getOutput(expectedLength, out, onlyAligned = true) {
9706
+ if (out === undefined)
9707
+ return new Uint8Array(expectedLength);
9708
+ abytes(out, expectedLength, "output");
9709
+ if (onlyAligned && !isAligned32(out))
9710
+ throw new Error("invalid output, must be aligned");
9711
+ return out;
9712
+ }
9713
+ function u64Lengths(dataLength, aadLength, isLE) {
9714
+ anumber(dataLength);
9715
+ anumber(aadLength);
9716
+ abool(isLE);
9717
+ const num = new Uint8Array(16);
9718
+ const view = createView(num);
9719
+ view.setBigUint64(0, BigInt(aadLength), isLE);
9720
+ view.setBigUint64(8, BigInt(dataLength), isLE);
9721
+ return num;
9722
+ }
9723
+ function isAligned32(bytes) {
9724
+ return bytes.byteOffset % 4 === 0;
9725
+ }
9726
+ function copyBytes(bytes) {
9727
+ return Uint8Array.from(abytes(bytes));
9728
+ }
9729
+
9730
+ // node_modules/@noble/ciphers/_arx.js
9731
+ var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
9732
+ var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))();
9733
+ var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))();
9734
+ function rotl(a, b) {
9735
+ return a << b | a >>> 32 - b;
9736
+ }
9737
+ var BLOCK_LEN = 64;
9738
+ var BLOCK_LEN32 = 16;
9739
+ var MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
9740
+ var U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
9741
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
9742
+ const len = data.length;
9743
+ const block = new Uint8Array(BLOCK_LEN);
9744
+ const b32 = u32(block);
9745
+ const isAligned = isLE && isAligned32(data) && isAligned32(output);
9746
+ const d32 = isAligned ? u32(data) : U32_EMPTY;
9747
+ const o32 = isAligned ? u32(output) : U32_EMPTY;
9748
+ if (!isLE) {
9749
+ for (let pos = 0;pos < len; counter++) {
9750
+ core(sigma, key, nonce, b32, counter, rounds);
9751
+ swap32IfBE(b32);
9752
+ if (counter >= MAX_COUNTER)
9753
+ throw new Error("arx: counter overflow");
9754
+ const take = Math.min(BLOCK_LEN, len - pos);
9755
+ for (let j = 0, posj;j < take; j++) {
9756
+ posj = pos + j;
9757
+ output[posj] = data[posj] ^ block[j];
9558
9758
  }
9759
+ pos += take;
9559
9760
  }
9560
- return all;
9761
+ return;
9561
9762
  }
9562
- async attach(name, options, dataVersionSpec, implementationVersion) {
9563
- for (let i = 0;i < this._backends.length; i++) {
9564
- const b = this._backends[i];
9565
- if (b.catalogs().includes(name)) {
9566
- const result = await b.attach(name, options, dataVersionSpec, implementationVersion);
9567
- const stamped = new Uint8Array(result.attach_opaque_data);
9568
- stamped[ROUTE_BYTE] = i;
9569
- result.attach_opaque_data = stamped;
9570
- return result;
9763
+ for (let pos = 0;pos < len; counter++) {
9764
+ core(sigma, key, nonce, b32, counter, rounds);
9765
+ if (counter >= MAX_COUNTER)
9766
+ throw new Error("arx: counter overflow");
9767
+ const take = Math.min(BLOCK_LEN, len - pos);
9768
+ if (isAligned && take === BLOCK_LEN) {
9769
+ const pos32 = pos / 4;
9770
+ if (pos % 4 !== 0)
9771
+ throw new Error("arx: invalid block position");
9772
+ for (let j = 0, posj;j < BLOCK_LEN32; j++) {
9773
+ posj = pos32 + j;
9774
+ o32[posj] = d32[posj] ^ b32[j];
9571
9775
  }
9776
+ pos += BLOCK_LEN;
9777
+ continue;
9572
9778
  }
9573
- throw new Error(`No worker handles catalog '${name}'`);
9574
- }
9575
- async detach(attachOpaqueData) {
9576
- await this._route(attachOpaqueData).detach(attachOpaqueData);
9577
- }
9578
- async version(attachOpaqueData, transactionOpaqueData) {
9579
- return await this._route(attachOpaqueData).version(attachOpaqueData, transactionOpaqueData);
9580
- }
9581
- async schemas(attachOpaqueData, transactionOpaqueData) {
9582
- return await this._route(attachOpaqueData).schemas(attachOpaqueData, transactionOpaqueData);
9583
- }
9584
- async schemaGet(attachOpaqueData, path, transactionOpaqueData) {
9585
- return await this._route(attachOpaqueData).schemaGet(attachOpaqueData, path, transactionOpaqueData);
9586
- }
9587
- async schemaContentsTables(attachOpaqueData, path, transactionOpaqueData) {
9588
- return await this._route(attachOpaqueData).schemaContentsTables(attachOpaqueData, path, transactionOpaqueData);
9589
- }
9590
- async schemaContentsViews(attachOpaqueData, path, transactionOpaqueData) {
9591
- return await this._route(attachOpaqueData).schemaContentsViews(attachOpaqueData, path, transactionOpaqueData);
9592
- }
9593
- async schemaContentsFunctions(attachOpaqueData, path, type, transactionOpaqueData) {
9594
- return await this._route(attachOpaqueData).schemaContentsFunctions(attachOpaqueData, path, type, transactionOpaqueData);
9595
- }
9596
- async schemaContentsMacros(attachOpaqueData, path, type, transactionOpaqueData) {
9597
- return await this._route(attachOpaqueData).schemaContentsMacros(attachOpaqueData, path, type, transactionOpaqueData);
9598
- }
9599
- async schemaContentsIndexes(attachOpaqueData, path, transactionOpaqueData) {
9600
- return await this._route(attachOpaqueData).schemaContentsIndexes(attachOpaqueData, path, transactionOpaqueData);
9601
- }
9602
- async indexGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9603
- return await this._route(attachOpaqueData).indexGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
9604
- }
9605
- async tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
9606
- return await this._route(attachOpaqueData).tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
9607
- }
9608
- async tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
9609
- return await this._route(attachOpaqueData).tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
9610
- }
9611
- async tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
9612
- return await this._route(attachOpaqueData).tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
9613
- }
9614
- async tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9615
- return await this._route(attachOpaqueData).tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
9616
- }
9617
- async viewGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9618
- return await this._route(attachOpaqueData).viewGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
9619
- }
9620
- async macroGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
9621
- return await this._route(attachOpaqueData).macroGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
9622
- }
9623
- async schemaCreate(...args) {
9624
- await this._route(args[0]).schemaCreate(...args);
9625
- }
9626
- async schemaDrop(...args) {
9627
- await this._route(args[0]).schemaDrop(...args);
9628
- }
9629
- async tableCreate(...args) {
9630
- await this._route(args[0]).tableCreate(...args);
9631
- }
9632
- async tableDrop(...args) {
9633
- await this._route(args[0]).tableDrop(...args);
9634
- }
9635
- async tableCommentSet(...args) {
9636
- await this._route(args[0]).tableCommentSet(...args);
9637
- }
9638
- async tableRename(...args) {
9639
- await this._route(args[0]).tableRename(...args);
9640
- }
9641
- async tableColumnAdd(...args) {
9642
- await this._route(args[0]).tableColumnAdd(...args);
9643
- }
9644
- async tableColumnDrop(...args) {
9645
- await this._route(args[0]).tableColumnDrop(...args);
9646
- }
9647
- async tableColumnRename(...args) {
9648
- await this._route(args[0]).tableColumnRename(...args);
9649
- }
9650
- async tableColumnDefaultSet(...args) {
9651
- await this._route(args[0]).tableColumnDefaultSet(...args);
9652
- }
9653
- async tableColumnDefaultDrop(...args) {
9654
- await this._route(args[0]).tableColumnDefaultDrop(...args);
9655
- }
9656
- async tableColumnTypeChange(...args) {
9657
- await this._route(args[0]).tableColumnTypeChange(...args);
9658
- }
9659
- async tableNotNullSet(...args) {
9660
- await this._route(args[0]).tableNotNullSet(...args);
9661
- }
9662
- async tableNotNullDrop(...args) {
9663
- await this._route(args[0]).tableNotNullDrop(...args);
9664
- }
9665
- async viewCreate(...args) {
9666
- await this._route(args[0]).viewCreate(...args);
9667
- }
9668
- async viewDrop(...args) {
9669
- await this._route(args[0]).viewDrop(...args);
9670
- }
9671
- async viewRename(...args) {
9672
- await this._route(args[0]).viewRename(...args);
9673
- }
9674
- async viewCommentSet(...args) {
9675
- await this._route(args[0]).viewCommentSet(...args);
9676
- }
9677
- async macroCreate(...args) {
9678
- await this._route(args[0]).macroCreate(...args);
9679
- }
9680
- async macroDrop(...args) {
9681
- await this._route(args[0]).macroDrop(...args);
9682
- }
9683
- async catalogContents(attachOpaqueData, ifNoneMatch) {
9684
- return await this._route(attachOpaqueData).catalogContents(attachOpaqueData, ifNoneMatch);
9685
- }
9686
- catalogContentsOwner(attachOpaqueData) {
9687
- return this._route(attachOpaqueData).catalogContentsOwner(attachOpaqueData);
9688
- }
9689
- async copyFromFormats(attachOpaqueData, transactionOpaqueData) {
9690
- return await this._route(attachOpaqueData).copyFromFormats(attachOpaqueData, transactionOpaqueData);
9691
- }
9692
- async transactionBegin(attachOpaqueData) {
9693
- return await this._route(attachOpaqueData).transactionBegin(attachOpaqueData);
9694
- }
9695
- async transactionCommit(attachOpaqueData, transactionOpaqueData) {
9696
- await this._route(attachOpaqueData).transactionCommit(attachOpaqueData, transactionOpaqueData);
9697
- }
9698
- async transactionRollback(attachOpaqueData, transactionOpaqueData) {
9699
- await this._route(attachOpaqueData).transactionRollback(attachOpaqueData, transactionOpaqueData);
9779
+ for (let j = 0, posj;j < take; j++) {
9780
+ posj = pos + j;
9781
+ output[posj] = data[posj] ^ block[j];
9782
+ }
9783
+ pos += take;
9700
9784
  }
9701
9785
  }
9702
- // src/functions/registry.ts
9703
- init_arrow();
9704
- var EXACT_MATCH_SCORE = 2;
9705
- var FAMILY_MATCH_SCORE = 1;
9706
- function typesIdentical(a, b) {
9707
- return typeSignature(a) === typeSignature(b);
9708
- }
9709
- function typesCompatible(actual, declared) {
9710
- if (typesIdentical(actual, declared))
9711
- return true;
9712
- if (isInt(actual) && isInt(declared))
9713
- return true;
9714
- if ((isFloat(actual) || isDecimal(actual)) && (isFloat(declared) || isDecimal(declared)))
9715
- return true;
9716
- if (isUtf8(actual) && isUtf8(declared))
9717
- return true;
9718
- if (isBinary(actual) && isBinary(declared))
9719
- return true;
9720
- if (isBool(actual) && isBool(declared))
9721
- return true;
9722
- return false;
9723
- }
9724
- function scoreTypes(specs, actualTypes) {
9725
- let score = 0;
9726
- let varArgsSpec = null;
9727
- for (let i = 0;i < specs.length; i++) {
9728
- const spec = specs[i];
9729
- if (spec.isVarargs)
9730
- varArgsSpec = spec;
9731
- if (i >= actualTypes.length)
9732
- break;
9733
- if (spec.isAnyType || isNull(spec.arrowType))
9734
- continue;
9735
- const actual = actualTypes[i];
9736
- if (actual === null)
9737
- continue;
9738
- if (typesIdentical(actual, spec.arrowType)) {
9739
- score += EXACT_MATCH_SCORE;
9740
- } else if (typesCompatible(actual, spec.arrowType)) {
9741
- score += FAMILY_MATCH_SCORE;
9786
+ function createCipher(core, opts) {
9787
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
9788
+ if (typeof core !== "function")
9789
+ throw new Error("core must be a function");
9790
+ anumber(counterLength);
9791
+ anumber(rounds);
9792
+ abool(counterRight);
9793
+ abool(allowShortKeys);
9794
+ return (key, nonce, data, output, counter = 0) => {
9795
+ abytes(key, undefined, "key");
9796
+ abytes(nonce, undefined, "nonce");
9797
+ abytes(data, undefined, "data");
9798
+ const len = data.length;
9799
+ output = getOutput(len, output, false);
9800
+ anumber(counter);
9801
+ if (counter < 0 || counter >= MAX_COUNTER)
9802
+ throw new Error("arx: counter overflow");
9803
+ const toClean = [];
9804
+ let l = key.length;
9805
+ let k;
9806
+ let sigma;
9807
+ if (l === 32) {
9808
+ toClean.push(k = copyBytes(key));
9809
+ sigma = sigma32_32;
9810
+ } else if (l === 16 && allowShortKeys) {
9811
+ k = new Uint8Array(32);
9812
+ k.set(key);
9813
+ k.set(key, 16);
9814
+ sigma = sigma16_32;
9815
+ toClean.push(k);
9742
9816
  } else {
9743
- return { score, matched: false };
9817
+ abytes(key, 32, "arx key");
9818
+ throw new Error("invalid key size");
9744
9819
  }
9745
- }
9746
- if (varArgsSpec && !varArgsSpec.isAnyType && !isNull(varArgsSpec.arrowType)) {
9747
- for (let i = specs.length;i < actualTypes.length; i++) {
9748
- const actual = actualTypes[i];
9749
- if (actual === null)
9750
- continue;
9751
- if (typesIdentical(actual, varArgsSpec.arrowType)) {
9752
- score += EXACT_MATCH_SCORE;
9753
- } else if (typesCompatible(actual, varArgsSpec.arrowType)) {
9754
- score += FAMILY_MATCH_SCORE;
9755
- } else {
9756
- return { score, matched: false };
9820
+ if (!isLE || !isAligned32(nonce))
9821
+ toClean.push(nonce = copyBytes(nonce));
9822
+ let k32 = u32(k);
9823
+ if (extendNonceFn) {
9824
+ if (nonce.length !== 24)
9825
+ throw new Error("arx: extended nonce must be 24 bytes");
9826
+ const n16 = nonce.subarray(0, 16);
9827
+ if (isLE)
9828
+ extendNonceFn(sigma, k32, u32(n16), k32);
9829
+ else {
9830
+ const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
9831
+ extendNonceFn(sigmaRaw, k32, u32(n16), k32);
9832
+ clean(sigmaRaw);
9833
+ swap32IfBE(k32);
9757
9834
  }
9835
+ nonce = nonce.subarray(16);
9836
+ } else if (!isLE)
9837
+ swap32IfBE(k32);
9838
+ const nonceNcLen = 16 - counterLength;
9839
+ if (nonceNcLen !== nonce.length)
9840
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
9841
+ if (nonceNcLen !== 12) {
9842
+ const nc = new Uint8Array(12);
9843
+ nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
9844
+ nonce = nc;
9845
+ toClean.push(nonce);
9758
9846
  }
9759
- }
9760
- return { score, matched: true };
9761
- }
9762
- function filterByArgumentTypes(candidates, args, inputSchema, isScalar) {
9763
- const scored = [];
9764
- for (const func of candidates) {
9765
- const specs = func.argumentSpecs;
9766
- let score = 0;
9767
- let matched = true;
9768
- if (isScalar) {
9769
- const constSpecs = specs.filter((s) => s.isConst);
9770
- const colSpecs = specs.filter((s) => !s.isConst && typeof s.position === "number");
9771
- const constTypes = [];
9772
- const argsSchema = args.argumentsSchema;
9773
- for (let i = 0;i < args.positional.length; i++) {
9774
- const field = argsSchema?.fields.find((f) => f.name === `positional_${i}`);
9775
- constTypes.push(field ? field.type : null);
9776
- }
9777
- const r1 = scoreTypes(constSpecs, constTypes);
9778
- score += r1.score;
9779
- matched = r1.matched;
9780
- if (matched && inputSchema) {
9781
- const colTypes = [];
9782
- let varArgsColSpec = null;
9783
- for (const spec of colSpecs) {
9784
- if (spec.isVarargs)
9785
- varArgsColSpec = spec;
9786
- const pos = spec.position;
9787
- colTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos].type : null);
9788
- }
9789
- if (varArgsColSpec) {
9790
- const start = varArgsColSpec.position + 1;
9791
- for (let i = start;i < inputSchema.fields.length; i++) {
9792
- colTypes.push(inputSchema.fields[i].type);
9793
- }
9794
- }
9795
- const r2 = scoreTypes(colSpecs, colTypes);
9796
- score += r2.score;
9797
- matched = r2.matched;
9798
- }
9799
- } else {
9800
- const posSpecs = specs.filter((s) => typeof s.position === "number" && !s.isTableInput).sort((a, b) => a.position - b.position);
9801
- const posTypes = [];
9802
- if (func.meta.inputFromArgs) {
9803
- if (inputSchema) {
9804
- let varArgsSpec = null;
9805
- for (const spec of posSpecs) {
9806
- if (spec.isVarargs)
9807
- varArgsSpec = spec;
9808
- const pos = spec.position;
9809
- posTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos].type : null);
9810
- }
9811
- if (varArgsSpec) {
9812
- for (let i = varArgsSpec.position + 1;i < inputSchema.fields.length; i++) {
9813
- posTypes.push(inputSchema.fields[i].type);
9814
- }
9815
- }
9816
- }
9817
- } else {
9818
- const argsSchema = args.argumentsSchema;
9819
- for (let i = 0;i < args.positional.length; i++) {
9820
- const field = argsSchema?.fields.find((f) => f.name === `positional_${i}`);
9821
- posTypes.push(field ? field.type : null);
9822
- }
9823
- }
9824
- const r = scoreTypes(posSpecs, posTypes);
9825
- score += r.score;
9826
- matched = r.matched;
9827
- }
9828
- if (matched) {
9829
- scored.push({ score, func });
9847
+ const n32 = swap32IfBE(u32(nonce));
9848
+ try {
9849
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
9850
+ return output;
9851
+ } finally {
9852
+ clean(...toClean);
9830
9853
  }
9831
- }
9832
- if (scored.length === 0)
9833
- return [];
9834
- const maxScore = Math.max(...scored.map((s) => s.score));
9835
- return scored.filter((s) => s.score === maxScore).map((s) => s.func);
9836
- }
9837
- function schemaKey(schemaPath, functionName) {
9838
- return `${schemaPathKey(schemaPath)}\x01${functionName}`;
9854
+ };
9839
9855
  }
9840
- function catalogKey(catalogName, schemaPath, functionName) {
9841
- return `${catalogName.toLowerCase()}\x00${schemaKey(schemaPath, functionName)}`;
9856
+
9857
+ // node_modules/@noble/ciphers/_poly1305.js
9858
+ function u8to16(a, i) {
9859
+ return a[i++] & 255 | (a[i++] & 255) << 8;
9842
9860
  }
9843
9861
 
9844
- class FunctionRegistry {
9845
- _functions = new Map;
9846
- _bySchema = new Map;
9847
- _byCatalog = new Map;
9848
- register(func) {
9849
- const name = func.meta.name;
9850
- if (!this._functions.has(name)) {
9851
- this._functions.set(name, []);
9852
- }
9853
- this._functions.get(name).push(func);
9854
- }
9855
- registerInSchema(func, schemaPath, catalogName) {
9856
- const add = (map, key) => {
9857
- const bucket = map.get(key);
9858
- if (!bucket) {
9859
- map.set(key, [func]);
9860
- return;
9861
- }
9862
- if (!bucket.includes(func))
9863
- bucket.push(func);
9864
- };
9865
- add(this._bySchema, schemaKey(schemaPath, func.meta.name));
9866
- if (catalogName) {
9867
- add(this._byCatalog, catalogKey(catalogName, schemaPath, func.meta.name));
9868
- }
9869
- }
9870
- schemasFor(functionName) {
9871
- const out = [];
9872
- for (const key of this._bySchema.keys()) {
9873
- const separator = key.lastIndexOf("\x01");
9874
- const name = key.slice(separator + 1);
9875
- if (name === functionName)
9876
- out.push(key.slice(0, separator).split("\x00"));
9877
- }
9878
- return out.sort((left, right) => schemaPathKey(left).localeCompare(schemaPathKey(right)));
9879
- }
9880
- get(name, context) {
9881
- let candidates = this._functions.get(name);
9882
- const catalogName = context?.catalogName;
9883
- const schemaPath = context?.schemaPath;
9884
- if (catalogName && schemaPath) {
9885
- const scoped = this._byCatalog.get(catalogKey(catalogName, schemaPath, name));
9886
- if (scoped && scoped.length > 0) {
9887
- return this._disambiguate(name, scoped, context);
9888
- }
9889
- }
9890
- if (schemaPath) {
9891
- const scoped = this._bySchema.get(schemaKey(schemaPath, name));
9892
- if (scoped && scoped.length > 0) {
9893
- candidates = scoped;
9894
- } else if (candidates && candidates.length > 0) {
9895
- const schemas = this.schemasFor(name);
9896
- if (schemas.length > 0) {
9897
- throw new Error(`Function '${name}' is not registered in schema ${schemaPathDisplay(schemaPath)}. ` + `It is available in: [${schemas.map(schemaPathDisplay).join(", ")}]`);
9898
- }
9899
- }
9900
- }
9901
- if (!candidates || candidates.length === 0) {
9902
- throw new FunctionNotFoundError(name, this.names());
9903
- }
9904
- return this._disambiguate(name, candidates, context);
9862
+ class Poly1305 {
9863
+ blockLen = 16;
9864
+ outputLen = 16;
9865
+ buffer = new Uint8Array(16);
9866
+ r = new Uint16Array(10);
9867
+ h = new Uint16Array(10);
9868
+ pad = new Uint16Array(8);
9869
+ pos = 0;
9870
+ finished = false;
9871
+ destroyed = false;
9872
+ constructor(key) {
9873
+ key = copyBytes(abytes(key, 32, "key"));
9874
+ const t0 = u8to16(key, 0);
9875
+ const t1 = u8to16(key, 2);
9876
+ const t2 = u8to16(key, 4);
9877
+ const t3 = u8to16(key, 6);
9878
+ const t4 = u8to16(key, 8);
9879
+ const t5 = u8to16(key, 10);
9880
+ const t6 = u8to16(key, 12);
9881
+ const t7 = u8to16(key, 14);
9882
+ this.r[0] = t0 & 8191;
9883
+ this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
9884
+ this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
9885
+ this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
9886
+ this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
9887
+ this.r[5] = t4 >>> 1 & 8190;
9888
+ this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
9889
+ this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
9890
+ this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
9891
+ this.r[9] = t7 >>> 5 & 127;
9892
+ for (let i = 0;i < 8; i++)
9893
+ this.pad[i] = u8to16(key, 16 + 2 * i);
9905
9894
  }
9906
- _disambiguate(name, candidates, context) {
9907
- if (candidates.length === 1) {
9908
- return candidates[0];
9909
- }
9910
- if (!context?.arguments) {
9911
- return candidates[0];
9912
- }
9913
- const args = context.arguments;
9914
- const isScalar = context.isScalar ?? candidates[0].kind === "scalar";
9915
- let matches;
9916
- if (isScalar) {
9917
- const numConstArgs = args.positional.length;
9918
- matches = candidates.filter((func) => {
9919
- const constSpecs = func.argumentSpecs.filter((s) => s.isConst);
9920
- const hasVarargs = constSpecs.some((s) => s.isVarargs);
9921
- const nonVarargConst = constSpecs.filter((s) => !s.isVarargs).length;
9922
- if (hasVarargs) {
9923
- return numConstArgs >= nonVarargConst;
9924
- }
9925
- return constSpecs.length === numConstArgs;
9926
- });
9927
- if (matches.length === 0 || matches.length === candidates.length) {
9928
- matches = candidates;
9929
- }
9930
- } else {
9931
- const numArgs = args.positional.length;
9932
- matches = candidates.filter((func) => {
9933
- const posSpecs = func.argumentSpecs.filter((s) => typeof s.position === "number" && !s.isTableInput);
9934
- const hasVarargs = posSpecs.some((s) => s.isVarargs);
9935
- const nonVarargs = posSpecs.filter((s) => !s.isVarargs).length;
9936
- if (func.meta.inputFromArgs) {
9937
- const numInputCols = context.inputSchema?.fields.length ?? 0;
9938
- if (hasVarargs) {
9939
- if (numInputCols < nonVarargs)
9940
- return false;
9941
- } else if (numInputCols !== posSpecs.length) {
9942
- return false;
9943
- }
9944
- const validNamed = new Set(func.argumentSpecs.filter((s) => typeof s.position === "string").map((s) => s.position));
9945
- for (const key of args.named.keys()) {
9946
- if (!validNamed.has(key))
9947
- return false;
9948
- }
9949
- return true;
9950
- }
9951
- if (hasVarargs) {
9952
- return numArgs >= nonVarargs;
9953
- }
9954
- return posSpecs.length === numArgs;
9955
- });
9956
- if (matches.length === 0) {
9957
- matches = candidates;
9958
- }
9959
- }
9960
- if (matches.length === 1) {
9961
- return matches[0];
9962
- }
9963
- const typeFiltered = filterByArgumentTypes(matches, args, context.inputSchema, isScalar);
9964
- if (typeFiltered.length === 1) {
9965
- return typeFiltered[0];
9966
- }
9967
- if (typeFiltered.length > 1) {
9968
- return typeFiltered[0];
9895
+ process(data, offset, isLast = false) {
9896
+ const hibit = isLast ? 0 : 1 << 11;
9897
+ const { h, r } = this;
9898
+ const r0 = r[0];
9899
+ const r1 = r[1];
9900
+ const r2 = r[2];
9901
+ const r3 = r[3];
9902
+ const r4 = r[4];
9903
+ const r5 = r[5];
9904
+ const r6 = r[6];
9905
+ const r7 = r[7];
9906
+ const r8 = r[8];
9907
+ const r9 = r[9];
9908
+ const t0 = u8to16(data, offset + 0);
9909
+ const t1 = u8to16(data, offset + 2);
9910
+ const t2 = u8to16(data, offset + 4);
9911
+ const t3 = u8to16(data, offset + 6);
9912
+ const t4 = u8to16(data, offset + 8);
9913
+ const t5 = u8to16(data, offset + 10);
9914
+ const t6 = u8to16(data, offset + 12);
9915
+ const t7 = u8to16(data, offset + 14);
9916
+ let h0 = h[0] + (t0 & 8191);
9917
+ let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
9918
+ let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
9919
+ let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
9920
+ let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
9921
+ let h5 = h[5] + (t4 >>> 1 & 8191);
9922
+ let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
9923
+ let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
9924
+ let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
9925
+ let h9 = h[9] + (t7 >>> 5 | hibit);
9926
+ let c = 0;
9927
+ let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
9928
+ c = d0 >>> 13;
9929
+ d0 &= 8191;
9930
+ d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
9931
+ c += d0 >>> 13;
9932
+ d0 &= 8191;
9933
+ let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
9934
+ c = d1 >>> 13;
9935
+ d1 &= 8191;
9936
+ d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
9937
+ c += d1 >>> 13;
9938
+ d1 &= 8191;
9939
+ let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
9940
+ c = d2 >>> 13;
9941
+ d2 &= 8191;
9942
+ d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
9943
+ c += d2 >>> 13;
9944
+ d2 &= 8191;
9945
+ let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
9946
+ c = d3 >>> 13;
9947
+ d3 &= 8191;
9948
+ d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
9949
+ c += d3 >>> 13;
9950
+ d3 &= 8191;
9951
+ let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
9952
+ c = d4 >>> 13;
9953
+ d4 &= 8191;
9954
+ d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
9955
+ c += d4 >>> 13;
9956
+ d4 &= 8191;
9957
+ let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
9958
+ c = d5 >>> 13;
9959
+ d5 &= 8191;
9960
+ d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
9961
+ c += d5 >>> 13;
9962
+ d5 &= 8191;
9963
+ let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
9964
+ c = d6 >>> 13;
9965
+ d6 &= 8191;
9966
+ d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
9967
+ c += d6 >>> 13;
9968
+ d6 &= 8191;
9969
+ let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
9970
+ c = d7 >>> 13;
9971
+ d7 &= 8191;
9972
+ d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
9973
+ c += d7 >>> 13;
9974
+ d7 &= 8191;
9975
+ let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
9976
+ c = d8 >>> 13;
9977
+ d8 &= 8191;
9978
+ d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
9979
+ c += d8 >>> 13;
9980
+ d8 &= 8191;
9981
+ let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
9982
+ c = d9 >>> 13;
9983
+ d9 &= 8191;
9984
+ d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
9985
+ c += d9 >>> 13;
9986
+ d9 &= 8191;
9987
+ c = (c << 2) + c | 0;
9988
+ c = c + d0 | 0;
9989
+ d0 = c & 8191;
9990
+ c = c >>> 13;
9991
+ d1 += c;
9992
+ h[0] = d0;
9993
+ h[1] = d1;
9994
+ h[2] = d2;
9995
+ h[3] = d3;
9996
+ h[4] = d4;
9997
+ h[5] = d5;
9998
+ h[6] = d6;
9999
+ h[7] = d7;
10000
+ h[8] = d8;
10001
+ h[9] = d9;
10002
+ }
10003
+ finalize() {
10004
+ const { h, pad } = this;
10005
+ const g = new Uint16Array(10);
10006
+ let c = h[1] >>> 13;
10007
+ h[1] &= 8191;
10008
+ for (let i = 2;i < 10; i++) {
10009
+ h[i] += c;
10010
+ c = h[i] >>> 13;
10011
+ h[i] &= 8191;
9969
10012
  }
9970
- return candidates[0];
10013
+ h[0] += c * 5;
10014
+ c = h[0] >>> 13;
10015
+ h[0] &= 8191;
10016
+ h[1] += c;
10017
+ c = h[1] >>> 13;
10018
+ h[1] &= 8191;
10019
+ h[2] += c;
10020
+ g[0] = h[0] + 5;
10021
+ c = g[0] >>> 13;
10022
+ g[0] &= 8191;
10023
+ for (let i = 1;i < 10; i++) {
10024
+ g[i] = h[i] + c;
10025
+ c = g[i] >>> 13;
10026
+ g[i] &= 8191;
10027
+ }
10028
+ g[9] -= 1 << 13;
10029
+ let mask = (c ^ 1) - 1;
10030
+ for (let i = 0;i < 10; i++)
10031
+ g[i] &= mask;
10032
+ mask = ~mask;
10033
+ for (let i = 0;i < 10; i++)
10034
+ h[i] = h[i] & mask | g[i];
10035
+ h[0] = (h[0] | h[1] << 13) & 65535;
10036
+ h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
10037
+ h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
10038
+ h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
10039
+ h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
10040
+ h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
10041
+ h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
10042
+ h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
10043
+ let f = h[0] + pad[0];
10044
+ h[0] = f & 65535;
10045
+ for (let i = 1;i < 8; i++) {
10046
+ f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
10047
+ h[i] = f & 65535;
10048
+ }
10049
+ clean(g);
9971
10050
  }
9972
- has(name) {
9973
- return this._functions.has(name) && this._functions.get(name).length > 0;
10051
+ update(data) {
10052
+ aexists(this);
10053
+ abytes(data);
10054
+ data = copyBytes(data);
10055
+ const { buffer, blockLen } = this;
10056
+ const len = data.length;
10057
+ for (let pos = 0;pos < len; ) {
10058
+ const take = Math.min(blockLen - this.pos, len - pos);
10059
+ if (take === blockLen) {
10060
+ for (;blockLen <= len - pos; pos += blockLen)
10061
+ this.process(data, pos);
10062
+ continue;
10063
+ }
10064
+ buffer.set(data.subarray(pos, pos + take), this.pos);
10065
+ this.pos += take;
10066
+ pos += take;
10067
+ if (this.pos === blockLen) {
10068
+ this.process(buffer, 0, false);
10069
+ this.pos = 0;
10070
+ }
10071
+ }
10072
+ return this;
9974
10073
  }
9975
- names() {
9976
- return [...this._functions.keys()].sort();
10074
+ destroy() {
10075
+ this.destroyed = true;
10076
+ clean(this.h, this.r, this.buffer, this.pad);
9977
10077
  }
9978
- all() {
9979
- const result = [];
9980
- for (const candidates of this._functions.values()) {
9981
- result.push(...candidates);
10078
+ digestInto(out) {
10079
+ aexists(this);
10080
+ aoutput(out, this);
10081
+ this.finished = true;
10082
+ const { buffer, h } = this;
10083
+ let { pos } = this;
10084
+ if (pos) {
10085
+ buffer[pos++] = 1;
10086
+ for (;pos < 16; pos++)
10087
+ buffer[pos] = 0;
10088
+ this.process(buffer, 0, true);
9982
10089
  }
9983
- return result;
10090
+ this.finalize();
10091
+ let opos = 0;
10092
+ for (let i = 0;i < 8; i++) {
10093
+ out[opos++] = h[i] >>> 0;
10094
+ out[opos++] = h[i] >>> 8;
10095
+ }
10096
+ }
10097
+ digest() {
10098
+ const { buffer, outputLen } = this;
10099
+ this.digestInto(buffer);
10100
+ const res = buffer.slice(0, outputLen);
10101
+ this.destroy();
10102
+ return res;
9984
10103
  }
9985
10104
  }
9986
- // src/metadata/serialize.ts
9987
- init_arrow();
9988
- var EXAMPLE_STRUCT = struct2([
9989
- field2("sql", utf82(), false),
9990
- field2("description", utf82(), false),
9991
- field2("expected_output", utf82(), true)
9992
- ]);
9993
- var PARAMETER_STRUCT = struct2([
9994
- field2("name", utf82(), false),
9995
- field2("position", int322(), true),
9996
- field2("position_name", utf82(), true),
9997
- field2("type_name", utf82(), true),
9998
- field2("description", utf82(), false),
9999
- field2("required", bool2(), false),
10000
- field2("default", utf82(), true),
10001
- field2("constraints", utf82(), true),
10002
- field2("is_table_input", bool2(), false),
10003
- field2("is_varargs", bool2(), false),
10004
- field2("is_const", bool2(), false)
10005
- ]);
10006
- var FILTER_IDENTITY_STRUCT = struct2([
10007
- field2("namespace", utf82(), false),
10008
- field2("name", utf82(), false),
10009
- field2("version", uint642(), false)
10010
- ]);
10011
- var FILTER_CONTEXT_STRUCT = struct2([
10012
- field2("profile", utf82(), false),
10013
- field2("provider_fingerprint", utf82(), true)
10014
- ]);
10015
- var METADATA_SCHEMA = schema2([
10016
- field2("name", utf82(), false),
10017
- field2("class_name", utf82(), false),
10018
- field2("function_type", utf82(), false),
10019
- field2("description", utf82(), false),
10020
- field2("examples", list2(field2("item", EXAMPLE_STRUCT, true)), false),
10021
- field2("categories", list2(field2("item", utf82(), true)), false),
10022
- field2("tags", map2(field2("key", utf82(), false), field2("value", utf82(), true), false), false),
10023
- field2("parameters", list2(field2("item", PARAMETER_STRUCT, true)), false),
10024
- field2("stability", utf82(), false),
10025
- field2("null_handling", utf82(), false),
10026
- field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
10027
- field2("required_settings", list2(field2("item", utf82(), true)), false),
10028
- field2("required_secrets", list2(field2("item", utf82(), true)), false),
10029
- field2("projection_pushdown", bool2(), false),
10030
- field2("filter_pushdown", bool2(), false),
10031
- field2("filter_semantic_profiles", list2(field2("item", utf82(), true)), false),
10032
- field2("additional_filter_functions", list2(field2("item", FILTER_IDENTITY_STRUCT, true)), false),
10033
- field2("runtime_filter_algorithms", list2(field2("item", FILTER_IDENTITY_STRUCT, true)), false),
10034
- field2("filter_evaluation_contexts", list2(field2("item", FILTER_CONTEXT_STRUCT, true)), false),
10035
- field2("preserves_order", utf82(), false),
10036
- field2("max_workers", int322(), true),
10037
- field2("order_dependent", utf82(), false),
10038
- field2("distinct_dependent", utf82(), false)
10039
- ]);
10040
- function metadataToRow(m) {
10041
- return {
10042
- name: m.name,
10043
- class_name: m.className,
10044
- function_type: m.functionType,
10045
- description: m.description,
10046
- examples: m.examples.map((e) => ({
10047
- sql: e.sql,
10048
- description: e.description,
10049
- expected_output: e.expectedOutput
10050
- })),
10051
- categories: m.categories,
10052
- tags: Object.entries(m.tags).map(([k, v]) => [k, v]),
10053
- parameters: m.parameters.map((p) => ({
10054
- name: p.name,
10055
- position: p.position,
10056
- position_name: p.positionName,
10057
- type_name: p.typeName,
10058
- description: p.description,
10059
- required: p.required,
10060
- default: p.default,
10061
- constraints: p.constraints,
10062
- is_table_input: p.isTableInput,
10063
- is_varargs: p.isVarargs,
10064
- is_const: p.isConst
10065
- })),
10066
- stability: m.stability,
10067
- null_handling: m.nullHandling,
10068
- argument_monotonicity: m.argumentMonotonicity,
10069
- required_settings: m.requiredSettings,
10070
- required_secrets: m.requiredSecrets,
10071
- projection_pushdown: m.projectionPushdown,
10072
- filter_pushdown: m.filterPushdown,
10073
- sampling_pushdown: m.samplingPushdown,
10074
- filter_semantic_profiles: m.filterSemanticProfiles,
10075
- additional_filter_functions: m.additionalFilterFunctions.map((value) => ({
10076
- ...value,
10077
- version: BigInt(value.version)
10078
- })),
10079
- runtime_filter_algorithms: m.runtimeFilterAlgorithms.map((value) => ({
10080
- ...value,
10081
- version: BigInt(value.version)
10082
- })),
10083
- filter_evaluation_contexts: m.filterEvaluationContexts.map((value) => ({
10084
- profile: value.profile,
10085
- provider_fingerprint: value.providerFingerprint
10086
- })),
10087
- preserves_order: m.preservesOrder,
10088
- max_workers: m.maxWorkers,
10089
- order_dependent: m.orderDependent,
10090
- distinct_dependent: m.distinctDependent
10091
- };
10092
- }
10093
- function metadatasToArrow(metadatas) {
10094
- if (metadatas.length === 0) {
10095
- return emptyBatch(METADATA_SCHEMA);
10096
- }
10097
- const rows = metadatas.map(metadataToRow);
10098
- const columns = {};
10099
- for (const f of METADATA_SCHEMA.fields) {
10100
- columns[f.name] = rows.map((r) => r[f.name]);
10101
- }
10102
- return batchFromColumns(columns, METADATA_SCHEMA);
10103
- }
10104
- function arrowToMetadatas(batch) {
10105
- const results = [];
10106
- for (let i = 0;i < batch.numRows; i++) {
10107
- const get = (name) => {
10108
- const col = batch.getChild(name);
10109
- return col ? col.get(i) : null;
10110
- };
10111
- const rawExamples = get("examples") ?? [];
10112
- const examples = [];
10113
- if (rawExamples && typeof rawExamples[Symbol.iterator] === "function") {
10114
- for (const e of rawExamples) {
10115
- if (e) {
10116
- examples.push({
10117
- sql: e.sql ?? "",
10118
- description: e.description ?? "",
10119
- expectedOutput: e.expected_output ?? null
10120
- });
10121
- }
10122
- }
10123
- }
10124
- const rawParams = get("parameters") ?? [];
10125
- const parameters = [];
10126
- if (rawParams && typeof rawParams[Symbol.iterator] === "function") {
10127
- for (const p of rawParams) {
10128
- if (p) {
10129
- parameters.push({
10130
- name: p.name ?? "",
10131
- position: p.position ?? null,
10132
- positionName: p.position_name ?? null,
10133
- typeName: p.type_name ?? null,
10134
- description: p.description ?? "",
10135
- required: p.required ?? true,
10136
- default: p.default ?? null,
10137
- constraints: p.constraints ?? null,
10138
- isTableInput: p.is_table_input ?? false,
10139
- isVarargs: p.is_varargs ?? false,
10140
- isConst: p.is_const ?? false
10141
- });
10142
- }
10143
- }
10144
- }
10145
- const rawCategories = get("categories") ?? [];
10146
- const categories = rawCategories ? [...rawCategories].filter((c) => c != null) : [];
10147
- const rawTags = get("tags");
10148
- const tags = {};
10149
- if (rawTags) {
10150
- if (typeof rawTags[Symbol.iterator] === "function") {
10151
- for (const entry of rawTags) {
10152
- if (Array.isArray(entry)) {
10153
- tags[String(entry[0])] = String(entry[1] ?? "");
10154
- } else if (entry && entry.key != null) {
10155
- tags[String(entry.key)] = String(entry.value ?? "");
10156
- }
10157
- }
10158
- }
10159
- }
10160
- const rawRequiredSettings = get("required_settings") ?? [];
10161
- const requiredSettings = rawRequiredSettings ? [...rawRequiredSettings].filter((s) => s != null) : [];
10162
- const rawRequiredSecrets = get("required_secrets") ?? [];
10163
- const requiredSecrets = rawRequiredSecrets ? [...rawRequiredSecrets].filter((s) => s != null) : [];
10164
- results.push({
10165
- name: get("name") ?? "",
10166
- className: get("class_name") ?? "",
10167
- functionType: get("function_type") ?? "TABLE",
10168
- description: get("description") ?? "",
10169
- examples,
10170
- categories,
10171
- tags,
10172
- parameters,
10173
- stability: get("stability") ?? "CONSISTENT",
10174
- nullHandling: get("null_handling") ?? "DEFAULT",
10175
- argumentMonotonicity: get("argument_monotonicity") == null ? null : [...get("argument_monotonicity")].map(String),
10176
- requiredSettings,
10177
- requiredSecrets,
10178
- projectionPushdown: get("projection_pushdown") ?? false,
10179
- filterPushdown: get("filter_pushdown") ?? false,
10180
- samplingPushdown: get("sampling_pushdown") ?? false,
10181
- filterSemanticProfiles: [...get("filter_semantic_profiles") ?? []].filter((s) => s != null).map(String),
10182
- additionalFilterFunctions: [...get("additional_filter_functions") ?? []].filter((v) => v != null).map((v) => ({
10183
- namespace: String(v.namespace),
10184
- name: String(v.name),
10185
- version: Number(v.version)
10186
- })),
10187
- runtimeFilterAlgorithms: [...get("runtime_filter_algorithms") ?? []].filter((v) => v != null).map((v) => ({
10188
- namespace: String(v.namespace),
10189
- name: String(v.name),
10190
- version: Number(v.version)
10191
- })),
10192
- filterEvaluationContexts: [...get("filter_evaluation_contexts") ?? []].filter((v) => v != null).map((v) => ({
10193
- profile: String(v.profile),
10194
- providerFingerprint: v.provider_fingerprint == null ? null : String(v.provider_fingerprint)
10195
- })),
10196
- preservesOrder: get("preserves_order") ?? "NO_ORDER_GUARANTEE",
10197
- maxWorkers: get("max_workers") ?? null,
10198
- orderDependent: get("order_dependent") ?? "NOT_ORDER_DEPENDENT",
10199
- distinctDependent: get("distinct_dependent") ?? "NOT_DISTINCT_DEPENDENT"
10200
- });
10201
- }
10202
- return results;
10203
- }
10204
- // src/protocol/dispatch.ts
10205
- import { Protocol } from "@query-farm/vgi-rpc";
10206
-
10207
- // src/protocol/handlers/function.ts
10208
- init_arrow();
10105
+ var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
10209
10106
 
10210
- // src/protocol/handlers/shared.ts
10211
- init_arrow();
10212
- var RESULT_BINARY_SCHEMA = schema2([
10213
- field2("result", binary2(), false)
10214
- ]);
10215
- var REQUEST_PARAMS_SCHEMA = schema2([
10216
- field2("request", binary2(), false)
10217
- ]);
10218
- var RESULT_BINARY_NULLABLE_SCHEMA = schema2([
10219
- field2("result", binary2(), true)
10220
- ]);
10221
- function unwrapRequest(requestBytes) {
10222
- const bytes = toUint8Array(requestBytes);
10223
- const innerBatch = deserializeBatch(bytes);
10224
- const params = batchToScalarDict(innerBatch);
10225
- normalizeRequestSchemaPaths(params);
10226
- return params;
10107
+ // node_modules/@noble/ciphers/chacha.js
10108
+ function chachaCore(s, k, n, out, cnt, rounds = 20) {
10109
+ let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
10110
+ let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
10111
+ for (let r = 0;r < rounds; r += 2) {
10112
+ x00 = x00 + x04 | 0;
10113
+ x12 = rotl(x12 ^ x00, 16);
10114
+ x08 = x08 + x12 | 0;
10115
+ x04 = rotl(x04 ^ x08, 12);
10116
+ x00 = x00 + x04 | 0;
10117
+ x12 = rotl(x12 ^ x00, 8);
10118
+ x08 = x08 + x12 | 0;
10119
+ x04 = rotl(x04 ^ x08, 7);
10120
+ x01 = x01 + x05 | 0;
10121
+ x13 = rotl(x13 ^ x01, 16);
10122
+ x09 = x09 + x13 | 0;
10123
+ x05 = rotl(x05 ^ x09, 12);
10124
+ x01 = x01 + x05 | 0;
10125
+ x13 = rotl(x13 ^ x01, 8);
10126
+ x09 = x09 + x13 | 0;
10127
+ x05 = rotl(x05 ^ x09, 7);
10128
+ x02 = x02 + x06 | 0;
10129
+ x14 = rotl(x14 ^ x02, 16);
10130
+ x10 = x10 + x14 | 0;
10131
+ x06 = rotl(x06 ^ x10, 12);
10132
+ x02 = x02 + x06 | 0;
10133
+ x14 = rotl(x14 ^ x02, 8);
10134
+ x10 = x10 + x14 | 0;
10135
+ x06 = rotl(x06 ^ x10, 7);
10136
+ x03 = x03 + x07 | 0;
10137
+ x15 = rotl(x15 ^ x03, 16);
10138
+ x11 = x11 + x15 | 0;
10139
+ x07 = rotl(x07 ^ x11, 12);
10140
+ x03 = x03 + x07 | 0;
10141
+ x15 = rotl(x15 ^ x03, 8);
10142
+ x11 = x11 + x15 | 0;
10143
+ x07 = rotl(x07 ^ x11, 7);
10144
+ x00 = x00 + x05 | 0;
10145
+ x15 = rotl(x15 ^ x00, 16);
10146
+ x10 = x10 + x15 | 0;
10147
+ x05 = rotl(x05 ^ x10, 12);
10148
+ x00 = x00 + x05 | 0;
10149
+ x15 = rotl(x15 ^ x00, 8);
10150
+ x10 = x10 + x15 | 0;
10151
+ x05 = rotl(x05 ^ x10, 7);
10152
+ x01 = x01 + x06 | 0;
10153
+ x12 = rotl(x12 ^ x01, 16);
10154
+ x11 = x11 + x12 | 0;
10155
+ x06 = rotl(x06 ^ x11, 12);
10156
+ x01 = x01 + x06 | 0;
10157
+ x12 = rotl(x12 ^ x01, 8);
10158
+ x11 = x11 + x12 | 0;
10159
+ x06 = rotl(x06 ^ x11, 7);
10160
+ x02 = x02 + x07 | 0;
10161
+ x13 = rotl(x13 ^ x02, 16);
10162
+ x08 = x08 + x13 | 0;
10163
+ x07 = rotl(x07 ^ x08, 12);
10164
+ x02 = x02 + x07 | 0;
10165
+ x13 = rotl(x13 ^ x02, 8);
10166
+ x08 = x08 + x13 | 0;
10167
+ x07 = rotl(x07 ^ x08, 7);
10168
+ x03 = x03 + x04 | 0;
10169
+ x14 = rotl(x14 ^ x03, 16);
10170
+ x09 = x09 + x14 | 0;
10171
+ x04 = rotl(x04 ^ x09, 12);
10172
+ x03 = x03 + x04 | 0;
10173
+ x14 = rotl(x14 ^ x03, 8);
10174
+ x09 = x09 + x14 | 0;
10175
+ x04 = rotl(x04 ^ x09, 7);
10176
+ }
10177
+ let oi = 0;
10178
+ out[oi++] = y00 + x00 | 0;
10179
+ out[oi++] = y01 + x01 | 0;
10180
+ out[oi++] = y02 + x02 | 0;
10181
+ out[oi++] = y03 + x03 | 0;
10182
+ out[oi++] = y04 + x04 | 0;
10183
+ out[oi++] = y05 + x05 | 0;
10184
+ out[oi++] = y06 + x06 | 0;
10185
+ out[oi++] = y07 + x07 | 0;
10186
+ out[oi++] = y08 + x08 | 0;
10187
+ out[oi++] = y09 + x09 | 0;
10188
+ out[oi++] = y10 + x10 | 0;
10189
+ out[oi++] = y11 + x11 | 0;
10190
+ out[oi++] = y12 + x12 | 0;
10191
+ out[oi++] = y13 + x13 | 0;
10192
+ out[oi++] = y14 + x14 | 0;
10193
+ out[oi++] = y15 + x15 | 0;
10227
10194
  }
10228
- function normalizeRequestSchemaPaths(params) {
10229
- if (params.path != null)
10230
- params.path = normalizeSchemaPath(params.path);
10231
- if (params.schema_path != null)
10232
- params.schema_path = normalizeSchemaPath(params.schema_path);
10195
+ function hchacha(s, k, i, out) {
10196
+ const s2 = isLE ? s : swap32IfBE(s.slice(0, 4));
10197
+ const k2 = isLE ? k : swap32IfBE(k.slice(0, 8));
10198
+ const i2 = isLE ? i : swap32IfBE(i.slice(0, 4));
10199
+ const t = new Uint32Array(16);
10200
+ chachaCore(s2, k2, i2.subarray(1), t, i2[0]);
10201
+ let oi = 0;
10202
+ out[oi++] = t[0] - s2[0] | 0;
10203
+ out[oi++] = t[1] - s2[1] | 0;
10204
+ out[oi++] = t[2] - s2[2] | 0;
10205
+ out[oi++] = t[3] - s2[3] | 0;
10206
+ out[oi++] = t[12] - i2[0] | 0;
10207
+ out[oi++] = t[13] - i2[1] | 0;
10208
+ out[oi++] = t[14] - i2[2] | 0;
10209
+ out[oi++] = t[15] - i2[3] | 0;
10210
+ swap32IfBE(out);
10211
+ if (!isLE)
10212
+ clean(s2, k2, i2);
10213
+ clean(t);
10233
10214
  }
10234
- function wrapResult(values, innerSchema) {
10235
- const a = innerSchema;
10236
- const batch = batchFromColumns(Object.fromEntries(a.fields.map((f) => [f.name, [values[f.name] ?? null]])), a);
10237
- return { result: serializeBatch(batch) };
10215
+ var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
10216
+ counterRight: false,
10217
+ counterLength: 8,
10218
+ extendNonceFn: hchacha,
10219
+ allowShortKeys: false
10220
+ });
10221
+ var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
10222
+ var updatePadded = (h, msg) => {
10223
+ h.update(msg);
10224
+ const leftover = msg.length % 16;
10225
+ if (leftover)
10226
+ h.update(ZEROS16.subarray(leftover));
10227
+ };
10228
+ var ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
10229
+ function computeTag(fn, key, nonce, ciphertext, AAD) {
10230
+ if (AAD !== undefined)
10231
+ abytes(AAD, undefined, "AAD");
10232
+ const authKey = fn(key, nonce, ZEROS32);
10233
+ const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
10234
+ const h = poly1305.create(authKey);
10235
+ if (AAD)
10236
+ updatePadded(h, AAD);
10237
+ updatePadded(h, ciphertext);
10238
+ h.update(lengths);
10239
+ const res = h.digest();
10240
+ clean(authKey, lengths);
10241
+ return res;
10238
10242
  }
10239
- function overloadContext(req, catalogInterface) {
10240
- let catalogName = null;
10241
- if (catalogInterface && req.attach_opaque_data) {
10242
- try {
10243
- catalogName = catalogInterface.catalogNameForAttach(req.attach_opaque_data);
10244
- } catch {
10245
- catalogName = null;
10246
- }
10247
- }
10243
+ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
10244
+ const tagLength = 16;
10248
10245
  return {
10249
- arguments: req.arguments,
10250
- inputSchema: req.input_schema,
10251
- isScalar: String(req.function_type).toLowerCase() === "scalar",
10252
- schemaPath: req.schema_path ?? null,
10253
- catalogName
10246
+ encrypt(plaintext, output) {
10247
+ const plength = plaintext.length;
10248
+ output = getOutput(plength + tagLength, output, false);
10249
+ output.set(plaintext);
10250
+ const oPlain = output.subarray(0, -tagLength);
10251
+ xorStream(key, nonce, oPlain, oPlain, 1);
10252
+ const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
10253
+ output.set(tag, plength);
10254
+ clean(tag);
10255
+ return output;
10256
+ },
10257
+ decrypt(ciphertext, output) {
10258
+ output = getOutput(ciphertext.length - tagLength, output, false);
10259
+ const data = ciphertext.subarray(0, -tagLength);
10260
+ const passedTag = ciphertext.subarray(-tagLength);
10261
+ const tag = computeTag(xorStream, key, nonce, data, AAD);
10262
+ if (!equalBytes(passedTag, tag)) {
10263
+ clean(tag);
10264
+ throw new Error("invalid tag");
10265
+ }
10266
+ output.set(ciphertext.subarray(0, -tagLength));
10267
+ xorStream(key, nonce, output, output, 1);
10268
+ clean(tag);
10269
+ return output;
10270
+ }
10254
10271
  };
10255
- }
10272
+ };
10273
+ var xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true }, /* @__PURE__ */ _poly1305_aead(xchacha20));
10256
10274
 
10257
- // src/protocol/handlers/catalog/shared.ts
10258
- init_arrow();
10275
+ // src/crypto.ts
10276
+ var _UTF8 = new TextEncoder;
10277
+ var ATTACH_ENVELOPE_VERSION = 2;
10278
+ var TRANSACTION_ENVELOPE_VERSION = 2;
10279
+ var ATTACH_UUID_LEN = 16;
10280
+ var NONCE_LEN = 24;
10281
+ var TAG_LEN = 16;
10282
+ var MIN_ENVELOPE_LEN = 1 + NONCE_LEN + TAG_LEN;
10283
+ var ATTACH_AAD_PREFIX = _UTF8.encode("vgi.attach_opaque_data.v1\x00");
10284
+ var TRANSACTION_AAD_PREFIX = _UTF8.encode("vgi.transaction_opaque_data.v1\x00");
10259
10285
 
10260
- // node_modules/@noble/ciphers/utils.js
10261
- /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
10262
- function isBytes(a) {
10263
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
10264
- }
10265
- var atitle = (title) => title ? `"${title}" ` : "";
10266
- function abool(value, title = "") {
10267
- if (typeof value !== "boolean")
10268
- throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
10269
- return value;
10270
- }
10271
- function anumber(n, title = "") {
10272
- if (typeof n !== "number")
10273
- throw new TypeError(atitle(title) + "expected number, got " + typeof n);
10274
- if (!Number.isSafeInteger(n) || n < 0)
10275
- throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
10276
- return n;
10277
- }
10278
- function abytes(value, length, title = "") {
10279
- if (isBytes(value) && (length === undefined || value.length === length))
10280
- return value;
10281
- if (length !== undefined)
10282
- anumber(length, "length");
10283
- const bytes = isBytes(value);
10284
- const ofLen = length !== undefined ? ` of length ${length}` : "";
10285
- const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
10286
- const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
10287
- if (!bytes)
10288
- throw new TypeError(message);
10289
- throw new RangeError(message);
10290
- }
10291
- var aobject = (value, label) => {
10292
- if (value === null || typeof value !== "object" || Array.isArray(value))
10293
- throw new TypeError(label === "object" ? "expected valid options object" : `"${label}" expected object, got type=${typeof value}`);
10294
- };
10295
- function aexists(instance, checkFinished = true) {
10296
- if (instance.destroyed)
10297
- throw new Error("hash was destroyed");
10298
- if (checkFinished && instance.finished)
10299
- throw new Error("digest() was already called");
10286
+ class OpaqueDataRejectedError extends Error {
10287
+ errorCode = "INVALID_ARGUMENT";
10288
+ errorKind = "opaque_data_not_recognized";
10289
+ constructor(field = "opaque data") {
10290
+ super(`${field} not recognized`);
10291
+ this.name = "OpaqueDataRejectedError";
10292
+ }
10300
10293
  }
10301
- function aoutput(out, instance) {
10302
- abytes(out, undefined, "output");
10303
- const min = instance.outputLen;
10304
- if (!(out.length >= min)) {
10305
- throw new RangeError('"output" expected length >= ' + min);
10294
+ function concat(...parts) {
10295
+ let total = 0;
10296
+ for (const p of parts)
10297
+ total += p.length;
10298
+ const out = new Uint8Array(total);
10299
+ let off = 0;
10300
+ for (const p of parts) {
10301
+ out.set(p, off);
10302
+ off += p.length;
10306
10303
  }
10304
+ return out;
10307
10305
  }
10308
- function u32(arr) {
10309
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
10306
+ async function normalizeKey(key) {
10307
+ if (key.length === 32)
10308
+ return key;
10309
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", key));
10310
10310
  }
10311
- function clean(...arrays) {
10312
- for (let i = 0;i < arrays.length; i++) {
10313
- arrays[i].fill(0);
10314
- }
10311
+ function identityTail(auth) {
10312
+ if (!auth || !auth.authenticated)
10313
+ return _UTF8.encode("\x00anonymous");
10314
+ const domain = _UTF8.encode(auth.domain ?? "");
10315
+ const principal = _UTF8.encode(auth.principal ?? "");
10316
+ return concat(Uint8Array.of(1), domain, Uint8Array.of(0), principal);
10315
10317
  }
10316
- function createView(arr) {
10317
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
10318
+ function attachAad(auth) {
10319
+ return concat(ATTACH_AAD_PREFIX, identityTail(auth));
10318
10320
  }
10319
- var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
10320
- function byteSwap(word) {
10321
- return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
10321
+ function transactionAad(auth, attachEnvelope) {
10322
+ return concat(TRANSACTION_AAD_PREFIX, identityTail(auth), Uint8Array.of(0), attachEnvelope);
10322
10323
  }
10323
- function byteSwap32(arr) {
10324
- for (let i = 0;i < arr.length; i++) {
10325
- arr[i] = byteSwap(arr[i]);
10324
+ async function sealBytes(payload, key, aad, version, fixedNonce) {
10325
+ if (fixedNonce !== undefined && fixedNonce.length !== NONCE_LEN) {
10326
+ throw new Error(`nonce must be ${NONCE_LEN} bytes`);
10326
10327
  }
10327
- return arr;
10328
- }
10329
- var swap32IfBE = isLE ? (u) => u : byteSwap32;
10330
- function checkOpts(defaults, opts) {
10331
- aobject(defaults, "defaults");
10332
- aobject(opts, "opts");
10333
- const merged = Object.assign(defaults, opts);
10334
- return merged;
10335
- }
10336
- function equalBytes(a, b) {
10337
- a = abytes(a);
10338
- b = abytes(b);
10339
- if (a.length !== b.length)
10340
- return false;
10341
- let diff = 0;
10342
- for (let i = 0;i < a.length; i++)
10343
- diff |= a[i] ^ b[i];
10344
- return diff === 0;
10328
+ const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
10329
+ const ciphertext = xchacha20poly1305(await normalizeKey(key), nonce, aad).encrypt(payload);
10330
+ const out = new Uint8Array(1 + NONCE_LEN + ciphertext.length);
10331
+ out[0] = version & 255;
10332
+ out.set(nonce, 1);
10333
+ out.set(ciphertext, 1 + NONCE_LEN);
10334
+ return out;
10345
10335
  }
10346
- function wrapMacConstructor(keyLen, macCons, fromMsg) {
10347
- const mac = macCons;
10348
- const getArgs = fromMsg || (() => []);
10349
- const macC = (msg, key) => mac(key, ...getArgs(msg)).update(msg).digest();
10350
- const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
10351
- macC.outputLen = tmp.outputLen;
10352
- macC.blockLen = tmp.blockLen;
10353
- macC.create = (key, ...args) => mac(key, ...args);
10354
- return macC;
10336
+ async function openBytes(token, key, aad, version, field = "opaque data") {
10337
+ if (token.length < MIN_ENVELOPE_LEN || token[0] !== (version & 255)) {
10338
+ throw new OpaqueDataRejectedError(field);
10339
+ }
10340
+ const nonce = token.subarray(1, 1 + NONCE_LEN);
10341
+ const ciphertext = token.subarray(1 + NONCE_LEN);
10342
+ try {
10343
+ return xchacha20poly1305(await normalizeKey(key), nonce, aad).decrypt(ciphertext);
10344
+ } catch {
10345
+ throw new OpaqueDataRejectedError(field);
10346
+ }
10355
10347
  }
10356
- var wrapCipher = (params, constructor) => {
10357
- function wrappedCipher(key, ...args) {
10358
- abytes(key, undefined, "key");
10359
- if (params.nonceLength !== undefined) {
10360
- const nonce = args[0];
10361
- abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, "nonce");
10348
+
10349
+ // src/catalog/composite.ts
10350
+ var ROUTE_BYTE = 0;
10351
+
10352
+ class CompositeCatalogInterface extends CatalogInterface {
10353
+ _backends;
10354
+ constructor(_backends) {
10355
+ super();
10356
+ this._backends = _backends;
10357
+ if (_backends.length > 256) {
10358
+ throw new Error("CompositeCatalog: at most 256 backends supported");
10362
10359
  }
10363
- const tagl = params.tagLength;
10364
- const aadStart = params.nonceLength !== undefined ? 1 : 0;
10365
- if (!params.withAAD) {
10366
- for (let i = aadStart;i < args.length; i++)
10367
- if (isBytes(args[i]))
10368
- throw new Error("AAD not supported");
10360
+ }
10361
+ _route(attachOpaqueData) {
10362
+ const idx = attachOpaqueData[ROUTE_BYTE];
10363
+ const route = this._backends[idx];
10364
+ if (!route) {
10365
+ throw new OpaqueDataRejectedError("attach_opaque_data");
10369
10366
  }
10370
- if (params.withAAD && args[aadStart] !== undefined)
10371
- abytes(args[aadStart], undefined, "AAD");
10372
- const cipher = constructor(key, ...args);
10373
- const checkOutput = (fnLength, output) => {
10374
- if (output !== undefined) {
10375
- if (fnLength !== 2)
10376
- throw new Error("cipher output not supported");
10377
- abytes(output, undefined, "output");
10367
+ return route;
10368
+ }
10369
+ catalogNameForAttach(attachOpaqueData) {
10370
+ try {
10371
+ return this._route(attachOpaqueData).catalogNameForAttach(attachOpaqueData);
10372
+ } catch {
10373
+ return null;
10374
+ }
10375
+ }
10376
+ catalogs() {
10377
+ const all = [];
10378
+ for (const b of this._backends)
10379
+ all.push(...b.catalogs());
10380
+ return all;
10381
+ }
10382
+ async catalogsInfo() {
10383
+ const all = [];
10384
+ for (const b of this._backends) {
10385
+ if (b.catalogsInfo) {
10386
+ all.push(...await b.catalogsInfo());
10387
+ } else {
10388
+ for (const name of b.catalogs()) {
10389
+ all.push({ name, implementation_version: null, data_version_spec: null, attach_option_specs: [], releases: [] });
10390
+ }
10378
10391
  }
10379
- };
10380
- let called = false;
10381
- const wrCipher = {
10382
- encrypt(data, output) {
10383
- if (called)
10384
- throw new Error("cannot encrypt() twice with same key + nonce");
10385
- called = true;
10386
- abytes(data, undefined, "data");
10387
- checkOutput(cipher.encrypt.length, output);
10388
- return cipher.encrypt(data, output);
10389
- },
10390
- decrypt(data, output) {
10391
- abytes(data, undefined, "data");
10392
- if (tagl && data.length < tagl)
10393
- throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
10394
- checkOutput(cipher.decrypt.length, output);
10395
- return cipher.decrypt(data, output);
10392
+ }
10393
+ return all;
10394
+ }
10395
+ async attach(name, options, dataVersionSpec, implementationVersion) {
10396
+ for (let i = 0;i < this._backends.length; i++) {
10397
+ const b = this._backends[i];
10398
+ if (b.catalogs().includes(name)) {
10399
+ const result = await b.attach(name, options, dataVersionSpec, implementationVersion);
10400
+ const stamped = new Uint8Array(result.attach_opaque_data);
10401
+ stamped[ROUTE_BYTE] = i;
10402
+ result.attach_opaque_data = stamped;
10403
+ return result;
10396
10404
  }
10397
- };
10398
- return wrCipher;
10405
+ }
10406
+ throw new Error(`No worker handles catalog '${name}'`);
10407
+ }
10408
+ async detach(attachOpaqueData) {
10409
+ await this._route(attachOpaqueData).detach(attachOpaqueData);
10410
+ }
10411
+ async version(attachOpaqueData, transactionOpaqueData) {
10412
+ return await this._route(attachOpaqueData).version(attachOpaqueData, transactionOpaqueData);
10413
+ }
10414
+ async schemas(attachOpaqueData, transactionOpaqueData) {
10415
+ return await this._route(attachOpaqueData).schemas(attachOpaqueData, transactionOpaqueData);
10416
+ }
10417
+ async schemaGet(attachOpaqueData, path, transactionOpaqueData) {
10418
+ return await this._route(attachOpaqueData).schemaGet(attachOpaqueData, path, transactionOpaqueData);
10419
+ }
10420
+ async schemaContentsTables(attachOpaqueData, path, transactionOpaqueData) {
10421
+ return await this._route(attachOpaqueData).schemaContentsTables(attachOpaqueData, path, transactionOpaqueData);
10422
+ }
10423
+ async schemaContentsViews(attachOpaqueData, path, transactionOpaqueData) {
10424
+ return await this._route(attachOpaqueData).schemaContentsViews(attachOpaqueData, path, transactionOpaqueData);
10425
+ }
10426
+ async schemaContentsFunctions(attachOpaqueData, path, type, transactionOpaqueData) {
10427
+ return await this._route(attachOpaqueData).schemaContentsFunctions(attachOpaqueData, path, type, transactionOpaqueData);
10428
+ }
10429
+ async schemaContentsMacros(attachOpaqueData, path, type, transactionOpaqueData) {
10430
+ return await this._route(attachOpaqueData).schemaContentsMacros(attachOpaqueData, path, type, transactionOpaqueData);
10431
+ }
10432
+ async schemaContentsIndexes(attachOpaqueData, path, transactionOpaqueData) {
10433
+ return await this._route(attachOpaqueData).schemaContentsIndexes(attachOpaqueData, path, transactionOpaqueData);
10434
+ }
10435
+ async indexGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10436
+ return await this._route(attachOpaqueData).indexGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
10437
+ }
10438
+ async tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10439
+ return await this._route(attachOpaqueData).tableGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
10440
+ }
10441
+ async tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10442
+ return await this._route(attachOpaqueData).tableScanFunctionGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
10443
+ }
10444
+ async tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData) {
10445
+ return await this._route(attachOpaqueData).tableScanBranchesGet(attachOpaqueData, schemaPath, name, atUnit, atValue, transactionOpaqueData);
10446
+ }
10447
+ async tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10448
+ return await this._route(attachOpaqueData).tableColumnStatisticsGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
10449
+ }
10450
+ async viewGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10451
+ return await this._route(attachOpaqueData).viewGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
10452
+ }
10453
+ async macroGet(attachOpaqueData, schemaPath, name, transactionOpaqueData) {
10454
+ return await this._route(attachOpaqueData).macroGet(attachOpaqueData, schemaPath, name, transactionOpaqueData);
10455
+ }
10456
+ async schemaCreate(...args) {
10457
+ await this._route(args[0]).schemaCreate(...args);
10458
+ }
10459
+ async schemaDrop(...args) {
10460
+ await this._route(args[0]).schemaDrop(...args);
10461
+ }
10462
+ async tableCreate(...args) {
10463
+ await this._route(args[0]).tableCreate(...args);
10464
+ }
10465
+ async tableDrop(...args) {
10466
+ await this._route(args[0]).tableDrop(...args);
10467
+ }
10468
+ async tableCommentSet(...args) {
10469
+ await this._route(args[0]).tableCommentSet(...args);
10470
+ }
10471
+ async tableRename(...args) {
10472
+ await this._route(args[0]).tableRename(...args);
10473
+ }
10474
+ async tableColumnAdd(...args) {
10475
+ await this._route(args[0]).tableColumnAdd(...args);
10476
+ }
10477
+ async tableColumnDrop(...args) {
10478
+ await this._route(args[0]).tableColumnDrop(...args);
10479
+ }
10480
+ async tableColumnRename(...args) {
10481
+ await this._route(args[0]).tableColumnRename(...args);
10482
+ }
10483
+ async tableColumnDefaultSet(...args) {
10484
+ await this._route(args[0]).tableColumnDefaultSet(...args);
10485
+ }
10486
+ async tableColumnDefaultDrop(...args) {
10487
+ await this._route(args[0]).tableColumnDefaultDrop(...args);
10488
+ }
10489
+ async tableColumnTypeChange(...args) {
10490
+ await this._route(args[0]).tableColumnTypeChange(...args);
10491
+ }
10492
+ async tableNotNullSet(...args) {
10493
+ await this._route(args[0]).tableNotNullSet(...args);
10494
+ }
10495
+ async tableNotNullDrop(...args) {
10496
+ await this._route(args[0]).tableNotNullDrop(...args);
10497
+ }
10498
+ async viewCreate(...args) {
10499
+ await this._route(args[0]).viewCreate(...args);
10500
+ }
10501
+ async viewDrop(...args) {
10502
+ await this._route(args[0]).viewDrop(...args);
10503
+ }
10504
+ async viewRename(...args) {
10505
+ await this._route(args[0]).viewRename(...args);
10506
+ }
10507
+ async viewCommentSet(...args) {
10508
+ await this._route(args[0]).viewCommentSet(...args);
10509
+ }
10510
+ async macroCreate(...args) {
10511
+ await this._route(args[0]).macroCreate(...args);
10512
+ }
10513
+ async macroDrop(...args) {
10514
+ await this._route(args[0]).macroDrop(...args);
10515
+ }
10516
+ async catalogContents(attachOpaqueData, ifNoneMatch) {
10517
+ return await this._route(attachOpaqueData).catalogContents(attachOpaqueData, ifNoneMatch);
10518
+ }
10519
+ catalogContentsOwner(attachOpaqueData) {
10520
+ return this._route(attachOpaqueData).catalogContentsOwner(attachOpaqueData);
10521
+ }
10522
+ async copyFromFormats(attachOpaqueData, transactionOpaqueData) {
10523
+ return await this._route(attachOpaqueData).copyFromFormats(attachOpaqueData, transactionOpaqueData);
10524
+ }
10525
+ async transactionBegin(attachOpaqueData) {
10526
+ return await this._route(attachOpaqueData).transactionBegin(attachOpaqueData);
10527
+ }
10528
+ async transactionCommit(attachOpaqueData, transactionOpaqueData) {
10529
+ await this._route(attachOpaqueData).transactionCommit(attachOpaqueData, transactionOpaqueData);
10530
+ }
10531
+ async transactionRollback(attachOpaqueData, transactionOpaqueData) {
10532
+ await this._route(attachOpaqueData).transactionRollback(attachOpaqueData, transactionOpaqueData);
10399
10533
  }
10400
- Object.assign(wrappedCipher, params);
10401
- return wrappedCipher;
10402
- };
10403
- function getOutput(expectedLength, out, onlyAligned = true) {
10404
- if (out === undefined)
10405
- return new Uint8Array(expectedLength);
10406
- abytes(out, expectedLength, "output");
10407
- if (onlyAligned && !isAligned32(out))
10408
- throw new Error("invalid output, must be aligned");
10409
- return out;
10410
- }
10411
- function u64Lengths(dataLength, aadLength, isLE) {
10412
- anumber(dataLength);
10413
- anumber(aadLength);
10414
- abool(isLE);
10415
- const num = new Uint8Array(16);
10416
- const view = createView(num);
10417
- view.setBigUint64(0, BigInt(aadLength), isLE);
10418
- view.setBigUint64(8, BigInt(dataLength), isLE);
10419
- return num;
10420
- }
10421
- function isAligned32(bytes) {
10422
- return bytes.byteOffset % 4 === 0;
10423
10534
  }
10424
- function copyBytes(bytes) {
10425
- return Uint8Array.from(abytes(bytes));
10535
+ // src/functions/registry.ts
10536
+ init_arrow();
10537
+ var EXACT_MATCH_SCORE = 2;
10538
+ var FAMILY_MATCH_SCORE = 1;
10539
+ function typesIdentical(a, b) {
10540
+ return typeSignature(a) === typeSignature(b);
10426
10541
  }
10427
-
10428
- // node_modules/@noble/ciphers/_arx.js
10429
- var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
10430
- var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))();
10431
- var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))();
10432
- function rotl(a, b) {
10433
- return a << b | a >>> 32 - b;
10542
+ function typesCompatible(actual, declared) {
10543
+ if (typesIdentical(actual, declared))
10544
+ return true;
10545
+ if (isInt(actual) && isInt(declared))
10546
+ return true;
10547
+ if ((isFloat(actual) || isDecimal(actual)) && (isFloat(declared) || isDecimal(declared)))
10548
+ return true;
10549
+ if (isUtf8(actual) && isUtf8(declared))
10550
+ return true;
10551
+ if (isBinary(actual) && isBinary(declared))
10552
+ return true;
10553
+ if (isBool(actual) && isBool(declared))
10554
+ return true;
10555
+ return false;
10434
10556
  }
10435
- var BLOCK_LEN = 64;
10436
- var BLOCK_LEN32 = 16;
10437
- var MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
10438
- var U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
10439
- function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
10440
- const len = data.length;
10441
- const block = new Uint8Array(BLOCK_LEN);
10442
- const b32 = u32(block);
10443
- const isAligned = isLE && isAligned32(data) && isAligned32(output);
10444
- const d32 = isAligned ? u32(data) : U32_EMPTY;
10445
- const o32 = isAligned ? u32(output) : U32_EMPTY;
10446
- if (!isLE) {
10447
- for (let pos = 0;pos < len; counter++) {
10448
- core(sigma, key, nonce, b32, counter, rounds);
10449
- swap32IfBE(b32);
10450
- if (counter >= MAX_COUNTER)
10451
- throw new Error("arx: counter overflow");
10452
- const take = Math.min(BLOCK_LEN, len - pos);
10453
- for (let j = 0, posj;j < take; j++) {
10454
- posj = pos + j;
10455
- output[posj] = data[posj] ^ block[j];
10456
- }
10457
- pos += take;
10557
+ function scoreTypes(specs, actualTypes) {
10558
+ let score = 0;
10559
+ let varArgsSpec = null;
10560
+ for (let i = 0;i < specs.length; i++) {
10561
+ const spec = specs[i];
10562
+ if (spec.isVarargs)
10563
+ varArgsSpec = spec;
10564
+ if (i >= actualTypes.length)
10565
+ break;
10566
+ if (spec.isAnyType || isNull(spec.arrowType))
10567
+ continue;
10568
+ const actual = actualTypes[i];
10569
+ if (actual === null)
10570
+ continue;
10571
+ if (typesIdentical(actual, spec.arrowType)) {
10572
+ score += EXACT_MATCH_SCORE;
10573
+ } else if (typesCompatible(actual, spec.arrowType)) {
10574
+ score += FAMILY_MATCH_SCORE;
10575
+ } else {
10576
+ return { score, matched: false };
10458
10577
  }
10459
- return;
10460
10578
  }
10461
- for (let pos = 0;pos < len; counter++) {
10462
- core(sigma, key, nonce, b32, counter, rounds);
10463
- if (counter >= MAX_COUNTER)
10464
- throw new Error("arx: counter overflow");
10465
- const take = Math.min(BLOCK_LEN, len - pos);
10466
- if (isAligned && take === BLOCK_LEN) {
10467
- const pos32 = pos / 4;
10468
- if (pos % 4 !== 0)
10469
- throw new Error("arx: invalid block position");
10470
- for (let j = 0, posj;j < BLOCK_LEN32; j++) {
10471
- posj = pos32 + j;
10472
- o32[posj] = d32[posj] ^ b32[j];
10579
+ if (varArgsSpec && !varArgsSpec.isAnyType && !isNull(varArgsSpec.arrowType)) {
10580
+ for (let i = specs.length;i < actualTypes.length; i++) {
10581
+ const actual = actualTypes[i];
10582
+ if (actual === null)
10583
+ continue;
10584
+ if (typesIdentical(actual, varArgsSpec.arrowType)) {
10585
+ score += EXACT_MATCH_SCORE;
10586
+ } else if (typesCompatible(actual, varArgsSpec.arrowType)) {
10587
+ score += FAMILY_MATCH_SCORE;
10588
+ } else {
10589
+ return { score, matched: false };
10473
10590
  }
10474
- pos += BLOCK_LEN;
10475
- continue;
10476
- }
10477
- for (let j = 0, posj;j < take; j++) {
10478
- posj = pos + j;
10479
- output[posj] = data[posj] ^ block[j];
10480
10591
  }
10481
- pos += take;
10482
10592
  }
10593
+ return { score, matched: true };
10483
10594
  }
10484
- function createCipher(core, opts) {
10485
- const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
10486
- if (typeof core !== "function")
10487
- throw new Error("core must be a function");
10488
- anumber(counterLength);
10489
- anumber(rounds);
10490
- abool(counterRight);
10491
- abool(allowShortKeys);
10492
- return (key, nonce, data, output, counter = 0) => {
10493
- abytes(key, undefined, "key");
10494
- abytes(nonce, undefined, "nonce");
10495
- abytes(data, undefined, "data");
10496
- const len = data.length;
10497
- output = getOutput(len, output, false);
10498
- anumber(counter);
10499
- if (counter < 0 || counter >= MAX_COUNTER)
10500
- throw new Error("arx: counter overflow");
10501
- const toClean = [];
10502
- let l = key.length;
10503
- let k;
10504
- let sigma;
10505
- if (l === 32) {
10506
- toClean.push(k = copyBytes(key));
10507
- sigma = sigma32_32;
10508
- } else if (l === 16 && allowShortKeys) {
10509
- k = new Uint8Array(32);
10510
- k.set(key);
10511
- k.set(key, 16);
10512
- sigma = sigma16_32;
10513
- toClean.push(k);
10595
+ function filterByArgumentTypes(candidates, args, inputSchema, isScalar) {
10596
+ const scored = [];
10597
+ for (const func of candidates) {
10598
+ const specs = func.argumentSpecs;
10599
+ let score = 0;
10600
+ let matched = true;
10601
+ if (isScalar) {
10602
+ const constSpecs = specs.filter((s) => s.isConst);
10603
+ const colSpecs = specs.filter((s) => !s.isConst && typeof s.position === "number");
10604
+ const constTypes = [];
10605
+ const argsSchema = args.argumentsSchema;
10606
+ for (let i = 0;i < args.positional.length; i++) {
10607
+ const field = argsSchema?.fields.find((f) => f.name === `positional_${i}`);
10608
+ constTypes.push(field ? field.type : null);
10609
+ }
10610
+ const r1 = scoreTypes(constSpecs, constTypes);
10611
+ score += r1.score;
10612
+ matched = r1.matched;
10613
+ if (matched && inputSchema) {
10614
+ const colTypes = [];
10615
+ let varArgsColSpec = null;
10616
+ for (const spec of colSpecs) {
10617
+ if (spec.isVarargs)
10618
+ varArgsColSpec = spec;
10619
+ const pos = spec.position;
10620
+ colTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos].type : null);
10621
+ }
10622
+ if (varArgsColSpec) {
10623
+ const start = varArgsColSpec.position + 1;
10624
+ for (let i = start;i < inputSchema.fields.length; i++) {
10625
+ colTypes.push(inputSchema.fields[i].type);
10626
+ }
10627
+ }
10628
+ const r2 = scoreTypes(colSpecs, colTypes);
10629
+ score += r2.score;
10630
+ matched = r2.matched;
10631
+ }
10514
10632
  } else {
10515
- abytes(key, 32, "arx key");
10516
- throw new Error("invalid key size");
10517
- }
10518
- if (!isLE || !isAligned32(nonce))
10519
- toClean.push(nonce = copyBytes(nonce));
10520
- let k32 = u32(k);
10521
- if (extendNonceFn) {
10522
- if (nonce.length !== 24)
10523
- throw new Error("arx: extended nonce must be 24 bytes");
10524
- const n16 = nonce.subarray(0, 16);
10525
- if (isLE)
10526
- extendNonceFn(sigma, k32, u32(n16), k32);
10527
- else {
10528
- const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
10529
- extendNonceFn(sigmaRaw, k32, u32(n16), k32);
10530
- clean(sigmaRaw);
10531
- swap32IfBE(k32);
10633
+ const posSpecs = specs.filter((s) => typeof s.position === "number" && !s.isTableInput).sort((a, b) => a.position - b.position);
10634
+ const posTypes = [];
10635
+ if (func.meta.inputFromArgs) {
10636
+ if (inputSchema) {
10637
+ let varArgsSpec = null;
10638
+ for (const spec of posSpecs) {
10639
+ if (spec.isVarargs)
10640
+ varArgsSpec = spec;
10641
+ const pos = spec.position;
10642
+ posTypes.push(pos < inputSchema.fields.length ? inputSchema.fields[pos].type : null);
10643
+ }
10644
+ if (varArgsSpec) {
10645
+ for (let i = varArgsSpec.position + 1;i < inputSchema.fields.length; i++) {
10646
+ posTypes.push(inputSchema.fields[i].type);
10647
+ }
10648
+ }
10649
+ }
10650
+ } else {
10651
+ const argsSchema = args.argumentsSchema;
10652
+ for (let i = 0;i < args.positional.length; i++) {
10653
+ const field = argsSchema?.fields.find((f) => f.name === `positional_${i}`);
10654
+ posTypes.push(field ? field.type : null);
10655
+ }
10532
10656
  }
10533
- nonce = nonce.subarray(16);
10534
- } else if (!isLE)
10535
- swap32IfBE(k32);
10536
- const nonceNcLen = 16 - counterLength;
10537
- if (nonceNcLen !== nonce.length)
10538
- throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
10539
- if (nonceNcLen !== 12) {
10540
- const nc = new Uint8Array(12);
10541
- nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
10542
- nonce = nc;
10543
- toClean.push(nonce);
10657
+ const r = scoreTypes(posSpecs, posTypes);
10658
+ score += r.score;
10659
+ matched = r.matched;
10544
10660
  }
10545
- const n32 = swap32IfBE(u32(nonce));
10546
- try {
10547
- runCipher(core, sigma, k32, n32, data, output, counter, rounds);
10548
- return output;
10549
- } finally {
10550
- clean(...toClean);
10661
+ if (matched) {
10662
+ scored.push({ score, func });
10551
10663
  }
10552
- };
10664
+ }
10665
+ if (scored.length === 0)
10666
+ return [];
10667
+ const maxScore = Math.max(...scored.map((s) => s.score));
10668
+ return scored.filter((s) => s.score === maxScore).map((s) => s.func);
10553
10669
  }
10554
-
10555
- // node_modules/@noble/ciphers/_poly1305.js
10556
- function u8to16(a, i) {
10557
- return a[i++] & 255 | (a[i++] & 255) << 8;
10670
+ function schemaKey(schemaPath, functionName) {
10671
+ return `${schemaPathKey(schemaPath)}\x01${functionName}`;
10672
+ }
10673
+ function catalogKey(catalogName, schemaPath, functionName) {
10674
+ return `${catalogName.toLowerCase()}\x00${schemaKey(schemaPath, functionName)}`;
10558
10675
  }
10559
10676
 
10560
- class Poly1305 {
10561
- blockLen = 16;
10562
- outputLen = 16;
10563
- buffer = new Uint8Array(16);
10564
- r = new Uint16Array(10);
10565
- h = new Uint16Array(10);
10566
- pad = new Uint16Array(8);
10567
- pos = 0;
10568
- finished = false;
10569
- destroyed = false;
10570
- constructor(key) {
10571
- key = copyBytes(abytes(key, 32, "key"));
10572
- const t0 = u8to16(key, 0);
10573
- const t1 = u8to16(key, 2);
10574
- const t2 = u8to16(key, 4);
10575
- const t3 = u8to16(key, 6);
10576
- const t4 = u8to16(key, 8);
10577
- const t5 = u8to16(key, 10);
10578
- const t6 = u8to16(key, 12);
10579
- const t7 = u8to16(key, 14);
10580
- this.r[0] = t0 & 8191;
10581
- this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
10582
- this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
10583
- this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
10584
- this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
10585
- this.r[5] = t4 >>> 1 & 8190;
10586
- this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
10587
- this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
10588
- this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
10589
- this.r[9] = t7 >>> 5 & 127;
10590
- for (let i = 0;i < 8; i++)
10591
- this.pad[i] = u8to16(key, 16 + 2 * i);
10677
+ class FunctionRegistry {
10678
+ _functions = new Map;
10679
+ _bySchema = new Map;
10680
+ _byCatalog = new Map;
10681
+ register(func) {
10682
+ const name = func.meta.name;
10683
+ if (!this._functions.has(name)) {
10684
+ this._functions.set(name, []);
10685
+ }
10686
+ this._functions.get(name).push(func);
10592
10687
  }
10593
- process(data, offset, isLast = false) {
10594
- const hibit = isLast ? 0 : 1 << 11;
10595
- const { h, r } = this;
10596
- const r0 = r[0];
10597
- const r1 = r[1];
10598
- const r2 = r[2];
10599
- const r3 = r[3];
10600
- const r4 = r[4];
10601
- const r5 = r[5];
10602
- const r6 = r[6];
10603
- const r7 = r[7];
10604
- const r8 = r[8];
10605
- const r9 = r[9];
10606
- const t0 = u8to16(data, offset + 0);
10607
- const t1 = u8to16(data, offset + 2);
10608
- const t2 = u8to16(data, offset + 4);
10609
- const t3 = u8to16(data, offset + 6);
10610
- const t4 = u8to16(data, offset + 8);
10611
- const t5 = u8to16(data, offset + 10);
10612
- const t6 = u8to16(data, offset + 12);
10613
- const t7 = u8to16(data, offset + 14);
10614
- let h0 = h[0] + (t0 & 8191);
10615
- let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
10616
- let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
10617
- let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
10618
- let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
10619
- let h5 = h[5] + (t4 >>> 1 & 8191);
10620
- let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
10621
- let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
10622
- let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
10623
- let h9 = h[9] + (t7 >>> 5 | hibit);
10624
- let c = 0;
10625
- let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
10626
- c = d0 >>> 13;
10627
- d0 &= 8191;
10628
- d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
10629
- c += d0 >>> 13;
10630
- d0 &= 8191;
10631
- let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
10632
- c = d1 >>> 13;
10633
- d1 &= 8191;
10634
- d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
10635
- c += d1 >>> 13;
10636
- d1 &= 8191;
10637
- let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
10638
- c = d2 >>> 13;
10639
- d2 &= 8191;
10640
- d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
10641
- c += d2 >>> 13;
10642
- d2 &= 8191;
10643
- let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
10644
- c = d3 >>> 13;
10645
- d3 &= 8191;
10646
- d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
10647
- c += d3 >>> 13;
10648
- d3 &= 8191;
10649
- let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
10650
- c = d4 >>> 13;
10651
- d4 &= 8191;
10652
- d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
10653
- c += d4 >>> 13;
10654
- d4 &= 8191;
10655
- let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
10656
- c = d5 >>> 13;
10657
- d5 &= 8191;
10658
- d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
10659
- c += d5 >>> 13;
10660
- d5 &= 8191;
10661
- let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
10662
- c = d6 >>> 13;
10663
- d6 &= 8191;
10664
- d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
10665
- c += d6 >>> 13;
10666
- d6 &= 8191;
10667
- let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
10668
- c = d7 >>> 13;
10669
- d7 &= 8191;
10670
- d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
10671
- c += d7 >>> 13;
10672
- d7 &= 8191;
10673
- let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
10674
- c = d8 >>> 13;
10675
- d8 &= 8191;
10676
- d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
10677
- c += d8 >>> 13;
10678
- d8 &= 8191;
10679
- let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
10680
- c = d9 >>> 13;
10681
- d9 &= 8191;
10682
- d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
10683
- c += d9 >>> 13;
10684
- d9 &= 8191;
10685
- c = (c << 2) + c | 0;
10686
- c = c + d0 | 0;
10687
- d0 = c & 8191;
10688
- c = c >>> 13;
10689
- d1 += c;
10690
- h[0] = d0;
10691
- h[1] = d1;
10692
- h[2] = d2;
10693
- h[3] = d3;
10694
- h[4] = d4;
10695
- h[5] = d5;
10696
- h[6] = d6;
10697
- h[7] = d7;
10698
- h[8] = d8;
10699
- h[9] = d9;
10688
+ registerInSchema(func, schemaPath, catalogName) {
10689
+ const add = (map, key) => {
10690
+ const bucket = map.get(key);
10691
+ if (!bucket) {
10692
+ map.set(key, [func]);
10693
+ return;
10694
+ }
10695
+ if (!bucket.includes(func))
10696
+ bucket.push(func);
10697
+ };
10698
+ add(this._bySchema, schemaKey(schemaPath, func.meta.name));
10699
+ if (catalogName) {
10700
+ add(this._byCatalog, catalogKey(catalogName, schemaPath, func.meta.name));
10701
+ }
10700
10702
  }
10701
- finalize() {
10702
- const { h, pad } = this;
10703
- const g = new Uint16Array(10);
10704
- let c = h[1] >>> 13;
10705
- h[1] &= 8191;
10706
- for (let i = 2;i < 10; i++) {
10707
- h[i] += c;
10708
- c = h[i] >>> 13;
10709
- h[i] &= 8191;
10703
+ schemasFor(functionName) {
10704
+ const out = [];
10705
+ for (const key of this._bySchema.keys()) {
10706
+ const separator = key.lastIndexOf("\x01");
10707
+ const name = key.slice(separator + 1);
10708
+ if (name === functionName)
10709
+ out.push(key.slice(0, separator).split("\x00"));
10710
10710
  }
10711
- h[0] += c * 5;
10712
- c = h[0] >>> 13;
10713
- h[0] &= 8191;
10714
- h[1] += c;
10715
- c = h[1] >>> 13;
10716
- h[1] &= 8191;
10717
- h[2] += c;
10718
- g[0] = h[0] + 5;
10719
- c = g[0] >>> 13;
10720
- g[0] &= 8191;
10721
- for (let i = 1;i < 10; i++) {
10722
- g[i] = h[i] + c;
10723
- c = g[i] >>> 13;
10724
- g[i] &= 8191;
10711
+ return out.sort((left, right) => schemaPathKey(left).localeCompare(schemaPathKey(right)));
10712
+ }
10713
+ get(name, context) {
10714
+ let candidates = this._functions.get(name);
10715
+ const catalogName = context?.catalogName;
10716
+ const schemaPath = context?.schemaPath;
10717
+ if (catalogName && schemaPath) {
10718
+ const scoped = this._byCatalog.get(catalogKey(catalogName, schemaPath, name));
10719
+ if (scoped && scoped.length > 0) {
10720
+ return this._disambiguate(name, scoped, context);
10721
+ }
10725
10722
  }
10726
- g[9] -= 1 << 13;
10727
- let mask = (c ^ 1) - 1;
10728
- for (let i = 0;i < 10; i++)
10729
- g[i] &= mask;
10730
- mask = ~mask;
10731
- for (let i = 0;i < 10; i++)
10732
- h[i] = h[i] & mask | g[i];
10733
- h[0] = (h[0] | h[1] << 13) & 65535;
10734
- h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
10735
- h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
10736
- h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
10737
- h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
10738
- h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
10739
- h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
10740
- h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
10741
- let f = h[0] + pad[0];
10742
- h[0] = f & 65535;
10743
- for (let i = 1;i < 8; i++) {
10744
- f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
10745
- h[i] = f & 65535;
10723
+ if (schemaPath) {
10724
+ const scoped = this._bySchema.get(schemaKey(schemaPath, name));
10725
+ if (scoped && scoped.length > 0) {
10726
+ candidates = scoped;
10727
+ } else if (candidates && candidates.length > 0) {
10728
+ const schemas = this.schemasFor(name);
10729
+ if (schemas.length > 0) {
10730
+ throw new Error(`Function '${name}' is not registered in schema ${schemaPathDisplay(schemaPath)}. ` + `It is available in: [${schemas.map(schemaPathDisplay).join(", ")}]`);
10731
+ }
10732
+ }
10746
10733
  }
10747
- clean(g);
10734
+ if (!candidates || candidates.length === 0) {
10735
+ throw new FunctionNotFoundError(name, this.names());
10736
+ }
10737
+ return this._disambiguate(name, candidates, context);
10748
10738
  }
10749
- update(data) {
10750
- aexists(this);
10751
- abytes(data);
10752
- data = copyBytes(data);
10753
- const { buffer, blockLen } = this;
10754
- const len = data.length;
10755
- for (let pos = 0;pos < len; ) {
10756
- const take = Math.min(blockLen - this.pos, len - pos);
10757
- if (take === blockLen) {
10758
- for (;blockLen <= len - pos; pos += blockLen)
10759
- this.process(data, pos);
10760
- continue;
10739
+ _disambiguate(name, candidates, context) {
10740
+ if (candidates.length === 1) {
10741
+ return candidates[0];
10742
+ }
10743
+ if (!context?.arguments) {
10744
+ return candidates[0];
10745
+ }
10746
+ const args = context.arguments;
10747
+ const isScalar = context.isScalar ?? candidates[0].kind === "scalar";
10748
+ let matches;
10749
+ if (isScalar) {
10750
+ const numConstArgs = args.positional.length;
10751
+ matches = candidates.filter((func) => {
10752
+ const constSpecs = func.argumentSpecs.filter((s) => s.isConst);
10753
+ const hasVarargs = constSpecs.some((s) => s.isVarargs);
10754
+ const nonVarargConst = constSpecs.filter((s) => !s.isVarargs).length;
10755
+ if (hasVarargs) {
10756
+ return numConstArgs >= nonVarargConst;
10757
+ }
10758
+ return constSpecs.length === numConstArgs;
10759
+ });
10760
+ if (matches.length === 0 || matches.length === candidates.length) {
10761
+ matches = candidates;
10761
10762
  }
10762
- buffer.set(data.subarray(pos, pos + take), this.pos);
10763
- this.pos += take;
10764
- pos += take;
10765
- if (this.pos === blockLen) {
10766
- this.process(buffer, 0, false);
10767
- this.pos = 0;
10763
+ } else {
10764
+ const numArgs = args.positional.length;
10765
+ matches = candidates.filter((func) => {
10766
+ const posSpecs = func.argumentSpecs.filter((s) => typeof s.position === "number" && !s.isTableInput);
10767
+ const hasVarargs = posSpecs.some((s) => s.isVarargs);
10768
+ const nonVarargs = posSpecs.filter((s) => !s.isVarargs).length;
10769
+ if (func.meta.inputFromArgs) {
10770
+ const numInputCols = context.inputSchema?.fields.length ?? 0;
10771
+ if (hasVarargs) {
10772
+ if (numInputCols < nonVarargs)
10773
+ return false;
10774
+ } else if (numInputCols !== posSpecs.length) {
10775
+ return false;
10776
+ }
10777
+ const validNamed = new Set(func.argumentSpecs.filter((s) => typeof s.position === "string").map((s) => s.position));
10778
+ for (const key of args.named.keys()) {
10779
+ if (!validNamed.has(key))
10780
+ return false;
10781
+ }
10782
+ return true;
10783
+ }
10784
+ if (hasVarargs) {
10785
+ return numArgs >= nonVarargs;
10786
+ }
10787
+ return posSpecs.length === numArgs;
10788
+ });
10789
+ if (matches.length === 0) {
10790
+ matches = candidates;
10791
+ }
10792
+ }
10793
+ if (matches.length === 1) {
10794
+ return matches[0];
10795
+ }
10796
+ const typeFiltered = filterByArgumentTypes(matches, args, context.inputSchema, isScalar);
10797
+ if (typeFiltered.length === 1) {
10798
+ return typeFiltered[0];
10799
+ }
10800
+ if (typeFiltered.length > 1) {
10801
+ return typeFiltered[0];
10802
+ }
10803
+ return candidates[0];
10804
+ }
10805
+ has(name) {
10806
+ return this._functions.has(name) && this._functions.get(name).length > 0;
10807
+ }
10808
+ names() {
10809
+ return [...this._functions.keys()].sort();
10810
+ }
10811
+ all() {
10812
+ const result = [];
10813
+ for (const candidates of this._functions.values()) {
10814
+ result.push(...candidates);
10815
+ }
10816
+ return result;
10817
+ }
10818
+ }
10819
+ // src/metadata/serialize.ts
10820
+ init_arrow();
10821
+ var EXAMPLE_STRUCT = struct2([
10822
+ field2("sql", utf82(), false),
10823
+ field2("description", utf82(), false),
10824
+ field2("expected_output", utf82(), true)
10825
+ ]);
10826
+ var PARAMETER_STRUCT = struct2([
10827
+ field2("name", utf82(), false),
10828
+ field2("position", int322(), true),
10829
+ field2("position_name", utf82(), true),
10830
+ field2("type_name", utf82(), true),
10831
+ field2("description", utf82(), false),
10832
+ field2("required", bool2(), false),
10833
+ field2("default", utf82(), true),
10834
+ field2("constraints", utf82(), true),
10835
+ field2("is_table_input", bool2(), false),
10836
+ field2("is_varargs", bool2(), false),
10837
+ field2("is_const", bool2(), false)
10838
+ ]);
10839
+ var FILTER_IDENTITY_STRUCT = struct2([
10840
+ field2("namespace", utf82(), false),
10841
+ field2("name", utf82(), false),
10842
+ field2("version", uint642(), false)
10843
+ ]);
10844
+ var FILTER_CONTEXT_STRUCT = struct2([
10845
+ field2("profile", utf82(), false),
10846
+ field2("provider_fingerprint", utf82(), true)
10847
+ ]);
10848
+ var METADATA_SCHEMA = schema2([
10849
+ field2("name", utf82(), false),
10850
+ field2("class_name", utf82(), false),
10851
+ field2("function_type", utf82(), false),
10852
+ field2("description", utf82(), false),
10853
+ field2("examples", list2(field2("item", EXAMPLE_STRUCT, true)), false),
10854
+ field2("categories", list2(field2("item", utf82(), true)), false),
10855
+ field2("tags", map2(field2("key", utf82(), false), field2("value", utf82(), true), false), false),
10856
+ field2("parameters", list2(field2("item", PARAMETER_STRUCT, true)), false),
10857
+ field2("stability", utf82(), false),
10858
+ field2("null_handling", utf82(), false),
10859
+ field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
10860
+ field2("required_settings", list2(field2("item", utf82(), true)), false),
10861
+ field2("required_secrets", list2(field2("item", utf82(), true)), false),
10862
+ field2("projection_pushdown", bool2(), false),
10863
+ field2("filter_pushdown", bool2(), false),
10864
+ field2("filter_semantic_profiles", list2(field2("item", utf82(), true)), false),
10865
+ field2("additional_filter_functions", list2(field2("item", FILTER_IDENTITY_STRUCT, true)), false),
10866
+ field2("runtime_filter_algorithms", list2(field2("item", FILTER_IDENTITY_STRUCT, true)), false),
10867
+ field2("filter_evaluation_contexts", list2(field2("item", FILTER_CONTEXT_STRUCT, true)), false),
10868
+ field2("preserves_order", utf82(), false),
10869
+ field2("max_workers", int322(), true),
10870
+ field2("order_dependent", utf82(), false),
10871
+ field2("distinct_dependent", utf82(), false)
10872
+ ]);
10873
+ function metadataToRow(m) {
10874
+ return {
10875
+ name: m.name,
10876
+ class_name: m.className,
10877
+ function_type: m.functionType,
10878
+ description: m.description,
10879
+ examples: m.examples.map((e) => ({
10880
+ sql: e.sql,
10881
+ description: e.description,
10882
+ expected_output: e.expectedOutput
10883
+ })),
10884
+ categories: m.categories,
10885
+ tags: Object.entries(m.tags).map(([k, v]) => [k, v]),
10886
+ parameters: m.parameters.map((p) => ({
10887
+ name: p.name,
10888
+ position: p.position,
10889
+ position_name: p.positionName,
10890
+ type_name: p.typeName,
10891
+ description: p.description,
10892
+ required: p.required,
10893
+ default: p.default,
10894
+ constraints: p.constraints,
10895
+ is_table_input: p.isTableInput,
10896
+ is_varargs: p.isVarargs,
10897
+ is_const: p.isConst
10898
+ })),
10899
+ stability: m.stability,
10900
+ null_handling: m.nullHandling,
10901
+ argument_monotonicity: m.argumentMonotonicity,
10902
+ required_settings: m.requiredSettings,
10903
+ required_secrets: m.requiredSecrets,
10904
+ projection_pushdown: m.projectionPushdown,
10905
+ filter_pushdown: m.filterPushdown,
10906
+ sampling_pushdown: m.samplingPushdown,
10907
+ filter_semantic_profiles: m.filterSemanticProfiles,
10908
+ additional_filter_functions: m.additionalFilterFunctions.map((value) => ({
10909
+ ...value,
10910
+ version: BigInt(value.version)
10911
+ })),
10912
+ runtime_filter_algorithms: m.runtimeFilterAlgorithms.map((value) => ({
10913
+ ...value,
10914
+ version: BigInt(value.version)
10915
+ })),
10916
+ filter_evaluation_contexts: m.filterEvaluationContexts.map((value) => ({
10917
+ profile: value.profile,
10918
+ provider_fingerprint: value.providerFingerprint
10919
+ })),
10920
+ preserves_order: m.preservesOrder,
10921
+ max_workers: m.maxWorkers,
10922
+ order_dependent: m.orderDependent,
10923
+ distinct_dependent: m.distinctDependent
10924
+ };
10925
+ }
10926
+ function metadatasToArrow(metadatas) {
10927
+ if (metadatas.length === 0) {
10928
+ return emptyBatch(METADATA_SCHEMA);
10929
+ }
10930
+ const rows = metadatas.map(metadataToRow);
10931
+ const columns = {};
10932
+ for (const f of METADATA_SCHEMA.fields) {
10933
+ columns[f.name] = rows.map((r) => r[f.name]);
10934
+ }
10935
+ return batchFromColumns(columns, METADATA_SCHEMA);
10936
+ }
10937
+ function arrowToMetadatas(batch) {
10938
+ const results = [];
10939
+ for (let i = 0;i < batch.numRows; i++) {
10940
+ const get = (name) => {
10941
+ const col = batch.getChild(name);
10942
+ return col ? col.get(i) : null;
10943
+ };
10944
+ const rawExamples = get("examples") ?? [];
10945
+ const examples = [];
10946
+ if (rawExamples && typeof rawExamples[Symbol.iterator] === "function") {
10947
+ for (const e of rawExamples) {
10948
+ if (e) {
10949
+ examples.push({
10950
+ sql: e.sql ?? "",
10951
+ description: e.description ?? "",
10952
+ expectedOutput: e.expected_output ?? null
10953
+ });
10954
+ }
10768
10955
  }
10769
10956
  }
10770
- return this;
10771
- }
10772
- destroy() {
10773
- this.destroyed = true;
10774
- clean(this.h, this.r, this.buffer, this.pad);
10775
- }
10776
- digestInto(out) {
10777
- aexists(this);
10778
- aoutput(out, this);
10779
- this.finished = true;
10780
- const { buffer, h } = this;
10781
- let { pos } = this;
10782
- if (pos) {
10783
- buffer[pos++] = 1;
10784
- for (;pos < 16; pos++)
10785
- buffer[pos] = 0;
10786
- this.process(buffer, 0, true);
10957
+ const rawParams = get("parameters") ?? [];
10958
+ const parameters = [];
10959
+ if (rawParams && typeof rawParams[Symbol.iterator] === "function") {
10960
+ for (const p of rawParams) {
10961
+ if (p) {
10962
+ parameters.push({
10963
+ name: p.name ?? "",
10964
+ position: p.position ?? null,
10965
+ positionName: p.position_name ?? null,
10966
+ typeName: p.type_name ?? null,
10967
+ description: p.description ?? "",
10968
+ required: p.required ?? true,
10969
+ default: p.default ?? null,
10970
+ constraints: p.constraints ?? null,
10971
+ isTableInput: p.is_table_input ?? false,
10972
+ isVarargs: p.is_varargs ?? false,
10973
+ isConst: p.is_const ?? false
10974
+ });
10975
+ }
10976
+ }
10787
10977
  }
10788
- this.finalize();
10789
- let opos = 0;
10790
- for (let i = 0;i < 8; i++) {
10791
- out[opos++] = h[i] >>> 0;
10792
- out[opos++] = h[i] >>> 8;
10978
+ const rawCategories = get("categories") ?? [];
10979
+ const categories = rawCategories ? [...rawCategories].filter((c) => c != null) : [];
10980
+ const rawTags = get("tags");
10981
+ const tags = {};
10982
+ if (rawTags) {
10983
+ if (typeof rawTags[Symbol.iterator] === "function") {
10984
+ for (const entry of rawTags) {
10985
+ if (Array.isArray(entry)) {
10986
+ tags[String(entry[0])] = String(entry[1] ?? "");
10987
+ } else if (entry && entry.key != null) {
10988
+ tags[String(entry.key)] = String(entry.value ?? "");
10989
+ }
10990
+ }
10991
+ }
10793
10992
  }
10794
- }
10795
- digest() {
10796
- const { buffer, outputLen } = this;
10797
- this.digestInto(buffer);
10798
- const res = buffer.slice(0, outputLen);
10799
- this.destroy();
10800
- return res;
10801
- }
10802
- }
10803
- var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
10804
-
10805
- // node_modules/@noble/ciphers/chacha.js
10806
- function chachaCore(s, k, n, out, cnt, rounds = 20) {
10807
- let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
10808
- let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
10809
- for (let r = 0;r < rounds; r += 2) {
10810
- x00 = x00 + x04 | 0;
10811
- x12 = rotl(x12 ^ x00, 16);
10812
- x08 = x08 + x12 | 0;
10813
- x04 = rotl(x04 ^ x08, 12);
10814
- x00 = x00 + x04 | 0;
10815
- x12 = rotl(x12 ^ x00, 8);
10816
- x08 = x08 + x12 | 0;
10817
- x04 = rotl(x04 ^ x08, 7);
10818
- x01 = x01 + x05 | 0;
10819
- x13 = rotl(x13 ^ x01, 16);
10820
- x09 = x09 + x13 | 0;
10821
- x05 = rotl(x05 ^ x09, 12);
10822
- x01 = x01 + x05 | 0;
10823
- x13 = rotl(x13 ^ x01, 8);
10824
- x09 = x09 + x13 | 0;
10825
- x05 = rotl(x05 ^ x09, 7);
10826
- x02 = x02 + x06 | 0;
10827
- x14 = rotl(x14 ^ x02, 16);
10828
- x10 = x10 + x14 | 0;
10829
- x06 = rotl(x06 ^ x10, 12);
10830
- x02 = x02 + x06 | 0;
10831
- x14 = rotl(x14 ^ x02, 8);
10832
- x10 = x10 + x14 | 0;
10833
- x06 = rotl(x06 ^ x10, 7);
10834
- x03 = x03 + x07 | 0;
10835
- x15 = rotl(x15 ^ x03, 16);
10836
- x11 = x11 + x15 | 0;
10837
- x07 = rotl(x07 ^ x11, 12);
10838
- x03 = x03 + x07 | 0;
10839
- x15 = rotl(x15 ^ x03, 8);
10840
- x11 = x11 + x15 | 0;
10841
- x07 = rotl(x07 ^ x11, 7);
10842
- x00 = x00 + x05 | 0;
10843
- x15 = rotl(x15 ^ x00, 16);
10844
- x10 = x10 + x15 | 0;
10845
- x05 = rotl(x05 ^ x10, 12);
10846
- x00 = x00 + x05 | 0;
10847
- x15 = rotl(x15 ^ x00, 8);
10848
- x10 = x10 + x15 | 0;
10849
- x05 = rotl(x05 ^ x10, 7);
10850
- x01 = x01 + x06 | 0;
10851
- x12 = rotl(x12 ^ x01, 16);
10852
- x11 = x11 + x12 | 0;
10853
- x06 = rotl(x06 ^ x11, 12);
10854
- x01 = x01 + x06 | 0;
10855
- x12 = rotl(x12 ^ x01, 8);
10856
- x11 = x11 + x12 | 0;
10857
- x06 = rotl(x06 ^ x11, 7);
10858
- x02 = x02 + x07 | 0;
10859
- x13 = rotl(x13 ^ x02, 16);
10860
- x08 = x08 + x13 | 0;
10861
- x07 = rotl(x07 ^ x08, 12);
10862
- x02 = x02 + x07 | 0;
10863
- x13 = rotl(x13 ^ x02, 8);
10864
- x08 = x08 + x13 | 0;
10865
- x07 = rotl(x07 ^ x08, 7);
10866
- x03 = x03 + x04 | 0;
10867
- x14 = rotl(x14 ^ x03, 16);
10868
- x09 = x09 + x14 | 0;
10869
- x04 = rotl(x04 ^ x09, 12);
10870
- x03 = x03 + x04 | 0;
10871
- x14 = rotl(x14 ^ x03, 8);
10872
- x09 = x09 + x14 | 0;
10873
- x04 = rotl(x04 ^ x09, 7);
10874
- }
10875
- let oi = 0;
10876
- out[oi++] = y00 + x00 | 0;
10877
- out[oi++] = y01 + x01 | 0;
10878
- out[oi++] = y02 + x02 | 0;
10879
- out[oi++] = y03 + x03 | 0;
10880
- out[oi++] = y04 + x04 | 0;
10881
- out[oi++] = y05 + x05 | 0;
10882
- out[oi++] = y06 + x06 | 0;
10883
- out[oi++] = y07 + x07 | 0;
10884
- out[oi++] = y08 + x08 | 0;
10885
- out[oi++] = y09 + x09 | 0;
10886
- out[oi++] = y10 + x10 | 0;
10887
- out[oi++] = y11 + x11 | 0;
10888
- out[oi++] = y12 + x12 | 0;
10889
- out[oi++] = y13 + x13 | 0;
10890
- out[oi++] = y14 + x14 | 0;
10891
- out[oi++] = y15 + x15 | 0;
10892
- }
10893
- function hchacha(s, k, i, out) {
10894
- const s2 = isLE ? s : swap32IfBE(s.slice(0, 4));
10895
- const k2 = isLE ? k : swap32IfBE(k.slice(0, 8));
10896
- const i2 = isLE ? i : swap32IfBE(i.slice(0, 4));
10897
- const t = new Uint32Array(16);
10898
- chachaCore(s2, k2, i2.subarray(1), t, i2[0]);
10899
- let oi = 0;
10900
- out[oi++] = t[0] - s2[0] | 0;
10901
- out[oi++] = t[1] - s2[1] | 0;
10902
- out[oi++] = t[2] - s2[2] | 0;
10903
- out[oi++] = t[3] - s2[3] | 0;
10904
- out[oi++] = t[12] - i2[0] | 0;
10905
- out[oi++] = t[13] - i2[1] | 0;
10906
- out[oi++] = t[14] - i2[2] | 0;
10907
- out[oi++] = t[15] - i2[3] | 0;
10908
- swap32IfBE(out);
10909
- if (!isLE)
10910
- clean(s2, k2, i2);
10911
- clean(t);
10912
- }
10913
- var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
10914
- counterRight: false,
10915
- counterLength: 8,
10916
- extendNonceFn: hchacha,
10917
- allowShortKeys: false
10918
- });
10919
- var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
10920
- var updatePadded = (h, msg) => {
10921
- h.update(msg);
10922
- const leftover = msg.length % 16;
10923
- if (leftover)
10924
- h.update(ZEROS16.subarray(leftover));
10925
- };
10926
- var ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
10927
- function computeTag(fn, key, nonce, ciphertext, AAD) {
10928
- if (AAD !== undefined)
10929
- abytes(AAD, undefined, "AAD");
10930
- const authKey = fn(key, nonce, ZEROS32);
10931
- const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
10932
- const h = poly1305.create(authKey);
10933
- if (AAD)
10934
- updatePadded(h, AAD);
10935
- updatePadded(h, ciphertext);
10936
- h.update(lengths);
10937
- const res = h.digest();
10938
- clean(authKey, lengths);
10939
- return res;
10993
+ const rawRequiredSettings = get("required_settings") ?? [];
10994
+ const requiredSettings = rawRequiredSettings ? [...rawRequiredSettings].filter((s) => s != null) : [];
10995
+ const rawRequiredSecrets = get("required_secrets") ?? [];
10996
+ const requiredSecrets = rawRequiredSecrets ? [...rawRequiredSecrets].filter((s) => s != null) : [];
10997
+ results.push({
10998
+ name: get("name") ?? "",
10999
+ className: get("class_name") ?? "",
11000
+ functionType: get("function_type") ?? "TABLE",
11001
+ description: get("description") ?? "",
11002
+ examples,
11003
+ categories,
11004
+ tags,
11005
+ parameters,
11006
+ stability: get("stability") ?? "CONSISTENT",
11007
+ nullHandling: get("null_handling") ?? "DEFAULT",
11008
+ argumentMonotonicity: get("argument_monotonicity") == null ? null : [...get("argument_monotonicity")].map(String),
11009
+ requiredSettings,
11010
+ requiredSecrets,
11011
+ projectionPushdown: get("projection_pushdown") ?? false,
11012
+ filterPushdown: get("filter_pushdown") ?? false,
11013
+ samplingPushdown: get("sampling_pushdown") ?? false,
11014
+ filterSemanticProfiles: [...get("filter_semantic_profiles") ?? []].filter((s) => s != null).map(String),
11015
+ additionalFilterFunctions: [...get("additional_filter_functions") ?? []].filter((v) => v != null).map((v) => ({
11016
+ namespace: String(v.namespace),
11017
+ name: String(v.name),
11018
+ version: Number(v.version)
11019
+ })),
11020
+ runtimeFilterAlgorithms: [...get("runtime_filter_algorithms") ?? []].filter((v) => v != null).map((v) => ({
11021
+ namespace: String(v.namespace),
11022
+ name: String(v.name),
11023
+ version: Number(v.version)
11024
+ })),
11025
+ filterEvaluationContexts: [...get("filter_evaluation_contexts") ?? []].filter((v) => v != null).map((v) => ({
11026
+ profile: String(v.profile),
11027
+ providerFingerprint: v.provider_fingerprint == null ? null : String(v.provider_fingerprint)
11028
+ })),
11029
+ preservesOrder: get("preserves_order") ?? "NO_ORDER_GUARANTEE",
11030
+ maxWorkers: get("max_workers") ?? null,
11031
+ orderDependent: get("order_dependent") ?? "NOT_ORDER_DEPENDENT",
11032
+ distinctDependent: get("distinct_dependent") ?? "NOT_DISTINCT_DEPENDENT"
11033
+ });
11034
+ }
11035
+ return results;
10940
11036
  }
10941
- var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
10942
- const tagLength = 16;
10943
- return {
10944
- encrypt(plaintext, output) {
10945
- const plength = plaintext.length;
10946
- output = getOutput(plength + tagLength, output, false);
10947
- output.set(plaintext);
10948
- const oPlain = output.subarray(0, -tagLength);
10949
- xorStream(key, nonce, oPlain, oPlain, 1);
10950
- const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
10951
- output.set(tag, plength);
10952
- clean(tag);
10953
- return output;
10954
- },
10955
- decrypt(ciphertext, output) {
10956
- output = getOutput(ciphertext.length - tagLength, output, false);
10957
- const data = ciphertext.subarray(0, -tagLength);
10958
- const passedTag = ciphertext.subarray(-tagLength);
10959
- const tag = computeTag(xorStream, key, nonce, data, AAD);
10960
- if (!equalBytes(passedTag, tag)) {
10961
- clean(tag);
10962
- throw new Error("invalid tag");
10963
- }
10964
- output.set(ciphertext.subarray(0, -tagLength));
10965
- xorStream(key, nonce, output, output, 1);
10966
- clean(tag);
10967
- return output;
10968
- }
10969
- };
10970
- };
10971
- var xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true }, /* @__PURE__ */ _poly1305_aead(xchacha20));
11037
+ // src/protocol/dispatch.ts
11038
+ import { Protocol as Protocol2 } from "@query-farm/vgi-rpc";
10972
11039
 
10973
- // src/crypto.ts
10974
- var _UTF8 = new TextEncoder;
10975
- var ATTACH_ENVELOPE_VERSION = 2;
10976
- var TRANSACTION_ENVELOPE_VERSION = 2;
10977
- var ATTACH_UUID_LEN = 16;
10978
- var NONCE_LEN = 24;
10979
- var TAG_LEN = 16;
10980
- var MIN_ENVELOPE_LEN = 1 + NONCE_LEN + TAG_LEN;
10981
- var ATTACH_AAD_PREFIX = _UTF8.encode("vgi.attach_opaque_data.v1\x00");
10982
- var TRANSACTION_AAD_PREFIX = _UTF8.encode("vgi.transaction_opaque_data.v1\x00");
11040
+ // src/protocol/handlers/function.ts
11041
+ init_arrow();
10983
11042
 
10984
- class OpaqueDataRejectedError extends Error {
10985
- constructor(field = "opaque data") {
10986
- super(`${field} not recognized`);
10987
- this.name = "OpaqueDataRejectedError";
10988
- }
10989
- }
10990
- function concat(...parts) {
10991
- let total = 0;
10992
- for (const p of parts)
10993
- total += p.length;
10994
- const out = new Uint8Array(total);
10995
- let off = 0;
10996
- for (const p of parts) {
10997
- out.set(p, off);
10998
- off += p.length;
10999
- }
11000
- return out;
11001
- }
11002
- async function normalizeKey(key) {
11003
- if (key.length === 32)
11004
- return key;
11005
- return new Uint8Array(await crypto.subtle.digest("SHA-256", key));
11006
- }
11007
- function identityTail(auth) {
11008
- if (!auth || !auth.authenticated)
11009
- return _UTF8.encode("\x00anonymous");
11010
- const domain = _UTF8.encode(auth.domain ?? "");
11011
- const principal = _UTF8.encode(auth.principal ?? "");
11012
- return concat(Uint8Array.of(1), domain, Uint8Array.of(0), principal);
11013
- }
11014
- function attachAad(auth) {
11015
- return concat(ATTACH_AAD_PREFIX, identityTail(auth));
11043
+ // src/protocol/handlers/shared.ts
11044
+ init_arrow();
11045
+ var RESULT_BINARY_SCHEMA = schema2([
11046
+ field2("result", binary2(), false)
11047
+ ]);
11048
+ var REQUEST_PARAMS_SCHEMA = schema2([
11049
+ field2("request", binary2(), false)
11050
+ ]);
11051
+ var RESULT_BINARY_NULLABLE_SCHEMA = schema2([
11052
+ field2("result", binary2(), true)
11053
+ ]);
11054
+ function unwrapRequest(requestBytes) {
11055
+ const bytes = toUint8Array(requestBytes);
11056
+ const innerBatch = deserializeBatch(bytes);
11057
+ const params = batchToScalarDict(innerBatch);
11058
+ normalizeRequestSchemaPaths(params);
11059
+ return params;
11016
11060
  }
11017
- function transactionAad(auth, attachEnvelope) {
11018
- return concat(TRANSACTION_AAD_PREFIX, identityTail(auth), Uint8Array.of(0), attachEnvelope);
11061
+ function normalizeRequestSchemaPaths(params) {
11062
+ if (params.path != null)
11063
+ params.path = normalizeSchemaPath(params.path);
11064
+ if (params.schema_path != null)
11065
+ params.schema_path = normalizeSchemaPath(params.schema_path);
11019
11066
  }
11020
- async function sealBytes(payload, key, aad, version) {
11021
- const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LEN));
11022
- const ciphertext = xchacha20poly1305(await normalizeKey(key), nonce, aad).encrypt(payload);
11023
- const out = new Uint8Array(1 + NONCE_LEN + ciphertext.length);
11024
- out[0] = version & 255;
11025
- out.set(nonce, 1);
11026
- out.set(ciphertext, 1 + NONCE_LEN);
11027
- return out;
11067
+ function wrapResult(values, innerSchema) {
11068
+ const a = innerSchema;
11069
+ const batch = batchFromColumns(Object.fromEntries(a.fields.map((f) => [f.name, [values[f.name] ?? null]])), a);
11070
+ return { result: serializeBatch(batch) };
11028
11071
  }
11029
- async function openBytes(token, key, aad, version, field = "opaque data") {
11030
- if (token.length < MIN_ENVELOPE_LEN || token[0] !== (version & 255)) {
11031
- throw new OpaqueDataRejectedError(field);
11032
- }
11033
- const nonce = token.subarray(1, 1 + NONCE_LEN);
11034
- const ciphertext = token.subarray(1 + NONCE_LEN);
11035
- try {
11036
- return xchacha20poly1305(await normalizeKey(key), nonce, aad).decrypt(ciphertext);
11037
- } catch {
11038
- throw new OpaqueDataRejectedError(field);
11072
+ function overloadContext(req, catalogInterface) {
11073
+ let catalogName = null;
11074
+ if (catalogInterface && req.attach_opaque_data) {
11075
+ try {
11076
+ catalogName = catalogInterface.catalogNameForAttach(req.attach_opaque_data);
11077
+ } catch {
11078
+ catalogName = null;
11079
+ }
11039
11080
  }
11081
+ return {
11082
+ arguments: req.arguments,
11083
+ inputSchema: req.input_schema,
11084
+ isScalar: String(req.function_type).toLowerCase() === "scalar",
11085
+ schemaPath: req.schema_path ?? null,
11086
+ catalogName
11087
+ };
11040
11088
  }
11041
11089
 
11042
11090
  // src/protocol/handlers/catalog/shared.ts
11091
+ init_arrow();
11043
11092
  async function sealAttach(plaintext, auth, signingKey) {
11044
11093
  const uuid = new Uint8Array(ATTACH_UUID_LEN);
11045
11094
  crypto.getRandomValues(uuid);
@@ -12072,6 +12121,398 @@ async function serveCatalogContents(cat, attach, ifNoneMatch) {
12072
12121
  return wrapResult(await buildCatalogContents(cat, owner, attach, version, ifNoneMatch), CatalogContentsResultSchema);
12073
12122
  }
12074
12123
 
12124
+ // src/attach-ticket.ts
12125
+ init_arrow();
12126
+ import {
12127
+ Protocol,
12128
+ badRequest,
12129
+ errorInfo,
12130
+ preconditionFailure
12131
+ } from "@query-farm/vgi-rpc";
12132
+ var ATTACH_TICKET_PREFIX = "vgia1.";
12133
+ var ATTACH_TICKET_OPTION = RESERVED_ATTACH_OPTION;
12134
+ var ATTACH_TICKETS_PROTOCOL_NAME = "vgi.attach_tickets.v1";
12135
+ var ATTACH_TICKETS_PROTOCOL_VERSION = "1.0.0";
12136
+ var TICKET_ENVELOPE_VERSION = 1;
12137
+ var MAX_OPTIONS_BYTES = 16 * 1024;
12138
+ var MAX_TICKET_CHARS = 32 * 1024;
12139
+ var CLOCK_SKEW_SECONDS = 60;
12140
+ var UTF82 = new TextEncoder;
12141
+ var STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
12142
+ var TICKET_AAD_DOMAIN = UTF82.encode("vgi.attach_ticket.v1\x00");
12143
+ var TICKET_ID = /^[0-9a-f]{32}$/;
12144
+ var B64URL = /^[A-Za-z0-9_-]+$/;
12145
+ var MAX_TEXT = 65535;
12146
+
12147
+ class AttachTicketInvalidError extends Error {
12148
+ static errorKind = "attach_ticket_invalid";
12149
+ errorKind = "attach_ticket_invalid";
12150
+ errorCode = "INVALID_ARGUMENT";
12151
+ errorDetails;
12152
+ constructor(detail = "attach ticket not accepted") {
12153
+ super(detail);
12154
+ this.name = "AttachTicketInvalidError";
12155
+ this.errorDetails = [badRequest([{ field: ATTACH_TICKET_OPTION, description: detail }])];
12156
+ }
12157
+ }
12158
+
12159
+ class AttachTicketExpiredError extends Error {
12160
+ static errorKind = "attach_ticket_expired";
12161
+ errorKind = "attach_ticket_expired";
12162
+ errorCode = "FAILED_PRECONDITION";
12163
+ errorDetails;
12164
+ constructor(detail = "attach ticket has expired") {
12165
+ super(detail);
12166
+ this.name = "AttachTicketExpiredError";
12167
+ this.errorDetails = [
12168
+ preconditionFailure([{ type: "ATTACH_TICKET", subject: ATTACH_TICKET_OPTION, description: detail }])
12169
+ ];
12170
+ }
12171
+ }
12172
+
12173
+ class AttachTicketRequestError extends Error {
12174
+ errorKind = "invalid_request";
12175
+ errorCode = "INVALID_ARGUMENT";
12176
+ errorDetails;
12177
+ constructor(message, violations) {
12178
+ super(message);
12179
+ this.name = "AttachTicketRequestError";
12180
+ this.errorDetails = [
12181
+ badRequest(violations.map(([f, description]) => ({ field: f, description })))
12182
+ ];
12183
+ }
12184
+ }
12185
+
12186
+ class SealAttachDeniedError extends Error {
12187
+ errorKind = "action_denied";
12188
+ errorCode = "PERMISSION_DENIED";
12189
+ errorDetails = [errorInfo({ action: "seal_attach" })];
12190
+ constructor(message) {
12191
+ super(message);
12192
+ this.name = "SealAttachDeniedError";
12193
+ }
12194
+ }
12195
+ function attachTicketAad(principal) {
12196
+ const p = UTF82.encode(principal);
12197
+ const out = new Uint8Array(TICKET_AAD_DOMAIN.length + p.length);
12198
+ out.set(TICKET_AAD_DOMAIN, 0);
12199
+ out.set(p, TICKET_AAD_DOMAIN.length);
12200
+ return out;
12201
+ }
12202
+ function packText(value, name) {
12203
+ const raw = UTF82.encode(value);
12204
+ if (raw.length > MAX_TEXT)
12205
+ throw new Error(`${name} is longer than 65535 bytes`);
12206
+ const out = new Uint8Array(2 + raw.length);
12207
+ new DataView(out.buffer).setUint16(0, raw.length, true);
12208
+ out.set(raw, 2);
12209
+ return out;
12210
+ }
12211
+ function encodePayload(c) {
12212
+ if (c.optionsIpc.length > MAX_OPTIONS_BYTES) {
12213
+ throw new Error(`options are ${c.optionsIpc.length} bytes; a ticket carries at most ${MAX_OPTIONS_BYTES}`);
12214
+ }
12215
+ const head = new Uint8Array(16);
12216
+ const hv = new DataView(head.buffer);
12217
+ hv.setBigInt64(0, BigInt(c.issuedAt), true);
12218
+ hv.setBigInt64(8, BigInt(c.expiresAt), true);
12219
+ const optLen = new Uint8Array(4);
12220
+ new DataView(optLen.buffer).setUint32(0, c.optionsIpc.length, true);
12221
+ const parts = [
12222
+ head,
12223
+ packText(c.ticketId, "ticket_id"),
12224
+ packText(c.catalogName, "catalog_name"),
12225
+ packText(c.dataVersionSpec, "data_version_spec"),
12226
+ packText(c.implementationVersion, "implementation_version"),
12227
+ optLen,
12228
+ c.optionsIpc
12229
+ ];
12230
+ let total = 0;
12231
+ for (const p of parts)
12232
+ total += p.length;
12233
+ const out = new Uint8Array(total);
12234
+ let off = 0;
12235
+ for (const p of parts) {
12236
+ out.set(p, off);
12237
+ off += p.length;
12238
+ }
12239
+ return out;
12240
+ }
12241
+ function decodePayload(payload) {
12242
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
12243
+ let pos = 0;
12244
+ const need = (n) => {
12245
+ if (pos + n > payload.length)
12246
+ throw new AttachTicketInvalidError("attach ticket payload is truncated");
12247
+ };
12248
+ const text = () => {
12249
+ need(2);
12250
+ const len = view.getUint16(pos, true);
12251
+ pos += 2;
12252
+ need(len);
12253
+ const raw = payload.subarray(pos, pos + len);
12254
+ pos += len;
12255
+ try {
12256
+ return STRICT_UTF8.decode(raw);
12257
+ } catch {
12258
+ throw new AttachTicketInvalidError("attach ticket payload is not UTF-8");
12259
+ }
12260
+ };
12261
+ need(16);
12262
+ const issuedAt = Number(view.getBigInt64(0, true));
12263
+ const expiresAt = Number(view.getBigInt64(8, true));
12264
+ pos = 16;
12265
+ const ticketId = text();
12266
+ const catalogName = text();
12267
+ const dataVersionSpec = text();
12268
+ const implementationVersion = text();
12269
+ need(4);
12270
+ const optionsLen = view.getUint32(pos, true);
12271
+ pos += 4;
12272
+ if (optionsLen > MAX_OPTIONS_BYTES)
12273
+ throw new AttachTicketInvalidError("attach ticket options exceed 16 KiB");
12274
+ need(optionsLen);
12275
+ const optionsIpc = payload.slice(pos, pos + optionsLen);
12276
+ pos += optionsLen;
12277
+ if (pos !== payload.length)
12278
+ throw new AttachTicketInvalidError("attach ticket payload has trailing bytes");
12279
+ if (!TICKET_ID.test(ticketId))
12280
+ throw new AttachTicketInvalidError("attach ticket id is not 32 lowercase hex");
12281
+ if (!catalogName)
12282
+ throw new AttachTicketInvalidError("attach ticket names no catalog");
12283
+ if (expiresAt !== 0 && expiresAt <= issuedAt)
12284
+ throw new AttachTicketInvalidError("attach ticket lifetime is empty");
12285
+ return { issuedAt, expiresAt, ticketId, catalogName, dataVersionSpec, implementationVersion, optionsIpc };
12286
+ }
12287
+ function b64url(data) {
12288
+ let bin = "";
12289
+ for (let i = 0;i < data.length; i++)
12290
+ bin += String.fromCharCode(data[i]);
12291
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
12292
+ }
12293
+ function b64urlStrict(text) {
12294
+ if (!B64URL.test(text) || text.length % 4 === 1) {
12295
+ throw new AttachTicketInvalidError("attach ticket is not unpadded base64url");
12296
+ }
12297
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - text.length % 4) % 4);
12298
+ const bin = atob(padded);
12299
+ const raw = new Uint8Array(bin.length);
12300
+ for (let i = 0;i < bin.length; i++)
12301
+ raw[i] = bin.charCodeAt(i);
12302
+ if (b64url(raw) !== text)
12303
+ throw new AttachTicketInvalidError("attach ticket is not canonical base64url");
12304
+ return raw;
12305
+ }
12306
+ function randomHex(bytes) {
12307
+ const b = crypto.getRandomValues(new Uint8Array(bytes));
12308
+ let s = "";
12309
+ for (const x of b)
12310
+ s += x.toString(16).padStart(2, "0");
12311
+ return s;
12312
+ }
12313
+ async function mintAttachTicket(signingKey, opts) {
12314
+ if (!opts.principal)
12315
+ throw new Error("a ticket needs a principal");
12316
+ if (!opts.catalogName)
12317
+ throw new Error("a ticket needs a catalog name");
12318
+ const claims = {
12319
+ issuedAt: Math.trunc(opts.issuedAt),
12320
+ expiresAt: Math.trunc(opts.expiresAt),
12321
+ ticketId: opts.ticketId ?? randomHex(16),
12322
+ catalogName: opts.catalogName,
12323
+ dataVersionSpec: opts.dataVersionSpec ?? "",
12324
+ implementationVersion: opts.implementationVersion ?? "",
12325
+ optionsIpc: opts.optionsIpc
12326
+ };
12327
+ if (!TICKET_ID.test(claims.ticketId))
12328
+ throw new Error("ticket_id must be 32 lowercase hex");
12329
+ if (claims.expiresAt !== 0 && claims.expiresAt <= claims.issuedAt) {
12330
+ throw new Error("expires_at must be 0 or after issued_at");
12331
+ }
12332
+ const envelope = await sealBytes(encodePayload(claims), signingKey, attachTicketAad(opts.principal), TICKET_ENVELOPE_VERSION, opts.nonce);
12333
+ const token = ATTACH_TICKET_PREFIX + b64url(envelope);
12334
+ if (token.length > MAX_TICKET_CHARS) {
12335
+ throw new Error(`the ticket would be ${token.length} characters; at most ${MAX_TICKET_CHARS} are accepted`);
12336
+ }
12337
+ return { token, claims };
12338
+ }
12339
+ async function openAttachTicket(signingKey, token, principal, now) {
12340
+ if (!token.startsWith(ATTACH_TICKET_PREFIX))
12341
+ throw new AttachTicketInvalidError("not an attach ticket");
12342
+ if (token.length > MAX_TICKET_CHARS)
12343
+ throw new AttachTicketInvalidError("attach ticket is too long");
12344
+ const envelope = b64urlStrict(token.slice(ATTACH_TICKET_PREFIX.length));
12345
+ if (!principal)
12346
+ throw new AttachTicketInvalidError("an anonymous caller cannot redeem an attach ticket");
12347
+ let payload;
12348
+ try {
12349
+ payload = await openBytes(envelope, signingKey, attachTicketAad(principal), TICKET_ENVELOPE_VERSION);
12350
+ } catch (e) {
12351
+ if (e instanceof OpaqueDataRejectedError) {
12352
+ throw new AttachTicketInvalidError("attach ticket failed verification");
12353
+ }
12354
+ throw e;
12355
+ }
12356
+ const claims = decodePayload(payload);
12357
+ const current = now ?? Date.now() / 1000;
12358
+ if (claims.issuedAt > current + CLOCK_SKEW_SECONDS)
12359
+ throw new AttachTicketExpiredError("attach ticket is not yet valid");
12360
+ if (claims.expiresAt !== 0 && current >= claims.expiresAt + CLOCK_SKEW_SECONDS) {
12361
+ throw new AttachTicketExpiredError("attach ticket has expired");
12362
+ }
12363
+ return claims;
12364
+ }
12365
+ function callerPrincipal(auth) {
12366
+ if (!auth || !auth.authenticated)
12367
+ return null;
12368
+ return auth.principal || null;
12369
+ }
12370
+ async function redeemAttachTicket(options, signingKey, auth, now) {
12371
+ const keys = Object.keys(options);
12372
+ const ticketKeys = keys.filter((k) => k.toLowerCase() === ATTACH_TICKET_OPTION);
12373
+ if (ticketKeys.length === 0)
12374
+ return null;
12375
+ const others = keys.filter((k) => k !== ticketKeys[0]);
12376
+ if (others.length > 0) {
12377
+ throw new AttachTicketRequestError(`${ATTACH_TICKET_OPTION} must be the only attach option`, others.map((k) => [`options.${k}`, `not allowed alongside ${ATTACH_TICKET_OPTION}`]));
12378
+ }
12379
+ const token = options[ticketKeys[0]];
12380
+ if (typeof token !== "string")
12381
+ throw new AttachTicketInvalidError(`${ATTACH_TICKET_OPTION} must be a string`);
12382
+ if (!signingKey)
12383
+ throw new AttachTicketInvalidError("this worker does not redeem attach tickets");
12384
+ const claims = await openAttachTicket(signingKey, token, callerPrincipal(auth), now);
12385
+ let restored = {};
12386
+ if (claims.optionsIpc.length > 0) {
12387
+ try {
12388
+ restored = decodeOptionsBatch(claims.optionsIpc);
12389
+ } catch {
12390
+ throw new AttachTicketInvalidError("attach ticket options are not an Arrow IPC record");
12391
+ }
12392
+ }
12393
+ return {
12394
+ name: claims.catalogName,
12395
+ optionsIpc: claims.optionsIpc.length > 0 ? claims.optionsIpc : null,
12396
+ options: restored,
12397
+ dataVersionSpec: claims.dataVersionSpec || null,
12398
+ implementationVersion: claims.implementationVersion || null
12399
+ };
12400
+ }
12401
+ var SEAL_ATTACH_REQUEST_SCHEMA = schema2([
12402
+ field2("catalog_name", utf82(), false),
12403
+ field2("options", binary2(), true),
12404
+ field2("data_version_spec", utf82(), false),
12405
+ field2("implementation_version", utf82(), false),
12406
+ field2("ttl_seconds", int642(), false)
12407
+ ]);
12408
+ var ATTACH_TICKET_SCHEMA = schema2([
12409
+ field2("ticket", utf82(), false),
12410
+ field2("expires_at", float642(), false)
12411
+ ]);
12412
+ function resolveTicketMaxTtl(grantKeys, env) {
12413
+ if (grantKeys)
12414
+ return Math.trunc(grantKeys.maxTtlSeconds);
12415
+ const raw = (env?.VGI_RPC_GRANT_MAX_TTL_SECONDS ?? "").trim();
12416
+ if (!raw)
12417
+ return null;
12418
+ const value = /^\d+$/.test(raw) ? Number(raw) : 0;
12419
+ if (!(value > 0))
12420
+ throw new Error(`VGI_RPC_GRANT_MAX_TTL_SECONDS=${JSON.stringify(raw)} must be a positive integer`);
12421
+ return value;
12422
+ }
12423
+ async function declaredSpecs(catalog, catalogName) {
12424
+ if (!catalog)
12425
+ return null;
12426
+ const infos = catalog.catalogsInfo ? await catalog.catalogsInfo() : catalog.catalogs().map((name) => ({ name, attach_option_specs: [] }));
12427
+ for (const info of infos) {
12428
+ if (info.name === catalogName) {
12429
+ return deserializeAttachOptionSpecs((info.attach_option_specs ?? []).map((b) => toUint8Array(b)));
12430
+ }
12431
+ }
12432
+ return null;
12433
+ }
12434
+ async function sealAttach2(config, request, auth) {
12435
+ const principal = callerPrincipal(auth);
12436
+ if (principal === null)
12437
+ throw new SealAttachDeniedError("an anonymous caller cannot seal an attach ticket");
12438
+ const violations = [];
12439
+ const ttl = Number(request.ttl_seconds ?? 0);
12440
+ if (!Number.isFinite(ttl) || ttl < 0)
12441
+ violations.push(["ttl_seconds", "must be 0 (as long as allowed) or positive"]);
12442
+ const catalogName = String(request.catalog_name ?? "");
12443
+ let optionsIpc = new Uint8Array(0);
12444
+ let options = {};
12445
+ if (request.options != null) {
12446
+ const raw = toUint8Array(request.options);
12447
+ if (raw.length > 0) {
12448
+ const batch = deserializeBatch(raw);
12449
+ if (batch.numRows > 1) {
12450
+ violations.push(["options", "must be a one-row record"]);
12451
+ } else if (batch.numRows === 1) {
12452
+ options = decodeOptionsBatch(raw);
12453
+ optionsIpc = raw;
12454
+ }
12455
+ }
12456
+ }
12457
+ const specs = await declaredSpecs(config.catalogInterface, catalogName);
12458
+ if (specs === null) {
12459
+ violations.push(["catalog_name", `no catalog named ${JSON.stringify(catalogName)}`]);
12460
+ } else {
12461
+ const declared = new Set(specs.map((s) => s.name.toLowerCase()));
12462
+ for (const name of Object.keys(options)) {
12463
+ if (name.toLowerCase() === ATTACH_TICKET_OPTION) {
12464
+ violations.push([`options.${name}`, "a ticket cannot seal another ticket"]);
12465
+ } else if (!declared.has(name.toLowerCase())) {
12466
+ violations.push([`options.${name}`, "not an attach option this catalog declares"]);
12467
+ }
12468
+ }
12469
+ const supplied = new Set(Object.keys(options).map((n) => n.toLowerCase()));
12470
+ for (const spec of specs) {
12471
+ if (spec.required && !supplied.has(spec.name.toLowerCase()))
12472
+ violations.push([`options.${spec.name}`, "required"]);
12473
+ }
12474
+ }
12475
+ if (optionsIpc.length > MAX_OPTIONS_BYTES) {
12476
+ violations.push(["options", `${optionsIpc.length} bytes; a ticket carries at most ${MAX_OPTIONS_BYTES}`]);
12477
+ }
12478
+ if (violations.length > 0)
12479
+ throw new AttachTicketRequestError("seal_attach request is invalid", violations);
12480
+ const issuedAt = Math.trunc(config.now ? config.now() : Date.now() / 1000);
12481
+ const ceiling = config.maxTtlSeconds;
12482
+ const lifetime = ttl === 0 ? ceiling : ceiling === null ? Math.trunc(ttl) : Math.min(Math.trunc(ttl), ceiling);
12483
+ const expiresAt = lifetime === null ? 0 : issuedAt + lifetime;
12484
+ let token;
12485
+ try {
12486
+ ({ token } = await mintAttachTicket(config.signingKey, {
12487
+ principal,
12488
+ catalogName,
12489
+ optionsIpc,
12490
+ dataVersionSpec: String(request.data_version_spec ?? ""),
12491
+ implementationVersion: String(request.implementation_version ?? ""),
12492
+ issuedAt,
12493
+ expiresAt
12494
+ }));
12495
+ } catch (e) {
12496
+ throw new AttachTicketRequestError("seal_attach request is invalid", [["request", e.message]]);
12497
+ }
12498
+ return { ticket: token, expires_at: expiresAt === 0 ? Number.POSITIVE_INFINITY : expiresAt };
12499
+ }
12500
+ function buildAttachTicketsProtocol(config) {
12501
+ const p = new Protocol(ATTACH_TICKETS_PROTOCOL_NAME, { protocolVersion: ATTACH_TICKETS_PROTOCOL_VERSION });
12502
+ p.unary("seal_attach", {
12503
+ params: REQUEST_PARAMS_SCHEMA,
12504
+ result: RESULT_BINARY_SCHEMA,
12505
+ doc: "Seal the caller's attach of request.catalog_name into a ticket.",
12506
+ handler: async (params, ctx) => {
12507
+ const request = unwrapRequest(params.request);
12508
+ const sealed = await sealAttach2(config, request, ctx?.auth);
12509
+ const batch = batchFromColumns({ ticket: [sealed.ticket], expires_at: [sealed.expires_at] }, ATTACH_TICKET_SCHEMA);
12510
+ return { result: serializeBatch(batch) };
12511
+ }
12512
+ });
12513
+ return p;
12514
+ }
12515
+
12075
12516
  // src/protocol/handlers/catalog/admin.ts
12076
12517
  function registerCatalogAdminMethods(protocol, getCatalog, signingKey) {
12077
12518
  catalogUnary(protocol, signingKey, "catalog_catalogs", {
@@ -12096,7 +12537,15 @@ function registerCatalogAdminMethods(protocol, getCatalog, signingKey) {
12096
12537
  handler: async (params, ctx) => {
12097
12538
  const innerParams = unwrapRequest(params.request);
12098
12539
  const cat = getCatalog();
12099
- const optionsDict = decodeOptionsBatch(innerParams.options);
12540
+ let optionsDict = decodeOptionsBatch(innerParams.options);
12541
+ const restored = await redeemAttachTicket(optionsDict, signingKey, ctx?.auth ?? currentRequestAuth());
12542
+ if (restored !== null) {
12543
+ innerParams.name = restored.name;
12544
+ innerParams.options = restored.optionsIpc;
12545
+ innerParams.data_version_spec = restored.dataVersionSpec;
12546
+ innerParams.implementation_version = restored.implementationVersion;
12547
+ optionsDict = restored.options;
12548
+ }
12100
12549
  const result = await cat.attach(innerParams.name, optionsDict, innerParams.data_version_spec ?? null, innerParams.implementation_version ?? null);
12101
12550
  const sealedAttach = await sealAttach(toUint8Array(result.attach_opaque_data), ctx?.auth, signingKey);
12102
12551
  return wrapResult(buildCatalogAttachResult({
@@ -12552,7 +13001,7 @@ function registerCatalogMethods(protocol, catalog, _catalogName, signingKey) {
12552
13001
  // src/protocol/dispatch.ts
12553
13002
  var VGI_PROTOCOL_NAME = "vgi.v2";
12554
13003
  function buildVgiProtocol(config) {
12555
- const protocol = new Protocol(VGI_PROTOCOL_NAME, { protocolVersion: "2.1.0" });
13004
+ const protocol = new Protocol2(VGI_PROTOCOL_NAME, { protocolVersion: "2.1.0" });
12556
13005
  registerFunctionMethods(protocol, {
12557
13006
  registry: config.registry,
12558
13007
  signingKey: config.signingKey,
@@ -13722,6 +14171,7 @@ import { subprocessConnect, httpConnect, tcpConnect } from "@query-farm/vgi-rpc"
13722
14171
 
13723
14172
  // src/rpc-server.ts
13724
14173
  import {
14174
+ GrantKeys,
13725
14175
  IdentityImpl,
13726
14176
  VgiRpcServer
13727
14177
  } from "@query-farm/vgi-rpc";
@@ -13734,11 +14184,20 @@ function buildRpcServer(primary, hosting, options) {
13734
14184
  throw new Error(`Unknown transport ${JSON.stringify(options.transport)}; expected one of ${[...TRANSPORTS].join(", ")}.`);
13735
14185
  }
13736
14186
  const protocols = validatedHostedProtocols(hosting, primary);
13737
- const identity = IDENTITY_TRANSPORTS.has(options.transport) ? buildIdentity(hosting, options.env) : undefined;
14187
+ let identity;
14188
+ if (IDENTITY_TRANSPORTS.has(options.transport)) {
14189
+ const env = options.env ?? processEnv();
14190
+ const grantKeys = hosting.grantKeys === undefined ? GrantKeys.fromEnv(env) : hosting.grantKeys;
14191
+ identity = buildIdentity(hosting, grantKeys, options.env);
14192
+ const tickets = buildAttachTickets(hosting, grantKeys, options.attachTickets, env);
14193
+ if (tickets)
14194
+ protocols.push(tickets);
14195
+ }
13738
14196
  return new VgiRpcServer(primary, {
13739
14197
  serverId: options.serverId,
13740
14198
  protocols,
13741
- identity
14199
+ identity,
14200
+ grantKeys: null
13742
14201
  });
13743
14202
  }
13744
14203
  function validatedHostedProtocols(hosting, primary) {
@@ -13779,17 +14238,29 @@ function validatedHostedProtocols(hosting, primary) {
13779
14238
  }
13780
14239
  return out;
13781
14240
  }
13782
- function buildIdentity(hosting, env) {
14241
+ function buildIdentity(hosting, grantKeys, env) {
13783
14242
  const { resolveToken, mintGrant } = hosting;
13784
- if (!resolveToken && !mintGrant)
14243
+ if (!resolveToken && !mintGrant && !grantKeys)
13785
14244
  return;
13786
14245
  return new IdentityImpl({
13787
14246
  resolveToken,
13788
14247
  mintGrant,
14248
+ grantKeys: grantKeys ?? undefined,
13789
14249
  introspectPrincipals: resolveToken ? resolveIntrospectPrincipals(hosting.introspectPrincipals, env) : undefined,
13790
14250
  maxAuthAge: hosting.maxAuthAge
13791
14251
  });
13792
14252
  }
14253
+ function buildAttachTickets(hosting, grantKeys, config, env) {
14254
+ if (!config || !config.signingKeyConfigured || !config.signingKey)
14255
+ return;
14256
+ if (!grantKeys && !hosting.mintGrant)
14257
+ return;
14258
+ return buildAttachTicketsProtocol({
14259
+ signingKey: config.signingKey,
14260
+ catalogInterface: config.catalogInterface,
14261
+ maxTtlSeconds: resolveTicketMaxTtl(grantKeys, env)
14262
+ });
14263
+ }
13793
14264
  function resolveIntrospectPrincipals(explicit, env) {
13794
14265
  let principals;
13795
14266
  if (explicit !== undefined) {
@@ -13806,10 +14277,31 @@ function resolveIntrospectPrincipals(explicit, env) {
13806
14277
  }
13807
14278
  return principals;
13808
14279
  }
14280
+ function processEnv() {
14281
+ return globalThis.process?.env;
14282
+ }
14283
+ function grantKeysFromArgv(argv, env = processEnv()) {
14284
+ const keys = [];
14285
+ for (let i = 0;i < argv.length; i++) {
14286
+ const a = argv[i];
14287
+ if (a === "--grant-key") {
14288
+ if (i + 1 >= argv.length)
14289
+ throw new Error("--grant-key requires a value");
14290
+ keys.push(argv[++i]);
14291
+ } else if (a.startsWith("--grant-key=")) {
14292
+ keys.push(a.slice("--grant-key=".length));
14293
+ }
14294
+ }
14295
+ if (keys.length === 0)
14296
+ return;
14297
+ const fromEnv = GrantKeys.fromEnv({ ...env ?? {}, VGI_RPC_GRANT_KEYS: keys.join(",") });
14298
+ return fromEnv ?? undefined;
14299
+ }
13809
14300
 
13810
14301
  // src/index.core.ts
13811
14302
  import {
13812
14303
  AuthUnavailableError,
14304
+ GrantKeys as GrantKeys2,
13813
14305
  GrantRefusedError,
13814
14306
  IdentityUnavailableError,
13815
14307
  StatusError
@@ -13916,6 +14408,13 @@ class Worker {
13916
14408
  }
13917
14409
  run(argv = process.argv.slice(2)) {
13918
14410
  debug(() => `[worker] starting, pid=${process.pid}`);
14411
+ checkReservedAttachOptions(this._catalogInterface).then(() => this._serve(argv), (err) => {
14412
+ process.stderr.write(`Worker init error: ${err.message}
14413
+ `);
14414
+ process.exit(1);
14415
+ });
14416
+ }
14417
+ _serve(argv) {
13919
14418
  try {
13920
14419
  const protocol = this.buildProtocol();
13921
14420
  debug(() => `[worker] protocol built`);
@@ -14000,9 +14499,17 @@ ${err.stack}
14000
14499
  }
14001
14500
  }
14002
14501
  export {
14502
+ ATTACH_TICKETS_PROTOCOL_NAME,
14503
+ ATTACH_TICKETS_PROTOCOL_VERSION,
14504
+ ATTACH_TICKET_OPTION,
14505
+ ATTACH_TICKET_PREFIX,
14506
+ ATTACH_TICKET_SCHEMA,
14003
14507
  ArgumentMonotonicity,
14004
14508
  ArgumentValidationError,
14005
14509
  Arguments,
14510
+ AttachTicketExpiredError,
14511
+ AttachTicketInvalidError,
14512
+ AttachTicketRequestError,
14006
14513
  AuthContext,
14007
14514
  AuthUnavailableError,
14008
14515
  BindResultSchema,
@@ -14042,6 +14549,7 @@ export {
14042
14549
  FunctionStorageSqlite,
14043
14550
  FunctionType,
14044
14551
  GROUP_COLUMN_NAME,
14552
+ GrantKeys2 as GrantKeys,
14045
14553
  GrantRefusedError,
14046
14554
  INTROSPECT_PRINCIPALS_ENV,
14047
14555
  IdentityUnavailableError,
@@ -14054,9 +14562,13 @@ export {
14054
14562
  PARENT_ROW_METADATA_KEY,
14055
14563
  PushdownFilters,
14056
14564
  READ_ONLY_ITEM_ATTACH_ID,
14565
+ RESERVED_ATTACH_OPTION,
14057
14566
  ReadOnlyCatalogInterface,
14567
+ ReservedAttachOptionError,
14058
14568
  RowCountMismatchError,
14569
+ SEAL_ATTACH_REQUEST_SCHEMA,
14059
14570
  ScanFunctionResultSchema,
14571
+ SealAttachDeniedError,
14060
14572
  StatusError,
14061
14573
  TableInOutPhase,
14062
14574
  TimeUnit2 as TimeUnit,
@@ -14088,6 +14600,7 @@ export {
14088
14600
  asTimestampSeconds,
14089
14601
  asUint64,
14090
14602
  asUnscaledDecimal,
14603
+ attachTicketAad,
14091
14604
  backend,
14092
14605
  batchFromColumns,
14093
14606
  batchFromRows,
@@ -14163,6 +14676,7 @@ export {
14163
14676
  fromBrandedBigInt,
14164
14677
  fromBrandedNumber,
14165
14678
  storage as functionStorage,
14679
+ grantKeysFromArgv,
14166
14680
  httpConnect,
14167
14681
  int3 as int,
14168
14682
  int162 as int16,
@@ -14198,12 +14712,15 @@ export {
14198
14712
  macroParameterDocsFromSchema,
14199
14713
  map2 as map,
14200
14714
  metadatasToArrow,
14715
+ mintAttachTicket,
14201
14716
  normalizeSchemaPath,
14202
14717
  nullType2 as nullType,
14718
+ openAttachTicket,
14203
14719
  parentRowsMetadata,
14204
14720
  projectBatch,
14205
14721
  projectSchema,
14206
14722
  readCanonicalValue,
14723
+ redeemAttachTicket,
14207
14724
  reprPushedFilters,
14208
14725
  resolveMetadata,
14209
14726
  resolveStorageFromEnv,
@@ -14250,4 +14767,4 @@ export {
14250
14767
  utf82 as utf8
14251
14768
  };
14252
14769
 
14253
- //# debugId=03676B1C4ED9A21664756E2164756E21
14770
+ //# debugId=121A6A9C9B24594A64756E2164756E21