@query-farm/vgi 0.44.0 → 0.46.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 +8 -1
  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 +2 -2
  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/impl-flechette/schema.d.ts +19 -5
  9. package/dist/arrow/index.d.ts +1 -1
  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/client.d.ts +20 -1
  17. package/dist/client-entry.js +189 -37
  18. package/dist/client-entry.js.map +15 -12
  19. package/dist/codec/asd.d.ts +4 -0
  20. package/dist/functions/continuation.d.ts +69 -0
  21. package/dist/functions/table-in-out.d.ts +51 -7
  22. package/dist/functions/types.d.ts +20 -0
  23. package/dist/generated/vgi-client.d.ts +7 -14
  24. package/dist/generated/vgi-protocol-schemas.d.ts +2 -0
  25. package/dist/generated/vgi-protocol-types.d.ts +26 -3
  26. package/dist/generated/vgi-service.d.ts +3 -3
  27. package/dist/index.core.d.ts +1 -0
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +981 -138
  30. package/dist/index.js.map +31 -25
  31. package/dist/protocol/dispatch.d.ts +1 -1
  32. package/dist/protocol/handlers/catalog/contents.d.ts +4 -4
  33. package/dist/serve-entry.js +643 -81
  34. package/dist/serve-entry.js.map +22 -18
  35. package/dist/util/parent-rows.d.ts +8 -0
  36. package/dist/worker-cf-entry.d.ts +1 -1
  37. package/dist/worker-cf-entry.js +821 -131
  38. package/dist/worker-cf-entry.js.map +29 -24
  39. package/package.json +4 -4
  40. package/src/arrow/impl-arrowjs/index.ts +1 -0
  41. package/src/arrow/impl-arrowjs/ipc.ts +23 -0
  42. package/src/arrow/impl-flechette/build.ts +4 -2
  43. package/src/arrow/impl-flechette/canonical.ts +14 -7
  44. package/src/arrow/impl-flechette/index.ts +1 -0
  45. package/src/arrow/impl-flechette/ipc.ts +19 -0
  46. package/src/arrow/index.ts +1 -1
  47. package/src/catalog/contents-codec.ts +77 -0
  48. package/src/catalog/contents-digest.ts +20 -17
  49. package/src/catalog/interface.ts +3 -0
  50. package/src/catalog/publication-envelope.ts +62 -0
  51. package/src/catalog/publication.ts +290 -0
  52. package/src/catalog/read-only.ts +6 -2
  53. package/src/catalog/s3-publication.ts +81 -0
  54. package/src/client/client.ts +82 -30
  55. package/src/codec/asd.ts +40 -1
  56. package/src/codec/conform.ts +2 -1
  57. package/src/filter-pushdown/collector.ts +17 -1
  58. package/src/functions/continuation.ts +202 -0
  59. package/src/functions/table-in-out.ts +131 -56
  60. package/src/functions/types.ts +20 -0
  61. package/src/generated/vgi-client.ts +8 -16
  62. package/src/generated/vgi-protocol-schemas.ts +14 -6
  63. package/src/generated/vgi-protocol-types.ts +39 -5
  64. package/src/generated/vgi-service.ts +4 -3
  65. package/src/index.core.ts +6 -0
  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/function.ts +12 -0
  71. package/src/protocol/state-serializer.ts +7 -1
  72. package/src/util/parent-rows.ts +41 -0
  73. package/src/worker-cf-entry.ts +3 -0
