@query-farm/vgi 0.47.2 → 0.48.1

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 (105) hide show
  1. package/README.md +1 -1
  2. package/dist/arguments/argument-spec.d.ts +17 -11
  3. package/dist/catalog/descriptors.d.ts +2 -2
  4. package/dist/catalog/publication.d.ts +7 -7
  5. package/dist/client/client.d.ts +9 -3
  6. package/dist/client/errors.d.ts +2 -2
  7. package/dist/client/types.d.ts +21 -0
  8. package/dist/client-entry.d.ts +1 -1
  9. package/dist/client-entry.js +56 -7
  10. package/dist/client-entry.js.map +23 -23
  11. package/dist/filter-pushdown/deserialize.d.ts +1 -1
  12. package/dist/filter-pushdown/types.d.ts +10 -10
  13. package/dist/functions/scalar.d.ts +1 -1
  14. package/dist/functions/table-buffering.d.ts +20 -20
  15. package/dist/functions/table-in-out.d.ts +4 -4
  16. package/dist/functions/table.d.ts +7 -7
  17. package/dist/functions/types.d.ts +47 -47
  18. package/dist/generated/vgi-client.d.ts +5 -0
  19. package/dist/generated/vgi-protocol-schemas.d.ts +5 -0
  20. package/dist/generated/vgi-protocol-types.d.ts +57 -0
  21. package/dist/generated/vgi-service.d.ts +1 -1
  22. package/dist/http/fetch.d.ts +10 -10
  23. package/dist/index.core.d.ts +3 -1
  24. package/dist/index.js +289 -103
  25. package/dist/index.js.map +57 -55
  26. package/dist/protocol/dispatch.d.ts +4 -4
  27. package/dist/protocol/handlers/function.d.ts +2 -2
  28. package/dist/protocol/serializers/cardinality.d.ts +4 -1
  29. package/dist/protocol/serializers/splits.d.ts +41 -1
  30. package/dist/protocol/types.d.ts +5 -5
  31. package/dist/rpc-server.d.ts +6 -6
  32. package/dist/serve-entry.d.ts +16 -16
  33. package/dist/serve-entry.js +119 -30
  34. package/dist/serve-entry.js.map +42 -40
  35. package/dist/split-token.d.ts +6 -6
  36. package/dist/types.d.ts +9 -2
  37. package/dist/util/defined.d.ts +21 -0
  38. package/dist/worker-cf-entry.js +199 -94
  39. package/dist/worker-cf-entry.js.map +55 -53
  40. package/dist/worker.d.ts +2 -2
  41. package/package.json +6 -4
  42. package/src/arguments/argument-spec.ts +17 -11
  43. package/src/arrow/codec/registry.ts +2 -2
  44. package/src/arrow/impl-arrowjs/build.ts +1 -1
  45. package/src/arrow/impl-arrowjs/canonical.ts +23 -23
  46. package/src/arrow/impl-arrowjs/empty.ts +2 -2
  47. package/src/arrow/impl-arrowjs/ipc.ts +2 -2
  48. package/src/arrow/impl-arrowjs/iterate.ts +2 -2
  49. package/src/arrow/impl-arrowjs/project.ts +2 -2
  50. package/src/arrow/impl-flechette/build.ts +2 -1
  51. package/src/arrow/impl-flechette/canonical.ts +10 -9
  52. package/src/arrow/impl-flechette/compat.ts +3 -3
  53. package/src/arrow/impl-flechette/message-meta.ts +5 -4
  54. package/src/arrow/impl-flechette/statistics.ts +2 -2
  55. package/src/attach-ticket.ts +2 -2
  56. package/src/catalog/column-metadata.ts +1 -1
  57. package/src/catalog/composite.ts +2 -2
  58. package/src/catalog/constraints.ts +9 -9
  59. package/src/catalog/descriptors.ts +1 -1
  60. package/src/catalog/interface.ts +12 -12
  61. package/src/catalog/publication.ts +9 -8
  62. package/src/catalog/read-only.ts +9 -8
  63. package/src/catalog/sql-grammar.ts +6 -6
  64. package/src/client/client.ts +52 -15
  65. package/src/client/errors.ts +1 -1
  66. package/src/client/types.ts +23 -0
  67. package/src/client-entry.ts +2 -0
  68. package/src/codec/asd.ts +3 -3
  69. package/src/codec/conform.ts +3 -3
  70. package/src/filter-pushdown/collector.ts +1 -1
  71. package/src/filter-pushdown/deserialize.ts +13 -10
  72. package/src/filter-pushdown/evaluate.ts +3 -2
  73. package/src/filter-pushdown/history.ts +3 -2
  74. package/src/filter-pushdown/types.ts +10 -10
  75. package/src/functions/continuation.ts +1 -1
  76. package/src/functions/projection.ts +1 -1
  77. package/src/functions/registry.ts +14 -14
  78. package/src/functions/scalar.ts +3 -3
  79. package/src/functions/storage-cf-do.ts +2 -2
  80. package/src/functions/table-buffering.ts +25 -21
  81. package/src/functions/table-in-out.ts +8 -8
  82. package/src/functions/table.ts +27 -25
  83. package/src/functions/types.ts +47 -47
  84. package/src/generated/vgi-client.ts +6 -1
  85. package/src/generated/vgi-protocol-schemas.ts +36 -1
  86. package/src/generated/vgi-protocol-types.ts +130 -1
  87. package/src/generated/vgi-service.ts +7 -5
  88. package/src/http/fetch.ts +17 -12
  89. package/src/index.core.ts +34 -0
  90. package/src/protocol/carried-init-request.ts +1 -1
  91. package/src/protocol/dispatch.ts +4 -4
  92. package/src/protocol/handlers/aggregate.ts +8 -7
  93. package/src/protocol/handlers/catalog/shared.ts +1 -1
  94. package/src/protocol/handlers/function.ts +2 -2
  95. package/src/protocol/serializers/cardinality.ts +16 -3
  96. package/src/protocol/serializers/splits.ts +82 -9
  97. package/src/protocol/state-serializer.ts +1 -1
  98. package/src/protocol/types.ts +5 -5
  99. package/src/rpc-server.ts +13 -12
  100. package/src/serve-entry.ts +18 -18
  101. package/src/split-token.ts +10 -9
  102. package/src/types.ts +9 -2
  103. package/src/util/defined.ts +30 -0
  104. package/src/util/parent-rows.ts +2 -2
  105. package/src/worker.ts +15 -14
