@query-farm/vgi 0.43.0 → 0.45.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.
Files changed (73) hide show
  1. package/README.md +5 -2
  2. package/dist/arrow/impl-arrowjs/index.d.ts +1 -1
  3. package/dist/arrow/impl-arrowjs/ipc.d.ts +6 -0
  4. package/dist/arrow/impl-flechette/build.d.ts +2 -2
  5. package/dist/arrow/impl-flechette/canonical.d.ts +1 -1
  6. package/dist/arrow/impl-flechette/index.d.ts +1 -1
  7. package/dist/arrow/impl-flechette/ipc.d.ts +6 -0
  8. package/dist/arrow/index.d.ts +1 -1
  9. package/dist/attach-ticket.d.ts +18 -7
  10. package/dist/catalog/contents-codec.d.ts +7 -0
  11. package/dist/catalog/contents-digest.d.ts +2 -1
  12. package/dist/catalog/interface.d.ts +3 -0
  13. package/dist/catalog/publication-envelope.d.ts +1 -0
  14. package/dist/catalog/publication.d.ts +142 -0
  15. package/dist/catalog/s3-publication.d.ts +38 -0
  16. package/dist/client-entry.js +349 -114
  17. package/dist/client-entry.js.map +16 -14
  18. package/dist/codec/asd.d.ts +7 -1
  19. package/dist/codec/conform.d.ts +51 -0
  20. package/dist/errors.d.ts +5 -1
  21. package/dist/generated/vgi-client.d.ts +6 -14
  22. package/dist/generated/vgi-protocol-schemas.d.ts +2 -0
  23. package/dist/generated/vgi-protocol-types.d.ts +26 -3
  24. package/dist/generated/vgi-service.d.ts +3 -3
  25. package/dist/index.core.d.ts +1 -1
  26. package/dist/index.d.ts +4 -0
  27. package/dist/index.js +955 -118
  28. package/dist/index.js.map +33 -28
  29. package/dist/protocol/dispatch.d.ts +1 -1
  30. package/dist/protocol/handlers/catalog/contents.d.ts +4 -4
  31. package/dist/protocol/handlers/shared.d.ts +2 -1
  32. package/dist/protocol/serializers/shared.d.ts +2 -1
  33. package/dist/rpc-server.d.ts +2 -2
  34. package/dist/serve-entry.js +867 -165
  35. package/dist/serve-entry.js.map +26 -22
  36. package/dist/worker-cf-entry.js +825 -114
  37. package/dist/worker-cf-entry.js.map +31 -27
  38. package/package.json +3 -3
  39. package/src/arrow/impl-arrowjs/index.ts +1 -0
  40. package/src/arrow/impl-arrowjs/ipc.ts +23 -0
  41. package/src/arrow/impl-flechette/build.ts +4 -2
  42. package/src/arrow/impl-flechette/canonical.ts +7 -2
  43. package/src/arrow/impl-flechette/index.ts +1 -0
  44. package/src/arrow/impl-flechette/ipc.ts +19 -0
  45. package/src/arrow/index.ts +1 -1
  46. package/src/attach-ticket.ts +41 -13
  47. package/src/catalog/composite.ts +2 -1
  48. package/src/catalog/contents-codec.ts +77 -0
  49. package/src/catalog/contents-digest.ts +20 -17
  50. package/src/catalog/interface.ts +8 -4
  51. package/src/catalog/publication-envelope.ts +62 -0
  52. package/src/catalog/publication.ts +290 -0
  53. package/src/catalog/read-only.ts +8 -8
  54. package/src/catalog/s3-publication.ts +81 -0
  55. package/src/client/client.ts +15 -24
  56. package/src/codec/asd.ts +45 -3
  57. package/src/codec/conform.ts +194 -0
  58. package/src/errors.ts +27 -7
  59. package/src/functions/registry.ts +3 -2
  60. package/src/generated/vgi-client.ts +7 -16
  61. package/src/generated/vgi-protocol-schemas.ts +13 -6
  62. package/src/generated/vgi-protocol-types.ts +39 -5
  63. package/src/generated/vgi-service.ts +4 -3
  64. package/src/http/fetch.ts +1 -1
  65. package/src/index.core.ts +3 -1
  66. package/src/index.ts +5 -0
  67. package/src/protocol/dispatch.ts +1 -1
  68. package/src/protocol/handlers/catalog/admin.ts +7 -4
  69. package/src/protocol/handlers/catalog/contents.ts +50 -35
  70. package/src/protocol/handlers/shared.ts +8 -2
  71. package/src/protocol/serializers/bind.ts +3 -1
  72. package/src/protocol/serializers/shared.ts +5 -2
  73. package/src/rpc-server.ts +7 -7
@@ -1,4 +1,27 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
2
25
  var __returnValue = (v) => v;
3
26
  function __exportSetter(name, newValue) {
4
27
  this[name] = __returnValue.bind(null, newValue);
@@ -1706,7 +1729,26 @@ function deserializeBatch(bytes) {
1706
1729
  }
1707
1730
  return batches[0];
1708
1731
  }
1732
+ function deserializeBatches(bytes) {
1733
+ return [...RecordBatchReader.from(bytes)];
1734
+ }
1735
+ function serializeBatches(batches, schema) {
1736
+ const writer = new RecordBatchStreamWriter;
1737
+ writer.reset(undefined, schema);
1738
+ for (const batch of batches)
1739
+ writer._writeRecordBatch(batch);
1740
+ writer.close();
1741
+ return writer.toUint8Array(true);
1742
+ }
1743
+ function serializeCollectionRows(schema, rows, maxBatchRows) {
1744
+ const batch = batchFromRows(rows, schema);
1745
+ const batches = [];
1746
+ for (let offset = 0;offset < batch.numRows; offset += maxBatchRows)
1747
+ batches.push(batch.slice(offset, offset + maxBatchRows));
1748
+ return serializeBatches(batches, schema);
1749
+ }
1709
1750
  var init_ipc = __esm(() => {
1751
+ init_build();
1710
1752
  init_empty();
1711
1753
  });
1712
1754
 