@@ -566,6 +566,7 @@ __export(exports_impl_arrowjs, {
566
566
  decodeDictValue: () => decodeDictValue,
567
567
  denseUnion: () => denseUnion,
568
568
  deserializeBatch: () => deserializeBatch,
569
+ deserializeBatches: () => deserializeBatches,
569
570
  deserializeSchema: () => deserializeSchema,
570
571
  dictionary: () => dictionary,
571
572
  duration: () => duration,
@@ -595,6 +596,8 @@ __export(exports_impl_arrowjs, {
595
596
  safeNumber: () => safeNumber,
596
597
  schema: () => schema,
597
598
  serializeBatch: () => serializeBatch,
599
+ serializeBatches: () => serializeBatches,
600
+ serializeCollectionRows: () => serializeCollectionRows,
598
601
  serializeSchema: () => serializeSchema,
599
602
  sparseUnion: () => sparseUnion,
600
603
  struct: () => struct,
@@ -2277,6 +2280,24 @@ function deserializeBatch(bytes) {
2277
2280
  }
2278
2281
  return batches[0];
2279
2282
  }
2283
+ function deserializeBatches(bytes) {
2284
+ return [...RecordBatchReader.from(bytes)];
2285
+ }
2286
+ function serializeBatches(batches, schema) {
2287
+ const writer = new RecordBatchStreamWriter;
2288
+ writer.reset(undefined, schema);
2289
+ for (const batch of batches)
2290
+ writer._writeRecordBatch(batch);
2291
+ writer.close();
2292
+ return writer.toUint8Array(true);
2293
+ }
2294
+ function serializeCollectionRows(schema, rows, maxBatchRows) {
2295
+ const batch = batchFromRows(rows, schema);
2296
+ const batches = [];
2297
+ for (let offset = 0;offset < batch.numRows; offset += maxBatchRows)
2298
+ batches.push(batch.slice(offset, offset + maxBatchRows));
2299
+ return serializeBatches(batches, schema);
2300
+ }
2280
2301
  // src/arrow/impl-arrowjs/statistics.ts
2281
2302
  import {
2282
2303
  Field as Field3,
@@ -2703,7 +2724,9 @@ function mapPairs(raw) {
2703
2724
  return Object.entries(raw);
2704
2725
  }
2705
2726
  function zeroValue(type) {
2706
- if (isUtf8(type) || isDictionary(type))
2727
+ if (isDictionary(type))
2728
+ return zeroValue(type.dictionary);
2729
+ if (isUtf8(type))
2707
2730
  return "";
2708
2731
  if (isBinary(type))
2709
2732
  return new Uint8Array(0);
@@ -3149,7 +3172,8 @@ var EXCHANGE_STATE_SCHEMA = schema2([
3149
3172
  field2("opaque_data", binary2(), true),
3150
3173
  field2("is_producer", bool2(), false),
3151
3174
  field2("user_state", binary2(), true),
3152
- field2("filter_history", binary2(), true)
3175
+ field2("filter_history", binary2(), true),
3176
+ field2("more_pending", bool2(), false)
3153
3177
  ]);
3154
3178
  var TEXT_ENCODER = new TextEncoder;
3155
3179
  var TEXT_DECODER = new TextDecoder;
@@ -3158,6 +3182,7 @@ var FLAG_PRODUCER = 1;
3158
3182
  var FLAG_OPAQUE_DATA = 2;
3159
3183
  var FLAG_USER_STATE = 4;
3160
3184
  var FLAG_FILTER_HISTORY = 8;
3185
+ var FLAG_MORE_PENDING = 16;
3161
3186
  var LIST_CHILD_NAME = "item";
3162
3187
  var emptyListElementType = () => utf82();
3163
3188
  function inferElementType(values) {
@@ -3263,7 +3288,7 @@ var arrowStateSerializer = {
3263
3288
  const opaqueData = state.opaqueData != null ? toUint8Array(state.opaqueData) : null;
3264
3289
  const userState = serializeUserState(state.userState);
3265
3290
  const filterHistory = encodeFilterHistory(state.filterHistory);
3266
- const flags = (state.isProducer ? FLAG_PRODUCER : 0) | (opaqueData ? FLAG_OPAQUE_DATA : 0) | (userState ? FLAG_USER_STATE : 0) | (filterHistory ? FLAG_FILTER_HISTORY : 0);
3291
+ const flags = (state.isProducer ? FLAG_PRODUCER : 0) | (opaqueData ? FLAG_OPAQUE_DATA : 0) | (userState ? FLAG_USER_STATE : 0) | (filterHistory ? FLAG_FILTER_HISTORY : 0) | (state.morePending ? FLAG_MORE_PENDING : 0);
3267
3292
  const chunks = [functionName, initRequest, executionId];
3268
3293
  if (opaqueData)
3269
3294
  chunks.push(opaqueData);
@@ -3324,7 +3349,8 @@ var arrowStateSerializer = {
3324
3349
  isProducer,
3325
3350
  __isProducer: isProducer,
3326
3351
  userState: deserializeUserState(userStateBytes),
3327
- filterHistory: decodeFilterHistory(filterHistoryBytes)
3352
+ filterHistory: decodeFilterHistory(filterHistoryBytes),
3353
+ morePending: (flags & FLAG_MORE_PENDING) !== 0
3328
3354
  };
3329
3355
  }
3330
3356
  };
@@ -3335,7 +3361,7 @@ import {
3335
3361
  Protocol
3336
3362
  } from "@query-farm/vgi-rpc";
3337
3363
  var VGI_PROTOCOL_NAME = "vgi.v2";
3338
- var VGI_PROTOCOL_VERSION = "2.1.0";
3364
+ var VGI_PROTOCOL_VERSION = "2.2.0";
3339
3365
  function exchangeStream(callbacks) {
3340
3366
  return { kind: "exchange", ...callbacks };
3341
3367
  }
@@ -4583,12 +4609,32 @@ function createVgiProtocol(service) {
4583
4609
  return registerVgiService(new Protocol(VGI_PROTOCOL_NAME, { protocolVersion: VGI_PROTOCOL_VERSION }), service);
4584
4610
  }
4585
4611
 
4612
+ // src/functions/continuation.ts
4613
+ var STATUS_KEY = "vgi.status";
4614
+ var HAVE_MORE_OUTPUT = "HAVE_MORE_OUTPUT";
4615
+ function replyMetadata(out) {
4616
+ const idx = out.dataBatchIdx;
4617
+ if (idx == null)
4618
+ return null;
4619
+ const emitted = out.batches[idx];
4620
+ const md = new Map(emitted.batch.metadata ?? []);
4621
+ for (const [k, v] of emitted.metadata ?? [])
4622
+ md.set(k, v);
4623
+ return md;
4624
+ }
4625
+ function refuseMoreOutput(name, out) {
4626
+ if (replyMetadata(out)?.get(STATUS_KEY) === HAVE_MORE_OUTPUT) {
4627
+ throw new Error(`${name}: HAVE_MORE_OUTPUT (moreOutputMetadata) is only valid in a table-in-out ` + `function's process() or resume()`);
4628
+ }
4629
+ }
4630
+
4586
4631
  // src/util/statistics.ts
4587
4632
  function serializeColumnStatistics(stats, _cacheMaxAgeSeconds) {
4588
4633
  return serializeBatch(buildStatisticsBatch(stats));
4589
4634
  }
4590
4635
 
4591
4636
  // src/generated/vgi-protocol-schemas.ts
4637
+ var VGI_CATALOG_CONTRACT_HASH = "0aa39285365f5f4326ce85c4d41d2705ea992dee41cf98d07640a2767b6ac3fb";
4592
4638
  var CatalogInfoSchema = schema2([
4593
4639
  field2("name", utf82(), false),
4594
4640
  field2("implementation_version", utf82(), true),
@@ -4600,7 +4646,6 @@ var CatalogInfoSchema = schema2([
4600
4646
  var SchemaInfoSchema = schema2([
4601
4647
  field2("comment", utf82(), true),
4602
4648
  field2("tags", map2(field2("key", utf82(), false), field2("value", utf82(), true), false), false),
4603
- field2("attach_opaque_data", binary2(), false),
4604
4649
  field2("path", list2(field2("item", utf82(), true)), false),
4605
4650
  field2("estimated_object_count", map2(field2("key", utf82(), false), field2("value", int642(), true), false), true)
4606
4651
  ]);
@@ -4641,9 +4686,9 @@ var FunctionInfoSchema = schema2([
4641
4686
  field2("name", utf82(), false),
4642
4687
  field2("schema_path", list2(field2("item", utf82(), true)), false),
4643
4688
  field2("function_type", dictionary2(utf82(), int162()), false),
4644
- field2("arguments", binary2(), false),
4645
- field2("output_schema", binary2(), false),
4646
- field2("parameter_default_values", binary2(), true),
4689
+ field2("arguments", dictionary2(binary2(), int322()), false),
4690
+ field2("output_schema", dictionary2(binary2(), int322()), false),
4691
+ field2("parameter_default_values", dictionary2(binary2(), int322()), true),
4647
4692
  field2("stability", dictionary2(utf82(), int162()), true),
4648
4693
  field2("null_handling", dictionary2(utf82(), int162()), true),
4649
4694
  field2("argument_monotonicity", list2(field2("item", utf82(), true)), true),
@@ -4675,6 +4720,7 @@ var FunctionInfoSchema = schema2([
4675
4720
  field2("sink_order_dependent", bool2(), false),
4676
4721
  field2("requires_input_batch_index", bool2(), false),
4677
4722
  field2("input_from_args", bool2(), false),
4723
+ field2("input_rows_per_call", int642(), true),
4678
4724
  field2("required_settings", list2(field2("item", utf82(), true)), false),
4679
4725
  field2("required_secrets", list2(field2("item", struct2([field2("secret_type", utf82(), false), field2("scope", utf82(), true), field2("secret_name", utf82(), true)]), true)), false)
4680
4726
  ]);
@@ -5104,7 +5150,12 @@ var CatalogContentsResultSchema = schema2([
5104
5150
  field2("catalog_version", int642(), false),
5105
5151
  field2("etag", utf82(), true),
5106
5152
  field2("not_modified", bool2(), false),
5107
- 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)
5153
+ field2("schemas", binary2(), true),
5154
+ field2("tables", binary2(), true),
5155
+ field2("views", binary2(), true),
5156
+ field2("functions", binary2(), true),
5157
+ field2("macros", binary2(), true),
5158
+ field2("indexes", binary2(), true)
5108
5159
  ]);
5109
5160
  var CatalogCopyFromFormatsResultSchema = schema2([
5110
5161
  field2("items", list2(field2("item", binary2(), true)), false)
@@ -5562,13 +5613,6 @@ var TableFunctionStatisticsParamsSchema = schema2([
5562
5613
  function normalizeSchemaPath(path) {
5563
5614
  return typeof path === "string" ? [path] : Array.from(path, String);
5564
5615
  }
5565
- function schemaPathKey(path) {
5566
- const normalized = normalizeSchemaPath(path);
5567
- if (normalized.length === 0 || normalized.some((part) => part.length === 0)) {
5568
- throw new Error("schema paths must contain at least one non-empty component");
5569
- }
5570
- return normalized.map((part) => part.toLowerCase()).join("\x00");
5571
- }
5572
5616
 
5573
5617
  // src/protocol/handlers/shared.ts
5574
5618
  var RESULT_BINARY_SCHEMA = schema2([
@@ -6835,6 +6879,9 @@ function functionHandlers(config) {
6835
6879
  if (state.userState != null && handlerState?.state !== undefined) {
6836
6880
  handlerState.state = state.userState;
6837
6881
  }
6882
+ if (handlers.continuesOutput) {
6883
+ handlerState.morePending = state.morePending === true;
6884
+ }
6838
6885
  }
6839
6886
  if (state.isProducer && handlers.producerFn) {
6840
6887
  out.finish = () => {
@@ -6847,10 +6894,14 @@ function functionHandlers(config) {
6847
6894
  } else if (handlers.exchangeFn) {
6848
6895
  await handlers.exchangeFn(handlerState, input, out);
6849
6896
  }
6897
+ if (!handlers.continuesOutput) {
6898
+ refuseMoreOutput(state.functionName, out);
6899
+ }
6850
6900
  if (handlerState?.state !== undefined) {
6851
6901
  state.userState = handlerState.state;
6852
6902
  }
6853
6903
  state.filterHistory = handlerState?.filterHistory ?? null;
6904
+ state.morePending = handlerState?.morePending === true;
6854
6905
  },
6855
6906
  headerInit: (params, state, ctx) => {
6856
6907
  if (!state._initResponse) {
@@ -7562,6 +7613,109 @@ function sortMapsForSchema(schema, obj) {
7562
7613
  }
7563
7614
  return out ?? obj;
7564
7615
  }
7616
+ function normalizeValue(raw, type) {
7617
+ if (raw == null)
7618
+ return null;
7619
+ if (isList(type)) {
7620
+ const childType = type.children[0].type;
7621
+ const out = [];
7622
+ for (const item of raw)
7623
+ out.push(normalizeValue(item, childType));
7624
+ return out;
7625
+ }
7626
+ if (isMap(type)) {
7627
+ const entries = type.children[0].type;
7628
+ const valueType = entries.children[1].type;
7629
+ const out = {};
7630
+ const put = (k, v) => {
7631
+ out[String(k)] = normalizeValue(v, valueType);
7632
+ };
7633
+ if (raw[Symbol.iterator]) {
7634
+ for (const entry of raw) {
7635
+ if (Array.isArray(entry)) {
7636
+ put(entry[0], entry[1]);
7637
+ } else if (entry && typeof entry === "object") {
7638
+ put(entry.key ?? entry[0], entry.value ?? entry[1]);
7639
+ }
7640
+ }
7641
+ } else if (typeof raw === "object") {
7642
+ for (const [k, v] of Object.entries(raw))
7643
+ put(k, v);
7644
+ }
7645
+ return out;
7646
+ }
7647
+ if (isStruct(type)) {
7648
+ const childFields = type.children;
7649
+ const out = {};
7650
+ for (const cf of childFields) {
7651
+ out[cf.name] = normalizeValue(raw[cf.name], cf.type);
7652
+ }
7653
+ return out;
7654
+ }
7655
+ if (isDictionary(type)) {
7656
+ return normalizeValue(raw, type.dictionary);
7657
+ }
7658
+ if (isBinary(type)) {
7659
+ return toUint8Array3(raw);
7660
+ }
7661
+ if (isInt(type) && type.bitWidth === 64) {
7662
+ if (typeof raw === "bigint") {
7663
+ if (raw >= BigInt(Number.MIN_SAFE_INTEGER) && raw <= BigInt(Number.MAX_SAFE_INTEGER)) {
7664
+ return Number(raw);
7665
+ }
7666
+ return raw;
7667
+ }
7668
+ return raw;
7669
+ }
7670
+ if (isBool(type)) {
7671
+ return Boolean(raw);
7672
+ }
7673
+ return raw;
7674
+ }
7675
+ function toUint8Array3(val) {
7676
+ if (val instanceof Uint8Array)
7677
+ return val;
7678
+ if (val instanceof ArrayBuffer)
7679
+ return new Uint8Array(val);
7680
+ if (val && val.buffer instanceof ArrayBuffer) {
7681
+ return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
7682
+ }
7683
+ return new Uint8Array(0);
7684
+ }
7685
+ function encodeASDCollection(schema, records) {
7686
+ if (records.length === 0)
7687
+ return null;
7688
+ return serializeCollectionRows(schema, records.map((record) => sortMapsForSchema(schema, conformRecord(schema, record))), 1024);
7689
+ }
7690
+ function decodeASDCollection(schema, bytes) {
7691
+ if (bytes == null)
7692
+ return [];
7693
+ const output = [];
7694
+ const batches = deserializeBatches(bytes);
7695
+ const validateSchema = (actualSchema) => {
7696
+ if (actualSchema.fields.length !== schema.fields.length || schema.fields.some((field, i) => {
7697
+ const actual = actualSchema.fields[i];
7698
+ return actual.name !== field.name || actual.nullable !== field.nullable || typeSignature(actual.type) !== typeSignature(field.type);
7699
+ }))
7700
+ throw new Error("catalog collection has an incompatible metadata schema");
7701
+ };
7702
+ if (batches.length === 0)
7703
+ validateSchema(deserializeSchema(bytes));
7704
+ for (const batch of batches) {
7705
+ validateSchema(batch.schema);
7706
+ for (let row = 0;row < batch.numRows; row++) {
7707
+ const item = {};
7708
+ for (const field of schema.fields) {
7709
+ const value = batch.getChild(field.name)?.get(row);
7710
+ if (value == null && !field.nullable)
7711
+ throw new Error(`catalog collection has null ${field.name}`);
7712
+ item[field.name] = normalizeValue(value, field.type);
7713
+ }
7714
+ output.push(item);
7715
+ }
7716
+ }
7717
+ return output;
7718
+ }
7565
7719
 
7566
7720
  // src/generated/vgi-client.ts
7567
7721
  var encodeCatalogInfo = (v) => encodeASD(CatalogInfoSchema, v);
@@ -7595,54 +7749,110 @@ function buildCatalogAttachResult(init) {
7595
7749
  supports_catalog_contents: init.supports_catalog_contents ?? false
7596
7750
  };
7597
7751
  }
7598
- function buildSchemaContents(init) {
7599
- return {
7600
- path: init.path,
7601
- schema: init.schema,
7602
- tables: init.tables ?? [],
7603
- views: init.views ?? [],
7604
- scalar_functions: init.scalar_functions ?? [],
7605
- aggregate_functions: init.aggregate_functions ?? [],
7606
- table_functions: init.table_functions ?? [],
7607
- scalar_macros: init.scalar_macros ?? [],
7608
- table_macros: init.table_macros ?? [],
7609
- indexes: init.indexes ?? []
7610
- };
7611
- }
7612
7752
  function buildCatalogContentsResponse(init) {
7613
7753
  return {
7614
7754
  catalog_version: init.catalog_version,
7615
7755
  etag: init.etag ?? null,
7616
7756
  not_modified: init.not_modified ?? false,
7617
- schemas: init.schemas ?? []
7757
+ schemas: init.schemas ?? null,
7758
+ tables: init.tables ?? null,
7759
+ views: init.views ?? null,
7760
+ functions: init.functions ?? null,
7761
+ macros: init.macros ?? null,
7762
+ indexes: init.indexes ?? null
7618
7763
  };
7619
7764
  }
7620
7765
 
7621
- // src/catalog/item-encoding.ts
7622
- var ENCODED = new WeakMap;
7623
- function encodeFunctionInfoOnce(info) {
7624
- if (!Object.isFrozen(info))
7625
- return encodeFunctionInfo(info);
7626
- let encoded = ENCODED.get(info);
7627
- if (encoded === undefined) {
7628
- encoded = encodeFunctionInfo(info);
7629
- ENCODED.set(info, encoded);
7766
+ // src/protocol/handlers/catalog/contents.ts
7767
+ import { ExternalRef as ExternalRef2 } from "@query-farm/vgi-rpc";
7768
+
7769
+ // src/catalog/publication.ts
7770
+ import { ExternalRef, publishExternalResult, resolveExternalLocation } from "@query-farm/vgi-rpc";
7771
+
7772
+ // src/catalog/contents-codec.ts
7773
+ var schemaPathKey = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
7774
+ var CATALOG_STREAM_KINDS = ["schemas", "tables", "views", "functions", "macros", "indexes"];
7775
+ function encodeCatalogStreams(inventory) {
7776
+ const streams = {
7777
+ schemas: encodeASDCollection(SchemaInfoSchema, inventory.map((s) => s.schema)),
7778
+ tables: encodeASDCollection(TableInfoSchema, inventory.flatMap((s) => s.tables)),
7779
+ views: encodeASDCollection(ViewInfoSchema, inventory.flatMap((s) => s.views)),
7780
+ functions: encodeASDCollection(FunctionInfoSchema, inventory.flatMap((s) => [...s.scalar_functions, ...s.aggregate_functions, ...s.table_functions])),
7781
+ macros: encodeASDCollection(MacroInfoSchema, inventory.flatMap((s) => [...s.scalar_macros, ...s.table_macros])),
7782
+ indexes: encodeASDCollection(IndexInfoSchema, inventory.flatMap((s) => s.indexes))
7783
+ };
7784
+ return streams;
7785
+ }
7786
+ function decodeCatalogStreams(response, ifNoneMatch) {
7787
+ if (response.not_modified) {
7788
+ if (response.etag == null || ifNoneMatch !== undefined && response.etag !== ifNoneMatch || CATALOG_STREAM_KINDS.some((kind) => response[kind] != null)) {
7789
+ throw new Error("invalid catalog_contents not_modified response");
7790
+ }
7791
+ return [];
7630
7792
  }
7631
- return encoded;
7793
+ const infos = decodeASDCollection(SchemaInfoSchema, response.schemas);
7794
+ const schemas = [];
7795
+ const index = new Map;
7796
+ for (const schema of infos) {
7797
+ if (!Array.isArray(schema.path) || schema.path.length === 0)
7798
+ throw new Error("catalog schema has an empty path");
7799
+ const key = schemaPathKey(schema.path);
7800
+ if (index.has(key))
7801
+ throw new Error("catalog contains duplicate schema paths");
7802
+ if (schema.path.length > 1 && !index.has(schemaPathKey(schema.path.slice(0, -1)))) {
7803
+ throw new Error("catalog schema is missing its preceding parent");
7804
+ }
7805
+ const entry = { schema, tables: [], views: [], scalar_functions: [], aggregate_functions: [], table_functions: [], scalar_macros: [], table_macros: [], indexes: [] };
7806
+ index.set(key, entry);
7807
+ schemas.push(entry);
7808
+ }
7809
+ const owner = (item) => {
7810
+ const entry = index.get(schemaPathKey(item.schema_path));
7811
+ if (!entry)
7812
+ throw new Error("catalog object references an absent schema");
7813
+ return entry;
7814
+ };
7815
+ for (const item of decodeASDCollection(TableInfoSchema, response.tables))
7816
+ owner(item).tables.push(item);
7817
+ for (const item of decodeASDCollection(ViewInfoSchema, response.views))
7818
+ owner(item).views.push(item);
7819
+ for (const item of decodeASDCollection(FunctionInfoSchema, response.functions)) {
7820
+ const entry = owner(item);
7821
+ switch (String(item.function_type).toUpperCase()) {
7822
+ case "SCALAR":
7823
+ entry.scalar_functions.push(item);
7824
+ break;
7825
+ case "AGGREGATE":
7826
+ entry.aggregate_functions.push(item);
7827
+ break;
7828
+ case "TABLE":
7829
+ case "TABLE_BUFFERING":
7830
+ entry.table_functions.push(item);
7831
+ break;
7832
+ default:
7833
+ throw new Error(`unknown catalog function type ${item.function_type}`);
7834
+ }
7835
+ }
7836
+ for (const item of decodeASDCollection(MacroInfoSchema, response.macros)) {
7837
+ const entry = owner(item);
7838
+ switch (String(item.macro_type).toUpperCase()) {
7839
+ case "SCALAR":
7840
+ entry.scalar_macros.push(item);
7841
+ break;
7842
+ case "TABLE":
7843
+ entry.table_macros.push(item);
7844
+ break;
7845
+ default:
7846
+ throw new Error(`unknown catalog macro type ${item.macro_type}`);
7847
+ }
7848
+ }
7849
+ for (const item of decodeASDCollection(IndexInfoSchema, response.indexes))
7850
+ owner(item).indexes.push(item);
7851
+ return schemas;
7632
7852
  }
7633
7853
 
7634
7854
  // src/catalog/contents-digest.ts
7635
- var KINDS = [
7636
- "tables",
7637
- "views",
7638
- "scalar_functions",
7639
- "aggregate_functions",
7640
- "table_functions",
7641
- "scalar_macros",
7642
- "table_macros",
7643
- "indexes"
7644
- ];
7645
- async function catalogContentsDigest(schemas) {
7855
+ async function catalogContentsDigest(streams, version = 0) {
7646
7856
  const utf8 = new TextEncoder;
7647
7857
  const parts = [];
7648
7858
  let total = 0;
@@ -7662,12 +7872,23 @@ async function catalogContentsDigest(schemas) {
7662
7872
  for (const v of values)
7663
7873
  chunk(v);
7664
7874
  };
7665
- count(schemas.length);
7666
- for (const entry of schemas) {
7667
- chunks(entry.path.map((p) => utf8.encode(p)));
7668
- chunk(entry.schema);
7669
- for (const kind of KINDS)
7670
- chunks(entry[kind]);
7875
+ if (Array.isArray(streams)) {
7876
+ count(streams.length);
7877
+ for (const entry of streams) {
7878
+ chunks(entry.path.map((p) => utf8.encode(p)));
7879
+ chunk(entry.schema);
7880
+ for (const kind of ["tables", "views", "scalar_functions", "aggregate_functions", "table_functions", "scalar_macros", "table_macros", "indexes"])
7881
+ chunks(entry[kind]);
7882
+ }
7883
+ } else {
7884
+ chunk(utf8.encode("vgi.catalog-contents.2.2"));
7885
+ count(version);
7886
+ for (const kind of CATALOG_STREAM_KINDS) {
7887
+ const value = streams[kind];
7888
+ count(value == null ? 0 : 1);
7889
+ if (value != null)
7890
+ chunk(value);
7891
+ }
7671
7892
  }
7672
7893
  const buf = new Uint8Array(total);
7673
7894
  let off = 0;
@@ -7682,7 +7903,297 @@ async function catalogContentsDigest(schemas) {
7682
7903
  return hex;
7683
7904
  }
7684
7905
 
7906
+ // src/catalog/publication-envelope.ts
7907
+ function validateCatalogPublicationEnvelope(bytes) {
7908
+ try {
7909
+ const stream = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
7910
+ let position = 0, messages = 0;
7911
+ while (position < bytes.length) {
7912
+ let length = stream.getInt32(position, true);
7913
+ position += 4;
7914
+ if (length === -1) {
7915
+ length = stream.getInt32(position, true);
7916
+ position += 4;
7917
+ }
7918
+ if (length === 0) {
7919
+ if (position !== bytes.length)
7920
+ throw new Error("trailing data");
7921
+ break;
7922
+ }
7923
+ if (length < 4 || length > bytes.length - position)
7924
+ throw new Error("invalid message length");
7925
+ const head = new DataView(bytes.buffer, bytes.byteOffset + position, length);
7926
+ const tableField = (table, field) => {
7927
+ const vtable = table - head.getInt32(table, true);
7928
+ const vlength = head.getUint16(vtable, true);
7929
+ if (vlength < 4 || vlength % 2 || vtable + vlength > length)
7930
+ throw new Error("invalid vtable");
7931
+ if (4 + 2 * field >= vlength)
7932
+ return null;
7933
+ const offset = head.getUint16(vtable + 4 + 2 * field, true);
7934
+ return offset === 0 ? null : table + offset;
7935
+ };
7936
+ const follow = (pointer) => pointer + head.getUint32(pointer, true);
7937
+ const root = head.getUint32(0, true);
7938
+ const typePosition = tableField(root, 1);
7939
+ const type = typePosition == null ? 0 : head.getUint8(typePosition);
7940
+ if (type !== (messages === 0 ? 1 : messages === 1 ? 3 : -1))
7941
+ throw new Error("expected one schema and one record batch");
7942
+ if (type === 3) {
7943
+ const header = tableField(root, 2);
7944
+ if (header == null)
7945
+ throw new Error("missing record header");
7946
+ const rows = tableField(follow(header), 0);
7947
+ if (rows == null || head.getBigInt64(rows, true) !== 1n)
7948
+ throw new Error("expected one response row");
7949
+ }
7950
+ const metadata = tableField(root, 4);
7951
+ if (metadata != null) {
7952
+ const vector = follow(metadata), count = head.getUint32(vector, true);
7953
+ if (count > length / 4)
7954
+ throw new Error("invalid metadata vector");
7955
+ for (let i = 0;i < count; i++) {
7956
+ const keyPointer = tableField(follow(vector + 4 + 4 * i), 0);
7957
+ if (keyPointer == null)
7958
+ continue;
7959
+ const keyStart = follow(keyPointer), keyLength = head.getUint32(keyStart, true);
7960
+ if (keyStart + 4 + keyLength > length)
7961
+ throw new Error("invalid metadata key");
7962
+ const key = new TextDecoder().decode(new Uint8Array(head.buffer, head.byteOffset + keyStart + 4, keyLength));
7963
+ if (key === "vgi_rpc.location" || key === "vgi_rpc.log_level")
7964
+ throw new Error("pointer/log metadata is not a catalog result");
7965
+ }
7966
+ }
7967
+ const bodyPosition = tableField(root, 3);
7968
+ const bodyLength = bodyPosition == null ? 0 : Number(head.getBigInt64(bodyPosition, true));
7969
+ position += length;
7970
+ if (!Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyLength > bytes.length - position)
7971
+ throw new Error("invalid body length");
7972
+ position += bodyLength;
7973
+ messages++;
7974
+ }
7975
+ if (messages !== 2)
7976
+ throw new Error("missing response batch");
7977
+ } catch (error) {
7978
+ throw new Error(`invalid published RPC envelope: ${error instanceof Error ? error.message : String(error)}`);
7979
+ }
7980
+ }
7981
+
7982
+ // src/catalog/publication.ts
7983
+ var OUTER_SCHEMA = schema2([field2("result", binary2(), false)]);
7984
+ var DEFAULT_MAX = 64 * 1024 * 1024;
7985
+ var utf83 = new TextEncoder;
7986
+ var equalBytes3 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
7987
+ async function digest(value) {
7988
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", utf83.encode(value)));
7989
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
7990
+ }
7991
+ function assertRenewedPublication(before, after) {
7992
+ 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]);
7993
+ if (unchanged(before) !== unchanged(after))
7994
+ throw new Error("renewal changed immutable catalog identity");
7995
+ }
7996
+ var manifestSame = (a, b) => a.manifestId === b.manifestId;
7997
+ class CatalogSnapshotManager {
7998
+ policy;
7999
+ cached = new Map;
8000
+ pending = new Map;
8001
+ constructor(policy) {
8002
+ this.policy = policy;
8003
+ for (const value of [policy.maxRawBytes, policy.maxStoredBytes, policy.maxCachedManifests]) {
8004
+ if (value != null && (!Number.isSafeInteger(value) || value <= 0))
8005
+ throw new Error("catalog publication limits must be positive safe integers");
8006
+ }
8007
+ if (policy.referenceGraceMs != null && (!Number.isSafeInteger(policy.referenceGraceMs) || policy.referenceGraceMs < 0))
8008
+ throw new Error("catalog publication reference grace must be a nonnegative safe integer");
8009
+ }
8010
+ usable(m) {
8011
+ const deadline = Date.now() + (this.policy.referenceGraceMs ?? 60000);
8012
+ return (m.stable || m.expiresAt != null) && (m.expiresAt == null || m.expiresAt > deadline) && (m.retainUntil == null || m.retainUntil > deadline);
8013
+ }
8014
+ async key(identity) {
8015
+ for (const value of [identity.catalogNamespace, identity.sourceRevision, identity.visibilityScope])
8016
+ if (!value)
8017
+ throw new Error("published catalogs require explicit namespace, revision and visibility scope");
8018
+ if (!Number.isSafeInteger(identity.catalogVersion))
8019
+ throw new Error("catalog version is not a safe integer");
8020
+ return digest(JSON.stringify([
8021
+ VGI_PROTOCOL_NAME,
8022
+ VGI_PROTOCOL_VERSION,
8023
+ VGI_CATALOG_CONTRACT_HASH,
8024
+ 1,
8025
+ identity.catalogNamespace,
8026
+ identity.sourceRevision,
8027
+ identity.visibilityScope,
8028
+ identity.catalogVersion,
8029
+ this.policy.repository.profile,
8030
+ this.policy.compression ?? "identity"
8031
+ ]));
8032
+ }
8033
+ remember(m) {
8034
+ this.cached.delete(m.key);
8035
+ this.cached.set(m.key, Object.freeze({ ...m }));
8036
+ while (this.cached.size > (this.policy.maxCachedManifests ?? 128))
8037
+ this.cached.delete(this.cached.keys().next().value);
8038
+ }
8039
+ async invalidate(key) {
8040
+ await this.pending.get(key)?.catch(() => {
8041
+ return;
8042
+ });
8043
+ const m = this.cached.get(key) ?? await this.policy.repository.lookup(key);
8044
+ this.cached.delete(key);
8045
+ if (m)
8046
+ await this.policy.repository.invalidate(key, m);
8047
+ }
8048
+ async validate(m, key, identity, expected) {
8049
+ 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))
8050
+ throw new Error("invalid or expired catalog publication manifest");
8051
+ const ref = new ExternalRef(m.url, m.sha256);
8052
+ const configuredFetch = this.policy.repository.resolver.fetch ?? fetch;
8053
+ const resolved = await resolveExternalLocation(ref.pointerBatch(OUTER_SCHEMA), {
8054
+ ...this.policy.repository.resolver,
8055
+ fetch: (input, init) => configuredFetch(input, { ...init, signal: AbortSignal.any([...init?.signal ? [init.signal] : [], AbortSignal.timeout(30000)]) }),
8056
+ maxFetchBytes: Math.min(this.policy.maxStoredBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxFetchBytes ?? Infinity),
8057
+ maxDecompressedBytes: Math.min(this.policy.maxRawBytes ?? DEFAULT_MAX, this.policy.repository.resolver.maxDecompressedBytes ?? Infinity),
8058
+ validateFetchedIpc: (bytes) => {
8059
+ this.policy.repository.resolver.validateFetchedIpc?.(bytes);
8060
+ if (bytes.length !== m.rawSize)
8061
+ throw new Error("catalog publication raw size mismatch");
8062
+ validateCatalogPublicationEnvelope(bytes);
8063
+ }
8064
+ });
8065
+ 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)
8066
+ throw new Error("invalid published RPC envelope");
8067
+ const bytes = resolved.getChild("result")?.get(0);
8068
+ if (!(bytes instanceof Uint8Array))
8069
+ throw new Error("published catalog has no result bytes");
8070
+ const decoded = decodeASDCollection(CatalogContentsResultSchema, bytes);
8071
+ if (decoded.length !== 1)
8072
+ throw new Error("published catalog must contain exactly one response row");
8073
+ const response = decoded[0];
8074
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion || response.etag !== m.etag)
8075
+ throw new Error("published catalog version or ETag mismatch");
8076
+ decodeCatalogStreams(response);
8077
+ if (expected)
8078
+ for (const kind of CATALOG_STREAM_KINDS) {
8079
+ const a = response[kind], b = expected[kind];
8080
+ if (a == null !== (b == null) || a != null && b != null && !equalBytes3(a, b))
8081
+ throw new Error("publication readback changed catalog metadata");
8082
+ }
8083
+ }
8084
+ async import(manifest, identity) {
8085
+ const key = await this.key(identity);
8086
+ await this.validate(manifest, key, identity);
8087
+ const winner = await this.policy.repository.commitIfAbsent(manifest);
8088
+ if (!manifestSame(manifest, winner))
8089
+ await this.validate(winner, key, identity);
8090
+ this.remember(winner);
8091
+ return winner;
8092
+ }
8093
+ async warm(identity, build) {
8094
+ const key = await this.key(identity);
8095
+ const cached = this.cached.get(key);
8096
+ if (cached && this.usable(cached))
8097
+ return cached;
8098
+ const active = this.pending.get(key);
8099
+ if (active)
8100
+ return active;
8101
+ const pending = this.recoverOrPublish(key, identity, build);
8102
+ this.pending.set(key, pending);
8103
+ try {
8104
+ const m = await pending;
8105
+ this.remember(m);
8106
+ return m;
8107
+ } finally {
8108
+ if (this.pending.get(key) === pending)
8109
+ this.pending.delete(key);
8110
+ }
8111
+ }
8112
+ async recoverOrPublish(key, identity, build) {
8113
+ const repository = this.policy.repository;
8114
+ let existing = await repository.lookup(key);
8115
+ if (existing) {
8116
+ try {
8117
+ if (!this.usable(existing) && repository.renew) {
8118
+ const renewed = await repository.renew(existing);
8119
+ if (renewed) {
8120
+ assertRenewedPublication(existing, renewed);
8121
+ existing = renewed;
8122
+ }
8123
+ }
8124
+ await this.validate(existing, key, identity);
8125
+ return existing;
8126
+ } catch {
8127
+ await repository.invalidate(key, existing);
8128
+ }
8129
+ }
8130
+ const response = await build();
8131
+ if (response.not_modified || Number(response.catalog_version) !== identity.catalogVersion)
8132
+ throw new Error("publication requires a full snapshot of the requested version");
8133
+ decodeCatalogStreams(response);
8134
+ response.etag ??= await catalogContentsDigest(response, identity.catalogVersion);
8135
+ const payload = encodeASD(CatalogContentsResultSchema, response);
8136
+ let rawSize = 0, storedSize = 0;
8137
+ const bounded = { upload: async (data, encoding) => {
8138
+ if (encoding)
8139
+ throw new Error("catalog publication uploader requires identity encoding");
8140
+ rawSize = data.byteLength;
8141
+ if (rawSize > (this.policy.maxRawBytes ?? DEFAULT_MAX))
8142
+ throw new Error("catalog publication exceeds byte limit");
8143
+ let body = data;
8144
+ const compression = this.policy.compression ?? "identity";
8145
+ if (compression !== "identity" && compression !== "gzip" && compression !== "zstd")
8146
+ throw new Error("catalog publication compression must be identity, gzip or zstd");
8147
+ if (compression === "gzip") {
8148
+ body = new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer());
8149
+ } else if (compression === "zstd") {
8150
+ const runtime = globalThis.Bun;
8151
+ if (typeof runtime?.zstdCompress === "function") {
8152
+ body = new Uint8Array(await runtime.zstdCompress(data));
8153
+ } else if (typeof process !== "undefined" && process.versions?.node) {
8154
+ const nodeZlib = "node:zlib";
8155
+ const zlib = await import(nodeZlib);
8156
+ if (typeof zlib.zstdCompressSync !== "function")
8157
+ throw new Error("zstd catalog publication requires Node >=22.15, Bun, or an encoder-capable runtime");
8158
+ body = new Uint8Array(zlib.zstdCompressSync(data));
8159
+ } else {
8160
+ throw new Error("zstd catalog publication requires an encoder-capable runtime; use gzip or identity here");
8161
+ }
8162
+ }
8163
+ storedSize = body.byteLength;
8164
+ if (storedSize > (this.policy.maxStoredBytes ?? DEFAULT_MAX))
8165
+ throw new Error("catalog publication exceeds byte limit");
8166
+ return repository.storage.upload(body, compression === "identity" ? "" : compression);
8167
+ } };
8168
+ const ref = await publishExternalResult(OUTER_SCHEMA, { result: payload }, bounded, { includeSha256: true });
8169
+ const m = {
8170
+ formatVersion: 1,
8171
+ manifestId: crypto.randomUUID(),
8172
+ key,
8173
+ protocolName: VGI_PROTOCOL_NAME,
8174
+ protocolVersion: VGI_PROTOCOL_VERSION,
8175
+ contractHash: VGI_CATALOG_CONTRACT_HASH,
8176
+ codecRevision: 1,
8177
+ catalogVersion: identity.catalogVersion,
8178
+ etag: response.etag,
8179
+ sha256: ref.sha256,
8180
+ rawSize,
8181
+ storedSize,
8182
+ url: ref.url,
8183
+ validated: true,
8184
+ ...await repository.describe(ref.url)
8185
+ };
8186
+ await this.validate(m, key, identity, response);
8187
+ const winner = await repository.commitIfAbsent(m);
8188
+ if (!manifestSame(m, winner))
8189
+ await this.validate(winner, key, identity);
8190
+ return winner;
8191
+ }
8192
+ }
8193
+
7685
8194
  // src/protocol/handlers/catalog/contents.ts
8195
+ var schemaPathKey2 = (path) => JSON.stringify(path.map((part) => part.toLowerCase()));
8196
+ var PUBLICATIONS = new WeakMap;
7686
8197
  var CACHE = new WeakMap;
7687
8198
  async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
7688
8199
  const result = await cat.catalogContents(attach, ifNoneMatch);
@@ -7697,39 +8208,74 @@ async function buildCatalogContents(cat, owner, attach, version, ifNoneMatch) {
7697
8208
  return buildCatalogContentsResponse({ catalog_version: version, etag: etag0, not_modified: true });
7698
8209
  }
7699
8210
  const infos = [...result.schemas ?? []];
7700
- const keys = infos.map((c) => schemaPathKey(c.schema.path));
8211
+ const keys = infos.map((c) => schemaPathKey2(c.schema.path));
7701
8212
  const keySet = new Set(keys);
7702
8213
  if (keySet.size !== keys.length)
7703
8214
  throw new Error("catalog_contents returned duplicate schema paths");
7704
8215
  for (const c of infos) {
7705
- if (c.schema.path.length > 1 && !keySet.has(schemaPathKey(c.schema.path.slice(0, -1)))) {
8216
+ if (c.schema.path.length > 1 && !keySet.has(schemaPathKey2(c.schema.path.slice(0, -1)))) {
7706
8217
  throw new Error(`catalog_contents returned schema path ${JSON.stringify(c.schema.path)} without its parent`);
7707
8218
  }
7708
8219
  }
7709
- const schemas = infos.sort((a, b) => a.schema.path.length - b.schema.path.length).map((c) => buildSchemaContents({
7710
- path: [...c.schema.path],
7711
- schema: encodeSchemaInfo(c.schema),
7712
- tables: c.tables.map((t) => encodeTableInfo(t)),
7713
- views: c.views.map((v) => encodeViewInfo(v)),
7714
- scalar_functions: c.scalar_functions.map((f) => encodeFunctionInfoOnce(f)),
7715
- aggregate_functions: c.aggregate_functions.map((f) => encodeFunctionInfoOnce(f)),
7716
- table_functions: c.table_functions.map((f) => encodeFunctionInfoOnce(f)),
7717
- scalar_macros: c.scalar_macros.map((m) => encodeMacroInfo(m)),
7718
- table_macros: c.table_macros.map((m) => encodeMacroInfo(m)),
7719
- indexes: c.indexes.map((i) => encodeIndexInfo(i))
7720
- }));
8220
+ const streams = encodeCatalogStreams(infos.sort((a, b) => a.schema.path.length - b.schema.path.length));
7721
8221
  let etag = etag0;
7722
8222
  if (etag === null && owner.catalogContentsEtag === "content-hash") {
7723
- etag = await catalogContentsDigest(schemas);
8223
+ etag = await catalogContentsDigest(streams, version);
7724
8224
  }
7725
8225
  if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {
7726
8226
  return buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true });
7727
8227
  }
7728
- return buildCatalogContentsResponse({ catalog_version: version, etag, schemas });
8228
+ const response = buildCatalogContentsResponse({ catalog_version: version, etag, ...streams });
8229
+ decodeCatalogStreams(response);
8230
+ return response;
7729
8231
  }
7730
- async function serveCatalogContents(cat, attach, ifNoneMatch) {
8232
+ async function serveCatalogContents(cat, attach, ifNoneMatch, callContext, sealedAttach = attach) {
7731
8233
  const owner = cat.catalogContentsOwner(attach);
7732
8234
  const version = Number(await cat.version(attach));
8235
+ const policy = owner.catalogSnapshotPolicy;
8236
+ if (policy?.delivery === "published") {
8237
+ const request = { catalog: cat, attachOpaqueData: attach, callContext, catalogVersion: version };
8238
+ const inline = (etag) => wrapResult(buildCatalogContentsResponse({ catalog_version: version, etag, not_modified: true }), CatalogContentsResultSchema);
8239
+ const cheapEtag = await policy.etag?.(request);
8240
+ if (cheapEtag != null && cheapEtag === ifNoneMatch)
8241
+ return inline(cheapEtag);
8242
+ let manager = PUBLICATIONS.get(policy);
8243
+ if (!manager) {
8244
+ manager = new CatalogSnapshotManager(policy);
8245
+ PUBLICATIONS.set(policy, manager);
8246
+ }
8247
+ const scopeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", sealedAttach));
8248
+ const attachmentScope = "attachment:" + Array.from(scopeBytes, (b) => b.toString(16).padStart(2, "0")).join("");
8249
+ const identify = async (input) => {
8250
+ const id = await policy.identity(input);
8251
+ return { ...id, visibilityScope: id.visibilityScope ?? attachmentScope };
8252
+ };
8253
+ const identity = await identify(request);
8254
+ if (identity.catalogVersion !== version)
8255
+ throw new Error("snapshot identity version differs from the attached catalog");
8256
+ const assertCurrentIdentity = async () => {
8257
+ const currentVersion = Number(await cat.version(attach));
8258
+ const current = await identify({ ...request, catalogVersion: currentVersion });
8259
+ if (currentVersion !== version || await manager.key(identity) !== await manager.key(current))
8260
+ throw new Error("catalog changed while resolving its publication");
8261
+ };
8262
+ const buildSnapshot = async (validator) => {
8263
+ const response = await buildCatalogContents(cat, owner, attach, version, validator);
8264
+ await assertCurrentIdentity();
8265
+ return response;
8266
+ };
8267
+ try {
8268
+ const manifest = await manager.warm(identity, () => buildSnapshot(null));
8269
+ await assertCurrentIdentity();
8270
+ if (manifest.etag === ifNoneMatch)
8271
+ return inline(manifest.etag);
8272
+ return new ExternalRef2(manifest.url, manifest.sha256);
8273
+ } catch (error) {
8274
+ if (policy.onPublicationFailure !== "ordinary")
8275
+ throw error;
8276
+ return wrapResult(await buildSnapshot(ifNoneMatch), CatalogContentsResultSchema);
8277
+ }
8278
+ }
7733
8279
  if (owner.catalogContentsCacheable()) {
7734
8280
  let pending = CACHE.get(owner);
7735
8281
  let snapshot = pending ? await pending.catch(() => null) : null;
@@ -7759,6 +8305,19 @@ async function serveCatalogContents(cat, attach, ifNoneMatch) {
7759
8305
  return wrapResult(await buildCatalogContents(cat, owner, attach, version, ifNoneMatch), CatalogContentsResultSchema);
7760
8306
  }
7761
8307
 
8308
+ // src/catalog/item-encoding.ts
8309
+ var ENCODED = new WeakMap;
8310
+ function encodeFunctionInfoOnce(info) {
8311
+ if (!Object.isFrozen(info))
8312
+ return encodeFunctionInfo(info);
8313
+ let encoded = ENCODED.get(info);
8314
+ if (encoded === undefined) {
8315
+ encoded = encodeFunctionInfo(info);
8316
+ ENCODED.set(info, encoded);
8317
+ }
8318
+ return encoded;
8319
+ }
8320
+
7762
8321
  // src/catalog/interface.ts
7763
8322
  var encodeCopyFromFormatInfo = (v) => encodeASD(CopyFromFormatInfoSchema, {
7764
8323
  comment: v.comment ?? null,
@@ -8334,10 +8893,13 @@ function catalogAdminHandlers(getCatalog, signingKey) {
8334
8893
  items: schemas.map((s) => encodeSchemaInfo(s))
8335
8894
  }, CatalogSchemasResultSchema);
8336
8895
  });
8337
- const catalogContents = catalogHandler(signingKey, async (params) => {
8338
- const ifNoneMatch = params.if_none_match == null ? null : String(params.if_none_match);
8339
- return serveCatalogContents(getCatalog(), toUint8Array(params.attach_opaque_data), ifNoneMatch);
8340
- });
8896
+ const catalogContents = async (params, ctx) => {
8897
+ const sealedAttach = toUint8Array(params.attach_opaque_data).slice();
8898
+ return catalogHandler(signingKey, async (opened, context) => {
8899
+ const ifNoneMatch = opened.if_none_match == null ? null : String(opened.if_none_match);
8900
+ return serveCatalogContents(getCatalog(), toUint8Array(opened.attach_opaque_data), ifNoneMatch, context, sealedAttach);
8901
+ })(params, ctx);
8902
+ };
8341
8903
  const catalogCopyFromFormats = catalogHandler(signingKey, async (params) => {
8342
8904
  const cat = getCatalog();
8343
8905
  const formats = await cat.copyFromFormats(toUint8Array(params.attach_opaque_data), params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined);
@@ -9060,4 +9622,4 @@ export {
9060
9622
  serveVgiWorker
9061
9623
  };
9062
9624
 
9063
- //# debugId=8C488693F22A8E5A64756E2164756E21
9625
+ //# debugId=C0E67975BCC50FF364756E2164756E21