@@ -10,6 +10,7 @@ import {
10
10
  TableFunctionPlanResultSchema,
11
11
  } from "../../generated/vgi-protocol-schemas.js";
12
12
  import type { BindRequest } from "../types.js";
13
+ import { OrderByDirection, OrderByNullOrder } from "../types.js";
13
14
  import { deserializeBatch, batchToScalarDict } from "../../util/arrow/index.js";
14
15
  import { toUint8Array } from "./shared.js";
15
16
  import { deserializeBindRequest } from "./bind.js";
@@ -35,7 +36,16 @@ export interface ScanSplit {
35
36
  * claiming client needs no cost model at all.
36
37
  */
37
38
  estimatedBytes?: number | bigint | null;
38
- /** 2-row (min, max) batch in the existing `vgi_partition_values` encoding. */
39
+ /** One-row exact transformed-key tuple aligned with `PlanResult.keyGrouping`. */
40
+ keyValue?: Uint8Array | null;
41
+ /** Zero-based range owned by this split under `PlanResult.rangePartitioning`. */
42
+ rangeIndex?: number | bigint | null;
43
+ /** Two-row (min, max) pruning batch; never an exact distribution claim. */
44
+ columnBounds?: Uint8Array | null;
45
+ /**
46
+ * Two-row (min, max) batch in the legacy `vgi_partition_values` encoding.
47
+ * @deprecated Protocol 3 producers should use `columnBounds`.
48
+ */
39
49
  partitionBounds?: Uint8Array | null;
40
50
  columnStatistics?: Uint8Array | null;
41
51
  locationIds?: number[] | null;
@@ -76,7 +86,21 @@ export interface PlanResult {
76
86
  * cacheable and is not redeemable after commit or rollback.
77
87
  */
78
88
  scope?: "catalog" | "transaction";
89
+ /** Hoisted host list indexed by each split's `locationIds`. */
90
+ locations?: string[] | null;
91
+ /** Serialized `KeyGrouping` shared by every page of this plan. */
92
+ keyGrouping?: Uint8Array | null;
93
+ /** Serialized `RangePartitioning` shared by every page of this plan. */
94
+ rangePartitioning?: Uint8Array | null;
95
+ /** @deprecated Protocol 3 producers should use `keyGrouping` or `rangePartitioning`. */
96
+ partitioning?: Uint8Array[] | null;
97
+ /** Serialized `SortField` records describing order within each split. */
98
+ sortOrder?: Uint8Array[] | null;
79
99
  cacheMaxAgeSeconds?: number | null;
100
+ /** Actual exclusive lower data position selected by the worker. */
101
+ startPosition?: Uint8Array | null;
102
+ /** Data frontier resolved by the worker for this plan. */
103
+ endPosition?: Uint8Array | null;
80
104
  }
81
105
 
82
106
  /** The request a client sends to divide a scan. */
@@ -85,6 +109,8 @@ export interface TableFunctionPlanRequest {
85
109
  bind_opaque_data: Uint8Array | null;
86
110
  projection_ids: number[] | null;
87
111
  pushdown_filters: Uint8Array | null;
112
+ join_keys: Uint8Array[] | null;
113
+ row_limit: bigint | null;
88
114
  /** The primary sizing lever: every engine is byte-driven. */
89
115
  target_split_bytes: bigint | null;
90
116
  /**
@@ -92,12 +118,26 @@ export interface TableFunctionPlanRequest {
92
118
  * per thread, which a byte target alone would not give it.
93
119
  */
94
120
  min_splits: bigint | null;
121
+ /** Maximum number of splits to enumerate on this response page. */
122
+ max_splits_per_response: bigint | null;
95
123
  /**
96
124
  * A place in the ENUMERATION of splits — NOT a place in the data. A cursor
97
125
  * lives for one plan call; a position is checkpointed and must survive
98
126
  * restarts, upgrades and key rotation.
99
127
  */
100
128
  cursor: Uint8Array | null;
129
+ /** Narrower filters supplied on a continuation request. */
130
+ refined_filters: Uint8Array | null;
131
+ /** False while the client may still send further filter refinement. */
132
+ filters_complete: boolean;
133
+ start_position: Uint8Array | null;
134
+ end_position: Uint8Array | null;
135
+ order_by_column_name: string | null;
136
+ order_by_direction: OrderByDirection | null;
137
+ order_by_null_order: OrderByNullOrder | null;
138
+ order_by_limit: bigint | null;
139
+ tablesample_percentage: number | null;
140
+ tablesample_seed: bigint | null;
101
141
  }
102
142
 
103
143
  /**
@@ -136,15 +176,43 @@ export function deserializePlanRequest(params: Record<string, any>): TableFuncti
136
176
 
137
177
  const asBigInt = (v: unknown): bigint | null =>
138
178
  v == null ? null : typeof v === "bigint" ? v : BigInt(Number(v));
179
+ const asBytes = (v: unknown): Uint8Array | null => v == null ? null : toUint8Array(v);
180
+ const asBytesList = (v: unknown): Uint8Array[] | null => {
181
+ if (v == null) return null;
182
+ const values = Array.isArray(v)
183
+ ? v
184
+ : v && typeof (v as any)[Symbol.iterator] === "function"
185
+ ? [...(v as Iterable<unknown>)]
186
+ : [];
187
+ return values.filter((entry) => entry != null).map(toUint8Array);
188
+ };
189
+ const enumValue = <T extends string>(v: unknown, values: readonly T[]): T | null => {
190
+ if (v == null) return null;
191
+ const text = String(v) as T;
192
+ return values.includes(text) ? text : null;
193
+ };
139
194
 
140
195
  return {
141
196
  bind_call: bindCall,
142
- bind_opaque_data: params.bind_opaque_data ? toUint8Array(params.bind_opaque_data) : null,
197
+ bind_opaque_data: asBytes(params.bind_opaque_data),
143
198
  projection_ids: projectionIds,
144
- pushdown_filters: params.pushdown_filters ? toUint8Array(params.pushdown_filters) : null,
199
+ pushdown_filters: asBytes(params.pushdown_filters),
200
+ join_keys: asBytesList(params.join_keys),
201
+ row_limit: asBigInt(params.row_limit),
145
202
  target_split_bytes: asBigInt(params.target_split_bytes),
146
203
  min_splits: asBigInt(params.min_splits),
147
- cursor: params.cursor ? toUint8Array(params.cursor) : null,
204
+ max_splits_per_response: asBigInt(params.max_splits_per_response),
205
+ cursor: asBytes(params.cursor),
206
+ refined_filters: asBytes(params.refined_filters),
207
+ filters_complete: params.filters_complete == null ? true : Boolean(params.filters_complete),
208
+ start_position: asBytes(params.start_position),
209
+ end_position: asBytes(params.end_position),
210
+ order_by_column_name: params.order_by_column_name == null ? null : String(params.order_by_column_name),
211
+ order_by_direction: enumValue(params.order_by_direction, Object.values(OrderByDirection)),
212
+ order_by_null_order: enumValue(params.order_by_null_order, Object.values(OrderByNullOrder)),
213
+ order_by_limit: asBigInt(params.order_by_limit),
214
+ tablesample_percentage: params.tablesample_percentage == null ? null : Number(params.tablesample_percentage),
215
+ tablesample_seed: asBigInt(params.tablesample_seed),
148
216
  };
149
217
  }
150
218
 
@@ -188,6 +256,9 @@ export function scanSplitRow(split: ScanSplit, token: Uint8Array): Record<string
188
256
  estimated_rows: asBigInt(split.estimatedRows),
189
257
  rows_exact: split.rowsExact === true,
190
258
  estimated_bytes: asBigInt(split.estimatedBytes),
259
+ key_value: split.keyValue ?? null,
260
+ range_index: asBigInt(split.rangeIndex),
261
+ column_bounds: split.columnBounds ?? null,
191
262
  partition_bounds: split.partitionBounds ?? null,
192
263
  column_statistics: split.columnStatistics ?? null,
193
264
  location_ids: split.locationIds ?? null,
@@ -211,11 +282,13 @@ export function planResponseRow(result: PlanResult, splitBlobs: Uint8Array[]): R
211
282
  estimated_total_bytes: asBigInt(result.estimatedTotalBytes),
212
283
  catalog_version: asBigInt(result.catalogVersion),
213
284
  scope: result.scope ?? "catalog",
214
- locations: null,
215
- partitioning: [],
216
- sort_order: [],
285
+ locations: result.locations ?? null,
286
+ key_grouping: result.keyGrouping ?? null,
287
+ range_partitioning: result.rangePartitioning ?? null,
288
+ partitioning: result.partitioning ?? null,
289
+ sort_order: result.sortOrder ?? null,
217
290
  cache_max_age_seconds: asBigInt(result.cacheMaxAgeSeconds),
218
- start_position: new Uint8Array(0),
219
- end_position: new Uint8Array(0),
291
+ start_position: result.startPosition ?? null,
292
+ end_position: result.endPosition ?? null,
220
293
  };
221
294
  }
@@ -274,7 +274,7 @@ export const arrowStateSerializer: StateSerializer = {
274
274
  if (bytes.byteLength < 10 || bytes[0] !== STATE_FORMAT_VERSION) {
275
275
  throw new Error("exchange state has an unknown format (minted by another build of this worker?)");
276
276
  }
277
- const flags = bytes[1];
277
+ const flags = bytes[1]!; // in range: byteLength >= 10 was checked above
278
278
  const maxWorkers = view.getFloat64(2, true);
279
279
  let offset = 10;
280
280
  // Each field is copied out, not viewed: Arrow readers want a buffer of
@@ -109,13 +109,13 @@ export type BindRepeatability = "UNKNOWN" | "STABLE_WITHIN_QUERY";
109
109
 
110
110
  export interface BindResponse {
111
111
  /** Omitted provider values serialize as UNKNOWN. Wire values are required. */
112
- repeatability?: BindRepeatability;
113
- projection_expression_profiles?: string[];
112
+ repeatability?: BindRepeatability | undefined;
113
+ projection_expression_profiles?: string[] | undefined;
114
114
  output_schema: VgiSchema;
115
115
  opaque_data: Uint8Array | null;
116
- lookup_secret_types?: string[];
117
- lookup_scopes?: string[];
118
- lookup_names?: string[];
116
+ lookup_secret_types?: string[] | undefined;
117
+ lookup_scopes?: string[] | undefined;
118
+ lookup_names?: string[] | undefined;
119
119
  }