@@ -1860,6 +1902,7 @@ __export(exports_impl_arrowjs, {
1860
1902
  decodeDictValue: () => decodeDictValue,
1861
1903
  denseUnion: () => denseUnion,
1862
1904
  deserializeBatch: () => deserializeBatch,
1905
+ deserializeBatches: () => deserializeBatches,
1863
1906
  deserializeSchema: () => deserializeSchema,
1864
1907
  dictionary: () => dictionary,
1865
1908
  duration: () => duration,
@@ -1889,6 +1932,8 @@ __export(exports_impl_arrowjs, {
1889
1932
  safeNumber: () => safeNumber,
1890
1933
  schema: () => schema,
1891
1934
  serializeBatch: () => serializeBatch,
1935
+ serializeBatches: () => serializeBatches,
1936
+ serializeCollectionRows: () => serializeCollectionRows,
1892
1937
  serializeSchema: () => serializeSchema,
1893
1938
  sparseUnion: () => sparseUnion,
1894
1939
  struct: () => struct,
@@ -1978,6 +2023,11 @@ var init_arrow = __esm(() => {
1978
2023
  });
1979
2024
 
1980
2025
  // src/functions/storage-cf-do.ts
2026
+ var exports_storage_cf_do = {};
2027
+ __export(exports_storage_cf_do, {
2028
+ FunctionStorageCfDo: () => FunctionStorageCfDo
2029
+ });
2030
+
1981
2031
  class FunctionStorageCfDo {
1982
2032
  _baseUrl;
1983
2033
  _token;
@@ -2423,7 +2473,7 @@ function resolveStorageFromEnv() {
2423
2473
  return new FunctionStorageSqlite;
2424
2474
  }
2425
2475
  if (backend === "cloudflare-do") {
2426
- init_storage_cf_do();
2476
+ const { FunctionStorageCfDo } = (init_storage_cf_do(), __toCommonJS(exports_storage_cf_do));
2427
2477
  return FunctionStorageCfDo.fromEnv();
2428
2478
  }
2429
2479
  throw new Error(`Unknown VGI_WORKER_SHARED_STORAGE backend: '${backend}'. Supported: 'memory', 'sqlite', 'cloudflare-do'.`);
@@ -4138,6 +4188,137 @@ var VGI_RANGE_KEY = "vgi_range";
4138
4188
  var VGI_PATTERN_KEY = "vgi_pattern";
4139
4189
  var DEFAULT_MAX_WORKERS = 99999;
4140
4190
 
4191
+ // src/codec/conform.ts
4192
+ init_arrow();
4193
+ var OPTIONAL_ITEM_FIELDS = new Set(["argument_names"]);
4194
+ function children(type) {
4195
+ return type.children ?? [];
4196
+ }
4197
+ function mapValueType(type) {
4198
+ const entries = children(type)[0].type;
4199
+ return children(entries)[1].type;
4200
+ }
4201
+ function mapPairs(raw) {
4202
+ if (Array.isArray(raw))
4203
+ return raw.map((e) => Array.isArray(e) ? [e[0], e[1]] : [e?.key, e?.value]);
4204
+ if (raw instanceof Map)
4205
+ return Array.from(raw.entries());
4206
+ if (typeof raw[Symbol.iterator] === "function")
4207
+ return Array.from(raw);
4208
+ return Object.entries(raw);
4209
+ }
4210
+ function zeroValue(type) {
4211
+ if (isDictionary(type))
4212
+ return zeroValue(type.dictionary);
4213
+ if (isUtf8(type))
4214
+ return "";
4215
+ if (isBinary(type))
4216
+ return new Uint8Array(0);
4217
+ if (isBool(type))
4218
+ return false;
4219
+ if (isInt(type))
4220
+ return type.bitWidth === 64 ? 0n : 0;
4221
+ if (isFloat(type))
4222
+ return 0;
4223
+ if (isList(type) || isMap(type))
4224
+ return [];
4225
+ if (isStruct(type)) {
4226
+ const out = {};
4227
+ for (const c of children(type))
4228
+ out[c.name] = c.nullable ? null : conformValue(c.type, undefined, false, c.name);
4229
+ return out;
4230
+ }
4231
+ return null;
4232
+ }
4233
+ var HAS_CONTAINER = new WeakMap;
4234
+ function hasContainer(type) {
4235
+ const cached = HAS_CONTAINER.get(type);
4236
+ if (cached !== undefined)
4237
+ return cached;
4238
+ let has = isList(type) || isMap(type);
4239
+ if (!has && isStruct(type))
4240
+ has = children(type).some((c) => hasContainer(c.type));
4241
+ HAS_CONTAINER.set(type, has);
4242
+ return has;
4243
+ }
4244
+ function conformValue(type, value, nullable, name) {
4245
+ if (value == null) {
4246
+ if (nullable)
4247
+ return value ?? null;
4248
+ if (isList(type) || isMap(type))
4249
+ return [];
4250
+ return value;
4251
+ }
4252
+ if (!hasContainer(type))
4253
+ return value;
4254
+ if (isList(type)) {
4255
+ const itemType = children(type)[0].type;
4256
+ const itemsNullable = OPTIONAL_ITEM_FIELDS.has(name);
4257
+ const items = Array.isArray(value) ? value : Array.from(value);
4258
+ let changed = !Array.isArray(value);
4259
+ const out = items.map((item) => {
4260
+ const next = item == null && !itemsNullable ? zeroValue(itemType) : conformValue(itemType, item, true, name);
4261
+ if (next !== item)
4262
+ changed = true;
4263
+ return next;
4264
+ });
4265
+ return changed ? out : value;
4266
+ }
4267
+ if (isMap(type)) {
4268
+ const valueType = mapValueType(type);
4269
+ const pairs = mapPairs(value);
4270
+ let changed = false;
4271
+ const out = pairs.map(([k, v]) => {
4272
+ const next = v == null ? zeroValue(valueType) : conformValue(valueType, v, true, name);
4273
+ if (next !== v)
4274
+ changed = true;
4275
+ return [k, next];
4276
+ });
4277
+ return changed ? out : value;
4278
+ }
4279
+ if (isStruct(type)) {
4280
+ let out = null;
4281
+ for (const c of children(type)) {
4282
+ const v = value[c.name];
4283
+ const next = conformValue(c.type, v, c.nullable, c.name);
4284
+ if (next !== v) {
4285
+ (out ??= { ...value })[c.name] = next;
4286
+ }
4287
+ }
4288
+ return out ?? value;
4289
+ }
4290
+ return value;
4291
+ }
4292
+ function conformRecord(schema, obj) {
4293
+ let out = null;
4294
+ for (const f of schema.fields) {
4295
+ const v = obj[f.name];
4296
+ const next = conformValue(f.type, v, f.nullable, f.name);
4297
+ if (next !== v) {
4298
+ (out ??= { ...obj })[f.name] = next;
4299
+ }
4300
+ }
4301
+ return out ?? obj;
4302
+ }
4303
+ function conformColumns(schema, columns) {
4304
+ let out = null;
4305
+ for (const f of schema.fields) {
4306
+ const col = columns[f.name];
4307
+ const rows = col ?? [undefined];
4308
+ let changed = col === undefined;
4309
+ const next = rows.map((v) => {
4310
+ const c = conformValue(f.type, v, f.nullable, f.name);
4311
+ if (c !== v)
4312
+ changed = true;
4313
+ return c;
4314
+ });
4315
+ if (changed) {
4316
+ (out ??= { ...columns })[f.name] = next;
4317
+ }
4318
+ }
4319
+ return out ?? columns;
4320
+ }
4321
+
4141
4322
  // src/protocol/serializers/shared.ts
4142
4323
  function toUint8Array2(val) {
4143
4324
  if (typeof val === "string")
@@ -4682,7 +4863,7 @@ import {
4682
4863
  Protocol
4683
4864
  } from "@query-farm/vgi-rpc";
4684
4865
  var VGI_PROTOCOL_NAME = "vgi.v2";
4685
- var VGI_PROTOCOL_VERSION = "2.1.0";
4866
+ var VGI_PROTOCOL_VERSION = "2.2.0";
4686
4867
  function exchangeStream(callbacks) {
4687
4868
  return { kind: "exchange", ...callbacks };
4688
4869
  }
@@ -5941,6 +6122,7 @@ function serializeColumnStatistics(stats, _cacheMaxAgeSeconds) {
5941
6122
 
5942
6123
  // src/generated/vgi-protocol-schemas.ts
5943
6124
  init_arrow();
6125
+ var VGI_CATALOG_CONTRACT_HASH = "121e8fe1c074bce00a6d0fcec49d7a90f05e45498cd9ca8a5a3b4a9ae2377a2d";
5944
6126
  var CatalogInfoSchema = schema2([
5945
6127
  field2("name", utf82(), false),
5946
6128
  field2("implementation_version", utf82(), true),
@@ -5952,7 +6134,6 @@ var CatalogInfoSchema = schema2([
5952
6134
  var SchemaInfoSchema = schema2([
5953
6135
  field2("comment", utf82(), true),
5954
6136
  field2("tags", map2(field2("key", utf82(), false), field2("value", utf82(), true), false), false),
5955
- field2("attach_opaque_data", binary2(), false),
5956
6137
  field2("path", list2(field2("item", utf82(), true)), false),
5957
6138
  field2("estimated_object_count", map2(field2("key", utf82(), false), field2("value", int642(), true), false), true)
5958
6139
  ]);
@@ -5993,9 +6174,9 @@ var FunctionInfoSchema = schema2([
5993
6174
  field2("name", utf82(), false),
5994
6175
  field2("schema_path", list2(field2("item", utf82(), true)), false),
5995
6176
  field2("function_type", dictionary2(utf82(), int162()), false),
5996
- field2("arguments", binary2(), false),
5997
- field2("output_schema", binary2(), false),
5998
- field2("parameter_default_values", binary2(), true),
6177
+ field2("arguments", dictionary2(binary2(), int322()), false),
6178
+ field2("output_schema", dictionary2(binary2(), int322()), false),
6179
+ field2("parameter_default_values", dictionary2(binary2(), int322()), true),
5999
6180
  field2("stability", dictionary2(utf82(), int162()), true),
6000
6181
  field2("null_handling", dictionary2(utf82(), int162()), true),
6001
6182
  field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
@@ -6456,7 +6637,12 @@ var CatalogContentsResultSchema = schema2([
6456
6637
  field2("catalog_version", int642(), false),
6457
6638
  field2("etag", utf82(), true),
6458
6639
  field2("not_modified", bool2(), false),
6459
- field2("schemas", list2(field2("item", struct2([field2("path", list2(field2("item", utf82(), true)), false), field2("schema", binary2(), false), field2("tables", list2(field2("item", binary2(), true)), false), field2("views", list2(field2("item", binary2(), true)), false), field2("scalar_functions", list2(field2("item", binary2(), true)), false), field2("aggregate_functions", list2(field2("item", binary2(), true)), false), field2("table_functions", list2(field2("item", binary2(), true)), false), field2("scalar_macros", list2(field2("item", binary2(), true)), false), field2("table_macros", list2(field2("item", binary2(), true)), false), field2("indexes", list2(field2("item", binary2(), true)), false)]), true)), false)
6640
+ field2("schemas", binary2(), true),
6641
+ field2("tables", binary2(), true),
6642
+ field2("views", binary2(), true),
6643
+ field2("functions", binary2(), true),
6644
+ field2("macros", binary2(), true),
6645
+ field2("indexes", binary2(), true)
6460
6646
  ]);
6461
6647
  var CatalogCopyFromFormatsResultSchema = schema2([
6462
6648
  field2("items", list2(field2("item", binary2(), true)), false)
@@ -6953,7 +7139,8 @@ function normalizeRequestSchemaPaths(params) {
6953
7139
  }
6954
7140
  function wrapResult(values, innerSchema) {
6955
7141
  const a = innerSchema;
6956
- const batch = batchFromColumns(Object.fromEntries(a.fields.map((f) => [f.name, [values[f.name] ?? null]])), a);
7142
+ const row = conformRecord(a, values);
7143
+ const batch = batchFromColumns(Object.fromEntries(a.fields.map((f) => [f.name, [row[f.name] ?? null]])), a);
6957
7144
  return { result: serializeBatch(batch) };
6958
7145
  }
6959
7146
  function overloadContext(req, catalogInterface) {
@@ -6979,9 +7166,12 @@ init_arrow();
6979
7166
 
6980
7167
  // src/errors.ts
6981
7168
  class VgiError extends Error {
6982
- constructor(message) {
7169
+ errorCode;
7170
+ constructor(message, code) {
6983
7171
  super(message);
6984
7172
  this.name = "VgiError";
7173
+ if (code !== undefined)
7174
+ this.errorCode = code;
6985
7175
  }
6986
7176
  }
6987
7177
 
@@ -6994,27 +7184,27 @@ class RowCountMismatchError extends VgiError {
6994
7184
 
6995
7185
  class FunctionNotFoundError extends VgiError {
6996
7186
  constructor(name, available) {
6997
- super(`Unknown function '${name}'`);
7187
+ super(`Unknown function '${name}'`, "NOT_FOUND");
6998
7188
  this.name = "FunctionNotFoundError";
6999
7189
  }
7000
7190
  }
7001
7191
 
7002
7192
  class CatalogReadOnlyError extends VgiError {
7003
7193
  constructor(operation) {
7004
- super(`catalog is read-only: ${operation} is not supported`);
7194
+ super(`catalog is read-only: ${operation} is not supported`, "FAILED_PRECONDITION");
7005
7195
  this.name = "CatalogReadOnlyError";
7006
7196
  }
7007
7197
  }
7008
7198
  class ArgumentValidationError extends VgiError {
7009
7199
  constructor(message) {
7010
- super(message);
7200
+ super(message, "INVALID_ARGUMENT");
7011
7201
  this.name = "ArgumentValidationError";
7012
7202
  }
7013
7203
  }
7014
7204
 
7015
7205
  class NoCatalogError extends VgiError {
7016
7206
  constructor() {
7017
- super("No catalog is configured for this worker");
7207
+ super("No catalog is configured for this worker", "UNIMPLEMENTED");
7018
7208
  this.name = "NoCatalogError";
7019
7209
  }
7020
7210
  }
@@ -9111,7 +9301,7 @@ function hex(buf) {
9111
9301
  // src/codec/asd.ts
9112
9302
  init_arrow();
9113
9303
  function encodeASD(schema, obj) {
9114
- return serializeBatch(batchFromRows([sortMapsForSchema(schema, obj)], schema));
9304
+ return serializeBatch(batchFromRows([sortMapsForSchema(schema, conformRecord(schema, obj))], schema));
9115
9305
  }
9116
9306
  function compareCodePoints(a, b) {
9117
9307
  const n = Math.min(a.length, b.length);
@@ -9128,7 +9318,7 @@ function compareCodePoints(a, b) {
9128
9318
  }
9129
9319
  return a.length - b.length;
9130
9320
  }
9131
- function mapPairs(raw) {
9321
+ function mapPairs2(raw) {
9132
9322
  if (Array.isArray(raw))
9133
9323
  return raw.map((e) => Array.isArray(e) ? [e[0], e[1]] : [e?.key, e?.value]);
9134
9324
  if (raw instanceof Map)
@@ -9163,7 +9353,7 @@ function sortMapsForType(type, value) {
9163
9353
  if (isMap(type)) {
9164
9354
  const entries = type.children[0].type;
9165
9355
  const valueType = entries.children[1].type;
9166
- return mapPairs(value).map(([k, v]) => [k, sortMapsForType(valueType, v)]).sort((x, y) => compareKeys(x[0], y[0]));
9356
+ return mapPairs2(value).map(([k, v]) => [k, sortMapsForType(valueType, v)]).sort((x, y) => compareKeys(x[0], y[0]));
9167
9357
  }
9168
9358
  if (isList(type)) {
9169
9359
  const child = type.children[0].type;
@@ -9190,6 +9380,109 @@ function sortMapsForSchema(schema, obj) {
9190
9380
  }
9191
9381
  return out ?? obj;
9192
9382
  }
9383
+ function normalizeValue(raw, type) {
9384
+ if (raw == null)
9385
+ return null;
9386
+ if (isList(type)) {
9387
+ const childType = type.children[0].type;
9388
+ const out = [];
9389
+ for (const item of raw)
9390
+ out.push(normalizeValue(item, childType));
9391
+ return out;
9392
+ }
9393
+ if (isMap(type)) {
9394
+ const entries = type.children[0].type;
9395
+ const valueType = entries.children[1].type;
9396
+ const out = {};
9397
+ const put = (k, v) => {
9398
+ out[String(k)] = normalizeValue(v, valueType);
9399
+ };
9400
+ if (raw[Symbol.iterator]) {
9401
+ for (const entry of raw) {
9402
+ if (Array.isArray(entry)) {
9403
+ put(entry[0], entry[1]);
9404
+ } else if (entry && typeof entry === "object") {
9405
+ put(entry.key ?? entry[0], entry.value ?? entry[1]);
9406
+ }
9407
+ }
9408
+ } else if (typeof raw === "object") {
9409
+ for (const [k, v] of Object.entries(raw))
9410
+ put(k, v);
9411
+ }
9412
+ return out;
9413
+ }
9414
+ if (isStruct(type)) {
9415
+ const childFields = type.children;
9416
+ const out = {};
9417
+ for (const cf of childFields) {
9418
+ out[cf.name] = normalizeValue(raw[cf.name], cf.type);
9419
+ }
9420
+ return out;
9421
+ }
9422
+ if (isDictionary(type)) {
9423
+ return normalizeValue(raw, type.dictionary);
9424
+ }
9425
+ if (isBinary(type)) {
9426
+ return toUint8Array3(raw);
9427
+ }
9428
+ if (isInt(type) && type.bitWidth === 64) {
9429
+ if (typeof raw === "bigint") {
9430
+ if (raw >= BigInt(Number.MIN_SAFE_INTEGER) && raw <= BigInt(Number.MAX_SAFE_INTEGER)) {
9431
+ return Number(raw);
9432
+ }
9433
+ return raw;
9434
+ }
9435
+ return raw;
9436
+ }
9437
+ if (isBool(type)) {
9438
+ return Boolean(raw);
9439
+ }
9440
+ return raw;
9441
+ }
9442
+ function toUint8Array3(val) {
9443
+ if (val instanceof Uint8Array)
9444
+ return val;
9445
+ if (val instanceof ArrayBuffer)
9446
+ return new Uint8Array(val);
9447
+ if (val && val.buffer instanceof ArrayBuffer) {
9448
+ return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
9449
+ }
9450
+ return new Uint8Array(0);
9451
+ }
9452
+ function encodeASDCollection(schema, records) {
9453
+ if (records.length === 0)
9454
+ return null;
9455
+ return serializeCollectionRows(schema, records.map((record) => sortMapsForSchema(schema, conformRecord(schema, record))), 1024);
9456
+ }
9457
+ function decodeASDCollection(schema, bytes) {
9458
+ if (bytes == null)
9459
+ return [];
9460
+ const output = [];
9461
+ const batches = deserializeBatches(bytes);
9462
+ const validateSchema = (actualSchema) => {
9463
+ if (actualSchema.fields.length !== schema.fields.length || schema.fields.some((field, i) => {
9464
+ const actual = actualSchema.fields[i];
9465
+ return actual.name !== field.name || actual.nullable !== field.nullable || typeSignature(actual.type) !== typeSignature(field.type);
9466
+ }))
9467
+ throw new Error("catalog collection has an incompatible metadata schema");
9468
+ };
9469
+ if (batches.length === 0)
9470
+ validateSchema(deserializeSchema(bytes));
9471
+ for (const batch of batches) {
9472
+ validateSchema(batch.schema);
9473
+ for (let row = 0;row < batch.numRows; row++) {
9474
+ const item = {};
9475
+ for (const field of schema.fields) {
9476
+ const value = batch.getChild(field.name)?.get(row);
9477
+ if (value == null && !field.nullable)
9478
+ throw new Error(`catalog collection has null ${field.name}`);
9479
+ item[field.name] = normalizeValue(value, field.type);
9480
+ }
9481
+ output.push(item);
9482
+ }
9483
+ }
9484
+ return output;
9485
+ }
9193
9486
 
9194
9487
  // src/generated/vgi-client.ts
9195
9488
  var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
@@ -9223,68 +9516,111 @@ function buildCatalogAttachResult(init) {
9223
9516
  supports_catalog_contents: init.supports_catalog_contents ?? false
9224
9517
  };
9225
9518
  }
9226
- function buildSchemaContents(init) {
9227
- return {
9228
- path: init.path,
9229
- schema: init.schema,
9230
- tables: init.tables ?? [],
9231
- views: init.views ?? [],
9232
- scalar_functions: init.scalar_functions ?? [],
9233
- aggregate_functions: init.aggregate_functions ?? [],
9234
- table_functions: init.table_functions ?? [],
9235
- scalar_macros: init.scalar_macros ?? [],
9236
- table_macros: init.table_macros ?? [],
9237
- indexes: init.indexes ?? []
9238
- };
9239
- }
9240
9519
  function buildCatalogContentsResponse(init) {
9241
9520
  return {
9242
9521
  catalog_version: init.catalog_version,
9243
9522
  etag: init.etag ?? null,
9244
9523
  not_modified: init.not_modified ?? false,
9245
- schemas: init.schemas ?? []
9524
+ schemas: init.schemas ?? null,
9525
+ tables: init.tables ?? null,
9526
+ views: init.views ?? null,
9527
+ functions: init.functions ?? null,
9528
+ macros: init.macros ?? null,
9529
+ indexes: init.indexes ?? null
9246
9530
  };
9247
9531
  }
9248
9532
 
9249
- // src/catalog/item-encoding.ts
9250
- var ENCODED = new WeakMap;
9251
- function freezeCatalogItem(item) {
9252
- deepFreeze(item);
9253
- return item;
9254
- }
9255
- function deepFreeze(value) {
9256
- if (value === null || typeof value !== "object" || Object.isFrozen(value) || ArrayBuffer.isView(value))
9257
- return;
9258
- const proto = Object.getPrototypeOf(value);
9259
- if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
9260
- return;
9261
- for (const child of Object.values(value))
9262
- deepFreeze(child);
9263
- Object.freeze(value);
9533
+ // src/protocol/handlers/catalog/contents.ts
9534
+ import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
9535
+
9536
+ // src/catalog/publication.ts
9537
+ init_arrow();
9538
+ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@query-farm/vgi-rpc";
9539
+
9540
+ // src/catalog/contents-codec.ts
9541
+ var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
9542
+ var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
9543
+ function encodeCatalogStreams(inventory) {
9544
+ const streams = {
9545
+ schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
9546
+ tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
9547
+ views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
9548
+ functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
9549
+ macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
9550
+ indexes: encodeASDCollection(IndexInfoSchema, inventory.flatMap((s) => s.indexes))
9551
+ };
9552
+ return streams;
9264
9553
  }
9265
- function encodeFunctionInfoOnce(info) {
9266
- if (!Object.isFrozen(info))
9267
- return encodeFunctionInfo(info);
9268
- let encoded = ENCODED.get(info);
9269
- if (encoded === undefined) {
9270
- encoded = encodeFunctionInfo(info);
9271
- ENCODED.set(info, encoded);
9554
+ function decodeCatalogStreams(response, ifNoneMatch) {
9555
+ if (response.not_modified) {
9556
+ if (response.etag == null || ifNoneMatch !== undefined && response.etag !== ifNoneMatch || CATALOG_STREAM_KINDS.some((kind) => response[kind] != null)) {
9557
+ throw new Error("invalid catalog_contents not_modified response");
9558
+ }
9559
+ return [];
9272
9560
  }
9273
- return encoded;
9561
+ const infos = decodeASDCollection(SchemaInfoSchema, response.schemas);
9562
+ const schemas = [];
9563
+ const index = new Map;
9564
+ for (const schema of infos) {
9565
+ if (!Array.isArray(schema.path) || schema.path.length === 0)
9566
+ throw new Error("catalog schema has an empty path");
9567
+ const key = schemaPathKey2(schema.path);
9568
+ if (index.has(key))
9569
+ throw new Error("catalog contains duplicate schema paths");
9570
+ if (schema.path.length > 1 && !index.has(schemaPathKey2(schema.path.slice(0, -1)))) {
9571
+ throw new Error("catalog schema is missing its preceding parent");
9572
+ }
9573
+ const entry = { schema, tables: [], views: [], scalar_functions: [], aggregate_functions: [], table_functions: [], scalar_macros: [], table_macros: [], indexes: [] };
9574
+ index.set(key, entry);
9575
+ schemas.push(entry);
9576
+ }
9577
+ const owner = (item) => {
9578
+ const entry = index.get(schemaPathKey2(item.schema_path));
9579
+ if (!entry)
9580
+ throw new Error("catalog object references an absent schema");
9581
+ return entry;
9582
+ };
9583
+ for (const item of decodeASDCollection(TableInfoSchema, response.tables))
9584
+ owner(item).tables.push(item);
9585
+ for (const item of decodeASDCollection(ViewInfoSchema, response.views))
9586
+ owner(item).views.push(item);
9587
+ for (const item of decodeASDCollection(FunctionInfoSchema, response.functions)) {
9588
+ const entry = owner(item);
9589
+ switch (String(item.function_type).toUpperCase()) {
9590
+ case "SCALAR":
9591
+ entry.scalar_functions.push(item);
9592
+ break;
9593
+ case "AGGREGATE":
9594
+ entry.aggregate_functions.push(item);
9595
+ break;
9596
+ case "TABLE":
9597
+ case "TABLE_BUFFERING":
9598
+ entry.table_functions.push(item);
9599
+ break;
9600
+ default:
9601
+ throw new Error(`unknown catalog function type ${item.function_type}`);
9602
+ }
9603
+ }
9604
+ for (const item of decodeASDCollection(MacroInfoSchema, response.macros)) {
9605
+ const entry = owner(item);
9606
+ switch (String(item.macro_type).toUpperCase()) {
9607
+ case "SCALAR":
9608
+ entry.scalar_macros.push(item);
9609
+ break;
9610
+ case "TABLE":
9611
+ entry.table_macros.push(item);
9612
+ break;
9613
+ default:
9614
+ throw new Error(`unknown catalog macro type ${item.macro_type}`);
9615
+ }
9616
+ }
9617
+ for (const item of decodeASDCollection(IndexInfoSchema, response.indexes))
9618
+ owner(item).indexes.push(item);
9619
+ return schemas;
9274
9620
  }
9275
9621
 
9276
9622
  // src/catalog/contents-digest.ts
9277
- var KINDS = [
9278
- "tables",
9279
- "views",
9280
- "scalar_functions",
9281
- "aggregate_functions",
9282
- "table_functions",
9283
- "scalar_macros",
9284
- "table_macros",
9285
- "indexes"
9286
- ];
9287
- async function catalogContentsDigest(schemas) {
9623
+ async function catalogContentsDigest(streams, version = 0) {
9288
9624
  const utf8 = new TextEncoder;
9289
9625
  const parts = [];
9290
9626
  let total = 0;
@@ -9304,12 +9640,23 @@ async function catalogContentsDigest(schemas) {
9304
9640
  for (const v of values)
9305
9641
  chunk(v);
9306
9642
  };
9307
- count(schemas.length);
9308
- for (const entry of schemas) {
9309
- chunks(entry.path.map((p) => utf8.encode(p)));
9310
- chunk(entry.schema);
9311
- for (const kind of KINDS)
9312
- chunks(entry[kind]);
9643
+ if (Array.isArray(streams)) {
9644
+ count(streams.length);
9645
+ for (const entry of streams) {
9646
+ chunks(entry.path.map((p) => utf8.encode(p)));
9647
+ chunk(entry.schema);
9648
+ for (const kind of ["tables", "views", "scalar_functions", "aggregate_functions", "table_functions", "scalar_macros", "table_macros", "indexes"])
9649
+ chunks(entry[kind]);
9650
+ }
9651
+ } else {
9652
+ chunk(utf8.encode("vgi.catalog-contents.2.2"));
9653
+ count(version);
9654
+ for (const kind of CATALOG_STREAM_KINDS) {
9655
+ const value = streams[kind];
9656
+ count(value == null ? 0 : 1);
9657
+ if (value != null)
9658
+ chunk(value);
9659
+ }
9313
9660
  }
9314
9661
  const buf = new Uint8Array(total);
9315
9662
  let off = 0;
@@ -9324,7 +9671,297 @@ async function catalogContentsDigest(schemas) {
9324
9671
  return hex;
9325
9672
  }
9326
9673
 
9674
+ // src/catalog/publication-envelope.ts
9675
+ function validateCatalogPublicationEnvelope(bytes) {
9676
+ try {
9677
+ const stream = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9678
+ let position = 0, messages = 0;
9679
+ while (position < bytes.length) {
9680
+ let length = stream.getInt32(position, true);
9681
+ position += 4;
9682
+ if (length === -1) {
9683
+ length = stream.getInt32(position, true);
9684
+ position += 4;
9685
+ }
9686
+ if (length === 0) {
9687
+ if (position !== bytes.length)
9688
+ throw new Error("trailing data");
9689
+ break;
9690
+ }
9691
+ if (length < 4 || length > bytes.length - position)
9692
+ throw new Error("invalid message length");
9693
+ const head = new DataView(bytes.buffer, bytes.byteOffset + position, length);
9694
+ const tableField = (table, field) => {
9695
+ const vtable = table - head.getInt32(table, true);
9696
+ const vlength = head.getUint16(vtable, true);
9697
+ if (vlength < 4 || vlength % 2 || vtable + vlength > length)
9698
+ throw new Error("invalid vtable");
9699
+ if (4 + 2 * field >= vlength)
9700
+ return null;
9701
+ const offset = head.getUint16(vtable + 4 + 2 * field, true);
9702
+ return offset === 0 ? null : table + offset;
9703
+ };
9704
+ const follow = (pointer) => pointer + head.getUint32(pointer, true);
9705
+ const root = head.getUint32(0, true);
9706
+ const typePosition = tableField(root, 1);
9707
+ const type = typePosition == null ? 0 : head.getUint8(typePosition);
9708
+ if (type !== (messages === 0 ? 1 : messages === 1 ? 3 : -1))
9709
+ throw new Error("expected one schema and one record batch");
9710
+ if (type === 3) {
9711
+ const header = tableField(root, 2);
9712
+ if (header == null)
9713
+ throw new Error("missing record header");
9714
+ const rows = tableField(follow(header), 0);
9715
+ if (rows == null || head.getBigInt64(rows, true) !== 1n)
9716
+ throw new Error("expected one response row");
9717
+ }
9718
+ const metadata = tableField(root, 4);
9719
+ if (metadata != null) {
9720
+ const vector = follow(metadata), count = head.getUint32(vector, true);
9721
+ if (count > length / 4)
9722
+ throw new Error("invalid metadata vector");
9723
+ for (let i = 0;i < count; i++) {
9724
+ const keyPointer = tableField(follow(vector + 4 + 4 * i), 0);
9725
+ if (keyPointer == null)
9726
+ continue;
9727
+ const keyStart = follow(keyPointer), keyLength = head.getUint32(keyStart, true);
9728
+ if (keyStart + 4 + keyLength > length)
9729
+ throw new Error("invalid metadata key");
9730
+ const key = new TextDecoder().decode(new Uint8Array(head.buffer, head.byteOffset + keyStart + 4, keyLength));
9731
+ if (key === "vgi_rpc.location" || key === "vgi_rpc.log_level")
9732
+ throw new Error("pointer/log metadata is not a catalog result");
9733
+ }
9734
+ }
9735
+ const bodyPosition = tableField(root, 3);
9736
+ const bodyLength = bodyPosition == null ? 0 : Number(head.getBigInt64(bodyPosition, true));
9737
+ position += length;
9738
+ if (!Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyLength > bytes.length - position)
9739
+ throw new Error("invalid body length");
9740
+ position += bodyLength;
9741
+ messages++;
9742
+ }
9743
+ if (messages !== 2)
9744
+ throw new Error("missing response batch");
9745
+ } catch (error) {
9746
+ throw new Error(`invalid published RPC envelope: ${error instanceof Error ? error.message : String(error)}`);
9747
+ }
9748
+ }
9749
+
9750
+ // src/catalog/publication.ts
9751
+ var OUTER_SCHEMA = schema2([field2("result", binary2(), false)]);
9752
+ var DEFAULT_MAX = 64 * 1024 * 1024;
9753
+ var utf83 = new TextEncoder;
9754
+ var equalBytes3 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
9755
+ async function digest(value) {
9756
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", utf83.encode(value)));
9757
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
9758
+ }
9759
+ function assertRenewedPublication(before, after) {
9760
+ const unchanged = (m) => JSON.stringify([m.key, m.formatVersion, m.protocolName, m.protocolVersion, m.contractHash, m.codecRevision, m.catalogVersion, m.etag, m.sha256, m.rawSize, m.storedSize, m.objectId, m.retainUntil, m.stable, m.validated]);
9761
+ if (unchanged(before) !== unchanged(after))
9762
+ throw new Error("renewal changed immutable catalog identity");
9763
+ }
9764
+ var manifestSame = (a, b) => a.manifestId === b.manifestId;
9765
+ class CatalogSnapshotManager {
9766
+ policy;
9767
+ cached = new Map;
9768
+ pending = new Map;
9769
+ constructor(policy) {
9770
+ this.policy = policy;
9771
+ for (const value of [policy.maxRawBytes, policy.maxStoredBytes, policy.maxCachedManifests]) {
9772
+ if (value != null && (!Number.isSafeInteger(value) || value <= 0))
9773
+ throw new Error("catalog publication limits must be positive safe integers");
9774
+ }
9775
+ if (policy.referenceGraceMs != null && (!Number.isSafeInteger(policy.referenceGraceMs) || policy.referenceGraceMs < 0))
9776
+ throw new Error("catalog publication reference grace must be a nonnegative safe integer");
9777
+ }
9778
+ usable(m) {
9779
+ const deadline = Date.now() + (this.policy.referenceGraceMs ?? 60000);
9780
+ return (m.stable || m.expiresAt != null) && (m.expiresAt == null || m.expiresAt > deadline) && (m.retainUntil == null || m.retainUntil > deadline);
9781
+ }
9782
+ async key(identity) {
9783
+ for (const value of [identity.catalogNamespace, identity.sourceRevision, identity.visibilityScope])
9784
+ if (!value)
9785
+ throw new Error("published catalogs require explicit namespace, revision and visibility scope");
9786
+ if (!Number.isSafeInteger(identity.catalogVersion))
9787
+ throw new Error("catalog version is not a safe integer");
9788
+ return digest(JSON.stringify([
9789
+ VGI_PROTOCOL_NAME,
9790
+ VGI_PROTOCOL_VERSION,
9791
+ VGI_CATALOG_CONTRACT_HASH,
9792
+ 1,
9793
+ identity.catalogNamespace,
9794
+ identity.sourceRevision,
9795
+ identity.visibilityScope,
9796
+ identity.catalogVersion,
9797
+ this.policy.repository.profile,
9798
+ this.policy.compression ?? "identity"
9799
+ ]));
9800
+ }
9801
+ remember(m) {
9802
+ this.cached.delete(m.key);
9803
+ this.cached.set(m.key, Object.freeze({ ...m }));
9804
+ while (this.cached.size > (this.policy.maxCachedManifests ?? 128))
9805
+ this.cached.delete(this.cached.keys().next().value);
9806
+ }
9807
+ async invalidate(key) {
9808
+ await this.pending.get(key)?.catch(() => {
9809
+ return;
9810
+ });
9811
+ const m = this.cached.get(key) ?? await this.policy.repository.lookup(key);
9812
+ this.cached.delete(key);
9813
+ if (m)
9814
+ await this.policy.repository.invalidate(key, m);
9815
+ }
9816
+ async validate(m, key, identity, expected) {
9817
+ if (m.formatVersion !== 1 || typeof m.manifestId !== "string" || !m.manifestId || m.key !== key || m.protocolName !== VGI_PROTOCOL_NAME || m.protocolVersion !== VGI_PROTOCOL_VERSION || m.contractHash !== VGI_CATALOG_CONTRACT_HASH || m.codecRevision !== 1 || m.catalogVersion !== identity.catalogVersion || m.validated !== true || typeof m.stable !== "boolean" || typeof m.etag !== "string" || !/^[0-9a-f]{64}$/.test(m.sha256) || !Number.isSafeInteger(m.rawSize) || !Number.isSafeInteger(m.storedSize) || m.rawSize <= 0 || m.storedSize <= 0 || m.rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX) || m.storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX) || !this.usable(m))
9818
+ throw new Error("invalid or expired catalog publication manifest");
9819
+ const ref = new ExternalRef(m.url, m.sha256);
9820
+ const configuredFetch = this.policy.repository.resolver.fetch ?? fetch;
9821
+ const resolved = await resolveExternalLocation(ref.pointerBatch(OUTER_SCHEMA), {
9822
+ ...this.policy.repository.resolver,
9823
+ fetch: (input, init) => configuredFetch(input, { ...init, signal: AbortSignal.any([...init?.signal ? [init.signal] : [], AbortSignal.timeout(30000)]) }),
9824
+ maxFetchBytes: Math.min(this.policy.maxStoredBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxFetchBytes ?? Infinity),
9825
+ maxDecompressedBytes: Math.min(this.policy.maxRawBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxDecompressedBytes ?? Infinity),
9826
+ validateFetchedIpc: (bytes) => {
9827
+ this.policy.repository.resolver.validateFetchedIpc?.(bytes);
9828
+ if (bytes.length !== m.rawSize)
9829
+ throw new Error("catalog publication raw size mismatch");
9830
+ validateCatalogPublicationEnvelope(bytes);
9831
+ }
9832
+ });
9833
+ if (resolved.numRows !== 1 || resolved.schema.fields.length !== 1 || resolved.schema.fields[0].name !== "result" || typeSignature(resolved.schema.fields[0].type) !== typeSignature(binary2()) || resolved.schema.fields[0].nullable)
9834
+ throw new Error("invalid published RPC envelope");
9835
+ const bytes = resolved.getChild("result")?.get(0);
9836
+ if (!(bytes instanceof Uint8Array))
9837
+ throw new Error("published catalog has no result bytes");
9838
+ const decoded = decodeASDCollection(CatalogContentsResultSchema, bytes);
9839
+ if (decoded.length !== 1)
9840
+ throw new Error("published catalog must contain exactly one response row");
9841
+ const response = decoded[0];
9842
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion || response.etag !== m.etag)
9843
+ throw new Error("published catalog version or ETag mismatch");
9844
+ decodeCatalogStreams(response);
9845
+ if (expected)
9846
+ for (const kind of CATALOG_STREAM_KINDS) {
9847
+ const a = response[kind], b = expected[kind];
9848
+ if (a == null !== (b == null) || a != null && b != null && !equalBytes3(a, b))
9849
+ throw new Error("publication readback changed catalog metadata");
9850
+ }
9851
+ }
9852
+ async import(manifest, identity) {
9853
+ const key = await this.key(identity);
9854
+ await this.validate(manifest, key, identity);
9855
+ const winner = await this.policy.repository.commitIfAbsent(manifest);
9856
+ if (!manifestSame(manifest, winner))
9857
+ await this.validate(winner, key, identity);
9858
+ this.remember(winner);
9859
+ return winner;
9860
+ }
9861
+ async warm(identity, build) {
9862
+ const key = await this.key(identity);
9863
+ const cached = this.cached.get(key);
9864
+ if (cached && this.usable(cached))
9865
+ return cached;
9866
+ const active = this.pending.get(key);
9867
+ if (active)
9868
+ return active;
9869
+ const pending = this.recoverOrPublish(key, identity, build);
9870
+ this.pending.set(key, pending);
9871
+ try {
9872
+ const m = await pending;
9873
+ this.remember(m);
9874
+ return m;
9875
+ } finally {
9876
+ if (this.pending.get(key) === pending)
9877
+ this.pending.delete(key);
9878
+ }
9879
+ }
9880
+ async recoverOrPublish(key, identity, build) {
9881
+ const repository = this.policy.repository;
9882
+ let existing = await repository.lookup(key);
9883
+ if (existing) {
9884
+ try {
9885
+ if (!this.usable(existing) && repository.renew) {
9886
+ const renewed = await repository.renew(existing);
9887
+ if (renewed) {
9888
+ assertRenewedPublication(existing, renewed);
9889
+ existing = renewed;
9890
+ }
9891
+ }
9892
+ await this.validate(existing, key, identity);
9893
+ return existing;
9894
+ } catch {
9895
+ await repository.invalidate(key, existing);
9896
+ }
9897
+ }
9898
+ const response = await build();
9899
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion)
9900
+ throw new Error("publication requires a full snapshot of the requested version");
9901
+ decodeCatalogStreams(response);
9902
+ response.etag ??= await catalogContentsDigest(response, identity.catalogVersion);
9903
+ const payload = encodeASD(CatalogContentsResultSchema, response);
9904
+ let rawSize = 0, storedSize = 0;
9905
+ const bounded = { upload: async (data, encoding) => {
9906
+ if (encoding)
9907
+ throw new Error("catalog publication uploader requires identity encoding");
9908
+ rawSize = data.byteLength;
9909
+ if (rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX))
9910
+ throw new Error("catalog publication exceeds byte limit");
9911
+ let body = data;
9912
+ const compression = this.policy.compression ?? "identity";
9913
+ if (compression !== "identity" && compression !== "gzip" && compression !== "zstd")
9914
+ throw new Error("catalog publication compression must be identity, gzip or zstd");
9915
+ if (compression === "gzip") {
9916
+ body = new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer());
9917
+ } else if (compression === "zstd") {
9918
+ const runtime = globalThis.Bun;
9919
+ if (typeof runtime?.zstdCompress === "function") {
9920
+ body = new Uint8Array(await runtime.zstdCompress(data));
9921
+ } else if (typeof process !== "undefined" && process.versions?.node) {
9922
+ const nodeZlib = "node:zlib";
9923
+ const zlib = await import(nodeZlib);
9924
+ if (typeof zlib.zstdCompressSync !== "function")
9925
+ throw new Error("zstd catalog publication requires Node >=22.15, Bun, or an encoder-capable runtime");
9926
+ body = new Uint8Array(zlib.zstdCompressSync(data));
9927
+ } else {
9928
+ throw new Error("zstd catalog publication requires an encoder-capable runtime; use gzip or identity here");
9929
+ }
9930
+ }
9931
+ storedSize = body.byteLength;
9932
+ if (storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX))
9933
+ throw new Error("catalog publication exceeds byte limit");
9934
+ return repository.storage.upload(body, compression === "identity" ? "" : compression);
9935
+ } };
9936
+ const ref = await publishExternalResult(OUTER_SCHEMA, { result: payload }, bounded, { includeSha256: true });
9937
+ const m = {
9938
+ formatVersion: 1,
9939
+ manifestId: crypto.randomUUID(),
9940
+ key,
9941
+ protocolName: VGI_PROTOCOL_NAME,
9942
+ protocolVersion: VGI_PROTOCOL_VERSION,
9943
+ contractHash: VGI_CATALOG_CONTRACT_HASH,
9944
+ codecRevision: 1,
9945
+ catalogVersion: identity.catalogVersion,
9946
+ etag: response.etag,
9947
+ sha256: ref.sha256,
9948
+ rawSize,
9949
+ storedSize,
9950
+ url: ref.url,
9951
+ validated: true,
9952
+ ...await repository.describe(ref.url)
9953
+ };
9954
+ await this.validate(m, key, identity, response);
9955
+ const winner = await repository.commitIfAbsent(m);
9956
+ if (!manifestSame(m, winner))
9957
+ await this.validate(winner, key, identity);
9958
+ return winner;
9959
+ }
9960
+ }
9961
+
9327
9962
  // src/protocol/handlers/catalog/contents.ts
9963
+ var schemaPathKey3 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
9964
+ var PUBLICATIONS = new WeakMap;
9328
9965
  var CACHE = new WeakMap;
9329
9966
  async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
9330
9967
  const result = await cat.catalogContents(attach, ifNoneMatch);
@@ -9339,39 +9976,74 @@ async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
9339
9976
  return buildCatalogContentsResponse({ catalog_version: version, etag: etag0, not_modified: true });
9340
9977
  }
9341
9978
  const infos = [...result.schemas ?? []];
9342
- const keys = infos.map((c) => schemaPathKey(c.schema.path));
9979
+ const keys = infos.map((c) => schemaPathKey3(c.schema.path));
9343
9980
  const keySet = new Set(keys);
9344
9981
  if (keySet.size !== keys.length)
9345
9982
  throw new Error("catalog_contents returned duplicate schema paths");
9346
9983
  for (const c of infos) {
9347
- if (c.schema.path.length > 1 && !keySet.has(schemaPathKey(c.schema.path.slice(0, -1)))) {
9984
+ if (c.schema.path.length > 1 && !keySet.has(schemaPathKey3(c.schema.path.slice(0, -1)))) {
9348
9985
  throw new Error(`catalog_contents returned schema path ${JSON.stringify(c.schema.path)} without its parent`);
9349
9986
  }
9350
9987
  }
9351
- const schemas = infos.sort((a, b) => a.schema.path.length - b.schema.path.length).map((c) => buildSchemaContents({
9352
- path: [...c.schema.path],
9353
- schema: encodeSchemaInfo(c.schema),
9354
- tables: c.tables.map((t) => encodeTableInfo(t)),
9355
- views: c.views.map((v) => encodeViewInfo(v)),
9356
- scalar_functions: c.scalar_functions.map((f) => encodeFunctionInfoOnce(f)),
9357
- aggregate_functions: c.aggregate_functions.map((f) => encodeFunctionInfoOnce(f)),
9358
- table_functions: c.table_functions.map((f) => encodeFunctionInfoOnce(f)),
9359
- scalar_macros: c.scalar_macros.map((m) => encodeMacroInfo(m)),
9360
- table_macros: c.table_macros.map((m) => encodeMacroInfo(m)),
9361
- indexes: c.indexes.map((i) => encodeIndexInfo(i))
9362
- }));
9988
+ const streams = encodeCatalogStreams(infos.sort((a, b) => a.schema.path.length - b.schema.path.length));
9363
9989
  let etag = etag0;
9364
9990
  if (etag === null && owner.catalogContentsEtag === "content-hash") {
9365
- etag = await catalogContentsDigest(schemas);
9991
+ etag = await catalogContentsDigest(streams, version);
9366
9992
  }
9367
9993
  if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {
9368
9994
  return buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true });
9369
9995
  }
9370
- return buildCatalogContentsResponse({ catalog_version: version, etag, schemas });
9996
+ const response = buildCatalogContentsResponse({ catalog_version: version, etag, ...streams });
9997
+ decodeCatalogStreams(response);
9998
+ return response;
9371
9999
  }
9372
- async function serveCatalogContents(cat, attach, ifNoneMatch) {
10000
+ async function serveCatalogContents(cat, attach, ifNoneMatch, callContext, sealedAttach = attach) {
9373
10001
  const owner = cat.catalogContentsOwner(attach);
9374
10002
  const version = Number(await cat.version(attach));
10003
+ const policy = owner.catalogSnapshotPolicy;
10004
+ if (policy?.delivery === "published") {
10005
+ const request = { catalog: cat, attachOpaqueData: attach, callContext, catalogVersion: version };
10006
+ const inline = (etag) => wrapResult(buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true }), CatalogContentsResultSchema);
10007
+ const cheapEtag = await policy.etag?.(request);
10008
+ if (cheapEtag != null && cheapEtag === ifNoneMatch)
10009
+ return inline(cheapEtag);
10010
+ let manager = PUBLICATIONS.get(policy);
10011
+ if (!manager) {
10012
+ manager = new CatalogSnapshotManager(policy);
10013
+ PUBLICATIONS.set(policy, manager);
10014
+ }
10015
+ const scopeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", sealedAttach));
10016
+ const attachmentScope = "attachment:" + Array.from(scopeBytes, (b) => b.toString(16).padStart(2, "0")).join("");
10017
+ const identify = async (input) => {
10018
+ const id = await policy.identity(input);
10019
+ return { ...id, visibilityScope: id.visibilityScope ?? attachmentScope };
10020
+ };
10021
+ const identity = await identify(request);
10022
+ if (identity.catalogVersion !== version)
10023
+ throw new Error("snapshot identity version differs from the attached catalog");
10024
+ const assertCurrentIdentity = async () => {
10025
+ const currentVersion = Number(await cat.version(attach));
10026
+ const current = await identify({ ...request, catalogVersion: currentVersion });
10027
+ if (currentVersion !== version || await manager.key(identity) !== await manager.key(current))
10028
+ throw new Error("catalog changed while resolving its publication");
10029
+ };
10030
+ const buildSnapshot = async (validator) => {
10031
+ const response = await buildCatalogContents(cat, owner, attach, version, validator);
10032
+ await assertCurrentIdentity();
10033
+ return response;
10034
+ };
10035
+ try {
10036
+ const manifest = await manager.warm(identity, () => buildSnapshot(null));
10037
+ await assertCurrentIdentity();
10038
+ if (manifest.etag === ifNoneMatch)
10039
+ return inline(manifest.etag);
10040
+ return new ExternalRef2(manifest.url, manifest.sha256);
10041
+ } catch (error) {
10042
+ if (policy.onPublicationFailure !== "ordinary")
10043
+ throw error;
10044
+ return wrapResult(await buildSnapshot(ifNoneMatch), CatalogContentsResultSchema);
10045
+ }
10046
+ }
9375
10047
  if (owner.catalogContentsCacheable()) {
9376
10048
  let pending = CACHE.get(owner);
9377
10049
  let snapshot = pending ? await pending.catch(() => null) : null;
@@ -9400,6 +10072,33 @@ async function serveCatalogContents(cat, attach, ifNoneMatch) {
9400
10072
  }
9401
10073
  return wrapResult(await buildCatalogContents(cat, owner, attach, version, ifNoneMatch), CatalogContentsResultSchema);
9402
10074
  }
10075
+
10076
+ // src/catalog/item-encoding.ts
10077
+ var ENCODED = new WeakMap;
10078
+ function freezeCatalogItem(item) {
10079
+ deepFreeze(item);
10080
+ return item;
10081
+ }
10082
+ function deepFreeze(value) {
10083
+ if (value === null || typeof value !== "object" || Object.isFrozen(value) || ArrayBuffer.isView(value))
10084
+ return;
10085
+ const proto = Object.getPrototypeOf(value);
10086
+ if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
10087
+ return;
10088
+ for (const child of Object.values(value))
10089
+ deepFreeze(child);
10090
+ Object.freeze(value);
10091
+ }
10092
+ function encodeFunctionInfoOnce(info) {
10093
+ if (!Object.isFrozen(info))
10094
+ return encodeFunctionInfo(info);
10095
+ let encoded = ENCODED.get(info);
10096
+ if (encoded === undefined) {
10097
+ encoded = encodeFunctionInfo(info);
10098
+ ENCODED.set(info, encoded);
10099
+ }
10100
+ return encoded;
10101
+ }
9403
10102
  // src/catalog/interface.ts
9404
10103
  var encodeCopyFromFormatInfo = (v) => encodeASD(CopyFromFormatInfoSchema, {
9405
10104
  comment: v.comment ?? null,
@@ -9421,12 +10120,12 @@ var encodeAttachCatalogInfo = (v) => encodeASD(AttachCatalogInfoSchema, {
9421
10120
  secret_ref: v.secret_ref ?? ""
9422
10121
  });
9423
10122
  function encodeScanFunctionResult(functionName, argumentsBytes, requiredExtensions = [], schemaPath = null) {
9424
- return serializeBatch(batchFromColumns({
10123
+ return serializeBatch(batchFromColumns(conformColumns(ScanFunctionResultSchema, {
9425
10124
  function_name: [functionName],
9426
10125
  arguments: [argumentsBytes],
9427
10126
  required_extensions: [requiredExtensions],
9428
10127
  schema_path: [schemaPath]
9429
- }, ScanFunctionResultSchema));
10128
+ }), ScanFunctionResultSchema));
9430
10129
  }
9431
10130
  function singleBranchResult(legacy) {
9432
10131
  return {
@@ -9441,7 +10140,7 @@ function singleBranchResult(legacy) {
9441
10140
  };
9442
10141
  }
9443
10142
  function encodeScanBranch(cols) {
9444
- return serializeBatch(batchFromColumns({
10143
+ return serializeBatch(batchFromColumns(conformColumns(ScanBranchSchema, {
9445
10144
  function_name: [cols.function_name],
9446
10145
  arguments: [cols.arguments],
9447
10146
  branch_filter: [cols.branch_filter ?? null],
@@ -9453,13 +10152,14 @@ function encodeScanBranch(cols) {
9453
10152
  format_locations: [cols.format_locations ?? null],
9454
10153
  format_options: [cols.format_options ?? null],
9455
10154
  schema_path: [cols.schema_path ?? null]
9456
- }, ScanBranchSchema));
10155
+ }), ScanBranchSchema));
9457
10156
  }
9458
10157
  function isPromise(v) {
9459
10158
  return v != null && typeof v.then === "function";
9460
10159
  }
9461
10160
 
9462
10161
  class CatalogInterface {
10162
+ catalogSnapshotPolicy = null;
9463
10163
  catalogContentsEtag = null;
9464
10164
  catalogContentsAttachIndependent = false;
9465
10165
  catalogVersionFrozen = false;
@@ -9762,7 +10462,7 @@ async function checkReservedAttachOptions(catalog) {
9762
10462
  var ATTACH_TICKET_PREFIX = "vgia1.";
9763
10463
  var ATTACH_TICKET_OPTION = RESERVED_ATTACH_OPTION;
9764
10464
  var ATTACH_TICKETS_PROTOCOL_NAME = "vgi.attach_tickets.v1";
9765
- var ATTACH_TICKETS_PROTOCOL_VERSION = "1.0.0";
10465
+ var ATTACH_TICKETS_PROTOCOL_VERSION = "2.0.0";
9766
10466
  var TICKET_ENVELOPE_VERSION = 1;
9767
10467
  var MAX_OPTIONS_BYTES = 16 * 1024;
9768
10468
  var MAX_TICKET_CHARS = 32 * 1024;
@@ -10037,8 +10737,19 @@ var SEAL_ATTACH_REQUEST_SCHEMA = schema2([
10037
10737
  ]);
10038
10738
  var ATTACH_TICKET_SCHEMA = schema2([
10039
10739
  field2("ticket", utf82(), false),
10040
- field2("expires_at", float642(), false)
10740
+ field2("expires_at", timestamp2(TimeUnit2.MICROSECOND, "UTC"), true)
10041
10741
  ]);
10742
+ function expiresAtMicros(value) {
10743
+ if (value === null)
10744
+ return null;
10745
+ const ms = value.getTime();
10746
+ if (!Number.isFinite(ms))
10747
+ throw new TypeError("AttachTicket.expires_at must be a valid Date or null");
10748
+ return BigInt(ms) * 1000n;
10749
+ }
10750
+ function encodeAttachTicket(ticket) {
10751
+ return serializeBatch(batchFromColumns({ ticket: [ticket.ticket], expires_at: [expiresAtMicros(ticket.expires_at)] }, ATTACH_TICKET_SCHEMA));
10752
+ }
10042
10753
  function resolveTicketMaxTtl(grantKeys, env) {
10043
10754
  if (grantKeys)
10044
10755
  return Math.trunc(grantKeys.maxTtlSeconds);
@@ -10125,7 +10836,7 @@ async function sealAttach2(config, request, auth) {
10125
10836
  } catch (e) {
10126
10837
  throw new AttachTicketRequestError("seal_attach request is invalid", [["request", e.message]]);
10127
10838
  }
10128
- return { ticket: token, expires_at: expiresAt === 0 ? Number.POSITIVE_INFINITY : expiresAt };
10839
+ return { ticket: token, expires_at: expiresAt === 0 ? null : new Date(expiresAt * 1000) };
10129
10840
  }
10130
10841
  function buildAttachTicketsProtocol(config) {
10131
10842
  const p = new Protocol2(ATTACH_TICKETS_PROTOCOL_NAME, { protocolVersion: ATTACH_TICKETS_PROTOCOL_VERSION });
@@ -10136,8 +10847,7 @@ function buildAttachTicketsProtocol(config) {
10136
10847
  handler: async (params, ctx) => {
10137
10848
  const request = unwrapRequest(params.request);
10138
10849
  const sealed = await sealAttach2(config, request, ctx?.auth);
10139
- const batch = batchFromColumns({ ticket: [sealed.ticket], expires_at: [sealed.expires_at] }, ATTACH_TICKET_SCHEMA);
10140
- return { result: serializeBatch(batch) };
10850
+ return { result: encodeAttachTicket(sealed) };
10141
10851
  }
10142
10852
  });
10143
10853
  return p;
@@ -10223,10 +10933,13 @@ function catalogAdminHandlers(getCatalog, signingKey) {
10223
10933
  items: schemas.map((s) => encodeSchemaInfo(s))
10224
10934
  }, CatalogSchemasResultSchema);
10225
10935
  });
10226
- const catalogContents = catalogHandler(signingKey, async (params) => {
10227
- const ifNoneMatch = params.if_none_match == null ? null : String(params.if_none_match);
10228
- return serveCatalogContents(getCatalog(), toUint8Array(params.attach_opaque_data), ifNoneMatch);
10229
- });
10936
+ const catalogContents = async (params, ctx) => {
10937
+ const sealedAttach = toUint8Array(params.attach_opaque_data).slice();
10938
+ return catalogHandler(signingKey, async (opened, context) => {
10939
+ const ifNoneMatch = opened.if_none_match == null ? null : String(opened.if_none_match);
10940
+ return serveCatalogContents(getCatalog(), toUint8Array(opened.attach_opaque_data), ifNoneMatch, context, sealedAttach);
10941
+ })(params, ctx);
10942
+ };
10230
10943
  const catalogCopyFromFormats = catalogHandler(signingKey, async (params) => {
10231
10944
  const cat = getCatalog();
10232
10945
  const formats = await cat.copyFromFormats(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -10664,7 +11377,7 @@ function validatedHostedProtocols(hosting, primary) {
10664
11377
  }
10665
11378
  const name = p.name;
10666
11379
  if (name.startsWith(RESERVED_PREFIX)) {
10667
- throw new Error(`${owner} entry ${index} is named '${name}', which claims the reserved '${RESERVED_PREFIX}' prefix. ` + "Framework protocols are not supplied through this hook: reflection is hosted automatically, and " + "vgi_rpc.Identity.v1 is enabled by supplying resolveToken and/or mintGrant.");
11380
+ throw new Error(`${owner} entry ${index} is named '${name}', which claims the reserved '${RESERVED_PREFIX}' prefix. ` + "Framework protocols are not supplied through this hook: reflection is hosted automatically, and " + "vgi_rpc.Identity.v2 is enabled by supplying resolveToken and/or mintGrant.");
10668
11381
  }
10669
11382
  if (!/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name)) {
10670
11383
  throw new Error(`${owner} entry ${index}: protocol name '${name}' is not an identifier, optionally dot-qualified ` + "(e.g. 'acme.Reports.v1').");
@@ -10714,7 +11427,7 @@ function resolveIntrospectPrincipals(explicit, env) {
10714
11427
  principals = raw.split(",").map((p) => p.trim()).filter((p) => p !== "");
10715
11428
  }
10716
11429
  if (principals.length === 0) {
10717
- throw new Error("This worker supplies resolveToken, which hosts the vgi_rpc.Identity.v1 protocol, but no " + `introspector allowlist was configured. Set ${INTROSPECT_PRINCIPALS_ENV} (comma-separated) or pass ` + `introspectPrincipals.
11430
+ throw new Error("This worker supplies resolveToken, which hosts the vgi_rpc.Identity.v2 protocol, but no " + `introspector allowlist was configured. Set ${INTROSPECT_PRINCIPALS_ENV} (comma-separated) or pass ` + `introspectPrincipals.
10718
11431
 
10719
11432
  ` + "There is no permissive default on purpose: introspection is a separate capability from " + "authentication, and allowing every authenticated caller lets any user resolve any other user's " + "credential to its owner. Remove resolveToken to leave the protocol unhosted entirely.");
10720
11433
  }
@@ -12000,7 +12713,7 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
12000
12713
  }
12001
12714
  attach(name, options, dataVersionSpec, implementationVersion) {
12002
12715
  if (!this.catalogs().includes(name)) {
12003
- throw new Error(`No worker handles catalog '${name}'`);
12716
+ throw new VgiError(`No worker handles catalog '${name}'`, "NOT_FOUND");
12004
12717
  }
12005
12718
  validateRequiredAttachOptions(name, this.attachOptionSpecs(name), options ?? {});
12006
12719
  const attachOpaqueData = new Uint8Array(16);
@@ -12050,7 +12763,6 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
12050
12763
  }
12051
12764
  schemas(attachOpaqueData, transactionOpaqueData) {
12052
12765
  return this._descriptor.schemas.map((s) => ({
12053
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
12054
12766
  path: schemaDescriptorPath(s),
12055
12767
  comment: s.comment ?? null,
12056
12768
  tags: s.tags ?? {},
@@ -12082,7 +12794,6 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
12082
12794
  if (!desc)
12083
12795
  return null;
12084
12796
  return {
12085
- attach_opaque_data: this.itemAttachId(attachOpaqueData),
12086
12797
  path: schemaDescriptorPath(desc),
12087
12798
  comment: desc.comment ?? null,
12088
12799
  tags: desc.tags ?? {},
@@ -12400,11 +13111,11 @@ class ReadOnlyCatalogInterface extends CatalogInterface {
12400
13111
  validateAtParams(atUnit, atValue);
12401
13112
  const schema = this._descriptor.schemas.find((s) => schemaPathsEqual(schemaDescriptorPath(s), schemaPath));
12402
13113
  if (!schema || !schema.tables) {
12403
- throw new Error(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`);
13114
+ throw new VgiError(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`, "NOT_FOUND");
12404
13115
  }
12405
13116
  const table = schema.tables.find((t) => t.name === name);
12406
13117
  if (!table) {
12407
- throw new Error(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`);
13118
+ throw new VgiError(`Table '${name}' not found in schema ${schemaPathDisplay(schemaPath)}`, "NOT_FOUND");
12408
13119
  }
12409
13120
  if (atUnit && !table.supportsTimeTravel) {
12410
13121
  throw new Error(`Table ${schemaPathDisplay(schemaPath)}.${name} does not support time travel queries`);
@@ -12489,12 +13200,12 @@ function resolveIndexGroups(schema, groups) {
12489
13200
  function serializeForeignKeys(fks, schemaPath) {
12490
13201
  if (!fks || fks.length === 0)
12491
13202
  return [];
12492
- return fks.map((fk) => serializeBatch(batchFromColumns({
13203
+ return fks.map((fk) => serializeBatch(batchFromColumns(conformColumns(ForeignKeyInfoSchema, {
12493
13204
  fk_columns: [fk.columns],
12494
13205
  pk_columns: [fk.referencedColumns],
12495
13206
  referenced_table: [fk.referencedTable],
12496
13207
  referenced_schema_path: [fk.referencedSchemaPath ?? schemaPath ?? ["main"]]
12497
- }, ForeignKeyInfoSchema)));
13208
+ }), ForeignKeyInfoSchema)));
12498
13209
  }
12499
13210
  function defaultToSql(value) {
12500
13211
  if (value === null || value === undefined)
@@ -12634,7 +13345,7 @@ function serializeArgsBatch(args, argSpecSchema) {
12634
13345
  }
12635
13346
  function validateAtParams(atUnit, atValue) {
12636
13347
  if (Boolean(atUnit) !== Boolean(atValue)) {
12637
- throw new Error("at_unit and at_value must both be provided or both be absent");
13348
+ throw new VgiError("at_unit and at_value must both be provided or both be absent", "INVALID_ARGUMENT");
12638
13349
  }
12639
13350
  }
12640
13351
  function inferScalarType(val) {
@@ -12732,7 +13443,7 @@ class CompositeCatalogInterface extends CatalogInterface {
12732
13443
  return result;
12733
13444
  }
12734
13445
  }
12735
- throw new Error(`No worker handles catalog '${name}'`);
13446
+ throw new VgiError(`No worker handles catalog '${name}'`, "NOT_FOUND");
12736
13447
  }
12737
13448
  async detach(attachOpaqueData) {
12738
13449
  await this._route(attachOpaqueData).detach(attachOpaqueData);
@@ -13056,7 +13767,7 @@ class FunctionRegistry {
13056
13767
  } else if (candidates && candidates.length > 0) {
13057
13768
  const schemas = this.schemasFor(name);
13058
13769
  if (schemas.length > 0) {
13059
- throw new Error(`Function '${name}' is not registered in schema ${schemaPathDisplay(schemaPath)}. ` + `It is available in: [${schemas.map(schemaPathDisplay).join(", ")}]`);
13770
+ throw new VgiError(`Function '${name}' is not registered in schema ${schemaPathDisplay(schemaPath)}. ` + `It is available in: [${schemas.map(schemaPathDisplay).join(", ")}]`, "NOT_FOUND");
13060
13771
  }
13061
13772
  }
13062
13773
  }
@@ -13277,4 +13988,4 @@ export {
13277
13988
  utf82 as utf8
13278
13989
  };
13279
13990
 
13280
- //# debugId=D9B447159663895D64756E2164756E21
13991
+ //# debugId=E0D4B40A7639489164756E2164756E21