120
120
 
121
121
  export interface InitRequest {
package/src/rpc-server.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  } from "@query-farm/vgi-rpc";
35
35
  import { buildAttachTicketsProtocol, resolveTicketMaxTtl } from "./attach-ticket.js";
36
36
  import type { CatalogInterface } from "./catalog/interface.js";
37
+ import { omitUndefined } from "./util/defined.js";
37
38
 
38
39
  /** The transport a server is being built for. Only `"http"` changes what is
39
40
  * hosted (identity); the rest are recorded so the decision lives here rather
@@ -81,7 +82,7 @@ export interface HostingOptions {
81
82
  * `vgi_rpc.Identity.v2` is enabled through {@link resolveToken} /
82
83
  * {@link mintGrant}. Violations are a startup error naming this hook.
83
84
  */
84
- hostedProtocols?: () => Iterable<Protocol>;
85
+ hostedProtocols?: (() => Iterable<Protocol>) | undefined;
85
86
 
86
87
  /**
87
88
  * Resolve an opaque bearer credential to the identity it authenticates as.
@@ -102,7 +103,7 @@ export interface HostingOptions {
102
103
  * Requires {@link introspectPrincipals} (or `VGI_INTROSPECT_PRINCIPALS`);
103
104
  * there is no permissive default, and a worker without one refuses to start.
104
105
  */
105
- resolveToken?: TokenResolver;
106
+ resolveToken?: TokenResolver | undefined;
106
107
 
107
108
  /**
108
109
  * Mint a standing delegation credential for the *calling* user. Supplying
@@ -111,18 +112,18 @@ export interface HostingOptions {
111
112
  * {@link resolveToken}). Needs no allowlist: it is not an oracle about
112
113
  * anybody else.
113
114
  */
114
- mintGrant?: GrantMinter;
115
+ mintGrant?: GrantMinter | undefined;
115
116
 
116
117
  /**
117
118
  * Principals permitted to call `introspect_token`. When omitted,
118
119
  * `VGI_INTROSPECT_PRINCIPALS` (comma-separated) is read. Only consulted when
119
120
  * {@link resolveToken} is supplied.
120
121
  */
121
- introspectPrincipals?: Iterable<string>;
122
+ introspectPrincipals?: Iterable<string> | undefined;
122
123
 
123
124
  /** Maximum age of the caller's authentication for `issue_grant`, in
124
125
  * seconds. vgi-rpc's default when omitted. */
125
- maxAuthAge?: number;
126
+ maxAuthAge?: number | undefined;
126
127
 
127
128
  /**
128
129
  * Sealed-grant keys (vgi-rpc `GrantKeys`), turning on the framework's own
@@ -136,7 +137,7 @@ export interface HostingOptions {
136
137
  * malformed key refuses to start. `null` turns grants off regardless of the
137
138
  * environment.
138
139
  */
139
- grantKeys?: GrantKeys | null;
140
+ grantKeys?: GrantKeys | null | undefined;
140
141
  }
141
142
 
142
143
  /** Server-level options passed through to `VgiRpcServer`. */
@@ -194,14 +195,14 @@ export function buildRpcServer(
194
195
  const tickets = buildAttachTickets(hosting, grantKeys, options.attachTickets, env);
195
196
  if (tickets) protocols.push(tickets);
196
197
  }
197
- return new VgiRpcServer(primary, {
198
+ return new VgiRpcServer(primary, omitUndefined({
198
199
  serverId: options.serverId,
199
200
  protocols,
200
201
  identity,
201
202
  // Resolved here, per transport, rather than by vgi-rpc's own environment
202
203
  // default: identity (and so grants) is hosted on HTTP only.
203
204
  grantKeys: null,
204
- });
205
+ }));
205
206
  }
206
207
 
207
208
  /** Call `hostedProtocols()` once and check its shape and names.
@@ -271,7 +272,7 @@ function buildIdentity(
271
272
  ): IdentityImpl | undefined {
272
273
  const { resolveToken, mintGrant } = hosting;
273
274
  if (!resolveToken && !mintGrant && !grantKeys) return undefined;
274
- return new IdentityImpl({
275
+ return new IdentityImpl(omitUndefined({
275
276
  resolveToken,
276
277
  // Absent with grant keys configured, vgi-rpc mints sealed grants itself.
277
278
  mintGrant,
@@ -280,7 +281,7 @@ function buildIdentity(
280
281
  // nothing is not an oracle and needs no allowlist.
281
282
  introspectPrincipals: resolveToken ? resolveIntrospectPrincipals(hosting.introspectPrincipals, env) : undefined,
282
283
  maxAuthAge: hosting.maxAuthAge,
283
- });
284
+ }));
284
285
  }
285
286
 
286
287
  /** Build `vgi.attach_tickets.v1`, or `undefined` when it must not be hosted.
@@ -358,10 +359,10 @@ export function grantKeysFromArgv(
358
359
  ): GrantKeys | undefined {
359
360
  const keys: string[] = [];
360
361
  for (let i = 0; i < argv.length; i++) {
361
- const a = argv[i];
362
+ const a = argv[i]!;
362
363
  if (a === "--grant-key") {
363
364
  if (i + 1 >= argv.length) throw new Error("--grant-key requires a value");
364
- keys.push(argv[++i]);
365
+ keys.push(argv[++i]!);
365
366
  } else if (a.startsWith("--grant-key=")) {
366
367
  keys.push(a.slice("--grant-key=".length));
367
368
  }
@@ -61,14 +61,14 @@ export interface IrohHttpBridgeOptions {
61
61
  /** Worker-local namespace for EndpointId principals. */
62
62
  issuer: string;
63
63
  /** Exact bridge IP addresses. No CIDRs or hostnames. */
64
- trustedProxyAddresses?: readonly string[];
64
+ trustedProxyAddresses?: readonly string[] | undefined;
65
65
  /** Authenticate the EndpointId (default) or expose evidence only. */
66
- authenticate?: boolean;
66
+ authenticate?: boolean | undefined;
67
67
  /**
68
68
  * Host-specific physical peer and raw-header adapter. Required because a
69
69
  * Fetch Request alone does not preserve duplicate header fields.
70
70
  */
71
- peerResolutionContext?: (request: Request) => PeerResolutionOptions | Promise<PeerResolutionOptions>;
71
+ peerResolutionContext?: ((request: Request) => PeerResolutionOptions | Promise<PeerResolutionOptions>) | undefined;
72
72
  }
73
73
 
74
74
  export interface ServeVgiWorkerOptions extends HostingOptions {
@@ -84,34 +84,34 @@ export interface ServeVgiWorkerOptions extends HostingOptions {
84
84
  catalogInterface: CatalogInterface;
85
85
 
86
86
  /** Public source-repository URL, linked from the landing page. */
87
- repositoryUrl?: string;
87
+ repositoryUrl?: string | undefined;
88
88
  /** Overrides `$PORT` (default 8787). Pass 0 to bind an ephemeral port. */
89
- port?: number;
89
+ port?: number | undefined;
90
90
  /** Bind address. Iroh bridge mode defaults to loopback; otherwise Bun's default. */
91
- hostname?: string;
91
+ hostname?: string | undefined;
92
92
  /** Overrides `$VGI_SIGNING_KEY`. 32 bytes. */
93
- signingKey?: Uint8Array;
93
+ signingKey?: Uint8Array | undefined;
94
94
  /** Overrides `$VGI_TOKEN_TTL` (default 3600 seconds). */
95
- tokenTtl?: number;
95
+ tokenTtl?: number | undefined;
96
96
  /** Overrides `$CORS_ORIGINS` (default "*"). Pass `null` to disable CORS. */
97
- corsOrigins?: string | null;
97
+ corsOrigins?: string | null | undefined;
98
98
  /** Server ID for state-token attribution (default: `name`). */
99
- serverId?: string;
99
+ serverId?: string | undefined;
100
100
  /** Mount point for the VGI endpoints (default "", the origin root). */
101
- prefix?: string;
101
+ prefix?: string | undefined;
102
102
  /** Suppress the startup banner on stdout. */
103
- quiet?: boolean;
103
+ quiet?: boolean | undefined;
104
104
  /** Environment source (default `process.env`). */
105
- env?: ServeEnv;
105
+ env?: ServeEnv | undefined;
106
106
  /** Command-line arguments to read `--grant-key KEY` (repeatable, first mints)
107
107
  * from. Default `process.argv.slice(2)`. A key here takes precedence over
108
108
  * `VGI_RPC_GRANT_KEYS`; an explicit {@link grantKeys} over both. */
109
- argv?: readonly string[];
109
+ argv?: readonly string[] | undefined;
110
110
  /** Authenticates each request, returning the caller's `AuthContext`.
111
111
  * Omit for an anonymous worker (the default). */
112
- authenticate?: AuthenticateFn;
112
+ authenticate?: AuthenticateFn | undefined;
113
113
  /** Preserve authenticated Iroh identity forwarded by an adjacent HTTP bridge. */
114
- irohBridge?: IrohHttpBridgeOptions;
114
+ irohBridge?: IrohHttpBridgeOptions | undefined;
115
115
  }
116
116
 
117
117
  /** The slice of `Bun.serve`'s return value this module uses. */
@@ -125,7 +125,7 @@ export interface VgiHttpServer {
125
125
  interface BunLike {
126
126
  serve(options: {
127
127
  port: number;
128
- hostname?: string;
128
+ hostname?: string | undefined;
129
129
  fetch: (req: Request) => Promise<Response>;
130
130
  }): VgiHttpServer;
131
131
  }
@@ -302,7 +302,7 @@ export function serveVgiWorker(opts: ServeVgiWorkerOptions): VgiHttpServer {
302
302
  const immediatePeer = server.requestIP?.(request)?.address;
303
303
  const forwarded = request.headers.get(IROH_FORWARDED_ENDPOINT_HEADER);
304
304
  return {
305
- immediatePeer,
305
+ ...(immediatePeer !== undefined ? { immediatePeer } : {}),
306
306
  headers: forwarded === null
307
307
  ? {}
308
308
  : { [IROH_FORWARDED_ENDPOINT_HEADER]: [forwarded] },
@@ -95,7 +95,7 @@ function concat(...parts: Uint8Array[]): Uint8Array {
95
95
  function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
96
96
  if (a.length !== b.length) return false;
97
97
  let diff = 0;
98
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
98
+ for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;
99
99
  return diff === 0;
100
100
  }
101
101
 
@@ -163,8 +163,8 @@ export async function buildSplitToken(opts: {
163
163
  payload: Uint8Array;
164
164
  fingerprint: Uint8Array;
165
165
  anchor: Uint8Array;
166
- signingKey?: Uint8Array;
167
- auth?: AuthContext;
166
+ signingKey?: Uint8Array | undefined;
167
+ auth?: AuthContext | undefined;
168
168
  }): Promise<Uint8Array> {
169
169
  const { payload, fingerprint, anchor, signingKey, auth } = opts;
170
170
  if (fingerprint.length !== FINGERPRINT_LEN) {
@@ -200,10 +200,10 @@ export async function buildSplitToken(opts: {
200
200
  export async function openSplitToken(
201
201
  token: Uint8Array,
202
202
  opts: {
203
- signingKey?: Uint8Array;
204
- auth?: AuthContext;
205
- expectedFingerprint?: Uint8Array;
206
- currentAnchor?: Uint8Array;
203
+ signingKey?: Uint8Array | undefined;
204
+ auth?: AuthContext | undefined;
205
+ expectedFingerprint?: Uint8Array | undefined;
206
+ currentAnchor?: Uint8Array | undefined;
207
207
  } = {},
208
208
  ): Promise<Uint8Array> {
209
209
  const { signingKey, auth, expectedFingerprint, currentAnchor } = opts;
@@ -214,8 +214,9 @@ export async function openSplitToken(
214
214
  `split token too short: ${token.length} bytes, need at least ${HEADER_LEN}`,
215
215
  );
216
216
  }
217
- const version = token[0];
218
- const flags = token[1];
217
+ // Both in range: the length check above guarantees HEADER_LEN bytes.
218
+ const version = token[0]!;
219
+ const flags = token[1]!;
219
220
  const view = new DataView(token.buffer, token.byteOffset, token.byteLength);
220
221
  const anchorLen = view.getUint16(2, true);
221
222
 
package/src/types.ts CHANGED
@@ -89,9 +89,16 @@ export const VGI_CHOICES_KEY = "vgi_choices";
89
89
  export const VGI_RANGE_KEY = "vgi_range";
90
90
  export const VGI_PATTERN_KEY = "vgi_pattern";
91
91
 
92
+ /**
93
+ * Row-count estimate/upper bound returned by a table function's `cardinality`
94
+ * hook. Both travel as int64 on the wire, so either a `number` (must be an
95
+ * integer) or a `bigint` is accepted — int64 arguments arrive as `bigint`, so
96
+ * `{ estimate: args.count, max: args.count }` works without a `Number(...)`
97
+ * conversion. `null` means unknown.
98
+ */
92
99
  export interface TableCardinality {
93
- estimate: number | null;
94
- max: number | null;
100
+ estimate: number | bigint | null;
101
+ max: number | bigint | null;
95
102
  }
96
103
 
97
104
  // Default max workers (matches Python DEFAULT_MAX_WORKERS = 99999)
@@ -0,0 +1,30 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+
3
+ /**
4
+ * The type of `T` with every property whose value may be `undefined` made
5
+ * optional and stripped of `undefined` — the shape `omitUndefined` returns.
6
+ * It is assignable to option bags declared `{ k?: V }` under
7
+ * `exactOptionalPropertyTypes`.
8
+ */
9
+ export type OmitUndefined<T> = {
10
+ [K in keyof T as undefined extends T[K] ? never : K]: T[K];
11
+ } & {
12
+ [K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined>;
13
+ };
14
+
15
+ /**
16
+ * Copy `obj` without the keys whose value is `undefined`.
17
+ *
18
+ * Used when forwarding optional settings to an options bag owned by another
19
+ * package (vgi-rpc, Bun) whose optional properties do not admit an explicit
20
+ * `undefined`. Readers of such bags treat an absent key and an `undefined`
21
+ * one identically (`??`, destructuring defaults), so this only changes the
22
+ * static type.
23
+ */
24
+ export function omitUndefined<T extends object>(obj: T): OmitUndefined<T> {
25
+ const out: Record<string, unknown> = {};
26
+ for (const [k, v] of Object.entries(obj)) {
27
+ if (v !== undefined) out[k] = v;
28
+ }
29
+ return out as OmitUndefined<T>;
30
+ }
@@ -14,13 +14,13 @@ export function encodeParentRows(parentRows: ArrayLike<number>): string {
14
14
  const raw = new Uint8Array(parentRows.length * 4);
15
15
  const dv = new DataView(raw.buffer);
16
16
  for (let i = 0; i < parentRows.length; i++) {
17
- dv.setInt32(i * 4, parentRows[i], true);
17
+ dv.setInt32(i * 4, parentRows[i]!, true);
18
18
  }
19
19
  if (typeof (globalThis as any).Buffer !== "undefined") {
20
20
  return (globalThis as any).Buffer.from(raw).toString("base64");
21
21
  }
22
22
  let bin = "";
23
- for (let i = 0; i < raw.length; i++) bin += String.fromCharCode(raw[i]);
23
+ for (let i = 0; i < raw.length; i++) bin += String.fromCharCode(raw[i]!);
24
24
  return (globalThis as any).btoa(bin);
25
25
  }
26
26
 
package/src/worker.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  serveStream as serveStreamRpc,
10
10
  type VgiRpcServer,
11
11
  } from "@query-farm/vgi-rpc";
12
+ import { omitUndefined } from "./util/defined.js";
12
13
  import { buildRpcServer, type HostingOptions, type ServerTransport } from "./rpc-server.js";
13
14
  import { FunctionRegistry } from "./functions/registry.js";
14
15
  import type { VgiFunction } from "./functions/types.js";
@@ -73,31 +74,31 @@ function parseTcpSpec(spec: string, out: LauncherArgs): void {
73
74
  function parseLauncherArgs(argv: readonly string[]): LauncherArgs {
74
75
  const out: LauncherArgs = { irohTrustedProxyAddresses: [], irohAuthenticate: true };
75
76
  for (let i = 0; i < argv.length; i++) {
76
- const a = argv[i];
77
+ const a = argv[i]!;
77
78
  if (a === "--unix" && i + 1 < argv.length) {
78
- out.unixPath = argv[++i];
79
+ out.unixPath = argv[++i]!;
79
80
  } else if (a.startsWith("--unix=")) {
80
81
  out.unixPath = a.slice("--unix=".length);
81
82
  } else if (a === "--tcp" && i + 1 < argv.length) {
82
- parseTcpSpec(argv[++i], out);
83
+ parseTcpSpec(argv[++i]!, out);
83
84
  } else if (a.startsWith("--tcp=")) {
84
85
  parseTcpSpec(a.slice("--tcp=".length), out);
85
86
  } else if (a === "--idle-timeout" && i + 1 < argv.length) {
86
- out.idleTimeout = Number(argv[++i]);
87
+ out.idleTimeout = Number(argv[++i]!);
87
88
  } else if (a.startsWith("--idle-timeout=")) {
88
89
  out.idleTimeout = Number(a.slice("--idle-timeout=".length));
89
90
  } else if (a === "--iroh-raw-upstream" && i + 1 < argv.length) {
90
- parseTcpSpec(argv[++i], out);
91
+ parseTcpSpec(argv[++i]!, out);
91
92
  out.irohRawUpstream = true;
92
93
  } else if (a.startsWith("--iroh-raw-upstream=")) {
93
94
  parseTcpSpec(a.slice("--iroh-raw-upstream=".length), out);
94
95
  out.irohRawUpstream = true;
95
96
  } else if (a === "--iroh-issuer" && i + 1 < argv.length) {
96
- out.irohIssuer = argv[++i];
97
+ out.irohIssuer = argv[++i]!;
97
98
  } else if (a.startsWith("--iroh-issuer=")) {
98
99
  out.irohIssuer = a.slice("--iroh-issuer=".length);
99
100
  } else if (a === "--iroh-trusted-proxy" && i + 1 < argv.length) {
100
- out.irohTrustedProxyAddresses.push(...argv[++i].split(",").filter(Boolean));
101
+ out.irohTrustedProxyAddresses.push(...argv[++i]!.split(",").filter(Boolean));
101
102
  } else if (a.startsWith("--iroh-trusted-proxy=")) {
102
103
  out.irohTrustedProxyAddresses.push(...a.slice("--iroh-trusted-proxy=".length).split(",").filter(Boolean));
103
104
  } else if (a === "--iroh-observe") {
@@ -127,8 +128,8 @@ export interface WorkerConfig extends HostingOptions {
127
128
  export class Worker {
128
129
  private _registry: FunctionRegistry;
129
130
  private _hosting: HostingOptions;
130
- private _catalogInterface?: CatalogInterface;
131
- private _catalogName?: string;
131
+ private _catalogInterface: CatalogInterface | undefined;
132
+ private _catalogName: string | undefined;
132
133
 
133
134
  constructor(config: WorkerConfig) {
134
135
  // Reuse the caller's registry when given: a catalogInterface built
@@ -217,10 +218,10 @@ export class Worker {
217
218
  debug(() =>
218
219
  `[worker] AF_UNIX mode: ${launcher.unixPath} idle=${idleTimeout ?? 300}s${envOverride !== undefined && envOverride !== "" ? " (env override)" : ""}`,
219
220
  );
220
- serveUnix(this.buildServer(protocol, "unix"), {
221
+ serveUnix(this.buildServer(protocol, "unix"), omitUndefined({
221
222
  unixPath: launcher.unixPath,
222
223
  idleTimeout,
223
- }).then((handle) => handle.done).then(() => {
224
+ })).then((handle) => handle.done).then(() => {
224
225
  debug(() => `[worker] serveUnix done (idle shutdown)`);
225
226
  }).catch((err: any) => {
226
227
  process.stderr.write(`Worker error: ${err.message}\n${err.stack}\n`);
@@ -242,7 +243,7 @@ export class Worker {
242
243
  debug(() =>
243
244
  `[worker] TCP mode: ${launcher.tcpHost}:${launcher.tcpPort} idle=${idleTimeout ?? 300}s${envOverride !== undefined && envOverride !== "" ? " (env override)" : ""}`,
244
245
  );
245
- serveTcp(this.buildServer(protocol, launcher.irohRawUpstream ? "iroh" : "tcp"), {
246
+ serveTcp(this.buildServer(protocol, launcher.irohRawUpstream ? "iroh" : "tcp"), omitUndefined({
246
247
  host: launcher.tcpHost,
247
248
  port: launcher.tcpPort,
248
249
  idleTimeout,
@@ -258,7 +259,7 @@ export class Worker {
258
259
  : observePeerIdentity,
259
260
  }
260
261
  : {}),
261
- }).then((handle) => handle.done).then(() => {
262
+ })).then((handle) => handle.done).then(() => {
262
263
  debug(() => `[worker] serveTcp done (idle shutdown)`);
263
264
  }).catch((err: any) => {
264
265
  process.stderr.write(`Worker error: ${err.message}\n${err.stack}\n`);
@@ -317,6 +318,6 @@ export class Worker {
317
318
  readable: ReadableStream<Uint8Array> | NodeJS.ReadableStream,
318
319
  writable?: number | import("node:net").Socket | import("@query-farm/vgi-rpc").ByteSink,
319
320
  ): Promise<void> {
320
- await serveStreamRpc(this.buildServer(this.buildProtocol(), "stream"), { readable, writable });
321
+ await serveStreamRpc(this.buildServer(this.buildProtocol(), "stream"), omitUndefined({ readable, writable }));
321
322
  }
322
323
  }